Finds a list of new pull requests that need to be processed.

        :arg testpulls: a list of tserver.FakePull instances so we can test the code
          functionality without making live requests to github.
348663
def find_pulls(self, testpulls=None):
        
        #We check all the repositories installed for new (open) pull requests.
        #If any exist, we check the pull request number against our archive to
        #see if we have to do anything for it.
        result = {}
        for lname, repo in self.repositories.items():
            if lname not in self.archive:
                raise ValueError("Trying to find pull requests for a repository "
                                 "that hasn't been installed. Use server.install().")
            if self.runnable is not None and lname not in self.runnable:
                #We just ignore this repository completely and don't even bother
                #performing a live check on github.
                continue
            
            pulls = testpulls if testpulls is not None else repo.repo.get_pulls("open")
            result[lname] = []
            for pull in pulls:
                newpull = True
                if pull.snumber in self.archive[lname]:
                    #Check the status of that pull request processing. If it was
                    #successful, we just ignore this open pull request; it is
                    #obviously waiting to be merged in.
                    if self.archive[lname][pull.snumber]["completed"] == True:
                        newpull = False

                if newpull:
                    #Add the pull request to the list that needs to be processed.
                    #We don't add the request to the archive yet because the
                    #processing step hasn't happened yet.
                    result[lname].append(PullRequest(self, repo, pull, testpulls is not None))

        return result
242780
private static boolean isPull(ReplicatorConfiguration.ReplicatorType type) {
        return type == ReplicatorConfiguration.ReplicatorType.PUSH_AND_PULL
            || type == ReplicatorConfiguration.ReplicatorType.PULL;
    }
1088642
def get_filtered_pull_requests(pull_requests)
      pull_requests = filter_array_by_labels(pull_requests)
      pull_requests = filter_merged_pull_requests(pull_requests)
      puts "Filtered pull requests: #{pull_requests.count}" if options[:verbose]
      pull_requests
    end
607287
function getMockServerPathList(rootPath) {
    let list = [];

    fsHandler.search.getAll(rootPath, { globs: ['**/mockstar.config.js'] }).forEach((item) => {
        let opts = require(path.join(item.basePath, item.relativePath));

        list.push(opts.mockServerPath || path.join(opts.rootPath, 'src'));
    });

    return list;
}
688599
def get_pulls_list(project, auth=False, **params):
    """"""
    params.setdefault("state", "closed")
    url = "https://api.github.com/repos/{project}/pulls".format(project=project)
    if auth:
        headers = make_auth_header()
    else:
        headers = None
    pages = get_paged_request(url, headers=headers, **params)
    return pages
1113588
def parse_args(args, default_server_definitions_path,
               default_profile_definitions_path):
    
    prog = os.path.basename(sys.argv[0])
    usage = '%(prog)s [options] server'
    desc = """
Test script for testing get_central_instances method. This script executes
a number of tests and displays against a set of servers defined in the
test file

"""
    epilog = """
Examples:
  %s Fujitsu -v 3

  %s -v 1`
""" % (prog, prog)

    argparser = _argparse.ArgumentParser(
        prog=prog, usage=usage, description=desc, epilog=epilog,
        add_help=False, formatter_class=_WbemcliCustomFormatter)

    pos_arggroup = argparser.add_argument_group(
        'Positional arguments')
    pos_arggroup.add_argument(
        'servers', metavar='servers', nargs='*', type=str,
        default=['default'],
        help='R|Define by nickname zero or more specific servers to\n'
             'test. If  no servers are specified, the default\n'
             'group is tested. If there is no default group defined,\n'
             'all servers are tested.')

    general_arggroup = argparser.add_argument_group(
        'General options')

    general_arggroup.add_argument(
        '-l', '--list_servers', dest='list_servers',
        action='store_true',
        default=False,
        help='List servers nicknames defined by the servers arguement. If '
             'there are no servers defined by the servers argument, list '
             'the servers defined by the group "default". If there is no '
             'default group. list all servers')

    general_arggroup.add_argument(
        '--tests', dest='tests', default=None, nargs='*',
        choices=['overview', 'tree', 'profiles', 'insts', 'centralinsts'],
        help='List the tests to be executed. Default  is all tests')

    general_arggroup.add_argument(
        '-d', '--direction', dest='direction', default=None,
        choices=['dmtf', 'snia'],
        help='Define a particular reference direction for the test. If this '
             'is not specified, the direction algorithm is used, all of them.')

    general_arggroup.add_argument(
        '--serversfile', dest='servers_file', metavar='serversfile',
        default=default_server_definitions_path,
        help='R|The file path for the JSON file that defines the servers\n'
             'to be tested\n'
             'Default: %(default)s')

    general_arggroup.add_argument(
        '--profilesfile', dest='profiles_file', metavar='profilesfile',
        default=default_profile_definitions_path,
        help='R|The file path for the file that defines the\n'
             'characteristics of known profiles.\n'
             'Default: %(default)s')

    general_arggroup.add_argument(
        '-v', '--verbosity', dest='verbosity', type=int,
        default=0,
        help='Increment the output verbosity as integer from 0 t0 3')
    general_arggroup.add_argument(
        '-V', '--version', action='version', version='%(prog)s ' + __version__,
        help='Display script version and exit.')

    general_arggroup.add_argument(
        '-h', '--help', action='help',
        help='Show this help message and exit')

    args = argparser.parse_args()

    return args
1248061
function parseGithubURL(url) {
  var githubUrlRe = /github\.com\/([^/]+)\/([^/]+)\/pull\/([0-9]+)/;
  var match = url.match(githubUrlRe);

  if (!match) {
    return null;
  }

  return {
    owner: match[1],
    repo: match[2],
    number: match[3]
  };
}
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
}
1328309
@Override
    @SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength", "PMD.NcssMethodCount"}) // agreed, fixme
    public List<GitRequest> getPulls(GitHubRepo repo, String status, boolean firstRun, Map<Long, String> prMap) throws MalformedURLException, HygieiaException {

        List<GitRequest> pulls = new ArrayList<>();
        String decryptedPassword = decryptString(repo.getPassword(), settings.getKey());
        GitHubParsed gitHubParsed = new GitHubParsed((String) repo.getOptions().get("url"));
        String branch = (repo.getBranch() != null) ? repo.getBranch() : "master";
        String personalAccessToken = (String) repo.getOptions().get("personalAccessToken");
        String decryptedPersonalAccessToken = decryptString(personalAccessToken, settings.getKey());

        String pageUrl = gitHubParsed.getApiUrl().concat("/pulls?state=" + status + "&base=" + branch + "&sort=updated&direction=desc");

        boolean lastPage = false;
        boolean stop = false;
        String queryUrlPage = pageUrl;

        while (!lastPage && !stop) {
            LOG.info("Executing [" + queryUrlPage);
            ResponseEntity<String> response = makeRestCall(queryUrlPage, repo.getUserId(), decryptedPassword,decryptedPersonalAccessToken);
            JSONArray jsonArray = parseAsArray(response);
            for (Object item : jsonArray) {
                JSONObject jsonObject = (JSONObject) item;
                String message = str(jsonObject, "title");
                String number = str(jsonObject, "number");
                LOG.info("pr " + number + " " + message);
                String sha = str(jsonObject, "merge_commit_sha");

                JSONObject userObject = (JSONObject) jsonObject.get("user");
                String name = str(userObject, "login");
                String created = str(jsonObject, "created_at");
                String merged = str(jsonObject, "merged_at");
                String closed = str(jsonObject, "closed_at");
                String  updated = str(jsonObject, "updated_at");
                long createdTimestamp = new DateTime(created).getMillis();
                String commentsUrl = str(jsonObject, "comments_url");
                String commitStatusesUrl = str(jsonObject, "statuses_url");
                String reviewCommentsUrl = str(jsonObject, "review_comments_url");
                String reviewsUrl = str(jsonObject, "url") + "/reviews";

                GitRequest pull = new GitRequest();

                if (merged != null && merged.length() >= 10) {
                    long mergedTimestamp = new DateTime(merged).getMillis();
                    pull.setScmCommitTimestamp(mergedTimestamp);
                    pull.setResolutiontime((mergedTimestamp - createdTimestamp) / (24 * 3600000));
                }
                pull.setUserId(name);
                pull.setScmUrl(repo.getRepoUrl());
                pull.setScmBranch(branch);
                pull.setTimestamp(createdTimestamp);
                pull.setScmRevisionNumber(sha);
                pull.setScmCommitLog(message);
                pull.setCreatedAt(createdTimestamp);
                pull.setClosedAt(new DateTime(closed).getMillis());
                pull.setMergedAt(new DateTime(merged).getMillis());
                pull.setUpdatedAt(new DateTime(updated).getMillis());
                pull.setNumber(number);
                pull.setRequestType("pull");
                pull.setState("open");
                if (merged != null) {
                    pull.setState("merged");
                } else if (closed != null) {
                    pull.setState("closed");
                }
                pull.setOrgName(gitHubParsed.getOrgName());
                pull.setRepoName(gitHubParsed.getRepoName());

                JSONObject headObject = (JSONObject) jsonObject.get("head");
                if (headObject != null) {
                    String headSha = str(headObject, "sha");
                    pull.setHeadSha(headSha);
                    pull.setSourceBranch(str(headObject, "ref"));
                    JSONObject headRepoObject = (JSONObject) headObject.get("repo");
                    if (headRepoObject != null) {
                        pull.setSourceRepo(str(headRepoObject, "full_name"));
                    }
                }

                JSONObject baseObject = (JSONObject) jsonObject.get("base");
                if (baseObject != null) {
                    pull.setBaseSha(str(baseObject, "sha"));
                    pull.setTargetBranch(str(baseObject, "ref"));
                    JSONObject baseRepoObject = (JSONObject) baseObject.get("repo");
                    if (baseRepoObject != null) {
                        pull.setTargetRepo(str(baseRepoObject, "full_name"));
                    }
                }

                pull.setCommentsUrl(commentsUrl);
                List<Comment> comments = getComments(commentsUrl, repo);
                pull.setComments(comments);
                pull.setReviewCommentsUrl(reviewCommentsUrl);
                List<CommitStatus> commitStatuses = getCommitStatuses(commitStatusesUrl, repo);
                pull.setCommitStatuses(commitStatuses);
                List<Review> reviews = getReviews(reviewsUrl, repo);
                pull.setReviews(reviews);
                pull.setCommitStatuses(commitStatuses);
                pulls.add(pull);
                stop = (!MapUtils.isEmpty(prMap) && prMap.get(pull.getUpdatedAt()) != null) && (prMap.get(pull.getUpdatedAt()).equals(pull.getNumber()));
                if (stop) {
                    break;
                }
            }
            if (CollectionUtils.isEmpty(jsonArray)) {
                lastPage = true;
            } else {
                if (isThisLastPage(response)) {
                    lastPage = true;
                } else {
                    lastPage = false;
                    queryUrlPage = getNextPageUrl(response);
                }
            }
        }
        return pulls;
    }
555044
def pull_requests(repo_name)
      org_name = org_name_from(repo_name)

      unless @block
        if @org_name == org_name
          print '-'
        else
          puts ''
          print "#{org_name} -"
          @org_name = org_name
        end
      end

      issues = @client.issues(repo_name, creator: @login, state: 'open').
        select { |issue| issue.pull_request }
      issues.concat @client.issues(repo_name, creator: @login, state: 'closed').
        select { |issue| issue.pull_request }

      @block.call(repo_name, issues) if @block

      issues
    rescue Octokit::ClientError
    rescue => e
      puts e
    end
160756
def main():
  
  parser = argparse.ArgumentParser(description='A distributed test framework')
  parser.add_argument('testfile',
      help='The file that is used to determine the test suite run')
  parser.add_argument('--test-only',
      nargs='*',
      dest='test_list',
      help='run only the named tests to help debug broken tests')
  parser.add_argument('--machine-list',
      nargs='*',
      dest='machine_list',
      help='''mapping of logical host names to physical names allowing the same
              test suite to run on different hardware, each argument is a pair
              of logical name and physical name separated by a =''')
  parser.add_argument('--config-overrides',
      nargs='*',
      dest='config_overrides',
      help='''config overrides at execution time, each argument is a config with
              its value separated by a =. This has the highest priority of all
              configs''')
  parser.add_argument('-d', '--output-dir',
      dest='output_dir',
      help='''Directory to write output files and logs. Defaults to the current
              directory.''')
  parser.add_argument("--log-level", dest="log_level", help="Log level (default INFO)", default="INFO")
  parser.add_argument("--console-log-level", dest="console_level", help="Console Log level (default ERROR)",
                      default="ERROR")
  parser.add_argument("--nopassword", action='store_true', dest="nopassword", help="Disable password prompt")
  parser.add_argument("--user", dest="user", help="user to run the test as (defaults to current user)")
  args = parser.parse_args()
  try:
    call_main(args)
  except ValueError:
    #We only sys.exit here, as call_main is used as part of a unit test
    #and should not exit the system
    sys.exit(1)
721128
def call_requests(
    requests: Union[Request, Iterable[Request]], methods: Methods, debug: bool
) -> Response:
    
    if isinstance(requests, collections.Iterable):
        return BatchResponse(safe_call(r, methods, debug=debug) for r in requests)
    return safe_call(requests, methods, debug=debug)
125545
function GitHub(ready, user, pass, useSsh) {

  var opts = {
    version: '3.0.0',
    timeout: 30000
  };

  var proxy = bag.proxy();
  if (proxy) {
    proxy = url.parse(proxy);
    opts.proxy = {
      host: proxy.hostname,
      port: proxy.port
    };
  }

  this.gh = new github(opts);
  this.useSsh = useSsh;

  var self = this;
  if (user && pass) {
    // if credentials are provided, use those to authenticate
    self.gh.authenticate({
      type: 'basic',
      username: user,
      password: pass
    });
    // the other branches (oauth and no authentication only call the ready()
    // callback after another callback has resolved, which guarantees that this
    // (constructor) function has returned before the ready callback has been
    // called. This, in turn, ensures that the code calling this constructor has received a constructed object. To ensure this also for the basic auth case, we need to make this asynchronous as well.
    process.nextTick(ready);
  } else {
    var gitHubAuth = new GithubAuth();
    gitHubAuth
      .readAuthToken()
      .then(function success(token) {
        self.gh.authenticate({
          type : 'oauth',
          token : token
        });
        ready();
      }, function error() {
        // no auth token, user did not execute repoman --signin
        // continue without authentication
        ready();
    });
  }
}
433209
def utils(opts, whitelist=None, context=None, proxy=proxy):
    '''
    
    '''
    return LazyLoader(
        _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'),
        opts,
        tag='utils',
        whitelist=whitelist,
        pack={'__context__': context, '__proxy__': proxy or {}},
    )
1083444
def run(self):
        
        try:
            if self.should_fetch:
                self.fetch()

            self.rebase_all_branches()

            if self.with_bundler():
                self.check_bundler()

            if self.settings['push.auto']:
                self.push()

        except GitError as error:
            self.print_error(error)

            # Used for test cases
            if self.testing:
                raise
            else:  # pragma: no cover
                sys.exit(1)
922273
def setup_callbacks(self):
        '''
        
        '''
        if PYGIT2_VERSION >= _LooseVersion('0.23.2'):
            self.remotecallbacks = pygit2.RemoteCallbacks(
                credentials=self.credentials)
            if not self.ssl_verify:
                # Override the certificate_check function with a lambda that
                # just returns True, thus skipping the cert check.
                self.remotecallbacks.certificate_check = \
                    lambda *args, **kwargs: True
        else:
            self.remotecallbacks = None
            if not self.ssl_verify:
                warnings.warn(
                    'pygit2 does not support disabling the SSL certificate '
                    'check in versions prior to 0.23.2 (installed: {0}). '
                    'Fetches for self-signed certificates will fail.'.format(
                        PYGIT2_VERSION
                    )
                )
1058829
def execute(self):
        
        if not self.config.pr:
            raise NotPullRequestException

        logger.debug('Using the following configuration:')
        for name, value in self.config.as_dict().items():
            logger.debug('  - {}={}'.format(name, repr(value)))

        logger.info('Running Lintly against PR #{} for repo {}'.format(self.config.pr, self.project))

        parser = PARSERS.get(self.config.format)
        self._all_violations = parser.parse_violations(self.linter_output)
        logger.info('Lintly found violations in {} files'.format(len(self._all_violations)))

        diff = self.get_pr_diff()
        patch = self.get_pr_patch(diff)
        self._diff_violations = self.find_diff_violations(patch)
        logger.info('Lintly found diff violations in {} files'.format(len(self._diff_violations)))

        self.post_pr_comment(patch)
        self.post_commit_status()