Exemple #1
0
 private void runForked(String[] commandLine) {
   // use the main method in FileSystemCompiler
   final Execute executor =
       new Execute(); // new LogStreamHandler ( attributes , Project.MSG_INFO , Project.MSG_WARN )
                      // ) ;
   executor.setAntRun(getProject());
   executor.setWorkingDirectory(getProject().getBaseDir());
   executor.setCommandline(commandLine);
   try {
     executor.execute();
   } catch (final IOException ioe) {
     throw new BuildException("Error running forked groovyc.", ioe);
   }
   final int returnCode = executor.getExitValue();
   if (returnCode != 0) {
     taskSuccess = false;
     if (errorProperty != null) {
       getProject().setNewProperty(errorProperty, "true");
     }
     if (failOnError) {
       throw new BuildException("Forked groovyc returned error code: " + returnCode);
     } else {
       log.error("Forked groovyc returned error code: " + returnCode);
     }
   }
 }
  @Override
  public void execute() throws BuildException {

    // Source directory defaults to current directory
    if (_sourceDir == null) {
      _sourceDir = getProject().getBaseDir();
    }

    // Destination directory defaults to source directory
    if (_destDir == null) {
      _destDir = _sourceDir;
    }

    // Check the directories
    checkDir("Source directory", _sourceDir, true, false);
    checkDir("Destination directory", _destDir, false, true);

    // Create a watch dog, if there is a time-out configured
    ExecuteWatchdog watchdog = (_timeOut > 0L) ? new ExecuteWatchdog(_timeOut) : null;

    // Determine what command to execute
    String command = (_command == null || _command.length() < 1) ? DEFAULT_COMMAND : _command;

    // Check that the command is executable
    Buffer buffer = new Buffer();
    Execute execute = new Execute(buffer, watchdog);
    String[] cmdline = new String[] {command, "-v"};
    execute.setAntRun(getProject());
    execute.setCommandline(cmdline);
    try {
      if (execute.execute() != 0) {
        throw new BuildException(
            "Unable to execute LessCSS command "
                + quote(command)
                + ". Running '"
                + command
                + " -v' resulted in exit code "
                + execute.getExitValue()
                + '.');
      }
    } catch (IOException cause) {
      throw new BuildException("Unable to execute LessCSS command " + quote(command) + '.', cause);
    }

    // Display the command and version number
    String versionString = buffer.getOutString().trim();
    if (versionString.startsWith(command)) {
      versionString = versionString.substring(command.length()).trim();
    }
    if (versionString.startsWith("v")) {
      versionString = versionString.substring(1).trim();
    }
    log(
        "Using command " + quote(command) + ", version is " + quote(versionString) + '.',
        MSG_VERBOSE);

    // TODO: Improve this, detect kind of command
    boolean createOutputFile = command.indexOf("plessc") >= 0;

    // Preparations done, consider each individual file for processing
    log(
        "Transforming from " + _sourceDir.getPath() + " to " + _destDir.getPath() + '.',
        MSG_VERBOSE);
    long start = System.currentTimeMillis();
    int failedCount = 0, successCount = 0, skippedCount = 0;
    for (String inFileName : getDirectoryScanner(_sourceDir).getIncludedFiles()) {

      // Make sure the input file exists
      File inFile = new File(_sourceDir, inFileName);
      if (!inFile.exists()) {
        continue;
      }

      // Determine if the file type is supported
      if (!matches(inFileName.toLowerCase(), "\\.less$")) {
        log(
            "Skipping "
                + quote(inFileName)
                + " because the file does not end in \".less\" (case-insensitive).",
            MSG_VERBOSE);
        skippedCount++;
        continue;
      }

      // Some preparations related to the input file and output file
      long thisStart = System.currentTimeMillis();
      String outFileName = inFile.getName().replaceFirst("\\.less$", ".css");
      File outFile = new File(_destDir, outFileName);
      String outFilePath = outFile.getPath();
      String inFilePath = inFile.getPath();

      if (!_overwrite) {

        // Skip this file is the output file exists and is newer
        if (outFile.exists() && (outFile.lastModified() > inFile.lastModified())) {
          log("Skipping " + quote(inFileName) + " because output file is newer.", MSG_VERBOSE);
          skippedCount++;
          continue;
        }
      }

      // Prepare for the command execution
      buffer = new Buffer();
      watchdog = (_timeOut > 0L) ? new ExecuteWatchdog(_timeOut) : null;
      execute = new Execute(buffer, watchdog);
      cmdline =
          createOutputFile
              ? new String[] {command, inFilePath}
              : new String[] {command, inFilePath, outFilePath};

      execute.setAntRun(getProject());
      execute.setCommandline(cmdline);

      // Execute the command
      boolean failure;
      try {
        execute.execute();
        failure = execute.isFailure();
      } catch (IOException cause) {
        failure = true;
      }

      // Output to stderr or stdout indicates a failure
      String errorOutput = buffer.getErrString();
      errorOutput = isEmpty(errorOutput) ? buffer.getOutString() : errorOutput;
      failure = failure ? true : !isEmpty(errorOutput);

      // Create the output file if the command just sent everything to
      // standard out
      if (createOutputFile) {
        try {
          buffer.writeOutTo(new FileOutputStream(outFile));
        } catch (IOException cause) {
          throw new BuildException(
              "Failed to write output to file \"" + outFile.getPath() + "\".", cause);
        }
      }

      // Log the result for this individual file
      long thisDuration = System.currentTimeMillis() - thisStart;
      if (failure) {
        String logMessage = "Failed to transform " + quote(inFilePath);
        if (isEmpty(errorOutput)) {
          logMessage += '.';
        } else {
          logMessage += ':' + System.getProperty("line.separator") + errorOutput;
        }
        log(logMessage, MSG_ERR);
        failedCount++;
      } else {
        log("Transformed " + quote(inFileName) + " in " + thisDuration + " ms.", MSG_VERBOSE);
        successCount++;
      }
    }

    // Log the total result
    long duration = System.currentTimeMillis() - start;
    if (failedCount > 0) {
      throw new BuildException(
          ""
              + failedCount
              + " file(s) failed to transform, while "
              + successCount
              + " succeeded. Total duration is "
              + duration
              + " ms.");
    } else {
      log(
          ""
              + successCount
              + " file(s) transformed in "
              + duration
              + " ms; "
              + skippedCount
              + " file(s) skipped.");
    }
  }