Retrieve a method config from a workspace, send stdout
180318
def config_get(args):
    
    r = fapi.get_workspace_config(args.project, args.workspace,
                                        args.namespace, args.config)
    fapi._check_response_code(r, 200)
    # Setting ensure_ascii to False ensures unicode string returns
    return json.dumps(r.json(), indent=4, separators=(',', ': '),
                      sort_keys=True, ensure_ascii=False)
825510
def main(argv=None, apply_config=True):
    """"""
    if argv is None:
        argv = sys.argv

    try:
        # Exit on broken pipe.
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    except AttributeError:  # pragma: no cover
        # SIGPIPE is not available on Windows.
        pass

    try:
        args = parse_args(argv[1:], apply_config=apply_config)

        if args.list_fixes:
            for code, description in sorted(supported_fixes()):
                print('{code} - {description}'.format(
                    code=code, description=description))
            return 0

        if args.files == ['-']:
            assert not args.in_place

            encoding = sys.stdin.encoding or get_encoding()

            # LineEndingWrapper is unnecessary here due to the symmetry between
            # standard in and standard out.
            wrap_output(sys.stdout, encoding=encoding).write(
                fix_code(sys.stdin.read(), args, encoding=encoding))
        else:
            if args.in_place or args.diff:
                args.files = list(set(args.files))
            else:
                assert len(args.files) == 1
                assert not args.recursive

            fix_multiple_files(args.files, args, sys.stdout)
    except KeyboardInterrupt:
        return 1
90547
def capture_stdout():
    
    stdout = sys.stdout
    sys.stdout = six.moves.cStringIO()
    try:
        yield sys.stdout
    finally:
        sys.stdout = stdout
473940
def get_stdin_pid(cached_result=None):
    """"""
    if cached_result is None:
        try:
            tasks = os.listdir('/proc/self/task')
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise
            cached_result = os.getpid()
        else:
            tasks.remove(str(os.getpid()))
            assert len(tasks) == 1
            cached_result = int(tasks[0])
    return cached_result
1347991
def cli(ctx, config_file, profile, endpoint_url, output, color, debug):
    
    config = Config(config_file)
    config.get_config_for_profle(profile)
    config.get_remote_config(endpoint_url)

    ctx.obj = config.options

    # override current options with command-line options or environment variables
    ctx.obj['output'] = output or config.options['output']
    ctx.obj['color'] = color or os.environ.get('CLICOLOR', None) or config.options['color']
    endpoint = endpoint_url or config.options['endpoint']

    ctx.obj['client'] = Client(
        endpoint=endpoint,
        key=config.options['key'],
        token=get_token(endpoint),
        username=config.options.get('username', None),
        password=config.options.get('password', None),
        timeout=float(config.options['timeout']),
        ssl_verify=config.options['sslverify'],
        debug=debug or os.environ.get('DEBUG', None) or config.options['debug']
    )
705891
def exec(method, options = {})
    results = nil

    logger.info("Executing extension hook #{Nucleon.blue(method)} at #{Nucleon.green(Time.now.to_s)}")

    extensions = Util::Data.clone(active_plugins(:nucleon, :extension))

    extensions.each do |name, plugin|
      provider = plugin.plugin_provider
      result   = nil

      logger.info("Checking extension #{provider}")

      if plugin.respond_to?(method)
        results = {} if results.nil?

        result = plugin.send(method, options)
        logger.info("Completed hook #{method} at #{Time.now}")

        if block_given?
          results[provider] = yield(:process, result)
          logger.debug("Processed extension result into: #{results[provider].inspect}")
        end

        if results[provider].nil?
          logger.debug("Setting extension result to: #{result.inspect}")
          results[provider] = result
        end
      end
    end

    if ! results.nil? && block_given?
      results = yield(:reduce, results)
      logger.debug("Reducing extension results to: #{results.inspect}")
    else
      logger.debug("Final extension results: #{results.inspect}")
    end
    results
  end
262314
def _call_config(self, method, *args, **kwargs):
        """"""
        return getattr(self._config, method)(self._section_name, *args, **kwargs)
497223
def config_validate(args):
    ''' '''

    r = fapi.validate_config(args.project, args.workspace, args.namespace,
                                                                args.config)
    fapi._check_response_code(r, 200)
    entity_d = None
    config_d = r.json()
    if args.entity:
        entity_type = config_d['methodConfiguration']['rootEntityType']
        entity_r = fapi.get_entity(args.project, args.workspace,
                                                 entity_type, args.entity)
        fapi._check_response_code(entity_r, [200,404])
        if entity_r.status_code == 404:
            eprint("Error: No {0} named '{1}'".format(entity_type, args.entity))
            return 2
        else:
            entity_d = entity_r.json()

    # also get the workspace info
    w = fapi.get_workspace(args.project, args.workspace)
    fapi._check_response_code(w, 200)
    workspace_d = w.json()

    ii, io, ma, mwa = _validate_helper(args, config_d, workspace_d, entity_d)
    ii_msg = "\nInvalid inputs:"
    io_msg = "\nInvalid outputs:"
    ma_msg = "\n{0} {1} doesn't satisfy the following inputs:".format(entity_type, args.entity) if args.entity else ""
    mwa_msg = "\nWorkspace {0}/{1} doesn't satisfy following inputs:".format(args.project, args.workspace)

    for errs, msg in zip([ii, io, ma, mwa], [ii_msg, io_msg, ma_msg, mwa_msg]):
        if errs:
            print(msg)
            for inp, val in errs:
                print("{0} -> {1}".format(inp, val))

    if ii + io + ma + mwa:
        return 1
674821
def main(argv=None):  # suppress(unused-function)
    
    argv = argv or sys.argv

    if "--" not in argv:
        sys.stderr.write("""Must specify command after '--'.\n""")
        return 1

    cmd_index = argv.index("--")
    args, cmd = (argv[1:cmd_index], argv[cmd_index + 1:])

    parser = argparse.ArgumentParser(description="""Cache results from jobs""")
    parser.add_argument("--dependencies",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of paths which, if more recent than the last time this job was invoked, will cause the job to be re-invoked.""")
    parser.add_argument("--output-files",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of expected output paths form this command, which, if they do not exist, will cause the job to be re-invoked.""")
    parser.add_argument("--stamp-directory",
                        metavar="DIRECTORY",
                        type=str,
                        help="""A directory to store cached results from this command. If a matching invocation is used and the files specified in --dependencies and --output-files are up-to-date, then the cached stdout, stderr and return code is used and the command is not run again.""")
    parser.add_argument("--use-hashes",
                        action="store_true",
                        help="""Use hash comparison in order to determine if dependencies have changed since the last invocation of the job. This method is slower, but can withstand files being copied or moved.""")
    namespace = parser.parse_args(args)
    stamp_directory = namespace.stamp_directory
    if namespace.use_hashes:
        method = jobstamp.HashMethod
    else:
        method = jobstamp.MTimeMethod

    result = jobstamp.run(_run_cmd,
                          cmd,
                          jobstamps_dependencies=namespace.dependencies,
                          jobstamps_output_files=namespace.output_files,
                          jobstamps_cache_output_directory=stamp_directory,
                          jobstamps_method=method)

    sys.stdout.write(result["stdout"].decode())
    sys.stderr.write(result["stderr"].decode())
    return result["code"]
1011490
def _RunMethod(dev, args, extra):
    """"""
    logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
    result = args.method(dev, *args.positional, **extra)
    if result is not None:
        if isinstance(result, io.StringIO):
            sys.stdout.write(result.getvalue())
        elif isinstance(result, (list, types.GeneratorType)):
            r = ''
            for r in result:
                r = str(r)
                sys.stdout.write(r)
            if not r.endswith('\n'):
                sys.stdout.write('\n')
        else:
            result = str(result)
            sys.stdout.write(result)
            if not result.endswith('\n'):
                sys.stdout.write('\n')
    return 0
338034
def call(command, working_directory=config.BASE_DIR):
    
    LOG.info(command)
    proc = sp.Popen(command, stdout=sp.PIPE, stderr=sp.PIPE, cwd=working_directory, shell=True)
    out, err = proc.communicate()
    return (out, err)
1242893
def main(cls):
        
        log_level = logging.INFO
        log_fmt = '[%(asctime)s] %(message)s'
        if bool(os.getenv('DEBUG')):
            log_level = logging.DEBUG
            log_fmt = '%(levelname).1s %(name)s [%(asctime)s] %(message)s'
        logging.basicConfig(format=log_fmt, datefmt='%Y-%m-%d %H:%M:%S', level=log_level)
        logging.getLogger('requests').setLevel(logging.WARNING)

        obj, extract_args = cls.from_args()

        LOG.info('Identified task: %s', obj.task_url)
        LOG.info('> Task ID: %s', obj.task_id)
        LOG.info('> Rank: %s', obj.rank)
        LOG.info('> Changeset: %s', obj.changeset)
        LOG.info('> Build ID: %s', obj.build_id)

        if extract_args['dry_run']:
            return

        out = extract_args['out']
        os.mkdir(out)

        try:
            obj.extract_build(out, tests=extract_args['tests'], full_symbols=extract_args['full_symbols'])
            os.makedirs(os.path.join(out, 'download'))
            with open(os.path.join(out, 'download', 'firefox-temp.txt'), 'a') as dl_fd:
                dl_fd.write('buildID=' + obj.build_id + os.linesep)
        except:  # noqa
            if os.path.isdir(out):
                junction_path.rmtree(out)
            raise
1214323
def get_config(workflow):
    
    try:
        workspace = workflow.plugin_workspace[ReactorConfigPlugin.key]
        return workspace[WORKSPACE_CONF_KEY]
    except KeyError:
        # The plugin did not run or was not successful: use defaults
        conf = ReactorConfig()
        workspace = workflow.plugin_workspace.get(ReactorConfigPlugin.key, {})
        workspace[WORKSPACE_CONF_KEY] = conf
        workflow.plugin_workspace[ReactorConfigPlugin.key] = workspace
        return conf
1069089
private MethodConfig getMethodConfig(String methodName) {
        if (methods == null) {
            return null;
        }
        return methods.get(methodName);
    }
964833
def main(ctx, config, debug):  # pragma: no cover
    
    ctx.obj = {}
    ctx.obj['args'] = {}
    ctx.obj['args']['debug'] = debug
    ctx.obj['args']['config'] = config
867691
def invoke(name, args=ARGV)
      logger.debug "invoke name: #{name}, args #{args.inspect}, configuration defined: #{configuration ? 'yes' : 'no'}"
      args = args.dup
      load_tasks

      logger.debug "find_by_namespace: #{name}"
      klass, task  = find_by_namespace(name)

      if klass
        config = {}
        config[:shell] ||= shell
        klass.send(:dispatch, task, args, nil, config) do |instance|
          if defined?(instance.configuration)
            instance.configuration = configuration.deep_clone
          end
        end
        logger.debug "after invoke"
        result = 0
      else
        puts "Could not find task #{name}"
        result = 1
      end
      result
    end
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]);
			}
		}
	}