Patch a setuptools command to depend on `prebuild`
504601
def _patch_prebuild(cls):
    """"""
    orig_run = cls.run

    def new_run(self):
        self.run_command("prebuild")
        orig_run(self)

    cls.run = new_run
139704
def patched(attrs, updates):
    """"""
    orig = patch(attrs, updates.items())
    try:
        yield orig
    finally:
        patch(attrs, orig.items())
153917
def _resolve_deps(name, pkgs, **kwargs):
    '''
    
    '''
    missing_deps = []
    for pkg_file in pkgs:
        deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
        if deb.check():
            missing_deps.extend(deb.missing_deps)

    if missing_deps:
        cmd = ['apt-get', '-q', '-y']
        cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
        cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
        cmd.append('install')
        cmd.extend(missing_deps)

        ret = __salt__['cmd.retcode'](
            cmd,
            env=kwargs.get('env'),
            python_shell=False
        )

        if ret != 0:
            raise CommandExecutionError(
                'Error: unable to resolve dependencies for: {0}'.format(name)
            )
        else:
            try:
                cmd = ['apt-mark', 'auto'] + missing_deps
                __salt__['cmd.run'](
                    cmd,
                    env=kwargs.get('env'),
                    python_shell=False
                )
            except MinionError as exc:
                raise CommandExecutionError(exc)
    return
561666
def require_prebuilt_dist(func):
    

    @wraps(func)
    def wrapper_func(self, args):
        ctx = self.ctx
        ctx.set_archs(self._archs)
        ctx.prepare_build_environment(user_sdk_dir=self.sdk_dir,
                                      user_ndk_dir=self.ndk_dir,
                                      user_android_api=self.android_api,
                                      user_ndk_api=self.ndk_api)
        dist = self._dist
        if dist.needs_build:
            if dist.folder_exists():  # possible if the dist is being replaced
                dist.delete()
            info_notify('No dist exists that meets your requirements, '
                        'so one will be built.')
            build_dist_from_args(ctx, dist, args)
        func(self, args)
    return wrapper_func
612449
def setup_hook(config):
    """"""
    metadata = config['metadata']
    if sys.platform == 'win32':
        requires = metadata.get('requires_dist', '').split('\n')
        metadata['requires_dist'] = "\n".join(requires)
    config['metadata'] = metadata

    metadata['version'] = str(version)

    # pbr's setup_hook replaces easy_install.get_script_args with
    # their own version, override_get_script_args, prefering simpler
    # scripts which are not aware of multi-version.
    # prevent that by doing the opposite.  it's a horrible hack
    # but we are in patching wars already...
    from pbr import packaging

    def my_get_script_args(*args, **kwargs):
        return _main_module()._orig_get_script_args(*args, **kwargs)

    packaging.override_get_script_args = my_get_script_args
    easy_install.get_script_args = my_get_script_args

    # another hack to allow setup from tarball.
    orig_get_version = packaging.get_version

    def my_get_version(package_name, pre_version=None):
        if package_name == 'ryu':
            return str(version)
        return orig_get_version(package_name, pre_version)

    packaging.get_version = my_get_version
1353935
def install(self, dependency):
        """"""
        if not self.pip_installed:
            logger.info("Need to install a dependency with pip, but no builtin, "
                        "doing it manually (just wait a little, all should go well)")
            self._brute_force_install_pip()

        # split to pass several tokens on multiword dependency (this is very specific for '-e' on
        # external requirements, but implemented generically; note that this does not apply for
        # normal reqs, because even if it originally is 'foo > 1.2', after parsing it loses the
        # internal spaces)
        str_dep = str(dependency)
        args = [self.pip_exe, "install"] + str_dep.split()

        if self.options:
            for option in self.options:
                args.extend(option.split())
        logger.info("Installing dependency: %r", str_dep)
        try:
            helpers.logged_exec(args)
        except helpers.ExecutionError as error:
            error.dump_to_log(logger)
            raise error
        except Exception as error:
            logger.exception("Error installing %s: %s", str_dep, error)
            raise error
834686
def get_cli():
    """"""
    parser = argparse.ArgumentParser(
        prog="auto_version",
        description="auto version v%s: a tool to control version numbers" % __version__,
    )
    parser.add_argument(
        "--target",
        action="append",
        default=[],
        help="Files containing version info. "
        "Assumes unique variable names between files. (default: %s)."
        % (config.targets,),
    )
    parser.add_argument(
        "--bump",
        choices=SemVerSigFig,
        help="Bumps the specified part of SemVer string. "
        "Use this locally to correctly modify the version file.",
    )
    parser.add_argument(
        "--news",
        "--file-triggers",
        action="store_true",
        dest="file_triggers",
        help="Detects need to bump based on presence of files (as specified in config).",
    )
    parser.add_argument(
        "--set",
        help="Set the SemVer string. Use this locally to set the project version explicitly.",
    )
    parser.add_argument(
        "--set-patch-count",
        action="store_true",
        help="Sets the patch number to the commit count.",
    )
    parser.add_argument(
        "--lock",
        action="store_true",
        help="Locks the SemVer string. "
        "Lock will remain for another call to autoversion before being cleared.",
    )
    parser.add_argument(
        "--release",
        action="store_true",
        default=False,
        help="Marks as a release build, which flags the build as released.",
    )
    parser.add_argument(
        "--version",
        action="store_true",
        default=False,
        help="Prints the version of auto_version itself (self-version).",
    )
    parser.add_argument("--config", help="Configuration file path.")
    parser.add_argument(
        "-v",
        "--verbosity",
        action="count",
        default=0,
        help="increase output verbosity. " "can be specified multiple times",
    )
    return parser.parse_known_args()
1093241
def setup_build_path(build_path):
    
    if os.path.isdir(build_path):
        fname = os.path.join(build_path, 'CMakeCache.txt')
        if os.path.exists(fname):
            sys.stderr.write('aborting setup\n')
            sys.stderr.write(
                'build directory {0} which contains CMakeCache.txt already exists\n'.
                format(build_path))
            sys.stderr.write(
                'remove the build directory and then rerun setup\n')
            sys.exit(1)
    else:
        os.makedirs(build_path, 0o755)
881760
function enableModuleReplacement(opts) {
  // TODO: use proxy here instead of just monkey-patching so all furure extensions are tracked automatically
  const savedExtensions = Module._extensions;
  const _extensions = {};
  Object.keys(savedExtensions).forEach(extension => {
    _extensions[extension] = function(module, filename) {
      addHMRHooks(module);
      savedExtensions[extension](module, filename);
    };
  });

  Module._extensions = _extensions;

  // module is changed, which dependency needs to be reloaded?
  function collectDependencies(module) {
    let paths = [];
    function pathsToAcceptingModules(path, root) {
      const requiredMe = parents[root.filename];
      if (module.hot._selfAccepted) {
        paths.push(path.concat(root.filename));
        return;
      }
      if (module.hot._selfDeclined) {
        return;
      }
      for (let next in requiredMe) {
        let parentHotRuntime = requiredMe[next].hot;
        if (parentHotRuntime._acceptedDependencies[root.filename]) {
          paths.push(path.concat(root.filename));
          continue;
        }
        if (parentHotRuntime._declinedDependencies[root.filename]) {
          continue;
        }
        pathsToAcceptingModules(path.concat(root.filename), requiredMe[next]);
      }
    }
    pathsToAcceptingModules([], module);
    return paths;
  }

  opts = opts || {};
  function ignore(path) {
    if (isBuiltinModule(path)) {
      return true;
    }
    if (typeof opts.ignore === 'function') {
      return opts.ignore(path);
    }
    if (opts.ignore instanceof RegExp) {
      return !!opts.ignore.exec(path);
    }
  }

  const watching = {};
  function startWatching(path) {
    if (ignore(path)) {
      return;
    }
    if (watching[path]) {
      return;
    }
    watching[path] = watch(path, { persistent: false }, function(eventType, filename) {
      const oldModule = require.cache[path];

      const deps = oldModule ? collectDependencies(oldModule) : [];
      const reloaded = {};

      for (let d = 0; d < deps.length; ++d) {
        for (let l = 0; l < deps[d].length; ++l) {
          const path = deps[d][l];
          if (reloaded[path]) {
            continue;
          }
          reloaded[path] = true;
          const oldModule = require.cache[path];
          if (oldModule.hot._disposeHandlers) {
            oldModule.hot._disposeHandlers.forEach(h => h());
          }
          const newModule = new Module(path, oldModule.parent);
          addHMRHooks(newModule);
          try {
            newModule.load(path);
            require.cache[path] = newModule;
            const ps = parents[path];
            for (parentPath in ps) {
              let parent = require.cache[parentPath];
              if (parent.hot._acceptedDependencies[path]) {
                // TODO: try/catch here?
                parent.hot._acceptedDependencies[path](path);
              }
            }
          } catch (e) {
            console.log(e);
          }
        }
      }
    });
  }

  // monkey-patch require
  const originalRequire = Module.prototype.require;
  const originalLoad = Module._load;
  const originalCompile = Module.prototype._compile;

  const parents = {};
  Module._load = function(request, parent, isMain) {
    const requirePath = Module._resolveFilename(request, parent);
    if (ignore(requirePath)) {
      return originalLoad(request, parent, isMain);
    }

    startWatching(requirePath);
    const parentPath = parent && parent.filename;
    const myParents = parents[requirePath];
    if (parentPath) {
      if (!myParents) {
        var p = {};
        p[parentPath] = parent;
        parents[requirePath] = p;
      } else {
        myParents[parentPath] = parent;
      }
    }
    return originalLoad(request, parent, isMain);
  };

  if (module.parent) {
    if (!module.parent.hot) {
      addHMRHooks(module.parent);
    }
  }

  function addHMRHooks(module) {
    const resolve = name => {
      return Module._resolveFilename(name, module);
    };
    // copied directly from webpack HMR
    // https://github.com/webpack/webpack/blob/0257f6c6e41255cf26230c099fb90140f1f0e0bb/lib/HotModuleReplacement.runtime.js#L77
    var hot = {
      // private stuff
      _acceptedDependencies: {},
      _declinedDependencies: {},
      _selfAccepted: false,
      _selfDeclined: false,
      _disposeHandlers: [],
      // _main: hotCurrentChildModule !== moduleId,

      // Module API
      active: true,
      accept: function(dep, callback) {
        if (typeof dep === 'undefined') hot._selfAccepted = true;
        else if (typeof dep === 'function') hot._selfAccepted = dep;
        else if (typeof dep === 'object')
          for (var i = 0; i < dep.length; i++)
            hot._acceptedDependencies[resolve(dep[i])] = callback || function() {};
        else hot._acceptedDependencies[resolve(dep)] = callback || function() {};
      },
      decline: function(dep) {
        if (typeof dep === 'undefined') hot._selfDeclined = true;
        else if (typeof dep === 'object')
          for (var i = 0; i < dep.length; i++) hot._declinedDependencies[resolve(dep[i])] = true;
        else hot._declinedDependencies[resolve(dep)] = true;
      },
      dispose: function(callback) {
        hot._disposeHandlers.push(callback);
      },
      addDisposeHandler: function(callback) {
        hot._disposeHandlers.push(callback);
      },
      removeDisposeHandler: function(callback) {
        var idx = hot._disposeHandlers.indexOf(callback);
        if (idx >= 0) hot._disposeHandlers.splice(idx, 1);
      }
      /*
      // TODO: Management API
      check: hotCheck,
      apply: hotApply,

      status: function(l) {
        if (!l) return hotStatus;
        hotStatusHandlers.push(l);
      },
      addStatusHandler: function(l) {
        hotStatusHandlers.push(l);
      },
      removeStatusHandler: function(l) {
        var idx = hotStatusHandlers.indexOf(l);
        if (idx >= 0) hotStatusHandlers.splice(idx, 1);
      }

      //inherit from previous dispose call
      data: hotCurrentModuleData[moduleId]
    */
    };
    module.hot = hot;
  }
}
1173397
def setup(app):
    """"""
    app.add_config_value('jsdoc_source_root', '..', 'env')
    app.add_config_value('jsdoc_output_root', 'javascript', 'env')
    app.add_config_value('jsdoc_exclude', [], 'env')
    app.connect('builder-inited', generate_docs)
140622
def set_dependencies(analysis, dependencies, path):
    

    for toc in (analysis.binaries, analysis.datas):
        for i, tpl in enumerate(toc):
            if not tpl[1] in dependencies.keys():
                logger.info("Adding dependency %s located in %s" % (tpl[1], path))
                dependencies[tpl[1]] = path
            else:
                dep_path = get_relative_path(path, dependencies[tpl[1]])
                logger.info("Referencing %s to be a dependecy for %s, located in %s" % (tpl[1], path, dep_path))
                analysis.dependencies.append((":".join((dep_path, tpl[0])), tpl[1], "DEPENDENCY"))
                toc[i] = (None, None, None)
        # Clean the list
        toc[:] = [tpl for tpl in toc if tpl != (None, None, None)]
1221382
def version_cmd(argv):
    """"""
    import pkg_resources

    try:
        __version__ = pkg_resources.get_distribution('pew').version
    except pkg_resources.DistributionNotFound:
        __version__ = 'unknown'
        print('Setuptools has some issues here, failed to get our own package.', file=sys.stderr)

    print(__version__)
675262
def installFunc(target, source, env):
    """"""
    try:
        install = env['INSTALL']
    except KeyError:
        raise SCons.Errors.UserError('Missing INSTALL construction variable.')

    assert len(target)==len(source), \
           "Installing source %s into target %s: target and source lists must have same length."%(list(map(str, source)), list(map(str, target)))
    for t,s in zip(target,source):
        if install(t.get_path(),s.get_path(),env):
            return 1

    return 0
1141670
def patch_modules():
    
    old_call = subprocess.call

    def dummy_call(*args, **kwargs):
        with tempfile.TemporaryFile("wb+") as f:
            kwargs["stdout"] = f
            kwargs["stderr"] = f
            rv = subprocess.Popen(*args, **kwargs).wait()
            f.seek(0)
            click.echo(f.read().decode("utf-8", "replace").rstrip())
        return rv

    subprocess.call = dummy_call

    try:
        yield
    finally:
        subprocess.call = old_call
442364
def cmd_build(conf: Config, run_tests: bool=False):
    """"""
    build_context = BuildContext(conf)
    populate_targets_graph(build_context, conf)
    build_context.build_graph(run_tests=run_tests)
    build_context.write_artifacts_metadata()
1295773
def _call_apt(args, scope=True, **kwargs):
    '''
    
    '''
    cmd = []
    if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
        cmd.extend(['systemd-run', '--scope'])
    cmd.extend(args)

    params = {'output_loglevel': 'trace',
              'python_shell': False,
              'env': salt.utils.environment.get_module_environment(globals())}
    params.update(kwargs)

    return __salt__['cmd.run_all'](cmd, **params)
17376
function defaultStrategy(projectDir, builder, cb)
{
  const pkg = fs.realpathSync(INSTALLER_PACKAGE);
  builder.buildFromPackage(pkg, projectDir, cb);
}