run `node-gyp rebuild` on a mocked version of the addon that prints what we want so we can test that their JS is doing what it is supposed to be doing and there is no cheating! (e.g. console.log(...))
18036
function checkJs (mode, callback) {
  var exercise = this

  if (!exercise.passed)
    return callback(null, true) // shortcut if we've already had a failure

  gyp.rebuild(copyFauxTempDir, function (err) {
    if (err) {
      exercise.emit('fail', 'Compile mock C++ to test JavaScript: ' + err.message)
      return callback(null, false)
    }

    execWith(copyFauxTempDir, '♥ FAUX', function (err, pass) {
      if (err)
        return callback(err)
      if (!pass) {
        exercise.emit('fail', 'JavaScript code loads addon, invokes `length(str)` method and prints the return value')
        return callback(null, false)
      }

      execWith(copyFauxTempDir, '♥ FAUX FAUX FAUX FAUX ♥', function (err, pass) {
        if (err)
          return callback(err)

        exercise.emit(pass ? 'pass' : 'fail'
            , 'JavaScript code loads addon, invokes `length(str)` method and prints the return value')
        callback(null, pass)
      })
    })
  })
}
426563
function gnodeJsExtensionCompiler (module, filename) {
  var content = fs.readFileSync(filename, 'utf8');

  // remove the Byte Order Marker if present
  content = stripBOM(content);

  // strip away the shebang if present
  content = stripShebang(content);

  if (genFunExp.test(content) && !isValid(content)) {
    // compile JS via facebook/regenerator
    content = regenerator.compile(content, {
      includeRuntime: 'object' !== typeof regeneratorRuntime
    }).code;
  }

  module._compile(content, filename);
}
416036
function evalScript (name) {
  var Module = require('module');
  var path = require('path');
  var cwd = process.cwd();

  var module = new Module(name);
  module.filename = path.join(cwd, name);
  module.paths = Module._nodeModulePaths(cwd);
  var script = process._eval;

  // compile JS via facebook/regenerator
  script = regenerator.compile(script, {
    includeRuntime: 'object' !== typeof regeneratorRuntime
  }).code;

  if (!Module._contextLoad) {
    var body = script;
    script = 'global.__filename = ' + JSON.stringify(name) + ';\n' +
             'global.exports = exports;\n' +
             'global.module = module;\n' +
             'global.__dirname = __dirname;\n' +
             'global.require = require;\n' +
             'return require("vm").runInThisContext(' +
             JSON.stringify(body) + ', ' +
             JSON.stringify(name) + ', true);\n';
  }

  var result = module._compile(script, name + '-wrapper');
  if (process._print_eval) console.log(result);
}
654219
async function injectGhStars () {
  const opts = {}
  if ('GITHUB_TOKEN' in process.env) {
    opts.auth = process.env.GITHUB_TOKEN
  }

  const Octokit = require('@octokit/rest')
  const octokit = new Octokit(opts)

  let { headers, data } = await octokit.repos.get({
    owner: 'transloadit',
    repo: 'uppy'
  })

  console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)

  let dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  fs.writeFileSync(dstpath, data.stargazers_count, 'utf-8')

  console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
}
111772
function run(options, callback) {
  var settings = {}
  var stdin = new PassThrough()
  var tree
  var detectConfig
  var hasConfig
  var detectIgnore
  var hasIgnore

  try {
    stdin = process.stdin
  } catch (error) {
    /* Obscure bug in Node (seen on windows):
     * - https://github.com/nodejs/node/blob/f856234/lib/internal/
     *   process/stdio.js#L82;
     * - https://github.com/AtomLinter/linter-markdown/pull/85.
     */
  }

  if (!callback) {
    throw new Error('Missing `callback`')
  }

  if (!options || !options.processor) {
    return next(new Error('Missing `processor`'))
  }

  /* Processor. */
  settings.processor = options.processor

  /* Path to run as. */
  settings.cwd = options.cwd || process.cwd()

  /* Input. */
  settings.files = options.files || []
  settings.extensions = (options.extensions || []).map(extension)

  settings.filePath = options.filePath || null
  settings.streamIn = options.streamIn || stdin

  /* Output. */
  settings.streamOut = options.streamOut || process.stdout
  settings.streamError = options.streamError || process.stderr
  settings.alwaysStringify = options.alwaysStringify
  settings.output = options.output
  settings.out = options.out

  /* Null overwrites config settings, `undefined` doesn’t. */
  if (settings.output === null || settings.output === undefined) {
    settings.output = undefined
  }

  if (settings.output && settings.out) {
    return next(new Error('Cannot accept both `output` and `out`'))
  }

  /* Process phase management. */
  tree = options.tree || false

  settings.treeIn = options.treeIn
  settings.treeOut = options.treeOut
  settings.inspect = options.inspect

  if (settings.treeIn === null || settings.treeIn === undefined) {
    settings.treeIn = tree
  }

  if (settings.treeOut === null || settings.treeOut === undefined) {
    settings.treeOut = tree
  }

  /* Configuration. */
  detectConfig = options.detectConfig
  hasConfig = Boolean(options.rcName || options.packageField)

  if (detectConfig && !hasConfig) {
    return next(
      new Error('Missing `rcName` or `packageField` with `detectConfig`')
    )
  }

  settings.detectConfig =
    detectConfig === null || detectConfig === undefined
      ? hasConfig
      : detectConfig
  settings.rcName = options.rcName || null
  settings.rcPath = options.rcPath || null
  settings.packageField = options.packageField || null
  settings.settings = options.settings || {}
  settings.configTransform = options.configTransform
  settings.defaultConfig = options.defaultConfig

  /* Ignore. */
  detectIgnore = options.detectIgnore
  hasIgnore = Boolean(options.ignoreName)

  settings.detectIgnore =
    detectIgnore === null || detectIgnore === undefined
      ? hasIgnore
      : detectIgnore
  settings.ignoreName = options.ignoreName || null
  settings.ignorePath = options.ignorePath || null
  settings.silentlyIgnore = Boolean(options.silentlyIgnore)

  if (detectIgnore && !hasIgnore) {
    return next(new Error('Missing `ignoreName` with `detectIgnore`'))
  }

  /* Plug-ins. */
  settings.pluginPrefix = options.pluginPrefix || null
  settings.plugins = options.plugins || {}

  /* Reporting. */
  settings.reporter = options.reporter || null
  settings.reporterOptions = options.reporterOptions || null
  settings.color = options.color || false
  settings.silent = options.silent || false
  settings.quiet = options.quiet || false
  settings.frail = options.frail || false

  /* Process. */
  fileSetPipeline.run({files: options.files || []}, settings, next)

  function next(error, context) {
    var stats = statistics((context || {}).files)
    var failed = Boolean(
      settings.frail ? stats.fatal || stats.warn : stats.fatal
    )

    if (error) {
      callback(error)
    } else {
      callback(null, failed ? 1 : 0, context)
    }
  }
}
445518
function mock () {
    // flag set if any library is successfully mocked
    var mocked = false

    // attempt to load mockable libraries
    _.each(automock.module, (module, name) => {
        // catch errors on libraries that are not available
        try {
            // load library to be mocked
            var library = require(module.libraryName)
            // apply automock function on library
            library.automock(module.automock)
            // set success flag
            mocked = true
        }
        catch (ex) {
            console.log(ex)
        }
    })

    // throw error if no libraries found
    if (!mocked) {
        throw new Error('immutable-automock: no mockable libraries found')
    }

    // return class instance for chaining
    return automock
}
858864
function()
	{
		if (typeof console !== 'undefined' && ((pwf.has('module', 'config') && pwf.config.get('debug.frontend')) || !pwf.has('module', 'config'))) {
			var args = pwf.clone_array(arguments);

			if (args.length > 1) {
				console.log(args);
			} else {
				console.log(args[0]);
			}
		}
	}
983829
function build(options) {
  var args = [require.resolve(path.join('node-gyp', 'bin', 'node-gyp.js')), 'rebuild', '--verbose'].concat(
    ['libsass_ext', 'libsass_cflags', 'libsass_ldflags', 'libsass_library'].map(function(subject) {
      return ['--', subject, '=', process.env[subject.toUpperCase()] || ''].join('');
    })).concat(options.args);

  console.log('Building:', [process.execPath].concat(args).join(' '));

  var proc = spawn(process.execPath, args, {
    stdio: [0, 1, 2]
  });

  proc.on('exit', function(errorCode) {
    if (!errorCode) {
      afterBuild(options);
      return;
    }

    if (errorCode === 127 ) {
      console.error('node-gyp not found!');
    } else {
      console.error('Build failed with error code:', errorCode);
    }

    process.exit(1);
  });
}
1198987
function dependencyMatch (expected, actual) {
  // expand github:user/repo#hash to git://github.com/...
  if (expected.indexOf('github:') === 0) {
    expected = expected.replace(/^github:/, 'git://github.com/')
    var parsed = url.parse(expected)
    parsed.pathname += '.git'
    expected = url.format(parsed)
  }

    // normalize git+https prefix
  actual = actual.replace(/^git\+https/, 'git')
  expected = expected.replace(/^git\+https/, 'git')

  expected = ngu(expected)
  actual = ngu(actual)

  expected.url = expected.url.replace('https://', 'git://')
  actual.url = actual.url.replace('https://', 'git://')

  if (expected.url !== actual.url) {
    return false
  }

  if (actual.branch && actual.branch.indexOf(expected.branch) !== 0) {
    return false
  }

  return true
}
1067544
function checkRequirements () {
      // Check if git version meets requirements
      var gitVersion = (shelljs.exec('git --version', {silent: true}).output.match(/\d+\.\d+\.\d+/) || []).shift();
      if (!gitVersion || semver.lt(gitVersion, '1.8.0')) {
        throw('Current Git version is ' + gitVersion + '. This plugin requires Git >= 1.8.0.');
      }

      // Check that build directory exists
      if (!fs.existsSync(options.dir)) {
        throw('Build directory "' + options.dir + '" doesn\'t exist. Nothing to version.');
      }

      // Check that build directory conteins files
      if (fs.readdirSync(options.dir).length === 0) {
        throw('Build directory "' + options.dir + '" is empty. Nothing to version.');
      }

      // If connectCommits is true check that the main project's working
      // directory is clean
      if (options.connectCommits) {
        var gitDiffOutput = shelljs.exec('git diff').output;
        if (gitDiffOutput !== '') {
          throw ('There are uncommitted changes in your working directory. \n' +
          'Please commit changes to the main project before you commit to \n' +
          'the built code.\n');
        }
      }

      if (options.shallowFetch && semver.lt(gitVersion, '1.9.0')) {
        throw('Current Git version is ' + gitVersion + '. Option "shallowFetch" is supported on Git >= 1.9.0.');
      }
    }
943418
function MockRpc(endpoint) {
    events.EventEmitter.call(this);
    this._endpoint = endpoint;
    this._handlers = {};
    glNetwork[endpoint] = this;
}
655992
function (setUp, tearDown, fn) {
    return function (test) {
        var context = {};
        if (tearDown) {
            var done = test.done;
            test.done = function (err) {
                try {
                    tearDown.call(context, function (err2) {
                        if (err && err2) {
                            test._assertion_list.push(
                                types.assertion({error: err})
                            );
                            return done(err2);
                        }
                        done(err || err2);
                    });
                }
                catch (e) {
                    done(e);
                }
            };
        }
        if (setUp) {
            setUp.call(context, function (err) {
                if (err) {
                    return test.done(err);
                }
                fn.call(context, test);
            });
        }
        else {
            fn.call(context, test);
        }
    };
}
986067
async function initRepo({
  repository,
  token,
  endpoint,
  forkMode,
  forkToken,
  gitPrivateKey,
  gitFs,
  localDir,
  includeForks,
}) {
  logger.debug(`initRepo("${repository}")`);
  const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitHub repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'github', default: true });
  logger.info('Authenticated as user: ' + (await getRenovateUsername()));
  logger.info('Using renovate version: ' + global.renovateVersion);
  // config is used by the platform api itself, not necessary for the app layer to know
  cleanRepo();
  config.isGhe = endpoint && !endpoint.startsWith('https://api.github.com');
  config.localDir = localDir;
  config.platform = 'github';
  config.repository = repository;
  [config.repositoryOwner, config.repositoryName] = repository.split('/');
  config.gitPrivateKey = gitPrivateKey;
  // platformConfig is passed back to the app layer and contains info about the platform they require
  const platformConfig = {};
  let res;
  try {
    res = await get(`repos/${repository}`);
    logger.trace({ repositoryDetails: res.body }, 'Repository details');
    // istanbul ignore if
    if (res.body.fork && gitFs && !includeForks) {
      try {
        const renovateConfig = JSON.parse(
          Buffer.from(
            (await get(
              `repos/${config.repository}/contents/${defaultConfigFile}`
            )).body.content,
            'base64'
          ).toString()
        );
        if (!renovateConfig.includeForks) {
          throw new Error();
        }
      } catch (err) {
        throw new Error('fork');
      }
    }
    // istanbul ignore if
    if (res.body.full_name && res.body.full_name !== repository) {
      logger.info(
        { repository, this_repository: res.body.full_name },
        'Repository has been renamed'
      );
      throw new Error('renamed');
    }
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    platformConfig.privateRepo = res.body.private === true;
    platformConfig.isFork = res.body.fork === true;
    const owner = res.body.owner.login;
    logger.debug(`${repository} owner = ${owner}`);
    // Use default branch as PR target unless later overridden.
    config.defaultBranch = res.body.default_branch;
    // Base branch may be configured but defaultBranch is always fixed
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // GitHub allows administrators to block certain types of merge, so we need to check it
    if (res.body.allow_rebase_merge) {
      config.mergeMethod = 'rebase';
    } else if (res.body.allow_squash_merge) {
      config.mergeMethod = 'squash';
    } else if (res.body.allow_merge_commit) {
      config.mergeMethod = 'merge';
    } else {
      // This happens if we don't have Administrator read access, it is not a critical error
      logger.info('Could not find allowed merge methods for repo');
    }
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message === 'archived' || err.message === 'renamed') {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    if (err.message.startsWith('Repository access blocked')) {
      throw new Error('blocked');
    }
    if (err.message === 'fork') {
      throw err;
    }
    logger.info({ err }, 'Unknown GitHub initRepo error');
    throw err;
  }
  // This shouldn't be necessary, but occasional strange errors happened until it was added
  config.issueList = null;
  config.prList = null;
  config.openPrList = null;
  config.closedPrList = null;
  config.storage = new Storage();
  await config.storage.initRepo(config);
  if (forkMode) {
    logger.info('Bot is in forkMode');
    config.forkToken = forkToken;
    // Save parent SHA then delete
    const parentSha = await getBaseCommitSHA();
    config.baseCommitSHA = null;
    // save parent name then delete
    config.parentRepo = config.repository;
    config.repository = null;
    // Get list of existing repos
    const existingRepos = (await get('user/repos?per_page=100', {
      token: forkToken || opts.token,
      paginate: true,
    })).body.map(r => r.full_name);
    try {
      config.repository = (await get.post(`repos/${repository}/forks`, {
        token: forkToken || opts.token,
      })).body.full_name;
    } catch (err) /* istanbul ignore next */ {
      logger.info({ err }, 'Error forking repository');
      throw new Error('cannot-fork');
    }
    if (existingRepos.includes(config.repository)) {
      logger.info(
        { repository_fork: config.repository },
        'Found existing fork'
      );
      // Need to update base branch
      logger.debug(
        { baseBranch: config.baseBranch, parentSha },
        'Setting baseBranch ref in fork'
      );
      // This is a lovely "hack" by GitHub that lets us force update our fork's master
      // with the base commit from the parent repository
      try {
        await get.patch(
          `repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
          {
            body: {
              sha: parentSha,
              force: true,
            },
            token: forkToken || opts.token,
          }
        );
      } catch (err) /* istanbul ignore next */ {
        if (
          err.statusCode === 422 &&
          err.message.startsWith('Object does not exist')
        ) {
          throw new Error('repository-changed');
        }
      }
    } else {
      logger.info({ repository_fork: config.repository }, 'Created fork');
      // Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
      await delay(30000);
    }
    await config.storage.initRepo(config);
  }

  // istanbul ignore if
  if (gitFs) {
    logger.debug('Enabling Git FS');
    let { host } = URL.parse(opts.endpoint);
    if (host === 'api.github.com') {
      host = null;
    }
    host = host || 'github.com';
    const url = GitStorage.getUrl({
      gitFs,
      auth:
        config.forkToken ||
        (global.appMode ? `x-access-token:${opts.token}` : opts.token),
      hostname: host,
      repository: config.repository,
    });
    config.storage = new GitStorage();
    await config.storage.initRepo({
      ...config,
      url,
    });
  }

  return platformConfig;
}
239944
def call_env_check_consistency(cls, kb_app, builder: StandaloneHTMLBuilder,
                                   sphinx_env: BuildEnvironment):
        

        for callback in EventAction.get_callbacks(kb_app,
                                                  SphinxEvent.ECC):
            callback(kb_app, builder, sphinx_env)
128955
function prepareDebug() {
  // Import Closure Library and deps.js.
  require('../src/wtf/bootstrap/node').importClosureLibrary([
    'wtf_js-deps.js'
  ]);

  // Disable asserts unless debugging - asserts cause all code to deopt.
  if (debugMode) {
    goog.require('goog.asserts');
    goog.asserts.assert = function(condition, opt_message) {
      console.assert(condition, opt_message);
      return condition;
    };
  } else {
    goog.DEBUG = false;
    goog.require('goog.asserts');
    goog.asserts.assert = function(condition) {
      return condition;
    };
  }

  // Load WTF and configure options.
  goog.require('wtf');
  wtf.NODE = true;
  goog.require('wtf.db.exports');
  goog.require('wtf.db.node');
}
1182940
async function build() {
    const clientConfig = await webpackConfig({target: 'web', env: 'prod'});
    const serverConfig = await webpackConfig({target: 'node', env: 'prod'});

    return new Promise((resolve, reject) => {
        console.log('Compiling client...');

        // eslint-disable-next-line consistent-return
        webpack(clientConfig, (clientError, clientStats) => {
            if (clientError) {
                return reject(clientError);
            }

            const clientMessages = formatWebpackMessages(clientStats.toJson({}, true));
            if (clientMessages.errors.length) {
                return reject(new Error(clientMessages.errors.join('\n\n')));
            }

            if (
                process.env.CI &&
                (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
                clientMessages.warnings.length
            ) {
                console.log(
                    chalk.yellow(
                        '\nTreating warnings as errors because process.env.CI = true.\n' +
                            'Most CI servers set it automatically.\n'
                    )
                );
                return reject(new Error(clientMessages.warnings.join('\n\n')));
            }

            console.log(chalk.green('Compiled client successfully.'), '\n');
            console.log('Compiling server...');
            webpack(serverConfig, (serverError, serverStats) => {
                if (serverError) {
                    return reject(serverError);
                }

                const serverMessages = formatWebpackMessages(serverStats.toJson({}, true));
                if (serverMessages.errors.length) {
                    return reject(new Error(serverMessages.errors.join('\n\n')));
                }

                if (
                    process.env.CI &&
                    (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
                    serverMessages.warnings.length
                ) {
                    console.log(
                        chalk.yellow(
                            '\nTreating warnings as errors because process.env.CI = true.\n' +
                                'Most CI servers set it automatically.\n'
                        )
                    );
                    return reject(new Error(serverMessages.warnings.join('\n\n')));
                }

                console.log(chalk.green('Compiled server successfully.'), '\n');
                return resolve({
                    stats: clientStats,
                    warnings: Object.assign({}, clientMessages.warnings, serverMessages.warnings),
                });
            });
        });
    });
}
1290634
function build(previousFileSizes) {
  console.log('Creating an optimized production build...');
  webpack(config).run((err, stats) => {
    if (err) {
      printErrors('Failed to compile.', [err]);
      process.exit(1);
    }

    if (stats.compilation.errors.length) {
      printErrors('Failed to compile.', stats.compilation.errors);
      process.exit(1);
    }

    if (process.env.CI && stats.compilation.warnings.length) {
      printErrors(
        'Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.',
        stats.compilation.warnings,
      );
      process.exit(1);
    }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    console.log('File sizes after gzip:');
    console.log();
    printFileSizesAfterBuild(stats, previousFileSizes);
    console.log();

    const appPackage = require(paths.appPackageJson);
    const publicUrl = paths.publicUrl;
    const publicPath = config.output.publicPath;
    const publicPathname = url.parse(publicPath).pathname;
    if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log(`The docs were built assuming they are hosted at ${chalk.green(publicUrl)}.`);
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log(`The project was built assuming it is hosted at ${chalk.green(publicPath)}.`);
      console.log(
        `You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan(
          'package.json',
        )}.`,
      );
      console.log();
      console.log(`The ${chalk.cyan('build')} folder is ready to be deployed.`);
      console.log();
    } else {
      if (publicUrl) {
        // "homepage": "http://mywebsite.com"
        console.log(`The project was built assuming it is hosted at ${chalk.green(publicUrl)}.`);
        console.log(
          `You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan(
            'package.json',
          )}.`,
        );
        console.log();
      } else {
        // no homepage
        console.log('The project was built assuming it is hosted at the server root.');
        console.log(
          `To override this, specify the ${chalk.green('homepage')} in your ${chalk.cyan(
            'package.json',
          )}.`,
        );
        console.log('For example, add this to build it for GitHub Pages:');
        console.log();
        console.log(
          `  ${chalk.green('"homepage"')}${chalk.cyan(': ')}${chalk.green(
            '"http://myname.github.io/myapp"',
          )}${chalk.cyan(',')}`,
        );
        console.log();
      }
      const build = path.relative(process.cwd(), paths.appBuild);
      console.log(`The ${chalk.cyan(build)} folder is ready to be deployed.`);
      console.log('You may serve it with a static server:');
      console.log();
      if (useYarn) {
        console.log(`  ${chalk.cyan('yarn')} global add serve`);
      } else {
        console.log(`  ${chalk.cyan('npm')} install -g serve`);
      }
      console.log(`  ${chalk.cyan('serve')} -s build`);
      console.log();
    }
  });
}