Pygit2: Need help on how to walk on all commits in all repo's branches - python-3.x

I'd need to walk on entire repo's branches commits. I have tried this but with no success. :
for branch_name in list(repo.branches.remote):
try:
branch = repo.lookup_branch(branch_name)
ref = repo.lookup_reference(branch.name)
repo.checkout(ref)
for commit in repo.walk(branch.target, pygit2.GIT_SORT_TIME):
print(commit.id.hex)
Any help would be appreciated, thanks.

This is what I have:
def iterate_repository(dir: str) -> None:
repo = pygit2.Repository(dir)
for branch_name in list(repo.branches.remote):
branch = repo.branches.get(branch_name)
latest_commit_id = branch.target
latest_commit = repo.revparse_single(latest_commit_id.hex)
for commit in repo.walk(latest_commit.id, pygit2.GIT_SORT_TIME):
print(commit.id.hex)
Expanding from that should be relatively easy. What I do is gather statistics from files included in a commit.

Related

How to do "git add ." for a bare repo (git init -- bare) in rust with git2 or other way?

I am trying to create a bare git repo, git clone into another directory, and do the git add . & git commit & git push. However, I could not successfully complete git add . After I did git add ., I checked by git status , the target file hasn't been added.
The code I tried as follows:
let mut index = repo.index().unwrap();
&index.add_all(&["."], git2::IndexAddOption::DEFAULT, None)?;
let oid = index.write_tree()?;
let signature = git2::Signature::now("secure-crates","abc#gmail.com")?;
let tree = repo.find_tree(oid)?;
let msg :&str = "Inital Commit";
repo.commit(Some("HEAD"), &signature, &signature, &msg, &tree, &[])?;
let mut remote = repo.find_remote("origin")?;
remote.push::<&'static str>(&[], None)?;
Is anybody know how to do git add operation for a bare repo?

Python git package get tag and commit

I would like to print a git commit and the tag in my Python code.
How can I do this using git package?
When I am going to my Bitbucket I see
tag: 73-2-g46b9856
commit checksum: 46b9856
How can I retrieve this info from git package?
I have done the following:
import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
So I assume you already have the checksum you want in the sha variable.
At this point, there's a post for how to get the tags and looking for a specific tag associated with that sha in this link: Get tags of a commit
# Example code for clarity
import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
tagmap = {}
for t in repo.tags:
tagmap.setdefault(repo.commit(t), []).append(t)
tags = tagmap[repo.commit(sha)] # Warning: Your latest commit might not have a tag associated with it so this will throw an error right now.
print(tags)
Here is what solved my issue:
repo = git.Repo(search_parent_directories = True)
sha = repo.head.object.hexsha
commit_chksum = repo.git.rev_parse(sha, short = 7)
tag = subprocess.check_output(["git", "describe", "--always"]).strip().decode()

How to get the list of source repositories of a user/organisation on GitHub?

I wanna get the list of repositories of a user or an organisation on GitHub, but excluding forked, mirrored or archived repos.
Using PyGithub you can do the following to filter public repos:
from github import Github
g = Github()
user = g.get_user("<username>") # target user
repos = user.get_repos()
non_forks = []
for repo in user.get_repos():
if repo.fork is False:
non_forks.append(repo.name)
print(non_forks)
https://github.com/PyGithub/PyGithub
is a python library for interacting with the Github API. From the readme:
from github import Github
# First create a Github instance:
# using username and password
g = Github("user", "password")
# or using an access token
g = Github("access_token")
# Github Enterprise with custom hostname
g = Github(base_url="https://{hostname}/api/v3", login_or_token="access_token")
# Then play with your Github objects:
for repo in g.get_user().get_repos():
print(repo.name)
The Repository object has properties that allow checking whether the repo is archived, a fork, or a mirror:
repo.archived // is repo archived?
repo.fork // is repo a fork?
repo.mirror_url // return the url of the mirrored repo, if applicable
I've written a small script that does the job perfectly
#!/usr/bin/env python3.9
#-*- coding: utf-8 -*-
import readline, sys, os, requests
import click
from github import Github
g = Github()
def userexists(username):
addr = "https://api.github.com/users/" + username
response = requests.get(addr)
if response.status_code == 404:
return False
else:
if response.status_code == 200:
return True
def printrepos(repos):
original_repos = []
for repo in repos:
if repo.fork is False and repo.archived is False:
print(repo.clone_url)
#click.command()
#click.argument('username')
def main(username):
if userexists(username):
user = g.get_user(username)
repos = user.get_repos()
printrepos(repos)
else:
print("Username doesn't exist")
if __name__ == "__main__":
main()

Git Aliases not working

I have specified certain aliases in the .gitconfig file located in /home/myUser/.gitconfig as below (I am pasting the entire file settings):
[user]
name = myName
email = myEmail#email.com
[core]
autocrlf = true
safecrlf = true
[push]
default = simple
[alias]
co = checkout
ci = commit
st = status
br = branch
hist = log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short
type = cat-file -t
dump = cat-file -p
I am having a problem specifically with that hist alias. Sometimes I get the desired output when y execute de git hist (I mean the format specified in the .gitconfig for the hist alias); and some other times it is not recognized. I tried restarting the terminal an the same happens: sometimes it works and some other times don't.
Would appreciate any help, thanks a lot!

How can I add the build version to a scons build

At the moment I'm using some magic to get the current git revision into my scons builds.. I just grab the version a stick it into CPPDEFINES.
It works quite nicely ... until the version changes and scons wants to rebuild everything, rather than just the files that have changed - becasue the define that all files use has changed.
Ideally I'd generate a file using a custom builder called git_version.cpp and
just have a function in there that returns the right tag. That way only that one file would be rebuilt.
Now I'm sure I've seen a tutorial showing exactly how to do this .. but I can't seem to track it down. And I find the custom builder stuff a little odd in scons...
So any pointers would be appreciated...
Anyway just for reference this is what I'm currently doing:
# Lets get the version from git
# first get the base version
git_sha = subprocess.Popen(["git","rev-parse","--short=10","HEAD"], stdout=subprocess.PIPE ).communicate()[0].strip()
p1 = subprocess.Popen(["git", "status"], stdout=subprocess.PIPE )
p2 = subprocess.Popen(["grep", "Changed but not updated\\|Changes to be committed"], stdin=p1.stdout,stdout=subprocess.PIPE)
result = p2.communicate()[0].strip()
if result!="":
git_sha += "[MOD]"
print "Building version %s"%git_sha
env = Environment()
env.Append( CPPDEFINES={'GITSHAMOD':'"\\"%s\\""'%git_sha} )
You don't need a custom Builder since this is just one file. You can use a function (attached to the target version file as an Action) to generate your version file. In the example code below, I've already computed the version and put it into an environment variable. You could do the same, or you could put your code that makes git calls in the version_action function.
version_build_template="""/*
* This file is automatically generated by the build process
* DO NOT EDIT!
*/
const char VERSION_STRING[] = "%s";
const char* getVersionString() { return VERSION_STRING; }
"""
def version_action(target, source, env):
"""
Generate the version file with the current version in it
"""
contents = version_build_template % (env['VERSION'].toString())
fd = open(target[0].path, 'w')
fd.write(contents)
fd.close()
return 0
build_version = env.Command('version.build.cpp', [], Action(version_action))
env.AlwaysBuild(build_version)

Resources