获取要合并的文件集合

@param {Context} context 打包上下文
@param {Object} options 打包选项
@return {Array.<File>}
550170
function getMergeFiles(context, options) {
    var pkg = options.packTarget;
    var pkgExt = pkg.rExt;

    var mergedFileMap = {};
    var ignoreFiles = options.ignoreFiles;
    var filter = function (id) {
        if (mergedFileMap[id]) {
            return;
        }
        mergedFileMap[id] = true;

        var file = context.getFileById(id);
        if (file
            && (file.rExt !== pkgExt || isMatch(file.subpath, ignoreFiles))
        ) {
            return;
        }
        return file;
    };

    // 初始化要合并的文件
    var toMergeFiles = options.rawCombines
        && options.rawCombines.filter(function (item) {
            return filter(item.id);
        })
        || [];
    context
        .findFileByPattern(options.includeFiles, pkgExt)
        .forEach(function (item) {
            if (filter(item.id)) {
                toMergeFiles.push(item);
            }
        });

    // 添加依赖文件，并更新文件的打包信息
    var index = 0;
    var packDeps = options.packDeps;
    var pkgId = options.packTarget.pkgId;
    while (index < toMergeFiles.length) {
        var processFile = toMergeFiles[index++];
        context.addFilePackInfo(processFile, pkg, pkgId);

        if (packDeps) {
            addMergeFile(toMergeFiles, processFile.requires, filter);
        }
    }

    return toMergeFiles;
}
1077972
function iterateFiles (dir, options, cb) {
  var iterateOptions = {
    ext: [], // extensions to look for
    dirs: false, // do callback for dirs too
    skip_: true, // skip files & dirs starting with _
    recursive: true // do a recursive find
  }

  options = deepMerge(iterateOptions, options)
  // console.log('options: ' + JSON.stringify(options))
  iterateRecurse(dir, options, cb)
}
707183
function mergeOptions(pluginOptions) {
  const defaultOptions = {
    config: null,
    debug: false,
    css: {
      file_types: ['.css', '.less', '.sass', '.scss'],
    },
    html: {
      file_types: ['.html'],
    },
    js: {
      file_types: ['.js', '.json'],
    },
  };

  // Load 'file options'
  const explorer = cosmiconfig('jsbeautify');
  let explorerResult;

  if (pluginOptions && pluginOptions.config) {
    explorerResult = explorer.loadSync(path.resolve(pluginOptions.config));
  } else {
    explorerResult = explorer.searchSync();
  }

  let fileOptions;
  if (explorerResult) {
    fileOptions = explorerResult.config;
  }

  // Merge options
  const finalOptions = mergeWith({}, defaultOptions, fileOptions, pluginOptions, (objValue, srcValue) => {
    if (Array.isArray(objValue)) {
      return objValue.concat(srcValue);
    }

    return undefined;
  });

  // Show debug messages
  if (finalOptions.debug) {
    if (fileOptions) {
      log(`File options:\n${JSON.stringify(fileOptions, null, 2)}`);
    }

    log(`Final options:\n${JSON.stringify(finalOptions, null, 2)}`);
  }

  // Delete properties not used
  delete finalOptions.config;
  delete finalOptions.debug;

  return finalOptions;
}
949104
function combine(file) {
      if (!file) return;

      if (pathArr.indexOf(file.path) < 0) {
        pathArr.push(file.path);

        if (file.caculateContents) {
          cont = file.caculateContents
        } else {
          return;
        }

        contents.push(cont);

        size += cont.length;
      }

      if (file.children) {
        // 遍历依赖文件并且合并
        file.children.forEach(function(fc) {
          combine(denps[fc] || {path: fc});
        });
      }
    }
900093
function(options) {
      options= options || {};

      var self = this;
      if (!self._previousSave) {
        self._previousSave = self._source.then(function(base64, type) {
          var data = {
            base64: base64,
            _ContentType: type
          };
          return Parse._request({
            route: "files",
            className: self._name,
            method: 'POST',
            data: data,
            useMasterKey: options.useMasterKey
          });

        }).then(function(response) {
          self._name = response.name;
          self._url = response.url;
          return self;
        });
      }
      return self._previousSave._thenRunCallbacks(options);
    }
965413
function discoverAndReadFiles(options) {
    const FILES = {};
    const in_queue = Object.create(null);
    const queue = [];
    const enqueue = (moduleId) => {
        if (in_queue[moduleId]) {
            return;
        }
        in_queue[moduleId] = true;
        queue.push(moduleId);
    };
    options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
    while (queue.length > 0) {
        const moduleId = queue.shift();
        const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
        if (fs.existsSync(dts_filename)) {
            const dts_filecontents = fs.readFileSync(dts_filename).toString();
            FILES[`${moduleId}.d.ts`] = dts_filecontents;
            continue;
        }
        const js_filename = path.join(options.sourcesRoot, moduleId + '.js');
        if (fs.existsSync(js_filename)) {
            // This is an import for a .js file, so ignore it...
            continue;
        }
        let ts_filename;
        if (options.redirects[moduleId]) {
            ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
        }
        else {
            ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
        }
        const ts_filecontents = fs.readFileSync(ts_filename).toString();
        const info = ts.preProcessFile(ts_filecontents);
        for (let i = info.importedFiles.length - 1; i >= 0; i--) {
            const importedFileName = info.importedFiles[i].fileName;
            if (options.importIgnorePattern.test(importedFileName)) {
                // Ignore vs/css! imports
                continue;
            }
            let importedModuleId = importedFileName;
            if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
                importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
            }
            enqueue(importedModuleId);
        }
        FILES[`${moduleId}.ts`] = ts_filecontents;
    }
    return FILES;
}
628023
function createLoader(context, babelOptions) {
    let resolve = (...args) => resolvePath(context)(...args),
        loader = src => executeFile(resolve(src), { context, babelOptions });

    // 返回函数
    loader.resolve = resolve;
    return loader;
}
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 }
    );
}
1228043
function mergePath(options, deps, base) {
    return deps.map(function (item) {
        var origId = item.origId;

        // 防止多次merge
        if (item.path) {
            return;
        }
        origId = margeConfig(options, origId);
        return {
            id: item.id,
            extName: item.extName,
            path: origId.slice(0, 4) === 'http' || origId.slice(0, 2) === '//' ? origId : path.resolve(base, origId),
            origId: origId
        };
    });
}
646595
function fileSystem(context, settings, next) {
  var input = context.files

  if (input.length === 0) {
    next()
  } else {
    find(
      input,
      {
        cwd: settings.cwd,
        extensions: settings.extensions,
        silentlyIgnore: settings.silentlyIgnore,
        ignore: new Ignore({
          cwd: settings.cwd,
          detectIgnore: settings.detectIgnore,
          ignoreName: settings.ignoreName,
          ignorePath: settings.ignorePath
        })
      },
      onfound
    )
  }

  function onfound(error, result) {
    var output = result.files

    /* Sort alphabetically. Everything’s unique so we don’t care
     * about cases where left and right are equal. */
    output.sort(sortAlphabetically)

    /* Mark as given.  This allows outputting files,
     * which can be pretty dangerous, so it’s “hidden”. */
    output.forEach(markAsGiven)

    context.files = output

    /* If `out` wasn’t set, detect it based on
     * whether one file was given. */
    if (settings.out === null || settings.out === undefined) {
      settings.out = result.oneFileMode
    }

    next(error)
  }

  function markAsGiven(file) {
    file.data.unifiedEngineGiven = true
  }

  function sortAlphabetically(left, right) {
    return left.path < right.path ? -1 : 1
  }
}
533416
private CharSequence iterableContext(final Iterable<Object> context, final Options options)
      throws IOException {
    StringBuilder buffer = new StringBuilder();
    if (options.isFalsy(context)) {
      buffer.append(options.inverse());
    } else {
      Iterator<Object> iterator = context.iterator();
      int index = -1;
      Context parent = options.context;
      while (iterator.hasNext()) {
        index += 1;
        Object element = iterator.next();
        boolean first = index == 0;
        boolean even = index % 2 == 0;
        boolean last = !iterator.hasNext();
        Context current = Context.newBuilder(parent, element)
            .combine("@index", index)
            .combine("@first", first ? "first" : "")
            .combine("@last", last ? "last" : "")
            .combine("@odd", even ? "" : "odd")
            .combine("@even", even ? "even" : "")
            .build();
        buffer.append(options.fn(current));
        current.destroy();
      }
    }
    return buffer.toString();
  }
1164510
function packPageAsynModule(file, context, options) {
    if (_.isFunction(options)) {
        options = options(file.id);
    }
    if (!options) {
        return;
    }

    var asyncs = (file.asyncs || []);
    if (_.isFunction(options.filterAsyncModule)) {
        asyncs = asyncs.filter(options.filterAsyncModule);
    }
    asyncs = asyncs.map(function (id) {
        var module = context.getFileById(id);
        if (!module) {
            fis.log.warn(
                '%s entry async module %s is not found!',
                file.subpath, module.subpath
            );
        }
        return module;
    }).filter(function (item) {
        return !!item;
    });

    if (asyncs.length) {
        // 对于异步模块多个，会作为整体一起合并
        var target = options.target;
        var defaultPkgFile = asyncs[0].subpath;
        if (_.isFunction(target)) {
            target = target(defaultPkgFile, file);
        }

        var preLoad = options.load;
        return createPackItem({
            //如果是合并的异步模块，为true
            mergeAsynModule:true,
            target: target || defaultPkgFile,
            files: options.files,
            loadOrder: options.loadOrder,
            host: file,
            rawCombines: asyncs,
            load: preLoad === undefined ? true : preLoad,
            packDeps: true,
            packId: options.packId
        }, context);
    }
}
145786
function getReqOptions(options) {
    var reqConf = options.reqConfig;
    var pp = _processPathsAndPackages(reqConf.paths, reqConf.packages, options);

    var options = {
        appDir: options.appDir,
        baseUrl: options.baseUrl,
        dir: options.dir,
        //    modules: _.map(options.entryPack, _entryToReqMod),
        modules: options.entryPack,
        paths: pp.paths,
        shim: reqConf.shim || {},
        packages: reqConf.packages || [],
        optimize: "none",
        onBuildRead: function (moduleName, path, contents) {
            if (moduleName.indexOf('require-conf') > -1) {
                // 将调试状态改成发布状态
                return contents.replace(/debug\s*\:\s*(true|false)/g, 'debug: false, optimized: true');
            }
            return contents;
        },
        preserveLicenseComments: false,
        removeCombined: options.removeCombined,
        fileExclusionRegExp: /^\./,
        writeBuildTxt: options.writeBuildTxt || false
    };

    return options;
}
1011863
function copy(files, options) {
    var copied = false
    files.forEach(function(file) {
      var src = file.src
      // Use source for destination if no destionation is available
      // This is done here so globbing can use the original dest
      var dest = file.dest || src

      // Add source prefix if not already added
      if (src.indexOf(options.srcPrefix + path.sep) !== 0) {
        src = path.join(options.srcPrefix, src)
      }

      // Add dest prefix if not already added
      if (dest.indexOf(options.destPrefix + path.sep) !== 0) {
        dest = path.join(options.destPrefix, dest)
      }

      // Copy main files if :main is specified
      var main = rmain.exec(src)
      if (main) {
        copied = copy(getMain(main[1], options, dest), options) || copied
        return
      }

      // Copy folders
      if (grunt.file.isDir(src)) {
        grunt.file.recurse(src, function(abspath, rootdir, subdir, filename) {
          copied = true
          grunt.file.copy(abspath, path.join(dest, subdir || '', filename), options.copyOptions)
        })
        log.writeln(src + ' -> ' + dest)
        // Copy files
      } else if (grunt.file.exists(src)) {
        if (!rperiod.test(path.basename(dest))) {
          dest = path.join(dest, path.basename(src))
        }
        copied = true
        grunt.file.copy(src, dest, options.copyOptions)
        log.writeln(src + ' -> ' + dest)
        // Glob
      } else {
        var matches = glob.sync(src)
        if (matches.length) {
          matches = convertMatches(matches, options, file.dest)
          copied = copy(matches, options) || copied
        } else {
          log.warn(src + ' was not found')
        }
      }
    })
    return copied
  }
807219
function findFiles( options ) {

  var cwd = options.cwd ? path.resolve( options.cwd ) : CWD;

  var patterns = makeSureArray( options.src ).map( function( pattern ) {
    return new Pattern( pattern, options.micromatch );
  } );

  return new MotaObservable( function( observer ) {

    var reader = new Reader( patterns, cwd, observer );

    reader.readDir( cwd ).then(
      observer.complete.bind( observer ),
      observer.error.bind( observer )
    );

    return function() {
      reader.cancel();
    };

  } );

}
1256385
function getConfig(context, options, extendsDefaults) {
  const defaults = getDefaults(context, options);
  const config = $.config(options, defaults, (typeof extendsDefaults !== `boolean`) || extendsDefaults);
  config.metadata = { global: config.metadata, collections: {
    'error-pages': {
      pattern: `**/{500,404}.*`,
      metadata: {
        permalink: false
      }
    }
  }};
  return config;
}
336028
function resolveSSLOptions(options) {
    var toReturn = _.clone(options);
    //Resolve the file-based properties
    _.forEach(_.keys(toReturn), function(key) {
        if (key === 'cert' || key === 'key' || key === 'pfx') {
            toReturn[key] = fs.readFileSync(path.resolve(global.__appDir, toReturn[key]));
        } else if (key === 'ca') { //this can be an array
            if (_.isArray(toReturn[key])) {
                //array
                toReturn[key] = _.map(toReturn[key], function(val) {
                    return fs.readFileSync(path.resolve(global.__appDir, val));
                });
            } else {
                //Single value
                toReturn[key] = fs.readFileSync(path.resolve(global.__appDir, toReturn[key]));
            }
        }
    });
    return toReturn;
}