/
VersionFile.cs
348 lines (313 loc) · 16.5 KB
/
VersionFile.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
namespace Nerdbank.GitVersioning
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Validation;
/// <summary>
/// Extension methods for interacting with the version.txt file.
/// </summary>
public static class VersionFile
{
/// <summary>
/// The filename of the version.txt file.
/// </summary>
public const string TxtFileName = "version.txt";
/// <summary>
/// The filename of the version.json file.
/// </summary>
public const string JsonFileName = "version.json";
/// <summary>
/// A sequence of possible filenames for the version file in preferred order.
/// </summary>
public static readonly IReadOnlyList<string> PreferredFileNames = new[] { JsonFileName, TxtFileName };
/// <summary>
/// Reads the version.txt file and returns the <see cref="Version"/> and prerelease tag from it.
/// </summary>
/// <param name="commit">The commit to read the version file from.</param>
/// <param name="repoRelativeProjectDirectory">The directory to consider when searching for the version.txt file.</param>
/// <returns>The version information read from the file.</returns>
public static VersionOptions GetVersion(LibGit2Sharp.Commit commit, string repoRelativeProjectDirectory = null)
{
if (commit == null)
{
return null;
}
string searchDirectory = repoRelativeProjectDirectory ?? string.Empty;
while (searchDirectory != null)
{
string parentDirectory = searchDirectory.Length > 0 ? Path.GetDirectoryName(searchDirectory) : null;
string candidatePath = Path.Combine(searchDirectory, TxtFileName).Replace('\\', '/');
var versionTxtBlob = commit.Tree[candidatePath]?.Target as LibGit2Sharp.Blob;
if (versionTxtBlob != null)
{
var result = TryReadVersionFile(new StreamReader(versionTxtBlob.GetContentStream()), isJsonFile: false);
if (result != null)
{
return result;
}
}
candidatePath = Path.Combine(searchDirectory, JsonFileName).Replace('\\', '/');
var versionJsonBlob = commit.Tree[candidatePath]?.Target as LibGit2Sharp.Blob;
if (versionJsonBlob != null)
{
string versionJsonContent;
using (var sr = new StreamReader(versionJsonBlob.GetContentStream()))
{
versionJsonContent = sr.ReadToEnd();
}
VersionOptions result;
try
{
result = TryReadVersionJsonContent(versionJsonContent);
}
catch (FormatException ex)
{
throw new FormatException(
$"Failure while reading {JsonFileName} from commit {commit.Sha}. " +
"Fix this commit with rebase if this is an error, or review this doc on how to migrate to Nerdbank.GitVersioning: " +
"https://github.com/AArnott/Nerdbank.GitVersioning/blob/master/doc/migrating.md", ex);
}
if (result?.Inherit ?? false)
{
if (parentDirectory != null)
{
result = GetVersion(commit, parentDirectory);
if (result != null)
{
JsonConvert.PopulateObject(versionJsonContent, result, VersionOptions.GetJsonSettings());
return result;
}
}
throw new InvalidOperationException($"\"{candidatePath}\" inherits from a parent directory version.json file but none exists.");
}
else if (result != null)
{
return result;
}
}
searchDirectory = parentDirectory;
}
return null;
}
/// <summary>
/// Reads the version.txt file and returns the <see cref="Version"/> and prerelease tag from it.
/// </summary>
/// <param name="repo">The repo to read the version file from.</param>
/// <param name="repoRelativeProjectDirectory">The directory to consider when searching for the version.txt file.</param>
/// <returns>The version information read from the file.</returns>
public static VersionOptions GetVersion(LibGit2Sharp.Repository repo, string repoRelativeProjectDirectory = null)
{
if (repo == null)
{
return null;
}
if (!repo.Info.IsBare)
{
string fullDirectory = Path.Combine(repo.Info.WorkingDirectory, repoRelativeProjectDirectory ?? string.Empty);
var workingCopyVersion = GetVersion(fullDirectory);
return workingCopyVersion;
}
return GetVersion(repo.Head.Tip, repoRelativeProjectDirectory);
}
/// <summary>
/// Reads the version.txt file and returns the <see cref="Version"/> and prerelease tag from it.
/// </summary>
/// <param name="projectDirectory">The path to the directory which may (or its ancestors may) define the version.txt file.</param>
/// <returns>The version information read from the file, or <c>null</c> if the file wasn't found.</returns>
public static VersionOptions GetVersion(string projectDirectory) => GetVersion(projectDirectory, out string _);
/// <summary>
/// Reads the version.txt file and returns the <see cref="Version"/> and prerelease tag from it.
/// </summary>
/// <param name="projectDirectory">The path to the directory which may (or its ancestors may) define the version.txt file.</param>
/// <param name="actualDirectory">Set to the actual directory that the version file was found in, which may be <paramref name="projectDirectory"/> or one of its ancestors.</param>
/// <returns>The version information read from the file, or <c>null</c> if the file wasn't found.</returns>
public static VersionOptions GetVersion(string projectDirectory, out string actualDirectory)
{
Requires.NotNullOrEmpty(projectDirectory, nameof(projectDirectory));
string searchDirectory = projectDirectory;
while (searchDirectory != null)
{
string parentDirectory = Path.GetDirectoryName(searchDirectory);
string versionTxtPath = Path.Combine(searchDirectory, TxtFileName);
if (File.Exists(versionTxtPath))
{
using (var sr = new StreamReader(File.OpenRead(versionTxtPath)))
{
var result = TryReadVersionFile(sr, isJsonFile: false);
if (result != null)
{
actualDirectory = searchDirectory;
return result;
}
}
}
string versionJsonPath = Path.Combine(searchDirectory, JsonFileName);
if (File.Exists(versionJsonPath))
{
string versionJsonContent = File.ReadAllText(versionJsonPath);
VersionOptions result = TryReadVersionJsonContent(versionJsonContent);
if (result?.Inherit ?? false)
{
if (parentDirectory != null)
{
result = GetVersion(parentDirectory);
if (result != null)
{
JsonConvert.PopulateObject(versionJsonContent, result, VersionOptions.GetJsonSettings());
actualDirectory = searchDirectory;
return result;
}
}
throw new InvalidOperationException($"\"{versionJsonPath}\" inherits from a parent directory version.json file but none exists.");
}
else if (result != null)
{
actualDirectory = searchDirectory;
return result;
}
}
searchDirectory = parentDirectory;
}
actualDirectory = null;
return null;
}
/// <summary>
/// Checks whether the version.txt file is defined in the specified commit.
/// </summary>
/// <param name="commit">The commit to search.</param>
/// <param name="projectDirectory">The directory to consider when searching for the version.txt file.</param>
/// <returns><c>true</c> if the version.txt file is found; otherwise <c>false</c>.</returns>
public static bool IsVersionDefined(LibGit2Sharp.Commit commit, string projectDirectory = null)
{
return GetVersion(commit, projectDirectory) != null;
}
/// <summary>
/// Checks whether the version.txt file is defined in the specified project directory
/// or one of its ancestors.
/// </summary>
/// <param name="projectDirectory">The directory to start searching within.</param>
/// <returns><c>true</c> if the version.txt file is found; otherwise <c>false</c>.</returns>
public static bool IsVersionDefined(string projectDirectory)
{
Requires.NotNullOrEmpty(projectDirectory, nameof(projectDirectory));
return GetVersion(projectDirectory) != null;
}
/// <summary>
/// Writes the version.json file to a directory within a repo with the specified version information.
/// The $schema property is included.
/// </summary>
/// <param name="projectDirectory">
/// The path to the directory in which to write the version.json file.
/// The file's impact will be all descendent projects and directories from this specified directory,
/// except where any of those directories have their own version.json file.
/// </param>
/// <param name="version">The version information to write to the file.</param>
/// <returns>The path to the file written.</returns>
public static string SetVersion(string projectDirectory, VersionOptions version) => SetVersion(projectDirectory, version, includeSchemaProperty: true);
/// <summary>
/// Writes the version.json file to a directory within a repo with the specified version information.
/// </summary>
/// <param name="projectDirectory">
/// The path to the directory in which to write the version.json file.
/// The file's impact will be all descendent projects and directories from this specified directory,
/// except where any of those directories have their own version.json file.
/// </param>
/// <param name="version">The version information to write to the file.</param>
/// <param name="includeSchemaProperty">A value indicating whether to serialize the $schema property for easier editing in most JSON editors.</param>
/// <returns>The path to the file written.</returns>
public static string SetVersion(string projectDirectory, VersionOptions version, bool includeSchemaProperty)
{
Requires.NotNullOrEmpty(projectDirectory, nameof(projectDirectory));
Requires.NotNull(version, nameof(version));
Requires.Argument(version.Version != null || version.Inherit, nameof(version), $"{nameof(VersionOptions.Version)} must be set for a root-level version.json file.");
Directory.CreateDirectory(projectDirectory);
string versionTxtPath = Path.Combine(projectDirectory, TxtFileName);
if (File.Exists(versionTxtPath))
{
if (version.IsDefaultVersionTheOnlyPropertySet)
{
File.WriteAllLines(
versionTxtPath,
new[] { version.Version.Version.ToString(), version.Version.Prerelease });
return versionTxtPath;
}
else
{
// The file must be upgraded to use the more descriptive JSON format.
File.Delete(versionTxtPath);
}
}
string versionJsonPath = Path.Combine(projectDirectory, JsonFileName);
var jsonContent = JsonConvert.SerializeObject(version, VersionOptions.GetJsonSettings(version.Inherit, includeSchemaProperty));
File.WriteAllText(versionJsonPath, jsonContent);
return versionJsonPath;
}
/// <summary>
/// Writes the version.txt file to a directory within a repo with the specified version information.
/// </summary>
/// <param name="projectDirectory">
/// The path to the directory in which to write the version.txt file.
/// The file's impact will be all descendent projects and directories from this specified directory,
/// except where any of those directories have their own version.txt file.
/// </param>
/// <param name="version">The version information to write to the file.</param>
/// <param name="unstableTag">The optional unstable tag to include in the file.</param>
/// <returns>The path to the file written.</returns>
public static string SetVersion(string projectDirectory, Version version, string unstableTag = null)
{
return SetVersion(projectDirectory, VersionOptions.FromVersion(version, unstableTag), includeSchemaProperty: false);
}
/// <summary>
/// Reads the version.txt file and returns the <see cref="Version"/> and prerelease tag from it.
/// </summary>
/// <param name="versionTextContent">The content of the version.txt file to read.</param>
/// <param name="isJsonFile"><c>true</c> if the file being read is a JSON file; <c>false</c> for the old-style text format.</param>
/// <returns>The version information read from the file; or <c>null</c> if a deserialization error occurs.</returns>
private static VersionOptions TryReadVersionFile(TextReader versionTextContent, bool isJsonFile)
{
if (isJsonFile)
{
string jsonContent = versionTextContent.ReadToEnd();
return TryReadVersionJsonContent(jsonContent);
}
string versionLine = versionTextContent.ReadLine();
string prereleaseVersion = versionTextContent.ReadLine();
if (!string.IsNullOrEmpty(prereleaseVersion))
{
if (!prereleaseVersion.StartsWith("-"))
{
// SemVer requires that prerelease suffixes begin with a hyphen, so add one if it's missing.
prereleaseVersion = "-" + prereleaseVersion;
}
}
SemanticVersion semVer;
Verify.Operation(SemanticVersion.TryParse(versionLine + prereleaseVersion, out semVer), "Unrecognized version format.");
return new VersionOptions
{
Version = semVer,
};
}
/// <summary>
/// Tries to read a version.json file from the specified string, but favors returning null instead of throwing a <see cref="JsonSerializationException"/>.
/// </summary>
/// <param name="jsonContent">The content of the version.json file.</param>
/// <returns>The deserialized <see cref="VersionOptions"/> object, if deserialization was successful.</returns>
private static VersionOptions TryReadVersionJsonContent(string jsonContent)
{
try
{
return JsonConvert.DeserializeObject<VersionOptions>(jsonContent, VersionOptions.GetJsonSettings());
}
catch (JsonSerializationException)
{
return null;
}
}
}
}