forked from Azure/azure-sdk-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
272 lines (231 loc) · 10 KB
/
Program.cs
File metadata and controls
272 lines (231 loc) · 10 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PipelineGenerator.Conventions;
using PipelineGenerator.CommandParserOptions;
namespace PipelineGenerator
{
public class Program
{
public static async Task Main(string[] args)
{
var cancellationTokenSource = new CancellationTokenSource();
Console.CancelKeyPress += (sender, e) =>
{
cancellationTokenSource.Cancel();
};
await Parser.Default
.ParseArguments<DefaultOptions, GenerateOptions>(args)
.WithNotParsed(_ => { Environment.Exit((int)ExitCondition.InvalidArguments); })
.WithParsedAsync(async o => { await Run(o, cancellationTokenSource); });
}
public static async Task Run(object commandObj, CancellationTokenSource cancellationTokenSource)
{
ExitCondition code = ExitCondition.Exception;
switch (commandObj)
{
case GenerateOptions g:
var serviceProvider = GetServiceProvider(g.Debug);
var program = serviceProvider.GetService<Program>();
code = await program.RunAsync(
g.Organization,
g.Project,
g.Prefix,
g.Path,
g.Endpoint,
g.Repository,
g.Branch,
g.Agentpool,
g.Convention,
g.VariableGroups.ToArray(),
g.DevOpsPath,
g.WhatIf,
g.Open,
g.Destroy,
g.NoSchedule,
g.SetManagedVariables,
g.OverwriteTriggers,
cancellationTokenSource.Token
);
break;
default:
code = ExitCondition.InvalidArguments;
break;
}
Environment.Exit((int)code);
}
private static IServiceProvider GetServiceProvider(bool debug)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(config => config.AddConsole().SetMinimumLevel(debug ? LogLevel.Debug : LogLevel.Information))
.AddTransient<Program>()
.AddTransient<SdkComponentScanner>()
.AddTransient<PullRequestValidationPipelineConvention>()
.AddTransient<IntegrationTestingPipelineConvention>();
return serviceCollection.BuildServiceProvider();
}
public Program(IServiceProvider serviceProvider, ILogger<Program> logger)
{
this.serviceProvider = serviceProvider;
this.logger = logger;
}
private IServiceProvider serviceProvider;
private ILogger<Program> logger;
public ILoggerFactory LoggerFactory { get; }
private PipelineConvention GetPipelineConvention(string convention, PipelineGenerationContext context)
{
var normalizedConvention = convention.ToLower();
switch (normalizedConvention)
{
case "ci":
var ciLogger = serviceProvider.GetService<ILogger<PullRequestValidationPipelineConvention>>();
return new PullRequestValidationPipelineConvention(ciLogger, context);
case "up":
var upLogger = serviceProvider.GetService<ILogger<UnifiedPipelineConvention>>();
return new UnifiedPipelineConvention(upLogger, context);
case "upweekly":
var upWeeklyTestLogger = serviceProvider.GetService<ILogger<WeeklyUnifiedPipelineConvention>>();
return new WeeklyUnifiedPipelineConvention(upWeeklyTestLogger, context);
case "tests":
var testLogger = serviceProvider.GetService<ILogger<IntegrationTestingPipelineConvention>>();
return new IntegrationTestingPipelineConvention(testLogger, context);
case "testsweekly":
var weeklyTestLogger = serviceProvider.GetService<ILogger<WeeklyIntegrationTestingPipelineConvention>>();
return new WeeklyIntegrationTestingPipelineConvention(weeklyTestLogger, context);
default: throw new ArgumentOutOfRangeException(nameof(convention), "Could not find matching convention.");
}
}
public async Task<ExitCondition> RunAsync(
string organization,
string project,
string prefix,
string path,
string endpoint,
string repository,
string branch,
string agentPool,
string convention,
int[] variableGroups,
string devOpsPath,
bool whatIf,
bool open,
bool destroy,
bool noSchedule,
bool setManagedVariables,
bool overwriteTriggers,
CancellationToken cancellationToken)
{
try
{
logger.LogDebug("Creating context.");
// Fall back to a form of prefix if DevOps path is not specified
var devOpsPathValue = string.IsNullOrEmpty(devOpsPath) ? $"\\{prefix}" : devOpsPath;
var context = new PipelineGenerationContext(
this.logger,
organization,
project,
endpoint,
repository,
branch,
agentPool,
variableGroups,
devOpsPathValue,
prefix,
whatIf,
noSchedule,
setManagedVariables,
overwriteTriggers
);
var pipelineConvention = GetPipelineConvention(convention, context);
var components = ScanForComponents(path, pipelineConvention.SearchPattern);
if (components.Count() == 0)
{
logger.LogWarning("No components were found.");
return ExitCondition.NoComponentsFound;
}
logger.LogInformation("Found {0} components", components.Count());
if (HasPipelineDefinitionNameDuplicates(pipelineConvention, components))
{
return ExitCondition.DuplicateComponentsFound;
}
foreach (var component in components)
{
logger.LogInformation("Processing component '{0}' in '{1}'.", component.Name, component.Path);
if (destroy)
{
var definition = await pipelineConvention.DeleteDefinitionAsync(component, cancellationToken);
}
else
{
var definition = await pipelineConvention.CreateOrUpdateDefinitionAsync(component, cancellationToken);
if (open)
{
OpenBrowser(definition.GetWebUrl());
}
}
}
return ExitCondition.Success;
}
catch (Exception ex)
{
logger.LogCritical(ex, "BOOM! Something went wrong, try running with --debug.");
return ExitCondition.Exception;
}
}
private void OpenBrowser(string url)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
return;
}
logger.LogDebug("Launching browser window for: {0}", url);
var processStartInfo = new ProcessStartInfo()
{
FileName = url,
UseShellExecute = true,
};
// TODO: Need to test this on macOS and Linux.
System.Diagnostics.Process.Start(processStartInfo);
}
private IEnumerable<SdkComponent> ScanForComponents(string path, string searchPattern)
{
var scanner = serviceProvider.GetService<SdkComponentScanner>();
var scanDirectory = new DirectoryInfo(path);
var components = scanner.Scan(scanDirectory, searchPattern);
return components;
}
private bool HasPipelineDefinitionNameDuplicates(PipelineConvention convention, IEnumerable<SdkComponent> components)
{
var pipelineNames = new Dictionary<string, SdkComponent>();
var duplicates = new HashSet<SdkComponent>();
foreach (var component in components)
{
var definitionName = convention.GetDefinitionName(component);
if (pipelineNames.TryGetValue(definitionName, out var duplicate))
{
duplicates.Add(duplicate);
duplicates.Add(component);
}
else
{
pipelineNames.Add(definitionName, component);
}
}
if (duplicates.Count > 0) {
logger.LogError("Found multiple pipeline definitions that will result in name collisions. This can happen when nested directory names are the same.");
logger.LogError("Suggested fix: add a 'variant' to the yaml filename, e.g. 'sdk/keyvault/internal/ci.yml' => 'sdk/keyvault/internal/ci.keyvault.yml'");
var paths = duplicates.Select(d => $"'{d.RelativeYamlPath}'");
logger.LogError($"Pipeline definitions affected: {String.Join(", ", paths)}");
return true;
}
return false;
}
}
}