-
Notifications
You must be signed in to change notification settings - Fork 821
Expand file tree
/
Copy pathPingetPackageDetailsProvider.cs
More file actions
614 lines (544 loc) · 20.3 KB
/
PingetPackageDetailsProvider.cs
File metadata and controls
614 lines (544 loc) · 20.3 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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using Devolutions.Pinget.Core;
using UniGetUI.Core.Data;
using UniGetUI.Core.Logging;
using UniGetUI.Core.Tools;
using UniGetUI.PackageEngine.Interfaces;
using UniGetUI.PackageEngine.ManagerClasses.Classes;
namespace UniGetUI.PackageEngine.Managers.WingetManager;
internal interface IPingetPackageDetailsProvider
{
bool LoadPackageDetails(IPackageDetails details, INativeTaskLogger logger);
}
internal sealed class PingetCliPackageDetailsProvider(string cliExecutablePath)
: IPingetPackageDetailsProvider
{
public bool LoadPackageDetails(IPackageDetails details, INativeTaskLogger logger)
{
try
{
PackageQuery query = PingetPackageDetailsProvider.CreateQuery(details.Package);
logger.Log("Loading WinGet installer metadata with bundled Pinget CLI");
logger.Log($" Query: {PingetPackageDetailsProvider.FormatQueryForLog(query)}");
string output = RunShow(query, logger);
ApplyManifestJson(details, output);
return true;
}
catch (Exception ex)
{
Logger.Warn(
"Could not load WinGet installer metadata with bundled Pinget CLI for package "
+ $"{details.Package.Id}: {ex.Message}"
);
logger.Error(ex);
return false;
}
}
private string RunShow(PackageQuery query, INativeTaskLogger logger)
{
List<string?> sources = [query.Source];
if (string.IsNullOrWhiteSpace(query.Source))
{
sources.AddRange(GetSourceNames(logger));
}
Exception? lastException = null;
foreach (string? source in sources.Distinct(StringComparer.OrdinalIgnoreCase))
{
try
{
logger.Log(
string.IsNullOrWhiteSpace(source)
? " Running source-less Pinget CLI show query"
: $" Running Pinget CLI show query with source {source}"
);
return RunPinget(BuildShowArguments(query, source), logger);
}
catch (Exception ex)
{
lastException = ex;
logger.Log(
string.IsNullOrWhiteSpace(source)
? " Source-less Pinget CLI show query failed: " + ex.Message
: $" Pinget CLI show query failed for source {source}: {ex.Message}"
);
if (!string.IsNullOrWhiteSpace(query.Source))
{
break;
}
}
}
throw lastException ?? new InvalidOperationException("Pinget CLI did not return package details.");
}
private IReadOnlyList<string> GetSourceNames(INativeTaskLogger logger)
{
try
{
string output = RunPinget(["source", "export", "--output", "json"], logger);
using JsonDocument document = JsonDocument.Parse(output);
if (
!document.RootElement.TryGetProperty("Sources", out JsonElement sources)
|| sources.ValueKind != JsonValueKind.Array
)
{
return [];
}
return sources
.EnumerateArray()
.Select(source =>
source.TryGetProperty("Name", out JsonElement name)
? name.GetString()
: null
)
.Where(name => !string.IsNullOrWhiteSpace(name))
.ToArray()!;
}
catch (Exception ex)
{
logger.Log(" Could not list bundled Pinget CLI sources for retry: " + ex.Message);
return [];
}
}
private static IReadOnlyList<string> BuildShowArguments(PackageQuery query, string? source)
{
List<string> arguments = ["show"];
if (!string.IsNullOrWhiteSpace(query.Id))
{
arguments.Add("--id");
arguments.Add(query.Id);
}
else if (!string.IsNullOrWhiteSpace(query.Name))
{
arguments.Add("--name");
arguments.Add(query.Name);
}
if (query.Exact)
{
arguments.Add("--exact");
}
if (!string.IsNullOrWhiteSpace(source))
{
arguments.Add("--source");
arguments.Add(source);
}
if (!string.IsNullOrWhiteSpace(query.Version))
{
arguments.Add("--version");
arguments.Add(query.Version);
}
arguments.Add("--output");
arguments.Add("json");
return arguments;
}
private string RunPinget(IReadOnlyList<string> arguments, INativeTaskLogger logger)
{
using Process process = new()
{
StartInfo = new ProcessStartInfo
{
FileName = cliExecutablePath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
},
};
foreach (string argument in arguments)
{
process.StartInfo.ArgumentList.Add(argument);
}
if (CoreTools.IsAdministrator())
{
string winGetTemp = Path.Join(Path.GetTempPath(), "UniGetUI", "ElevatedWinGetTemp");
logger.Log(
$"[WARN] Redirecting %TEMP% folder to {winGetTemp}, since UniGetUI was run as admin"
);
process.StartInfo.Environment["TEMP"] = winGetTemp;
process.StartInfo.Environment["TMP"] = winGetTemp;
}
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
string detail = string.Join(
Environment.NewLine,
new[] { error, output }.Where(text => !string.IsNullOrWhiteSpace(text))
);
throw new InvalidOperationException(
string.IsNullOrWhiteSpace(detail)
? $"Pinget exited with code {process.ExitCode}."
: detail.Trim()
);
}
return output;
}
private static void ApplyManifestJson(IPackageDetails details, string output)
{
using JsonDocument document = JsonDocument.Parse(output);
JsonElement manifest = document.RootElement;
JsonElement installer = default;
bool hasInstaller =
manifest.TryGetProperty("Installers", out JsonElement installers)
&& installers.ValueKind == JsonValueKind.Array
&& installers.GetArrayLength() > 0
&& (installer = installers[0]).ValueKind == JsonValueKind.Object;
SetIfMissing(value => details.Author = value, details.Author, GetString(manifest, "Author"));
SetIfMissing(
value => details.Description = value,
details.Description,
GetString(manifest, "Description") ?? GetString(manifest, "ShortDescription")
);
SetIfMissing(value => details.License = value, details.License, GetString(manifest, "License"));
SetIfMissing(
value => details.Publisher = value,
details.Publisher,
GetString(manifest, "Publisher")
);
SetIfMissing(
value => details.ReleaseNotes = value,
details.ReleaseNotes,
GetString(manifest, "ReleaseNotes")
);
SetUriIfMissing(uri => details.HomepageUrl = uri, details.HomepageUrl, GetString(manifest, "PackageUrl"));
SetUriIfMissing(uri => details.LicenseUrl = uri, details.LicenseUrl, GetString(manifest, "LicenseUrl"));
SetUriIfMissing(
uri => details.ReleaseNotesUrl = uri,
details.ReleaseNotesUrl,
GetString(manifest, "ReleaseNotesUrl")
);
if (
details.Tags.Length == 0
&& manifest.TryGetProperty("Tags", out JsonElement tags)
&& tags.ValueKind == JsonValueKind.Array
)
{
details.Tags = tags
.EnumerateArray()
.Select(tag => tag.GetString())
.Where(tag => !string.IsNullOrWhiteSpace(tag))
.ToArray()!;
}
// ReleaseDate is set at the manifest root by default, with an optional per-installer override
SetIfPresent(value => details.UpdateDate = value,
(hasInstaller ? GetString(installer, "ReleaseDate") : null) ?? GetString(manifest, "ReleaseDate"));
if (hasInstaller)
{
SetIfPresent(value => details.InstallerHash = value, GetString(installer, "InstallerSha256"));
SetIfPresent(value => details.InstallerType = value, GetString(installer, "InstallerType"));
if (TryCreateUri(GetString(installer, "InstallerUrl"), out Uri? installerUri))
{
details.InstallerUrl = installerUri;
details.InstallerSize = CoreTools.GetFileSizeAsLong(installerUri);
}
}
}
private static string? GetString(JsonElement element, string propertyName) =>
element.TryGetProperty(propertyName, out JsonElement value)
&& value.ValueKind == JsonValueKind.String
? value.GetString()
: null;
private static void SetIfMissing(
Action<string> setValue,
string? currentValue,
string? newValue
)
{
if (string.IsNullOrWhiteSpace(currentValue) && !string.IsNullOrWhiteSpace(newValue))
{
setValue(newValue);
}
}
private static void SetIfPresent(Action<string> setValue, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
setValue(value);
}
}
private static void SetUriIfMissing(
Action<Uri> setValue,
Uri? currentValue,
string? newValue
)
{
if (currentValue is null && TryCreateUri(newValue, out Uri? uri) && uri is not null)
{
setValue(uri);
}
}
private static bool TryCreateUri([NotNullWhen(true)] string? value, out Uri? uri)
{
return Uri.TryCreate(value, UriKind.Absolute, out uri);
}
}
internal sealed class PingetPackageDetailsProvider : IPingetPackageDetailsProvider
{
private readonly Func<PackageQuery, ShowResult> _showPackage;
private readonly Func<Uri, long> _installerSizeResolver;
public PingetPackageDetailsProvider()
: this(ShowWithRepository) { }
internal PingetPackageDetailsProvider(
Func<PackageQuery, ShowResult> showPackage,
Func<Uri, long>? installerSizeResolver = null
)
{
_showPackage = showPackage;
_installerSizeResolver = installerSizeResolver ?? CoreTools.GetFileSizeAsLong;
}
public bool LoadPackageDetails(IPackageDetails details, INativeTaskLogger logger)
{
try
{
PackageQuery query = CreateQuery(details.Package);
logger.Log("Loading WinGet installer metadata with Pinget");
logger.Log($" Query: {FormatQueryForLog(query)}");
Logger.Info($"Loading WinGet installer metadata with Pinget. Query: {FormatQueryForLog(query)}");
ShowResult result = _showPackage(query);
foreach (string warning in result.Warnings)
{
logger.Log(" Pinget warning: " + warning);
}
ApplyShowResult(details, result, _installerSizeResolver);
return true;
}
catch (Exception ex)
{
Logger.Warn(
"Could not load WinGet installer metadata with Pinget for package "
+ $"{details.Package.Id}: {ex.Message}"
);
logger.Error(ex);
return false;
}
}
internal static PackageQuery CreateQuery(IPackage package, string? version = null)
{
string id = package.Id.TrimEnd('…');
string name = package.Name.TrimEnd('…');
PackageQuery query;
if (!string.IsNullOrWhiteSpace(id))
{
query = new PackageQuery
{
Id = id,
Exact = !package.Id.EndsWith('…'),
};
}
else
{
query = new PackageQuery
{
Name = name,
Exact = !package.Name.EndsWith('…'),
};
}
if (
!package.Source.IsVirtualManager
&& !string.IsNullOrWhiteSpace(package.Source.Name)
&& !IsEllipsized(package.Source.Name)
)
{
query = query with { Source = package.Source.Name };
}
if (!string.IsNullOrWhiteSpace(version))
{
query = query with { Version = version };
}
return query;
}
internal static void ApplyShowResult(
IPackageDetails details,
ShowResult result,
Func<Uri, long>? installerSizeResolver = null
)
{
installerSizeResolver ??= CoreTools.GetFileSizeAsLong;
Manifest manifest = result.Manifest;
Installer? installer = result.SelectedInstaller ?? manifest.Installers.FirstOrDefault();
SetIfMissing(value => details.Author = value, details.Author, manifest.Author);
SetIfMissing(
value => details.Description = value,
details.Description,
manifest.Description ?? manifest.ShortDescription
);
SetIfMissing(value => details.License = value, details.License, manifest.License);
SetIfMissing(value => details.Publisher = value, details.Publisher, manifest.Publisher);
SetIfMissing(value => details.ReleaseNotes = value, details.ReleaseNotes, manifest.ReleaseNotes);
SetUriIfMissing(uri => details.HomepageUrl = uri, details.HomepageUrl, manifest.PackageUrl);
SetUriIfMissing(uri => details.LicenseUrl = uri, details.LicenseUrl, manifest.LicenseUrl);
SetUriIfMissing(
uri => details.ReleaseNotesUrl = uri,
details.ReleaseNotesUrl,
manifest.ReleaseNotesUrl
);
if (details.Tags.Length == 0 && manifest.Tags.Count > 0)
{
details.Tags = manifest.Tags.ToArray();
}
if (installer is not null)
{
SetIfPresent(value => details.InstallerHash = value, installer.Sha256);
SetIfPresent(value => details.InstallerType = value, installer.InstallerType);
SetIfPresent(value => details.UpdateDate = value, installer.ReleaseDate);
if (TryCreateUri(installer.Url, out Uri? installerUri))
{
details.InstallerUrl = installerUri;
details.InstallerSize = installerSizeResolver(installerUri);
}
}
details.Dependencies.Clear();
foreach (string dependency in manifest.PackageDependencies.Concat(
installer?.PackageDependencies ?? []
).Distinct(StringComparer.OrdinalIgnoreCase))
{
if (TryCreateDependency(dependency, out IPackageDetails.Dependency parsedDependency))
{
details.Dependencies.Add(parsedDependency);
}
}
}
private static ShowResult ShowWithRepository(PackageQuery query)
{
using Repository repository = OpenRepository();
return repository.ShowFirstMatchAcrossSources(query);
}
/// <summary>
/// Fetches the set of installer URL hosts for a specific version of a package.
/// Returns null if the manifest can't be loaded, OR a non-empty set otherwise.
/// Used to detect installer-host changes between installed and upgrade versions (issue #4617).
/// Returns the SET (not just one) because manifests typically have multiple installers
/// (per arch / locale / scope) — flagging on a single-installer comparison can produce
/// false positives when a publisher legitimately uses different CDNs per architecture
/// or adds/removes architectures across versions.
/// </summary>
internal static IReadOnlySet<string>? TryGetInstallerHostsForVersion(
IPackage package,
string version
)
{
try
{
PackageQuery query = CreateQuery(package, version);
ShowResult result;
using (Repository repository = OpenRepository())
{
result = repository.ShowFirstMatchAcrossSources(query);
}
// Pinget silently falls back to the latest manifest when the requested version
// isn't in the index (yanked / expired / never indexed). That fallback would
// make the host-change check return false-negatives, so reject any result whose
// manifest version doesn't match what we asked for.
string returnedVersion = result.Manifest.Version ?? "";
if (!string.Equals(returnedVersion, version, StringComparison.OrdinalIgnoreCase))
{
Logger.Info(
$"Pinget returned manifest version '{returnedVersion}' when '{version}' "
+ $"was requested for {package.Id}; treating as not found"
);
return null;
}
HashSet<string> hosts = new(StringComparer.OrdinalIgnoreCase);
foreach (Installer installer in result.Manifest.Installers)
{
if (TryCreateUri(installer.Url, out Uri? uri) && uri is not null)
hosts.Add(uri.Host);
}
return hosts.Count > 0 ? hosts : null;
}
catch (Exception ex)
{
Logger.Warn(
$"Could not resolve installer hosts for {package.Id} version {version}: {ex.Message}"
);
return null;
}
}
private static Repository OpenRepository()
{
return Repository.Open(CreateRepositoryOptions());
}
internal static RepositoryOptions CreateRepositoryOptions()
{
return new RepositoryOptions
{
UserAgent = CoreData.UserAgentString,
};
}
internal static string FormatQueryForLog(PackageQuery query)
{
return string.Join(
", ",
new[]
{
$"Id={query.Id}",
$"Name={query.Name}",
$"Source={query.Source}",
$"Exact={query.Exact}",
}.Where(part => !part.EndsWith("="))
);
}
private static bool IsEllipsized(string value) => value.Contains('…');
private static void SetIfMissing(
Action<string> setValue,
string? currentValue,
string? newValue
)
{
if (string.IsNullOrWhiteSpace(currentValue) && !string.IsNullOrWhiteSpace(newValue))
{
setValue(newValue);
}
}
private static void SetIfPresent(Action<string> setValue, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
setValue(value);
}
}
private static void SetUriIfMissing(Action<Uri> setValue, Uri? currentValue, string? value)
{
if (currentValue is null && TryCreateUri(value, out Uri? uri))
{
setValue(uri);
}
}
private static bool TryCreateUri(string? value, [NotNullWhen(true)] out Uri? uri)
{
return Uri.TryCreate(value, UriKind.Absolute, out uri);
}
private static bool TryCreateDependency(
string value,
out IPackageDetails.Dependency dependency
)
{
dependency = default;
string trimmedValue = value.Trim();
if (trimmedValue == "")
return false;
string name = trimmedValue;
string version = "";
int versionStart = trimmedValue.IndexOf('[', StringComparison.Ordinal);
if (versionStart >= 0)
{
name = trimmedValue[..versionStart].Trim();
version = trimmedValue[(versionStart + 1)..].TrimEnd(']').Trim();
}
if (name.Contains(' '))
{
name = name.Split(' ', StringSplitOptions.RemoveEmptyEntries)[0];
}
if (name == "")
return false;
dependency = new IPackageDetails.Dependency
{
Name = name,
Version = version,
Mandatory = true,
};
return true;
}
}