/
ChocolateyPackageService.cs
1940 lines (1634 loc) · 98.5 KB
/
ChocolateyPackageService.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
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2017 - 2023 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.
namespace chocolatey.infrastructure.app.services
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Text;
using chocolatey.infrastructure.app.registration;
using commandline;
using configuration;
using domain;
using events;
using infrastructure.commands;
using infrastructure.events;
using infrastructure.services;
using logging;
using nuget;
using NuGet.Configuration;
using NuGet.Packaging;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
using platforms;
using results;
using SimpleInjector;
using tolerance;
using IFileSystem = filesystem.IFileSystem;
public class ChocolateyPackageService : IChocolateyPackageService
{
private readonly INugetService _nugetService;
private readonly IPowershellService _powershellService;
private readonly IShimGenerationService _shimgenService;
private readonly IFileSystem _fileSystem;
private readonly IRegistryService _registryService;
private readonly IChocolateyPackageInformationService _packageInfoService;
private readonly IFilesService _filesService;
private readonly IAutomaticUninstallerService _autoUninstallerService;
private readonly IXmlService _xmlService;
private readonly IConfigTransformService _configTransformService;
private readonly IContainerResolver _containerResolver;
private readonly IDictionary<string, FileStream> _pendingLocks = new Dictionary<string, FileStream>();
private readonly IList<string> _proBusinessMessages = new List<string> {
@"
Are you ready for the ultimate experience? Check out Pro / Business!
https://chocolatey.org/compare"
,
@"
Enjoy using Chocolatey? Explore more amazing features to take your
experience to the next level at
https://chocolatey.org/compare"
,
@"
Did you know the proceeds of Pro (and some proceeds from other
licensed editions) go into bettering the community infrastructure?
Your support ensures an active community, keeps Chocolatey tip-top,
plus it nets you some awesome features!
https://chocolatey.org/compare",
@"
Did you know some organizations use Chocolatey completely internally
without using the community repository or downloads from the internet?
Wait until you see how Package Builder and Package Internalizer can
help you achieve more, quicker, and easier! Get your trial started
today at https://chocolatey.org/compare",
@"
An organization needed total software management life cycle automation.
They evaluated Chocolatey for Business. You won't believe what happens
next!
https://chocolatey.org/compare",
@"
Did you know that Package Synchronizer and AutoUninstaller enhancements
in licensed versions are up to 95% effective in removing system
installed software without an uninstall script? Find out more at
https://chocolatey.org/compare",
@"
Did you know Chocolatey goes to eleven? And it turns great developers /
system admins into something amazing! Singlehandedly solve your
organization's struggles with software management and save the day!
https://chocolatey.org/compare"
};
private const string ProBusinessListMessage = @"
Did you know Pro / Business automatically syncs with Programs and
Features? Learn more about Package Synchronizer at
https://chocolatey.org/compare";
private readonly string _shutdownExe = Environment.ExpandEnvironmentVariables("%systemroot%\\System32\\shutdown.exe");
// Hold a list of exit codes that are known to be related to reboots
// 1641 - restart initiated
// 3010 - restart required
private readonly List<int> _rebootExitCodes = new List<int> { 1641, 3010 };
public ChocolateyPackageService(
INugetService nugetService,
IPowershellService powershellService,
IShimGenerationService shimgenService,
IFileSystem fileSystem,
IRegistryService registryService,
IChocolateyPackageInformationService packageInfoService,
IFilesService filesService,
IAutomaticUninstallerService autoUninstallerService,
IXmlService xmlService,
IConfigTransformService configTransformService,
IContainerResolver containerResolver)
{
_nugetService = nugetService;
_powershellService = powershellService;
_shimgenService = shimgenService;
_fileSystem = fileSystem;
_registryService = registryService;
_packageInfoService = packageInfoService;
_filesService = filesService;
_autoUninstallerService = autoUninstallerService;
_xmlService = xmlService;
_configTransformService = configTransformService;
_containerResolver = containerResolver;
}
public virtual int Count(ChocolateyConfiguration config)
{
if (config.SourceType.IsEqualTo(SourceTypes.Normal))
{
return _nugetService.Count(config);
}
return PerformSourceRunnerFunction<ICountSourceRunner, int>(
config,
runner => runner.Count(config),
throwOnException: true);
}
private void PerformSourceRunnerAction<TSourceRunner>(ChocolateyConfiguration config, Action<TSourceRunner> action, bool throwOnException = false)
where TSourceRunner : class, IAlternativeSourceRunner
{
var alternativeSourceRunners = _containerResolver.ResolveAll<TSourceRunner>();
PerformSourceRunnerAction(config, action, alternativeSourceRunners, throwOnException);
}
private void PerformSourceRunnerAction<TSourceRunner>(ChocolateyConfiguration config, Action<TSourceRunner> action, IEnumerable<TSourceRunner> alternativeSourceRunners, bool throwOnException = false)
where TSourceRunner : class, IAlternativeSourceRunner
{
var runner = GetSourceRunner(config.SourceType, alternativeSourceRunners);
if (runner != null && action != null)
{
if (runner is IBootstrappableSourceRunner bootstrapper)
{
bootstrapper.EnsureSourceAppInstalled(config, (packageResult, configuration) => HandlePackageResult(packageResult, configuration, CommandNameType.Install));
}
action.Invoke(runner);
}
else
{
if (throwOnException)
{
throw new NotSupportedException("No runner was found that implements source type '{0}' or action was missing".FormatWith(config.SourceType));
}
else
{
this.Log().Warn("No runner was found that implements source type '{0}' or action was missing".FormatWith(config.SourceType));
}
}
}
private TResult PerformSourceRunnerFunction<TSourceRunner, TResult>(ChocolateyConfiguration config, Func<TSourceRunner, TResult> function, bool throwOnException = false)
where TSourceRunner : class, IAlternativeSourceRunner
{
var alternativeSourceRunners = _containerResolver.ResolveAll<TSourceRunner>();
return PerformSourceRunnerFunction(config, function, alternativeSourceRunners, throwOnException);
}
private TResult PerformSourceRunnerFunction<TSourceRunner, TResult>(ChocolateyConfiguration config, Func<TSourceRunner, TResult> function, IEnumerable<TSourceRunner> alternativeSourceRunners, bool throwOnException = false)
where TSourceRunner : class, IAlternativeSourceRunner
{
var runner = GetSourceRunner(config.SourceType, alternativeSourceRunners);
if (runner != null && function != null)
{
if (runner is IBootstrappableSourceRunner bootstrapper)
{
// NOTE: Here we are passing the original config into the HandlePackageResult method, rather than what comes out of the Action, since
// that configuration could be wildly different from what was passed in, and we want to continue with what was in play before
// installing the required source application.
bootstrapper.EnsureSourceAppInstalled(config, (packageResult, configuration) => HandlePackageResult(packageResult, config, CommandNameType.Install));
}
return function.Invoke(runner);
}
if (throwOnException)
{
throw new NotSupportedException("No runner was found that implements source type '{0}' or, it does not support requested functionality.".FormatWith(config.SourceType));
}
else
{
this.Log().Warn("No runner was found that implements source type '{0}' or, it does not support requested functionality.".FormatWith(config.SourceType));
}
return default;
}
public void ListDryRun(ChocolateyConfiguration config)
{
if (string.IsNullOrWhiteSpace(config.Sources) && !config.ListCommand.LocalOnly)
{
this.Log().Error(ChocolateyLoggers.Important, @"Unable to search for packages when there are no sources enabled for
packages and none were passed as arguments.");
Environment.ExitCode = 1;
return;
}
config.Noop = true;
if (config.ListCommand.LocalOnly && !config.SourceType.IsEqualTo(SourceTypes.Normal))
{
PerformSourceRunnerAction<IListSourceRunner>(config, runner => runner.ListDryRun(config));
}
else if (config.SourceType.IsEqualTo(SourceTypes.Normal))
{
_nugetService.ListDryRun(config);
}
else
{
PerformSourceRunnerAction<ISearchableSourceRunner>(config, runner => runner.SearchDryRun(config));
}
RandomlyNotifyAboutLicensedFeatures(config, ProBusinessListMessage);
}
public virtual IEnumerable<PackageResult> List(ChocolateyConfiguration config)
{
if (string.IsNullOrWhiteSpace(config.Sources) && !config.ListCommand.LocalOnly)
{
this.Log().Error(ChocolateyLoggers.Important, @"Unable to search for packages when there are no sources enabled for
packages and none were passed as arguments.");
Environment.ExitCode = 1;
yield break;
}
if (config.RegularOutput) this.Log().Debug(() => "Searching for package information");
var packages = new List<PackageResult>();
IEnumerable<PackageResult> results;
if (config.ListCommand.LocalOnly && !config.SourceType.IsEqualTo(SourceTypes.Normal))
{
results = PerformSourceRunnerFunction<IListSourceRunner, IEnumerable<PackageResult>>(config, runner => runner.List(config));
}
else if (config.SourceType.IsEqualTo(SourceTypes.Normal))
{
results = _nugetService.List(config).OrEmpty();
}
else
{
results = PerformSourceRunnerFunction<ISearchableSourceRunner, IEnumerable<PackageResult>>(config, runner => runner.Search(config));
}
if (results is null)
{
var message = config.ListCommand.LocalOnly ? "The '{0}' source does not support listing of packages".FormatWith(config.SourceType) : "The '{0}' source does not support searching for packages".FormatWith(config.SourceType);
throw new NotSupportedException(message);
}
foreach (PackageResult package in results)
{
if (config.SourceType.IsEqualTo(SourceTypes.Normal))
{
if (!config.ListCommand.IncludeRegistryPrograms)
{
yield return package;
}
if (config.ListCommand.LocalOnly && config.ListCommand.IncludeRegistryPrograms && package.PackageMetadata != null)
{
packages.Add(package);
}
}
}
if (config.RegularOutput)
{
if (config.ListCommand.LocalOnly && config.ListCommand.IncludeRegistryPrograms)
{
foreach (var installed in ReportRegistryPrograms(config, packages))
{
yield return installed;
}
}
}
RandomlyNotifyAboutLicensedFeatures(config, ProBusinessListMessage);
}
private IEnumerable<PackageResult> ReportRegistryPrograms(ChocolateyConfiguration config, IEnumerable<PackageResult> list)
{
var itemsToRemoveFromMachine = list.Select(package => _packageInfoService.Get(package.PackageMetadata)).Where(p => p.RegistrySnapshot != null).ToList();
var count = 0;
var machineInstalled = _registryService.GetInstallerKeys().RegistryKeys.Where(
p => p.IsInProgramsAndFeatures() &&
!itemsToRemoveFromMachine.Any(pkg => pkg.RegistrySnapshot.RegistryKeys.Any(k => k.DisplayName.IsEqualTo(p.DisplayName))) &&
!p.KeyPath.ContainsSafe("choco-")).OrderBy(p => p.DisplayName).Distinct();
this.Log().Info(() => "");
foreach (var key in machineInstalled)
{
if (config.RegularOutput)
{
this.Log().Info("{0}|{1}".FormatWith(key.DisplayName, key.DisplayVersion));
if (config.Verbose) this.Log().Info(" InstallLocation: {0}{1} Uninstall:{2}".FormatWith(key.InstallLocation.ToStringSafe().EscapeCurlyBraces(), Environment.NewLine, key.UninstallString.ToStringSafe().EscapeCurlyBraces()));
}
count++;
yield return new PackageResult(key.DisplayName, key.DisplayName, key.InstallLocation);
}
if (config.RegularOutput)
{
this.Log().Warn(() => @"{0} applications not managed with Chocolatey.".FormatWith(count));
}
}
public void PackDryRun(ChocolateyConfiguration config)
{
if (!config.SourceType.IsEqualTo(SourceTypes.Normal))
{
this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for packaging.");
return;
}
_nugetService.PackDryRun(config);
RandomlyNotifyAboutLicensedFeatures(config);
}
public virtual void Pack(ChocolateyConfiguration config)
{
if (!config.SourceType.IsEqualTo(SourceTypes.Normal))
{
this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for packaging.");
return;
}
_nugetService.Pack(config);
RandomlyNotifyAboutLicensedFeatures(config);
}
public void PushDryRun(ChocolateyConfiguration config)
{
if (!config.SourceType.IsEqualTo(SourceTypes.Normal))
{
this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for pushing.");
return;
}
_nugetService.PushDryRun(config);
RandomlyNotifyAboutLicensedFeatures(config);
}
public virtual void Push(ChocolateyConfiguration config)
{
if (!config.SourceType.IsEqualTo(SourceTypes.Normal))
{
this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for pushing.");
return;
}
_nugetService.Push(config);
RandomlyNotifyAboutLicensedFeatures(config);
}
public void InstallDryRun(ChocolateyConfiguration config)
{
ValidatePackageNames(config);
var installSourceRunners = _containerResolver.ResolveAll<IInstallSourceRunner>();
// each package can specify its own configuration values
foreach (var packageConfig in GetConfigFromInputAndPackageConfigInput(config, new ConcurrentDictionary<string, PackageResult>(), installSourceRunners).OrEmpty())
{
config.Noop = true;
if (packageConfig.SourceType.IsEqualTo(SourceTypes.Normal))
{
Action<PackageResult, ChocolateyConfiguration> action = (pkg, configuration) => _powershellService.InstallDryRun(pkg);
_nugetService.InstallDryRun(packageConfig, action);
}
else
{
PerformSourceRunnerAction(config, runner => runner.InstallDryRun(packageConfig, null), installSourceRunners);
}
}
RandomlyNotifyAboutLicensedFeatures(config);
}
/// <summary>
/// Once every 10 runs or so, Chocolatey FOSS should inform the user of the Pro / Business versions.
/// </summary>
/// <param name="config">The configuration.</param>
/// <param name="message">The message to send.</param>
/// <remarks>We want it random enough not to be annoying, but informative enough for awareness.</remarks>
public void RandomlyNotifyAboutLicensedFeatures(ChocolateyConfiguration config, string message = null)
{
if (!config.Information.IsLicensedVersion && config.RegularOutput)
{
// magic numbers! Basically about 10% of the time show a message.
if (new Random().Next(1, 10) == 3)
{
if (string.IsNullOrWhiteSpace(message))
{
// Choose a message at random to display. It is
// specifically done like this as sometimes Random
// doesn't like to grab the max value.
var messageCount = _proBusinessMessages.Count;
var chosenMessage = new Random().Next(0, messageCount);
if (chosenMessage >= messageCount) chosenMessage = messageCount - 1;
message = _proBusinessMessages[chosenMessage];
}
this.Log().Warn(ChocolateyLoggers.Important, message);
}
}
}
public virtual void HandlePackageResult(PackageResult packageResult, ChocolateyConfiguration config, CommandNameType commandName)
{
EnvironmentSettings.ResetEnvironmentVariables(config);
MarkPackagePending(packageResult, config);
this.Log().Info(packageResult.ExitCode == 0
? "{0} package files {1} completed. Performing other installation steps.".FormatWith(packageResult.Name, commandName.ToStringSafe())
: "{0} package files {1} failed with exit code {2}. Performing other installation steps.".FormatWith(packageResult.Name, commandName.ToStringSafe(), packageResult.ExitCode));
var pkgInfo = GetPackageInformation(packageResult, config);
// initialize this here so it can be used for the install location later
bool powerShellRan = false;
if (packageResult.Success && config.Information.PlatformType == PlatformType.Windows)
{
if (!config.SkipPackageInstallProvider)
{
var installersBefore = _registryService.GetInstallerKeys();
var environmentBefore = GetInitialEnvironment(config, allowLogging: false);
powerShellRan = _powershellService.Install(config, packageResult);
if (powerShellRan)
{
// we don't care about the exit code
if (config.Information.PlatformType == PlatformType.Windows) CommandExecutor.ExecuteStatic(_shutdownExe, "/a", config.CommandExecutionTimeoutSeconds, _fileSystem.GetCurrentDirectory(), (s, e) => { }, (s, e) => { }, false, false);
}
var installersDifferences = _registryService.GetInstallerKeysChanged(installersBefore, _registryService.GetInstallerKeys());
if (installersDifferences.RegistryKeys.Count != 0)
{
//todo: #2567 - note keys passed in
pkgInfo.RegistrySnapshot = installersDifferences;
var key = installersDifferences.RegistryKeys.FirstOrDefault();
if (key != null && key.HasQuietUninstall)
{
pkgInfo.HasSilentUninstall = true;
this.Log().Info(" {0} can be automatically uninstalled.".FormatWith(packageResult.Name));
}
else if (key != null)
{
this.Log().Info(" {0} may be able to be automatically uninstalled.".FormatWith(packageResult.Name));
}
}
IEnumerable<GenericRegistryValue> environmentChanges;
IEnumerable<GenericRegistryValue> environmentRemovals;
LogEnvironmentChanges(config, environmentBefore, out environmentChanges, out environmentRemovals);
//todo: #564 record this with package info
}
_filesService.EnsureCompatibleFileAttributes(packageResult, config);
_configTransformService.Run(packageResult, config);
pkgInfo.FilesSnapshot = _filesService.CaptureSnapshot(packageResult, config);
var is32Bit = !config.Information.Is64BitProcess || config.ForceX86;
CreateExecutableIgnoreFiles(packageResult.InstallLocation, !is32Bit);
if (packageResult.Success) _shimgenService.Install(config, packageResult);
}
else
{
if (config.Information.PlatformType != PlatformType.Windows) this.Log().Info(ChocolateyLoggers.Important, () => " Skipping PowerShell and shimgen portions of the install due to non-Windows.");
if (packageResult.Success)
{
_configTransformService.Run(packageResult, config);
pkgInfo.FilesSnapshot = _filesService.CaptureSnapshot(packageResult, config);
}
}
if (packageResult.Success)
{
HandleExtensionPackages(config, packageResult);
HandleTemplatePackages(config, packageResult);
HandleHookPackages(config, packageResult);
pkgInfo.Arguments = CaptureArguments(config, packageResult);
pkgInfo.IsPinned = config.PinPackage;
}
var toolsLocation = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyToolsLocation);
if (!string.IsNullOrWhiteSpace(toolsLocation) && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation)))
{
toolsLocation = _fileSystem.CombinePaths(toolsLocation, packageResult.Name);
if (_fileSystem.DirectoryExists(toolsLocation))
{
Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation, toolsLocation, EnvironmentVariableTarget.Process);
}
}
if (!powerShellRan && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation)))
{
Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation, packageResult.InstallLocation, EnvironmentVariableTarget.Process);
}
if (pkgInfo.RegistrySnapshot != null && pkgInfo.RegistrySnapshot.RegistryKeys.Any(k => !string.IsNullOrWhiteSpace(k.InstallLocation)))
{
var key = pkgInfo.RegistrySnapshot.RegistryKeys.FirstOrDefault(k => !string.IsNullOrWhiteSpace(k.InstallLocation));
if (key != null) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation, key.InstallLocation, EnvironmentVariableTarget.Process);
}
UpdatePackageInformation(pkgInfo);
EnsureBadPackagesPathIsClean(config, packageResult);
EventManager.Publish(new HandlePackageResultCompletedMessage(packageResult, config, commandName));
UnmarkPackagePending(packageResult, config);
if (_rebootExitCodes.Contains(packageResult.ExitCode))
{
if (config.Features.ExitOnRebootDetected)
{
Environment.ExitCode = ApplicationParameters.ExitCodes.ErrorInstallSuspend;
this.Log().Warn(ChocolateyLoggers.Important, @"Chocolatey has detected a pending reboot after installing/upgrading
package '{0}' - stopping further execution".FormatWith(packageResult.Name));
throw new ApplicationException("Reboot required before continuing. Reboot and run the same command again.");
}
}
if (!packageResult.Success)
{
this.Log().Error(ChocolateyLoggers.Important, "The {0} of {1} was NOT successful.".FormatWith(commandName.ToStringSafe(), packageResult.Name));
HandleFailedOperation(config, packageResult, movePackageToFailureLocation: true, attemptRollback: true);
if (config.Features.StopOnFirstPackageFailure)
{
throw new ApplicationException("Stopping further execution as {0} has failed {1}.".FormatWith(packageResult.Name, commandName.ToStringSafe()));
}
return;
}
RemoveBackupIfExists(packageResult);
this.Log().Info(ChocolateyLoggers.Important, " The {0} of {1} was successful.".FormatWith(commandName.ToStringSafe(), packageResult.Name));
var installLocation = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation);
var installerDetected = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallerType);
if (!string.IsNullOrWhiteSpace(installLocation))
{
this.Log().Info(ChocolateyLoggers.Important, " Software installed to '{0}'".FormatWith(installLocation.EscapeCurlyBraces()));
}
else if (!string.IsNullOrWhiteSpace(installerDetected))
{
this.Log().Info(ChocolateyLoggers.Important, @" Software installed as '{0}', install location is likely default.".FormatWith(installerDetected));
}
else
{
this.Log().Info(ChocolateyLoggers.Important, @" Software install location not explicitly set, it could be in package or
default install location of installer.");
}
}
private void CreateExecutableIgnoreFiles(string installLocation, bool is64Bit)
{
// If we are using a 64 bit architecture, we want to ignore exe's targeting x86
// This is done by adding a .ignore file into the package folder for each exe to ignore
var exeFiles32Bit = (_fileSystem.DirectoryExists(_fileSystem.CombinePaths(installLocation, "tools\\x86")) ? _fileSystem.GetFiles(_fileSystem.CombinePaths(installLocation, "tools\\x86"), pattern: "*.exe", option: SearchOption.AllDirectories) : new List<string>()).ToArray();
var exeFiles64Bit = (_fileSystem.DirectoryExists(_fileSystem.CombinePaths(installLocation, "tools\\x64")) ? _fileSystem.GetFiles(_fileSystem.CombinePaths(installLocation, "tools\\x64"), pattern: "*.exe", option: SearchOption.AllDirectories) : new List<string>()).ToArray();
// If 64bit, and there are only 32bit files, we should shim the 32bit versions,
// therefore, don't ignore anything
if (is64Bit && !exeFiles64Bit.Any() && exeFiles32Bit.Any())
{
return;
}
foreach (var exeFile in is64Bit ? exeFiles32Bit.OrEmpty() : exeFiles64Bit.OrEmpty())
{
_fileSystem.CreateFile(exeFile + ".ignore");
}
}
protected virtual ChocolateyPackageInformation GetPackageInformation(PackageResult packageResult, ChocolateyConfiguration config)
{
var pkgInfo = _packageInfoService.Get(packageResult.PackageMetadata);
return pkgInfo;
}
protected virtual void UpdatePackageInformation(ChocolateyPackageInformation pkgInfo)
{
_packageInfoService.Save(pkgInfo);
}
private string CaptureArguments(ChocolateyConfiguration config, PackageResult packageResult)
{
var arguments = new StringBuilder();
// use the config to reconstruct
//bug:sources are unable to be used - it's late in the process when a package is known
//arguments.Append(" --source=\"'{0}'\"".format_with(config.Sources));
if (config.Prerelease) arguments.Append(" --prerelease");
if (config.IgnoreDependencies) arguments.Append(" --ignore-dependencies");
if (config.ForceX86) arguments.Append(" --forcex86");
if (!string.IsNullOrWhiteSpace(config.InstallArguments)) arguments.Append(" --install-arguments=\"'{0}'\"".FormatWith(config.InstallArguments));
if (config.OverrideArguments) arguments.Append(" --override-arguments");
if (config.ApplyInstallArgumentsToDependencies) arguments.Append(" --apply-install-arguments-to-dependencies");
if (!string.IsNullOrWhiteSpace(config.PackageParameters)) arguments.Append(" --package-parameters=\"'{0}'\"".FormatWith(config.PackageParameters));
if (config.ApplyPackageParametersToDependencies) arguments.Append(" --apply-package-parameters-to-dependencies");
if (config.AllowDowngrade) arguments.Append(" --allow-downgrade");
// most times folks won't want to skip automation scripts on upgrade
//if (config.SkipPackageInstallProvider) arguments.Append(" --skip-automation-scripts");
//if (config.UpgradeCommand.FailOnUnfound) arguments.Append(" --fail-on-unfound");
if (!string.IsNullOrWhiteSpace(config.SourceCommand.Username)) arguments.Append(" --user=\"'{0}'\"".FormatWith(config.SourceCommand.Username));
if (!string.IsNullOrWhiteSpace(config.SourceCommand.Password)) arguments.Append(" --password=\"'{0}'\"".FormatWith(config.SourceCommand.Password));
if (!string.IsNullOrWhiteSpace(config.SourceCommand.Certificate)) arguments.Append(" --cert=\"'{0}'\"".FormatWith(config.SourceCommand.Certificate));
if (!string.IsNullOrWhiteSpace(config.SourceCommand.CertificatePassword)) arguments.Append(" --certpassword=\"'{0}'\"".FormatWith(config.SourceCommand.CertificatePassword));
// this should likely be limited
//if (!config.Features.ChecksumFiles) arguments.Append(" --ignore-checksums");
//if (!config.Features.AllowEmptyChecksums) arguments.Append(" --allow-empty-checksums");
//if (!config.Features.AllowEmptyChecksumsSecure) arguments.Append(" --allow-empty-checksums-secure");
//arguments.Append(config.Features.UsePackageExitCodes ? " --use-package-exit-codes" : " --ignore-package-exit-codes");
//global options
if (config.CommandExecutionTimeoutSeconds != ApplicationParameters.DefaultWaitForExitInSeconds)
{
arguments.Append(" --execution-timeout=\"'{0}'\"".FormatWith(config.CommandExecutionTimeoutSeconds));
}
if (!string.IsNullOrWhiteSpace(config.CacheLocation)) arguments.Append(" --cache-location=\"'{0}'\"".FormatWith(config.CacheLocation));
if (config.Features.FailOnStandardError) arguments.Append(" --fail-on-standard-error");
if (!config.Features.UsePowerShellHost) arguments.Append(" --use-system-powershell");
return NugetEncryptionUtility.EncryptString(arguments.ToStringSafe());
}
public virtual ConcurrentDictionary<string, PackageResult> Install(ChocolateyConfiguration config)
{
ValidatePackageNames(config);
this.Log().Info(IsPackagesConfigFile(config.PackageNames) ? @"Installing from config file:" : @"Installing the following packages:");
this.Log().Info(ChocolateyLoggers.Important, @"{0}".FormatWith(config.PackageNames));
var packageInstalls = new ConcurrentDictionary<string, PackageResult>();
if (string.IsNullOrWhiteSpace(config.Sources))
{
this.Log().Error(ChocolateyLoggers.Important, @"Installation was NOT successful. There are no sources enabled for
packages, and none were passed as arguments.");
Environment.ExitCode = 1;
return packageInstalls;
}
this.Log().Info(@"By installing, you accept licenses for the packages.");
GetInitialEnvironment(config, allowLogging: true);
var installSourceRunners = _containerResolver.ResolveAll<IInstallSourceRunner>();
try
{
foreach (var packageConfig in GetConfigFromInputAndPackageConfigInput(config, packageInstalls, installSourceRunners).OrEmpty())
{
ConcurrentDictionary<string, PackageResult> results;
if (packageConfig.SourceType.IsEqualTo(SourceTypes.Normal))
{
var action = new Action<PackageResult, ChocolateyConfiguration>((packageResult, configuration) => HandlePackageResult(packageResult, configuration, CommandNameType.Install));
var beforeModifyAction = new Action<PackageResult, ChocolateyConfiguration>((packageResult, configuration) => BeforeModifyAction(packageResult, configuration));
results = _nugetService.Install(packageConfig, action, beforeModifyAction);
}
else
{
results = PerformSourceRunnerFunction<IInstallSourceRunner, ConcurrentDictionary<string, PackageResult>>(packageConfig, runner => runner.Install(packageConfig, null));
}
if (results is null)
{
throw new NotSupportedException("The '{0}' source does not support installing packages".FormatWith(config.SourceType));
}
foreach (var result in results)
{
packageInstalls.GetOrAdd(result.Key, result.Value);
}
}
}
finally
{
var installFailures = ReportActionSummary(packageInstalls, "installed");
if (installFailures != 0 && Environment.ExitCode == 0)
{
Environment.ExitCode = 1;
}
RandomlyNotifyAboutLicensedFeatures(config);
}
return packageInstalls;
}
public void OutdatedDryRun(ChocolateyConfiguration config)
{
this.Log().Info(@"
Would have determined packages that are out of date based on what is
installed and what versions are available for upgrade.");
}
public virtual void Outdated(ChocolateyConfiguration config)
{
if (!config.SourceType.IsEqualTo(SourceTypes.Normal))
{
this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for outdated.");
return;
}
if (config.RegularOutput) this.Log().Info(ChocolateyLoggers.Important, @"Outdated Packages
Output is package name | current version | available version | pinned?
");
config.PackageNames = ApplicationParameters.AllPackages;
config.UpgradeCommand.NotifyOnlyAvailableUpgrades = true;
var output = config.RegularOutput;
config.RegularOutput = false;
var outdatedPackages = _nugetService.GetOutdated(config);
config.RegularOutput = output;
var outdatedPackageCount = outdatedPackages.Count(p => p.Value.Success && !p.Value.Inconclusive);
if (config.RegularOutput)
{
var upgradeWarnings = outdatedPackages.Count(p => p.Value.Warning);
this.Log().Warn(() => @"{0}{1} has determined {2} package(s) are outdated. {3}".FormatWith(
Environment.NewLine,
ApplicationParameters.Name,
outdatedPackageCount,
upgradeWarnings == 0 ? string.Empty : "{0} {1} package(s) had warnings.".FormatWith(Environment.NewLine, upgradeWarnings)
));
if (upgradeWarnings != 0)
{
this.Log().Warn(ChocolateyLoggers.Important, "Warnings:");
foreach (var warning in outdatedPackages.Where(p => p.Value.Warning).OrEmpty())
{
this.Log().Warn(ChocolateyLoggers.Important, " - {0}".FormatWith(warning.Value.Name));
}
}
}
// outdated packages, return 2
if (config.Features.UseEnhancedExitCodes && outdatedPackageCount != 0 && Environment.ExitCode == 0)
{
Environment.ExitCode = 2;
}
RandomlyNotifyAboutLicensedFeatures(config);
}
private IEnumerable<ChocolateyConfiguration> GetConfigFromInputAndPackageConfigInput(ChocolateyConfiguration config, ConcurrentDictionary<string, PackageResult> packageInstalls, IEnumerable<IAlternativeSourceRunner> alternativeSourceRunners)
{
// if there are any .config files, split those off of the config. Then return the config without those package names.
foreach (var packageConfigFile in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty().Where(p => p.EndsWith(".config")).ToList())
{
config.PackageNames = config.PackageNames.Replace(packageConfigFile, string.Empty);
foreach (var packageConfig in GetPackagesFromConfigFile(packageConfigFile, config, packageInstalls, alternativeSourceRunners).OrEmpty())
{
yield return packageConfig;
}
}
yield return config;
}
private bool IsPackagesConfigFile(string packageNames)
{
return packageNames.ToStringSafe().EndsWith(".config", StringComparison.OrdinalIgnoreCase) && !packageNames.ToStringSafe().ContainsSafe(";");
}
private IEnumerable<ChocolateyConfiguration> GetPackagesFromConfigFile(string packageConfigFile, ChocolateyConfiguration config, ConcurrentDictionary<string, PackageResult> packageInstalls, IEnumerable<IAlternativeSourceRunner> alternativeSourceRunners)
{
IList<ChocolateyConfiguration> packageConfigs = new List<ChocolateyConfiguration>();
if (!_fileSystem.FileExists(_fileSystem.GetFullPath(packageConfigFile)))
{
var logMessage = "'{0}' could not be found in the location specified.".FormatWith(packageConfigFile);
this.Log().Error(ChocolateyLoggers.Important, logMessage);
var results = packageInstalls.GetOrAdd(packageConfigFile, new PackageResult(packageConfigFile, null, null));
results.Messages.Add(new ResultMessage(ResultType.Error, logMessage));
return packageConfigs;
}
var settings = _xmlService.Deserialize<PackagesConfigFileSettings>(_fileSystem.GetFullPath(packageConfigFile));
this.Log().Info(@"Installing the following packages:");
foreach (var pkgSettings in settings.Packages.OrEmpty())
{
if (!pkgSettings.Disabled)
{
var packageConfig = config.DeepCopy();
packageConfig.PackageNames = pkgSettings.Id;
packageConfig.Sources = string.IsNullOrWhiteSpace(pkgSettings.Source) ? packageConfig.Sources : pkgSettings.Source;
packageConfig.Version = pkgSettings.Version;
packageConfig.InstallArguments = string.IsNullOrWhiteSpace(pkgSettings.InstallArguments) ? packageConfig.InstallArguments : pkgSettings.InstallArguments;
packageConfig.PackageParameters = string.IsNullOrWhiteSpace(pkgSettings.PackageParameters) ? packageConfig.PackageParameters : pkgSettings.PackageParameters;
if (pkgSettings.ForceX86) packageConfig.ForceX86 = true;
if (pkgSettings.IgnoreDependencies) packageConfig.IgnoreDependencies = true;
if (pkgSettings.ApplyInstallArgumentsToDependencies) packageConfig.ApplyInstallArgumentsToDependencies = true;
if (pkgSettings.ApplyPackageParametersToDependencies) packageConfig.ApplyPackageParametersToDependencies = true;
if (!string.IsNullOrWhiteSpace(pkgSettings.Source) && HasSourceType(pkgSettings.Source, alternativeSourceRunners))
{
packageConfig.SourceType = pkgSettings.Source;
}
if (pkgSettings.PinPackage) packageConfig.PinPackage = true;
if (pkgSettings.Force) packageConfig.Force = true;
packageConfig.CommandExecutionTimeoutSeconds = pkgSettings.ExecutionTimeout == -1 ? packageConfig.CommandExecutionTimeoutSeconds : pkgSettings.ExecutionTimeout;
if (pkgSettings.Prerelease) packageConfig.Prerelease = true;
if (pkgSettings.OverrideArguments) packageConfig.OverrideArguments = true;
if (pkgSettings.NotSilent) packageConfig.NotSilent = true;
if (pkgSettings.AllowDowngrade) packageConfig.AllowDowngrade = true;
if (pkgSettings.ForceDependencies) packageConfig.ForceDependencies = true;
if (pkgSettings.SkipAutomationScripts) packageConfig.SkipPackageInstallProvider = true;
packageConfig.SourceCommand.Username = string.IsNullOrWhiteSpace(pkgSettings.User) ? packageConfig.SourceCommand.Username : pkgSettings.User;
packageConfig.SourceCommand.Password = string.IsNullOrWhiteSpace(pkgSettings.Password) ? packageConfig.SourceCommand.Password : pkgSettings.Password;
packageConfig.SourceCommand.Certificate = string.IsNullOrWhiteSpace(pkgSettings.Cert) ? packageConfig.SourceCommand.Certificate : pkgSettings.Cert;
packageConfig.SourceCommand.CertificatePassword = string.IsNullOrWhiteSpace(pkgSettings.CertPassword) ? packageConfig.SourceCommand.CertificatePassword : pkgSettings.CertPassword;
if (pkgSettings.IgnoreChecksums) packageConfig.Features.ChecksumFiles = false;
if (pkgSettings.AllowEmptyChecksums) packageConfig.Features.AllowEmptyChecksums = true;
if (pkgSettings.AllowEmptyChecksumsSecure) packageConfig.Features.AllowEmptyChecksumsSecure = true;
if (pkgSettings.RequireChecksums)
{
packageConfig.Features.AllowEmptyChecksums = false;
packageConfig.Features.AllowEmptyChecksumsSecure = false;
}
packageConfig.DownloadChecksum = string.IsNullOrWhiteSpace(pkgSettings.DownloadChecksum) ? packageConfig.DownloadChecksum : pkgSettings.DownloadChecksum;
packageConfig.DownloadChecksum64 = string.IsNullOrWhiteSpace(pkgSettings.DownloadChecksum64) ? packageConfig.DownloadChecksum64 : pkgSettings.DownloadChecksum64;
packageConfig.DownloadChecksumType = string.IsNullOrWhiteSpace(pkgSettings.DownloadChecksumType) ? packageConfig.DownloadChecksumType : pkgSettings.DownloadChecksumType;
packageConfig.DownloadChecksumType64 = string.IsNullOrWhiteSpace(pkgSettings.DownloadChecksumType64) ? packageConfig.DownloadChecksumType : pkgSettings.DownloadChecksumType64;
if (pkgSettings.IgnorePackageExitCodes) packageConfig.Features.UsePackageExitCodes = false;
if (pkgSettings.UsePackageExitCodes) packageConfig.Features.UsePackageExitCodes = true;
if (pkgSettings.StopOnFirstFailure) packageConfig.Features.StopOnFirstPackageFailure = true;
if (pkgSettings.ExitWhenRebootDetected) packageConfig.Features.ExitOnRebootDetected = true;
if (pkgSettings.IgnoreDetectedReboot) packageConfig.Features.ExitOnRebootDetected = false;
if (pkgSettings.DisableRepositoryOptimizations) packageConfig.Features.UsePackageRepositoryOptimizations = false;
if (pkgSettings.AcceptLicense) packageConfig.AcceptLicense = true;
if (pkgSettings.Confirm)
{
packageConfig.PromptForConfirmation = false;
packageConfig.AcceptLicense = true;
}
if (pkgSettings.LimitOutput) packageConfig.RegularOutput = false;
packageConfig.CacheLocation = string.IsNullOrWhiteSpace(pkgSettings.CacheLocation) ? packageConfig.CacheLocation : pkgSettings.CacheLocation;
if (pkgSettings.FailOnStderr) packageConfig.Features.FailOnStandardError = true;
if (pkgSettings.UseSystemPowershell) packageConfig.Features.UsePowerShellHost = false;
if (pkgSettings.NoProgress) packageConfig.Features.ShowDownloadProgress = false;
this.Log().Info(ChocolateyLoggers.Important, @"{0}".FormatWith(packageConfig.PackageNames));
packageConfigs.Add(packageConfig);
this.Log().Debug(() => "Package Configuration Start:{0}{1}{0}Package Configuration End".FormatWith(System.Environment.NewLine, packageConfig.ToString()));
}
}
return packageConfigs;
}
public void UpgradeDryRun(ChocolateyConfiguration config)
{
ValidatePackageNames(config);
var upgradeSourceRunners = _containerResolver.ResolveAll<IUpgradeSourceRunner>();
config.Noop = true;
ConcurrentDictionary<string, PackageResult> noopUpgrades;
if (config.SourceType.IsEqualTo(SourceTypes.Normal))
{
Action<PackageResult, ChocolateyConfiguration> action = (pkg, configuration) => _powershellService.InstallDryRun(pkg);
noopUpgrades = _nugetService.UpgradeDryRun(config, action);
}
else
{
noopUpgrades = PerformSourceRunnerFunction(config, runner => runner.UpgradeDryRun(config, null), upgradeSourceRunners);
}
if (config.RegularOutput)
{
var noopFailures = ReportActionSummary(noopUpgrades, "can upgrade");
}
RandomlyNotifyAboutLicensedFeatures(config);
}
public virtual ConcurrentDictionary<string, PackageResult> Upgrade(ChocolateyConfiguration config)
{
ValidatePackageNames(config);
this.Log().Info(@"Upgrading the following packages:");
this.Log().Info(ChocolateyLoggers.Important, @"{0}".FormatWith(config.PackageNames));
if (string.IsNullOrWhiteSpace(config.Sources))
{
this.Log().Error(ChocolateyLoggers.Important, @"Upgrading was NOT successful. There are no sources enabled for
packages and none were passed as arguments.");
Environment.ExitCode = 1;
return new ConcurrentDictionary<string, PackageResult>();
}
this.Log().Info(@"By upgrading, you accept licenses for the packages.");
foreach (var packageConfigFile in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty().Where(p => p.EndsWith(".config")).ToList())
{
throw new ApplicationException("A packages.config file is only used with installs.");
}
var packageUpgrades = new ConcurrentDictionary<string, PackageResult>();
try
{
GetInitialEnvironment(config, allowLogging: true);
ConcurrentDictionary<string, PackageResult> results;
if (config.SourceType.IsEqualTo(SourceTypes.Normal))
{
var action = new Action<PackageResult, ChocolateyConfiguration>((packageResult, configuration) => HandlePackageResult(packageResult, configuration, CommandNameType.Upgrade));
var beforeUpgradeAction = new Action<PackageResult, ChocolateyConfiguration>((packageResult, configuration) => BeforeModifyAction(packageResult, configuration));
results = _nugetService.Upgrade(config, action, beforeUpgradeAction);
}
else
{
results = PerformSourceRunnerFunction<IUpgradeSourceRunner, ConcurrentDictionary<string, PackageResult>>(config, runner => runner.Upgrade(config, null));
}
if (results is null)
{
throw new NotSupportedException("The '{0}' source does not support upgrading packages".FormatWith(config.SourceType));
}
foreach (var result in results)
{
packageUpgrades.GetOrAdd(result.Key, result.Value);
}
}
finally
{
var upgradeFailures = ReportActionSummary(packageUpgrades, "upgraded");
if (upgradeFailures != 0 && Environment.ExitCode == 0)
{
Environment.ExitCode = 1;
}
RandomlyNotifyAboutLicensedFeatures(config);