2
2
// Copyright © 2024 Intel Corporation
3
3
4
4
#include " vcs_tag.hpp"
5
+ #include " util/process.hpp"
5
6
#include " util/utils.hpp"
6
7
7
8
#include < cassert>
8
9
#include < fstream>
9
10
#include < iostream>
11
+ #include < optional>
10
12
#include < sstream>
13
+ #include < vector>
11
14
12
15
namespace Tools {
13
16
14
17
namespace fs = std::filesystem;
15
18
19
+ namespace {
20
+
21
+ struct VCSData {
22
+ std::vector<std::string> command;
23
+ fs::path dep;
24
+ };
25
+
26
+ std::optional<VCSData> find_vcs (const fs::path & source_dir) {
27
+ // TODO: HG, Subversion, bazaar
28
+ const fs::path gitdir = source_dir / " .git" ;
29
+
30
+ if (fs::is_directory (gitdir)) {
31
+ return VCSData{
32
+ .command = {" git" , " -C" , source_dir, " describe" , " --dirty=+" , " --always" },
33
+ .dep = gitdir / " logs" / " HEAD" , // TODO: This doesn't work for git work trees
34
+ };
35
+ }
36
+
37
+ return std::nullopt;
38
+ }
39
+
40
+ std::string get_version (const std::optional<VCSData> & vcs_o, std::string_view fallback) {
41
+ if (!vcs_o) {
42
+ return std::string{fallback};
43
+ }
44
+
45
+ const VCSData & vcs = vcs_o.value ();
46
+ auto [rc, out, err] = Util::process (vcs.command );
47
+ if (rc != 0 ) {
48
+ throw std::runtime_error{" TODO: " + err};
49
+ }
50
+ out.pop_back ();
51
+ return out;
52
+ }
53
+
54
+ } // namespace
55
+
16
56
int generate_vcs_tag (const std::filesystem::path & infile, const std::filesystem::path & outfile,
17
- std::string_view version , std::string_view replacement,
57
+ std::string_view fallback , std::string_view replacement,
18
58
const std::filesystem::path & source_dir) {
19
59
// We assume that the infile exists and has been validated by the
20
60
// transpiler, but for debug builds we can assert here.
@@ -23,6 +63,9 @@ int generate_vcs_tag(const std::filesystem::path & infile, const std::filesystem
23
63
std::ifstream istream{infile};
24
64
std::stringstream ostream{};
25
65
66
+ const std::optional<VCSData> vcs = find_vcs (source_dir);
67
+ const std::string version = get_version (vcs, fallback);
68
+
26
69
for (std::string line; std::getline (istream, line);) {
27
70
ostream << Util::replace (line, replacement, version) << std::endl;
28
71
}
@@ -57,6 +100,8 @@ int generate_vcs_tag(const std::filesystem::path & infile, const std::filesystem
57
100
}
58
101
}
59
102
103
+ // TODO: emit depfile for git
104
+
60
105
std::ofstream out{outfile};
61
106
out << ostream.str ();
62
107
return 0 ;
0 commit comments