OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Blame | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.utils.system;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Powershell {

    private static final Powershell INSTANCE = new Powershell();

    // No static methods to future-proof if the syntax changes in the future
    static public final Powershell getInstance() {
        return INSTANCE;
    }

    static private final Pattern PS_CHARS = Pattern.compile("\\R+|'");

    private Powershell() {
    }

    public final String quote(String s) {
        final StringBuffer sb = new StringBuffer((int) (s.length() * 1.1));
        quote(s, sb);
        return sb.toString();
    }

    public final void quote(String s, final StringBuffer sb) {
        sb.append("'");
        final Matcher m = PS_CHARS.matcher(s);
        while (m.find()) {
            final String replacement;
            if (m.group().equals("'")) {
                replacement = "''";
            } else {
                // `n isn't expanded in single quoted strings and it's complicated to handle all
                // needed escaping in double quoted strings, so just concatenate a single newline.
                replacement = "' + \"`n\" + '";
            }
            m.appendReplacement(sb, replacement);
        }
        m.appendTail(sb);
        sb.append("'");
    }

    // @("C:\Users\ILM\Documents", "2")
    public final String quoteArray(List<String> l) {
        final StringBuffer sb = new StringBuffer(l.size() * 64);
        sb.append("@(");
        final Iterator<String> iter = l.iterator();
        while (iter.hasNext()) {
            final String s = iter.next();
            quote(s, sb);
            if (iter.hasNext())
                sb.append(", ");
        }
        sb.append(")");
        return sb.toString();
    }

    public final String getEncodedCommand(final String s) {
        return java.util.Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_16LE));
    }
}