def sync_handler(fork_from: str, from_sha: str, repo_name: str, ticket_id: int, pr_url: str): output_path = '{}.txt'.format(pr_url.split('/', 3)[3].rsplit('/', 2)[0]) output_path = os.path.join(WORK_DIR, output_path.replace('/', '_')) work_tree = os.path.join(WORK_DIR, fork_from) parent_path = os.path.dirname(work_tree) if not os.path.exists(parent_path): os.makedirs(parent_path) if not os.path.exists(work_tree): repo = clone_repository( '{0}{1}.git'.format(GITHUB_URL, fork_from), work_tree) else: repo = Repository(work_tree) remote_name = repo_name.split('/')[0] update_remote(work_tree, repo, repo_name, remote_name) if remote_name == 'origin': commit = repo.revparse_single(from_sha) repo.checkout_tree(commit, strategy=GIT_CHECKOUT_FORCE) else: ref_name = 'refs/pull/{0}/head'.format(ticket_id) try: repo.create_reference(ref_name, from_sha) except ValueError: pass ref = repo.lookup_reference(ref_name) repo.checkout(ref, strategy=GIT_CHECKOUT_FORCE) cwd = os.getcwd() os.chdir(work_tree) subprocess.call( '{} . --output-file={}'.format(FLAKE8_EXECUTABLE, output_path), shell=True) os.chdir(cwd) return output_path
def sync(repo: pygit2.Repository, branch_name: str) -> None: """ Tries to update the `branch_name` branch of the `repo` repo to the latest upstream branch state. If the branch is up to date, does nothing. If the branch can be fast-forwarded, resets to the upstream. Otherwise, fails with an error. """ branch = repo.branches.local[branch_name] if not branch.is_head(): raise ValueError(branch) try: remote = repo.remotes['origin'] except KeyError: return remote.fetch(callbacks=RemoteCallbacks()) upstream_branch = branch.upstream if not upstream_branch: return merge_state, _ = repo.merge_analysis(upstream_branch.target, branch.name) if merge_state & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE: return if not (merge_state & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD): raise ValueError(branch) repo.reset(upstream_branch.target, pygit2.GIT_RESET_HARD) repo.checkout(refname=branch)
def finish(repo: pygit2.Repository, branch_name: str, message: str) -> None: master = repo.branches.local['master'] branch = repo.branches.local[branch_name] if not branch.is_head(): raise ValueError(branch) merge_state, _ = repo.merge_analysis(branch.target, master.name) if merge_state & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE: repo.checkout(refname=master) return if not (merge_state & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD): raise ValueError(branch) index: pygit2.Index = repo.merge_trees(ancestor=master, ours=master, theirs=branch) tree = index.write_tree(repo=repo) repo.create_commit( master.name, repo.default_signature, repo.default_signature, message, tree, [master.target], ) repo.checkout(refname=master) branch.delete()
def makeInstanceBranch(repo: Repository, name: str) -> None: # headCommit = repo.revparse_single('origin/master') headCommit = repo.revparse_single('HEAD') # branch = repo.creare_branch(name, headCommit, force = True) print('creating branch ' + name) branch = repo.branches.local.create(name, headCommit, force=True) print('checkouting to ' + name) repo.checkout(branch)
def getHist(repo): base = Repository(repo) base.checkout('HEAD') history = [] for commit in base.walk(base.head.target, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE): history.append(commit) return history
def new_switch_branch(working_dir, branch_name): repo = Repository(working_dir + '.git') commit = repo.revparse_single('HEAD') new_branch = repo.branches.create(branch_name, commit, force=False) print 'refs/heads/' + new_branch.branch_name print working_dir print 'ddddddddddddddddd' repo.checkout('refs/heads/' + new_branch.branch_name) print('switch to a new branch: ' + branch_name)
def finish(repo: pygit2.Repository, branch_name: str, message: str) -> None: master = repo.branches.local['master'] branch = repo.branches.local[branch_name] if not branch.is_head(): raise ValueError(branch) merge_squash(repo=repo, ours_branch=master, theirs_branch=branch, message=message) repo.checkout(refname=master) branch.delete()
def switch(repo: pygit2.Repository, ref: pygit2.Reference) -> None: stashed = False if not is_clean(repo=repo): repo.stash(stasher=repo.default_signature) stashed = True repo.checkout(refname=ref) if stashed: repo.stash_pop()
def test_003_init_in_branch(data_dir: pathlib.Path, root_repo: pygit2.Repository) -> None: dev_branch = root_repo.branches.local.create( name='dev', commit=next(root_repo.walk(root_repo.head.target))) root_repo.checkout(refname=dev_branch, strategy=pygit2.GIT_CHECKOUT_FORCE) core.init() assert config.Config.load( path=pathlib.Path('wok.yml')) == config.Config.load(path=data_dir / '003_wok.yml')
def commitInfo(repo, history): # GET A REPO ON DISK base = Repository(repo) base.checkout('HEAD') # MOVE THROUGH THE SYSTEM HISTORY FROM NEWEST TO OLDEST COMMIT for commit in history: print 'Date/Time: ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(commit.commit_time)) print 'Comment Hex: ' + commit.hex print 'Message: ' + commit.message.rstrip('\n') print ''
def test_003_init_in_branch( data_dir: pathlib.Path, root_repo: pygit2.Repository ) -> None: dev_branch = root_repo.branches.local.create( name='dev', commit=root_repo.head.peel() ) root_repo.checkout(refname=dev_branch) core.init() assert config.Config.load(path=pathlib.Path('wok.yml')) == config.Config.load( path=data_dir / '003_wok.yml' )
class Repo(object): def __init__(self, path="", branch="develop"): self.path = path if path else os.getcwd() # Retrieve the repo if its already defined try: self.repo = Repository(self.path) # This is a little hacky, but we need a git command interface to do # certain things self.pygitrepo = git.Repo(self.repo.path) self.git = self.pygitrepo.git self.currentBranch = self.repo.lookup_branch(self.repo.head.shorthand) self._user = self.repo.default_signature except KeyError: self.repo = None self.currentBranch = None self._user = None # TODO Handle this another way self.branch = branch @property def user(self): if not self._user and self.repo: self._user = self.repo.default_signature return self._user def clone(self, repourl): self.repo = clone_repository( repourl, self.path, checkout_branch=self.branch ) def checkoutBranch(self, name): # TODO check if a branch of this name exists developBranch = self.repo.lookup_branch("develop") self.repo.checkout(developBranch) self.currentBranch = self.repo.create_branch( name, self.repo.head.get_object() ) self.repo.checkout(self.currentBranch) def merge(self, branch, delete=False, push=False): pass def release(self): # Checkout the release branch # Need some way to control versioning # Internal versioning pass
class GitRepo: def __init__(self, repo_path): self.repo = Repository(repo_path) def checkout_by(self, commit_id): ref = 'refs/tags/t-%s' % commit_id if self.repo.references.get(ref) is None: self.repo.create_reference(ref, commit_id) self.repo.checkout(ref) self.repo.references[ref].delete() def master(self): branch = self.repo.lookup_branch('master') self.repo.checkout(branch) def get_all_commit_id(self): self.master() return self.repo.walk(self.repo.head.target, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE)
class Repo: def __init__(self, config): self.repo = Repository(config.repository_path) self.config = config self.lock = threading.Lock() master_ref = self.repo.lookup_reference("refs/heads/master") self.repo.checkout(master_ref) self.cred = MyRemoteCallback(config) def lock_patch_work(self, id): self.lock.acquire(True) try: #first lets update master self.repo.remotes[self.config.repository_patch_origin].fetch() #get the latest master master_ref = self.repo.branches.remote[ self.config.repository_patch_origin + '/master'] #In case the branch exists, delete it if id in self.repo.branches: self.repo.branches.delete(id) #create a new branch local = self.repo.branches.local.create(id, master_ref.peel()) #finally switch over self.repo.checkout(local) except Exception as e: self.lock.release() raise e def unlock_patch_work(self, id): try: self.repo.remotes[self.config.repository_patch_destination].push( ["+refs/heads/" + id], callbacks=self.cred) master_ref = self.repo.branches.remote[ self.config.repository_patch_origin + '/master'] self.repo.checkout(master_ref) finally: self.lock.release() def dispatch(self, id): #FIXME also delete on the remote self.repo.branches.delete(id) def fetch_commit_message(self, chash): obj = self.repo.get(chash) return obj.message
def get_folders(projectCode, branch, requested_path): """ :projectCode: идентификатор проекта :branch: необходимая ветка :folderPath: GET параметр путь к папке, получить через request.args.get('folderPath') **Response:** ``` { "list": [ { "name": "myfile.md", "full_path": "/folder/myfile.md", "parent": "/folder/" } ], "_meta": { "per-page": 12, "page": 12, "total-pages": 12 } } ``` """ # Get path requested_path = "/" + requested_path # print(requested_path, file=sys.stderr) # Set folder folder = config["REPO_FOLDER"] + projectCode if not os.path.isdir(folder): # TODO: throw exception return json.dumps({"error": 404, "description": "Project not found"}) # Checkout branch repo = Repository(folder) branch = repo.lookup_branch('master') ref = repo.lookup_reference(branch.name) repo.checkout(ref) # TODO: exception if branch not exists # Get files it path list = [] for root, dirs, files in os.walk(folder + requested_path): for filename in files: if root == folder + "/": list.append({ "name": filename, "full_path": "/" + filename, "parent": "/" }) else: list.append({ "name": filename, "full_path": root[len(folder):] + "/" + filename, "parent": root[len(folder):] + "/" }) response = { "list": list, "_meta": { "per-page": 99999, # TODO: make pagination? "page": 1, "total-pages": 1 } } return json.dumps(response)
def process(repo, history): # GET A REPO ON DISK base = Repository(repo) base.checkout('HEAD') file_xsmall = 0 file_small = 0 file_medium = 0 file_large = 0 file_xlarge = 0 hunk_xsmall = 0 hunk_small = 0 hunk_medium = 0 hunk_large = 0 hunk_xlarge = 0 line_xsmall = 0 line_small = 0 line_medium = 0 line_large = 0 line_xlarge = 0 i = 0 while i < len(history) - 1: print '\rDiff#: ' + str(i + 1) + ' of ' + str(len(history)-1), t0 = base.revparse_single(history[i].hex) t1 = base.revparse_single(history[i+1].hex) try: diff = base.diff(t0,t1) except ValueError: print '' print 'Value Error' print '' i += 1 continue files = [p for p in diff] if len(files) == 1: file_xsmall += 1 if len(files) >= 2 and len(files) <= 4: file_small += 1 if len(files) >= 5 and len(files) <= 7: file_medium += 1 if len(files) >= 8 and len(files) <= 10: file_large += 1 if len(files) >= 11: file_xlarge += 1 hunksInCommit = 0 linesInCommit = 0 for modfile in files: hunksInCommit += len(modfile.hunks) for hunk in modfile.hunks: for line in hunk.lines: if line[0] == '-' or line[0] == '+': linesInCommit += 1 if hunksInCommit <= 1: hunk_xsmall += 1 if hunksInCommit >= 2 and hunksInCommit <= 8: hunk_small += 1 if hunksInCommit >= 9 and hunksInCommit <= 17: hunk_medium += 1 if hunksInCommit >= 18 and hunksInCommit <= 26: hunk_large += 1 if hunksInCommit >= 27: hunk_xlarge += 1 if linesInCommit <= 5: line_xsmall += 1 if linesInCommit >= 6 and linesInCommit <= 46: line_small += 1 if linesInCommit >= 47 and linesInCommit <= 106: line_medium += 1 if linesInCommit >= 107 and linesInCommit <= 166: line_large += 1 if linesInCommit >= 167: line_xlarge += 1 i += 1 print '' ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('-%Y-%m-%d.%H.%M.%S') name = repo.replace('/.git', '') + st + '.txt' output = open(name,'w') output.write('--------- ' + repo + ' ----------' + '\n') output.write('Number of Lines Modified:' + '\n') output.write('x-small: ' + str( + line_xsmall) + '\n') output.write('small: ' + str(line_small) + '\n') output.write('medium: ' + str(line_medium) + '\n') output.write('large: ' + str(line_large) + '\n') output.write('x-large: ' + str(line_xlarge) + '\n') output.write('Number of Files Modified:' + '\n') output.write('x-small: ' + str(file_xsmall) + '\n') output.write('small: ' + str(file_small) + '\n') output.write('medium: ' + str(file_medium) + '\n') output.write('large: ' + str(file_large) + '\n') output.write('x-large: ' + str(file_xlarge) + '\n') output.write('Number of Hunks Per Commit' + '\n') output.write('x-small: ' + str(hunk_xsmall) + '\n') output.write('small: ' + str(hunk_small) + '\n') output.write('medium: ' + str(hunk_medium) + '\n') output.write('large: ' + str(hunk_large) + '\n') output.write('x-large: ' + str(hunk_xlarge) + '\n') output.close()
class prototype: repo = "" # Path to a given repository name = "" # Name of a repository base = "" # Repository as defined in pygit2 # Initialization. Clones the given repository, placing it in the current directory, # and changes to the repository directory. def init(self, repository): self.repo = repository # Use regular expressions to match the last instance of a forward slash # followed by the name of the repository, which we wish to extract, followed # by ".git". m = re.search('/([^/]+).git$', repository) if m: self.name = m.group(1) if not os.path.isdir(self.name): os.system('git clone ' + self.repo) # Get the repository from GitHub self.base = Repository(self.name) self.base.checkout('HEAD') # Destruction. Remove the given repository from memory. def destroy(self): os.system('cd ' + self.name) os.system('rm -rf ' + self.name) # Get total LOC by given repository. def totalRepoLOC(self): loc = countDirLOC(self.name) return loc # Get total commits by a given repository def totalRepoCommits(self): commits = 0 for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL): commits = commits + 1 return commits # Get a list of LOC changed per commit def locPerCommit(self): loc = [] oldPath = os.popen('pwd') os.chdir(self.name) sha1 = 0 sha2 = 0 start = 1 total = self.totalRepoCommits() # For each commit within the repository for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL): print '\r', start, '/', total, start += 1 # Based on the SHA, use git to show the patch for that commit sha1 = sha2 sha2 = commit.hex if sha1 != 0: p = os.popen('git diff --shortstat ' + sha1 + ' ' + sha2) line = p.readline() # line contains "# file changed, # insertions(+), # deletions(-) # Use regular expressions to find the number of additions and deletions. # Additions are found after ", " and before " insertion". Deletions are # found after "(+), " and before " deletion". m = re.search(', (.*) insertion', line) additions = 0 deletions = 0 if m: additions = m.group(1) m = re.search('\(\+\), (.*) deletion', line) if m: deletions = m.group(1) # Get the total and append to array modifications = int(additions) + int(deletions) loc.append(modifications) os.chdir('..') return loc # Get a list containing the total number of line additions and deletions (including # whitespace and comments) contained within each hunk that was changed over t def locPerHunk(self): loc = [] history = [] # Get the hex number for each commit within the repository for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL): sha = commit.hex history.append(sha) # Compare each revision in the history of the repository with the previous rev. i = 0 while i < len(history) - 1: t0 = self.base.revparse_single(history[i]) t1 = self.base.revparse_single(history[i+1]) diff = self.base.diff(t0,t1) patches = [p for p in diff] for patch in patches: for hunk in patch.hunks: # Check the first character in each hunk line. Only those that have # been modified will contain a '+' (insertion) or '-' (deletion) totalModifications = 0 for line in hunk.lines: if line[0] == '-' or line[0] == '+': totalModifications +=1 loc.append(totalModifications) i += 1 return loc # Get the total number of lines contained within a hunk, including additions, deletions, # and surrounding non-changed lines def locInHunk(self): loc = [] history = [] # Get the hex number for each commit within the repository for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL): sha = commit.hex history.append(sha) # Compare each revision in the history of the repository with the previous rev. i = 0 while i < len(history) - 1: t0 = self.base.revparse_single(history[i]) t1 = self.base.revparse_single(history[i+1]) diff = self.base.diff(t0,t1) patches = [p for p in diff] for patch in patches: for hunk in patch.hunks: totalLines = 0 for line in hunk.lines: totalLines += 1 loc.append(totalLines) i += 1 return loc # Perform a diff between all commits starting from oldest to newest # and compile temp files comprised of only modified lines. # Run cloc on temp files to get sloc for each diff set. def slocPerDiff(self): # Storage for commit history hashes history = [] # Store all slocs slocPerDiffs = [] # Move through the system history from newest to oldest commit for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE): history.append(commit) i = 0 while i < len(history) - 2: sloc = 0 t0 = self.base.revparse_single(history[i].hex) t1 = self.base.revparse_single(history[i+1].hex) try: diff = self.base.diff(t0,t1) except ValueError: print "Caught value error." i += 1 continue patches = [p for p in diff] for patch in patches: print patch.new_file_path hunkfile = open("tmp", 'w') for hunk in patch.hunks: totesLines = 0 totesMods = 0 for line in hunk.lines: totesLines += 1 if line[0] == '-' or line[0] == '+': totesMods += 1 hunkfile.write(line[1]) hunkfile.close() output = subprocess.Popen('cloc ' + patch.new_file_path + ' --by-file --csv', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) start = False for line in output.stdout.readlines(): if line[0] == 'l': start = True continue if start: temp = line.split(',') sloc += int(temp[4].replace('\n', '')) retval = output.wait() os.remove("tmp") i += 1 slocPerDiffs.append(int(sloc)) return slocPerDiffs # Get a list containing the number of hunks changed per commit def hunksPerCommit(self): hunks = [] history = [] start = 1 total = self.totalRepoCommits() # Get the hex number for each commit within the repository for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL): sha = commit.hex history.append(sha) # Compare each revision in the history of the repository with the previous rev. i = 0 while i < len(history) - 1: print '\r', start, '/', total, start += 1 t0 = self.base.revparse_single(history[i]) t1 = self.base.revparse_single(history[i+1]) try: diff = self.base.diff(t0,t1) except ValueError: print "Caught value error." i += 1 continue patches = [p for p in diff] for patch in patches: hunks.append(len(patch.hunks)) i += 1 return hunks # Get a list of the number of files changed per commit def filesPerCommit(self): files = [] oldPath = os.popen('pwd') os.chdir(self.name) sha1 = 0 sha2 = 0 start = 1 total = self.totalRepoCommits() # For each commit within the repository for commit in self.base.walk(self.base.head.target, GIT_SORT_TOPOLOGICAL): print '\r', start, '/', total, start += 1 # Based on the SHA, use git to show the patch for that commit sha1 = sha2 sha2 = commit.hex if sha1 != 0: p = os.popen('git diff --shortstat ' + sha1 + ' ' + sha2) line = p.readline() # line contains "# file changed, # insertions(+), # deletions(-) # Use regular expressions to find the number of files modified, which # are contained first on the line followed by " file" m = re.search(' (.*) file', line) if m: numFilesChanged = int(m.group(1)) files.append(numFilesChanged) os.chdir('..') return files # Print out all stats for the repository def printStats(self): f = open(self.name + '-results.txt', 'w') f.write(("-----------" + self.name + "-----------\n")) # Stats on entire repository repoLOC = self.totalRepoLOC() repoCommits = self.totalRepoCommits() # Lists by commit locPerCommit = self.locPerCommit() #slocPerDiff = self.slocPerDiff() hunksPerCommit = self.hunksPerCommit() filesPerCommit = self.filesPerCommit() # Stats for LOC xsmall = 0 small = 0 medium = 0 large = 0 xlarge = 0 for item in locPerCommit: if (item >= 0 and item <= 5): xsmall += 1 if (item >= 6 and item <= 46): small += 1 if (item >= 47 and item <= 106): medium += 1 if (item >= 107 and item <= 166): large += 1 if (item >= 167): xlarge += 1 f.write("Number of Modified Lines:\n") f.write("x-small: " + str(xsmall) + "\n") f.write("small: " + str(small) + "\n") f.write("medium: " + str(medium) + "\n") f.write("large: " + str(large) + "\n") f.write("x-large: " + str(xlarge) + "\n") ''' # Stats for SLOC xsmall = 0 small = 0 medium = 0 large = 0 xlarge = 0 for item in slocPerDiff: if (item >= 0 and item <= 5): xsmall += 1 if (item >= 6 and item <= 46): small += 1 if (item >= 47 and item <= 106): medium += 1 if (item >= 107 and item <= 166): large += 1 if (item >= 167): xlarge += 1 f.write("Number of Modified SLOC: \n") f.write("x-small: " + str(xsmall) + "\n") f.write("small: " + str(small) + "\n") f.write("medium: " + str(medium) + "\n") f.write("large: " + str(large) + "\n") f.write("x-large: " + str(xlarge) + "\n") ''' # Print stats for modified files xsmall = 0 small = 0 medium = 0 large = 0 xlarge = 0 for item in filesPerCommit: if (item == 1): xsmall += 1 if (item >= 2 and item <= 4): small += 1 if (item >= 5 and item <= 7): medium += 1 if (item >= 8 and item <= 10): large += 1 if (item >= 11): xlarge += 1 f.write("Number of modified files: \n") f.write("x-small: " + str(xsmall) + "\n") f.write("small: " + str(small) + "\n") f.write("medium: " + str(medium) + "\n") f.write("large: " + str(large) + "\n") f.write("x-large: " + str(xlarge) + "\n") # Prints stats for hunks xsmall = 0 small = 0 medium = 0 large = 0 xlarge = 0 for item in hunksPerCommit: if (item >= 0 and item <= 1): xsmall += 1 if (item >= 2 and item <= 8): small += 1 if (item >= 9 and item <= 17): medium += 1 if (item >= 18 and item <= 26): large += 1 if (item >= 27): xlarge += 1 f.write("Number of hunks per commit: \n") f.write("x-small: " + str(xsmall) + "\n") f.write("small: " + str(small) + "\n") f.write("medium: " + str(medium) + "\n") f.write("large: " + str(large) + "\n") f.write("x-large: " + str(xlarge) + "\n") f.close()
from pygit2 import clone_repository from pygit2 import Repository from pygit2 import GIT_SORT_TOPOLOGICAL, GIT_SORT_REVERSE, GIT_CHECKOUT_SAFE_CREATE import os import sh import subprocess import time repo_url = 'https://github.com/octocat/Spoon-Knife.git' repo_path = 'spoon-knife' if not os.path.exists(repo_path): repo = clone_repository(repo_url, repo_path) base = Repository(repo_path + '/.git') base.checkout('HEAD') history = [] # Display Commits Newest to Oldest for commit in base.walk(base.head.target, GIT_SORT_TOPOLOGICAL): #print commit.hex #print commit.message print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(commit.commit_time)) history.append(commit.hex) #print '-----------------------------------------------------------' # Display Commits Oldest to Newest for commit in base.walk(base.head.target, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE): pass # print commit.hex
def switch_branch(working_dir, branch_name): repo = Repository(working_dir + '.git') print('switch to: ' + branch_name) branch = repo.branches[branch_name] repo.checkout('refs/heads/' + branch.branch_name)
config = repo.config remote_url = repo.remotes[args.remote].url pass_path = None for glob in credentials_mapping.keys(): if fnmatch.fnmatch(remote_url, glob): pass_path = credentials_mapping[glob]["target"] # FIXME: user identity (name + email) is not always set at repo level # that said, we need a SPOT for git identities as used/implemented # in git-identity emacs package source_branch_name = args.update_source_branch if args.update_source_branch != "" else get_active_branch( repo) remote = resolve_remote(repo, args.remote) if not remote: log_error(f"cannot find remote '{args.remote}'") sys.exit(1) if args.update_op == "fetch": remote.fetch(refspecs=[f"refs/heads/*:refs/heads/*"]) elif args.update_op == "merge": source_branch_head = repo.references[source_branch_name].resolve().target repo.merge(source_branch_head) elif args.update_op == "rebase": source_branch = repo.lookup_branch(source_branch_name, GIT_BRANCH_REMOTE) dest_branch = repo.lookup_branch(get_active_branch(repo)) dest_branch.set_target(source_branch.target) # Fast-forwarding with set_target() leaves the index and the working tree # in their old state. That's why we need to checkout() and reset() repo.checkout(f"refs/heads/{dest_branch.name}") repo.reset(dest_branch.target, GIT_RESET_HARD)
def _checkout_commit(self, repo: pygit2.Repository, commit): repo.create_reference(DataExtractor.WORKING_TAG_REFNAME, commit.id) repo.checkout(DataExtractor.WORKING_TAG_REFNAME) repo.lookup_reference(DataExtractor.WORKING_TAG_REFNAME).delete()
if not is_repo(os.getcwd()): log_error("Not a git repo") sys.exit(1) repo = Repository(os.getcwd() + "/.git") config = repo.config remote_url = repo.remotes[args.remote].url pass_path = None for glob in credentials_mapping.keys(): if fnmatch.fnmatch(remote_url, glob): pass_path = credentials_mapping[glob]["target"] if args.tags_sync: remote = resolve_remote(repo, args.remote) if not remote: log_error(f"cannot find remote '{args.remote}'") sys.exit(1) remote.fetch(refspecs=["refs/tags/*:refs/tags/*"]) remote.push(specs=collect_tags(repo), callbacks=build_auth_callbacks(repo, pass_path)) elif args.tags_checkout: tag_name = args.tags_name if is_interactive: tag_name = get_selection_rofi(collect_tags(repo), "") if not tag_name: log_error("No tag to checkout") sys.exit(1) repo.checkout(tag_name)
"--finish", help="full commit id to end with", type=str) args = parser.parse_args() if args.path: # verify path existence if path.exists(args.path) and args.path.endswith('.git'): proj_path = args.path[:-4] repo = Repository(args.path) if args.branch and args.branch in list(repo.branches.local): branch = repo.lookup_branch( list(repo.branches.local)[list(repo.branches.local).index( args.branch)]) ref = repo.lookup_reference(branch.name) repo.checkout(ref) print('Current Branch:') print(repo.head.shorthand) if args.list: pprint.pprint(get_commit_id_list(args.finish, args.start)) if args.start and args.finish: pprint.pprint( git_perform_analysis(args.start, args.finish, proj_path)) else: # pyprint avaliable branches print('Specify one of local avaliable local branches:') print(*list(repo.branches.local), sep="\n") else: print('path ether not exis or it\'s not a repo') exit()