コード例 #1
0
  public int executeScriptWithCaching(CommandLine commandLine) {
    processSystemArguments(commandLine);

    System.setProperty("grails.cli.args", commandLine.getRemainingArgsLineSeparated());
    return executeScriptWithCaching(
        commandLine,
        GrailsNameUtils.getNameFromScript(commandLine.getCommandName()),
        commandLine.getEnvironment());
  }
コード例 #2
0
  private GrailsConsole getConsole(CommandLine commandLine) {
    GrailsConsole console = GrailsConsole.getInstance();

    // Set the console display properties
    console.setAnsiEnabled(!commandLine.hasOption(CommandLine.NOANSI_ARGUMENT));
    console.setStacktrace(commandLine.hasOption(CommandLine.STACKTRACE_ARGUMENT));
    console.setVerbose(commandLine.hasOption(CommandLine.VERBOSE_ARGUMENT));

    return console;
  }
コード例 #3
0
 private static void loadConfigEnvironment(CommandLine commandLine, BuildSettings build) {
   String env;
   if (commandLine.isEnvironmentSet()) {
     env = commandLine.getEnvironment();
   } else {
     env = commandLine.lookupEnvironmentForCommand();
   }
   build.setGrailsEnv(env);
   build.loadConfig(env);
 }
コード例 #4
0
  private static ScriptAndArgs processArgumentsAndReturnScriptName(CommandLine commandLine) {

    if (commandLine.hasOption(CommandLine.VERBOSE_ARGUMENT)) {
      GrailsConsole.getInstance().setVerbose(true);
    }
    if (commandLine.hasOption(CommandLine.STACKTRACE_ARGUMENT)) {
      GrailsConsole.getInstance().setStacktrace(true);
    }

    processSystemArguments(commandLine);
    return processAndReturnArguments(commandLine);
  }
コード例 #5
0
  private static ScriptAndArgs processAndReturnArguments(CommandLine commandLine) {
    ScriptAndArgs info = new ScriptAndArgs();
    if (Environment.isSystemSet()) {
      info.env = Environment.getCurrent().getName();
    } else if (commandLine.getEnvironment() != null) {
      info.env = commandLine.getEnvironment();
    }

    info.inputName = commandLine.getCommandName();
    info.name = GrailsNameUtils.getNameFromScript(commandLine.getCommandName());
    return info;
  }
コード例 #6
0
  private int attemptPrecompiledScriptExecute(
      CommandLine commandLine,
      String scriptName,
      String env,
      GantBinding binding,
      List<File> allScripts) {
    console.updateStatus("Running pre-compiled script");

    // Must be called before the binding is initialised.
    setRunningEnvironment(commandLine, env);

    // Get Gant to load the class by name using our class loader.
    ScriptBindingInitializer bindingInitializer =
        new ScriptBindingInitializer(
            commandLine, classLoader, settings, pluginPathSupport, isInteractive);
    Gant gant = new Gant(bindingInitializer.initBinding(binding, scriptName), classLoader);

    try {
      loadScriptClass(gant, scriptName);
    } catch (ScriptNotFoundException e) {
      if (!isInteractive || InteractiveMode.isActive()) {
        throw e;
      }
      scriptName = fixScriptName(scriptName, allScripts);
      if (scriptName == null) {
        throw e;
      }

      try {
        loadScriptClass(gant, scriptName);
      } catch (ScriptNotFoundException ce) {
        return executeScriptWithCaching(commandLine, scriptName, env);
      }

      // at this point if they were calling a script that has a non-default
      // env (e.g. war or test-app) it wouldn't have been correctly set, so
      // set it now, but only if they didn't specify the env (e.g. "grails test war" -> "grails test
      // war")

      if (Boolean.TRUE.toString().equals(System.getProperty(Environment.DEFAULT))) {
        commandLine.setCommand(GrailsNameUtils.getScriptName(scriptName));
        env = commandLine.lookupEnvironmentForCommand();
        binding.setVariable("grailsEnv", env);
        settings.setGrailsEnv(env);
        System.setProperty(Environment.KEY, env);
        settings.setDefaultEnv(false);
        System.setProperty(Environment.DEFAULT, Boolean.FALSE.toString());
      }
    }

    return executeWithGantInstance(gant, DO_NOTHING_CLOSURE, binding).exitCode;
  }
コード例 #7
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  private int executeScriptWithCaching(CommandLine commandLine, String scriptName, String env) {
    List<File> potentialScripts;
    List<File> allScripts = getAvailableScripts();
    GantBinding binding = new GantBinding();
    binding.setVariable("scriptName", scriptName);

    setDefaultInputStream(binding);

    // Now find what scripts match the one requested by the user.
    potentialScripts = getPotentialScripts(scriptName, allScripts);

    if (potentialScripts.size() == 0) {
      try {
        File aliasFile = new File(settings.getUserHome(), ".grails/.aliases");
        if (aliasFile.exists()) {
          Properties aliasProperties = new Properties();
          aliasProperties.load(new FileReader(aliasFile));
          if (aliasProperties.containsKey(commandLine.getCommandName())) {
            String aliasValue = (String) aliasProperties.get(commandLine.getCommandName());
            String[] aliasPieces = aliasValue.split(" ");
            String commandName = aliasPieces[0];
            String correspondingScriptName = GrailsNameUtils.getNameFromScript(commandName);
            potentialScripts = getPotentialScripts(correspondingScriptName, allScripts);

            if (potentialScripts.size() > 0) {
              String[] additionalArgs = new String[aliasPieces.length - 1];
              System.arraycopy(aliasPieces, 1, additionalArgs, 0, additionalArgs.length);
              insertArgumentsInFrontOfExistingArguments(commandLine, additionalArgs);
            }
          }
        }
      } catch (Exception e) {
        console.error(e);
      }
    }

    // First try to load the script from its file. If there is no
    // file, then attempt to load it as a pre-compiled script. If
    // that fails, then let the user know and then exit.
    if (potentialScripts.size() > 0) {
      potentialScripts = (List) DefaultGroovyMethods.unique(potentialScripts);
      final File scriptFile = potentialScripts.get(0);
      if (!isGrailsProject() && !isExternalScript(scriptFile)) {
        return handleScriptExecutedOutsideProjectError();
      }
      return executeScriptFile(commandLine, scriptName, env, binding, scriptFile);
    }

    return attemptPrecompiledScriptExecute(commandLine, scriptName, env, binding, allScripts);
  }
コード例 #8
0
  private void setRunningEnvironment(CommandLine commandLine, String env) {
    // Get the default environment if one hasn't been set.
    System.setProperty("base.dir", settings.getBaseDir().getPath());

    if (env != null) {
      // Add some extra binding variables that are now available.
      settings.setGrailsEnv(env);
      settings.setDefaultEnv(false);
    } else {
      // Add some extra binding variables that are now available.
      settings.setGrailsEnv(commandLine.getEnvironment());
      settings.setDefaultEnv(!commandLine.isEnvironmentSet());
    }
  }
コード例 #9
0
 private void insertArgumentsInFrontOfExistingArguments(
     CommandLine commandLine, String[] argumentsToInsert) {
   List<String> remainingArgs = commandLine.getRemainingArgs();
   for (int i = argumentsToInsert.length - 1; i >= 0; i--) {
     remainingArgs.add(0, argumentsToInsert[i]);
   }
 }
コード例 #10
0
 private static void processSystemArguments(CommandLine allArgs) {
   Properties systemProps = allArgs.getSystemProperties();
   if (systemProps != null) {
     for (Map.Entry<Object, Object> entry : systemProps.entrySet()) {
       System.setProperty(entry.getKey().toString(), entry.getValue().toString());
     }
   }
 }
コード例 #11
0
  /**
   * Evaluate the arguments to get the name of the script to execute, which environment to run it
   * in, and the arguments to pass to the script. This also evaluates arguments of the form
   * "-Dprop=value" and creates system properties from each one.
   *
   * @param args Command line arguments
   */
  public static void main(String[] args) {
    originalIn = System.in;
    originalOut = System.out;

    CommandLineParser parser = getCommandLineParser();

    GrailsConsole console = GrailsConsole.getInstance();

    CommandLine commandLine;
    try {
      if (args.length == 0) {
        commandLine = new DefaultCommandLine();
      } else {
        commandLine = parser.parseString(args[0]);
        if (commandLine.hasOption(CommandLine.NOANSI_ARGUMENT)) {
          console.setAnsiEnabled(false);
        }
      }
    } catch (ParseException e) {
      console.error("Error processing command line arguments: " + e.getMessage());
      System.exit(1);
      return;
    }

    String version = System.getProperty("grails.version");

    ScriptAndArgs script = processArgumentsAndReturnScriptName(commandLine);

    // Get hold of the GRAILS_HOME environment variable if it is available.
    String grailsHome = System.getProperty("grails.home");

    // Now we can pick up the Grails version from the Ant project properties.
    BuildSettings build = null;
    try {
      build = new BuildSettings(new File(grailsHome));
      build.setModified(commandLine.hasOption(CommandLine.REFRESH_DEPENDENCIES_ARGUMENT));
      build.setOffline(commandLine.hasOption(CommandLine.OFFLINE_ARGUMENT));
      if (build.getRootLoader() == null) {
        build.setRootLoader((URLClassLoader) GrailsScriptRunner.class.getClassLoader());
      }
    } catch (Exception e) {
      exitWithError(
          "An error occurred loading the grails-app/conf/BuildConfig.groovy file: "
              + e.getMessage(),
          null);
    }

    // Check that Grails' home actually exists.
    final File grailsHomeInSettings = build.getGrailsHome();
    if (grailsHomeInSettings == null || !grailsHomeInSettings.exists()) {
      exitWithError("Grails' installation directory not found: " + build.getGrailsHome(), null);
    }

    if (commandLine.hasOption(CommandLine.VERSION_ARGUMENT)) {
      console.log("Grails version: " + build.getGrailsVersion());
      System.exit(0);
    }

    if (commandLine.hasOption(CommandLine.HELP_ARGUMENT)) {
      console.log(parser.getHelpMessage());
      System.exit(0);
    }

    // If there aren't any arguments, then we don't have a command
    // to execute, so enter "interactive mode"
    boolean resolveDeps = commandLine.hasOption(CommandLine.REFRESH_DEPENDENCIES_ARGUMENT);
    if (resolveDeps) {
      if (commandLine.hasOption("include-source")) {
        build.setIncludeSource(true);
      }
      if (commandLine.hasOption("include-javadoc")) {
        build.setIncludeJavadoc(true);
      }
    }
    GrailsScriptRunner scriptRunner = new GrailsScriptRunner(build);
    scriptRunner.setInteractive(!commandLine.hasOption(CommandLine.NON_INTERACTIVE_ARGUMENT));
    if ("Interactive".equals(script.name)) {
      console.error(
          "The 'interactive' script is deprecated; to run in interactive mode just omit the script name");
      script.name = null;
    }
    if (script.name == null) {
      console.updateStatus(
          "Loading Grails " + (version != null ? version : build.getGrailsVersion()));

      build.loadConfig();
      if (resolveDeps) {
        ClasspathConfigurer.cleanResolveCache(build);
      }
      scriptRunner.initializeState();
      try {
        new InteractiveMode(build, scriptRunner).run();
      } catch (Throwable e) {
        console.error("Interactive mode exited with error: " + e.getMessage(), e);
      }
    } else {
      console.getCategory().push(script.inputName);
      console.verbose("Base Directory: " + build.getBaseDir().getPath());

      try {
        int exitCode = scriptRunner.executeCommand(commandLine, script.name, script.env);
        System.exit(exitCode);
      } catch (ScriptNotFoundException ex) {
        console.error("Script not found: " + ex.getScriptName());
      } catch (Throwable t) {
        String msg = "Error executing script " + script.name + ": " + t.getMessage();
        exitWithError(msg, t);
      }
    }
  }