Handle provided directory

Optionally an existing result file can be provided

If a valid file could be generated the file name is supposed to be
returned, otherwise return null.

@param Project $project
@param string $existingResult
@return string
433383
public function handle(Project $project, $existingResult = null)
    {
        if ($existingResult) {
            // @TODO: Verify file is actually sensible?
            return $existingResult;
        }

        $options = array(
            '--count-tests',
            '--log-xml=' . ($tmpFile = $this->shell->getTempFile('qa', 'xml')),
        );

        foreach ($project->excludes as $exclude) {
            $options[] = '--exclude=' . $exclude;
        }

        $this->shell->exec('vendor/bin/phploc', array_merge($options, array($project->baseDir)));
        return $tmpFile;
    }
206585
public function readProjectConfigFile($dir, $configFile)
    {
        $result = null;
        $filename = $dir . '/' . $this->config->get('service.project_config_dir') . '/' . $configFile;
        if (file_exists($filename)) {
            $parser = new Parser();
            $result = $parser->parse(file_get_contents($filename));
        }

        return $result;
    }
328195
public function addProject(Project $project)
    {
        $this->storage->updateProject($project);

        $this->projects[$project->getSlug()] = $project;
    }
131764
public function execute(ProjectDescriptor $project): void
    {
        $markerTerms = $project->getSettings()->getMarkers();

        foreach ($project->getFiles() as $file) {
            $marker_data = [];
            $matches = [];
            preg_match_all(
                '~//[\s]*(' . implode('|', $markerTerms) . ')\:?[\s]*(.*)~',
                $file->getSource(),
                $matches,
                PREG_SET_ORDER | PREG_OFFSET_CAPTURE
            );

            foreach ($matches as $match) {
                list($before) = str_split($file->getSource(), $match[1][1]); // fetches all the text before the match

                $line_number = strlen($before) - strlen(str_replace("\n", '', $before)) + 1;

                $marker_data[] = ['type' => trim($match[1][0], '@'), 'line' => $line_number, $match[2][0]];
            }

            $file->setMarkers(new Collection($marker_data));
        }
    }
582101
function handleFileRename() {
        // Prefer selected sidebar item (which could be a folder)
        var entry = ProjectManager.getContext();
        if (!entry) {
            // Else use current file (not selected in ProjectManager if not visible in tree or workingset)
            entry = MainViewManager.getCurrentlyViewedFile();
        }
        if (entry) {
            ProjectManager.renameItemInline(entry);
        }
    }
774224
static function &loadExistingReport($reportfile, $projects_folder = "projects")
    {
        $q = new Reportico();
        $q->reports_path = $projects_folder . "/" . ReporticoApp::getconfig("project");
        $q->projects_folder = $projects_folder;

        $reader = new XmlReader ($q, $reportfile, false);
        $reader->xml2query();

        return $q;
    }
190362
def project_rename_folder(object_id, input_params={}, always_retry=False, **kwargs):
    
    return DXHTTPRequest('/%s/renameFolder' % object_id, input_params, always_retry=always_retry, **kwargs)
1105899
public static final function registerProject(Project $project) {
        if (isset(self::$REGISTERED_PRROJECT_INSTANCES[$project->getProjectName()])) {
            throw new ConflictProjectNameException(sprintf("The project \"%s\" EXISTS.", $project->getProjectName()));
        }
        self::$REGISTERED_PRROJECT_INSTANCES[$project->getProjectName()] = $project;
    }
743006
public function getFiles(Project $p)
    {
        if ($this->isReference()) {
            $ret = $this->getRef($p);
            $ret = $ret->getFiles($p);

            return $ret;
        }

        if ($this->listfile !== null) {
            $this->readListFile($p);
        }

        return $this->filenames;
    }
687851
public ProjectFileHandler getProjectFile(final int projectId, final int version) {
    log.info(
        String.format("Fetching project file. project ID: %d version: %d", projectId, version));
    // TODO spyne: remove huge hack ! There should not be any special handling for Database Storage.
    if (this.storage instanceof DatabaseStorage) {
      return ((DatabaseStorage) this.storage).get(projectId, version);
    }

    /* Fetch meta data from db */
    final ProjectFileHandler pfh = this.projectLoader.fetchProjectMetaData(projectId, version);

    /* Fetch project file from storage and copy to local file */
    final String resourceId = requireNonNull(pfh.getResourceId(),
        String.format("URI is null. project ID: %d version: %d",
            pfh.getProjectId(), pfh.getVersion()));
    try (InputStream is = this.storage.get(resourceId)) {
      final File file = createTempOutputFile(pfh);

      /* Copy from storage to output stream */
      try (FileOutputStream fos = new FileOutputStream(file)) {
        IOUtils.copy(is, fos);
      }

      /* Validate checksum */
      validateChecksum(file, pfh);

      /* Attach file to handler */
      pfh.setLocalFile(file);

      return pfh;
    } catch (final IOException e) {
      throw new StorageException(e);
    }
  }
960424
public static final function getRegisteredProject($project_name) {
        if (isset(self::$REGISTERED_PRROJECT_INSTANCES[$project_name])) {
            return self::$REGISTERED_PRROJECT_INSTANCES[$project_name];
        } else {
            throw new ProjectNotFoundException(sprintf("The project \"%s\" NOT registered.", $project_name));
        }
    }
96041
public function generate(Project $project)
    {
        $newFile = clone $this->file;
        $newFile->setData([
            'generator' => array_filter($this->file->getData('generator'), function ($value) {
                return $value !== 'PaginationGenerator';
            }),
        ]);

        if (! $configuration = $this->file->getData('pagination')) {
            return $newFile;
        }

        $defaultConfiguration = [
            'perPage' => 5,
            'skip' => 0,
        ];

        $configuration = array_merge($defaultConfiguration, $configuration);
        $paginationKey = $configuration['provider'].'_items';

        if (! $paginationItems = $this->file->getData($paginationKey)) {
            return $newFile;
        }

        $paginationItems = array_filter($paginationItems, function ($key) use ($project) {
            return $project->has('files.'.$key);
        }, ARRAY_FILTER_USE_KEY);

        // Segment $paginationItems into n segments based upon perPage and create a clone of the file with that page's items
        // also update the files permalink and uid (unless its the first page). Follow up by injecting an instance of Paginator
        // which is loaded with previous/next links and how many total pages there are.

        $totalPages = ceil(count($paginationItems) / $configuration['perPage']);

        // If there are no pages because the pagination filter cleared out the array then return; otherwise this ends
        // up with an infinite loop
        if ($totalPages == 0) {
            return $newFile;
        }

        $generatedFiles = [];

        // Skip functionality for #147
        // @link https://github.com/carbontwelve/tapestry/issues/147
        if ($configuration['skip'] > 0) {
            $paginationItems = array_slice($paginationItems, $configuration['skip'], null, true);
        }

        $currentPage = 0;
        foreach (array_chunk($paginationItems, $configuration['perPage'], true) as $pageItems) {
            $pageFile = clone $newFile;
            $currentPage++;
            $pageFile->setData(['pagination' => new Pagination($project, $pageItems, $totalPages, ($currentPage))]);

            if ($currentPage > 1) {
                $pageFile->setUid($pageFile->getUid().'_page_'.$currentPage);

                $permalink = $pageFile->getPermalink();
                $template = $permalink->getTemplate();

                if (strpos($template, '.')) {
                    $parts = explode('.', $template);
                    $parts[0] .= '/{page}';
                    $template = implode('.', $parts);
                } else {
                    $template .= '/{page}';
                }

                // If the page calling this generator is, itself an index then we need to strip {filename} from the $template
                // because nobody expects page one to be /blog/index.html and page two to be blog/index/2/index.html
                // as per issue #50

                if ($this->file->getFilename() === 'index') {
                    $parts = array_filter(explode('/', $template), function ($value) {
                        return $value !== '{filename}';
                    });

                    $template = implode('/', $parts);
                }

                $pageFile->setPermalink(new Permalink($template));
            }

            array_push($generatedFiles, $pageFile);
            unset($pageFile);
        }

        $totalGenerated = count($generatedFiles);
        if ($totalGenerated > 1) {
            /**
             * @var int
             * @var File $generatedFile
             */
            foreach ($generatedFiles as $key => &$generatedFile) {
                /*
                 * @var Pagination
                 * @var null|File  $previous
                 * @var null|File  $next
                 */
                $pagination = $generatedFile->getData('pagination');

                $next = (isset($generatedFiles[($key + 1)])) ? $generatedFiles[($key + 1)] : null;
                $previous = (isset($generatedFiles[($key - 1)])) ? $generatedFiles[($key - 1)] : null;

                $pagination->setPreviousNext(
                    is_null($previous) ? null : $previous->getUid(),
                    is_null($next) ? null : $next->getUid()
                );

                $pagination->setPages($generatedFiles);
            }
            unset($generatedFile);
        }

        return $generatedFiles;
    }
606844
public function getDir(Project $p = null)
    {
        if ($p === null) {
            $p = $this->getProject();
        }
        if ($this->pps === null) {
            $this->loadPearPackageScanner($p);
        }

        return new PhingFile((string) $this->pps->getBaseDir());
    }
772000
public File getDirectory(String targetProject, String targetPackage)
      throws ShellException {
    // targetProject is interpreted as a directory that must exist
    //
    // targetPackage is interpreted as a sub directory, but in package
    // format (with dots instead of slashes). The sub directory will be
    // created
    // if it does not already exist

    File project = new File(targetProject);
    if (!project.isDirectory()) {
      throw new ShellException(getString("Warning.9", //$NON-NLS-1$
          targetProject));
    }

    StringBuilder sb = new StringBuilder();
    StringTokenizer st = new StringTokenizer(targetPackage, "."); //$NON-NLS-1$
    while (st.hasMoreTokens()) {
      sb.append(st.nextToken());
      sb.append(File.separatorChar);
    }

    File directory = new File(project, sb.toString());
    if (!directory.isDirectory()) {
      boolean rc = directory.mkdirs();
      if (!rc) {
        throw new ShellException(getString("Warning.10", //$NON-NLS-1$
            directory.getAbsolutePath()));
      }
    }

    return directory;
  }
978563
public function valid(Project $project)
    {
        if ($this->ifCond !== null && $project->getProperty($this->ifCond) === null) {
            return false;
        } else {
            if ($this->unlessCond !== null && $project->getProperty($this->unlessCond) !== null) {
                return false;
            }
        }

        return true;
    }
113631
public static function translatePath(Project $project, $source)
    {
        $result = [];
        if ($source == null) {
            return "";
        }

        $tok = new PathTokenizer($source);
        while ($tok->hasMoreTokens()) {
            $pathElement = $tok->nextToken();
            try {
                $element = self::resolveFile($project, $pathElement);
                for ($i = 0, $_i = strlen($element); $i < $_i; $i++) {
                    self::translateFileSep($element, $i);
                }
                $result[] = $element;
            } catch (BuildException $e) {
                $project->log(
                    "Dropping path element " . $pathElement
                    . " as it is not valid relative to the project",
                    Project::MSG_VERBOSE
                );
            }
        }

        return $result;
    }
1198845
public function readClass(Project $project, $name)
    {
        if (!file_exists($this->getFilename($project, $name))) {
            throw new \InvalidArgumentException(sprintf('File "%s" for class "%s" does not exist.', $this->getFilename($project, $name), $name));
        }

        return ClassReflection::fromArray($project, json_decode(file_get_contents($this->getFilename($project, $name)), true));
    }