<pre>
判断规则：
1. 源文件的最后修改时间比目标文件的最后修改时间新
2. 源文件和目标文件大小不一致
</pre>
489992
private boolean accept(FileData target, FileData source) {
        return (target.getLastModifiedTime() < source.getLastModifiedTime()) || (target.getSize() != source.getSize());
    }
1084917
function (file) {


        // 模板字符串
        var source = '';

        var readError = null;
        var compileError = null;
        var writeError = null;

        // 目标路径
        var target = file
        .replace(path.extname(file), '.js')
        .replace(this.base, this.output);

        var mod = this._getCache(file);
        var modObject = {};
        var metadata = {};
        var count = 0;

        var isDebug = this.options.debug;
        var isCacheDir = this.options.combo;


        try {
            source = fs.readFileSync(file, this.options.charset);
        } catch (e) {
            readError = e;
        }


        var newMd5 = this._getMd5(source + JSON.stringify(this['gcomp-config.json']));

        // 如果开启了合并，编译后的文件使用缓存目录保存
        if (isCacheDir) {
            target = target.replace(this.output, path.join(this.output, CACHE_DIR));
        }


        // 尝试从文件中读取上一次编译的结果
        if (!mod && fs.existsSync(target)) {
            mod = this._fsRead(target, this.options.charset);
        }


        // 获取缓存的元数据
        if (mod) {
            metadata = this._getMetadata(mod) || {};
            count = metadata.version || 0;
        }


        // 检查是否需要编译
        var modified = !this.options.cache
        || !mod                         // 从来没有编译过
        || metadata.debug               // 上个版本为调试版
        || isDebug                      // 当前配置为调试版
        || newMd5 !== metadata.md5;     // 模板已经发生了修改（包括配置文件）


        // 获取模板 ID
        var id = this._toId(file);


        // 广播：模板加载事件
        this.emit('load', readError, {

            // 模板 ID
            id: id,

            // 模板是否需要重新编译
            modified: modified,

            // 原始文件路径
            sourceFile: file,

            // 模板源代码
            source: source,

            // 输出路径
            outputFile: target

        });


        if (readError) {
            return;
        }


        try {

            // 编译模板
            if (modified) {
                modObject = this.template.AOTcompile(source, {
                    filename: id,
                    alias: this.options.alias,
                    type: this.options.type,
                    compress: this.options.compress,
                    escape: this.options.escape,
                    runtime: this.options.runtime,
                    debug: isDebug
                });
                mod = modObject.code;
            }

        } catch (e) {
           compileError = e;
        }


        // 不输出的情况：遇到错误 || 文件或配置没有更新
        if (!compileError && modified) {

            count ++;

            mod = this._setMetadata(mod, {
                debug: isDebug,
                version: count,
                md5: newMd5
            });

            if (this.options.output !== false) {
                try {
                    this._fsMkdir(path.dirname(target));//////
                    fs.writeFileSync(target, mod, this.options.charset);
                } catch (e) {
                    writeError = e;
                }


                if (!isCacheDir && !writeError) {
                    if (isDebug) {
                        this._beautify(target);
                    }

                    if (!isDebug && this.options.minify) {
                        this._minify(target);
                    }
                }
            }

        }


        var compileInfo = {

            // 模板 ID
            id: id,

            // 版本
            version: count,

            // 源码
            source: source,

            // 模板文件路径
            sourceFile: file,

            // 编译结果代码
            output: mod,

            // 编译输出文件路径
            outputFile: target,

            // 是否被修改
            modified: modified,

            // 依赖的子模板 ID 列表
            requires: modObject.requires || []
        };


        if (compileError && !compileError.source) {

            // 语法错误，目前只能对比生成后的 js 来查找错误的模板语法

            compileError.debugFile = path.join(this.base, DEBUG_File);

            this.debuging = true;

            this._debug(compileError, function (message) {

                var e = {

                    // 错误名称
                    name: compileError.name,

                    // 报错信息
                    message: message,

                    // 调试文件地址
                    debugFile: compileError.debugFile,

                    // 编译器输出的临时文件
                    temp: compileError.temp

                };

                for (var name in e) {
                    compileError[name] = e[name];
                }

                this.emit('debug', compileError);

            }.bind(this));


        } else {

            // 删除上次遗留的调试文件
            if (this.debuging) {
                this._fsUnlink(path.join(this.base, DEBUG_File));
                delete this.debuging;
            }

            // 缓存编译好的模板
            this._setCache(file, mod);
        }


        this.emit('compile', compileError || writeError, compileInfo);


        if (compileError || writeError) {
            this.emit('debug', compileError || writeError);
            return null;
        } else {
            return compileInfo;
        }
    }
1272453
function getBaesVsersion(dir, callBack) {
        fs.readdir(`${dir}/`, (err, files) => {
            let dirList = [],
                baseVersion;
            if (err) {
                console.log('第一次部署中...');
                fs.mkdir(dir, () => {
                    callBack([1, 1, 1]);
                });
            } else {
                if (files.length == 0) {
                    files = ['1.1.1'];
                }
                console.log('部署目标已存在，正在更新中...');
                files.forEach((v)=> {
                    let intV = v.replace(/\./g, '');
                    if (!!parseInt(intV)) {
                        dirList.push(intV);
                    }
                });
                baseVersion = Math.max.apply(null, dirList).toString().split('');
                callBack(baseVersion);
            }
        });
    }
482333
private static void analyzeCorpus(String zipFile, String output, final String separator, final boolean includePhrase) throws IOException{
        File outputFile = new File(output);
        //准备输出目录
        if(!outputFile.getParentFile().exists()){
            outputFile.getParentFile().mkdirs();
        }
        try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), ExtractText.class.getClassLoader());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile),"utf-8"));) {
            for(Path path : fs.getRootDirectories()){                
                LOGGER.info("处理目录："+path);
                Files.walkFileTree(path, new SimpleFileVisitor<Path>(){

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        LOGGER.info("处理文件："+file);
                        // 拷贝到本地文件系统
                        Path temp = Paths.get("target/corpus-"+System.currentTimeMillis()+".txt");
                        Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                        extractText(temp, writer, separator, includePhrase);
                        return FileVisitResult.CONTINUE;
                    }
                    
                });
            }
        }
    }
1308052
def _RealGetContents(self):
        """"""
        fp = self.fp
        try:
            endrec = _EndRecData(fp)
        except OSError:
            raise BadZipFile("File is not a zip file")
        if not endrec:
            raise BadZipFile("File is not a zip file")
        if self.debug > 1:
            print(endrec)
        size_cd = endrec[_ECD_SIZE]             # bytes in central directory
        offset_cd = endrec[_ECD_OFFSET]         # offset of central directory
        self._comment = endrec[_ECD_COMMENT]    # archive comment

        # ---> APK文件只有一个，不可能存在额外数据。
        # "concat" is zero, unless zip was concatenated to another file
        # concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
        # if endrec[_ECD_SIGNATURE] == stringEndArchive64:
        #     # If Zip64 extension structures are present, account for them
        #     concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
        concat = 0

        if self.debug > 2:
            inferred = concat + offset_cd
            print("given, inferred, offset", offset_cd, inferred, concat)
        # self.start_dir:  Position of start of central directory
        self.start_dir = offset_cd + concat
        fp.seek(self.start_dir, 0)
        data = fp.read(size_cd)
        fp = io.BytesIO(data)
        total = 0
        while total < size_cd:
            centdir = fp.read(sizeCentralDir)
            if len(centdir) != sizeCentralDir:
                raise BadZipFile("Truncated central directory")
            centdir = struct.unpack(structCentralDir, centdir)
            if centdir[_CD_SIGNATURE] != stringCentralDir:
                raise BadZipFile("Bad magic number for central directory")
            if self.debug > 2:
                print(centdir)
            filename = fp.read(centdir[_CD_FILENAME_LENGTH])
            flags = centdir[5]
            if flags & 0x800:
                # UTF-8 file names extension
                filename = filename.decode('utf-8')
            else:
                # Historical ZIP filename encoding
                filename = filename.decode('cp437')
            # Create ZipInfo instance to store file information
            x = ZipInfo(filename)
            x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
            x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
            x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
            (x.create_version, x.create_system, x.extract_version, x.reserved,
             x.flag_bits, x.compress_type, t, d,
             x.CRC, x.compress_size, x.file_size) = centdir[1:12]
            if x.extract_version > MAX_EXTRACT_VERSION:
                raise NotImplementedError("zip file version %.1f" %
                                          (x.extract_version / 10))
            x.volume, x.internal_attr, x.external_attr = centdir[15:18]
            # Convert date/time code to (year, month, day, hour, min, sec)
            x._raw_time = t
            x.date_time = ((d >> 9) + 1980, (d >> 5) & 0xF, d & 0x1F,
                           t >> 11, (t >> 5) & 0x3F, (t & 0x1F) * 2)

            x._decodeExtra()
            # x.header_offset = x.header_offset + concat
            self.filelist.append(x)
            self.NameToInfo[x.filename] = x

            # update total bytes read from central directory
            total = total + sizeCentralDir + \
                centdir[_CD_FILENAME_LENGTH] + \
                centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]
1133829
function(url, filepath, fn){
        // 提交请求
        try{
            fs.createReadStream(filepath).pipe(request.post(url, fn))
        }
        catch(e){ fn(e) }
    }
1125687
function copyExamp(path,pathLength){
	fs.readdir(path,function(err, files){
		if(err){
			console.log('examples read dir err:' + path);
		}else{
			// 遍历目录下所有子项
			files.forEach(function(item){
				var tmpPath = path + '/' + item;
				fs.stat(tmpPath,function(err, stat){
					if(stat.isFile()){
						// 判断文件类型,如果是.html则转化
						var htmlIndex = item.indexOf('.html');
						var jsIndex = item.indexOf('.js');
						var cssIndex = item.indexOf('.css');
						if(htmlIndex < 0 && (jsIndex > -1 || cssIndex > -1)){
							// 创建读取流
		                    readable = fs.createReadStream( tmpPath );
		                    // 创建写入流
		                    writable = fs.createWriteStream( 'examples/' + tmpPath.substring(pathLength) );
		                    // 通过管道来传输流
		                    readable.pipe(writable);
						}
						if(htmlIndex > -1){
							fs.readFile(tmpPath,function(err,data){
								var htmlStr = '';
								if(err){
									console.log('read html err:' + tmpPath)
								}else{
									htmlStr = data.toString();
								}
								var ctx = 'http://design.yonyoucloud.com/static/'
								var tpl = [
							        '<!DOCTYPE html>',
							        '<html lang="en">',
							        '<head>',
							        '<meta charset="UTF-8">',
							        '<meta name="viewport" content="width=device-width, initial-scale=1">',
							       	'<title>Title</title>',
									'<link rel="stylesheet" href="'+ ctx +'/font-awesome/css/font-awesome.css">',
							       	'<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/u.css">',
							       	'<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/u-extend.css">',
								    '<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/tree.css">',
							        '<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/grid.css">',
							        '<link rel="stylesheet" type="text/css" href="widget.css">',
							        '</head>',
							        '<body>',
							        htmlStr,
							        '<script src="'+ ctx +'/jquery/jquery-1.11.2.js"></script>',
							    	'<script src="'+ ctx +'/knockout/knockout-3.2.0.debug.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-polyfill.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-tree.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-grid.js"></script>',
									'<script src="'+ ctx +'/requirejs/require.debug.js"></script>',
									'<script src="widget.js"></script>',
							        '</body>',
							        '</html>'
						        ]
					        	var tplStr = tpl.join('\r\n');
					        	fs.writeFile('examples/' + tmpPath.substring(pathLength),tplStr,function(err){
						        	if(err){
						        		console.log('write err:' + 'examples/' + item + '.html');
						        	}
						        })
					        })
						}
					}
					// 子项为目录创建目录
					if(stat.isDirectory()){
						var dirPath = 'examples/' + tmpPath.substring(pathLength);
						fs.exists(dirPath, function(exist) {
							if(!exist){
								fs.mkdirSync(dirPath);
							}
						});
						copyExamp(tmpPath,pathLength);
					}
				})
			})
		}
	})
}
269206
function checkFileSize(opt) {    
    var stream = through.obj(function (file, enc, cb) {
        //有大小限制
        if(opt && opt.maxSize > 0) {
            var size = file.contents.length / 1024;//转为KB
            if(size > opt.maxSize) {
                gutil.log(gutil.colors.red('file size error:', '('+size.toFixed(2)+'KB)'+file.path));
                this.emit("error", new PluginError('file size error', '文件大于' + opt.maxSize + 'KB '));
            }
            
        }
        this.push(file);
        cb();
    });
    return stream;
}
908378
public static void transferFile(File src, File dest) throws Exception {

        // 删除文件
        // LOGGER.info("start to remove download file: " + ""
        // + dest.getAbsolutePath());
        if (dest.exists()) {
            dest.delete();
        }

        // 转移临时下载文件至下载文件夹
        FileUtils.copyFile(src, dest);
    }
909831
public byte[] getFileBytes(File file) throws IORuntimeException {
		byte[] bytes = cache.get(file);
		if (bytes != null) {
			return bytes;
		}

		// add file
		bytes = FileUtil.readBytes(file);

		if ((maxFileSize != 0) && (file.length() > maxFileSize)) {
			//大于缓存空间，不缓存，直接返回
			return bytes;
		}

		usedSize += bytes.length;

		//文件放入缓存，如果usedSize > capacity，purge()方法将被调用
		cache.put(file, bytes);

		return bytes;
	}
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();
    });
}
728240
function runFile(src, context) {

    // 格式作路径
    src = path.cwd(src);

    // 返回运行结果
    return runCode(fs.readFileSync(src, 'utf8'), {
        __dirname: path.dirname(src),
        __filename: src,
        ...context
    });
}
1014703
function makeRootDir(dest, cwd, savedir, callback) {
  let root = path.join(cwd, (savedir || ''), dest.split('/')[0]);
  console.log('delete: ', root)

  // 保存先フォルダがすでにある場合は一旦削除する
  let rm = 'if [ -e '+ root +' ]; then rm -rf ' + root + '; fi';
  let removed = exec(rm, (error, stdout, stderr) => {
    if (error !== null) throw ('[Error: makeRootDir:] ' + error);
  }).on('close', () => {
    // 削除後、保存先フォルダを作成
    let maked = exec('mkdir ' + root).on('close', () => {
      return callback && callback();
    });
  });
}
1353187
private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移动文件
        if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
            $arr = explode(yii::getAlias("@frontend/web"), $this->filePath);
            yii::$app->alioss->uploadFile($arr[1], $this->filePath);
            yii::$app->qiniu->uploadFile($arr[1], $this->filePath);
        }
    }
398156
function combineFileContent(pkg, toMergeFiles, context) {
    var content = '';
    var has = [];
    var isPackBundles = !! pkg.isPackBundles;
    toMergeFiles.forEach(function (file) {
        has.push(file.id);
        if(isPackBundles){
            if(file.packBundlesTo){
                fis.log.error('file [%s] has packBundlesTo[%s],can not packBundles more than once!',file.id,pkg.id);
                return;
            }
            file.packBundlesTo = pkg.subpath;
        }
        // 把要合并的文件的依赖信息添加到打包文件里
        addDependenceResource(pkg, 'addLink', file.links,context);
        addDependenceResource(pkg, 'addRequire', file.requires,context);
        addDependenceResource(pkg, 'addAsyncRequire', file.asyncs,context);

        var c;
        if(!isPackBundles && file.packBundlesTo){
            //已经合并在Bundles里面的模块不用打包到pkg里面，只需要pathmap里设置为Bundles文件的moduleId即可
            c = '';
        }else{
            c = file.getContent();
        }

        
       /* if (c && file.isCssLike && file !== pkg) {
            c = updateCSSContentUrl(c, file, pkg, context);
        }*/

        if (c) {
            if (file.isCssLike) {
                c = c.replace(CSS_CHARSET_REGEXP, '');
            }

            /**
             * @event pack:file 触发打包事件
             */
            fis.emit('pack:file', {
                file: file,
                content: c,
                pkg: pkg
            });

            content += c + '\n';
        }
    });

    return {
        content: content,
        has: has
    };
}
187447
public static boolean newerThan(File file, long timeMillis) {
		if (null == file || false == file.exists()) {
			return false;// 不存在的文件一定比任何时间旧
		}
		return file.lastModified() > timeMillis;
	}
897132
function downloadFile(url) {
  requestProgress(request({
    url: url,
    header: {
      'User-Agent': userAgent
    }
  }))
    .on('progress', function (state) {
      if (!bar) {
        console.log('downloading %s', url)
        bar = new ProgressBar(':bar :percent(:current byte)', {
          total: state.size.total,
          width: 12 + url.length
        })
      }
      bar.curr = state.size.transferred
      bar.tick()
    })
    .on('end', function () {
      bar.curr = bar.total
      bar.tick()
      // 为了显示 100% 和换行 所以下面代码运行在 nextTick
      process.nextTick(function () {
        console.log('download completed: ' + tmpZipFilePath)
        var fileMd5 = md5File.sync(tmpZipFilePath)
        if (expectedMd5 !== fileMd5) {
          console.error('md5 does not match, expect ' + expectedMd5 + ' but got ' + fileMd5)
          onInterrupted()
        }
        console.log('md5 check ok')
        console.log('unzip to ' + tmpZipFilePath)
        unZipFile(tmpZipFilePath)
      })
    })
    .pipe(fs.createWriteStream(tmpZipFilePath))
}