Adrián Deccico
Adrián Deccico

Reputation: 4995

How can I simulate svnversion command in git?

From svnversion documentation:

[adrdec@opsynxvm0081 common_cpp]$ svnversion --help
usage: svnversion [OPTIONS] [WC_PATH [TRAIL_URL]]

Produce a compact 'version number' for the working copy path
WC_PATH. For example:

$ svnversion . /repos/svn/trunk
4168

The version number will be a single number if the working copy is single revision, unmodified, not switched and with an URL that matches the TRAIL_URL argument. If the working copy is unusual the version number will be more complex:

   4123:4168     mixed revision working copy
   4168M         modified working copy
   4123S         switched working copy
   4123P         partial working copy, from a sparse checkout
   4123:4168MS   mixed revision, modified, switched working copy

Upvotes: 1

Views: 1228

Answers (2)

Adrián Deccico
Adrián Deccico

Reputation: 4995

This solution detects changes in the working directory like svnversion does.

    def get_version(self, path):
            curdir = self.get_cur_dir()
            os.chdir(path)
            version = self.execute_command("git log --pretty=format:%H -n1")[self.OUT].strip()  #get the last revision and it's comment
            status = self.execute_command("git status")[self.OUT].strip()  #get the status of the working copy
            if "modified" in status or "added" in status or "deleted" in status:
                    version += self.modified
            os.chdir(curdir)
            return version


    def execute_command(self, cmd_list):
            proc = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, shell=True)
            (out, err) = proc.communicate()
            rc = proc.returncode
            return rc, out, err   

Upvotes: 3

Kyle Lacy
Kyle Lacy

Reputation: 2278

I'm not super familar with SVN, but from what I can tell, SVN identifies revisions in the form of simple numbers: 1, 2, 3... Git doesn't translate so well, since it uses SSH hashes to identify revisions (known as 'commits' in the Git world). However, getting this is still pretty simple using git log:

git log --pretty="format:%h" -n1 HEAD

This prints the currently checked-out commit in the repo (which is what HEAD is). Alternatively, you can replace HEAD in the command with master (or any other branch, for that matter) to get the last commit of that branch, rather than the one that represents your working directory. Additionally, if you need the full SHA1, replace %h above with %H. You can also read the git-log manpage for more about --pretty formats.

Additionally, you could add an alias in .gitconfig to do this anywhere. Add the following lines to ~/.gitconfig (leave off [alias] if your .gitconfig already has that section, however):

[alias]
    rev = "git log --pretty='format:%h'"

Now, any time you're in a Git repo and you want to see the current revision, just type git rev.

Upvotes: 1

Related Questions