-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathModuleBuildPreparationService.cs
More file actions
259 lines (220 loc) · 10.7 KB
/
ModuleBuildPreparationService.cs
File metadata and controls
259 lines (220 loc) · 10.7 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
using System.Collections;
using System.IO;
using System.Management.Automation;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PowerForge;
internal sealed class ModuleBuildPreparationService
{
public ModuleBuildPreparedContext Prepare(ModuleBuildPreparationRequest request)
{
if (request is null)
throw new ArgumentNullException(nameof(request));
if (string.IsNullOrWhiteSpace(request.CurrentPath))
throw new ArgumentException("Current path is required.", nameof(request));
if (request.ResolvePath is null)
throw new ArgumentException("ResolvePath is required.", nameof(request));
var moduleName = string.Equals(request.ParameterSetName, "Configuration", StringComparison.Ordinal)
? LegacySegmentAdapter.ResolveModuleNameFromLegacyConfiguration(request.Configuration)
: request.ModuleName;
if (string.IsNullOrWhiteSpace(moduleName))
throw new PSArgumentException("ModuleName is required.");
var (projectRoot, basePathForScaffold) = ResolveProjectPaths(request, moduleName!);
var useLegacy = request.Legacy ||
string.Equals(request.ParameterSetName, "Configuration", StringComparison.Ordinal) ||
request.Settings is not null;
var segments = useLegacy
? (string.Equals(request.ParameterSetName, "Configuration", StringComparison.Ordinal)
? LegacySegmentAdapter.CollectFromLegacyConfiguration(request.Configuration)
: LegacySegmentAdapter.CollectFromSettings(request.Settings))
: Array.Empty<IConfigurationSegment>();
var frameworks = useLegacy && !request.DotNetFrameworkWasBound
? Array.Empty<string>()
: request.DotNetFramework;
var spec = new ModulePipelineSpec
{
Build = new ModuleBuildSpec
{
Name = moduleName!,
SourcePath = projectRoot,
StagingPath = request.StagingPath,
CsprojPath = request.CsprojPath,
Version = "1.0.0",
Configuration = request.DotNetConfiguration,
Frameworks = frameworks,
KeepStaging = request.KeepStaging,
ExcludeDirectories = request.ExcludeDirectories ?? Array.Empty<string>(),
ExcludeFiles = BuildStageExcludeFiles(request.ExcludeFiles, moduleName!),
BinaryConflictSearchRoots = request.DiagnosticsBinaryConflictSearchRoot ?? Array.Empty<string>(),
},
Install = new ModulePipelineInstallOptions
{
Enabled = !request.SkipInstall,
Strategy = request.InstallStrategyWasBound ? request.InstallStrategy : null,
KeepVersions = request.KeepVersionsWasBound ? request.KeepVersions : null,
Roots = request.InstallRootsWasBound ? (request.InstallRoots ?? Array.Empty<string>()) : null,
LegacyFlatHandling = request.LegacyFlatHandlingWasBound ? request.LegacyFlatHandling : null,
PreserveVersions = request.PreserveInstallVersionsWasBound ? request.PreserveInstallVersions : null,
},
Diagnostics = new ModulePipelineDiagnosticsOptions
{
BaselinePath = request.DiagnosticsBaselinePath,
GenerateBaseline = request.GenerateDiagnosticsBaseline,
UpdateBaseline = request.UpdateDiagnosticsBaseline,
FailOnNewDiagnostics = request.FailOnNewDiagnostics,
FailOnSeverity = request.FailOnDiagnosticsSeverity,
BinaryConflictSearchRoots = request.DiagnosticsBinaryConflictSearchRoot ?? Array.Empty<string>()
},
Segments = segments
};
spec.Build.Version = ResolveBaseVersion(projectRoot, moduleName!, segments);
return new ModuleBuildPreparedContext
{
ModuleName = moduleName!,
ProjectRoot = projectRoot,
BasePathForScaffold = basePathForScaffold,
UseLegacy = useLegacy,
PipelineSpec = spec,
JsonOutputPath = request.JsonOnly ? ResolveJsonOutputPath(request, projectRoot) : null
};
}
public void WritePipelineSpecJson(ModulePipelineSpec spec, string jsonFullPath)
{
if (spec is null) throw new ArgumentNullException(nameof(spec));
if (string.IsNullOrWhiteSpace(jsonFullPath)) throw new ArgumentException("Json path is required.", nameof(jsonFullPath));
PrepareSpecForJsonExport(spec, jsonFullPath);
var opts = new JsonSerializerOptions
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
opts.Converters.Add(new JsonStringEnumConverter());
opts.Converters.Add(new ConfigurationSegmentJsonConverter());
var outDir = Path.GetDirectoryName(jsonFullPath);
if (!string.IsNullOrWhiteSpace(outDir))
Directory.CreateDirectory(outDir);
var json = JsonSerializer.Serialize(spec, opts) + Environment.NewLine;
File.WriteAllText(jsonFullPath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
}
private static string ResolveBaseVersion(string projectRoot, string moduleName, IReadOnlyList<IConfigurationSegment>? segments)
{
var configuredVersion = ResolveConfiguredVersion(segments);
if (!string.IsNullOrWhiteSpace(configuredVersion))
return configuredVersion!;
return ResolveBaseVersion(projectRoot, moduleName);
}
private static string? ResolveConfiguredVersion(IReadOnlyList<IConfigurationSegment>? segments)
{
if (segments is null || segments.Count == 0)
return null;
for (var index = segments.Count - 1; index >= 0; index--)
{
if (segments[index] is not ConfigurationManifestSegment manifest)
continue;
var moduleVersion = manifest.Configuration?.ModuleVersion;
if (!string.IsNullOrWhiteSpace(moduleVersion))
{
var trimmed = (moduleVersion ?? string.Empty).Trim();
if (!string.IsNullOrWhiteSpace(trimmed))
return trimmed;
}
}
return null;
}
private static string ResolveBaseVersion(string projectRoot, string moduleName)
{
var baseVersion = "1.0.0";
var psd1 = Path.Combine(projectRoot, $"{moduleName}.psd1");
if (File.Exists(psd1) &&
ManifestEditor.TryGetTopLevelString(psd1, "ModuleVersion", out var version) &&
!string.IsNullOrWhiteSpace(version))
{
baseVersion = version!;
}
return baseVersion;
}
private static (string ProjectRoot, string? BasePathForScaffold) ResolveProjectPaths(ModuleBuildPreparationRequest request, string moduleName)
{
if (string.Equals(request.ParameterSetName, "Modern", StringComparison.Ordinal) && !string.IsNullOrWhiteSpace(request.InputPath))
{
var basePath = request.ResolvePath!(request.InputPath!);
var fullProjectPath = Path.Combine(basePath, moduleName);
return (fullProjectPath, basePath);
}
var rootToUse = !string.IsNullOrWhiteSpace(request.ScriptRoot)
? Path.GetFullPath(Path.Combine(request.ScriptRoot!, ".."))
: request.CurrentPath;
return (rootToUse, null);
}
private static string[] BuildStageExcludeFiles(string[]? excludeFiles, string moduleName)
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in (excludeFiles ?? Array.Empty<string>()).Where(s => !string.IsNullOrWhiteSpace(s)))
set.Add(entry.Trim());
if (!string.IsNullOrWhiteSpace(moduleName))
set.Add($"{moduleName}.Tests.ps1");
return set.ToArray();
}
private static string ResolveJsonOutputPath(ModuleBuildPreparationRequest request, string projectRoot)
{
if (!string.IsNullOrWhiteSpace(request.JsonPath))
return request.ResolvePath!(request.JsonPath!);
return Path.Combine(projectRoot, "powerforge.json");
}
private static void PrepareSpecForJsonExport(ModulePipelineSpec spec, string jsonFullPath)
{
if (spec.Build is null) throw new ArgumentException("Spec.Build is required.", nameof(spec));
var baseDir = Path.GetDirectoryName(jsonFullPath);
if (string.IsNullOrWhiteSpace(baseDir)) return;
spec.Build.SourcePath = MakeRelativeForConfig(baseDir, spec.Build.SourcePath);
spec.Build.StagingPath = MakeRelativeForConfigNullable(baseDir, spec.Build.StagingPath);
spec.Build.CsprojPath = MakeRelativeForConfigNullable(baseDir, spec.Build.CsprojPath);
if (spec.Diagnostics is not null && !string.IsNullOrWhiteSpace(spec.Diagnostics.BaselinePath))
spec.Diagnostics.BaselinePath = MakeRelativeForConfig(baseDir, spec.Diagnostics.BaselinePath!);
}
private static string MakeRelativeForConfig(string baseDir, string path)
{
if (string.IsNullOrWhiteSpace(path)) return path;
try
{
var full = Path.GetFullPath(path);
var rel = GetRelativePath(baseDir, full);
return rel.Replace('\\', '/');
}
catch
{
return path.Replace('\\', '/');
}
}
private static string? MakeRelativeForConfigNullable(string baseDir, string? path)
{
if (string.IsNullOrWhiteSpace(path)) return null;
return MakeRelativeForConfig(baseDir, path!);
}
private static string GetRelativePath(string baseDir, string fullPath)
{
#if NET472
var baseFull = EnsureTrailingSeparator(Path.GetFullPath(baseDir));
var baseUri = new Uri(baseFull);
var pathUri = new Uri(Path.GetFullPath(fullPath));
if (!string.Equals(baseUri.Scheme, pathUri.Scheme, StringComparison.OrdinalIgnoreCase))
return fullPath;
var relativeUri = baseUri.MakeRelativeUri(pathUri);
var relative = Uri.UnescapeDataString(relativeUri.ToString());
return relative.Replace('/', Path.DirectorySeparatorChar);
#else
return Path.GetRelativePath(baseDir, fullPath);
#endif
#if NET472
static string EnsureTrailingSeparator(string input)
{
if (string.IsNullOrWhiteSpace(input)) return input;
if (input.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) ||
input.EndsWith(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal))
return input;
return input + Path.DirectorySeparatorChar;
}
#endif
}
}