forked from Devolutions/UniGetUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChocolatey.cs
More file actions
348 lines (306 loc) · 14.8 KB
/
Chocolatey.cs
File metadata and controls
348 lines (306 loc) · 14.8 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
using System.Diagnostics;
using UniGetUI.Core.Data;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
using UniGetUI.Core.Tools;
using UniGetUI.Interface.Enums;
using UniGetUI.PackageEngine.Classes.Manager;
using UniGetUI.PackageEngine.Classes.Manager.ManagerHelpers;
using UniGetUI.PackageEngine.Enums;
using UniGetUI.PackageEngine.ManagerClasses.Classes;
using UniGetUI.PackageEngine.ManagerClasses.Manager;
using UniGetUI.PackageEngine.Managers.Choco;
using UniGetUI.PackageEngine.Managers.PowerShellManager;
using UniGetUI.PackageEngine.PackageClasses;
using Architecture = UniGetUI.PackageEngine.Enums.Architecture;
namespace UniGetUI.PackageEngine.Managers.ChocolateyManager
{
public class Chocolatey : BaseNuGet
{
public static readonly string[] FALSE_PACKAGE_IDS = ["Directory", "", "Did", "Features?", "Validation", "-", "being", "It", "Error", "L'accs", "Maximum", "This", "Output is package name ", "operable", "Invalid"];
public static readonly string[] FALSE_PACKAGE_VERSIONS = ["", "of", "Did", "Features?", "Validation", "-", "being", "It", "Error", "L'accs", "Maximum", "This", "packages", "current version", "installed version", "is", "program", "validations", "argument", "no"];
private static readonly string OldChocoPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs\\WingetUI\\choco-cli");
private static readonly string NewChocoPath = Path.Join(CoreData.UniGetUIDataDirectory, "Chocolatey");
public Chocolatey()
{
Capabilities = new ManagerCapabilities
{
CanRunAsAdmin = true,
CanDownloadInstaller = true,
CanSkipIntegrityChecks = true,
CanRunInteractively = true,
SupportsCustomVersions = true,
SupportsCustomArchitectures = true,
SupportedCustomArchitectures = [Architecture.x86],
SupportsPreRelease = true,
SupportsCustomSources = true,
SupportsCustomPackageIcons = true,
Sources = new SourceCapabilities
{
KnowsPackageCount = false,
KnowsUpdateDate = false,
},
SupportsProxy = ProxySupport.Yes,
SupportsProxyAuth = true
};
Properties = new ManagerProperties
{
Name = "Chocolatey",
Description = CoreTools.Translate("The classical package manager for windows. You'll find everything there. <br>Contains: <b>General Software</b>"),
IconId = IconType.Chocolatey,
ColorIconId = "choco_color",
ExecutableFriendlyName = "choco.exe",
InstallVerb = "install",
UninstallVerb = "uninstall",
UpdateVerb = "upgrade",
KnownSources = [new ManagerSource(this, "community", new Uri("https://community.chocolatey.org/api/v2/"))],
DefaultSource = new ManagerSource(this, "community", new Uri("https://community.chocolatey.org/api/v2/")),
};
SourcesHelper = new ChocolateySourceHelper(this);
DetailsHelper = new ChocolateyDetailsHelper(this);
OperationHelper = new ChocolateyPkgOperationHelper(this);
}
public static string GetProxyArgument()
{
if (!Settings.Get(Settings.K.EnableProxy)) return "";
var proxyUri = Settings.GetProxyUrl();
if (proxyUri is null) return "";
if (Settings.Get(Settings.K.EnableProxyAuth) is false)
return $"--proxy {proxyUri.ToString()}";
var creds = Settings.GetProxyCredentials();
if (creds is null)
return $"--proxy {proxyUri.ToString()}";
return $"--proxy={proxyUri.ToString()} --proxy-user={Uri.EscapeDataString(creds.UserName)}" +
$" --proxy-password={Uri.EscapeDataString(creds.Password)}";
}
protected override IReadOnlyList<Package> GetAvailableUpdates_UnSafe()
{
using Process p = new()
{
StartInfo = new ProcessStartInfo
{
FileName = Status.ExecutablePath,
Arguments = Status.ExecutableCallArgs + " outdated " + GetProxyArgument(),
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = System.Text.Encoding.UTF8
}
};
IProcessTaskLogger logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p);
p.Start();
string? line;
List<Package> Packages = [];
while ((line = p.StandardOutput.ReadLine()) is not null)
{
logger.AddToStdOut(line);
if (!line.StartsWith("Chocolatey"))
{
string[] elements = line.Split('|');
for (int i = 0; i < elements.Length; i++)
{
elements[i] = elements[i].Trim();
}
if (elements.Length <= 2)
{
continue;
}
if (FALSE_PACKAGE_IDS.Contains(elements[0]) || FALSE_PACKAGE_VERSIONS.Contains(elements[1]) || elements[1] == elements[2])
{
continue;
}
Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], elements[2], DefaultSource, this));
}
}
logger.AddToStdErr(p.StandardError.ReadToEnd());
p.WaitForExit();
logger.Close(p.ExitCode);
return Packages;
}
protected override IReadOnlyList<Package> _getInstalledPackages_UnSafe()
{
using Process p = new()
{
StartInfo = new ProcessStartInfo
{
FileName = Status.ExecutablePath,
Arguments = Status.ExecutableCallArgs + " list " + GetProxyArgument(),
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = System.Text.Encoding.UTF8
}
};
IProcessTaskLogger logger = TaskLogger.CreateNew(LoggableTaskType.ListInstalledPackages, p);
p.Start();
string? line;
List<Package> Packages = [];
while ((line = p.StandardOutput.ReadLine()) is not null)
{
logger.AddToStdOut(line);
if (!line.StartsWith("Chocolatey"))
{
string[] elements = line.Split(' ');
for (int i = 0; i < elements.Length; i++)
{
elements[i] = elements[i].Trim();
}
if (elements.Length <= 1)
{
continue;
}
if (FALSE_PACKAGE_IDS.Contains(elements[0]) || FALSE_PACKAGE_VERSIONS.Contains(elements[1]))
{
continue;
}
Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], DefaultSource, this));
}
}
logger.AddToStdErr(p.StandardError.ReadToEnd());
p.WaitForExit();
logger.Close(p.ExitCode);
return Packages;
}
public override IReadOnlyList<string> FindCandidateExecutableFiles()
{
List<string> candidates = [];
if (!Settings.Get(Settings.K.UseSystemChocolatey))
{
candidates.Add(Path.Join(NewChocoPath, "choco.exe"));
}
candidates.AddRange(CoreTools.WhichMultiple("choco.exe"));
return candidates;
}
protected override ManagerStatus LoadManager()
{
if (!Directory.Exists(OldChocoPath))
{
Logger.Debug("Old chocolatey path does not exist, not migrating Chocolatey");
}
else if (CoreTools.IsSymbolicLinkDir(OldChocoPath))
{
Logger.ImportantInfo("Old chocolatey path is a symbolic link, not migrating Chocolatey...");
}
else if (Settings.Get(Settings.K.ChocolateySymbolicLinkCreated))
{
Logger.Warn("The Choco path symbolic link has already been set to created!");
}
else
{
try
{
Logger.Info("Moving Bundled Chocolatey from old path to new path...");
string current_env_var =
Environment.GetEnvironmentVariable("chocolateyinstall", EnvironmentVariableTarget.User) ?? "";
if (current_env_var != "" && Path.GetRelativePath(current_env_var, OldChocoPath) == ".")
{
Logger.ImportantInfo("Migrating ChocolateyInstall environment variable to new location");
Environment.SetEnvironmentVariable("chocolateyinstall", NewChocoPath, EnvironmentVariableTarget.User);
}
if (!Directory.Exists(NewChocoPath))
{
Directory.CreateDirectory(NewChocoPath);
}
foreach (string old_subdir in Directory.GetDirectories(OldChocoPath, "*", SearchOption.AllDirectories))
{
string new_subdir = old_subdir.Replace(OldChocoPath, NewChocoPath);
if (!Directory.Exists(new_subdir))
{
Logger.Debug("New directory: " + new_subdir);
Directory.CreateDirectory(new_subdir);
}
else
{
Logger.Debug("Directory " + new_subdir + " already exists");
}
}
foreach (string old_file in Directory.GetFiles(OldChocoPath, "*", SearchOption.AllDirectories))
{
string new_file = old_file.Replace(OldChocoPath, NewChocoPath);
if (!File.Exists(new_file))
{
Logger.Info("Copying " + old_file);
File.Move(old_file, new_file);
}
else
{
Logger.Debug("File " + new_file + " already exists.");
File.Delete(old_file);
}
}
foreach (string old_subdir in Directory.GetDirectories(OldChocoPath, "*", SearchOption.AllDirectories).Reverse())
{
if (!Directory.EnumerateFiles(old_subdir).Any() && !Directory.EnumerateDirectories(old_subdir).Any())
{
Logger.Debug("Deleting old empty subdirectory " + old_subdir);
Directory.Delete(old_subdir);
}
}
if (!Directory.EnumerateFiles(OldChocoPath).Any() && !Directory.EnumerateDirectories(OldChocoPath).Any())
{
Logger.Info("Deleting old Chocolatey directory " + OldChocoPath);
Directory.Delete(OldChocoPath);
}
CoreTools.CreateSymbolicLinkDir(OldChocoPath, NewChocoPath);
Settings.Set(Settings.K.ChocolateySymbolicLinkCreated, true);
Logger.Info($"Symbolic link created successfully from {OldChocoPath} to {NewChocoPath}.");
}
catch (Exception e)
{
Logger.Error("An error occurred while migrating chocolatey");
Logger.Error(e);
}
}
var (found, executable) = GetExecutableFile();
ManagerStatus status = new() { Found = found, ExecutablePath = executable, ExecutableCallArgs = "", };
if (!status.Found)
{
return status;
}
Process process = new()
{
StartInfo = new ProcessStartInfo
{
FileName = status.ExecutablePath,
Arguments = "--version " + GetProxyArgument(),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
StandardOutputEncoding = System.Text.Encoding.UTF8
}
};
process.Start();
status.Version = process.StandardOutput.ReadToEnd().Trim();
// If the user is running bundled chocolatey and chocolatey is not in path, add chocolatey to path
if (!Settings.Get(Settings.K.UseSystemChocolatey)
&& !File.Exists("C:\\ProgramData\\Chocolatey\\bin\\choco.exe"))
/* && Settings.Get(Settings.K.ShownWelcomeWizard)) */
{
string? path = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User);
if (!path?.Contains(status.ExecutablePath.Replace("\\choco.exe", "\\bin")) ?? false)
{
Logger.ImportantInfo("Adding chocolatey to path since it was not on path.");
Environment.SetEnvironmentVariable("PATH", $"{status.ExecutablePath.Replace("\\choco.exe", "\\bin")};{path}", EnvironmentVariableTarget.User);
Environment.SetEnvironmentVariable("chocolateyinstall", Path.GetDirectoryName(status.ExecutablePath), EnvironmentVariableTarget.User);
}
else
{
Logger.Info("UniGetUI Chocolatey was found in the path");
}
}
// Trick chocolatey into using the wanted installation
var choco_dir = Path.GetDirectoryName(status.ExecutablePath)?.Replace('/', '\\').Trim('\\') ?? "";
if (choco_dir.EndsWith("bin"))
{
choco_dir = choco_dir[..^3].Trim('\\');
}
Environment.SetEnvironmentVariable("chocolateyinstall", choco_dir, EnvironmentVariableTarget.Process);
return status;
}
}
}