private int executeCommand(CommandLine commandLine, String scriptName, String env) {
    @SuppressWarnings("hiding")
    GrailsConsole console = GrailsConsole.getInstance();
    // Load the BuildSettings file for this project if it exists. Note
    // that this does not load any environment-specific settings.
    try {
      System.setProperty("disable.grails.plugin.transform", "true");

      console.updateStatus("Loading Grails " + settings.getGrailsVersion());
      settings.loadConfig();

      System.setProperty(
          "springloaded.directoriesContainingReloadableCode",
          settings.getClassesDir().getAbsolutePath()
              + ','
              + settings.getPluginClassesDir().getAbsolutePath());
    } catch (Exception e) {
      console.error("There was an error loading the BuildConfig: " + e.getMessage(), e);
      System.exit(1);
    } finally {
      System.setProperty("disable.grails.plugin.transform", "false");
    }

    // Add some extra binding variables that are now available.
    // settings.setGrailsEnv(env);
    // settings.setDefaultEnv(useDefaultEnv);

    BuildSettingsHolder.setSettings(settings);

    return callPluginOrGrailsScript(commandLine, scriptName, env);
  }
  protected void initializeLogging() {
    if (settings.getGrailsHome() == null) {
      return;
    }

    try {
      Class<?> cls =
          Thread.currentThread()
              .getContextClassLoader()
              .loadClass("org.apache.log4j.PropertyConfigurator");
      Method configure = cls.getMethod("configure", URL.class);
      configure.setAccessible(true);
      File f =
          new File(settings.getGrailsHome() + "/grails-scripts/src/main/scripts/log4j.properties");
      if (f.exists()) {
        configure.invoke(cls, f.toURI().toURL());
      } else {
        f = new File(settings.getGrailsHome() + "/scripts/log4j.properties");
        configure.invoke(cls, f.toURI().toURL());
      }
    } catch (Throwable e) {
      console.verbose(
          "Log4j was not found on the classpath and will not be used for command line logging. Cause "
              + e.getClass().getName()
              + ": "
              + e.getMessage());
    }
  }
  @Override
  public void setResourceLoader(ResourceLoader resourceLoader) {
    if (Metadata.getCurrent().isWarDeployed()) {
      localResourceLoader = resourceLoader;
    } else {
      // The "settings" may be null in some of the Grails unit tests.
      BuildSettings settings = BuildSettingsHolder.getSettings();

      String location = null;
      if (settings != null) {
        location = settings.getResourcesDir().getPath();
      } else if (Environment.getCurrent().isReloadEnabled()) {
        location = Environment.getCurrent().getReloadLocation();
      }

      if (location != null) {
        localResourceLoader = new DevelopmentResourceLoader(application, location);
      } else {
        localResourceLoader = resourceLoader;
      }
    }
    super.setResourceLoader(localResourceLoader);

    if (resourceResolver == null) {
      resourceResolver = new PathMatchingResourcePatternResolver(localResourceLoader);
    }
  }
 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);
 }
  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;
  }
  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());
    }
  }
  public ResourceLocator getResourceLocator() {
    if (resourceLocator == null) {
      resourceLocator = new DefaultResourceLocator();
      BuildSettings buildSettings = BuildSettingsHolder.getSettings();
      String basedir;
      if (buildSettings != null) {
        basedir = buildSettings.getBaseDir().getAbsolutePath();
      } else {
        basedir = ".";
      }

      resourceLocator.setSearchLocation(basedir);
    }
    return resourceLocator;
  }
  protected void initializeLogging() {
    if (settings.getGrailsHome() == null) {
      return;
    }

    try {
      org.springframework.util.Log4jConfigurer.initLogging(
          "file:" + settings.getGrailsHome() + "/scripts/log4j.properties");
    } catch (Throwable e) {
      console.verbose(
          "Log4j was not found on the classpath and will not be used for command line logging. Cause "
              + e.getClass().getName()
              + ": "
              + e.getMessage());
    }
  }
  public BaseSettingsApi(
      BuildSettings settings, GrailsBuildEventListener buildEventListener, boolean interactive) {
    buildSettings = settings;
    buildProps = buildSettings.getConfig().toProperties();
    grailsHome = buildSettings.getGrailsHome();

    metadataFile = new File(buildSettings.getBaseDir(), "application.properties");

    metadata = metadataFile.exists() ? Metadata.getInstance(metadataFile) : Metadata.getCurrent();

    metadataFile = metadata.getMetadataFile();
    enableProfile = Boolean.valueOf(getPropertyValue("grails.script.profile", false).toString());
    pluginsHome = buildSettings.getProjectPluginsDir().getPath();
    pluginSettings = GrailsPluginUtils.getPluginBuildSettings(settings);
    grailsAppName = metadata.getApplicationName();
    isInteractive = interactive;

    // If no app name property (upgraded/new/edited project) default to basedir.
    if (grailsAppName == null) {
      grailsAppName = buildSettings.getBaseDir().getName();
    }

    if (grailsAppName.indexOf('/') > -1) {
      appClassName =
          grailsAppName.substring(grailsAppName.lastIndexOf('/'), grailsAppName.length());
    } else {
      appClassName = GrailsNameUtils.getClassNameRepresentation(grailsAppName);
    }
    configSlurper = buildSettings.createConfigSlurper();
    configSlurper.setEnvironment(buildSettings.getGrailsEnv());
    this.buildEventListener = buildEventListener;
  }
  protected void loadEventHooks(@SuppressWarnings("hiding") BuildSettings buildSettings) {
    if (buildSettings == null) {
      return;
    }

    loadEventsScript(findEventsScript(new File(buildSettings.getUserHome(), ".grails/scripts")));
    loadEventsScript(findEventsScript(new File(buildSettings.getBaseDir(), "scripts")));

    PluginBuildSettings pluginSettings =
        (PluginBuildSettings) binding.getVariable("pluginSettings");
    for (Resource pluginBase : pluginSettings.getPluginDirectories()) {
      try {
        loadEventsScript(findEventsScript(new File(pluginBase.getFile(), "scripts")));
      } catch (IOException ex) {
        throw new RuntimeException(ex);
      }
    }
  }
 public String makeRelative(String path) {
   if (buildSettings != null && path != null) {
     String absolutePath = buildSettings.getBaseDir().getAbsolutePath();
     if (path.startsWith(absolutePath)) {
       return path.substring(absolutePath.length() + 1);
     }
   }
   return path;
 }
 protected void loadGrailsBuildListeners() {
   for (Object listener : buildSettings.getBuildListeners()) {
     if (listener instanceof String) {
       addGrailsBuildListener((String) listener);
     } else if (listener instanceof Class<?>) {
       addGrailsBuildListener((Class<?>) listener);
     } else {
       throw new IllegalStateException(
           "buildSettings.getBuildListeners() returned a " + listener.getClass().getName());
     }
   }
 }
  /** Returns a list of all the executable Gant scripts available to this application. */
  public List<File> getAvailableScripts() {
    List<File> scripts = new ArrayList<File>();
    if (settings.getGrailsHome() != null) {
      addCommandScripts(new File(settings.getGrailsHome(), "scripts"), scripts);
      addCommandScripts(
          new File(settings.getGrailsHome(), "grails-scripts/src/main/scripts"), scripts);
    }
    addCommandScripts(new File(settings.getBaseDir(), "scripts"), scripts);
    addCommandScripts(new File(settings.getUserHome(), ".grails/scripts"), scripts);

    for (File dir : pluginPathSupport.listKnownPluginDirs()) {
      addPluginScripts(dir, scripts);
    }

    PathMatchingResourcePatternResolver resolver =
        new PathMatchingResourcePatternResolver(settings.getRootLoader());
    try {
      final Resource[] resources = resolver.getResources("classpath*:META-INF/scripts/*.groovy");
      for (Resource resource : resources) {
        scripts.add(resource.getFile());
      }
    } catch (IOException e) {
      // ignore
    }
    return scripts;
  }
  @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);
  }
 private int handleScriptExecutedOutsideProjectError() {
   console.error(
       settings.getBaseDir().getPath() + " does not appear to be part of a Grails application.");
   console.error("The following commands are supported outside of a project:");
   Collections.sort(
       scriptsAllowedOutsideOfProject,
       new Comparator<Resource>() {
         public int compare(Resource resource, Resource resource1) {
           return resource.getFilename().compareTo(resource1.getFilename());
         }
       });
   for (Resource file : scriptsAllowedOutsideOfProject) {
     console.log("\t" + GrailsNameUtils.getScriptName(file.getFilename()));
   }
   console.addStatus("Run 'grails help' for a complete list of available scripts.");
   return -1;
 }
  private void initializeState(String scriptName) {
    // The directory where scripts are cached.
    this.scriptCacheDir = new File(settings.getProjectWorkDir(), "scriptCache");
    this.console = GrailsConsole.getInstance();
    // Add the remaining JARs (from 'grailsHome', the app, and
    // the plugins) to the root loader.

    boolean skipPlugins =
        scriptName != null
            && ("UninstallPlugin".equals(scriptName) || "InstallPlugin".equals(scriptName));

    console.updateStatus("Configuring classpath");
    ClasspathConfigurer configurer =
        new ClasspathConfigurer(pluginPathSupport, settings, skipPlugins);
    if ("DependencyReport".equals(scriptName) || "Upgrade".equals(scriptName)) {
      configurer.setExitOnResolveError(false);
    }
    this.classLoader = configurer.configuredClassLoader();
    initializeLogging();
  }
 private boolean isGrailsProject() {
   return new File(settings.getBaseDir(), "grails-app").exists();
 }
 public String getServletVersion() {
   return buildSettings.getServletVersion();
 }
  /**
   * 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);
      }
    }
  }