|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Net.Http.Headers; |
| 3 | +using System.Text; |
| 4 | +using System.Text.RegularExpressions; |
| 5 | +using UniGetUI.Core.Logging; |
| 6 | +using UniGetUI.PackageEngine.Classes.Manager; |
| 7 | +using UniGetUI.PackageEngine.Classes.Manager.Providers; |
| 8 | +using UniGetUI.PackageEngine.Enums; |
| 9 | +using UniGetUI.PackageEngine.Interfaces; |
| 10 | +using UniGetUI.PackageEngine.ManagerClasses.Classes; |
| 11 | +using UniGetUI.PackageEngine.Managers.Generic.NuGet; |
| 12 | + |
| 13 | +namespace UniGetUI.PackageEngine.Managers.DotNetManager; |
| 14 | + |
| 15 | +internal sealed record NuGetConfiguredSource(string Key, Uri Url); |
| 16 | + |
| 17 | +internal sealed class DotNetNuGetConfiguration |
| 18 | +{ |
| 19 | + private readonly IReadOnlyList<(string Path, DateTime? LastWriteTimeUtc)> _files; |
| 20 | + private readonly DateTime _loadedAtUtc; |
| 21 | + private DateTime _filesCheckedAtUtc; |
| 22 | + |
| 23 | + public DotNetNuGetConfiguration( |
| 24 | + IReadOnlyList<IManagerSource> sources, |
| 25 | + IReadOnlyList<NuGetConfiguredSource> configuredSources, |
| 26 | + NuGetSourceMapping mapping, |
| 27 | + IReadOnlyList<string> files, |
| 28 | + bool canBeReused |
| 29 | + ) |
| 30 | + { |
| 31 | + Sources = sources; |
| 32 | + ConfiguredSources = configuredSources; |
| 33 | + Mapping = mapping; |
| 34 | + CanBeReused = canBeReused; |
| 35 | + _files = [.. files.Select(path => (path, LastWriteTime(path)))]; |
| 36 | + _loadedAtUtc = DateTime.UtcNow; |
| 37 | + _filesCheckedAtUtc = _loadedAtUtc; |
| 38 | + } |
| 39 | + |
| 40 | + public IReadOnlyList<IManagerSource> Sources { get; } |
| 41 | + public IReadOnlyList<NuGetConfiguredSource> ConfiguredSources { get; } |
| 42 | + public NuGetSourceMapping Mapping { get; } |
| 43 | + public bool CanBeReused { get; } |
| 44 | + |
| 45 | + public bool IsCurrent(TimeSpan maxAge, TimeSpan fileCheckInterval) |
| 46 | + { |
| 47 | + DateTime now = DateTime.UtcNow; |
| 48 | + if (!CanBeReused || now - _loadedAtUtc >= maxAge) |
| 49 | + return false; |
| 50 | + |
| 51 | + if (now - _filesCheckedAtUtc < fileCheckInterval) |
| 52 | + return true; |
| 53 | + |
| 54 | + if (_files.Any(file => LastWriteTime(file.Path) != file.LastWriteTimeUtc)) |
| 55 | + return false; |
| 56 | + |
| 57 | + _filesCheckedAtUtc = now; |
| 58 | + return true; |
| 59 | + } |
| 60 | + |
| 61 | + public bool Allows(string packageId, Uri sourceUrl) |
| 62 | + { |
| 63 | + if (!Mapping.IsEnabled) |
| 64 | + return true; |
| 65 | + |
| 66 | + IReadOnlySet<string> allowed = Mapping.SourcesFor(packageId); |
| 67 | + return ConfiguredSources.Any(source => |
| 68 | + source.Url == sourceUrl && allowed.Contains(source.Key) |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + private static DateTime? LastWriteTime(string path) => |
| 73 | + File.Exists(path) ? File.GetLastWriteTimeUtc(path) : null; |
| 74 | +} |
| 75 | + |
| 76 | +internal sealed partial class DotNetSourceHelper : ReadOnlySourceHelper |
| 77 | +{ |
| 78 | + private static readonly TimeSpan MaxConfigurationAge = TimeSpan.FromMinutes(10); |
| 79 | + private static readonly TimeSpan ConfigurationFileCheckInterval = TimeSpan.FromSeconds(5); |
| 80 | + |
| 81 | + private readonly Lock _configurationLock = new(); |
| 82 | + private DotNetNuGetConfiguration? _configuration; |
| 83 | + |
| 84 | + public DotNetSourceHelper(DotNet manager) |
| 85 | + : base(manager, "NuGet sources are read from the NuGet configuration.") { } |
| 86 | + |
| 87 | + protected override IReadOnlyList<IManagerSource> GetSources_UnSafe() => |
| 88 | + GetConfiguration().Sources; |
| 89 | + |
| 90 | + internal DotNetNuGetConfiguration GetConfiguration() |
| 91 | + { |
| 92 | + lock (_configurationLock) |
| 93 | + { |
| 94 | + if (_configuration is { } current && current.IsCurrent(MaxConfigurationAge, ConfigurationFileCheckInterval)) |
| 95 | + return current; |
| 96 | + |
| 97 | + _configuration = LoadConfiguration(); |
| 98 | + return _configuration; |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + private DotNetNuGetConfiguration LoadConfiguration() |
| 103 | + { |
| 104 | + try |
| 105 | + { |
| 106 | + var (sourcesExitCode, sourceLines) = RunNuGet("list source --format Detailed"); |
| 107 | + IReadOnlyList<NuGetConfiguredSource>? configured = |
| 108 | + sourcesExitCode is 0 ? ParseSources(sourceLines) : null; |
| 109 | + if (configured is null) |
| 110 | + { |
| 111 | + Logger.Warn( |
| 112 | + $"Could not read the NuGet sources of {Manager.Name}, falling back to {Manager.Properties.DefaultSource.Name}" |
| 113 | + ); |
| 114 | + return Fallback(); |
| 115 | + } |
| 116 | + |
| 117 | + var (pathsExitCode, pathLines) = RunNuGet("config paths"); |
| 118 | + IReadOnlyList<string> files = |
| 119 | + pathsExitCode is 0 |
| 120 | + ? [.. pathLines.Select(line => line.Trim()).Where(File.Exists)] |
| 121 | + : []; |
| 122 | + NuGetConfigSettings settings = NuGetConfigFiles.Read(files); |
| 123 | + |
| 124 | + NuGetFeedCredentials.Replace(BuildCredentials(configured, settings)); |
| 125 | + |
| 126 | + return new DotNetNuGetConfiguration( |
| 127 | + ToManagerSources(configured), |
| 128 | + configured, |
| 129 | + settings.Mapping, |
| 130 | + files, |
| 131 | + canBeReused: true |
| 132 | + ); |
| 133 | + } |
| 134 | + catch (Exception ex) |
| 135 | + { |
| 136 | + Logger.Warn($"Could not read the NuGet configuration of {Manager.Name}"); |
| 137 | + Logger.Warn(ex); |
| 138 | + return Fallback(); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + private DotNetNuGetConfiguration Fallback() => |
| 143 | + new( |
| 144 | + [Manager.Properties.DefaultSource], |
| 145 | + [new NuGetConfiguredSource(Manager.Properties.DefaultSource.Name, Manager.Properties.DefaultSource.Url)], |
| 146 | + NuGetSourceMapping.None, |
| 147 | + [], |
| 148 | + canBeReused: false |
| 149 | + ); |
| 150 | + |
| 151 | + internal IReadOnlyList<IManagerSource> ToManagerSources( |
| 152 | + IReadOnlyList<NuGetConfiguredSource> configured |
| 153 | + ) |
| 154 | + { |
| 155 | + IManagerSource defaultSource = Manager.Properties.DefaultSource; |
| 156 | + List<IManagerSource> sources = []; |
| 157 | + foreach (NuGetConfiguredSource source in configured) |
| 158 | + { |
| 159 | + if (source.Url == defaultSource.Url) |
| 160 | + { |
| 161 | + if (!sources.Contains(defaultSource)) |
| 162 | + sources.Add(defaultSource); |
| 163 | + } |
| 164 | + else |
| 165 | + { |
| 166 | + sources.Add(new ManagerSource(Manager, source.Key, source.Url)); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + return sources; |
| 171 | + } |
| 172 | + |
| 173 | + internal static IEnumerable<(Uri Source, AuthenticationHeaderValue Header)> BuildCredentials( |
| 174 | + IReadOnlyList<NuGetConfiguredSource> configured, |
| 175 | + NuGetConfigSettings settings |
| 176 | + ) |
| 177 | + { |
| 178 | + foreach (NuGetConfiguredSource source in configured) |
| 179 | + { |
| 180 | + if ( |
| 181 | + source.Url.Scheme is not ("http" or "https") |
| 182 | + || !settings.Credentials.TryGetValue(source.Key, out NuGetCredential? credential) |
| 183 | + ) |
| 184 | + continue; |
| 185 | + |
| 186 | + string token = Convert.ToBase64String( |
| 187 | + Encoding.UTF8.GetBytes($"{credential.Username}:{credential.Password}") |
| 188 | + ); |
| 189 | + yield return (source.Url, new AuthenticationHeaderValue("Basic", token)); |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + private (int ExitCode, List<string> Lines) RunNuGet(string arguments) |
| 194 | + { |
| 195 | + using Process p = new() |
| 196 | + { |
| 197 | + StartInfo = new ProcessStartInfo |
| 198 | + { |
| 199 | + FileName = Manager.Status.ExecutablePath, |
| 200 | + Arguments = "nuget " + arguments, |
| 201 | + RedirectStandardOutput = true, |
| 202 | + RedirectStandardError = true, |
| 203 | + UseShellExecute = false, |
| 204 | + CreateNoWindow = true, |
| 205 | + WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), |
| 206 | + StandardOutputEncoding = Encoding.UTF8, |
| 207 | + }, |
| 208 | + }; |
| 209 | + p.StartInfo.Environment["DOTNET_CLI_UI_LANGUAGE"] = "en"; |
| 210 | + |
| 211 | + IProcessTaskLogger logger = Manager.TaskLogger.CreateNew(LoggableTaskType.ListSources, p); |
| 212 | + p.Start(); |
| 213 | + |
| 214 | + Task<string> stdErr = p.StandardError.ReadToEndAsync(); |
| 215 | + List<string> lines = []; |
| 216 | + string? line; |
| 217 | + while ((line = p.StandardOutput.ReadLine()) is not null) |
| 218 | + { |
| 219 | + logger.AddToStdOut(line); |
| 220 | + lines.Add(line); |
| 221 | + } |
| 222 | + |
| 223 | + logger.AddToStdErr(stdErr.GetAwaiter().GetResult()); |
| 224 | + p.WaitForExit(); |
| 225 | + logger.Close(p.ExitCode); |
| 226 | + return (p.ExitCode, lines); |
| 227 | + } |
| 228 | + |
| 229 | + internal static IReadOnlyList<NuGetConfiguredSource>? ParseSources(IEnumerable<string> lines) |
| 230 | + { |
| 231 | + List<NuGetConfiguredSource> sources = []; |
| 232 | + string? pendingName = null; |
| 233 | + |
| 234 | + foreach (string line in lines) |
| 235 | + { |
| 236 | + Match header = SourceHeader().Match(line); |
| 237 | + if (header.Success) |
| 238 | + { |
| 239 | + pendingName = header.Groups["state"].Value == "Enabled" |
| 240 | + ? header.Groups["name"].Value |
| 241 | + : null; |
| 242 | + continue; |
| 243 | + } |
| 244 | + |
| 245 | + if (NumberedEntry().IsMatch(line)) |
| 246 | + return null; |
| 247 | + |
| 248 | + if (pendingName is null || line.Trim().Length is 0) |
| 249 | + continue; |
| 250 | + |
| 251 | + if (Uri.TryCreate(line.Trim(), UriKind.Absolute, out Uri? url)) |
| 252 | + sources.Add(new NuGetConfiguredSource(pendingName, url)); |
| 253 | + |
| 254 | + pendingName = null; |
| 255 | + } |
| 256 | + |
| 257 | + return sources; |
| 258 | + } |
| 259 | + |
| 260 | + [GeneratedRegex(@"^\s*\d+\.\s+(?<name>.*\S)\s+\[(?<state>Enabled|Disabled)\]\s*$")] |
| 261 | + private static partial Regex SourceHeader(); |
| 262 | + |
| 263 | + [GeneratedRegex(@"^\s*\d+\.\s+\S")] |
| 264 | + private static partial Regex NumberedEntry(); |
| 265 | +} |
0 commit comments