****************************************
查找并解析文件
****************************************
5374
function any(...args) {

    // 遍历文件
    for (let file of args) {
        try {
            return require(path.cwd(file));
        } catch (err) {
            // do nothing;
        }
    }
}
1289022
private static void validateFiles(File zipFile, File... srcFiles) throws UtilException {
		if(zipFile.isDirectory()) {
			throw new UtilException("Zip file [{}] must not be a directory !", zipFile.getAbsoluteFile());
		}
		
		for (File srcFile : srcFiles) {
			if(null == srcFile) {
				continue;
			}
			if (false == srcFile.exists()) {
				throw new UtilException(StrUtil.format("File [{}] not exist!", srcFile.getAbsolutePath()));
			}

			try {
				final File parentFile = zipFile.getCanonicalFile().getParentFile();
				// 压缩文件不能位于被压缩的目录内
				if (srcFile.isDirectory() && parentFile.getCanonicalPath().contains(srcFile.getCanonicalPath())) {
					throw new UtilException("Zip file path [{}] must not be the child directory of [{}] !", zipFile.getCanonicalPath(), srcFile.getCanonicalPath());
				}

			} catch (IOException e) {
				throw new UtilException(e);
			}
		}
	}
45592
function parsePackScript(file, context, opts) {
    var content = file.getContent();
    var packScriptFiles = [];

    var hasScriptPlaceholder
        = content.indexOf(opts.scriptPlaceholder) !== -1;
    var hasScriptAsyncPlaceholder
        = content.indexOf(opts.scriptAsyncPlaceholder) !== -1;
    var hasRequireConfigPlaceholder
        = content.indexOf(opts.resourceConfigPlaceholder) !== -1;

    var getPlaceholder = function (isLoader) {
        if (!opts.autoInsertPlaceholder) {
            return;
        }
        // 在requirejs之后 requrie.config 脚本
        if (isLoader && !hasRequireConfigPlaceholder) {
            hasRequireConfigPlaceholder = true;
            return opts.resourceConfigPlaceholder;
        }
        //在异步入口模块前插入合成后的pkg
        else if (!hasScriptAsyncPlaceholder) {
            hasScriptAsyncPlaceholder = true;
            return opts.scriptAsyncPlaceholder;
        }
    };
    /*
    //在body之前插入scriptPlaceholder
    if(!hasScriptPlaceholder){
        hasScriptPlaceholder = true;
        var rBody = /<!--([\s\S]*?)(?:-->|$)|<\/body>/ig;
         content = content.replace(rBody, function(all, comment) {
          if (comment) {
            return all;
          } else {
            return '\n' + opts.scriptPlaceholder + '\n' + all;
          }
        });
    }*/


    content = _.parseHtmlScript(content, function (found) {
        var placeholder;
        var match = found.match;

        if (found.isScriptLink) {
            var src = found.src;
            var scriptFile = context.getFileByUrl(src, file);
            var loaderName = scriptFile
                ? scriptFile.basename
                : _.ext(src).basename;

            if (found.isLoader
                || opts.loaderScripts.indexOf(loaderName) !== -1
            ) {
                placeholder = getPlaceholder(true);
                if (placeholder) {
                    return match + placeholder+'\n';
                }
            }
            else if (scriptFile && opts.packJs) {
                packScriptFiles.push({
                    file: scriptFile,
                    raw: match,
                    attrs: found.attrs
                });
            }
        }
        else if (found.isInlineScript) {
            // 对于内联脚本，如果指定了异步入口模块或者包含异步 require，则在前面插入脚本占位符
            if (found.isEntryScript
                || _.extractAsyncModuleIds(found.inlineContent).length) {
                placeholder = getPlaceholder();
                if (placeholder) {
                    return placeholder+'\n' + match;
                }
            }
        }

        return match;
    });

    if (packScriptFiles.length
        && !hasScriptPlaceholder
        && opts.autoInsertPlaceholder
    ) {
        var lastScript = packScriptFiles[packScriptFiles.length - 1].raw;
        content = content.replace(lastScript, lastScript + opts.scriptPlaceholder);
    }

    file.setContent(content);
    file._initScriptPlacedholder = true;

    return packScriptFiles;
}
41304
public function resolveFileMenu()
    {
        $file_index = [];
        $files = $this->files;
        foreach ($files as $key => $file) {
            // 单页文件不做索引
            if (in_array($file['page_uuid'], $this->single_pages)) {
                continue;
            }
            // 标题索引处理
            $content = $this->fileSys->getContent($file['file_path']);
            $token = array_filter(explode("\n", $content['content']), function ($d){
                if (empty($d)) {
                    return false;
                }
                if (strpos($d, "\n#") === false && strpos($d, '#') !== 0 ) {
                    return false;
                }
                return true;
            });
            if (count($token)>0) {
                foreach ($token as &$value) {
                    $value = preg_replace_callback("|(#{1,6} )|", function($m){
                                return '';
                            }, $value);
                    $value = [
                        'title' => $value,
                        'href'  => '#'.$value,
                    ];
                }
            }
            $index = [
                'title' => $file['title'],
                'href'  => $file['href'],
                'uuid'  => $file['page_uuid'],
                'child' => $token
            ];
            $file_index[$file['page_uuid']] = $index;
        }
        $this->file_index = $file_index;
        // dd($file_index);
    }
1146185
function () {

        var that = this;
        var base = this.base;
        var $ = this.$;
        var files = [];


        $('link[rel=stylesheet]').each(function () {

            var $this = $(this);
            var cssFile;
            var href = $this.attr('href');

            cssFile = utils.resolve(base, href);
            cssFile = getUrl(cssFile);

            // 注意：为空也得放进去，保持与 link 标签一一对应
            files.push(cssFile);
        });


        // 转换 file 地址
        // 执行顺序：ignore > map > normalize
        function getUrl (file) {

            if (!that.ignore(file)) {
                file = that.map(file);
                file = utils.normalize(file);
                return file;
            }
        }


        if (this.options.debug) {
            console.log('');
            console.log('[DEBUG]', 'HtmlParser#getCssFiles', this.file);
            console.log(files);
        }


        return files;
    }
1146428
function removeFormpart(TPL,ctx)
{
    let files = ctx.files;
    for(let f in files) {
        fs.unlink(files[f].path, (err)=> {
            err && TPL.params[f] && console.error('删除文件失败', files[f])
        });//异步清除临时目录中的上传文件
    }
}
251272
function execute(&$content, $from_url, $min_file_size = 0)
    {
        preg_match_all('~<img[^>]*(?<!_mce_)\s+src\s?=\s?([\'"])((?:(?!\1).)*?)\1[^>]*>~i', $content, $match);
        if (empty($match[2]))
        {
            return 0;
        }

        $image_n = 0;
        $replaced = array();
        $this->referrer_url = $from_url;

        foreach ($match[2] as $uri)
        {
            //已经替换过的
            if (isset($replaced[$uri]))
            {
                continue;
            }
            if(!(strpos($uri,"data:image") === false))
            {
                return false;
            }
            if ($this->beforeUrlGet)
            {
                $replaced_uri = call_user_func($this->beforeUrlGet, $this, $uri);
            }
            else
            {
                $replaced_uri = $uri;
            }
            $_abs_uri = str_replace("%","",HTML::parseRelativePath($from_url, $replaced_uri));
            $info = parse_url($_abs_uri);
            $path = $info['host'].'/'.ltrim($info['path'], '/');
            $file =  $this->base_dir.'/'.$path;

            $update = true;
            if (!is_file($file))
            {
                $dir = dirname($file);
                if (!is_dir($dir))
                {
                    mkdir($dir, 0777, true);
                }
                $update = $this->downloadFile($_abs_uri, $file, $min_file_size);
                if ($this->afterUrlGet)
                {
                    call_user_func($this->afterUrlGet, $this, $_abs_uri);
                }
            }
            if ($update)
            {
                $new_uri = $this->base_url .'/'. ltrim($path, '/');
                $content = str_replace($uri, $new_uri, $content);
                $replaced[$uri] = true;
                $image_n ++;
            }
            else
            {
                return false;
            }
        }
        return $image_n;
    }
648153
private void scanFile(File file, String rootDir) {
		if (file.isFile()) {
			final String fileName = file.getAbsolutePath();
			if (fileName.endsWith(FileUtil.CLASS_EXT)) {
				final String className = fileName//
						// 8为classes长度，fileName.length() - 6为".class"的长度
						.substring(rootDir.length(), fileName.length() - 6)//
						.replace(File.separatorChar, CharUtil.DOT);//
				//加入满足条件的类
				addIfAccept(className);
			} else if (fileName.endsWith(FileUtil.JAR_FILE_EXT)) {
				try {
					scanJar(new JarFile(file));
				} catch (IOException e) {
					throw new IORuntimeException(e);
				}
			}
		} else if (file.isDirectory()) {
			for (File subFile : file.listFiles()) {
				scanFile(subFile, (null == rootDir) ? subPathBeforePackage(file) : rootDir);
			}
		}
	}
835648
function copy(src, dist, options = {}, callback = null) {
    let deferred = Promise.all([stat(src), stat(dist)]);

    // 处理参数
    if (typeof options === 'function') {
        callback = options;
        options = {};
    }

    // 异步处理
    deferred.then(async stats => {

        // 判断源文件是否存在
        if (!stats[0]) {
            return callback(new Error(`Error: '${src}' is not exists!`));
        }

        // 判断目标文件是否存在
        if (stats[1]) {
            return callback(new Error(`Error: '${dist}' is exists!`));
        }

        // 复制文件夹
        try {
            if (stats[0].isDirectory()) {
                let files = await proxy.readdir(src);

                // 创建目标文件夹
                await proxy.mkdir(dist);

                // 拷贝下级文件
                await Promise.all(files.map(file => {
                    let dir = path.join(src, file);

                    // 处理排队文件
                    if (options.exclude && options.exclude.test(dir)) {
                        return Promise.resolve();
                    }

                    // 复制文件
                    return proxy.copy(dir, path.join(dist, file), options);
                }));

            } else {
                await proxy.copyFile(src, dist);
            }
        } catch (err) {
            return callback(err);
        }

        // 执行回调
        callback();
    });
}
1171058
static String parseAttachmentFilename(Header header) throws UnsupportedEncodingException {
    if (header == null) {
      return null;
    }
    String value = header.getValue();
    String filenameWild = "filename*";
    int filenameWildIndex = value.indexOf(filenameWild);
    if (filenameWildIndex != -1) {
      int lastIndex = value.indexOf(';', filenameWildIndex);
      String substring;
      if (lastIndex == -1) {
        substring = value.substring(filenameWildIndex + filenameWild.length() + 1);
      } else {
        substring = value.substring(filenameWildIndex + filenameWild.length() + 1, lastIndex);
      }
      String[] ary = substring.split("''");
      return URLDecoder.decode(ary[1], ary[0]);
    }
    String filename = "filename";
    int filenameIndex = value.indexOf(filename);
    if (filenameIndex != -1) {
      int lastIndex = value.indexOf(';', filenameIndex);
      String substring;
      // 处理filename=文件名，不包含双引号的情况
      int offset = 2;
      if (value.substring(filenameIndex + filename.length() + 1).charAt(0) != '\"') {
        offset = 1;
      }
      if (lastIndex == -1) {
        substring = value.substring(filenameIndex + filename.length() + offset);
      } else {
        substring = value
            .substring(filenameIndex + filename.length() + offset, offset == 2 ? lastIndex - 1 : lastIndex);
      }
      return URLDecoder.decode(substring, "UTF-8");
    }
    throw new IllegalStateException("不合法的附件头信息" + header.getName() + ": " + header.getValue());
  }
1234983
function createDataJSON(pathArr) {
  return new Promise((resolve, reject) => {
    try {
      const commandData = {};
      const indexes = [];
      pathArr.forEach((mdPath, i) => {
        const json = {}
        const con = FS.readFileSync(mdPath);
        const str = con.toString();
        let title = str.match(/[^===]+(?=[===])/g);
        title = title[0] ? title[0].replace(/\n/g, '') : title[0];
        title = title.replace(/\r/, '')
        // 命令名称
        json["n"] = title;
        // 命令路径
        json["p"] = `/${path.basename(mdPath, '.md').replace(/\\/g, '/')}`;
        // 命令描述
        let des = str.match(/\n==={1,}([\s\S]*?)##/i);
        if (!des) {
          throw `格式错误: ${mdPath}`;
        }
        des = des[1] ? des[1].replace(/\n/g, '') : des[1];
        des = des.replace(/\r/g, '')
        json["d"] = des;
        indexes.push(json);
        commandData[title] = json;
      })
      resolve({
        json: commandData,
        data: indexes
      });
    } catch (err) {
      reject(err);
    }
  });
}
968111
async function copy(src, dist, options = {}) {
    let [from, to] = await Promise.all([stat(src), stat(dist)]);

    // 判断源文件是否存在
    if (!from) {
        throw new Error(`Error: '${src}' is not exists!`);
    }

    // 判断目标文件是否存在
    if (to) {
        throw new Error(`Error: '${dist}' is exists!`);
    }

    // 复制文件
    if (from.isDirectory()) {
        let files = await readdir(src);

        // 创建目标文件夹
        await mkdir(dist);

        // 拷贝下级文件
        await Promise.all(files.map(file => {
            let dir = path.join(src, file);

            // 处理排队文件
            if (options.exclude && options.exclude.test(dir)) {
                return Promise.resolve();
            }

            // 复制文件
            return copy(dir, path.join(dist, file), options);
        }));
    } else {
        await copyFile(src, dist);
    }
}
1066202
function updateConfigFiles (filePath, keep) {
  debug(`file path: ${filePath}`)

  if (typeof filePath !== 'string' || !fs.existsSync(filePath)) {
    debug(`file not exists: ${filePath}`)
    return
  }

  const baseDir = getBaseDir()
  const fileParsedObj = path.parse(filePath)
  const fileName = `${fileParsedObj.name}${fileParsedObj.ext}`
  const destFilePath = path.join(baseDir, fileName)
  const oldFilePath = path.join(
    baseDir,
    `${fileParsedObj.name}.old${fileParsedObj.ext}`
  )

  debug(`file dest path: ${destFilePath}`)

  // 获取输出时使用的相对路径
  const getRelativePath = p => {
    if (p.startsWith(baseDir)) {
      return path.relative(baseDir, p)
    }

    return p
  }

  // 旧文件存在，rename
  if (keep === true && fs.existsSync(destFilePath)) {
    if (isSameFile(filePath, destFilePath)) {
      debug('file exists, file same, ignore')
      console.log(`  "${getRelativePath(destFilePath)}" is up to date`)
      return
    }

    debug('file exists, file different, move.')
    debug(`file old name: ${oldFilePath}`)
    fs.moveSync(destFilePath, oldFilePath, { overwrite: true })
    console.log(`  move: from "${getRelativePath(destFilePath)}"`)
    console.log(`          to "${getRelativePath(oldFilePath)}"`)
  }

  fs.copySync(filePath, destFilePath)
  console.log(`  copy: from "${getRelativePath(filePath)}"`)
  console.log(`          to "${getRelativePath(destFilePath)}"`)
}
1133164
function copyFile(src, dist) {
    return new Promise((resolve, reject) => {
        let rs = fs.createReadStream(path.cwd(src)),
            ws = fs.createWriteStream(path.cwd(dist));

        // 监听事件
        rs.on('error', reject);
        ws.on('error', reject);
        ws.on('close', resolve);

        // 传输文件
        rs.pipe(ws);
    });
}
446412
function unzip(src, dist) {
    if (isString(src)) {

        // 获取输出目录
        if (arguments.length === 1) {
            dist = src.replace(/\.zip$/, '');
        }

        // 校验参数
        if (isString(dist)) {
            return new Promise((resolve, reject) => {
                let archive = fs.createReadStream(src),
                    output = unarchiver.Extract({ path: dist });

                // 监听回调
                archive.on('error', reject);
                output.on('error', reject);
                output.on('close', resolve);

                // 设置管道输出
                archive.pipe(output);
            });
        }
    }
}
122912
function copyTpl(options) {
  options.data = options.data || {};
  options.stringReplace = options.stringReplace || [];
  options.encoding = options.encoding || 'utf-8';

  if (!fs.existsSync(options.src)) {
    log.error(`${options.src} 文件不存在`);
    return;
  }

  if (fs.statSync(options.src).isDirectory()) {
    fs.mkdirsSync(options.dist);
    log.success(`${options.dist} written successfully`);
    return;
  }

  // 数据模板转换
  let content = fs.readFileSync(options.src, { encoding: options.encoding });
  try {
    content = _.template(content)(options.data);
  } catch (err) {
    log.error(`${options.src} template fail, Please check the template and the data is correct`);
  }
  for (let j = 0; j < options.stringReplace.length; j += 1) {
    content = content.replace(
      new RegExp(options.stringReplace[j].placeholder, 'g'),
      options.stringReplace[j].value
    );
  }

  // 若没有目录文件需要创建,最终创建文件
  fs.mkdirsSync(path.dirname(options.dist));
  fs.writeFileSync(options.dist, content);
  log.success(`${options.dist} written successfully`);
}
170205
function executeFile(src, { context, babelOptions } = {}) {
    let filename = resolvePath(context)(src);

    // 不存在文件
    if (!filename) {
        throw new Error(`Error: ENOENT: no such file, open '${src}'`);
    }

    // 解析【json】
    if (filename.endsWith('.json')) {
        return require(filename);
    }

    // 解析对象
    return execute(
        fs.readFileSync(filename, 'utf-8'), { filename, babelOptions }
    );
}