-
Notifications
You must be signed in to change notification settings - Fork 909
/
Copy pathGetChocolatey.cs
547 lines (487 loc) · 23.5 KB
/
GetChocolatey.cs
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
// Copyright © 2017 - 2025 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using chocolatey.infrastructure.licensing;
using SimpleInjector;
using chocolatey.infrastructure.app;
using chocolatey.infrastructure.app.builders;
using chocolatey.infrastructure.app.configuration;
using chocolatey.infrastructure.app.runners;
using chocolatey.infrastructure.configuration;
using chocolatey.infrastructure.extractors;
using chocolatey.infrastructure.logging;
using chocolatey.infrastructure.registration;
using chocolatey.infrastructure.synchronization;
using log4net;
#if !NoResources
using chocolatey.resources;
#endif
using Assembly = chocolatey.infrastructure.adapters.Assembly;
using IFileSystem = chocolatey.infrastructure.filesystem.IFileSystem;
using ILog = chocolatey.infrastructure.logging.ILog;
using System.Linq;
namespace chocolatey
{
/// <summary>
/// Entry point for API
/// </summary>
public static class Lets
{
private static readonly log4net.ILog _logger = LogManager.GetLogger(typeof(Lets));
private static GetChocolatey Setup(bool initializeLogging)
{
AddAssemblyResolver();
return new GetChocolatey(initializeLogging);
}
public static GetChocolatey GetChocolatey()
{
return GetChocolatey(initializeLogging: true);
}
public static GetChocolatey GetChocolatey(bool initializeLogging)
{
return GlobalMutex.Enter(() => Setup(initializeLogging), 10);
}
private static void AddAssemblyResolver()
{
AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolution.ResolveExtensionOrMergedAssembly;
}
}
/// <summary>
/// The place where all the magic happens.
/// NOTE: When using the API, this is the only means of accessing the ChocolateyConfiguration without side effects.
/// DO NOT call `Config.get_configuration_settings()` or access the container to pull out the ChocolateyConfiguration.
/// Doing so can set configuration items that are retained on next use.
/// </summary>
/// <remarks>Chocolatey - the most magical place on Windows</remarks>
public class GetChocolatey
{
private readonly Container _container;
private readonly ChocolateyLicense _license;
private readonly LogSinkLog _logSinkLogger = new LogSinkLog();
private Action<ChocolateyConfiguration> _propConfig;
/// <summary>
/// Initializes a new instance of the <see cref="GetChocolatey"/> class.
/// </summary>
public GetChocolatey()
: this(initializeLogging: true)
{
}
public GetChocolatey(bool initializeLogging)
{
_container = SimpleInjectorContainer.Container;
if (initializeLogging)
{
var loggingLocation = ApplicationParameters.LoggingLocation;
var fileSystem = _container.GetInstance<IFileSystem>();
fileSystem.EnsureDirectoryExists(loggingLocation);
Log4NetAppenderConfiguration.Configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.ToStringSafe());
Log.InitializeWith(new AggregateLog(new List<ILog>() { new Log4NetLog(), _logSinkLogger }));
"chocolatey".Log().Debug("XmlConfiguration is now operational");
}
_license = License.ValidateLicense();
}
/// <summary>
/// This is an optional helper to give you the correct settings for a logger. You can still set this in the set by calling propConfig.Logger without having to call this method.
/// </summary>
/// <param name="logger">This is the logger you want Chocolatey to also use.</param>
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
public GetChocolatey SetCustomLogging(ILog logger)
{
return SetCustomLogging(logger, logExistingMessages: true, addToExistingLoggers: false);
}
public GetChocolatey SetCustomLogging(ILog logger, bool logExistingMessages)
{
return SetCustomLogging(logger, logExistingMessages, addToExistingLoggers: false);
}
public GetChocolatey SetCustomLogging(ILog logger, bool logExistingMessages, bool addToExistingLoggers)
{
var aggregateLog = new AggregateLog(new List<ILog> { logger });
if (addToExistingLoggers)
{
aggregateLog = new AggregateLog(new List<ILog> { logger, Log.GetLoggerFor("chocolatey") });
}
Log.InitializeWith(aggregateLog, resetLoggers: false);
if (logExistingMessages)
{
DrainLogSink(logger);
}
return this;
}
private void DrainLogSink(ILog logger)
{
foreach (var logMessage in _logSinkLogger.Messages.OrEmpty())
{
switch (logMessage.LogLevel)
{
case LogLevelType.Trace:
logger.Trace(logMessage.Message);
break;
case LogLevelType.Debug:
logger.Debug(logMessage.Message);
break;
case LogLevelType.Information:
logger.Info(logMessage.Message);
break;
case LogLevelType.Warning:
logger.Warn(logMessage.Message);
break;
case LogLevelType.Error:
logger.Error(logMessage.Message);
break;
case LogLevelType.Fatal:
logger.Fatal(logMessage.Message);
break;
}
}
_logSinkLogger.Messages.Clear();
}
/// <summary>
/// Set your options for running chocolatey here. It looks like Set(c => {c.CommandName = "install"; c.PackageNames = "bob";}).Run();
/// </summary>
/// <param name="propConfig">The configuration to set</param>
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
public GetChocolatey Set(Action<ChocolateyConfiguration> propConfig)
{
_propConfig = propConfig;
return this;
}
/// <summary>
/// Registers a container component. Does not require a dependency on Simple Injector.
/// Will override existing component if registered.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="implementation">The implementation.</param>
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
/// <remarks>
/// This requires you to use ILMerged SimpleInjector. If you use SimpleInjector in your codebase, you must now use Chocolatey's version. This is required to not be internalized so licensed code will work appropriately.
/// </remarks>
public GetChocolatey RegisterContainerComponent(Type service, Type implementation)
{
_container.Register(service, implementation, Lifestyle.Singleton);
return this;
}
/// <summary>
/// Registers a container component. Does not require a dependency on Simple Injector.
/// Will override existing component if registered.
/// </summary>
/// <typeparam name="Service">The type of the service.</typeparam>
/// <typeparam name="Implementation">The type of the Implementation.</typeparam>
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
/// <remarks>
/// This requires you to use ILMerged SimpleInjector. If you use SimpleInjector in your codebase, you must now use Chocolatey's version. This is required to not be internalized so licensed code will work appropriately.
/// </remarks>
public GetChocolatey RegisterContainerComponent<Service, Implementation>()
where Service : class
where Implementation : class, Service
{
return RegisterContainerComponent<Service, Implementation>(Lifestyle.Singleton);
}
/// <summary>
/// Registers a container component.
/// Will override existing component if registered.
/// </summary>
/// <typeparam name="Service">The type of the service.</typeparam>
/// <typeparam name="Implementation">The type of the Implementation.</typeparam>
/// <param name="lifestyle">The lifestyle.</param>
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
/// <remarks>
/// This requires you to use ILMerged SimpleInjector. If you use SimpleInjector in your codebase, you must now use Chocolatey's version. This is required to not be internalized so licensed code will work appropriately.
/// </remarks>
public GetChocolatey RegisterContainerComponent<Service, Implementation>(Lifestyle lifestyle)
where Service : class
where Implementation : class, Service
{
_container.Register<Service, Implementation>(lifestyle);
return this;
}
/// <summary>
/// Registers a container component. Does not require a dependency on Simple Injector.
/// Will override existing component if registered.
/// </summary>
/// <typeparam name="Service">The type of the service.</typeparam>
/// <param name="implementationCreator">The implementation creator.</param>
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
/// <remarks>
/// This requires you to use ILMerged SimpleInjector. If you use SimpleInjector in your codebase, you must now use Chocolatey's version. This is required to not be internalized so licensed code will work appropriately.
/// </remarks>
public GetChocolatey RegisterContainerComponent<Service>(Func<Service> implementationCreator)
where Service : class
{
_container.Register(implementationCreator, Lifestyle.Singleton);
return this;
}
/// <summary>
/// Register container components when you need to do multiple setups and want to work with the container directly.
/// Will override existing components if registered.
/// </summary>
/// <param name="containerSetup">The container setup.</param>
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
/// <remarks>
/// This requires you to use ILMerged SimpleInjector. If you use SimpleInjector in your codebase, you must now use Chocolatey's version. This is required to not be internalized so licensed code will work appropriately.
/// </remarks>
public GetChocolatey RegisterContainerComponents(Action<Container> containerSetup)
{
if (containerSetup != null)
{
containerSetup.Invoke(_container);
}
return this;
}
/// <summary>
/// Returns the Chocolatey container.
/// WARNING: Once you call GetInstance of any kind, no more items can be registered on the container
/// </summary>
/// <returns>The IoC Container (implemented as a SimpleInjector.Container)</returns>
/// <remarks>
/// This requires you to use ILMerged SimpleInjector. If you use SimpleInjector in your codebase, you must now use Chocolatey's version. This is required to not be internalized so licensed code will work appropriately.
/// </remarks>
public Container Container()
{
return _container;
}
/// <summary>
/// Call this method to run Chocolatey after you have set the options.
/// WARNING: Once this is called, you will not be able to register additional container components.
/// WARNING: Ensure you don't nest additional calls to running Chocolatey here.
/// Make a call, then finish up and make another call. This includes
/// - Run()
/// - RunConsole()
/// - List()
/// - ListCount()
/// </summary>
public void Run()
{
EnsureEnvironment();
ExtractResources();
EnsureOriginalConfiguration(new List<string>(),
(config) =>
{
var runner = new GenericRunner();
runner.Run(config, _container, isConsole: false, parseArgs: command =>
{
command.Validate(config);
});
});
}
/// <summary>
/// Call this method to run chocolatey after you have set the options.
/// WARNING: Once this is called, you will not be able to register additional container components.
/// WARNING: Ensure you don't nest additional calls to running Chocolatey here.
/// Make a call, then finish up and make another call. This includes
/// - Run()
/// - RunConsole()
/// - List()
/// - ListCount()
/// </summary>
/// <param name="args">Commandline arguments to add to configuration.</param>
public void RunConsole(string[] args)
{
EnsureEnvironment();
ExtractResources();
EnsureOriginalConfiguration(new List<string>(args),
(config) =>
{
var runner = new ConsoleApplication();
runner.Run(args, config, _container);
});
}
/// <summary>
/// Run chocolatey after setting the options, and list the results.
/// WARNING: Once this is called, you will not be able to register additional container components.
/// WARNING: Ensure you don't nest additional calls to running Chocolatey here.
/// Make a call, then finish up and make another call. This includes
/// - Run()
/// - RunConsole()
/// - List()
/// - ListCount()
/// </summary>
/// <typeparam name="T">The typer of results you're expecting back.</typeparam>
public IEnumerable<T> List<T>()
{
EnsureEnvironment();
ExtractResources();
return EnsureOriginalConfiguration(new List<string>(),
(config) =>
{
var runner = new GenericRunner();
return runner.List<T>(config, _container, isConsole: false, parseArgs: null);
});
}
/// <summary>
/// Run chocolatey after setting the options,
/// and get the count of items that would be returned if you listed the results.
/// WARNING: Once this is called, you will not be able to register additional container components.
/// WARNING: Ensure you don't nest additional calls to running Chocolatey here.
/// Make a call, then finish up and make another call. This includes
/// - Run()
/// - RunConsole()
/// - List()
/// - ListCount()
/// </summary>
/// <remarks>
/// Is intended to be more efficient then simply calling <see cref="List{T}">List</see> and then Count() on the returned list.
/// It also returns the full count as is ignores paging.
/// </remarks>
public int ListCount()
{
EnsureEnvironment();
ExtractResources();
return EnsureOriginalConfiguration(new List<string>(),
(config) =>
{
var runner = new GenericRunner();
return runner.Count(config, _container, isConsole: false, parseArgs: null);
});
}
/// <summary>
/// Gets a copy of the configuration. Any changes here will have no effect as this is provided purely for informational purposes.
/// </summary>
/// <returns>The configuration for Chocolatey</returns>
/// <remarks>Only call this once you have registered all container components with Chocolatey</remarks>
public ChocolateyConfiguration GetConfiguration()
{
EnsureEnvironment();
// ensure_original_configuration() already calls create_configuration()
// so no need to repeat, just grab the result
var configuration = EnsureOriginalConfiguration(
new List<string>(),
(config) => config
);
return configuration;
}
private void EnsureOriginalConfiguration(IList<string> args, Action<ChocolateyConfiguration> action)
{
var success = EnsureOriginalConfiguration(args,
(config) =>
{
if (action != null)
{
action.Invoke(config);
}
return true;
});
}
/// <summary>
/// After the construction of GetChocolatey, we should have a ChocolateyConfiguration or LicensedChocolateyConfiguration loaded into the environment.
/// We want that original configuration to live on between calls to the API. This function ensures that the
/// original default configuration from new() is reset after each command finishes running, even as each command
/// may make changes to the configuration it uses.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="args">The arguments.</param>
/// <param name="function">The function.</param>
/// <returns></returns>
private T EnsureOriginalConfiguration<T>(IList<string> args, Func<ChocolateyConfiguration, T> function)
{
var originalConfig = Config.GetConfigurationSettings().DeepCopy();
var configuration = CreateConfiguration(args);
var returnValue = default(T);
try
{
if (function != null)
{
returnValue = function.Invoke(configuration);
}
var verboseAppenderName = "{0}LoggingColoredConsoleAppender".FormatWith(ChocolateyLoggers.Verbose.ToStringSafe());
var traceAppenderName = "{0}LoggingColoredConsoleAppender".FormatWith(ChocolateyLoggers.Trace.ToStringSafe());
Log4NetAppenderConfiguration.EnableDebugLoggingIf(configuration.Debug, verboseAppenderName, traceAppenderName);
Log4NetAppenderConfiguration.EnableVerboseLoggingIf(configuration.Verbose, configuration.Debug, verboseAppenderName);
if (!configuration.Information.IsProcessElevated && configuration.Trace)
{
var logger = ChocolateyLoggers.Normal;
if (!configuration.RegularOutput)
{
logger = ChocolateyLoggers.LogFileOnly;
}
"chocolatey".Log().Warn(logger, "Usage of the --trace option is only allowed when running from an elevated session.");
}
}
finally
{
// reset that configuration each time
configuration = originalConfig;
Config.InitializeWith(originalConfig);
}
return returnValue;
}
/// <summary>
/// Creates the configuration.
/// This should never be called directly, as it can cause issues that are very difficult to debug.
/// </summary>
/// <param name="args">The arguments.</param>
/// <returns>The configuration for Chocolatey</returns>
private ChocolateyConfiguration CreateConfiguration(IList<string> args)
{
// get or create a ChocolateyConfiguration. This maps directly
// to the same thing that is loaded into the container
var configuration = Config.GetConfigurationSettings();
ConfigurationBuilder.SetupConfiguration(
args,
configuration,
_container,
_license,
null);
configuration.PromptForConfirmation = false;
configuration.AcceptLicense = true;
if (_propConfig != null)
{
_propConfig.Invoke(configuration);
}
return configuration;
}
private void EnsureEnvironment()
{
var chocolateyInstall = string.Empty;
#if !DEBUG
chocolateyInstall = Environment.GetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, EnvironmentVariableTarget.Machine);
if (string.IsNullOrWhiteSpace(chocolateyInstall))
{
chocolateyInstall = Environment.GetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, EnvironmentVariableTarget.User);
}
#endif
if (string.IsNullOrWhiteSpace(chocolateyInstall))
{
chocolateyInstall = Environment.GetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName);
}
Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, chocolateyInstall);
}
private void ExtractResources()
{
//refactor - thank goodness this is temporary, cuz manifest resource streams are dumb
IList<string> folders = new List<string>
{
"helpers",
"functions",
"redirects",
"tools"
};
#if !NoResources
try
{
AssemblyFileExtractor.ExtractAssemblyResourcesToRelativeDirectory(_container.GetInstance<IFileSystem>(), Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources);
}
catch (Exception ex)
{
this.Log().Warn(ChocolateyLoggers.Important, "Please ensure that ChocolateyInstall environment variable is set properly and you've run once as an administrator to ensure all resources are extracted.");
this.Log().Error("Unable to extract resources. Please ensure the ChocolateyInstall environment variable is set properly. You may need to run once as an admin to ensure all resources are extracted. Details:{0} {1}".FormatWith(Environment.NewLine, ex.ToString()));
}
#endif
}
}
}