Hypermedia agent for the GitHub API

 @return [Sawyer::Agent]
340302
def agent
      @agent ||= Sawyer::Agent.new(endpoint, sawyer_options) do |http|
        http.headers[:accept] = default_media_type
        http.headers[:content_type] = "application/json"
        http.headers[:user_agent] = user_agent
        if basic_authenticated?
          http.basic_auth(@login, @password)
        elsif token_authenticated?
          http.authorization 'token', @access_token
        elsif bearer_authenticated?
          http.authorization 'Bearer', @bearer_token
        elsif application_authenticated?
          http.params = http.params.merge application_authentication
        end
      end
    end
1003834
function (service, name, user) {
  //
  var services = [];
  //
  services['gh'] = 'https://api.github.com/repos/:user/:name/releases';
  services['npm'] = 'http://registry.npmjs.org/:name/latest';
  services['gem'] = 'https://rubygems.org/api/v1/gems/:name.json';
  services['bower'] = 'https://api.github.com/repos/:user/:name/releases';

  var str = services[service].replace(':name', name).replace(':user', user);
  //
  return str;

}
965280
function Blob(source, parent, githubClient) {
    this.gh = githubClient;
    this.parent = parent;
    this.sha = source.sha;
    this.rawContent = source.content;
    this.size = source.size;
    this.contents = new Buffer(this.rawContent, 'base64').toString('utf-8');
}
959370
def initialize_agent
      return nil unless valid_rdf_subject?
      DPLA::MAP::Agent.new(rdf_subject).tap { |agent| agent.label = name }
    end
757564
def bundle
      content = @assets.map(&:content).join("\n")

      hash = JAPR::Pipeline.hash(@source, @manifest, @options)
      @assets = [JAPR::Asset.new(content, "#{@prefix}-#{hash}#{@type}")]
    end
975657
def build_github_url(
    repo,
    branch=None,
    path='requirements.txt',
    token=None
):
    

    repo = re.sub(r"^http(s)?://github.com/", "", repo).strip('/')

    # args come is as 'None' instead of not being provided
    if not path:
        path = 'requirements.txt'

    if not branch:
        branch = get_default_branch(repo)

    url = 'https://raw.githubusercontent.com/{}/{}/{}'.format(
        repo, branch, path
    )

    if token:
        url = '{}?token={}'.format(url, token)

    return url
14401
function remoteAsync() {
  var generator = this.generator;
  
  var username;
  var repo;
  var branch;
  var refresh;
  var url;

  // With URL and refresh
  if (arguments.length <= 2) {
    url = arguments[0];
    refresh = arguments[1];
  } else {
    username = arguments[0];
    repo = arguments[1];
    branch = arguments[2];
    refresh = arguments[3];
    url = 'https://github.com/' + [username, repo, 'archive', branch].join('/') + '.tar.gz';
  }
  
  return new Promise(function(resolve, reject) {
    parent.remote.call(parent, url, function(err, remote) {
      if (err) {
        reject(err);
      }
      else {
        resolve(remote);
      }
    }, refresh);
  });
}
79862
function github(url, destination) {
  return new Promise((resolve, reject) => {
    (0, _downloadGithubRepo2.default)(url, destination, err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}
717323
function GithubBot(options) {
  if (!(this instanceof GithubBot)) {
    return new GithubBot(options);
  }
  BaseBot.call(this, options);

  this.handlers(events);
  this.define('events', events);
}
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;
}
724645
def gh_release(name = nil, options = {})
      if name.is_a?(Hash)
        options, name = name, nil
      end

      source = options.fetch(:source)
      tag = options.fetch(:tag)
      remote_source = RemoteSources::GithubRelease.new(source, tag)

      name ||= remote_source.repository_name
      packages << Package.new(name, remote_source, options)
    end
497831
def run!
      story = @configuration.story
      fail("Could not find story associated with branch") unless story
      Git.clean_working_tree?
      Git.push(story.branch_name, set_upstream: true)
      unless story.release?
        print "Creating pull-request on Github... "
        pull_request_params = story.params_for_pull_request.merge(project: @configuration.project)
        @configuration.github_client.create_pullrequest(pull_request_params)
        puts 'OK'
      end
      return 0
    end
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([]);
      });
  };
}
7202
function(url, branch) {
  this.url = url;
  if (url.startsWith('https://api.github.com/repos/')) {
    this.path = url.substring(29);
    this.apiUrl = url;
  }
  else if (url.startsWith('https://github.com/')) {
    this.path = url.substring(19);
    this.apiUrl = 'https://api.github.com/repos/' + this.path;
  }
  else {
    throw new Error('Unsupported URL format: ' + url);
  }
  
  this.branch = branch ? branch : 'master';
  
  if (typeof window === 'undefined') {
    this.request = require('request');
    this.requestOptions = {headers: {'User-Agent': 'limberest'}};
  } 
  else {
    this.request = require('browser-request');
    this.requestOptions = {};
  }
}
715639
function publishRobotsTxt () {
    var path = 'robots.txt';
    return fs
        .statAsync(path)
        .then(function (pStat) {
            if (!pStat.isFile()) {
                // go to our default course of action, that is create robots.txt file
                throw new Error ();
            }
        })
        .catch(Error, function () {
            return fs
                .openAsync(path, 'w')
                .then(function () {
                    return fs.writeFileAsync(path, 'User-agent: *\nSitemap: ' + config.siteUrl + '/sitemap.xml');
                })
                .catch(function (pErr) {
                    log.error(pErr);
                });
        });
}
1044573
def _get_commit_msg(self, repo, sha):
        '''
        
        '''
        headers = {
            'User-Agent': 'Buildbot'
        }
        if self._token:
            headers['Authorization'] = 'token ' + self._token

        url = '/repos/{}/commits/{}'.format(repo, sha)
        http = yield httpclientservice.HTTPClientService.getService(
            self.master, self.github_api_endpoint, headers=headers,
            debug=self.debug, verify=self.verify)
        res = yield http.get(url)
        data = yield res.json()
        msg = data.get('commit', {'message': 'No message field'})['message']
        return msg
335546
def create_api_handler(self):
        
        try:
            self.github = github3.login(username=config.data['gh_user'],
                                    password=config.data['gh_password'])
        except KeyError as e:
            raise config.NotConfigured(e)
        logger.info("ratelimit remaining: {}".format(self.github.ratelimit_remaining))
        if hasattr(self.github, 'set_user_agent'):
            self.github.set_user_agent('{}: {}'.format(self.org_name, self.org_homepage))
        try:
            self.org = self.github.organization(self.org_name)
        except github3.GitHubError:
            logger.error("Possibly the github ratelimit has been exceeded")
            logger.info("ratelimit: " + str(self.github.ratelimit_remaining))