Executes PHP_Depend_TextUI_Runner against PhingFile or a FileSet

@throws BuildException
973671
public function main()
    {
        $this->requireDependencies();

        if (!isset($this->file) and count($this->filesets) == 0) {
            throw new BuildException('Missing either a nested fileset or attribute "file" set');
        }

        if (count($this->loggers) == 0) {
            throw new BuildException('Missing nested "logger" element');
        }

        $this->validateLoggers();
        $this->validateAnalyzers();

        $filesToParse = $this->getFilesToParse();

        $runner = $this->createRunner();
        $runner->setSourceArguments($filesToParse);

        foreach ($this->loggers as $logger) {
            // Register logger
            if ($this->oldVersion) {
                $runner->addLogger(
                    $logger->getType(),
                    $logger->getOutfile()->__toString()
                );
            } else {
                $runner->addReportGenerator(
                    $logger->getType(),
                    $logger->getOutfile()->__toString()
                );
            }
        }

        foreach ($this->analyzers as $analyzer) {
            // Register additional analyzer
            $runner->addOption(
                $analyzer->getType(),
                $analyzer->getValue()
            );
        }

        // Disable annotation parsing
        if ($this->withoutAnnotations) {
            $runner->setWithoutAnnotations();
        }

        // Enable bad documentation support
        if ($this->supportBadDocumentation) {
            $runner->setSupportBadDocumentation();
        }

        // Check for suffix
        if (count($this->allowedFileExtensions) > 0) {
            $runner->setFileExtensions($this->allowedFileExtensions);
        }

        // Check for ignore directories
        if (count($this->excludeDirectories) > 0) {
            $runner->setExcludeDirectories($this->excludeDirectories);
        }

        // Check for exclude packages
        if (count($this->excludePackages) > 0) {
            $runner->setExcludePackages($this->excludePackages);
        }

        $runner->run();

        if ($runner->hasParseErrors() === true) {
            $this->log('Following errors occurred:');

            foreach ($runner->getParseErrors() as $error) {
                $this->log($error);
            }

            if ($this->haltonerror === true) {
                throw new BuildException('Errors occurred during parse process');
            }
        }
    }
897809
public function execute()
    {
        try {
            $this->updateFile();
        } catch (\Exception $e) {
            $this->out(self::STATUS_FAIL . $e->getMessage());
            $this->out($this->getFooter());
        }
    }
423080
protected function prepare()
    {
        // Log
        $this->log('Initializing started ', $this->loglevel);

        ///// Validating the required parameters /////

        if (!in_array($this->type, self::$types)) {
            throw new BuildException('Type must be one of \'file\', \'dir\' or \'both\'.');
        }

        // Executable
        if ($this->commandline->getExecutable() === null) {
            $this->throwBuildException('Please provide "executable" information');
        }

        // Retrieving the current working directory
        $this->currentdirectory = getcwd();

        // Directory (in which the command should be executed)
        if ($this->dir !== null) {
            // Try expanding (any) symbolic links
            if (!$this->dir->getCanonicalFile()->isDirectory()) {
                $this->throwBuildException("'" . $this->dir . "' is not a valid directory");
            }

            // Change working directory
            $dirchangestatus = @chdir($this->dir->getPath());

            // Log
            $this->log(
                'Working directory change ' . ($dirchangestatus ? 'successful' : 'failed') . ' to ' . $this->dir->getPath(),
                $this->loglevel
            );
        }

        ///// Preparing the task environment /////

        // Getting current operationg system
        $this->currentos = Phing::getProperty('os.name');

        // Log
        $this->log('Operating System identified : ' . $this->currentos, $this->loglevel);

        // Getting the O.S. type identifier
        // Validating the 'filesystem' for determining the OS type [UNIX, WINNT and WIN32]
        // (Another usage could be with 'os.name' for determination)
        if ('WIN' === strtoupper(substr(Phing::getProperty('host.fstype'), 0, 3))) {
            $this->osvariant = 'WIN'; // Probable Windows flavour
        } else {
            $this->osvariant = 'LIN'; // Probable GNU/Linux flavour
        }

        // Log
        $this->log('Operating System variant identified : ' . $this->osvariant, $this->loglevel);

        if (count($this->filesets) === 0 && count($this->filelists) === 0 && count($this->getDirSets()) === 0) {
            throw new BuildException(
                "no resources specified",
                $this->getLocation()
            );
        }
        if ($this->targetFilePos !== null && $this->mapperElement === null) {
            throw new BuildException(
                "targetfile specified without mapper",
                $this->getLocation()
            );
        }
        if ($this->destDir !== null && $this->mapperElement === null) {
            throw new BuildException(
                "dest specified without mapper",
                $this->getLocation()
            );
        }

        if ($this->mapperElement !== null) {
            $this->mapper = $this->mapperElement->getImplementation();
            $this->log('Mapper identified : ' . get_class($this->mapper), $this->loglevel);
        }

        $this->commandline->setEscape($this->escape);

        // Log
        $this->log('Initializing completed ', $this->loglevel);
    }
1184719
public function main()
    {
        // if composer autoloader is not yet loaded, load it here
        @include_once 'vendor/autoload.php';
        if (!class_exists('\\JShrink\\Minifier')) {
            throw new BuildException(
                'JsMinTask depends on JShrink being installed and on include_path.',
                $this->getLocation()
            );
        }

        if (empty($this->targetDir)) {
            throw new BuildException('Attribute "targetDir" is required');
        }

        foreach ($this->filesets as $fs) {
            try {
                $this->processFileSet($fs);
            } catch (BuildException $be) {
                // directory doesn't exist or is not readable
                if ($this->failonerror) {
                    throw $be;
                } else {
                    $this->log($be->getMessage(), Project::MSG_WARN);
                }
            }
        }
    }
170432
public function main()
    {

        // Make sure the template path is set.
        if (empty($this->templatePath)) {
            throw new BuildException("The template path needs to be defined!");
        }

        // Make sure the control template is set.
        if ($this->controlTemplate === null) {
            throw new BuildException("The control template needs to be defined!");
        }

        // Make sure the output directory is set.
        if ($this->outputDirectory === null) {
            throw new BuildException("The output directory needs to be defined!");
        }

        // Make sure there is an output file.
        if ($this->outputFile === null) {
            throw new BuildException("The output file needs to be defined!");
        }

        // Setup Smarty runtime.

        // Smarty uses one object to store properties and to store
        // the context for the template (unlike Smarty).  We setup this object, calling it
        // $this->context, and then initControlContext simply zeros out
        // any assigned variables.
        //
        // Use the smarty backwards compatibility layer if existent.
        if (class_exists('SmartyBC')) {
            $this->context = new SmartyBC();
        } else {
            $this->context = new Smarty();
        }

        if ($this->compilePath !== null) {
            $this->log("Using compilePath: " . $this->compilePath);
            $this->context->compile_dir = $this->compilePath;
        }

        if ($this->configPath !== null) {
            $this->log("Using configPath: " . $this->configPath);
            $this->context->config_dir = $this->configPath;
        }

        if ($this->forceCompile !== null) {
            $this->context->force_compile = $this->forceCompile;
        }

        if ($this->leftDelimiter !== null) {
            $this->context->left_delimiter = $this->leftDelimiter;
        }

        if ($this->rightDelimiter !== null) {
            $this->context->right_delimiter = $this->rightDelimiter;
        }

        if ($this->templatePath !== null) {
            $this->log("Using templatePath: " . $this->templatePath);
            $this->context->template_dir = $this->templatePath;
        }

        $smartyCompilePath = new PhingFile($this->context->compile_dir);
        if (!$smartyCompilePath->exists()) {
            $this->log(
                "Compile directory does not exist, creating: " . $smartyCompilePath->getPath(),
                Project::MSG_VERBOSE
            );
            if (!$smartyCompilePath->mkdirs()) {
                throw new BuildException("Smarty needs a place to compile templates; specify a 'compilePath' or create " . $this->context->compile_dir);
            }
        }

        // Make sure the output directory exists, if it doesn't
        // then create it.
        $file = new PhingFile($this->outputDirectory);
        if (!$file->exists()) {
            $this->log("Output directory does not exist, creating: " . $file->getAbsolutePath());
            $file->mkdirs();
        }

        $path = $this->outputDirectory . DIRECTORY_SEPARATOR . $this->outputFile;
        $this->log("Generating to file " . $path);

        $writer = new FileWriter($path);

        // The generator and the output path should
        // be placed in the init context here and
        // not in the generator class itself.
        $c = $this->initControlContext();

        // Set any variables that need to always
        // be loaded
        $this->populateInitialContext($c);

        // Feed all the options into the initial
        // control context so they are available
        // in the control/worker templates.
        if ($this->contextProperties !== null) {
            foreach ($this->contextProperties->keys() as $property) {
                $value = $this->contextProperties->getProperty($property);

                // Special exception (from Texen)
                // for properties ending in file.contents:
                // in that case we dump the contents of the file
                // as the "value" for the Property.
                if (StringHelper::endsWith("file.contents", $property)) {
                    // pull in contents of file specified

                    $property = substr($property, 0, strpos($property, "file.contents") - 1);

                    // reset value, and then
                    // read in the contents of the file into that var
                    $value = "";
                    $f = new PhingFile($this->project->resolveFile($value)->getCanonicalPath());
                    if ($f->exists()) {
                        try {
                            $br = new BufferedReader(new FileReader($f));
                            $value = $br->read();
                        } catch (Exception $e) {
                            throw $e;
                        }
                    }
                } // if ends with file.contents

                if (StringHelper::isBoolean($value)) {
                    $value = StringHelper::booleanValue($value);
                }

                $c->assign($property, $value);
            } // foreach property
        } // if contextProperties !== null

        try {
            //$c->display($this->controlTemplate);
            $writer->write($c->fetch($this->controlTemplate));
            $writer->close();
        } catch (IOException $ioe) {
            $writer->close();
            throw new BuildException("Cannot write parsed template.");
        }

        $this->cleanup();
    }
1250468
@Override
    public void execute () throws BuildException
    {
        // make sure everything was set up properly
        ensureSet(_config, "Must specify the path to the bundler config " +
                  "file via the 'config' attribute.");
        ensureSet(_mapfile, "Must specify the path to the tileset id map " +
                  "file via the 'mapfile' attribute.");

        File cfile = null;
        try {
            // create a tileset bundler
            TileSetBundler bundler = createBundler();

            // create our tileset id broker
            MapFileTileSetIDBroker broker =
                new MapFileTileSetIDBroker(_mapfile);

            // deal with the filesets
            for (int ii = 0; ii < _filesets.size(); ii++) {
                FileSet fs = _filesets.get(ii);
                DirectoryScanner ds = fs.getDirectoryScanner(getProject());
                File fromDir = fs.getDir(getProject());
                String[] srcFiles = ds.getIncludedFiles();

                for (String srcFile : srcFiles) {
                    cfile = new File(fromDir, srcFile);

                    // figure out the bundle file based on the definition
                    // file
                    String cpath = cfile.getPath();
                    if (!cpath.endsWith(".xml")) {
                        System.err.println("Can't infer bundle name from " +
                                           "bundle config name " +
                                           "[path=" + cpath + "].\n" +
                                           "Config file should end with .xml.");
                        continue;
                    }
                    String bpath = getTargetPath(fromDir, cpath);
                    File bfile = new File(bpath);

                    // create the bundle
                    if (bundler.createBundle(broker, cfile, bfile)) {
                        System.out.println(
                            "Created bundle from '" + cpath + "'...");
                    } else {
                        System.out.println(
                            "Tileset bundle up to date '" + bpath + "'.");
                    }
                }
            }

            // commit changes to the tileset id mapping
            broker.commit();

        } catch (Exception e) {
            String errmsg = "Failure creating tileset bundle [source=" + cfile +
                "]: " + e.getMessage();
            throw new BuildException(errmsg, e);
        }
    }
1235381
public function main()
    {
        $buildFileRoot = $this->getProject()->getProperty('phing.file');
        $buildFile     = isset($this->_buildFile) ? $this->_buildFile : $buildFileRoot;
        $buildList     = $this->getBuildList($buildFileRoot);
        $parents       = array();
        $targets       = array();

        if (isset($this->_buildFile) && is_file($this->_buildFile)
            && !empty($this->getOwningTarget()->getName())
        ) {
            foreach ($buildList as $buildFile => $buildInfo) {
                if ($this->_buildFile === $buildFile
                    || in_array($buildInfo['parent'], $parents)
                ) {
                    $parents[] = $buildFile;
                    $targets   = array_merge(
                        $targets,
                        $this->getBuildTargets($buildFile)
                    );
                }
            }

            $targets = array_merge($targets, $this->project->helpTargets);
            $this->printBuildTargets($targets, $buildFile, $buildList);
        }

    }
768946
public function main()
    {
        if ($this->length !== null && $this->adjust !== null) {
            throw new BuildException(
                'length and adjust are mutually exclusive options'
            );
        }
        if ($this->length === null && $this->adjust === null) {
            $this->length = 0;
        }
        if ($this->file === null) {
            throw new BuildException('No files specified.');
        }

        if ($this->shouldProcess($this->file)) {
            $this->process($this->file);
        }
    }
197329
public function main()
    {
        $this->verifyConfiguration();
        $this->prepareEncoderCommand();

        try {
            if (empty($this->filesets)) {
                throw new BuildException(
                    "You must supply nested fileset.",
                    $this->getLocation()
                );
            }

            $encodedFilesCounter = 0;

            foreach ($this->filesets as $fs) {
                /* @var $fs FileSet */

                /* @var $fsBasedir PhingFile */
                $fsBasedir = $fs->getDir($this->project)->getAbsolutePath();

                $files = $fs->getIterator(false);

                foreach ($files as $file) {
                    $f = new PhingFile($fsBasedir, $file);

                    if ($f->isFile()) {
                        $path = $f->getAbsolutePath();

                        $this->log("Encoding " . $path, Project::MSG_VERBOSE);
                        $this->encodeFile($path);

                        $encodedFilesCounter++;
                    }
                }
            }

            $this->log("Encoded files: " . $encodedFilesCounter);
        } catch (IOException $ioe) {
            $msg = "Problem encoding files: " . $ioe->getMessage();
            throw new BuildException($msg, $ioe, $this->getLocation());
        }
    }
783970
public function main()
    {
        if ($this->property == null) {
            throw new BuildException("property attribute required", $this->getLocation());
        }
        if ($this->file == null) {
            throw new BuildException("file attribute required", $this->getLocation());
        } else {
            $value = $this->file->getAbsoluteFile()->getParent();
            $this->getProject()->setNewProperty($this->property, $value);
        }
    }
730085
public void execute() throws BuildException
   {
      if (file == null)
         throw new BuildException("File not defined");

      if (!file.exists())
         throw new BuildException("File doesn't exists: " + file);

      try
      {
         Boolean result = null;
         if (isLocal())
         {
            Object value = executeCommand("local-undeploy", new Serializable[] {file.toURI().toURL()});

            if (value instanceof Boolean)
            {
               result = (Boolean)value;
            }
            else
            {
               throw (Throwable)value;
            }
         }
         else
         {
            Object value = executeCommand("remote-undeploy", new Serializable[] {file.getName()});

            if (value instanceof Boolean)
            {
               result = (Boolean)value;
            }
            else
            {
               throw (Throwable)value;
            }
         }

         if (result.booleanValue())
         {
            log("Undeployed: " + file.getName());
         }
         else
         {
            log(file.getName() + " wasn't undeployed");
         }
      }
      catch (Throwable t)
      {
         throw new BuildException("Unable to undeploy to " + getHost() + ":" + getPort() + " (" + t.getMessage() + ")",
                                  t);
      }
   }
1288056
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
      Set<File> thriftFiles = findThriftFiles();

      final File outputDirectory = getOutputDirectory();
      ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());

      Set<String> compileRoots = new HashSet<String>();
      compileRoots.add("scrooge");

      if (thriftFiles.isEmpty()) {
        getLog().info("No thrift files to compile.");
      } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {
        getLog().info("Generated thrift files up to date, skipping compile.");
        attachFiles(compileRoots);
      } else {
        outputDirectory.mkdirs();

        // Quick fix to fix issues with two mvn installs in a row (ie no clean)
        cleanDirectory(outputDirectory);

        getLog().info(format("compiling thrift files %s with Scrooge", thriftFiles));
        synchronized(lock) {
          ScroogeRunner runner = new ScroogeRunner();
          Map<String, String> thriftNamespaceMap = new HashMap<String, String>();
          for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {
            thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());
          }

          // Include thrifts from resource as well.
          Set<File> includes = thriftIncludes;
          includes.add(getResourcesOutputDirectory());

          // Include thrift root
          final File thriftSourceRoot = getThriftSourceRoot();
          if (thriftSourceRoot != null && thriftSourceRoot.exists()) {
            includes.add(thriftSourceRoot);
          }

          runner.compile(
                  getLog(),
                  includeOutputDirectoryNamespace ? new File(outputDirectory, "scrooge") : outputDirectory,
                  thriftFiles,
                  includes,
                  thriftNamespaceMap,
                  language,
                  thriftOpts);
        }
        attachFiles(compileRoots);
      }
    } catch (IOException e) {
      throw new MojoExecutionException("An IO error occurred", e);
    }
  }
355208
public function run()
    {
        if (PHP_SAPI === 'cli' && is_subclass_of($this, ConsoleAppInterface::class))
        {
            $this->execConsoleApp();
        }
        else if (is_subclass_of($this, WebAppInterface::class))
        {
            $this->execWebApp();
        }
        else
        {
            throw new \Exception("No interface was implemented");
        }
    }
286590
protected function loadFile(PhingFile $file)
    {
        $props = new Properties();
        try {
            if ($file->exists()) {
                $props->load($file);

                $this->addProperties($props);
            } else {
                $this->log(
                    'Unable to find property file: ' . $file->getAbsolutePath(),
                    Project::MSG_VERBOSE
                );
            }
        } catch (IOException $ex) {
            throw new BuildException($ex, $this->getLocation());
        }
    }
416382
public function main()
    {
        $arguments = $this->constructArguments();

        $makelicense = new PhingFile($this->ioncubePath, 'make_license');

        $this->log("Running ionCube make_license...");

        exec($makelicense->__toString() . " " . $arguments . " 2>&1", $output, $return);

        if ($return != 0) {
            throw new BuildException("Could not execute ionCube make_license: " . implode(' ', $output));
        }
    }
793780
public void execute() throws BuildException {
        checkParameters();
        resetFileLists();
        loadRegisteredScriptExtensions();

        if (javac != null) jointCompilation = true;

        // scan source directories and dest directory to build up
        // compile lists
        String[] list = src.list();
        for (String filename : list) {
            File file = getProject().resolveFile(filename);
            if (!file.exists()) {
                throw new BuildException("srcdir \"" + file.getPath() + "\" does not exist!", getLocation());
            }
            DirectoryScanner ds = this.getDirectoryScanner(file);
            String[] files = ds.getIncludedFiles();
            scanDir(file, destDir != null ? destDir : file, files);
        }

        compile();
        if (updatedProperty != null
                && taskSuccess
                && compileList.length != 0) {
            getProject().setNewProperty(updatedProperty, "true");
        }
    }
631463
public void execute() throws BuildException {
    log.debug("projectname=" + getProjectName());
    log.debug("src/srcdir=" + getSrcdir());
    log.debug("destdir=" + getDestdir());
    log.debug("failOnError=" + getFailOnError());
    log.debug("checkedArithmetic=" + isCheckedArithmetic());
    log.debug("scriptExtensions=" + getScriptExtensions());
    log.debug("_compileClasspath=" + _compileClasspath);

    if(isCheckedArithmetic()) {
      System.setProperty("checkedArithmetic", "true");
    }
    
    ICompilerDriver driver = new SoutCompilerDriver();
    IGosuCompiler gosuc = new gw.lang.gosuc.simple.GosuCompiler();

    List<String> classpath = new ArrayList<>();
    classpath.addAll(Arrays.asList(_compileClasspath.list()));
    classpath.addAll( GosucUtil.getJreJars());

    String startupMsg = "Initializing Gosu compiler";
    if(!getProjectName().isEmpty()) {
      startupMsg += " for " + getProjectName();
    }
    log.info(startupMsg);
    log.debug("\tsourceFolders:" + Arrays.asList(getSrcdir().list()));
    log.debug("\tclasspath:" + classpath);
    log.debug("\toutputPath:" + getDestdir().getAbsolutePath());

    List<String> sourceRoots = Arrays.asList(getSrcdir().list());
    for (String sourceRootName : sourceRoots) {
      File sourceRoot = getProject().resolveFile(sourceRootName);
      if (!sourceRoot.exists()) {
        throw new BuildException("srcdir \"" + sourceRoot.getPath() + "\" does not exist!", getLocation());
      }
      DirectoryScanner ds = this.getDirectoryScanner(sourceRoot);
      String[] files = ds.getIncludedFiles();
      if( hasSelectors() ) { 
        // we have explicit includes/excludes criteria nested in a <src> element; no need to call scanDir
        // this is the typical use case when ant is invoked dynamically by gradle
        for( String relativeFilename : files ) {
          compileList.add( new File( sourceRoot, relativeFilename ) );
        }
      } else {
        // <src> element was not used - instead we have an explicit list of srcDir elements 
        // and optionally additionalscriptextensions specified in addition to the defaults
        scanDir(sourceRoot, _destDir != null ? _destDir : sourceRoot, files);
      }
    }
    
    gosuc.initializeGosu( sourceRoots, classpath, getDestdir().getAbsolutePath() );

    log.debug("About to compile these files:");
    for(File file : compileList) {
      log.debug("\t" + file.getAbsolutePath());
    }
    
    for(File file : compileList) {
      try {
        gosuc.compile(file, driver);
      } catch (Exception e) {
        log.error(e.getMessage());
        throw new BuildException(e);
      }
    }

    gosuc.uninitializeGosu();

    List<String> warnings = ((SoutCompilerDriver) driver).getWarnings();
    boolean errorsInCompilation = ((SoutCompilerDriver) driver).hasErrors();
    List<String> errors = ((SoutCompilerDriver) driver).getErrors();
    
    List<String> warningMessages = new ArrayList<>();
    List<String> errorMessages = new ArrayList<>();
   
    warnings.forEach(warning -> warningMessages.add("[WARNING] " + warning));
    int numWarnings = warningMessages.size();

    int numErrors = 0;
    if(errorsInCompilation) {
      errors.forEach(error -> errorMessages.add("[ERROR] " + error));
      numErrors = errorMessages.size();
    }

    boolean hasWarningsOrErrors = numWarnings > 0 || errorsInCompilation;
    StringBuilder sb;
    sb = new StringBuilder();
    sb.append(getProjectName().isEmpty() ? "Gosu compilation" : getProjectName());
    sb.append(" completed");
    if(hasWarningsOrErrors) {
      sb.append(" with ");
      if(numWarnings > 0) {
        sb.append(numWarnings).append(" warning").append(numWarnings == 1 ? "" : 's');
      }
      if(errorsInCompilation) {
        sb.append(numWarnings > 0 ? " and " : "");
        sb.append(numErrors).append(" error").append(numErrors == 1 ? "" : 's');
      }
    } else {
      sb.append(" successfully.");
    }

    if(hasWarningsOrErrors) {
      log.warn(sb.toString());
    } else {
      log.info(sb.toString());
    }

    //log at most 100 warnings or errors
    warningMessages.subList(0, Math.min(warningMessages.size(), 100)).forEach(log::info);
    errorMessages.subList(0, Math.min(errorMessages.size(), 100)).forEach(log::error);

    if(errorsInCompilation) {
      if(getFailOnError()) {
        buildError("Gosu compilation failed with errors; see compiler output for details.");
      } else {
        log.warn("Gosu Compiler: Ignoring compilation failure(s) as 'failOnError' was set to false");
      }
    }
    
  }