1. 程式人生 > >visual studio c++程式碼中使用git版本資訊

visual studio c++程式碼中使用git版本資訊

總體思路

本篇使用的方法不更改visual studio的任何設定,完全使用的是“蠻力”。

  1. 使用python寫成的tool獲取版本資訊,並auto code為一個.h檔案,檔案中僅是一個git版本資訊類
  2. 在需要git版本資訊的程式碼中,使用1中自動生成的類
  3. 將autocode, 程式碼編譯兩個過程寫到一個批處理

自動程式碼生成

我們希望將git 最後一次commit的hash值作為版本資訊,於是我們這一步的目標是自動生成以下程式碼:

#pragma once
#include <stdio.h>
class CVersion {
 public:
     static const char* version () {
        return "commit a6a4a5804c35529057a220c65a10f95976279071\nAuthor: xq <309905109.qq.com>\nDate:   Fri Oct 12 16:25:25 2018 +0800\n\n    add auto test\n";      }
};

我寫的python檔案完成自動生成功能,程式碼如下(此處可根據跟人需要修改):

import subprocess
cmd  = ['git', "log", "-1"]
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
out = (proc.stdout).decode('utf-8')
gitversion = out.replace("\n","\\n")
print(out)

codefilename = "Version.h"
with open(codefilename, "w") as outfile:
	outfile.write("#pragma once\n")
	outfile.write("#include <stdio.h>\n")
	outfile.write("class CVersion {\n")
	outfile.write(" public:\n")
	outfile.write("     static const char* version () {\n")
	outfile.write("        return \"{version}\";".format(version=gitversion))
	outfile.write("      }\n")
	outfile.write("};\n")

使用自動生成的程式碼

CVersion類中只有一個靜態方法,返回git版本資訊, 可直接使用,我的程式用作為日誌資訊打印出來,程式碼是這個樣子的:

#include "Version.h"
...
    CCoreMle::trace("", "\n\n\n%s\n\n", CVersion::version());
...

整合

要想每次編譯的時候上邊的過程自動執行, 可以寫下邊一個批處理檔案build.bat:

del ..\Serv\Version.h
python ..\tools\vercodegen.py
move Version.h ..\Serv\
"C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.com"  ..\Serv\Serv.sln /Rebuild

這個樣子的話,整個編譯過程就自動化起來了。

執行結果

最終執行出來的樣子是這樣的,在日誌裡打印出了git 最後一次commit的資訊: log