Discovering git branch from python script - python

I have a python script.
I need to access the name of the git branch from which I'm running the python script, through python, during runtime.
Is there a way to do this?
Edit:
os.system("git rev-parse --abbrev-ref HEAD") outputs to the cli, I don't see how I would get access to it from python...
I would like to have sth like git_branch = <python commands>

You could use GitPython, something like the following:
>>> import git
>>> import os
>>> git_branch = git.Repo(os.getcwd()).active_branch.name
>>> git_branch
'master'
Otherwise, as already pointed out by Yevhen Kuzmovych in the comments, you could use PyGit.

Related

Print bash script output in Python

I have a Python code that will run a script file.The script file will output the version tag of specific git repository.
My script file named 'start.sh' is as follows:
#!/bin/sh
git clone https://xxxxxxxxxx:x-oauth-basic#github.com/xxxxxxx/xxxxx.git
cd xxxxxxxx
git config --global user.email "xxxxxxxx"
git config --global user.name "xxxxxxxxx"
IMAGE_TAG=`echo \`git describe --tags\``
echo $IMAGE_TAG
My Python code is as follows:
import os
git_tag = os.popen('sh start.sh')
print(git_tag)
When I run the script file separately, it will return me the git tag. But, Whenever I try to print it in the Python code, it's not working.
How can I solve this issue?
Since you are using Python anyway, you could think of using GitPython as an alternative. You can list all your tags with:
from git import Repo
repo = Repo("path/to/repo")
print(repo.tags)
Try like this
from subprocess import check_output
out = check_output(['sh', 'start.sh'])
print(out)
According to python's documentation, os.popen() function has been deprecated since version 2.6. You might want to use subprocess module.
P.S: I wanted to comment but couldn't hence this answer.
For python3-X:
from subprocess
git_tag = subprocess.run(['sh', 'start.sh'], capture_output=True, text=True)
print(git_tag.stdout)

Shell command not found in python script

I source a dotcshrc file in my python script with :os.system(‘/bin/csh dotcshrc’) and it works,but when I want to use the command I have just put into the env by the source command,like os.system(‘ikvalidate mycase ‘),linux complaints:command not found.
But when I do it all by hand,everything go well.
Where is problem?
If you have a command in linux like ls and you want to use it in your python code do like this:
import os
ls = lambda : os.system('ls')
# This effectively turns that command into a python function.
ls() # skadoosh!
Output is :
FileManip.py Oscar
MySafety PROJECT DOCS
GooSpace Pg Admin
l1_2014 PlatformMavenRepo
l1_2015 R
l1_201617 R64
l2_2014 Resources
os.system runs each command in its own isolated environment. If you are sourcing something in an os.system call, subsequent calls will not see that because they are starting with a fresh shell environment. If you have dependencies like the above, you might be able to combine it into one call:
os.system(‘/bin/csh "dotcshrc; ikvalidate mycase"’)

Git diff call in pre-commit throws "fatal: unable to read [SHA1]"

I am working in windows and attempting to run a git diff command in the pre-commit script (Python) of a repository. My Python call looks like this:
repo_dir = 'D:/git/current_uic/src/gtc/resource'
cmd = ['diff', '--name-only']
print(Popen(['git', '--git-dir={}'.format(repo_dir + '/.git'),
'--work-tree={}'.format(repo_dir)] + cmd,
stdin=PIPE, stdout=PIPE).communicate())
Whenever I go to commit in the "D:/git/current_uic/src/gtc" repo, I get the following:
fatal: unable to read 6ff96bd371691b9e93520e133ebc4d84c74cd0f6
Note that this is a pre-commit hook for the 'D:/git/current_uic/src/gtc' repository and that 'D:/git/current_uic/src/gtc/resource' is a submodule of 'D:/git/current_uic/src/gtc'. Also note that if I pop open Git bash and run the following:
git --git-dir=D:/git/current_uic/src/gtc/resource/.git
--work-tree=D:/git/current_uic/src/gtc/resource diff --name-only
or if I just run the script straight from Git bash I get exactly what I want, regardless of working directory.
Any ideas as to what is going on here?
The Problem:
Upon running a hook, Git sets some environment variables that are accessible by the hook script. The problem is that Git itself uses these environment variables, and the normal way in which Git sets/uses them seems to be overridden by the values set when the hook gets fired off. In this particular instance, the environment variable GIT_INDEX_FILE has been set to the path to the index file corresponding to the repository which had called the hook (D:/git/current_uic/src/.git/modules/gtc/index), causing a mismatch between the (incorrect) index and the (correct) change tree.
The Fix:
In the hook script, set the environment variable GIT_INDEX_FILE to the correct value before making any git calls. In this case, you could do the following:
set GIT_INDEX_FILE=D:/git/current_uic/src/.git/modules/gtc/modules/resource/index
git --git-dir=D:/git/current_uic/src/gtc/resource/.git
--work-tree=D:/git/current_uic/src/gtc/resource diff --name-only
Additional Info
More information about these Git environment variables and which hooks set them can be found here.
Got exactly same issue but using gitpython.
I solved it like this:
repo = git.Repo()
for submodule in repo.submodules:
back_index = os.getenv('GIT_INDEX_FILE')
os.environ['GIT_INDEX_FILE'] = submodule.module().index.path
commit = submodule.module().head.commit
print([item.a_path for item in commit.diff(None)])
os.environ['GIT_INDEX_FILE'] = back_index

How to execute git command in a identified path?

I want to execute git command in python program.
I have tried
os.system("git-command")
As we know, git command can be executed correctly only in the directories which contains repositories. I have tried to print current path and this path is not what I hope for, it does not contains repositories.
Now my question is how to execute git command in a identified path.
Use the subprocess module; pick one of the functions that suits your needs (based on what output you need). The functions all take a cwd argument that lets you specify the directory to operate in:
import subprocess
output = subprocess.check_output(['git', 'status'], cwd='/path/to/git/workingdir')
Using GitPython:
from git import *
repo = Repo("/path/to/repo")
git = repo.git
print git.status()

Get git like option completion in python program

When I type
$ git br<tab>
Git automatically completes the option into this:
$ git branch
Suppose I want to imitate this functionality in my fictitious program say.py:
#!/usr/bin/python
import sys
args = ['morning', 'night']
if sys.argv[1] == args[0]:
print "Mr. Tacha Vinci! Good morning!"
elif sys.argv[1] == args[1]:
print "Mr. Tacha Vinci, sweet dreams..."
Such that when I do:
$ say.py mor<tab>
I get:
$ say.py morning
It's not Git that does the completion, it's your shell -- most probably Bash, and specifically by way of readline. (The link is to the Python bindings for this library, which is what you would use to provide completion inside a running Python program. To create Bash completions, look at e.g. the ABS intro.)

Categories