Пример #1
0
        public void backup_existing_version(ChocolateyConfiguration config, IPackage installedPackage)
        {
            _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackageBackupLocation);

            var pathResolver   = NugetCommon.GetPathResolver(config, NugetCommon.GetNuGetFileSystem(config, _nugetLogger));
            var pkgInstallPath = pathResolver.GetInstallPath(installedPackage);

            if (!_fileSystem.directory_exists(pkgInstallPath))
            {
                var chocoPathResolver = pathResolver as ChocolateyPackagePathResolver;
                if (chocoPathResolver != null)
                {
                    chocoPathResolver.UseSideBySidePaths = !chocoPathResolver.UseSideBySidePaths;
                    pkgInstallPath = chocoPathResolver.GetInstallPath(installedPackage);
                }
            }

            if (_fileSystem.directory_exists(pkgInstallPath))
            {
                this.Log().Debug("Backing up existing {0} prior to upgrade.".format_with(installedPackage.Id));

                var backupLocation = pkgInstallPath.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageBackupLocation);

                var errored = false;
                try
                {
                    _fileSystem.move_directory(pkgInstallPath, backupLocation);
                }
                catch (Exception ex)
                {
                    errored = true;
                    this.Log().Error("Error during backup (move phase):{0} {1}".format_with(Environment.NewLine, ex.Message));
                }
                finally
                {
                    try
                    {
                        _fileSystem.copy_directory(backupLocation, pkgInstallPath, overwriteExisting: true);
                    }
                    catch (Exception ex)
                    {
                        errored = true;
                        this.Log().Error("Error during backup (reset phase):{0} {1}".format_with(Environment.NewLine, ex.Message));
                    }
                }

                backup_configuration_files(pkgInstallPath, installedPackage.Version.to_string());

                if (errored)
                {
                    this.Log().Warn(ChocolateyLoggers.Important,
                                    @"There was an error accessing files. This could mean there is a 
 process locking the folder or files. Please make sure nothing is 
 running that would lock the files or folders in this directory prior 
 to upgrade. If the package fails to upgrade, this is likely the cause.");
                }
            }
        }
Пример #2
0
        public void list(ChocolateyConfiguration configuration)
        {
            var packageManager = NugetCommon.GetPackageManager(configuration, _nugetLogger,
                                                               new PackageDownloader(),
                                                               installSuccessAction: null,
                                                               uninstallSuccessAction: null,
                                                               addUninstallHandler: false);

            var templateDirList                   = _fileSystem.get_directories(ApplicationParameters.TemplatesLocation).ToList();
            var isBuiltInTemplateOverriden        = templateDirList.Contains(_fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, _builtInTemplateOverrideName));
            var isBuiltInOrDefaultTemplateDefault = string.IsNullOrWhiteSpace(configuration.DefaultTemplateName) || !templateDirList.Contains(_fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, configuration.DefaultTemplateName));

            if (string.IsNullOrWhiteSpace(configuration.TemplateCommand.Name))
            {
                if (templateDirList.Any())
                {
                    foreach (var templateDir in templateDirList)
                    {
                        configuration.TemplateCommand.Name = _fileSystem.get_file_name(templateDir);
                        list_custom_template_info(configuration, packageManager);
                    }

                    this.Log().Info(configuration.RegularOutput ? "{0} Custom templates found at {1}{2}".format_with(templateDirList.Count(), ApplicationParameters.TemplatesLocation, Environment.NewLine) : string.Empty);
                }
                else
                {
                    this.Log().Info(configuration.RegularOutput ? "No custom templates installed in {0}{1}".format_with(ApplicationParameters.TemplatesLocation, Environment.NewLine) : string.Empty);
                }

                list_built_in_template_info(configuration, isBuiltInTemplateOverriden, isBuiltInOrDefaultTemplateDefault);
            }
            else
            {
                if (templateDirList.Contains(_fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name)))
                {
                    list_custom_template_info(configuration, packageManager);
                    if (configuration.TemplateCommand.Name == _builtInTemplateName || configuration.TemplateCommand.Name == _builtInTemplateOverrideName)
                    {
                        list_built_in_template_info(configuration, isBuiltInTemplateOverriden, isBuiltInOrDefaultTemplateDefault);
                    }
                }
                else
                {
                    if (configuration.TemplateCommand.Name.ToLowerInvariant() == _builtInTemplateName || configuration.TemplateCommand.Name.ToLowerInvariant() == _builtInTemplateOverrideName)
                    {
                        // We know that the template is not overriden since the template directory was checked
                        list_built_in_template_info(configuration, isBuiltInTemplateOverriden, isBuiltInOrDefaultTemplateDefault);
                    }
                    else
                    {
                        throw new ApplicationException("Unable to find requested template '{0}'".format_with(configuration.TemplateCommand.Name));
                    }
                }
            }
        }
Пример #3
0
        public static void install_package(ChocolateyConfiguration config, string packageId, string version)
        {
            var pattern = "{0}.{1}{2}".format_with(packageId, string.IsNullOrWhiteSpace(version) ? "*" : version, Constants.PackageExtension);
            var files   = _fileSystem.get_files(config.Sources, pattern);

            foreach (var file in files)
            {
                var packageManager = NugetCommon.GetPackageManager(config, new ChocolateyNugetLogger(), null, null, false);
                packageManager.InstallPackage(new OptimizedZipPackage(file), false, false);
            }
        }
Пример #4
0
        public void run(ChocolateyConfiguration configuration)
        {
            var packageManager = NugetCommon.GetPackageManager(configuration, _nugetLogger,
                                                               installSuccessAction: null,
                                                               uninstallSuccessAction: null);

            switch (configuration.PinCommand.Command)
            {
            case PinCommandType.list:
                list_pins(packageManager, configuration);
                break;

            case PinCommandType.add:
            case PinCommandType.remove:
                set_pin(packageManager, configuration);
                break;
            }
        }
Пример #5
0
        public virtual void run(ChocolateyConfiguration configuration)
        {
            var packageManager = NugetCommon.GetPackageManager(configuration, _nugetLogger,
                                                               new PackageDownloader(),
                                                               installSuccessAction: null,
                                                               uninstallSuccessAction: null,
                                                               addUninstallHandler: false);

            switch (configuration.PinCommand.Command)
            {
            case PinCommandType.list:
                list_pins(packageManager, configuration);
                break;

            case PinCommandType.add:
            case PinCommandType.remove:
                set_pin(packageManager, configuration);
                break;
            }
        }
Пример #6
0
        public void rename_legacy_package_version(ChocolateyConfiguration config, IPackage installedPackage, ChocolateyPackageInformation pkgInfo)
        {
            if (pkgInfo != null && pkgInfo.IsSideBySide)
            {
                return;
            }

            var installDirectory = _fileSystem.combine_paths(ApplicationParameters.PackagesLocation, installedPackage.Id);

            if (!_fileSystem.directory_exists(installDirectory))
            {
                // if the folder has a version on it, we need to rename the folder first.
                var pathResolver = new ChocolateyPackagePathResolver(NugetCommon.GetNuGetFileSystem(config, _nugetLogger), useSideBySidePaths: true);
                installDirectory = pathResolver.GetInstallPath(installedPackage);
                if (_fileSystem.directory_exists(installDirectory))
                {
                    FaultTolerance.try_catch_with_logging_exception(
                        () => _fileSystem.move_directory(installDirectory, _fileSystem.combine_paths(ApplicationParameters.PackagesLocation, installedPackage.Id)),
                        "Error during old package rename");
                }
            }
        }
Пример #7
0
        public void backup_existing_version(ChocolateyConfiguration config, IPackage installedPackage)
        {
            var pathResolver   = NugetCommon.GetPathResolver(config, NugetCommon.GetNuGetFileSystem(config, _nugetLogger));
            var pkgInstallPath = pathResolver.GetInstallPath(installedPackage);

            if (!_fileSystem.directory_exists(pkgInstallPath))
            {
                var chocoPathResolver = pathResolver as ChocolateyPackagePathResolver;
                if (chocoPathResolver != null)
                {
                    chocoPathResolver.UseSideBySidePaths = !chocoPathResolver.UseSideBySidePaths;
                    pkgInstallPath = chocoPathResolver.GetInstallPath(installedPackage);
                }
            }

            if (_fileSystem.directory_exists(pkgInstallPath))
            {
                this.Log().Debug("Backing up existing {0} prior to upgrade.".format_with(installedPackage.Id));

                var backupLocation = pkgInstallPath + ApplicationParameters.RollbackPackageSuffix;
                _fileSystem.copy_directory(pkgInstallPath, backupLocation, overwriteExisting: true);
            }
        }
Пример #8
0
        public ConcurrentDictionary <string, PackageResult> uninstall_run(ChocolateyConfiguration config, Action <PackageResult> continueAction, bool performAction)
        {
            var packageUninstalls = new ConcurrentDictionary <string, PackageResult>();

            SemanticVersion version        = config.Version != null ? new SemanticVersion(config.Version) : null;
            var             packageManager = NugetCommon.GetPackageManager(config, _nugetLogger,
                                                                           installSuccessAction: null,
                                                                           uninstallSuccessAction: (e) =>
            {
                var pkg = e.Package;
                "chocolatey".Log().Info(ChocolateyLoggers.Important, " {0} has been successfully uninstalled.".format_with(pkg.Id));
            });

            var loopCount = 0;

            packageManager.PackageUninstalling += (s, e) =>
            {
                var pkg = e.Package;

                // this section fires twice sometimes, like for older packages in a sxs install...
                var    results    = packageUninstalls.GetOrAdd(pkg.Id.to_lower() + "." + pkg.Version.to_string(), new PackageResult(pkg, e.InstallPath));
                string logMessage = "{0}{1} v{2}{3}".format_with(Environment.NewLine, pkg.Id, pkg.Version.to_string(), config.Force ? " (forced)" : string.Empty);
                if (results.Messages.Count((p) => p.Message == ApplicationParameters.Messages.NugetEventActionHeader) == 0)
                {
                    results.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.NugetEventActionHeader));
                    "chocolatey".Log().Info(ChocolateyLoggers.Important, logMessage);
                    loopCount = 0;
                }
                else
                {
                    "chocolatey".Log().Debug(ChocolateyLoggers.Important, "Another time through!{0}{1}".format_with(Environment.NewLine, logMessage));
                    loopCount += 1;
                }

                if (loopCount == 10)
                {
                    this.Log().Warn("Loop detected. Attempting to break out. Check for issues with {0}".format_with(pkg.Id));
                    return;
                }

                // is this the latest version or have you passed --sxs? This is the only way you get through to the continue action.
                var latestVersion = packageManager.LocalRepository.FindPackage(e.Package.Id);
                if (latestVersion.Version == pkg.Version || config.AllowMultipleVersions)
                {
                    results.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.ContinueChocolateyAction));
                    if (continueAction != null)
                    {
                        continueAction.Invoke(results);
                    }
                }
                else
                {
                    //todo:allow cleaning of pkgstore files
                }
            };

            set_package_names_if_all_is_specified(config, () =>
            {
                // force remove the item, ignore the dependencies
                // as those are going to be picked up anyway
                config.Force             = true;
                config.ForceDependencies = false;
            });

            foreach (string packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null())
            {
                remove_existing_rollback_directory(packageName);

                IList <IPackage> installedPackageVersions = new List <IPackage>();
                if (string.IsNullOrWhiteSpace(config.Version))
                {
                    installedPackageVersions = packageManager.LocalRepository.FindPackagesById(packageName).OrderBy((p) => p.Version).ToList();
                }
                else
                {
                    IPackage installedPackage = packageManager.LocalRepository.FindPackage(packageName);
                    if (installedPackage != null)
                    {
                        installedPackageVersions.Add(installedPackage);
                    }
                }

                if (installedPackageVersions.Count == 0)
                {
                    string logMessage = "{0} is not installed. Cannot uninstall a non-existent package.".format_with(packageName);
                    var    results    = packageUninstalls.GetOrAdd(packageName, new PackageResult(packageName, null, null));
                    results.Messages.Add(new ResultMessage(ResultType.Error, logMessage));

                    if (config.RegularOuptut)
                    {
                        this.Log().Error(ChocolateyLoggers.Important, logMessage);
                    }
                    continue;
                }

                var packageVersionsToRemove = installedPackageVersions.ToList();
                if (!config.AllVersions)
                {
                    if (config.PromptForConfirmation)
                    {
                        packageVersionsToRemove.Clear();

                        IList <string> choices     = new List <string>();
                        const string   abortChoice = "None";
                        choices.Add(abortChoice);
                        foreach (var installedVersion in installedPackageVersions.or_empty_list_if_null())
                        {
                            choices.Add(installedVersion.Version.to_string());
                        }

                        const string allVersionsChoice = "All versions";
                        if (installedPackageVersions.Count != 1)
                        {
                            choices.Add(allVersionsChoice);
                        }

                        var selection = InteractivePrompt.prompt_for_confirmation("Which version of {0} would you like to uninstall?".format_with(packageName), choices, abortChoice, true);

                        if (string.IsNullOrWhiteSpace(selection))
                        {
                            continue;
                        }
                        if (selection.is_equal_to(abortChoice))
                        {
                            continue;
                        }
                        if (selection.is_equal_to(allVersionsChoice))
                        {
                            packageVersionsToRemove = installedPackageVersions.ToList();
                            if (config.RegularOuptut)
                            {
                                this.Log().Info(() => "You selected to remove all versions of {0}".format_with(packageName));
                            }
                        }
                        else
                        {
                            IPackage pkg = installedPackageVersions.FirstOrDefault((p) => p.Version.to_string().is_equal_to(selection));
                            packageVersionsToRemove.Add(pkg);
                            if (config.RegularOuptut)
                            {
                                this.Log().Info(() => "You selected {0} v{1}".format_with(pkg.Id, pkg.Version.to_string()));
                            }
                        }
                    }
                }

                foreach (var packageVersion in packageVersionsToRemove)
                {
                    if (performAction)
                    {
                        using (packageManager.SourceRepository.StartOperation(
                                   RepositoryOperationNames.Install,
                                   packageName,
                                   version == null ? null : version.ToString()))
                        {
                            packageManager.UninstallPackage(packageVersion, forceRemove: config.Force, removeDependencies: config.ForceDependencies);
                        }
                    }
                    else
                    {
                        packageUninstalls.GetOrAdd(packageVersion.Id.to_lower() + "." + packageVersion.Version.to_string(), new PackageResult(packageVersion, ApplicationParameters.PackagesLocation));
                    }
                }
            }

            return(packageUninstalls);
        }
Пример #9
0
        public ConcurrentDictionary <string, PackageResult> upgrade_run(ChocolateyConfiguration config, Action <PackageResult> continueAction, bool performAction)
        {
            _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackagesLocation);
            var packageInstalls = new ConcurrentDictionary <string, PackageResult>();

            SemanticVersion version        = config.Version != null ? new SemanticVersion(config.Version) : null;
            var             packageManager = NugetCommon.GetPackageManager(
                config,
                _nugetLogger,
                installSuccessAction: (e) =>
            {
                var pkg     = e.Package;
                var results = packageInstalls.GetOrAdd(pkg.Id.to_lower(), new PackageResult(pkg, e.InstallPath));
                results.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.ContinueChocolateyAction));

                if (continueAction != null)
                {
                    continueAction.Invoke(results);
                }
            },
                uninstallSuccessAction: null);

            var configIgnoreDependencies = config.IgnoreDependencies;

            set_package_names_if_all_is_specified(config, () => { config.IgnoreDependencies = true; });
            config.IgnoreDependencies = configIgnoreDependencies;


            foreach (string packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null())
            {
                //todo: get smarter about realizing multiple versions have been installed before and allowing that

                remove_existing_rollback_directory(packageName);

                IPackage installedPackage = packageManager.LocalRepository.FindPackage(packageName);

                if (installedPackage == null)
                {
                    //todo v1 Deprecation - reimplement error
                    //string logMessage = "{0} is not installed. Cannot upgrade a non-existent package.".format_with(packageName);
                    //var results = packageInstalls.GetOrAdd(packageName, new PackageResult(packageName, null, null));
                    //results.Messages.Add(new ResultMessage(ResultType.Error, logMessage));

                    //if (config.RegularOuptut) this.Log().Error(ChocolateyLoggers.Important, logMessage);
                    //continue;

                    string logMessage = @"
DEPRECATION NOTICE - Upgrade will no longer install non-installed 
packages as of version 1.0.0. That is what the install command is for.


{0} is not installed. Installing...".format_with(packageName);

                    if (config.RegularOuptut)
                    {
                        this.Log().Warn(ChocolateyLoggers.Important, logMessage);
                    }

                    var packageNames = config.PackageNames;
                    config.PackageNames = packageName;
                    var installResults = install_run(config, continueAction);
                    foreach (var packageResult in installResults)
                    {
                        packageInstalls.GetOrAdd(packageResult.Key, packageResult.Value);
                    }
                    config.PackageNames = packageNames;
                    continue;
                }

                var pkgInfo = _packageInfoService.get_package_information(installedPackage);
                if (pkgInfo != null && pkgInfo.IsPinned)
                {
                    string logMessage = "{0} is pinned. Skipping pinned package.".format_with(packageName);
                    var    results    = packageInstalls.GetOrAdd(packageName, new PackageResult(packageName, null, null));
                    results.Messages.Add(new ResultMessage(ResultType.Warn, logMessage));
                    results.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage));
                    if (config.RegularOuptut)
                    {
                        this.Log().Warn(ChocolateyLoggers.Important, logMessage);
                    }
                    continue;
                }

                IPackage availablePackage = packageManager.SourceRepository.FindPackage(packageName, version, config.Prerelease, allowUnlisted: false);
                if (availablePackage == null)
                {
                    string logMessage = "{0} was not found with the source(s) listed.{1} If you specified a particular version and are receiving this message, it is possible that the package name exists but the version does not.{1} Version: \"{2}\"{1} Source(s): \"{3}\"".format_with(packageName, Environment.NewLine, config.Version, config.Sources);
                    var    results    = packageInstalls.GetOrAdd(packageName, new PackageResult(packageName, version.to_string(), null));

                    if (config.UpgradeCommand.FailOnUnfound)
                    {
                        results.Messages.Add(new ResultMessage(ResultType.Error, logMessage));
                        if (config.RegularOuptut)
                        {
                            this.Log().Error(ChocolateyLoggers.Important, logMessage);
                        }
                    }
                    else
                    {
                        results.Messages.Add(new ResultMessage(ResultType.Warn, logMessage));
                        results.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage));
                        if (config.RegularOuptut)
                        {
                            this.Log().Warn(ChocolateyLoggers.Important, logMessage);
                        }
                    }

                    continue;
                }

                if ((installedPackage.Version > availablePackage.Version))
                {
                    string logMessage = "{0} v{1} is newer than the most recent.{2} You must be smarter than the average bear...".format_with(installedPackage.Id, installedPackage.Version, Environment.NewLine);
                    var    results    = packageInstalls.GetOrAdd(packageName, new PackageResult(installedPackage, ApplicationParameters.PackagesLocation));
                    results.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage));

                    if (config.RegularOuptut)
                    {
                        this.Log().Info(ChocolateyLoggers.Important, logMessage);
                    }
                    continue;
                }

                if ((installedPackage.Version == availablePackage.Version))
                {
                    string logMessage = "{0} v{1} is the latest version available based on your source(s).".format_with(installedPackage.Id, installedPackage.Version);
                    var    results    = packageInstalls.GetOrAdd(packageName, new PackageResult(installedPackage, ApplicationParameters.PackagesLocation));
                    if (results.Messages.Count((p) => p.Message == ApplicationParameters.Messages.ContinueChocolateyAction) == 0)
                    {
                        results.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage));
                    }

                    if (config.RegularOuptut)
                    {
                        this.Log().Info(logMessage);
                    }
                    if (!config.Force)
                    {
                        continue;
                    }
                }

                if (availablePackage.Version > installedPackage.Version || config.Force)
                {
                    if (availablePackage.Version > installedPackage.Version)
                    {
                        if (config.RegularOuptut)
                        {
                            this.Log().Warn("You have {0} v{1} installed. Version {2} is available based on your source(s)".format_with(installedPackage.Id, installedPackage.Version, availablePackage.Version));
                        }
                        else
                        {
                            //last one is whether this package is pinned or not
                            this.Log().Info("{0}|{1}|{2}|{3}".format_with(installedPackage.Id, installedPackage.Version, availablePackage.Version, "false"));
                        }
                    }

                    if (performAction)
                    {
                        using (packageManager.SourceRepository.StartOperation(
                                   RepositoryOperationNames.Update,
                                   packageName,
                                   version == null ? null : version.ToString()))
                        {
                            backup_existing_version(config, installedPackage);
                            packageManager.UpdatePackage(availablePackage, updateDependencies: !config.IgnoreDependencies, allowPrereleaseVersions: config.Prerelease);
                        }
                    }
                }
            }

            return(packageInstalls);
        }
Пример #10
0
        public ConcurrentDictionary <string, PackageResult> install_run(ChocolateyConfiguration config, Action <PackageResult> continueAction)
        {
            _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackagesLocation);
            var packageInstalls = new ConcurrentDictionary <string, PackageResult>();

            //todo: handle all

            SemanticVersion version = config.Version != null ? new SemanticVersion(config.Version) : null;

            IList <string> packageNames = config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null().ToList();

            if (packageNames.Count == 1)
            {
                var packageName = packageNames.DefaultIfEmpty(string.Empty).FirstOrDefault();
                if (packageName.EndsWith(Constants.PackageExtension) || packageName.EndsWith(Constants.ManifestExtension))
                {
                    this.Log().Debug("Updating source and package name to handle *.nupkg or *.nuspec file.");
                    packageNames.Clear();
                    packageNames.Add(_fileSystem.get_file_name_without_extension(packageName));
                    config.Sources = _fileSystem.get_directory_name(_fileSystem.get_full_path(packageName));

                    if (packageName.EndsWith(Constants.ManifestExtension))
                    {
                        this.Log().Debug("Building nuspec file prior to install.");
                        config.Input = packageName;
                        // build package
                        pack_run(config);
                    }
                }
            }

            if (config.Sources.to_string().EndsWith(Constants.PackageExtension))
            {
                config.Sources = _fileSystem.get_directory_name(_fileSystem.get_full_path(config.Sources));
            }

            var packageManager = NugetCommon.GetPackageManager(config, _nugetLogger,
                                                               installSuccessAction: (e) =>
            {
                var pkg     = e.Package;
                var results = packageInstalls.GetOrAdd(pkg.Id.to_lower(), new PackageResult(pkg, e.InstallPath));
                results.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.ContinueChocolateyAction));

                if (continueAction != null)
                {
                    continueAction.Invoke(results);
                }
            },
                                                               uninstallSuccessAction: null);

            foreach (string packageName in packageNames.or_empty_list_if_null())
            {
                //todo: get smarter about realizing multiple versions have been installed before and allowing that

                remove_existing_rollback_directory(packageName);

                IPackage installedPackage = packageManager.LocalRepository.FindPackage(packageName);

                if (installedPackage != null && (version == null || version == installedPackage.Version) && !config.Force)
                {
                    string logMessage = "{0} v{1} already installed.{2} Use --force to reinstall, specify a version to install, or try upgrade.".format_with(installedPackage.Id, installedPackage.Version, Environment.NewLine);
                    var    results    = packageInstalls.GetOrAdd(packageName, new PackageResult(installedPackage, ApplicationParameters.PackagesLocation));
                    results.Messages.Add(new ResultMessage(ResultType.Warn, logMessage));
                    results.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage));
                    this.Log().Warn(ChocolateyLoggers.Important, logMessage);
                    continue;
                }

                if (installedPackage != null && (version == null || version == installedPackage.Version) && config.Force)
                {
                    this.Log().Debug(() => "{0} v{1} already installed. Forcing reinstall.".format_with(installedPackage.Id, installedPackage.Version));
                    version = installedPackage.Version;
                }

                IPackage availablePackage = packageManager.SourceRepository.FindPackage(packageName, version, config.Prerelease, allowUnlisted: false);
                if (availablePackage == null)
                {
                    var logMessage = "{0} not installed. The package was not found with the source(s) listed.{1} If you specified a particular version and are receiving this message, it is possible that the package name exists but the version does not.{1} Version: \"{2}\"{1} Source(s): \"{3}\"".format_with(packageName, Environment.NewLine, config.Version, config.Sources);
                    this.Log().Error(ChocolateyLoggers.Important, logMessage);
                    var results = packageInstalls.GetOrAdd(packageName, new PackageResult(packageName, version.to_string(), null));
                    results.Messages.Add(new ResultMessage(ResultType.Error, logMessage));
                    continue;
                }

                if (installedPackage != null && (installedPackage.Version == availablePackage.Version))
                {
                    packageManager.UninstallPackage(installedPackage, forceRemove: config.Force, removeDependencies: config.ForceDependencies);
                }

                using (packageManager.SourceRepository.StartOperation(
                           RepositoryOperationNames.Install,
                           packageName,
                           version == null ? null : version.ToString()))
                {
                    packageManager.InstallPackage(availablePackage, config.IgnoreDependencies, config.Prerelease);
                    //packageManager.InstallPackage(packageName, version, configuration.IgnoreDependencies, configuration.Prerelease);
                }
            }

            return(packageInstalls);
        }
Пример #11
0
        public PackageManagerEx GetPackageManager(
            ChocolateyConfiguration configuration,
            Action <PackageOperationEventArgs> installSuccessAction   = null,
            Action <PackageOperationEventArgs> uninstallSuccessAction = null,
            bool addUninstallHandler = false
            )
        {
            IFileSystem          nugetPackagesFileSystem = NugetCommon.GetNuGetFileSystem(configuration, _nugetLogger);
            IPackagePathResolver pathResolver            = NugetCommon.GetPathResolver(configuration, nugetPackagesFileSystem);
            var packageManager = new PackageManagerEx(_registryService, NugetCommon.GetRemoteRepository(configuration, _nugetLogger, _packageDownloader), pathResolver, nugetPackagesFileSystem,
                                                      NugetCommon.GetLocalRepository(pathResolver, nugetPackagesFileSystem, _nugetLogger))
            {
                DependencyVersion = DependencyVersion.Highest,
                Logger            = _nugetLogger,
            };

            // GH-1548
            //note: is this a good time to capture a backup (for dependencies) / maybe grab remembered arguments here instead / and somehow get out of the endless loop!
            //NOTE DO NOT EVER use this method - packageManager.PackageInstalling += (s, e) => { };

            packageManager.PackageInstalled += (s, e) =>
            {
                var pkg = e.Package;
                "chocolatey".Log().Info(ChocolateyLoggers.Important, "{0}{1} v{2}{3}{4}{5}".format_with(
                                            System.Environment.NewLine,
                                            pkg.Id,
                                            pkg.Version.to_string(),
                                            configuration.Force ? " (forced)" : string.Empty,
                                            pkg.IsApproved ? " [Approved]" : string.Empty,
                                            pkg.PackageTestResultStatus == "Failing" && pkg.IsDownloadCacheAvailable ? " - Likely broken for FOSS users (due to download location changes)" : pkg.PackageTestResultStatus == "Failing" ? " - Possibly broken" : string.Empty
                                            ));

                if (installSuccessAction != null)
                {
                    installSuccessAction.Invoke(e);
                }
            };

            if (addUninstallHandler)
            {
                // NOTE DO NOT EVER use this method, or endless loop - packageManager.PackageUninstalling += (s, e) =>

                packageManager.PackageUninstalled += (s, e) =>
                {
                    IPackage pkg = packageManager.LocalRepository.FindPackage(e.Package.Id, e.Package.Version);
                    if (pkg != null)
                    {
                        // install not actually removed, let's clean it up. This is a bug with nuget, where it reports it removed some package and did NOTHING
                        // this is what happens when you are switching from AllowMultiple to just one and back
                        var chocoPathResolver = packageManager.PathResolver as ChocolateyPackagePathResolver;
                        if (chocoPathResolver != null)
                        {
                            chocoPathResolver.UseSideBySidePaths = !chocoPathResolver.UseSideBySidePaths;

                            // an unfound package folder can cause an endless loop.
                            // look for it and ignore it if doesn't line up with versioning
                            if (nugetPackagesFileSystem.DirectoryExists(chocoPathResolver.GetInstallPath(pkg)))
                            {
                                //todo: This causes an issue with upgrades.
                                // this causes this to be called again, which should then call the uninstallSuccessAction below
                                packageManager.UninstallPackage(pkg, forceRemove: configuration.Force, removeDependencies: false);
                            }

                            chocoPathResolver.UseSideBySidePaths = configuration.AllowMultipleVersions;
                        }
                    }
                    else
                    {
                        if (uninstallSuccessAction != null)
                        {
                            uninstallSuccessAction.Invoke(e);
                        }
                    }
                };
            }

            return(packageManager);
        }
Пример #12
0
 public override void Because()
 {
     because = () => packageRepository = NugetCommon.GetRemoteRepository(configuration, nugetLogger.Object, packageDownloader.Object);
 }