-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathGitRepositoryIssuesProvider.cs
More file actions
307 lines (258 loc) · 11.4 KB
/
GitRepositoryIssuesProvider.cs
File metadata and controls
307 lines (258 loc) · 11.4 KB
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
namespace Cake.Issues.GitRepository;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Core.IO;
using Cake.Core.Tooling;
/// <summary>
/// Provider for issues in Git repositories.
/// </summary>
internal class GitRepositoryIssuesProvider : BaseIssueProvider
{
private readonly GitRunner runner;
private readonly Lazy<IEnumerable<string>> allFiles;
private readonly Lazy<IEnumerable<string>> textFiles;
private readonly Lazy<IEnumerable<string>> binaryFiles;
/// <summary>
/// Initializes a new instance of the <see cref="GitRepositoryIssuesProvider"/> class.
/// </summary>
/// <param name="log">The Cake log context.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The Cake environment.</param>
/// <param name="processRunner">The process runner.</param>
/// <param name="toolLocator">The tool locator.</param>
/// <param name="issueProviderSettings">Settings for the issue provider.</param>
public GitRepositoryIssuesProvider(
ICakeLog log,
IFileSystem fileSystem,
ICakeEnvironment environment,
IProcessRunner processRunner,
IToolLocator toolLocator,
GitRepositoryIssuesSettings issueProviderSettings)
: base(log)
{
fileSystem.NotNull();
environment.NotNull();
processRunner.NotNull();
toolLocator.NotNull();
issueProviderSettings.NotNull();
this.IssueProviderSettings = issueProviderSettings;
this.runner = new GitRunner(fileSystem, environment, processRunner, toolLocator);
this.allFiles =
new Lazy<IEnumerable<string>>(
this.GetAllFilesFromRepository);
this.textFiles =
new Lazy<IEnumerable<string>>(
this.GetTextFilesFromRepository);
this.binaryFiles =
new Lazy<IEnumerable<string>>(
() => this.DetermineBinaryFiles(this.allFiles.Value, this.textFiles.Value));
}
/// <summary>
/// Gets the name of the Git repository issue provider.
/// This name can be used to identify issues based on the <see cref="IIssue.ProviderType"/> property.
/// </summary>
public static string ProviderTypeName => typeof(GitRepositoryIssuesProvider).FullName;
/// <inheritdoc />
public override string ProviderName => "Git Repository";
/// <summary>
/// Gets the settings for the issue provider.
/// </summary>
protected GitRepositoryIssuesSettings IssueProviderSettings { get; }
/// <inheritdoc />
protected override IEnumerable<IIssue> InternalReadIssues()
{
var result = new List<IIssue>();
var assembly = Assembly.GetAssembly(typeof(GitRepositoryIssuesProvider));
var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
var versionParts = fileVersion.Split('.');
var issueProviderVersion = $"{versionParts[0]}.{versionParts[1]}.{versionParts[2]}";
if (this.IssueProviderSettings.CheckBinaryFilesTrackedByLfs)
{
result.AddRange(
this.CheckForBinaryFilesNotTrackedByLfs(issueProviderVersion));
}
if (this.IssueProviderSettings.CheckFilesPathLength)
{
result.AddRange(this.CheckForFilesPathLength(issueProviderVersion));
}
return result;
}
/// <summary>
/// Checks for binary files which are not tracked by LFS.
/// </summary>
/// <param name="issueProviderVersion">Version of the issue provider.</param>
/// <returns>List of issues for binary files which are not tracked by LFS.</returns>
private List<IIssue> CheckForBinaryFilesNotTrackedByLfs(string issueProviderVersion)
{
if (!this.allFiles.Value.Any())
{
return [];
}
if (!this.binaryFiles.Value.Any())
{
return [];
}
var lfsTrackedFiles = this.GetLfsTrackedFilesFromRepository();
var binaryFilesNotTrackedByLfs =
this.DetermineBinaryFilesNotTrackedWithLfs(this.binaryFiles.Value, lfsTrackedFiles);
var result = new List<IIssue>();
foreach (var file in binaryFilesNotTrackedByLfs)
{
var ruleDescription = new BinaryFileNotTrackedByLfsRuleDescription();
result.Add(
IssueBuilder
.NewIssue($"The binary file \"{file}\" is not tracked by Git LFS", this)
.WithMessageInHtmlFormat($"The binary file <code>{file}</code> is not tracked by Git LFS")
.WithMessageInMarkdownFormat($"The binary file `{file}` is not tracked by Git LFS")
.InFile(file)
.OfRule(ruleDescription, issueProviderVersion)
.Create());
}
return result;
}
/// <summary>
/// Checks for files path length.
/// </summary>
/// <param name="issueProviderVersion">Version of the issue provider.</param>
/// <returns>List of issues for repository files with paths exceeding the allowed maximum.</returns>
private List<IIssue> CheckForFilesPathLength(string issueProviderVersion)
{
if (!this.allFiles.Value.Any())
{
return [];
}
var result = new List<IIssue>();
foreach (var file in this.allFiles.Value)
{
if (file.Length > this.IssueProviderSettings.MaxFilePathLength)
{
var ruleDescription = new FilePathTooLongRuleDescription();
result.Add(
IssueBuilder
.NewIssue($"The path for the file \"{file}\" is too long. Maximum allowed path length is {this.IssueProviderSettings.MaxFilePathLength}, actual path length is {file.Length}.", this)
.WithMessageInHtmlFormat($"The path for the file <code>{file}</code> is too long. Maximum allowed path length is {this.IssueProviderSettings.MaxFilePathLength}, actual path length is {file.Length}.")
.WithMessageInMarkdownFormat($"The path for the file `{file}` is too long. Maximum allowed path length is {this.IssueProviderSettings.MaxFilePathLength}, actual path length is {file.Length}.")
.InFile(file)
.OfRule(ruleDescription, issueProviderVersion)
.Create());
}
}
return result;
}
/// <summary>
/// Returns a list of the files in the repository.
/// </summary>
/// <returns>List of files in the repository.</returns>
private List<string> GetAllFilesFromRepository()
{
this.Log.Verbose("Reading all files from repository '{0}'...", this.Settings.RepositoryRoot);
var settings = new GitRunnerSettings
{
WorkingDirectory = this.Settings.RepositoryRoot,
};
settings.Arguments.Clear();
settings.Arguments.Add("ls-files -t -z");
var output =
this.runner.RunCommand(settings)
?? throw new Exception("Error reading files from repository");
var result =
string.Join(
string.Empty,
output)
.Split('\0')
.Where(x => !string.IsNullOrEmpty(x))
.Where(x => !x.StartsWith("S ", StringComparison.Ordinal)) // Exclude skip-worktree files (sparse checkout)
.Select(x => x.Length > 2 ? x[2..] : x) // Remove status prefix (e.g., "H ")
.ToList();
this.Log.Verbose("Found {0} file(s)", result.Count);
return result;
}
/// <summary>
/// Returns a list of text files in the repository.
/// </summary>
/// <returns>List of text files in the repository.</returns>
private List<string> GetTextFilesFromRepository()
{
this.Log.Verbose("Reading all text files from repository '{0}'...", this.Settings.RepositoryRoot);
var settings = new GitRunnerSettings
{
WorkingDirectory = this.Settings.RepositoryRoot,
// git grep -IL . can return an exit code of 1 if nothing matches
HandleExitCode = exitCode => exitCode is 0 or 1,
};
settings.Arguments.Clear();
settings.Arguments.Add("grep -Il .");
var textFilesFromRepository =
this.runner.RunCommand(settings)
?? throw new Exception("Error reading text files from repository");
settings.Arguments.Clear();
settings.Arguments.Add("grep -IL .");
var emptyFiles = this.runner.RunCommand(settings);
if (emptyFiles != null && emptyFiles.Any())
{
textFilesFromRepository = textFilesFromRepository.Concat(emptyFiles);
}
var result = textFilesFromRepository.ToList();
this.Log.Verbose("Found {0} text file(s)", result.Count);
return result;
}
/// <summary>
/// Returns a list of files tracked by Git LFS.
/// </summary>
/// <returns>List of files tracked by Git LFS.</returns>
private IEnumerable<string> GetLfsTrackedFilesFromRepository()
{
this.Log.Verbose("Reading all LFS tracked files from repository '{0}'...", this.Settings.RepositoryRoot);
var settings = new GitRunnerSettings
{
WorkingDirectory = this.Settings.RepositoryRoot,
};
settings.Arguments.Clear();
settings.Arguments.Add("lfs ls-files -n");
var lfsTrackedFiles =
this.runner.RunCommand(settings)
?? throw new Exception("Error reading LFS tracked files from repository");
lfsTrackedFiles = lfsTrackedFiles.ToList();
this.Log.Verbose("Found {0} LFS tracked file(s)", lfsTrackedFiles.Count());
return lfsTrackedFiles;
}
/// <summary>
/// Determines binary files.
/// </summary>
/// <param name="allFiles">List of all files in the repository.</param>
/// <param name="textFiles">List of text files in the repository.</param>
/// <returns>List of binary files in the repository.</returns>
private List<string> DetermineBinaryFiles(IEnumerable<string> allFiles, IEnumerable<string> textFiles)
{
this.Log.Verbose("Determine binary files...");
var result = allFiles.Except(textFiles).ToList();
if (result.Count > 0)
{
this.Log.Debug(string.Join(Environment.NewLine, result));
}
this.Log.Verbose("Found {0} binary file(s)", result.Count);
return result;
}
/// <summary>
/// Determines binary files which are not tracked with LFS.
/// </summary>
/// <param name="binaryFiles">List of binary files in the repository.</param>
/// <param name="lfsTrackedFiles">List of files tracked with LFS in the repository.</param>
/// <returns>List of binary files in the repository which are not tracked with LFS.</returns>
private List<string> DetermineBinaryFilesNotTrackedWithLfs(IEnumerable<string> binaryFiles, IEnumerable<string> lfsTrackedFiles)
{
this.Log.Verbose("Checking if binary files are tracked by LFS...");
var binaryFilesNotTrackedWithLfs = binaryFiles.Except(lfsTrackedFiles).ToList();
if (binaryFilesNotTrackedWithLfs.Count > 0)
{
this.Log.Debug(string.Join(Environment.NewLine, binaryFilesNotTrackedWithLfs));
}
this.Log.Verbose("Found {0} binary file(s) not tracked by LFS", binaryFilesNotTrackedWithLfs.Count);
return binaryFilesNotTrackedWithLfs;
}
}