Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
BEGIN LICENSE BLOCK ***** Version: EPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Eclipse Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.eclipse.org/legal/epl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2007-2011 Nick Sieger <nicksieger@gmail.com> Copyright (C) 2009 Joseph LaFata <joe@quibb.org> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the EPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the EPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 package org.jruby.util.cli;
 
 import org.jruby.Ruby;
 
 import java.io.File;
 import java.util.List;

Encapsulated logic for processing JRuby's command-line arguments. This class holds the processing logic for JRuby's non-JVM command-line arguments. All standard Ruby options are processed here, as well as nonstandard JRuby- specific options. Options passed directly to the JVM are processed separately, by either a launch script or by a native executable.
 
 public class ArgumentProcessor {
     private final class Argument {
         public final String originalValue;
         public final String dashedValue;
         public Argument(String valueboolean dashed) {
             this. = value;
             this. = dashed && !value.startsWith("-") ? "-" + value : value;
         }
 
         public String toString() {
             return ;
         }
     }
 
     private List<Argumentarguments;
     private int argumentIndex = 0;
     private boolean processArgv;
     private boolean endOfArguments = false;
     private int characterIndex = 0;
 
     public ArgumentProcessor(String[] argumentsRubyInstanceConfig config) {
         this(argumentstruefalseconfig);
     }
 
     public ArgumentProcessor(String[] argumentsboolean processArgvboolean dashedRubyInstanceConfig config) {
         this. = config;
         this. = new ArrayList<Argument>();
         if (arguments != null && arguments.length > 0) {
             for (String argument : arguments) {
                 this..add(new Argument(argumentdashed));
             }
         }
         this. = processArgv;
     }
 
     public void processArguments() {
         processArguments(true);
     }
 
     public void processArguments(boolean inline) {
             processArgument();
            ++;
        }
        if (inline && !.isInlineScript() && .getScriptFileName() == null) {
            if ( < .size()) {
                .setScriptFileName(.get().); //consume the file name
                ++;
            }
        }
        if () {
            processArgv();
        }
    }
    private void processArgv() {
        List<Stringarglist = new ArrayList<String>();
        for (;  < .size(); ++) {
            String arg = .get().;
            if (.isArgvGlobalsOn() && arg.startsWith("-")) {
                arg = arg.substring(1);
                if (arg.indexOf('=') > 0) {
                    String[] keyvalue = arg.split("=", 2);
                    // argv globals get their dashes replaced with underscores
                    String globalName = keyvalue[0].replaceAll("-""_");
                    .getOptionGlobals().put(globalNamekeyvalue[1]);
                } else {
                    .getOptionGlobals().put(argnull);
                }
            } else {
                .setArgvGlobalsOn(false);
                arglist.add(arg);
            }
        }
        // Remaining arguments are for the script itself
        arglist.addAll(Arrays.asList(.getArgv()));
        .setArgv(arglist.toArray(new String[arglist.size()]));
    }
    private boolean isInterpreterArgument(String argument) {
        return argument.length() > 0 && (argument.charAt(0) == '-' || argument.charAt(0) == '+') && !;
    }
    private String getArgumentError(String additionalError) {
        return "jruby: invalid argument\n" + additionalError + "\n";
    }
    private void processArgument() {
        String argument = .get().;
        FOR:
        for ( = 1;  < argument.length(); ++) {
            switch (argument.charAt()) {
                case '0':
                    {
                        String temp = grabOptionalValue();
                        if (null == temp) {
                            .setRecordSeparator("\u0000");
                        } else if (temp.equals("0")) {
                            .setRecordSeparator("\n\n");
                        } else if (temp.equals("777")) {
                            .setRecordSeparator("\uffff"); // Specify something that can't separate
                        } else {
                            try {
                                int val = Integer.parseInt(temp, 8);
                                .setRecordSeparator("" + (charval);
                            } catch (Exception e) {
                                MainExitException mee = new MainExitException(1, getArgumentError(" -0 must be followed by either 0, 777, or a valid octal value"));
                                mee.setUsageError(true);
                                throw mee;
                            }
                        }
                        break FOR;
                    }
                case 'a':
                    .setSplit(true);
                    break;
                case 'c':
                    .setShouldCheckSyntax(true);
                    break;
                case 'C':
                    try {
                        String saved = grabValue(getArgumentError(" -C must be followed by a directory expression"));
                        File base = new File(.getCurrentDirectory());
                        File newDir = new File(saved);
                        if (newDir.isAbsolute()) {
                            .setCurrentDirectory(newDir.getCanonicalPath());
                        } else {
                            .setCurrentDirectory(new File(basenewDir.getPath()).getCanonicalPath());
                        }
                        if (!(new File(.getCurrentDirectory()).isDirectory())) {
                            MainExitException mee = new MainExitException(1, "jruby: Can't chdir to " + saved + " (fatal)");
                            throw mee;
                        }
                    } catch (IOException e) {
                        MainExitException mee = new MainExitException(1, getArgumentError(" -C must be followed by a valid directory"));
                        throw mee;
                    }
                    break FOR;
                case 'd':
                    .setDebug(true);
                    .setVerbosity(..);
                    break;
                case 'e':
                    .getInlineScript().append(grabValue(getArgumentError(" -e must be followed by an expression to evaluate")));
                    .getInlineScript().append('\n');
                    .setHasInlineScript(true);
                    break FOR;
                case 'E':
                    processEncodingOption(grabValue(getArgumentError("unknown encoding name")));
                    break FOR;
                case 'F':
                    .setInputFieldSeparator(grabValue(getArgumentError(" -F must be followed by a pattern for input field separation")));
                    break FOR;
                case 'h':
                    .setShouldPrintUsage(true);
                    .setShouldRunInterpreter(false);
                    break;
                case 'i':
                    .setInPlaceBackupExtension(grabOptionalValue());
                    if (.getInPlaceBackupExtension() == null) {
                        .setInPlaceBackupExtension("");
                    }
                    break FOR;
                case 'I':
                    String s = grabValue(getArgumentError("-I must be followed by a directory name to add to lib path"));
                    String[] ls = s.split(...);
                    .getLoadPaths().addAll(Arrays.asList(ls));
                    break FOR;
                case 'J':
                    grabOptionalValue();
                    .getError().println("warning: " + argument + " argument ignored (launched in same VM?)");
                    break FOR;
                case 'K':
                    // FIXME: No argument seems to work for -K in MRI plus this should not
                    // siphon off additional args 'jruby -K ~/scripts/foo'.  Also better error
                    // processing.
                    String eArg = grabValue(getArgumentError("provide a value for -K"));
                    .setKCode(KCode.create(nulleArg));
                    // source encoding
                    .setSourceEncoding(.getKCode().getEncoding().toString());
                    // set external encoding if not already specified
                    if (.getExternalEncoding() == null) {
                        .setExternalEncoding(.getKCode().getEncoding().toString());
                    }
                    break;
                case 'l':
                    .setProcessLineEnds(true);
                    break;
                case 'n':
                    .setAssumeLoop(true);
                    .setKernelGsubDefined(true);
                    break;
                case 'p':
                    .setAssumePrinting(true);
                    .setAssumeLoop(true);
                    .setKernelGsubDefined(true);
                    break;
                case 'r':
                    .getRequiredLibraries().add(grabValue(getArgumentError("-r must be followed by a package to require")));
                    break FOR;
                case 's':
                    .setArgvGlobalsOn(true);
                    break;
                case 'G':
                    .setLoadGemfile(true);
                    break;
                case 'S':
                    runBinScript();
                    break FOR;
                case 'T':
                    {
                        String temp = grabOptionalValue();
                        break FOR;
                    }
                case 'U':
                    .setInternalEncoding("UTF-8");
                    break;
                case 'v':
                    .setVerbosity(..);
                    .setShowVersion(true);
                    break;
                case 'w':
                    .setVerbosity(..);
                    break;
                case 'W':
                    {
                        String temp = grabOptionalValue();
                        if (temp == null) {
                            .setVerbosity(..);
                        } else {
                            if (temp.equals("0")) {
                                .setVerbosity(..);
                            } else if (temp.equals("1")) {
                                .setVerbosity(..);
                            } else if (temp.equals("2")) {
                                .setVerbosity(..);
                            } else {
                                MainExitException mee = new MainExitException(1, getArgumentError(" -W must be followed by either 0, 1, 2 or nothing"));
                                mee.setUsageError(true);
                                throw mee;
                            }
                        }
                        break FOR;
                    }
                case 'x':
                    try {
                        String saved = grabOptionalValue();
                        if (saved != null) {
                            File base = new File(.getCurrentDirectory());
                            File newDir = new File(saved);
                            if (newDir.isAbsolute()) {
                                .setCurrentDirectory(newDir.getCanonicalPath());
                            } else {
                                .setCurrentDirectory(new File(basenewDir.getPath()).getCanonicalPath());
                            }
                            if (!(new File(.getCurrentDirectory()).isDirectory())) {
                                MainExitException mee = new MainExitException(1, "jruby: Can't chdir to " + saved + " (fatal)");
                                throw mee;
                            }
                        }
                        .setXFlag(true);
                    } catch (IOException e) {
                        MainExitException mee = new MainExitException(1, getArgumentError(" -x must be followed by a valid directory"));
                        throw mee;
                    }
                    break FOR;
                case 'X':
                    String extendedOption = grabOptionalValue();
                    if (extendedOption == null) {
                        if (SafePropertyAccessor.getBoolean("jruby.launcher.nopreamble"false)) {
                            throw new MainExitException(0, OutputStrings.getExtendedHelp());
                        } else {
                            throw new MainExitException(0, "jruby: missing argument\n" + OutputStrings.getExtendedHelp());
                        }
                    } else if (extendedOption.equals("-O")) {
                        .setObjectSpaceEnabled(false);
                    } else if (extendedOption.equals("+O")) {
                        .setObjectSpaceEnabled(true);
                    } else if (extendedOption.equals("-C")) {
                        .setCompileMode(..);
                    } else if (extendedOption.equals("-CIR")) {
                        .setCompileMode(..);
                    } else if (extendedOption.equals("+C")) {
                        .setCompileMode(..);
                    } else if (extendedOption.equals("+CIR")) {
                        .setCompileMode(..);
                    } else {
                        MainExitException mee = new MainExitException(1, "jruby: invalid extended option " + extendedOption + " (-X will list valid options)\n");
                        mee.setUsageError(true);
                        throw mee;
                    }
                    break FOR;
                case 'y':
                    .setParserDebug(true);
                    break FOR;
                case '-':
                    if (argument.equals("--command") || argument.equals("--bin")) {
                         = argument.length();
                        runBinScript();
                        break;
                    } else if (argument.equals("--compat")) {
                         = argument.length();
                        .setCompatVersion(CompatVersion.getVersionFromString(grabValue(getArgumentError("--compat must be RUBY1_8 or RUBY1_9"))));
                        break FOR;
                    } else if (argument.equals("--copyright")) {
                        .setShowCopyright(true);
                        .setShouldRunInterpreter(false);
                        break FOR;
                    } else if (argument.equals("--debug")) {
                        . = true;
                        .setCompileMode(..);
                        break FOR;
                    } else if (argument.equals("--jdb")) {
                        .setDebug(true);
                        .setVerbosity(..);
                        break;
                    } else if (argument.equals("--help")) {
                        .setShouldPrintUsage(true);
                        .setShouldRunInterpreter(false);
                        break;
                    } else if (argument.equals("--properties")) {
                        .setShouldPrintProperties(true);
                        .setShouldRunInterpreter(false);
                        break;
                    } else if (argument.equals("--version")) {
                        .setShowVersion(true);
                        .setShouldRunInterpreter(false);
                        break FOR;
                    } else if (argument.equals("--bytecode")) {
                        .setShowBytecode(true);
                        break FOR;
                    } else if (argument.equals("--fast")) {
                        .setCompileMode(..);
                        break FOR;
                    } else if (argument.startsWith("--profile")) {
                         = argument.length();
                        int dotIndex = argument.indexOf(".");
                        
                        if (dotIndex == -1) {
                            .setProfilingMode(..);
                            
                        } else {
                            String profilingMode = argument.substring(dotIndex + 1, argument.length());
                            
                            if (profilingMode.equals("out")) {
                                // output file for profiling results
                                String outputFile = grabValue(getArgumentError("--profile.out requires an output file argument"));
                                
                                try {
                                    .setProfileOutput(new ProfileOutput(new File(outputFile)));
                                } catch (FileNotFoundException e) {
                                    throw new MainExitException(1, String.format("jruby: %s"e.getMessage()));
                                }
                                
                            } else {
                                try {
                                    .setProfilingMode(RubyInstanceConfig.ProfilingMode.valueOf(profilingMode.toUpperCase()));
                                } catch (IllegalArgumentException e) {
                                    throw new MainExitException(1, String.format("jruby: unknown profiler mode \"%s\""profilingMode));
                                }
                            }
                        }
                        
                        break FOR;
                    } else if (argument.equals("--1.9")) {
                        .setCompatVersion(.);
                        break FOR;
                    } else if (argument.equals("--2.0")) {
                        .setCompatVersion(.);
                        break FOR;
                    } else if (argument.equals("--1.8")) {
                        .setCompatVersion(.);
                        break FOR;
                    } else if (argument.equals("--disable-gems")) {
                        .setDisableGems(true);
                        break FOR;
                    } else if (argument.equals("--gemfile")) {
                        .setLoadGemfile(true);
                        break FOR;
                    } else if (argument.equals("--dump")) {
                         = argument.length();
                        String error = "--dump only supports [version, copyright, usage, yydebug, syntax, insns] on JRuby";
                        String dumpArg = grabValue(getArgumentError(error));
                        if (dumpArg.equals("version")) {
                            .setShowVersion(true);
                            .setShouldRunInterpreter(false);
                            break FOR;
                        } else if (dumpArg.equals("copyright")) {
                            .setShowCopyright(true);
                            .setShouldRunInterpreter(false);
                            break FOR;
                        } else if (dumpArg.equals("usage")) {
                            .setShouldPrintUsage(true);
                            .setShouldRunInterpreter(false);
                            break FOR;
                        } else if (dumpArg.equals("yydebug")) {
                            .setParserDebug(true);
                            break FOR;
                        } else if (dumpArg.equals("syntax")) {
                            .setShouldCheckSyntax(true);
                        } else if (dumpArg.equals("insns")) {
                            .setShowBytecode(true);
                        } else {
                            MainExitException mee = new MainExitException(1, error);
                            mee.setUsageError(true);
                            throw mee;
                        }
                        break;
                    } else if (argument.equals("--dev")) {
                        ..force("false");
                        .setCompileMode(..);
                        break FOR;
                    } else {
                        if (argument.equals("--")) {
                            // ruby interpreter compatibilty
                            // Usage: ruby [switches] [--] [programfile] [arguments])
                             = true;
                            break;
                        }
                    }
                default:
                    throw new MainExitException(1, "jruby: unknown option " + argument);
            }
        }
    }
    private void processEncodingOption(String value) {
        String[] encodings = value.split(":", 3);
        switch (encodings.length) {
            case 3:
                throw new MainExitException(1, "extra argument for -E: " + encodings[2]);
            case 2:
                .setInternalEncoding(encodings[1]);
            case 1:
                .setExternalEncoding(encodings[0]);
                // Zero is impossible
        }
    }
    private void runBinScript() {
        String scriptName = grabValue("jruby: provide a bin script to execute");
        if (scriptName.equals("irb")) {
            scriptName = "jirb";
        }
        .setScriptFileName(resolveScript(scriptName));
        // run as a command if we couldn't find a script
        if (.getScriptFileName() == null) {
            .setScriptFileName(scriptName);
            .getRequiredLibraries().add("jruby/commands");
            .getInlineScript().append("JRuby::Commands.").append(scriptName);
            .getInlineScript().append("\n");
            .setHasInlineScript(true);
        }
         = true;
    }
    private String resolveScript(String scriptName) {
        // These try/catches are to allow failing over to the "commands" logic
        // when running from within a jruby-complete jar file, which has
        // jruby.home = a jar file URL that does not resolve correctly with
        // JRubyFile.create.
        File fullName = null;
        try {
            // try cwd first
            fullName = JRubyFile.create(.getCurrentDirectory(), scriptName);
            if (fullName.exists() && fullName.isFile()) {
                if (.) {
                    .getError().println("Found: " + fullName.getAbsolutePath());
                }
                return scriptName;
            }
        } catch (Exception e) {
            // keep going, try bin/#{scriptName}
        }
        try {
            fullName = JRubyFile.create(.getJRubyHome(), "bin/" + scriptName);
            if (fullName.exists() && fullName.isFile()) {
                if (.) {
                    .getError().println("Found: " + fullName.getAbsolutePath());
                }
                return fullName.getAbsolutePath();
            }
        } catch (Exception e) {
            // keep going, try PATH
        }
        if(Ruby.getClassLoader().getResourceAsStream("bin/" + scriptName) != null){
            return "classpath:bin/" + scriptName;
        }
        try {
            Object pathObj = .getEnvironment().get("PATH");
            String path = pathObj.toString();
            if (path != null) {
                String[] paths = path.split(System.getProperty("path.separator"));
                for (int i = 0; i < paths.lengthi++) {
                    fullName = JRubyFile.create(new File(paths[i]).getAbsolutePath(), scriptName);
                    if (fullName.exists() && fullName.isFile()) {
                        if (.) {
                            .getError().println("Found: " + fullName.getAbsolutePath());
                        }
                        return fullName.getAbsolutePath();
                    }
                }
            }
        } catch (Exception e) {
            // will fall back to JRuby::Commands
        }
        if (.isDebug()) {
            .getError().println("warning: could not resolve -S script on filesystem: " + scriptName);
        }
        return null;
    }
    private String grabValue(String errorMessage) {
        String optValue = grabOptionalValue();
        if (optValue != null) {
            return optValue;
        }
        ++;
        if ( < .size()) {
            return .get().;
        }
        MainExitException mee = new MainExitException(1, errorMessage);
        mee.setUsageError(true);
        throw mee;
    }
    private String grabOptionalValue() {
        ++;
        String argValue = .get().;
        if ( < argValue.length()) {
            return argValue.substring();
        }
        return null;
    }
    
New to GrepCode? Check out our FAQ X