ypicard
ypicard

Reputation: 3693

How to get access to git commit variables (python)?

I am new to git, and am starting to understand how it works.

I am trying to create a personal pre-commit hook to train myself, and I would like to get access to variables such as the username of the committer, number of files committed, their names, titles etc.

How can I do that?

I read this thread https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables and I know some of the variables that interest me exist, but as I said, my problem is not knowing how to access them.

Oh, and I am writing my hooks in python.

Upvotes: 0

Views: 592

Answers (1)

Amadan
Amadan

Reputation: 198314

The variables in that article are all configuration variables that you provide to git, not variables git provides to you. Unless you have set them yourself, they will be empty.

pre-commit is not provided any arguments.

The name of the committer is obviously the user who is executing the command:

import getpass
username = getpass.getuser()

To see the files that would be committed (and what action would be taken on each), use git diff --name-status:

import subprocess
diffs = subprocess.check_output(['git', 'diff', '--name-status'],
                                stderr=subprocess.STDOUT)
diff_dict = dict(list(reversed(item.split('\t')))
                 for item in diffs.split('\n') if item != '')

I don't know what you mean by "titles".

Upvotes: 2

Related Questions