-
Notifications
You must be signed in to change notification settings - Fork 13
/
GitCommit2AssemblyTitle.cs
200 lines (156 loc) · 6.88 KB
/
GitCommit2AssemblyTitle.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Build.Framework;
using Task = System.Threading.Tasks.Task;
// ReSharper disable AccessToDisposedClosure
namespace Vostok.Tools.GitCommit2AssemblyTitle
{
public class GitCommit2AssemblyTitle : Microsoft.Build.Utilities.Task
{
private static readonly TimeSpan CommandTimeout = TimeSpan.FromSeconds(30);
private static readonly TimeSpan StreamTimeout = TimeSpan.FromSeconds(5);
public override bool Execute()
{
void LogMessageFunction(string str, object[] args) => Log.LogMessage(str, args);
var assemblyTitleContent = GetAssemblyTitleContent(LogMessageFunction, AssemblyVersion);
WriteAssemblyTitleContent(LogMessageFunction, assemblyTitleContent);
return true;
}
[Required]
public string AssemblyVersion { get; set; }
public delegate void LogMessageFunction(string command, params object[] arguments);
private static string GetAssemblyTitleContent(LogMessageFunction log, string assemblyVersion)
{
var gitMessage = GetGitCommitMessage(log)?.Trim();
var gitCommitHash = GetGitCommitHash(log)?.Trim();
if (string.IsNullOrEmpty(gitMessage))
{
log("Git commit message is empty.");
return string.Empty;
}
if (string.IsNullOrEmpty(gitCommitHash))
{
log("Git commit hash is empty.");
return string.Empty;
}
var titleBuilder = new StringBuilder();
var contentBuilder = new StringBuilder();
titleBuilder.AppendLine();
titleBuilder.AppendLine(gitMessage);
titleBuilder.Append($"Build date: {DateTime.Now:O}");
var title = titleBuilder.ToString().Replace("\"", "'");
var informationalVersion = $"{assemblyVersion}-{gitCommitHash?.Substring(0, 8)}";
contentBuilder.AppendLine("using System.Reflection;");
contentBuilder.AppendLine();
contentBuilder.AppendLine($@"[assembly: AssemblyTitle(@""{title}"")]");
contentBuilder.AppendLine();
contentBuilder.AppendLine($@"[assembly: AssemblyInformationalVersion(""{informationalVersion}"")]");
return contentBuilder.ToString();
}
private static string GetGitCommitMessage(LogMessageFunction log)
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? GetCommandOutput("cmd", "/C git log --pretty=\"Commit: %H %nAuthor: %an %nDate: %ai %nRef names: %d%n\" -1", log)
: GetCommandOutput("git", "log --pretty=\"Commit: %H %nAuthor: %an %nDate: %ai %nRef names: %d%n\" -1", log);
}
private static string GetGitCommitHash(LogMessageFunction log)
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? GetCommandOutput("cmd", "/C git log --pretty=\"%H\" -1", log)
: GetCommandOutput("git", "log --pretty=\"%H\" -1", log);
}
private static void WriteAssemblyTitleContent(LogMessageFunction log, string newContent)
{
const string properties = "Properties";
var assemblyTitleFileName = Path.Combine(properties, "AssemblyTitle.cs");
if (!Directory.Exists(properties))
Directory.CreateDirectory(properties);
log("{0} updated", assemblyTitleFileName);
const int attempts = 10;
var random = new Random(Guid.NewGuid().GetHashCode());
for (var i = 1; i <= attempts; i++)
{
try
{
var lastWriteTime = File.Exists(assemblyTitleFileName)
? File.GetLastWriteTime(assemblyTitleFileName)
: DateTime.Now;
File.WriteAllText(assemblyTitleFileName, newContent);
File.SetLastWriteTime(assemblyTitleFileName, lastWriteTime);
return;
}
catch (IOException)
{
log($"File {assemblyTitleFileName} is locked.");
if (i == attempts)
throw;
log("Wait...");
Thread.Sleep(random.Next(500, 1000));
}
}
}
private static string GetCommandOutput(string command, string args, LogMessageFunction log)
{
log(command + " " + args);
var startInfo = new ProcessStartInfo
{
FileName = command,
Arguments = args,
WorkingDirectory = Directory.GetCurrentDirectory(),
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
ErrorDialog = false,
WindowStyle = ProcessWindowStyle.Hidden
};
var stdout = new StringBuilder();
var stderr = new StringBuilder();
try
{
using (var process = new Process {StartInfo = startInfo})
{
if (!process.Start())
throw new Exception("Failed to start Git process.");
var stdoutTask = Task.Run(() => ReadStreamAsync(process.StandardOutput, stdout));
var stderrTask = Task.Run(() => ReadStreamAsync(process.StandardError, stderr));
if (!process.WaitForExit((int) CommandTimeout.TotalMilliseconds))
{
try
{
process.Kill();
log("process killed");
}
catch (Exception)
{
log("killing already exited process");
}
process.WaitForExit();
}
log("exit code:" + process.ExitCode);
stdoutTask.Wait(StreamTimeout);
stderrTask.Wait(StreamTimeout);
return stdout.Length > 0 ? stdout.ToString() : stderr.ToString();
}
}
catch (Exception error)
{
log(error.Message);
return string.Empty;
}
}
private static async Task ReadStreamAsync(StreamReader reader, StringBuilder buffer)
{
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync().ConfigureAwait(false);
buffer.AppendLine(line);
Console.Out.WriteLine(line);
}
}
}
}