How can I get the Git build number and embed it in a file?
Asked Answered
S

6

17

I want to introduce a versioning constant grabbed from the version in Git. I know how to do this -- in a very hackish way in svn --

any ideas on how to do this with Git?

Selfrespect answered 23/6, 2011 at 18:28 Comment(4)
Do you want this embedded in a file like $Id$? That doesn't really work. If you just want to describe a build in whole though, git describeClaiborne
Yeah I do want to do something similar to that, or even maybe write a file version.log that I could parseSelfrespect
Similar to $ID$ -- sorry. I need to reuse that build number in my php codeSelfrespect
Git is not an acronym. It's just "Git", not "GIT".Skipton
T
10

For me, git describe didn't initially give the hashtag. The following did, however:

git describe --all --long

This results in something of the by kubi described format. Supposing you would only want the last part (hashtag) something like the following would do (saving to version.txt file):

git describe --all --long | tr "-" " " | awk '{ print $3 }' > version.txt

EDIT: As a friend pointed out to me this can actually be done using just cut instead, if you so desire:

git describe --all --long | cut -d "-" -f 3 > version.txt
Turbulent answered 20/12, 2011 at 17:14 Comment(2)
this actually was closer to what I wanted. Now I just need to find a way to embed it in a file. I want to reference the build id in codeSelfrespect
This seems to be a different question, but it is most definitely possible. In PHP: $git_version = file_get_contents("version.txt"); - now $git_version contains the hash :)Turbulent
S
7

Here's what I do:

As part of my build process I run the following script (paraphrased, since I'm not at Xcode right now)

git describe --all > version.txt

Inside my application I read the version number out of this file and display it to the user (when necessary). Make sure you add version.txt to your .gitignore. The benefit of doing it this way is that if you tag your releases git describe will just output the tag, otherwise it'll output the commit hash.

Secondary answered 23/6, 2011 at 18:49 Comment(4)
to me this gives me the branch name but not the version #Selfrespect
It will give you <last reachable tag>-<commits since tag>-<8 digit hash>Secondary
@Secondary No. Its 7 digit hash with prefix g.Zobe
For me it's git describe (without --all) (I am using 1.9.5.msysgit.0)Chengtu
L
4

Note: it is interesting to see how Git itself computes its own build number.
That just evolved in Git 2.12 (Q1 2017)

See commit a765974 (04 Dec 2016) by Ramsay Jones (``).
Helped-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 0a45050, 19 Dec 2016)

GIT-VERSION-GEN 

VN=$(git describe --match "v[0-9]*" HEAD 2>/dev/null) 
# instead of
VN=$(git describe --match "v[0-9]*" --abbrev=7 HEAD 2>/dev/null)

GIT-VERSION-GEN: do not force abbreviation length used by 'describe'

The default version name for a Git binary is computed by running "git describe" on the commit the binary is made out of, basing on a tag whose name matches "v[0-9]*", e.g. v2.11.0-rc2-2-g7f1dc9.

In the very early days, with 9b88fce ("Makefile: use git-describe to mark the git version.", 2005-12-27), we used "--abbrev=4" to get absolute minimum number of abbreviated commit object name.
This was later changed to match the default minimum of 7 with bf50515 ("Git 1.7.10.1", 2012-05-01).

These days, the "default minimum" scales automatically depending on the size of the repository, and there is no point in specifying a particular abbreviation length; all we wanted since Git 1.7.10.1 days was to get "something reasonable we would use by default".

(That was introduced in Git 2.11: see the last part of "How much of a git sha is generally considered necessary to uniquely identify a change in a given codebase?")

Just drop "--abbrev=<number>" from the invocation of "git describe" and let the command pick what it thinks is appropriate, taking the end user's configuration and the repository contents into account.

Liss answered 23/12, 2016 at 21:31 Comment(0)
A
3

To get Git revision in php, I use something like this (change your paths to .Git catalog)

public static function getGitRevision()
     {
         $rev = trim(file_get_contents(NT_Path::ROOT . "/.git/HEAD"));

         if (substr($rev, 0, 4) == 'ref:') {
             $ref =  end(explode('/', $rev));
             $rev = trim(file_get_contents(NT_Path::ROOT . "/.git/refs/heads/{$ref}"));
         }

         return $rev;
     }
Adler answered 3/10, 2014 at 6:32 Comment(0)
M
0

Instead of putting it in a text file then getting the contents of it each time, this appears to work quite well:

sed -i.bak "s/$version = '.*';/$version = '`git rev-parse --short HEAD | tr -d '\n'`';/g" version.php

where version.php looks like this:

<?php
$version = 'some version string';

and then just include the file in your script as you would a settings file.

You could also use git describe --all --long as your version string if you wanted to, I preferred the git-hash from git-ref-parse --short HEAD for my purposes.

Or as a constant which may be better:

sed -i.bak "s/define('VERSION','.*');/define('VERSION','`git describe --all --long | cut -d "-" -f 3`');/g" version.php

and version.php:

<?php
define('VERSION','some version string');
Mangan answered 29/7, 2015 at 18:44 Comment(0)
W
0

This is how I have done it. Note: Python code to get revision came from this post.

BuildInfo.hpp

#ifndef BUILDINFO_HPP_
#define BUILDINFO_HPP_

struct BuildInfo
{
    static const char Name[];
    static const char GitRevision[];
};

#endif

(Auto Generated) BuildInfo.cpp

#include "BuildInfo.hpp"

const char BuildInfo::Name[] = "MyAppNAme";
const char BuildInfo::GitRevision[] = "5e854351b342acff6a3481d9106076df379c449a";

GenerateBuildInfo.py. Python script to generate BuildInfo.cpp. Note that this could be easily adapted to get short or long revision numbers or other repository info. It could also be converted to generate C code rather than cpp so is compatible with both.

import sys
import os
import subprocess

#args: [0]: this script path [1]: Output file name [2]: Application name string

# Return the git revision as a string
def git_version():
    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        GIT_REVISION = out.strip().decode('ascii')
    except OSError:
        GIT_REVISION = "Unknown"

    return GIT_REVISION

if len(sys.argv) < 2 :
    exit("No output file name argument provided")
elif len(sys.argv) >= 3 :
    name = sys.argv[2]
else :
    name = ""

revision = git_version()
if (revision == "Unknown") :
    exit("Cant get git revision")

with open(sys.argv[1], "w") as f :
    f.write('#include "BuildInfo.hpp"\r\n\r\n')
    f.write('const char BuildInfo::Name[] = "' + name + '";\r\n')
    f.write('const char BuildInfo::GitRevision[] = "' + revision + '";\r\n')
    f.close()

To use the build info

#include "BuildInfo.hpp"
...
PrintRevision(BuildInfo::GitRevision);

To generate BuildInfo.cpp, in a post build step I call (from eclipse IDE in this case)

python ${ProjDirPath}/build/GenerateBuildInfo.py ${ProjDirPath}/src/BuildInfo.cpp ${ProjName}
Wieren answered 13/6, 2019 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.