Reputation: 42389
I'm trying to generate a simple Python code that:
git
folderI have this code that works correctly under Linux:
from subprocess import call, STDOUT
import os
if call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w')) != 0:
# Not a git folder
commit = ''
else:
# Inside a git folder.: fetch latest commit
commit = subprocess.check_output(['git', 'rev-parse', '{}'.format('HEAD')])
print(commit)
but I have no way of checking if itwill work under Windows and Mac.
Does it work? Is there any way of checking/knowing this sort of things when one has no access to the other operating system?
Upvotes: 0
Views: 93
Reputation: 155
There's a method check_output in subprocess library
from subprocess import check_output
try:
# use python to parse this log for info. This is your entire last commit
logs = check_output(['git', 'log', '-1', '--stat']).decode("UTF-8")
except Exception as e:
# Do whatever you wanna do otherwise if not git repository
print(e)
Git has a command called "git log".
"-1" indicates the last commit and --stat will give you the files that were changed, commit ID, TIME ETC
then you can use python to parse this log and retrive any information you want Check this out for more info on git log
Upvotes: 1
Reputation: 76774
You don't want to run git branch
to detect whether you're in a Git repository, because you may or may not have any branches. To detect whether you're able to use Git commands, you'll want to run something like git rev-parse --git-dir
, which will exit non-zero if you're not within a Git repository.
However, there are a couple of other issues with your code. First of all, in a new repository (one created fresh with git init
), there will be a .git
directory and the above command will succeed, but HEAD
will not point anywhere. Therefore, your git rev-parse HEAD
command will fail and print HEAD
and an error.
Finally, if you want parse a revision, you should usually use --verify
so that you don't print the dummy HEAD
value on failure. So your invocation should look like git rev-parse --verify HEAD
.
Ultimately, it's up to you to figure out what you want to do in a newly initialized repository, whether that's fail or fall back to an empty string.
The behaviors I've described here are consistent across platforms; they're built into Git and well defined.
Upvotes: 2