https://raw.githubusercontent.com/substack/node-mkdirp/master/index.js
335159
function (p, mode, made) {
      if (mode === undefined) {
        mode = 0o777 & (~process.umask());
      }
      if (!made) made = null;

      if (typeof mode === 'string') mode = parseInt(mode, 8);
      p = path.resolve(p);

      try {
        fs.mkdirSync(p, mode);
        made = made || p;
      } catch (err0) {
        switch (err0.code) {
          case 'ENOENT' :
            made = swig.fs.mkdir(path.dirname(p), mode, made);
            swig.fs.mkdir(p, mode, made);
            break;
          default: {
            let stat;
            try {
              stat = fs.statSync(p);
            } catch (err1) {
              throw err0;
            }
            if (!stat.isDirectory()) throw err0;
            break;
          }
        }
      }

      return made;
    }
1187783
function(dir, prefix) {
    if (fs.existsSync(dir)) {
      let dirname = path.relative(this.project.root, dir);
      let globs = this.parentRegistry.extensionsForType('js').map((extension) => `**/*.${extension}`);

      return walkSync(dir, { directories: false, globs }).map(file => {
        let module = prefix + '/' + file.replace(EXT_RE, '.js');
        this.fileLookup[module] = path.join(dirname, file);
        return module;
      });
    } else {
      return [];
    }
  }
1083499
function subModulePath(subModule, node_modules) {
  var index = subModule.indexOf("/");
  var length = subModule.length;
  if (index <= 0 || index + 1 == length) {
    return null;
  }
  var module = subModule.substring(0, index);
  var relative = subModule.substring(index + 1, length);

  var moduleDirectory = path.join(node_modules, module);
  var filePath = path.join(moduleDirectory, relative);
  return realRequirPath(filePath);
}
818037
function Slack(opts, debug) {
  if (!(this instanceof Slack)) return new Slack(opts);
  this.opts = opts;
  this.debug = debug;

  /**
   * Do everything.
   */

  this.import = function *() {
    try {
      console.log('Starting import');
      yield this.tokens();
      console.log('Got tokens');
      yield this.login();
      console.log('Logged in');
    } catch (e) {
      console.log('Uh oh! ' + e);
      throw e;
    }
    console.log('Getting emoji page');
    var emojiList = '';
    var aliasList = '';
    for (var i = 0; i < Object.keys(this.opts.emojis).length; i++) {
      var e = this.opts.emojis[i];
      if (e.src) {
        var uploadRes = yield this.upload(e.name, e.src);
        emojiList += ' :' + e.name + ':';
      }
      if (e.aliases) {
        for (var n = 0; n < e.aliases.length; n++) {
          yield this.alias(e.name, e.aliases[n]);
          aliasList += ' :' + e.aliases[n] + ':';
        }
      }
    }
    console.log('Uploaded emojis:' + emojiList);
    console.log('Uploaded emoji aliases:' + aliasList);
    return 'Success';
  };

  /**
   * Get login page (aka credentials).
   */

  this.tokens = function *() {
    var opts = this.opts;
    opts.jar = opts.jar || { _jar: { store: { idx: {} } } };
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'GET'
    };
    var res = yield request(load);
    var $ = cheerio.load(res[0].body);
    if (this.debug) write($('title').text(), $.html());
    opts.formData = {
      signin: $('#signin_form input[name="signin"]').attr('value'),
      redir: $('#signin_form input[name="redir"]').attr('value'),
      crumb: $('#signin_form input[name="crumb"]').attr('value'),
      remember: 'on',
      email: opts.email,
      password: opts.password
    };
    if (!opts.formData.signin && !opts.formData.redir && !opts.formData.crumb) throw new Error('Login error: could not get login form for ' + opts.url);
    return this.opts = opts;
  };

  /**
   * Log into Slack and populate cookies.
   */

  this.login = function *() {
    var opts = this.opts;
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'POST',
      followAllRedirects: true,
      formData: opts.formData
    };
    var res = yield request(load);
    if(res[0].body.indexOf("Sorry, you entered an incorrect email address or password.") != -1){
      throw new Error('Login error: incorrect username / password');
    }

    if(res[0].body.indexOf("Enter your authentication code") != -1){

      var $ = cheerio.load(res[0].body);

      var inputs = $("form input")

      var formData = {};

      inputs.each(function(i,v){
        formData[v.attribs.name] = v.attribs.value;
      })

      user_2fa_code = yield ask('2FA Code: ', isPassword, 'A password (as defined by this script) needs to have at least one character (not including you).');
      formData["2fa_code"] = user_2fa_code

      delete formData[undefined]
      delete formData['input']

      var load_2fa = {
        url: opts.url + "/",
        headers: headers,
        jar: opts.jar,
        method: 'POST',
        followAllRedirects: true,
        formData: formData
      };
      res = yield request(load_2fa);
    }

    //TODO: it may be necessary in the future to replace this with a user-supplied token
    var match = apiTokenRegex.exec(res[0].body);
    if (!match || !match[1]) {
      throw new Error('Application Error: unable to find api token on login page');
    }
    opts.apiToken = match[1];

    return this.opts = opts;
  };

  /**
   * Upload the emoji.
   */

  this.upload = function *(name, emoji) {
    console.log('Uploading %s with %s', name, emoji);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
        headers: headers,
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', name);
      form.append('mode', 'data');
      form.append('image', req(emoji));
      form.append('token', opts.apiToken);
    }.bind(this));
  };

  this.alias = function *(name, alias) {
    console.log('Aliasing %s to %s', alias, name);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
      headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'},
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', alias);
      form.append('mode', 'alias');
      form.append('alias', name);
      form.append('token', opts.apiToken);
    }.bind(this));
  };
}
227777
function commitlint () {
  const baseDir = getBaseDir()

  co(function * () {
    const readOptions = {
      cwd: baseDir,
      edit: '.git/COMMIT_EDITMSG'
    }

    debug('commitlint.read options: %o', readOptions)

    const gitMsgFilePath = path.join(readOptions.cwd, readOptions.edit)

    if (!fs.existsSync(gitMsgFilePath)) {
      debug(`can not found "${gitMsgFilePath}"`)
      throw new Error('无法读取 git commit 信息')
    }

    const [message, config] = yield Promise.all([read(readOptions), load()])

    debug('git commit message: %o', message)
    debug('commitlint config: %o', config)

    const rules = config.rules
    const options = config.parserPreset ? { parserOpts: config.parserPreset.parserOpts } : {}
    const report = yield lint(message[0], rules, options)
    const formatted = format({
      results: [report]
    })

    console.log()
    console.log(Array.isArray(formatted) ? formatted.join('\n') : formatted)
    console.log()

    process.exit(report.errors.length ? 1 : 0)
  }).catch(error => {
    log.error(error.message)
    process.exit(1)
  })
}
1131759
function buildTree(directory, depth, parentGitignoreList) {
  const files = fs.readdirSync(directory);
  const max_index = files.length - 1
  const color = chalk[colors[depth % colors.length]]
  parentGitignoreList = parentGitignoreList || []
  const gitignoreList = hideFilesInGitIgnore
    ? parentGitignoreList.concat(readGitignore(directory))
    : []

  for (let i = 0; i <= max_index; i++) {
    const file = files[i]
    depths[depth] = max_index - i
    const fullPath = path.resolve(directory, file)
    let printWithoutDescending = false
    let postfix = ''
    let prefix = buildPrefix(depth, i === max_index, directory)
    const stats = fs.statSync(fullPath)
    const isDirectory = stats.isDirectory()
    const size = prettybytes(stats.size)

    if (showTimeStamp) {
      prefix += dateTemplate.render(new Date(stats.mtime))
    }

    if (isDirectory) {
      directoryCount++
    } else {
      fileCount++
      totalFileSize += stats.size
    }

    if (!shouldBeIncluded(file)) {
      continue
    }

    if (hideFilesInGitIgnore) {
      let matchesGitIgnoreEntry = false
      let m = gitignoreList.length
      while (!matchesGitIgnoreEntry && m > 0) {
        matchesGitIgnoreEntry = minimatch(file, gitignoreList[m - 1])
        m--
      }

      if (matchesGitIgnoreEntry) {
        continue
      }
    }

    if (!isDirectory && showOnlyDirectories) {
      continue
    }

    if (isDirectory) {
      if (fileLimit !== Infinity || pruneEmptyDirectories) {
        const dirfiles = fs.readdirSync(fullPath).filter(shouldBeIncluded)
        if (pruneEmptyDirectories && dirfiles.length === 0) {
          continue
        }
        if (dirfiles.length > fileLimit) {
          printWithoutDescending = true
          postfix = ` [${dirfiles.length} entries exceeds filelimit (${fileLimit}), not opening dir]`
        }
      }
    }

    const filename = showFullPath ? color(fullPath.replace(cwd + '/', '')) : color(file)
    const JSXTags = createJSXTags(filename, isDirectory, size, fullPath)

    if (printJSX) {
      output += prefix + JSXTags.open + '\n'
    } else {
      output += prefix + filename + (!isDirectory && showSize ? ` (${size})` : '') + postfix + '\n';
    }
    if (printWithoutDescending) {
      continue
    }
    if (isDirectory && (depth + 1 < maxDepth)) {
      buildTree(path.resolve(directory, file), depth + 1, gitignoreList)
    }
    if (printJSX && JSXTags.close) {
      output += prefix + JSXTags.close + '\n'
    }
    --depths[depth]
  }
}
208690
function mkdirRecursive(dir) {
  var parts = path.normalize(dir).split(path.sep);
  dir = '';
  for (var i = 0; i < parts.length; i++) {
    dir += parts[i] + path.sep;
    if (!existsSync(dir)) {
      fs.mkdirSync(dir, 0x1FD); // 0775 permissions
    }
  }
}
820485
function createMiddleware(options, archiveFormat) {
  /**
   * Express middleware handling GitHub 'codeload' archive requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/contents/#get-archive-link
   */
  return async (req, res, next) => {
    // GET /:owner/:repo/:archive_format/:ref
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refName = req.params.ref;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    // project-helix/#187: serve modified content only if the requested ref is currently checked out
    const serveUncommitted = await isCheckedOut(repPath, refName);

    let commitSha;
    let archiveFileName;
    let archiveFilePath;

    resolveCommit(repPath, refName)
      .then((oid) => {
        commitSha = oid;
        return getObject(repPath, commitSha);
      })
      .then(({ object: commit }) => getObject(repPath, commit.tree))
      .then(async ({ object: tree }) => {
        archiveFileName = `${owner}-${repoName}-${serveUncommitted ? 'SNAPSHOT' : commitSha}${archiveFormat === 'zip' ? '.zip' : '.tgz'}`;
        archiveFilePath = joinPaths(CACHE_DIR, archiveFileName);
        await fse.ensureDir(CACHE_DIR);

        // check cache
        if (!serveUncommitted && await fse.pathExists(archiveFilePath)) {
          // no need to build archive, use cached archive file
          return fse.createReadStream(archiveFilePath); // lgtm [js/path-injection]
        }

        // build archive
        let archive;
        if (archiveFormat === 'zip') {
          // zip
          archive = new Archiver('zip', {
            zlib: { level: 9 }, // compression level
          });
        } else {
          // tar.gz
          archive = new Archiver('tar', {
            gzip: true,
            gzipOptions: {
              level: 9, // compression level
            },
          });
        }
        if (serveUncommitted) {
          // don't cache
          archive = await archiveWorkingDir(repPath, archive);
        } else {
          archive = await archiveGitTree(repPath, tree, archive);
        }

        return new Promise((resolve, reject) => {
          if (serveUncommitted) {
            // don't cache
            archive.finalize();
            resolve(archive);
          } else {
            // cache archive file
            archive.pipe(fse.createWriteStream(archiveFilePath)) // lgtm [js/path-injection]
              .on('finish', () => resolve(fse.createReadStream(archiveFilePath))) // lgtm [js/path-injection]
              .on('error', err => reject(err));
            archive.finalize();
          }
        });
      })
      .then((archiveStream) => {
        const mimeType = archiveFormat === 'zip' ? 'application/zip' : 'application/x-gzip';
        res.writeHead(200, {
          'Content-Type': mimeType,
          'Content-Disposition': `attachment; filename=${archiveFileName}`,
        });
        archiveStream.pipe(res);
      })
      .catch((err) => {
        options.logger.debug(`[archiveHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
      });
  };
}
457717
function gitTag() {
      return function() {
        var deferred = Q.defer();

        if (!grunt.option('version')) {
          throw new Error('Error in step [Git tag]. Version is not defined.');
        }
        Q.fcall(command(format('git tag -a v%s -m \'%s\'', grunt.option('version'), options.tag.replace('%v', grunt.option('version'))), 'Git tag'))
        //Q.fcall(command(format('echo "git tag -a v%s -m \'%s\'"', grunt.option('version'), options.tag.replace('%v', grunt.option('version'))), 'Git tag', false))//TODO:temp
          .then(function( data ) {
            deferred.resolve(data);
          })
          .catch(function( err ) {
            deferred.reject(err);
          });
        return deferred.promise;
      };
    }
623849
function createConfIndex() {
        requireConf.baseUrl = requireConf.baseUrl.replace(/\/$/, '') + '/';

        // create paths index
        pathsIndex = createKVSortedIndex(requireConf.paths);

        // create mappingId index
        mappingIdIndex = createKVSortedIndex(requireConf.map, 1);
        each(
            mappingIdIndex,
            function (item) {
                item.v = createKVSortedIndex(item.v);
            }
        );

        var lastMapItem = mappingIdIndex[mappingIdIndex.length - 1];
        if (lastMapItem && lastMapItem.k === '*') {
            each(
                mappingIdIndex,
                function (item) {
                    if (item != lastMapItem) {
                        item.v = item.v.concat(lastMapItem.v);
                    }
                }
            );
        }

        // create packages index
        packagesIndex = [];
        each(
            requireConf.packages,
            function (packageConf) {
                var pkg = packageConf;
                if (typeof packageConf === 'string') {
                    pkg = {
                        name: packageConf.split('/')[0],
                        location: packageConf,
                        main: 'main'
                    };
                }

                pkg.location = pkg.location || pkg.name;
                pkg.main = (pkg.main || 'main').replace(/\.js$/i, '');
                pkg.reg = createPrefixRegexp(pkg.name);
                packagesIndex.push(pkg);
            }
        );
        packagesIndex.sort(descSorterByKOrName);

        // create urlArgs index
        urlArgsIndex = createKVSortedIndex(requireConf.urlArgs, 1);

        // create bundles index
        bundlesIndex = {};
        /* eslint-disable no-use-before-define */
        function bundlesIterator(id) {
            bundlesIndex[resolvePackageId(id)] = key;
        }
        /* eslint-enable no-use-before-define */
        for (var key in requireConf.bundles) {
            each(requireConf.bundles[key], bundlesIterator);
        }
    }
1076047
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Contents requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/contents/#get-contents
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/contents/:path?ref=:ref
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refName = req.query.ref || 'master';
    let fpath = req.params[0] || '';

    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    const repPath = resolveRepositoryPath(options, owner, repoName);

    async function dirEntryToJson(sha, dirPath) {
      const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
      const url = `${req.protocol}://${host}${req.path}?ref=${refName}`;
      const gitUrl = `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`;
      const htmlUrl = `${req.protocol}://${host}/${owner}/${repoName}/tree/${refName}/${dirPath}`;
      return {
        type: 'dir',
        name: path.basename(dirPath),
        path: dirPath,
        sha,
        size: 0,
        url,
        html_url: htmlUrl,
        git_url: gitUrl,
        download_url: null,
        _links: {
          self: url,
          git: gitUrl,
          html: htmlUrl,
        },
      };
    }

    async function fileEntryToJson(sha, content, filePath, withContent) {
      const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
      const url = `${req.protocol}://${host}${req.path}?ref=${refName}`;
      const gitUrl = `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/blobs/${sha}`;
      const htmlUrl = `${req.protocol}://${host}/${owner}/${repoName}/blob/${refName}/${filePath}`;
      const rawlUrl = `${req.protocol}://${host}/raw/${owner}/${repoName}/${refName}/${filePath}`;
      const result = {
        type: 'file',
        name: path.basename(filePath),
        path: filePath,
        sha,
        size: content.length,
        url,
        html_url: htmlUrl,
        git_url: gitUrl,
        download_url: rawlUrl,
        _links: {
          self: url,
          git: gitUrl,
          html: htmlUrl,
        },
      };
      if (withContent) {
        result.content = `${content.toString('base64')}\n`;
        result.encoding = 'base64';
      }
      return result;
    }

    async function treeEntriesToJson(entries, dirPath) {
      return Promise.all(entries.map(async (entry) => {
        if (entry.type === 'blob') {
          const { object: content } = await getObject(repPath, entry.oid);
          return fileEntryToJson(entry.oid, content, path.join(dirPath, entry.path), false);
        }
        return dirEntryToJson(entry.oid, path.join(dirPath, entry.path));
      }));
    }

    resolveCommit(repPath, refName)
      .then(commitOid => git.readObject({ dir: repPath, oid: commitOid, filepath: fpath }))
      .then(({ type, oid, object }) => {
        if (type === 'blob') {
          // file
          return fileEntryToJson(oid, object, fpath, true);
        }
        // dir
        return treeEntriesToJson(object.entries, fpath);
      })
      .then((json) => {
        res.json(json);
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ResolveRefError') {
          options.logger.debug(`[contentHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: `No commit found for the ref ${refName}`,
            documentation_url: 'https://developer.github.com/v3/repos/contents/',
          });
        } else if (err.code === 'TreeOrBlobNotFoundError') {
          options.logger.debug(`[contentHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/repos/contents/#get-contents',
          });
        } else {
          options.logger.debug(`[contentHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
884074
function patchRequire(require) {
        if (require.patched) {
            return require;
        }
        function fromPackageJson(module, dir) {
            var pkgPath, pkgContents, pkg;
            pkgPath = fs.pathJoin(dir, module, 'package.json');
            if (!fs.exists(pkgPath)) {
                return;
            }
            pkgContents = fs.read(pkgPath);
            if (!pkgContents) {
                return;
            }
            try {
                pkg = JSON.parse(pkgContents);
            } catch (e) {
                return;
            }
            if (typeof pkg === "object" && pkg.main) {
                return fs.absolute(fs.pathJoin(dir, module, pkg.main));
            }
        }
        function resolveFile(path, dir) {
            var extensions = ['js', 'coffee', 'json'];
            var basenames = [path, path + '/index'];
            var paths = [];
            var nodejsScript = fromPackageJson(path, dir);
            if (nodejsScript) {
                return nodejsScript;
            }
            basenames.forEach(function(basename) {
                paths.push(fs.absolute(fs.pathJoin(dir, basename)));
                extensions.forEach(function(extension) {
                    paths.push(fs.absolute(fs.pathJoin(dir, [basename, extension].join('.'))));
                });
            });
            for (var i = 0; i < paths.length; i++) {
                if (fs.isFile(paths[i])) {
                    return paths[i];
                }
            }
            return null;
        }
        function getCurrentScriptRoot() {
            if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
                return phantom.casperScriptBaseDir;
            }
            return fs.absolute(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
        }
        function casperBuiltinPath(path) {
            return resolveFile(path, fs.pathJoin(phantom.casperPath, 'modules'));
        }
        function nodeModulePath(path) {
            var resolved, prevBaseDir;
            var baseDir = getCurrentScriptRoot();
            do {
                resolved = resolveFile(path, fs.pathJoin(baseDir, 'node_modules'));
                prevBaseDir = baseDir;
                baseDir = fs.absolute(fs.pathJoin(prevBaseDir, '..'));
            } while (!resolved && baseDir !== '/' && prevBaseDir !== '/' && baseDir !== prevBaseDir);
            return resolved;
        }
        function localModulePath(path) {
            return resolveFile(path, phantom.casperScriptBaseDir || fs.workingDirectory);
        }
        var patchedRequire = function patchedRequire(path) {
            try {
                return require(casperBuiltinPath(path) ||
                               nodeModulePath(path)    ||
                               localModulePath(path)   ||
                               path);
            } catch (e) {
                throw new CasperError("Can't find module " + path);
            }
        };
        patchedRequire.cache = require.cache;
        patchedRequire.extensions = require.extensions;
        patchedRequire.stubs = require.stubs;
        patchedRequire.patched = true;
        return patchedRequire;
    }
206850
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Commits requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/commits/?path=:path&sha=:sha
    const { owner } = req.params;
    const repoName = req.params.repo;
    const sha = req.query.sha || 'master';
    let fpath = req.query.path || '';

    // TODO: support filtering (author, since, until)
    // const { author, since, until } = req.query;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    if (typeof fpath !== 'string') {
      res.status(400).send('Bad request');
      return;
    }
    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    const NOT_IMPL = 'not implemented';

    function email2avatarUrl(email) {
      const hash = crypto.createHash('md5').update(email).digest('hex');
      return `https://s.gravatar.com/avatar/${hash}`;
    }

    commitLog(repPath, sha, fpath)
      .then((commits) => {
        const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
        const result = [];
        commits.forEach((commit) => {
          const parents = [];
          commit.parent.forEach(oid => parents.push({
            sha: oid,
            url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${oid}`,
            html_url: `${req.protocol}://${host}/repos/${owner}/${repoName}/commit/${oid}`,
          }));
          result.push({
            sha: commit.oid,
            node_id: NOT_IMPL,
            commit: {
              author: {
                name: commit.author.name,
                email: commit.author.email,
                date: new Date(commit.author.timestamp * 1000).toISOString(),
              },
              committer: {
                name: commit.committer.name,
                email: commit.committer.email,
                date: new Date(commit.committer.timestamp * 1000).toISOString(),
              },
              message: commit.message,
              tree: {
                sha: commit.tree,
                url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${commit.tree}`,
              },
              url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/commits/${commit.oid}`,
              comment_count: 0,
              verification: {
                verified: false,
                reason: NOT_IMPL,
                signature: NOT_IMPL,
                payload: NOT_IMPL,
              },
            },
            // TODO
            url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${commit.oid}`,
            html_url: `${req.protocol}://${host}/repos/${owner}/${repoName}/commit/${commit.oid}`,
            comments_url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${commit.oid}/comments`,
            author: {
              avatar_url: email2avatarUrl(commit.author.email),
              gravatar_id: '',
              // TODO
            },
            committer: {
              avatar_url: email2avatarUrl(commit.committer.email),
              gravatar_id: '',
              // TODO
            },
            parents,
          });
        });
        res.json(result);
      })
      .catch((err) => {
        options.logger.debug(`[commitHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
        // github seems to swallow errors and just return an empty array...
        // res.json([]);
      });
  };
}
1254382
function (buildConfig) {
        var projectRoot = buildConfig.projectRoot;
        var packageFile = path.join(projectRoot, 'package.json');

        var url = require(packageFile).repository.url;
        var prefix = 'github.com/';

        return url.substring(url.indexOf(prefix) + prefix.length, url.lastIndexOf('.git'));
    }
221308
function _main() {
  const srcIndexPath = join(DIST_DIR, 'index.html');
  const src404BodyPath = join(SRC_DIR, '404-body.html');
  const dst404PagePath = join(DIST_DIR, '404.html');

  const srcIndexContent = readFileSync(srcIndexPath, 'utf8');
  const src404BodyContent = readFileSync(src404BodyPath, 'utf8');
  const dst404PageContent = srcIndexContent.replace(/<body>[\s\S]+<\/body>/, src404BodyContent);

  if (dst404PageContent === srcIndexContent) {
    throw new Error(
        'Failed to generate \'404.html\'. ' +
        'The content of \'index.html\' does not match the expected pattern.');
  }

  writeFileSync(dst404PagePath, dst404PageContent);
}
1025147
function getRoot(cwd, filename, smap) {
    var relativePath = path.relative(cwd, filename);

    var segments = relativePath.split('node_modules');

    var sourceRoot = smap.getProperty('sourceRoot') || '/source/' + relativePath;

    if (segments.length <= 1) {
        return sourceRoot;
    } else {
        return sourceRoot
            .replace(/^\/source\//, '/source/' + pathToPackage());
    }

    // it works, somehow ¯\_(ツ)_/¯
    function pathToPackage() {
        var upToNodeModules = segments
            .slice(0, -1)
            .concat('/')
            .join('node_modules');

        var packageName = segments[segments.length - 1]
            .split('/', 2)[1]
            + '/';

        return upToNodeModules + packageName;
    }
}
467657
function getModulesByDir (dir, scope = '') {
  const nodeModulesDir = getNodeModulesDir()
  const results = []
  const modules = fs.readdirSync(dir)

  if (!modules.length) {
    return results
  }

  modules.forEach(module => {
    if (module.startsWith('.')) {

    } else if (module.startsWith('@')) {
      const subDir = path.join(nodeModulesDir, module)
      const subModules = getModulesByDir(subDir, module)
      Array.prototype.push.call(results, ...subModules)
    } else {
      results.push(scope ? `${scope}/${module}` : module)
    }
  })

  return results
}