Returns the "org/repo"-part of a github url
@param {string=} gitUrl the full repository url
@return {string|null} org and repository, separated by a "/"
@private
421091
function _githubOrgRepo (gitUrl) {
  if (!gitUrl) {
    return null
  }
  const match = gitUrl.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
  return match && match[2] && match[2].replace(/\.git$/, '')
}
1192956
function toRepoUrl(url) {
  if (url.startsWith('git@')) {
    if (argv.useSSH) {
      return url;
    }
    // have an ssh url need an http url
    const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/);
    return `https://${m[3]}/${m[4]}.git`;
  }
  if (url.startsWith('http')) {
    if (!argv.useSSH) {
      return url;
    }
    // have a http url need an ssh url
    const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/);
    return `git@${m[2]}:${m[4]}.git`;
  }
  if (!url.includes('/')) {
    url = `Caleydo/${url}`;
  }
  if (argv.useSSH) {
    return `git@github.com:${url}.git`;
  }
  return `https://github.com/${url}.git`;
}
1251637
function normalize(repo) {
	const regex = /^((github|gitlab|bitbucket|oschina):)?((.+):)?([^/]+)\/([^#]+)(#(.+))?$/;
	const match = regex.exec(repo);
	const type = match[2] || 'github';
	let host = match[4] || null;
	const owner = match[5];
	const name = match[6];
	const checkout = match[8] || 'master';

	if (host === null) {
		if (type === 'github') {
			host = 'github.com';
		} else if (type === 'gitlab') {
			host = 'gitlab.com';
		} else if (type === 'bitbucket') {
			host = 'bitbucket.com';
		} else if (type === 'oschina') {
			host = 'git.oschina.net';
		}
	}

	return {
		type,
		host,
		owner,
		name,
		checkout
	};
}
169305
async function initRepo({
  repository,
  endpoint,
  gitPrivateKey,
  gitFs,
  localDir,
}) {
  logger.debug(
    `initRepo("${JSON.stringify(
      { repository, endpoint, gitFs, localDir },
      null,
      2
    )}")`
  );
  const opts = hostRules.find({ platform }, { endpoint });
  // istanbul ignore if
  if (!(opts.username && opts.password)) {
    throw new Error(
      `No username/password found for Bitbucket repository ${repository}`
    );
  }
  // istanbul ignore if
  if (!opts.endpoint) {
    throw new Error(`No endpoint found for Bitbucket Server`);
  }
  hostRules.update({ ...opts, platform, default: true });
  api.reset();

  const [projectKey, repositorySlug] = repository.split('/');
  config = { projectKey, repositorySlug, gitPrivateKey };

  // Always gitFs
  const { host, pathname } = url.parse(opts.endpoint);
  const gitUrl = GitStorage.getUrl({
    gitFs: gitFs || 'https',
    auth: `${opts.username}:${opts.password}`,
    host: `${host}${pathname}${pathname.endsWith('/') ? '' : '/'}scm`,
    repository,
  });

  config.storage = new GitStorage();
  await config.storage.initRepo({
    ...config,
    localDir,
    url: gitUrl,
  });

  const platformConfig = {};

  try {
    const info = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }`
    )).body;
    platformConfig.privateRepo = info.is_private;
    platformConfig.isFork = !!info.parent;
    platformConfig.repoFullName = info.name;
    config.owner = info.project.key;
    logger.debug(`${repository} owner = ${config.owner}`);
    config.defaultBranch = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }/branches/default`
    )).body.displayId;
    config.baseBranch = config.defaultBranch;
    config.mergeMethod = 'merge';
  } catch (err) /* istanbul ignore next */ {
    logger.debug(err);
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    logger.info({ err }, 'Unknown Bitbucket initRepo error');
    throw err;
  }
  delete config.prList;
  delete config.fileList;
  logger.debug(
    { platformConfig },
    `platformConfig for ${config.projectKey}/${config.repositorySlug}`
  );
  return platformConfig;
}
577154
function( path, cb ) {
        // Set the content path
        octofish.setContentPath( path );

        // Use the content path to retrieve content
        octofish.github.repos.getContent( octofish.config.contentOpts, function ( err, res ) {

            var data = null;

            // Handle any error
            if (err) {
                // Log the error - not a very useful log at the moment
                console.log( 'An error occured whilst getting content from github - this should be dealt with properly' );
                console.log( 'It is most likely a URL error with the path' );

                // Call the callback with a null value to denote an error
                cb( data );
                return;
            }

            // Decode the data before sending on to the callback
            // Check for decoding an image
            if ( octofish.config.contentOpts.path.match(/img/) ) {
                data = octofish.decodeGithubImageData( res.content );
            } else {
                data = octofish.decodeGithubData( res.content );
            }

            // If the content was collected successfully then call the callback and remember to pass in the data
            cb( data );
        });
    }
257542
def get_github_hostname_user_repo_from_url(url):
    
    parsed = parse.urlparse(url)
    if parsed.netloc == '':
        # Probably ssh
        host, sep, path = parsed.path.partition(":")
        if "@" in host:
            username, sep, host = host.partition("@")
    else:
        path = parsed.path[1:].rstrip('/')
        host = parsed.netloc
    user, repo = path.split("/", 1)
    return host, user, repo[:-4] if repo.endswith('.git') else repo
235345
function prepareRepo(remoteUrl, origin, dir) {
  let promise

  if (remoteUrl) {
    // if a remoteUrl was provided, use it
    promise = wrapPromise.Promise.resolve(remoteUrl)
  } else {
    // else try to extract it from the .git folder of
    // the current directory.
    promise = getRemoteUrl(git(process.cwd()), origin)
  }

  return promise.catch(function (e) { console.error(e) }).then(function (rUrl) {
    remoteUrl = rUrl

    return wrapPromise(function (resolve, reject) {
      function initRepo(repo) {
        repo.branch(function (err, head) {
          if (err) {
            reject(err)
            return
          }

          resolve(new Git(repo, head.name).status())
        })
      }

      function clearAndInitRepo() {
        rimraf(dir, function (rmErr) {
          if (rmErr) {
            reject(rmErr)
            return
          }

          git.clone(rUrl, dir, function (cloneErr, repo) {
            if (cloneErr) {
              reject(cloneErr)
              return
            }

            initRepo(repo)
          })
        })
      }

      // assume that if there is a .git folder get its remoteUrl
      // and check if it mathces the one we want to use.
      getRemoteUrl(git(dir), origin).then(function (cwdRemoteUrl) {
        if (remoteUrl === cwdRemoteUrl) {
          initRepo(git(dir))
          return
        }

        clearAndInitRepo()
      }, function () {

        clearAndInitRepo()
      })
    })
  }).catch(function (err) {
    console.error(err)
  })
}
266980
def repository(namespace, name, branch='master'):
    ''''''
    with TemporaryDirectory() as download_path:
        old_directory = str(pwd()).strip()
        try:
            git.clone('https://github.com/{0}/{1}.git'.format(namespace, name), download_path)
            cd(download_path)
            git.fetch('origin', branch)
            git.checkout(branch)
            yield (download_path, git('rev-parse', 'HEAD'), redis.Dict(key="{0}.{1}".format(namespace, name)))
        except ErrorReturnCode_128:
            mkdir(download_path)
            yield (None, None, None)
        cd(old_directory)
508230
function _getSHA(id, callback) {
        repo.contents("").fetch({
            ref: options.branch
        }, function(err, res) {
            if (err) return callback(err);
            var sha = res.reduce(function(previousValue, item) {
                return item.name === id ? item.sha : previousValue;
            }, "");
            callback(err, sha);
        });
    }
924628
function _rawGithubUrl (resolvedPackageRoot) {
  var { packageJson, relativeFile } = resolvedPackageRoot
  const orgRepo = _githubOrgRepo(packageJson && packageJson.repository && packageJson.repository.url)
  if (orgRepo) {
    return `https://raw.githubusercontent.com/${orgRepo}/v${packageJson.version}/${relativeFile}`
  }
}
985255
def modurl(qualname):
    """"""
    obj, module = get_obj_module(qualname)
    github_url = github_url1
    try:
        path = PurePosixPath(Path(module.__file__).resolve().relative_to(project_dir))
    except ValueError:
        # trying to document something from another package
        github_url = github_url2
        path = '/'.join(module.__file__.split('/')[-2:])
    start, end = get_linenos(obj)
    fragment = '#L{}-L{}'.format(start, end) if start and end else ''
    return '{}/{}{}'.format(github_url, path, fragment)
429103
function parseGitUrl(giturl) {
    var ref, uri, fileParts, filepath;

    if (!checkGitUrl(giturl)) return null;
    giturl = giturl.slice(GIT_PREFIX.length);

    uri = new URI(giturl);
    ref = uri.fragment() || 'master';
    uri.fragment(null);

    // Extract file inside the repo (after the .git)
    fileParts =uri.path().split('.git');
    filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
    if (filepath[0] == '/') filepath = filepath.slice(1);

    // Recreate pathname without the real filename
    uri.path(_.first(fileParts)+'.git');

    return {
        host: uri.toString(),
        ref: ref || 'master',
        filepath: filepath
    };
}
1224751
def get_public_url(self, doc_id, branch='master'):
        
        name, path_frag = self.get_repo_and_path_fragment(doc_id)
        return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag
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 = {};
  }
}
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
}
884516
async function initRepo({ repository, token, endpoint, gitFs, localDir }) {
  const opts = hostRules.find({ platform: 'gitlab' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitLab repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'gitlab', default: true });
  config = {};
  get.reset();
  config.repository = urlEscape(repository);
  config.gitFs = gitFs;
  config.localDir = localDir;
  let res;
  try {
    res = await get(`projects/${config.repository}`);
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    if (res.body.default_branch === null) {
      throw new Error('empty');
    }
    config.defaultBranch = res.body.default_branch;
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // Discover our user email
    config.email = (await get(`user`)).body.email;
    logger.debug('Bot email=' + config.email);
    delete config.prList;
    // istanbul ignore if
    if (config.gitFs) {
      logger.debug('Enabling Git FS');
      const { host } = URL.parse(opts.endpoint);
      const url = GitStorage.getUrl({
        gitFs,
        auth: 'oauth2:' + opts.token,
        hostname: host || 'gitlab.com',
        repository,
      });
      config.storage = new GitStorage();
      await config.storage.initRepo({
        ...config,
        url,
      });
    } else {
      config.storage = new Storage();
      await config.storage.initRepo(config);
    }
    await Promise.all([getPrList(), getFileList()]);
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message.includes('HEAD is not a symbolic ref')) {
      throw new Error('empty');
    }
    if (['archived', 'empty'].includes(err.message)) {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    logger.info({ err }, 'Unknown GitLab initRepo error');
    throw err;
  }
  return {};
}
946190
function githubRepo (options) {
  try {
    const url = options.data.root.package.repository.url
    const match = url.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
    if (match) {
      return match[2].replace(/\.git$/, '')
    } else {
      return null
    }
  } catch (e) {
    // No repositor-url exists
    return null
  }
}