Returns the directory scanner needed to access the files to process.

@param  PhingFile $baseDir
@throws BuildException
@return DirectoryScanner
777648
protected function getDirectoryScanner(PhingFile $baseDir)
    {
        $this->fileset->setDir($baseDir);
        $this->fileset->setDefaultexcludes($this->useDefaultExcludes);

        return $this->fileset->getDirectoryScanner($this->project);
    }
857343
public function scanDir()
    {
        // only possible in directories
        if (!$this->isDir() || !$this->exists()) {
            return null;
        }

        $fileList = [];
        $fileNameList = scandir($this->absoluteFileName);
        foreach ($fileNameList as $fileName) {
            // do not add . and ..
            if ($fileName === "." or $fileName === "..") {
                continue;
            }
            $absoluteFileName = $this->absoluteFileName . "/" . $fileName;
            $fileList [] = new File ($absoluteFileName);
        }

        return $fileList;
    }
174874
protected function makeDirectory($path, $baseDir = null)
    {
        if (is_dir($path) === true) {
            return;
        }

        if ($this->chmod === null) {
            $chmod = 0777;
        } else {
            $chmod = $this->chmod;
        }

        $retries = 3;
        while ($retries --) {
            @mkdir($path, $chmod, true);
            if (is_dir($path)) {
                break;
            }
            usleep(20);
        }

        // enforce the correct mode for all directories created
        if (strpos(PHP_OS, 'WIN') !== 0 && $baseDir !== null) {
            $path    = strtr(str_replace($baseDir, '', $path), '\\', '/');
            $folders = explode('/', trim($path, '/'));
            foreach ($folders as $folder) {
                $baseDir .= $folder . DIRECTORY_SEPARATOR;
                if (!chmod($baseDir, $chmod)) {
                    throw new Exception('Unable to chmod ' . "$baseDir to $chmod: " . print_r(error_get_last(), true));
                }
            }
        }
    }
571677
public function getList($templateType, $base = THELIA_TEMPLATE_DIR)
    {
        $list = $exclude = array();

        $tplIterator = TemplateDefinition::getStandardTemplatesSubdirsIterator();

        foreach ($tplIterator as $type => $subdir) {
            if ($templateType == $type) {
                $baseDir = rtrim($base, DS).DS.$subdir;

                try {
                    // Every subdir of the basedir is supposed to be a template.
                    $di = new \DirectoryIterator($baseDir);

                    /** @var \DirectoryIterator $file */
                    foreach ($di as $file) {
                        // Ignore 'dot' elements
                        if ($file->isDot() || ! $file->isDir()) {
                            continue;
                        }

                        // Ignore reserved directory names
                        if (\in_array($file->getFilename(), $exclude)) {
                            continue;
                        }

                        $list[] = new TemplateDefinition($file->getFilename(), $templateType);
                    }
                } catch (\UnexpectedValueException $ex) {
                    // Ignore the exception and continue
                }
            }
        }

        return $list;
    }
1250408
public static function register($baseDir = null)
    {
        $key = $baseDir ? $baseDir : 0;

        if (!isset(self::$instances[$key])) {
            self::$instances[$key] = new self($baseDir);
        }

        $loader = self::$instances[$key];
        spl_autoload_register(array($loader, 'autoload'));

        return $loader;
    }
547675
public function getBaseDirectory($directoryToAppend = null)
    {
        $baseDirectory = $this->getNamingDirectory()->search('php:env/baseDirectory');
        if ($directoryToAppend != null) {
            $baseDirectory .= $directoryToAppend;
        }
        return $baseDirectory;
    }
151947
public function build(array $extra, $baseDir)
    {
        $this->reset();

        $commitAuto = 'never';
        $commitBinFile = null;
        $commitMessage = 'Update dependencies';
        $gitlabHosts = [];
        $postUpdatePriority = -1;

        if (array_key_exists('commit-auto', $extra)) {
            if (in_array($extra['commit-auto'], self::$validCommitAutoValues, true)) {
                $commitAuto = $extra['commit-auto'];
            } else {
                $this->warnings[] = self::createWarningFromInvalidValue(
                    $extra,
                    'commit-auto',
                    $commitAuto,
                    sprintf('Valid options are "%s".', implode('", "', self::$validCommitAutoValues))
                );
            }
        }

        if (array_key_exists('commit-bin-file', $extra)) {
            if ($commitAuto === 'never') {
                $this->warnings[] = '"commit-bin-file" is specified but "commit-auto" option is set to "never". Ignoring.';
            } else {
                $file = realpath(
                    FileSystemHelper::isAbsolute($extra['commit-bin-file'])
                    ? $extra['commit-bin-file']
                    : $baseDir . '/' . $extra['commit-bin-file']
                );

                if (!file_exists($file)) {
                    $this->warnings[] = 'The file pointed by the option "commit-bin-file" was not found. Ignoring.';
                } else {
                    $commitBinFile = $file;
                }
            }
        } else {
            if ($commitAuto !== 'never') {
                $this->warnings[] = sprintf(
                    '"commit-auto" is set to "%s" but "commit-bin-file" was not specified.',
                    $commitAuto
                );
            }
        }

        if (array_key_exists('commit-message', $extra)) {
            if (strlen(trim($extra['commit-message'])) === 0) {
                $this->warnings[] = '"commit-message" is specified but empty. Ignoring and using default commit message.';
            } else {
                $commitMessage = $extra['commit-message'];
            }
        }

        if (array_key_exists('gitlab-hosts', $extra)) {
            if (!is_array($extra['gitlab-hosts'])) {
                $this->warnings[] = '"gitlab-hosts" is specified but should be an array. Ignoring.';
            } else {
                $gitlabHosts = (array) $extra['gitlab-hosts'];
            }
        }

        if (array_key_exists('post-update-priority', $extra)) {
            if (!preg_match('/^-?\d+$/', $extra['post-update-priority'])) {
                $this->warnings[] = '"post-update-priority" is specified but not an integer. Ignoring and using default commit event priority.';
            } else {
                $postUpdatePriority = (int) $extra['post-update-priority'];
            }
        }

        return new Config($commitAuto, $commitBinFile, $commitMessage, $gitlabHosts, $postUpdatePriority);
    }
368603
public function getPathWithoutBase($basedir)
    {
        if (!StringHelper::endsWith(self::$separator, $basedir)) {
            $basedir .= self::$separator;
        }
        $path = $this->getPath();
        if (substr($path, 0, strlen($basedir)) != $basedir) {
            //path does not begin with basedir, we don't modify it
            return $path;
        }

        return substr($path, strlen($basedir));
    }
877035
public static function init($baseDir = "", $verbose = true) {
		
		// make sure a base dir was supplied
		if (empty($baseDir)) {
			Console::writeError("need a base directory to initialize the config class...");
		}
		
		// normalize the baseDir
		$baseDir = FileUtil::normalizePath($baseDir);
		
		// double-check the default config file exists
		if (!is_dir($baseDir)) {
			Console::writeError("make sure ".$baseDir." exists...");
		}
		
		// set the baseDir option
		self::$options["baseDir"] = ($baseDir[strlen($baseDir)-1] == DIRECTORY_SEPARATOR) ? $baseDir : $baseDir.DIRECTORY_SEPARATOR;
		
		// set-up the paths
		self::$userConfigDirClean  = self::$options["baseDir"].self::$userConfigDirClean;
		self::$userConfigDirDash   = self::$options["baseDir"].self::$userConfigDirDash;
		self::$userConfigDir       = (is_dir(self::$userConfigDirDash)) ? self::$userConfigDirDash : self::$userConfigDirClean;
		self::$userConfigPath      = self::$userConfigDir.DIRECTORY_SEPARATOR.self::$userConfig;
		self::$plConfigPath        = self::$options["baseDir"]."vendor/pattern-lab/core/".self::$plConfigPath;
		
		// can't add __DIR__ above so adding here
		if (!is_dir(self::$userConfigDir)) {
			mkdir(self::$userConfigDir);
		}
		
		// check to see if the user config exists, if not create it
		if ($verbose) {
			Console::writeLine("configuring pattern lab...");
		}
		
		// make sure migrate doesn't happen by default
		$migrate        = false;
		$diffVersion    = false;
		$defaultOptions = array();
		$userOptions    = array();
		
		// double-check the default config file exists
		if (!file_exists(self::$plConfigPath)) {
			Console::writeError("the default options for Pattern Lab don't seem to exist at <path>".Console::getHumanReadablePath(self::$plConfigPath)."</path>. please check on the install location of pattern lab...");
		}
		
		// set the default config using the pattern lab config
		try {
			$defaultOptions = Yaml::parse(file_get_contents(self::$plConfigPath));
			self::$options  = array_merge(self::$options, $defaultOptions);
		} catch (ParseException $e) {
			Console::writeError("Config parse error in <path>".Console::getHumanReadablePath(self::$plConfigPath)."</path>: ".$e->getMessage());
		}
		
		// double-check the user's config exists. if not mark that we should migrate the default one
		if (file_exists(self::$userConfigPath)) {
			try {
				$userOptions   = Yaml::parse(file_get_contents(self::$userConfigPath));
				self::$options = array_merge(self::$options, $userOptions);
			} catch (ParseException $e) {
				Console::writeError("Config parse error in <path>".Console::getHumanReadablePath(self::$userConfigPath)."</path>: ".$e->getMessage());
			}
		} else {
			$migrate = true;
		}
		
		// compare version numbers
		$diffVersion = (isset($userOptions["v"]) && ($userOptions["v"] == $defaultOptions["v"])) ? false : true;
		
		// run an upgrade and migrations if necessary
		if ($migrate || $diffVersion) {
			if ($verbose) {
				Console::writeInfo("upgrading your version of pattern lab...");
			}
			if ($migrate) {
				if (!@copy(self::$plConfigPath, self::$userConfigPath)) {
					Console::writeError("make sure that Pattern Lab can write a new config to ".self::$userConfigPath."...");
					exit;
				}
			} else {
				self::$options = self::writeNewConfigFile(self::$options, $defaultOptions);
			}
		}
		
		// making sure the config isn't empty
		if (empty(self::$options) && $verbose) {
			Console::writeError("a set of configuration options is required to use Pattern Lab...");
			exit;
		}
		
		// set-up the various dirs
		self::$options["configDir"]        = self::$userConfigDir;
		self::$options["configPath"]       = self::$userConfigPath;
		self::$options["coreDir"]          = is_dir(self::$options["baseDir"]."_core") ? self::$options["baseDir"]."_core" : self::$options["baseDir"]."core";
		self::$options["exportDir"]        = isset(self::$options["exportDir"])        ? self::$options["baseDir"].self::cleanDir(self::$options["exportDir"])   : self::$options["baseDir"]."exports";
		self::$options["publicDir"]        = isset(self::$options["publicDir"])        ? self::$options["baseDir"].self::cleanDir(self::$options["publicDir"])   : self::$options["baseDir"]."public";
		self::$options["scriptsDir"]       = isset(self::$options["scriptsDir"])       ? self::$options["baseDir"].self::cleanDir(self::$options["scriptsDir"])  : self::$options["baseDir"]."scripts";
		self::$options["sourceDir"]        = isset(self::$options["sourceDir"])        ? self::$options["baseDir"].self::cleanDir(self::$options["sourceDir"])   : self::$options["baseDir"]."source";
		self::$options["componentDir"]     = isset(self::$options["componentDir"])     ? self::$options["publicDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["componentDir"]) : self::$options["publicDir"].DIRECTORY_SEPARATOR."patternlab-components";
		self::$options["dataDir"]          = isset(self::$options["dataDir"])          ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["dataDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_data";
		self::$options["patternExportDir"] = isset(self::$options["patternExportDir"]) ? self::$options["exportDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["patternExportDir"]) : self::$options["exportDir"].DIRECTORY_SEPARATOR."patterns";
		self::$options["patternPublicDir"] = isset(self::$options["patternPublicDir"]) ? self::$options["publicDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["patternPublicDir"]) : self::$options["publicDir"].DIRECTORY_SEPARATOR."patterns";
		self::$options["patternSourceDir"] = isset(self::$options["patternSourceDir"]) ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["patternSourceDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_patterns";
		self::$options["metaDir"]          = isset(self::$options["metaDir"])          ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["metaDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_meta/";
		self::$options["annotationsDir"]   = isset(self::$options["annotationsDir"])   ? self::$options["sourceDir"].DIRECTORY_SEPARATOR.self::cleanDir(self::$options["annotationsDir"]) : self::$options["sourceDir"].DIRECTORY_SEPARATOR."_annotations/";
		
		// set-up outputFileSuffixes
		self::$options["outputFileSuffixes"]["rendered"]    = isset(self::$options["outputFileSuffixes"]["rendered"])    ? self::$options["outputFileSuffixes"]["rendered"]    : '';
		self::$options["outputFileSuffixes"]["rawTemplate"] = isset(self::$options["outputFileSuffixes"]["rawTemplate"]) ? self::$options["outputFileSuffixes"]["rawTemplate"] : '';
		self::$options["outputFileSuffixes"]["markupOnly"]  = isset(self::$options["outputFileSuffixes"]["markupOnly"])  ? self::$options["outputFileSuffixes"]["markupOnly"]  : '.markup-only';
		
		// handle a pre-2.1.0 styleguideKitPath before saving it
		if (isset(self::$options["styleguideKitPath"])) {
			self::$options["styleguideKitPath"] = self::$options["baseDir"].self::cleanDir(self::getStyleguideKitPath(self::$options["styleguideKitPath"]));
		}
		
		// double-check a few directories are real and set-up
		FileUtil::checkPathFromConfig(self::$options["sourceDir"], self::$userConfigPath, "sourceDir");
		FileUtil::checkPathFromConfig(self::$options["publicDir"], self::$userConfigPath, "publicDir");
		
		// make sure styleguideExcludes is set to an array even if it's empty
		if (is_string(self::$options["styleGuideExcludes"])) {
			self::$options["styleGuideExcludes"] = array();
		}
		
		// set the cacheBuster
		self::$options["cacheBuster"] = (self::$options["cacheBusterOn"] == "false") ? 0 : time();
		
		// provide the default for enable CSS. performance hog so it should be run infrequently
		self::$options["enableCSS"] = false;
		
		// which of these should be exposed in the front-end?
		self::$options["exposedOptions"] = array();
		self::setExposedOption("cacheBuster");
		self::setExposedOption("defaultPattern");
		self::setExposedOption("defaultShowPatternInfo");
		self::setExposedOption("patternExtension");
		self::setExposedOption("ishFontSize");
		self::setExposedOption("ishMaximum");
		self::setExposedOption("ishMinimum");
		self::setExposedOption("ishViewportRange");
		self::setExposedOption("outputFileSuffixes");
		self::setExposedOption("patternStates");
		self::setExposedOption("theme");
		self::setExposedOption("plugins");
		
	}
220275
public function actionIndex(array $sourceDirs, $targetDir)
    {
        $renderer = $this->findRenderer($this->template);
        $targetDir = $this->normalizeTargetDir($targetDir);
        if ($targetDir === false || $renderer === false) {
            return 1;
        }

        $renderer->apiUrl = './';
        $renderer->guidePrefix = $this->guidePrefix;

        if ($this->pageTitle !== null) {
            $renderer->pageTitle = $this->pageTitle;
        }

        // setup reference to guide
        if ($this->guide !== null) {
            $renderer->guideUrl = $guideUrl = $this->guide;
        } else {
            $guideUrl = './';
            $renderer->guideUrl = $targetDir;
            if (file_exists($renderer->generateGuideUrl('README.md'))) {
                $renderer->guideUrl = $guideUrl;
            } else {
                $renderer->guideUrl = null;
            }
        }

        // search for files to process
        if (($files = $this->searchFiles($sourceDirs)) === false) {
            return 1;
        }

        // load context from cache
        $context = $this->loadContext($targetDir);
        $this->stdout('Checking for updated files... ');
        foreach ($context->files as $file => $sha) {
            if (!file_exists($file)) {
                $this->stdout('At least one file has been removed. Rebuilding the context...');
                $context = new Context();
                if (($files = $this->searchFiles($sourceDirs)) === false) {
                    return 1;
                }
                break;
            }
            if (sha1_file($file) === $sha) {
                unset($files[$file]);
            }
        }
        $this->stdout('done.' . PHP_EOL, Console::FG_GREEN);

        // process files
        $fileCount = count($files);
        $this->stdout($fileCount . ' file' . ($fileCount == 1 ? '' : 's') . ' to update.' . PHP_EOL);
        Console::startProgress(0, $fileCount, 'Processing files... ', false);
        $done = 0;
        foreach ($files as $file) {
            $context->addFile($file);
            Console::updateProgress(++$done, $fileCount);
        }
        Console::endProgress(true);
        $this->stdout('done.' . PHP_EOL, Console::FG_GREEN);

        // save processed data to cache
        $this->storeContext($context, $targetDir);

        $this->updateContext($context);

        // render models
        $renderer->controller = $this;
        $renderer->render($context, $targetDir);

        if (!empty($context->errors)) {
            ArrayHelper::multisort($context->errors, 'file');
            file_put_contents($targetDir . '/errors.txt', print_r($context->errors, true));
            $this->stdout(count($context->errors) . " errors have been logged to $targetDir/errors.txt\n", Console::FG_RED, Console::BOLD);
        }

        if (!empty($context->warnings)) {
            ArrayHelper::multisort($context->warnings, 'file');
            file_put_contents($targetDir . '/warnings.txt', print_r($context->warnings, true));
            $this->stdout(count($context->warnings) . " warnings have been logged to $targetDir/warnings.txt\n", Console::FG_YELLOW, Console::BOLD);
        }

        return 0;
    }
937757
public function setBasedir($dir)
    {
        if ($dir instanceof PhingFile) {
            $dir = $dir->getAbsolutePath();
        }

        $dir = $this->fileUtils->normalize($dir);
        $dir = FileSystem::getFileSystem()->canonicalize($dir);

        $dir = new PhingFile((string) $dir);
        if (!$dir->exists()) {
            throw new BuildException("Basedir " . $dir->getAbsolutePath() . " does not exist");
        }
        if (!$dir->isDirectory()) {
            throw new BuildException("Basedir " . $dir->getAbsolutePath() . " is not a directory");
        }
        $this->basedir = $dir;
        $this->setPropertyInternal("project.basedir", $this->basedir->getAbsolutePath());
        $this->log("Project base dir set to: " . $this->basedir->getPath(), Project::MSG_VERBOSE);

        // [HL] added this so that ./ files resolve correctly.  This may be a mistake ... or may be in wrong place.
        chdir($dir->getAbsolutePath());
    }
528561
public static FilesIterator<File> getAbsoluteIterator(String baseDir) {
		return new FilesIterator<File>(new File(baseDir), Strategy.FILES);
	}
1171825
public function getImages($dir, $basedir)
    {
        $data = array();
        $dir = $basedir . $dir;
        $files = ftp_rawlist($this->link, $dir);
        foreach ($files as $v) {
            $file = ltrim(strrchr($v, ' '), ' ');
            $path = "{$dir}/{$file}";
            if (preg_match('/^-/', $v)) {
                if (preg_match('/^[a-zA-z0-9]+\.(gif|png|jpg|jpeg)$/', $file)) { //遍历目录设置
                    array_push($data, array(str_replace($basedir, '', $path), ftp_size($this->link, $path)));
                }
            }
        }
        return $data;
    }
710540
public static DirectoryRosterStore init(final File baseDir) {
        DirectoryRosterStore store = new DirectoryRosterStore(baseDir);
        if (store.setRosterVersion("")) {
            return store;
        }
        else {
            return null;
        }
    }
814553
public function getImages($dir, $basedir)
    {
        $files = array();
        $dir = $basedir . $dir;
        if ($handler = opendir($dir)) {
            while ($file = readdir($handler)) {
                $path = realpath("{$dir}/{$file}");
                if (is_file($path)) {
                    if (preg_match('/^[a-zA-z0-9=&,]+\.(gif|png|jpg|jpeg)$/', $file)) {
                        array_push($files, array(str_replace(array($basedir, '\\'), array('', '/'), $path),filesize($path)));
                    }
                }
            }
            closedir($handler);
        }
        
        return $files;
    }
1015370
private function _searchInControllerDir($base_dir, $file_name)
    {
        $dirs = $this->application->getControllerDirectories();
        foreach ($dirs as $dir) {
            $filter = $this->finder->path($dir . $base_dir)->name($file_name)->find()->first();
            if ($filter) return $filter;
        }
    }
362921
public function loadConfigDefinition($configId, $baseDir)
    {
        if (false === $this->container->hasDefinition($configId)) {
            $this->container->setDefinition($configId, $this->buildConfigDefinition($baseDir));
        }
    }