10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

D言語でdubを使ってビルド時に、最新のコミットのハッシュをバイナリに組み込む

Posted at

こんにちは。
タイトル通りですが、D言語でビルド時のコミットのハッシュをバイナリに組み込みたいという事になった場合に、どうすればいいか、ということについて書きます。

dubには様々なオプションが存在します。ここで使うのはpreGenerateCommandsを使います。
これは、dubでビルドする前にシェルのコマンドを叩くことができるオプションです。
これを使います。
また、最新のコミットのハッシュを得るにはgit rev-parse --short HEAD > versionというコマンドを用います。
したがって、イメージとしてはビルドに際して

  1. preGenerateCommandsを用いてgit rev-parse --short HEAD > versionを実行する。
  2. D言語にはstring importと言うものが有り、それを用いてversionというファイルを読み込む。
  3. これでバイナリにハッシュを組み込める!!!

という感じになります。

string importとは(これが正しい名前だったかは忘れてしまったのですが)、ビルド時に、string value = import("filepath");とすることで、filepathのファイルの中身をvalueに読み込むことができる機能です(なお、これを使うにはdmdでビルドする時に-Jオプションで、filepathのあるパスを指定する必要があります。)

以上をまとめると、次のようなコードで組み込む事ができます。

dub.json
{
  "name": "test_git",
  "authors": [
    "Akihiro Shoji"
  ],
  "description": "A minimal D application.",
  "copyright": "Copyright (c) 2017, Akihiro Shoji",
  "license": "MIT",
  "preGenerateCommands": ["bash getLatestCommitHash.sh"],
  "dflags":["-J."]
}
source/app.d
import std.stdio;

enum string _version = import("./version");

void main() {
  writeln("version : ", _version);
}
getLatestCommitHash.sh
git rev-parse --short HEAD > version

このようにして書くと、ビルド時にバイナリに、最新のコミットのハッシュを埋め込むことが出来ます。

10
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?