Send initial git-upload-pack request outputs refs and caps
549563
function discover(callback) {
      if (!callback) return discover.bind(this);
      if (!connection) {
        return connect("git-upload-pack", function (err) {
          if (err) return callback(err);
          return discover(callback);
        });
      }
      sharedDiscover(connection, callback);
    }
313188
def get_git_refs(self):
        
        return github.PaginatedList.PaginatedList(
            github.GitRef.GitRef,
            self._requester,
            self.url + "/git/refs",
            None
        )
1191430
def upload(self, cmd: str, meta: dict):
        """"""
        index = os.path.join(self.cached_repo, self.INDEX_FILE)
        if os.path.exists(index):
            os.remove(index)
        self._log.info("Writing the new index.json ...")
        with open(index, "w") as _out:
            json.dump(self.contents, _out)
        git.add(self.cached_repo, [index])
        message = self.COMMIT_MESSAGES[cmd].format(**meta)
        if self.signoff:
            global_conf_path = os.path.expanduser("~/.gitconfig")
            if os.path.exists(global_conf_path):
                with open(global_conf_path, "br") as _in:
                    conf = ConfigFile.from_file(_in)
                    try:
                        name = conf.get(b"user", b"name").decode()
                        email = conf.get(b"user", b"email").decode()
                        message += self.DCO_MESSAGE.format(name=name, email=email)
                    except KeyError:
                        self._log.warning(
                            "Did not find name or email in %s, committing without DCO.",
                            global_conf_path)
            else:
                self._log.warning("Global git configuration file %s does not exist, "
                                  "committing without DCO.", global_conf_path)
        else:
            self._log.info("Committing the index without DCO.")
        git.commit(self.cached_repo, message=message)
        self._log.info("Pushing the updated index ...")
        # TODO: change when https://github.com/dulwich/dulwich/issues/631 gets addressed
        git.push(self.cached_repo, self.remote_url, b"master")
        if self._are_local_and_remote_heads_different():
            self._log.error("Push has failed")
            raise ValueError("Push has failed")
1360495
def send_inline_comment(results, method)
      dir = "#{Dir.pwd}/"
      results.each do |r|
        github_filename = r['file'].gsub(dir, '')
        message = "#{r['reason']}".dup

        # extended content here
        filename = r['file'].split('/').last
        message << "\n"
        message << "`#{r['rule_id']}`" # helps writing exceptions // swiftlint:disable:this rule_id
        message << " `#{filename}:#{r['line']}`" # file:line for pasting into Xcode Quick Open
        
        send(method, message, file: github_filename, line: r['line'])
      end
    end
316960
def update_signature!
      result = Overcommit::Utils.execute(
        %w[git config --local] + [signature_config_key, signature]
      )

      verify_signature_value = @hash['verify_signatures'] ? 1 : 0
      result &&= Overcommit::Utils.execute(
        %W[git config --local #{verify_signature_config_key} #{verify_signature_value}]
      )

      unless result.success?
        raise Overcommit::Exceptions::GitConfigError,
              "Unable to write to local repo git config: #{result.stderr}"
      end
    end
1139142
function assignTokens () {
      var sourceBranch = shelljs.exec('git rev-parse --abbrev-ref HEAD', {silent: true});
      var sourceCommit = shelljs.exec('git rev-parse --short HEAD', {silent: true});

      if (sourceBranch.code === 0) {
        tokens.branch = sourceBranch.output.replace(/\n/g, '');
      }
      if (sourceCommit.code === 0) {
        tokens.commit = sourceCommit.output.replace(/\n/g, '');
      }
      if (shelljs.test('-f', 'package.json', {silent: true})) {
        tokens.name = JSON.parse(fs.readFileSync('package.json', 'utf8')).name;
      }
      else {
        tokens.name = process.cwd().split('/').pop();
      }
    }
917976
def upload(ui, repo, name, **opts):
	
	if codereview_disabled:
		raise hg_util.Abort(codereview_disabled)

	repo.ui.quiet = True
	cl, err = LoadCL(ui, repo, name, web=True)
	if err != "":
		raise hg_util.Abort(err)
	if not cl.local:
		raise hg_util.Abort("cannot upload non-local change")
	cl.Upload(ui, repo)
	print "%s%s\n" % (server_url_base, cl.name)
	return 0
130734
function readPackedRef(gitFolder, refName) {
	var packedRefs, i, each, match

	try {
		packedRefs = fs.readFileSync(path.join(gitFolder, 'packed-refs'), 'utf8').split(/\r?\n/)
	} catch (e) {
		return ''
	}

	for (i = 0; i < packedRefs.length; i++) {
		each = packedRefs[i].trim()

		// Look for lines like:
		// 1d6f5f98a254578e19b5eb163077170d45448c26 refs/heads/master
		match = each.match(/^(.{40}) (.*)$/)
		if (match && match[2] === refName && isSHA1(match[1])) {
			return match[1]
		}
	}
	return ''
}
618030
function confirmTransmit(outpacket, err) {
  if (this.active && err) {
    // Roll it all back into outbox (which may not be empty anymore)
    if (outpacket.responses.length > 0) {
      Array.prototype.push.apply(this.outbox.responses, outpacket.responses);
    }
    if (outpacket.requests.length > 0) {
      Array.prototype.push.apply(this.outbox.requests, outpacket.requests);
    }
  }
}
605920
def send(cfg, **kwargs):
    """"""
    for name, value in kwargs.items():
        setattr(cfg, name, value)
    with cfg.timing.add("import", which="cmd_send"):
        from . import cmd_send

    return go(cmd_send.send, cfg)
73890
def cmd(send, msg, args):
    
    repo = args['config']['api']['githubrepo']
    apikey = args['config']['api']['githubapikey']
    if not repo:
        send("GitHub repository undefined in config.cfg!")
        return
    parser = arguments.ArgParser(args['config'])
    parser.add_argument('title', nargs='*', default='')
    parser.add_argument('--get', '--show', action='store_true')
    parser.add_argument('--description', nargs='+', default="No description given.")
    cmdargs, remainder = parser.parse_known_args(msg)
    if isinstance(cmdargs.title, list):
        cmdargs.title = ' '.join(cmdargs.title)
    if isinstance(cmdargs.description, list):
        cmdargs.description = ' '.join(cmdargs.description)
    if remainder:
        cmdargs.title = "%s %s" % (cmdargs.title, ' '.join(remainder))
    if args['type'] == 'privmsg':
        send('You want to let everybody know about your problems, right?')
    elif cmdargs.get or cmdargs.title.isdigit():
        issue = get('https://api.github.com/repos/%s/issues/%d' % (repo, int(cmdargs.title))).json()
        if 'message' in issue:
            send("Invalid Issue Number")
        else:
            send("%s (%s) -- %s" % (issue['title'], issue['state'], issue['html_url']))
    elif not cmdargs.title:
        issues = []
        n = 1
        while True:
            headers = {'Authorization': 'token %s' % apikey}
            page = get('https://api.github.com/repos/%s/issues' % repo, params={'per_page': '100', 'page': n}, headers=headers).json()
            n += 1
            if page:
                issues += page
            else:
                break
        if len(issues) == 0:
            send("No open issues to choose from!")
        else:
            issue = choice(issues)
            num_issues = len([x for x in issues if 'pull_request' not in x])
            send("There are %d open issues, here's one." % num_issues)
            send("#%d -- %s -- %s" % (issue['number'], issue['title'], issue['html_url']))
    elif cmdargs.title and args['is_admin'](args['nick']):
        url, success = create_issue(cmdargs.title, cmdargs.description, args['source'], repo, apikey)
        if success:
            send("Issue created -- %s -- %s -- %s" % (url, cmdargs.title, cmdargs.description))
        else:
            send("Error creating issue: %s" % url)
    elif cmdargs.title:
        row = Issues(title=cmdargs.title, description=cmdargs.description, source=str(args['source']))  # str needed to make mysqlconnector happy
        args['db'].add(row)
        args['db'].flush()
        send("New Issue: #%d -- %s -- %s, Submitted by %s" % (row.id, cmdargs.title, cmdargs.description, args['nick']),
             target=args['config']['core']['ctrlchan'])
        send("Issue submitted for approval.", target=args['nick'])
    else:
        send("Invalid arguments.")
268983
function gitRelease() {
			// Tag release
			rbot.log.info('Tagging release ' + commit.versionTag + ' via ' + options.gitHostname);
			cmd('git tag -f -a ' + commit.versionTag + ' -m "'
					+ (chgLogRtn ? chgLogRtn.replace(coopt.regexLines, '$1 \\') : commit.message) + '"');
			cmd('git push -f ' + options.repoName + ' ' + commit.versionTag);
			commit.releaseId = commit.versionTag;
			// TODO : upload asset?
			rollCall.addRollback(rollbackTag);
			rollCall.then(publish);
		}
241395
def get_git_ref(self, ref):
        
        prefix = "/git/refs/"
        if not self._requester.FIX_REPO_GET_GIT_REF:
            prefix = "/git/"
        assert isinstance(ref, (str, unicode)), ref
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + prefix + ref
        )
        return github.GitRef.GitRef(self._requester, headers, data, completed=True)
472861
def send_file_to_remote(dev, src_file, dst_filename, filesize, dst_mode='wb'):
    
    bytes_remaining = filesize
    save_timeout = dev.timeout
    dev.timeout = 1
    while bytes_remaining > 0:
        # Wait for ack so we don't get too far ahead of the remote
        ack = dev.read(1)
        if ack is None or ack != b'\x06':
            sys.stderr.write("timed out or error in transfer to remote\n")
            sys.exit(2)

        if HAS_BUFFER:
            buf_size = BUFFER_SIZE
        else:
            buf_size = BUFFER_SIZE // 2
        read_size = min(bytes_remaining, buf_size)
        buf = src_file.read(read_size)
        #sys.stdout.write('\r%d/%d' % (filesize - bytes_remaining, filesize))
        #sys.stdout.flush()
        if HAS_BUFFER:
            dev.write(buf)
        else:
            dev.write(binascii.hexlify(buf))
        bytes_remaining -= read_size
    #sys.stdout.write('\r')
    dev.timeout = save_timeout
587270
def from_local_repository(repository_path, refspec=None):
        

        context = GitContext()

        # If no refspec is defined, fallback to the last commit on the current branch
        if refspec is None:
            # We tried many things here e.g.: defaulting to e.g. HEAD or HEAD^... (incl. dealing with
            # repos that only have a single commit - HEAD^... doesn't work there), but then we still get into
            # problems with e.g. merge commits. Easiest solution is just taking the SHA from `git log -1`.
            sha_list = [_git("log", "-1", "--pretty=%H", _cwd=repository_path).replace(u"\n", u"")]
        else:
            sha_list = _git("rev-list", refspec, _cwd=repository_path).split()

        for sha in sha_list:
            # Get info from the local git repository: https://git-scm.com/docs/pretty-formats
            long_format = "--pretty=%aN%x00%aE%x00%ai%x00%P%n%B"
            raw_commit = _git("log", sha, "-1", long_format, _cwd=repository_path).split("\n")

            (name, email, date, parents), commit_msg = raw_commit[0].split('\x00'), "\n".join(raw_commit[1:])

            commit_parents = parents.split(" ")
            commit_is_merge_commit = len(commit_parents) > 1

            # changed files in last commit
            changed_files = _git("diff-tree", "--no-commit-id", "--name-only", "-r", sha, _cwd=repository_path).split()

            # "YYYY-MM-DD HH:mm:ss Z" -> ISO 8601-like format
            # Use arrow for datetime parsing, because apparently python is quirky around ISO-8601 dates:
            # http://stackoverflow.com/a/30696682/381010
            commit_date = arrow.get(ustr(date), "YYYY-MM-DD HH:mm:ss Z").datetime

            # Create Git commit object with the retrieved info
            commit_msg_obj = GitCommitMessage.from_full_message(commit_msg)

            commit = GitCommit(context, commit_msg_obj, sha=sha, author_name=name,
                               author_email=email, date=commit_date, changed_files=changed_files,
                               parents=commit_parents, is_merge_commit=commit_is_merge_commit)

            context.commits.append(commit)

        return context
696842
function uploadRequest(res, fileObject, showProgress) {
  var url = res.url;
  var expiration = res.expiration;
  var hmac = res.hmac;
  var uuid = res.uuid;
  var file = fileObject.file;
  var uid = fileObject.uid;

  var upload_url = buildUploadURL(url, uuid, expiration, hmac, file.name);

  return new Promise(function (resolve, reject) {
    reqs[uid] = _superagent2.default.put(upload_url).send(file).set({
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }).on('progress', function (e) {
      showProgress(e, fileObject);
    }).end(function (err, res) {
      delete reqs[uid];

      // throw a custom error message
      if (err) return reject(customError('uploadRequest', err));

      resolve(res);
    });
  });
}
160899
def submit(ui, repo, *pats, **opts):
	
	if codereview_disabled:
		raise hg_util.Abort(codereview_disabled)

	# We already called this on startup but sometimes Mercurial forgets.
	set_mercurial_encoding_to_utf8()

	if not opts["no_incoming"] and hg_incoming(ui, repo):
		need_sync()

	cl, err = CommandLineCL(ui, repo, pats, opts, op="submit", defaultcc=defaultcc)
	if err != "":
		raise hg_util.Abort(err)

	user = None
	if cl.copied_from:
		user = cl.copied_from
	userline = CheckContributor(ui, repo, user)
	typecheck(userline, str)

	about = ""
	if cl.reviewer:
		about += "R=" + JoinComma([CutDomain(s) for s in cl.reviewer]) + "\n"
	if opts.get('tbr'):
		tbr = SplitCommaSpace(opts.get('tbr'))
		cl.reviewer = Add(cl.reviewer, tbr)
		about += "TBR=" + JoinComma([CutDomain(s) for s in tbr]) + "\n"
	if cl.cc:
		about += "CC=" + JoinComma([CutDomain(s) for s in cl.cc]) + "\n"

	if not cl.reviewer:
		raise hg_util.Abort("no reviewers listed in CL")

	if not cl.local:
		raise hg_util.Abort("cannot submit non-local CL")

	# upload, to sync current patch and also get change number if CL is new.
	if not cl.copied_from:
		cl.Upload(ui, repo, gofmt_just_warn=True)

	# check gofmt for real; allowed upload to warn in order to save CL.
	cl.Flush(ui, repo)
	CheckFormat(ui, repo, cl.files)

	about += "%s%s\n" % (server_url_base, cl.name)

	if cl.copied_from:
		about += "\nCommitter: " + CheckContributor(ui, repo, None) + "\n"
	typecheck(about, str)

	if not cl.mailed and not cl.copied_from:		# in case this is TBR
		cl.Mail(ui, repo)

	# submit changes locally
	message = cl.desc.rstrip() + "\n\n" + about
	typecheck(message, str)

	set_status("pushing " + cl.name + " to remote server")

	if hg_outgoing(ui, repo):
		raise hg_util.Abort("local repository corrupt or out-of-phase with remote: found outgoing changes")
	
	old_heads = len(hg_heads(ui, repo).split())

	global commit_okay
	commit_okay = True
	ret = hg_commit(ui, repo, *['path:'+f for f in cl.files], message=message, user=userline)
	commit_okay = False
	if ret:
		raise hg_util.Abort("nothing changed")
	node = repo["-1"].node()
	# push to remote; if it fails for any reason, roll back
	try:
		new_heads = len(hg_heads(ui, repo).split())
		if old_heads != new_heads and not (old_heads == 0 and new_heads == 1):
			# Created new head, so we weren't up to date.
			need_sync()

		# Push changes to remote.  If it works, we're committed.  If not, roll back.
		try:
			if hg_push(ui, repo):
				raise hg_util.Abort("push error")
		except hg_error.Abort, e:
			if e.message.find("push creates new heads") >= 0:
				# Remote repository had changes we missed.
				need_sync()
			raise
		except urllib2.HTTPError, e:
			print >>sys.stderr, "pushing to remote server failed; do you have commit permissions?"
			raise
	except:
		real_rollback()
		raise

	# We're committed. Upload final patch, close review, add commit message.
	changeURL = hg_node.short(node)
	url = ui.expandpath("default")
	m = re.match("(^https?://([^@/]+@)?([^.]+)\.googlecode\.com/hg/?)" + "|" +
		"(^https?://([^@/]+@)?code\.google\.com/p/([^/.]+)(\.[^./]+)?/?)", url)
	if m:
		if m.group(1): # prj.googlecode.com/hg/ case
			changeURL = "https://code.google.com/p/%s/source/detail?r=%s" % (m.group(3), changeURL)
		elif m.group(4) and m.group(7): # code.google.com/p/prj.subrepo/ case
			changeURL = "https://code.google.com/p/%s/source/detail?r=%s&repo=%s" % (m.group(6), changeURL, m.group(7)[1:])
		elif m.group(4): # code.google.com/p/prj/ case
			changeURL = "https://code.google.com/p/%s/source/detail?r=%s" % (m.group(6), changeURL)
		else:
			print >>sys.stderr, "URL: ", url
	else:
		print >>sys.stderr, "URL: ", url
	pmsg = "*** Submitted as " + changeURL + " ***\n\n" + message

	# When posting, move reviewers to CC line,
	# so that the issue stops showing up in their "My Issues" page.
	PostMessage(ui, cl.name, pmsg, reviewers="", cc=JoinComma(cl.reviewer+cl.cc))

	if not cl.copied_from:
		EditDesc(cl.name, closed=True, private=cl.private)
	cl.Delete(ui, repo)

	c = repo[None]
	if c.branch() == releaseBranch and not c.modified() and not c.added() and not c.removed():
		ui.write("switching from %s to default branch.\n" % releaseBranch)
		err = hg_clean(repo, "default")
		if err:
			return err
	return 0