Ejemplo n.º 1
0
 private void PrintSuccessMessage(IToolPackage oldPackage, IToolPackage newInstalledPackage)
 {
     if (oldPackage == null)
     {
         _reporter.WriteLine(
             string.Format(
                 Install.LocalizableStrings.InstallationSucceeded,
                 string.Join(", ", newInstalledPackage.Commands.Select(c => c.Name)),
                 newInstalledPackage.Id,
                 newInstalledPackage.Version.ToNormalizedString()).Green());
     }
     else if (oldPackage.Version != newInstalledPackage.Version)
     {
         _reporter.WriteLine(
             string.Format(
                 LocalizableStrings.UpdateSucceeded,
                 newInstalledPackage.Id,
                 oldPackage.Version.ToNormalizedString(),
                 newInstalledPackage.Version.ToNormalizedString()).Green());
     }
     else
     {
         _reporter.WriteLine(
             string.Format(
                 LocalizableStrings.UpdateSucceededVersionNoChange,
                 newInstalledPackage.Id, newInstalledPackage.Version).Green());
     }
 }
Ejemplo n.º 2
0
        public int Install(FilePath manifestFile)
        {
            IToolPackage toolDownloadedPackage =
                _toolLocalPackageInstaller.Install(manifestFile);

            _toolManifestEditor.Add(
                manifestFile,
                toolDownloadedPackage.Id,
                toolDownloadedPackage.Version,
                toolDownloadedPackage.Commands.Select(c => c.Name).ToArray());

            _localToolsResolverCache.SaveToolPackage(
                toolDownloadedPackage,
                _toolLocalPackageInstaller.TargetFrameworkToInstall);

            _reporter.WriteLine(
                string.Format(
                    LocalizableStrings.LocalToolInstallationSucceeded,
                    string.Join(", ", toolDownloadedPackage.Commands.Select(c => c.Name)),
                    toolDownloadedPackage.Id,
                    toolDownloadedPackage.Version.ToNormalizedString(),
                    manifestFile.Value).Green());

            return(0);
        }
Ejemplo n.º 3
0
        public void GivenNugetConfigInstallSucceedsInTransaction(bool testMockBehaviorIsInSync)
        {
            var nugetConfigPath = WriteNugetConfigFileToPointToTheFeed();

            var(store, installer, reporter, fileSystem) = Setup(
                useMock: testMockBehaviorIsInSync,
                feeds: GetMockFeedsForConfigFile(nugetConfigPath));

            IToolPackage package = null;

            using (var transactionScope = new TransactionScope(
                       TransactionScopeOption.Required,
                       TimeSpan.Zero))
            {
                package = installer.InstallPackage(
                    packageId: TestPackageId,
                    versionRange: VersionRange.Parse(TestPackageVersion),
                    targetFramework: _testTargetframework,
                    nugetConfig: nugetConfigPath);

                transactionScope.Complete();
            }

            AssertPackageInstall(reporter, fileSystem, package, store);

            package.Uninstall();
        }
Ejemplo n.º 4
0
        public void GivenNugetConfigVersionRangeInstallSucceeds(bool testMockBehaviorIsInSync)
        {
            string testDirectory = _testAssetsManager.CreateTestDirectory(identifier: testMockBehaviorIsInSync.ToString()).Path;

            var nugetConfigPath = WriteNugetConfigFileToPointToTheFeed(testDirectory);

            var(store, installer, reporter, fileSystem) = Setup(
                useMock: testMockBehaviorIsInSync,
                testDirectory: testDirectory,
                feeds: GetMockFeedsForConfigFile(nugetConfigPath));

            var nugetCacheLocation =
                new DirectoryPath(testDirectory).WithSubDirectories(Path.GetRandomFileName());

            IToolPackage toolPackage = installer.InstallPackageToExternalManagedLocation(
                packageId: TestPackageId,
                versionRange: VersionRange.Parse("1.0.0-*"),
                packageLocation: new PackageLocation(nugetConfig: nugetConfigPath),
                targetFramework: _testTargetframework);

            var expectedPackagesFolder = testMockBehaviorIsInSync ?
                                         NuGetGlobalPackagesFolder.GetLocation() :
                                         TestContext.Current.NuGetCachePath;

            var commands = toolPackage.Commands;

            commands[0].Executable.Value.Should().StartWith(expectedPackagesFolder);
            toolPackage.Version.Should().Be(NuGetVersion.Parse(TestPackageVersion));
        }
        public void GivenNugetConfigInstallSucceeds(bool testMockBehaviorIsInSync)
        {
            var nugetConfigPath = WriteNugetConfigFileToPointToTheFeed();

            var(store, installer, reporter, fileSystem) = Setup(
                useMock: testMockBehaviorIsInSync,
                feeds: GetMockFeedsForConfigFile(nugetConfigPath));

            var nugetCacheLocation =
                new DirectoryPath(Path.GetTempPath()).WithSubDirectories(Path.GetRandomFileName());

            IToolPackage toolPackage = installer.InstallPackageToExternalManagedLocation(
                packageId: TestPackageId,
                versionRange: VersionRange.Parse(TestPackageVersion),
                packageLocation: new PackageLocation(nugetConfig: nugetConfigPath),
                targetFramework: _testTargetframework);

            var commands = toolPackage.Commands;

            commands[0].Executable.Value.Should().StartWith(NuGetGlobalPackagesFolder.GetLocation());

            fileSystem.File
            .Exists(commands[0].Executable.Value)
            .Should().BeTrue($"{commands[0].Executable.Value} should exist");
        }
        public void GivenNugetConfigInstallSucceedsInTransaction(bool testMockBehaviorIsInSync)
        {
            var nugetConfigPath = GenerateRandomNugetConfigFilePath();

            var(store, storeQuery, installer, uninstaller, reporter, fileSystem) = Setup(
                useMock: testMockBehaviorIsInSync,
                writeLocalFeedToNugetConfig: nugetConfigPath);

            IToolPackage package = null;

            using (var transactionScope = new TransactionScope(
                       TransactionScopeOption.Required,
                       TimeSpan.Zero))
            {
                package = installer.InstallPackage(new PackageLocation(nugetConfig: nugetConfigPath),
                                                   packageId: TestPackageId,
                                                   versionRange: VersionRange.Parse(TestPackageVersion),
                                                   targetFramework: _testTargetframework);

                transactionScope.Complete();
            }

            AssertPackageInstall(reporter, fileSystem, package, store, storeQuery);

            uninstaller.Uninstall(package.PackageDirectory);
        }
Ejemplo n.º 7
0
        public override int Execute()
        {
            ValidateArguments();

            DirectoryPath?toolPath = null;

            if (_toolPath != null)
            {
                toolPath = new DirectoryPath(_toolPath);
            }

            (IToolPackageStore toolPackageStore,
             IToolPackageStoreQuery toolPackageStoreQuery,
             IToolPackageInstaller toolPackageInstaller,
             IToolPackageUninstaller toolPackageUninstaller) = _createToolPackageStoreInstallerUninstaller(toolPath, _forwardRestoreArguments);

            IShellShimRepository shellShimRepository = _createShellShimRepository(toolPath);

            IToolPackage oldPackageNullable = GetOldPackage(toolPackageStoreQuery);

            using (var scope = new TransactionScope(
                       TransactionScopeOption.Required,
                       TimeSpan.Zero))
            {
                if (oldPackageNullable != null)
                {
                    RunWithHandlingUninstallError(() =>
                    {
                        foreach (RestoredCommand command in oldPackageNullable.Commands)
                        {
                            shellShimRepository.RemoveShim(command.Name);
                        }

                        toolPackageUninstaller.Uninstall(oldPackageNullable.PackageDirectory);
                    });
                }

                RunWithHandlingInstallError(() =>
                {
                    IToolPackage newInstalledPackage = toolPackageInstaller.InstallPackage(
                        new PackageLocation(nugetConfig: GetConfigFile(), additionalFeeds: _additionalFeeds),
                        packageId: _packageId,
                        targetFramework: _framework,
                        verbosity: _verbosity);

                    foreach (RestoredCommand command in newInstalledPackage.Commands)
                    {
                        shellShimRepository.CreateShim(command.Executable, command.Name);
                    }

                    PrintSuccessMessage(oldPackageNullable, newInstalledPackage);
                });

                scope.Complete();
            }

            return(0);
        }
        // repro https://github.com/dotnet/cli/issues/10101
        public void GivenAPackageWithCasingAndenUSPOSIXInstallSucceeds(bool testMockBehaviorIsInSync)
        {
            var nugetConfigPath = GenerateRandomNugetConfigFilePath();
            var emptySource     = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(emptySource);

            var packageId      = new PackageId("Global.Tool.Console.Demo.With.Casing");
            var packageVersion = "2.0.4";
            var feed           = new MockFeed
            {
                Type     = MockFeedType.ImplicitAdditionalFeed,
                Uri      = nugetConfigPath.Value,
                Packages = new List <MockFeedPackage>
                {
                    new MockFeedPackage
                    {
                        PackageId       = packageId.ToString(),
                        Version         = packageVersion,
                        ToolCommandName = "DemoWithCasing",
                    }
                }
            };

            var(store, storeQuery, installer, uninstaller, reporter, fileSystem) = Setup(
                useMock: testMockBehaviorIsInSync,
                feeds: new List <MockFeed> {
                feed
            },
                writeLocalFeedToNugetConfig: nugetConfigPath);

            CultureInfo currentCultureBefore = CultureInfo.CurrentCulture;

            try
            {
                CultureInfo.CurrentCulture = new CultureInfo("en-US-POSIX");
                IToolPackage package = null;
                Action       action  = () => package = installer.InstallPackage(
                    new PackageLocation(
                        nugetConfig: nugetConfigPath,
                        additionalFeeds: new[] { emptySource }),
                    packageId: packageId,
                    versionRange: VersionRange.Parse(packageVersion),
                    targetFramework: _testTargetframework);

                action.ShouldNotThrow <ToolConfigurationException>();

                fileSystem.File.Exists(package.Commands[0].Executable.Value).Should().BeTrue($"{package.Commands[0].Executable.Value} should exist");

                uninstaller.Uninstall(package.PackageDirectory);
            }
            finally
            {
                CultureInfo.CurrentCulture = currentCultureBefore;
            }
        }
Ejemplo n.º 9
0
        private ToolRestoreResult InstallPackages(
            ToolManifestPackage package,
            FilePath?configFile)
        {
            string targetFramework = BundledTargetFramework.GetTargetFrameworkMoniker();

            if (PackageHasBeenRestored(package, targetFramework))
            {
                return(ToolRestoreResult.Success(
                           saveToCache: Array.Empty <(RestoredCommandIdentifier, RestoredCommand)>(),
                           message: string.Format(
                               LocalizableStrings.RestoreSuccessful, package.PackageId,
                               package.Version.ToNormalizedString(), string.Join(", ", package.CommandNames))));
            }

            try
            {
                IToolPackage toolPackage =
                    _toolPackageInstaller.InstallPackageToExternalManagedLocation(
                        new PackageLocation(
                            nugetConfig: configFile,
                            additionalFeeds: _sources,
                            rootConfigDirectory: package.FirstEffectDirectory),
                        package.PackageId, ToVersionRangeWithOnlyOneVersion(package.Version), targetFramework,
                        verbosity: _verbosity);

                if (!ManifestCommandMatchesActualInPackage(package.CommandNames, toolPackage.Commands))
                {
                    return(ToolRestoreResult.Failure(
                               string.Format(LocalizableStrings.CommandsMismatch,
                                             JoinBySpaceWithQuote(package.CommandNames.Select(c => c.Value.ToString())),
                                             package.PackageId,
                                             JoinBySpaceWithQuote(toolPackage.Commands.Select(c => c.Name.ToString())))));
                }

                return(ToolRestoreResult.Success(
                           saveToCache: toolPackage.Commands.Select(command => (
                                                                        new RestoredCommandIdentifier(
                                                                            toolPackage.Id,
                                                                            toolPackage.Version,
                                                                            NuGetFramework.Parse(targetFramework),
                                                                            Constants.AnyRid,
                                                                            command.Name),
                                                                        command)).ToArray(),
                           message: string.Format(
                               LocalizableStrings.RestoreSuccessful,
                               package.PackageId,
                               package.Version.ToNormalizedString(),
                               string.Join(" ", package.CommandNames))));
            }
            catch (ToolPackageException e)
            {
                return(ToolRestoreResult.Failure(package.PackageId, e));
            }
        }
Ejemplo n.º 10
0
 private static bool PackageHasCommands(IToolPackage package)
 {
     try
     {
         return(package.Commands.Count >= 0);
     }
     catch (Exception ex) when(ex is ToolConfigurationException)
     {
         return(false);
     }
 }
Ejemplo n.º 11
0
 private static void EnsureVersionIsHigher(IToolPackage oldPackageNullable, IToolPackage newInstalledPackage)
 {
     if (oldPackageNullable != null && (newInstalledPackage.Version < oldPackageNullable.Version))
     {
         throw new GracefulException(
                   new[]
         {
             string.Format(LocalizableStrings.UpdateToLowerVersion,
                           newInstalledPackage.Version.ToNormalizedString(),
                           oldPackageNullable.Version.ToNormalizedString())
         },
                   isUserError: false);
     }
 }
        public IToolPackage Install(FilePath manifestFile)
        {
            if (!string.IsNullOrEmpty(_configFilePath) && !File.Exists(_configFilePath))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.NuGetConfigurationFileDoesNotExist,
                              Path.GetFullPath(_configFilePath)));
            }

            VersionRange versionRange = null;

            if (!string.IsNullOrEmpty(_packageVersion) && !VersionRange.TryParse(_packageVersion, out versionRange))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.InvalidNuGetVersionRange,
                              _packageVersion));
            }

            FilePath?configFile = null;

            if (!string.IsNullOrEmpty(_configFilePath))
            {
                configFile = new FilePath(_configFilePath);
            }

            try
            {
                IToolPackage toolDownloadedPackage =
                    _toolPackageInstaller.InstallPackageToExternalManagedLocation(
                        new PackageLocation(
                            nugetConfig: configFile,
                            additionalFeeds: _sources,
                            rootConfigDirectory: manifestFile.GetDirectoryPath()),
                        _packageId,
                        versionRange,
                        TargetFrameworkToInstall,
                        verbosity: _verbosity);

                return(toolDownloadedPackage);
            }
            catch (Exception ex) when(InstallToolCommandLowLevelErrorConverter.ShouldConvertToUserFacingError(ex))
            {
                throw new GracefulException(
                          messages: InstallToolCommandLowLevelErrorConverter.GetUserFacingMessages(ex, _packageId),
                          verboseMessages: new[] { ex.ToString() },
                          isUserError: false);
            }
        }
Ejemplo n.º 13
0
        private static void AssertPackageInstall(
            BufferedReporter reporter,
            IFileSystem fileSystem,
            IToolPackage package,
            IToolPackageStore store)
        {
            reporter.Lines.Should().BeEmpty();

            package.PackageId.Should().Be(TestPackageId);
            package.PackageVersion.Should().Be(TestPackageVersion);
            package.PackageDirectory.Value.Should().Contain(store.Root.Value);

            store.GetInstalledPackages(TestPackageId).Select(p => p.PackageVersion).Should().Equal(TestPackageVersion);

            package.Commands.Count.Should().Be(1);
            fileSystem.File.Exists(package.Commands[0].Executable.Value).Should().BeTrue($"{package.Commands[0].Executable.Value} should exist");
            package.Commands[0].Executable.Value.Should().Contain(store.Root.Value);
        }
Ejemplo n.º 14
0
 private bool PackageHasCommands(IToolPackage package)
 {
     try
     {
         // Attempt to read the commands collection
         // If it fails, print a warning and treat as no commands
         return(package.Commands.Count >= 0);
     }
     catch (Exception ex) when(ex is ToolConfigurationException)
     {
         _errorReporter.WriteLine(
             string.Format(
                 LocalizableStrings.InvalidPackageWarning,
                 package.Id,
                 ex.Message).Yellow());
         return(false);
     }
 }
Ejemplo n.º 15
0
 private void PrintSuccessMessage(IToolPackage oldPackage, IToolPackage newInstalledPackage)
 {
     if (oldPackage.Version != newInstalledPackage.Version)
     {
         _reporter.WriteLine(
             string.Format(
                 LocalizableStrings.UpdateSucceeded,
                 newInstalledPackage.Id,
                 oldPackage.Version.ToNormalizedString(),
                 newInstalledPackage.Version.ToNormalizedString()).Green());
     }
     else
     {
         _reporter.WriteLine(
             string.Format(
                 LocalizableStrings.UpdateSucceededVersionNoChange,
                 newInstalledPackage.Id, newInstalledPackage.Version).Green());
     }
 }
Ejemplo n.º 16
0
        public void GivenNugetConfigInstallSucceeds(bool testMockBehaviorIsInSync)
        {
            string testDirectory = _testAssetsManager.CreateTestDirectory(identifier: testMockBehaviorIsInSync.ToString()).Path;

            var nugetConfigPath = WriteNugetConfigFileToPointToTheFeed(testDirectory);

            var(store, installer, reporter, fileSystem) = Setup(
                useMock: testMockBehaviorIsInSync,
                testDirectory: testDirectory,
                feeds: GetMockFeedsForConfigFile(nugetConfigPath));

            try

            {
                var nugetCacheLocation =
                    new DirectoryPath(testDirectory).WithSubDirectories(Path.GetRandomFileName());

                IToolPackage toolPackage = installer.InstallPackageToExternalManagedLocation(
                    packageId: TestPackageId,
                    versionRange: VersionRange.Parse(TestPackageVersion),
                    packageLocation: new PackageLocation(nugetConfig: nugetConfigPath),
                    targetFramework: _testTargetframework);

                var commands = toolPackage.Commands;
                commands[0].Executable.Value.Should().StartWith(NuGetGlobalPackagesFolder.GetLocation());

                fileSystem.File
                .Exists(commands[0].Executable.Value)
                .Should().BeTrue($"{commands[0].Executable.Value} should exist");
            }
            finally
            {
                foreach (var line in reporter.Lines)
                {
                    Log.WriteLine(line);
                }
            }
        }
Ejemplo n.º 17
0
        private static void AssertPackageInstall(
            BufferedReporter reporter,
            IFileSystem fileSystem,
            IToolPackage package,
            IToolPackageStore store,
            IToolPackageStoreQuery storeQuery)
        {
            reporter.Lines.Should().BeEmpty();

            package.Id.Should().Be(TestPackageId);
            package.Version.ToNormalizedString().Should().Be(TestPackageVersion);
            package.PackageDirectory.Value.Should().Contain(store.Root.Value);
            package.Frameworks.Should().BeEquivalentTo(TestFrameworks);

            storeQuery.EnumeratePackageVersions(TestPackageId)
            .Select(p => p.Version.ToNormalizedString())
            .Should()
            .Equal(TestPackageVersion);

            package.Commands.Count.Should().Be(1);
            fileSystem.File.Exists(package.Commands[0].Executable.Value).Should()
            .BeTrue($"{package.Commands[0].Executable.Value} should exist");
            package.Commands[0].Executable.Value.Should().Contain(store.Root.Value);
        }
Ejemplo n.º 18
0
        public static void SaveToolPackage(
            this ILocalToolsResolverCache localToolsResolverCache,
            IToolPackage toolDownloadedPackage,
            string targetFrameworkToInstall)
        {
            if (localToolsResolverCache == null)
            {
                throw new ArgumentNullException(nameof(localToolsResolverCache));
            }

            if (toolDownloadedPackage == null)
            {
                throw new ArgumentNullException(nameof(toolDownloadedPackage));
            }

            if (string.IsNullOrWhiteSpace(targetFrameworkToInstall))
            {
                throw new ArgumentException("targetFrameworkToInstall cannot be null or whitespace",
                                            nameof(targetFrameworkToInstall));
            }

            foreach (var restoredCommand in toolDownloadedPackage.Commands)
            {
                localToolsResolverCache.Save(
                    new Dictionary <RestoredCommandIdentifier, RestoredCommand>
                {
                    [new RestoredCommandIdentifier(
                         toolDownloadedPackage.Id,
                         toolDownloadedPackage.Version,
                         NuGetFramework.Parse(targetFrameworkToInstall),
                         Constants.AnyRid,
                         restoredCommand.Name)] =
                        restoredCommand
                });
            }
        }
Ejemplo n.º 19
0
        public override int Execute()
        {
            FilePath?customManifestFileLocation = GetCustomManifestFileLocation();

            FilePath?configFile = null;

            if (_configFilePath != null)
            {
                configFile = new FilePath(_configFilePath);
            }

            IReadOnlyCollection <ToolManifestPackage> packagesFromManifest;

            try
            {
                packagesFromManifest = _toolManifestFinder.Find(customManifestFileLocation);
            }
            catch (ToolManifestCannotFindException e)
            {
                _reporter.WriteLine(e.Message.Yellow());
                return(0);
            }

            Dictionary <RestoredCommandIdentifier, RestoredCommand> dictionary =
                new Dictionary <RestoredCommandIdentifier, RestoredCommand>();

            Dictionary <PackageId, ToolPackageException> toolPackageExceptions =
                new Dictionary <PackageId, ToolPackageException>();
            List <string> errorMessages = new List <string>();

            foreach (var package in packagesFromManifest)
            {
                string targetFramework = BundledTargetFramework.GetTargetFrameworkMoniker();

                try
                {
                    IToolPackage toolPackage =
                        _toolPackageInstaller.InstallPackageToExternalManagedLocation(
                            new PackageLocation(
                                nugetConfig: configFile,
                                additionalFeeds: _sources),
                            package.PackageId, ToVersionRangeWithOnlyOneVersion(package.Version), targetFramework,
                            verbosity: _verbosity);

                    if (!ManifestCommandMatchesActualInPackage(package.CommandNames, toolPackage.Commands))
                    {
                        errorMessages.Add(
                            string.Format(LocalizableStrings.CommandsMismatch,
                                          package.PackageId,
                                          JoinBySpaceWithQuote(toolPackage.Commands.Select(c => c.Name.ToString())),
                                          JoinBySpaceWithQuote(package.CommandNames.Select(c => c.Value.ToString()))));
                    }

                    foreach (RestoredCommand command in toolPackage.Commands)
                    {
                        dictionary.Add(
                            new RestoredCommandIdentifier(
                                toolPackage.Id,
                                toolPackage.Version,
                                NuGetFramework.Parse(targetFramework),
                                "any",
                                command.Name),
                            command);
                    }
                }
                catch (ToolPackageException e)
                {
                    toolPackageExceptions.Add(package.PackageId, e);
                }
            }

            EnsureNoCommandNameCollision(dictionary);

            _localToolsResolverCache.Save(dictionary, _nugetGlobalPackagesFolder);

            if (toolPackageExceptions.Any() || errorMessages.Any())
            {
                var partialOrTotalFailed = dictionary.Count() > 0
                    ? LocalizableStrings.RestorePartiallySuccessful
                    : LocalizableStrings.RestoreFailed;

                _errorReporter.WriteLine(partialOrTotalFailed +
                                         Environment.NewLine +
                                         string.Join(
                                             Environment.NewLine,
                                             CreateErrorMessage(toolPackageExceptions).Concat(errorMessages)));

                return(1);
            }

            return(0);
        }
Ejemplo n.º 20
0
        public override int Execute()
        {
            if (!string.IsNullOrEmpty(_configFilePath) && !File.Exists(_configFilePath))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.NuGetConfigurationFileDoesNotExist,
                              Path.GetFullPath(_configFilePath)));
            }

            VersionRange versionRange = _parseResult.GetVersionRange();

            DirectoryPath?toolPath = null;

            if (!string.IsNullOrEmpty(_toolPath))
            {
                toolPath = new DirectoryPath(_toolPath);
            }

            (IToolPackageStore toolPackageStore, IToolPackageStoreQuery toolPackageStoreQuery, IToolPackageInstaller toolPackageInstaller) =
                _createToolPackageStoresAndInstaller(toolPath, _forwardRestoreArguments);

            // Prevent installation if any version of the package is installed
            if (toolPackageStoreQuery.EnumeratePackageVersions(_packageId).FirstOrDefault() != null)
            {
                _errorReporter.WriteLine(string.Format(LocalizableStrings.ToolAlreadyInstalled, _packageId).Red());
                return(1);
            }

            FilePath?configFile = null;

            if (!string.IsNullOrEmpty(_configFilePath))
            {
                configFile = new FilePath(_configFilePath);
            }

            try
            {
                IToolPackage package = null;
                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           TimeSpan.Zero))
                {
                    package = toolPackageInstaller.InstallPackage(
                        new PackageLocation(nugetConfig: configFile, additionalFeeds: _source),
                        packageId: _packageId,
                        versionRange: versionRange,
                        targetFramework: _framework, verbosity: _verbosity);

                    NuGetFramework framework;
                    if (string.IsNullOrEmpty(_framework) && package.Frameworks.Count() > 0)
                    {
                        framework = package.Frameworks
                                    .Where(f => f.Version < (new NuGetVersion(Product.Version)).Version)
                                    .MaxBy(f => f.Version);
                    }
                    else
                    {
                        framework = string.IsNullOrEmpty(_framework)  ?
                                    null :
                                    NuGetFramework.Parse(_framework);
                    }

                    string appHostSourceDirectory            = _shellShimTemplateFinder.ResolveAppHostSourceDirectoryAsync(_architectureOption, framework, RuntimeInformation.ProcessArchitecture).Result;
                    IShellShimRepository shellShimRepository = _createShellShimRepository(appHostSourceDirectory, toolPath);

                    foreach (var command in package.Commands)
                    {
                        shellShimRepository.CreateShim(command.Executable, command.Name, package.PackagedShims);
                    }

                    scope.Complete();
                }

                foreach (string w in package.Warnings)
                {
                    _reporter.WriteLine(w.Yellow());
                }

                if (_global)
                {
                    _environmentPathInstruction.PrintAddPathInstructionIfPathDoesNotExist();
                }

                _reporter.WriteLine(
                    string.Format(
                        LocalizableStrings.InstallationSucceeded,
                        string.Join(", ", package.Commands.Select(c => c.Name)),
                        package.Id,
                        package.Version.ToNormalizedString()).Green());
                return(0);
            }
            catch (Exception ex) when(InstallToolCommandLowLevelErrorConverter.ShouldConvertToUserFacingError(ex))
            {
                throw new GracefulException(
                          messages: InstallToolCommandLowLevelErrorConverter.GetUserFacingMessages(ex, _packageId),
                          verboseMessages: new[] { ex.ToString() },
                          isUserError: false);
            }
        }
Ejemplo n.º 21
0
        public override int Execute()
        {
            FilePath?customManifestFileLocation = GetCustomManifestFileLocation();

            FilePath?configFile = null;

            if (_configFilePath != null)
            {
                configFile = new FilePath(_configFilePath);
            }

            IReadOnlyCollection <ToolManifestPackage> packagesFromManifest;

            try
            {
                packagesFromManifest = _toolManifestFinder.Find(customManifestFileLocation);
            }
            catch (ToolManifestCannotBeFoundException e)
            {
                _reporter.WriteLine(e.Message.Yellow());
                return(0);
            }

            Dictionary <RestoredCommandIdentifier, RestoredCommand> dictionary =
                new Dictionary <RestoredCommandIdentifier, RestoredCommand>();

            Dictionary <PackageId, ToolPackageException> toolPackageExceptions =
                new Dictionary <PackageId, ToolPackageException>();

            List <string> errorMessages   = new List <string>();
            List <string> successMessages = new List <string>();

            foreach (var package in packagesFromManifest)
            {
                string targetFramework = BundledTargetFramework.GetTargetFrameworkMoniker();

                if (PackageHasBeenRestored(package, targetFramework))
                {
                    successMessages.Add(string.Format(
                                            LocalizableStrings.RestoreSuccessful, package.PackageId,
                                            package.Version.ToNormalizedString(), string.Join(", ", package.CommandNames)));
                    continue;
                }

                try
                {
                    IToolPackage toolPackage =
                        _toolPackageInstaller.InstallPackageToExternalManagedLocation(
                            new PackageLocation(
                                nugetConfig: configFile,
                                additionalFeeds: _sources,
                                rootConfigDirectory: package.FirstEffectDirectory),
                            package.PackageId, ToVersionRangeWithOnlyOneVersion(package.Version), targetFramework,
                            verbosity: _verbosity);

                    if (!ManifestCommandMatchesActualInPackage(package.CommandNames, toolPackage.Commands))
                    {
                        errorMessages.Add(
                            string.Format(LocalizableStrings.CommandsMismatch,
                                          JoinBySpaceWithQuote(package.CommandNames.Select(c => c.Value.ToString())),
                                          package.PackageId,
                                          JoinBySpaceWithQuote(toolPackage.Commands.Select(c => c.Name.ToString()))));
                    }

                    foreach (RestoredCommand command in toolPackage.Commands)
                    {
                        dictionary.Add(
                            new RestoredCommandIdentifier(
                                toolPackage.Id,
                                toolPackage.Version,
                                NuGetFramework.Parse(targetFramework),
                                Constants.AnyRid,
                                command.Name),
                            command);
                    }

                    successMessages.Add(string.Format(
                                            LocalizableStrings.RestoreSuccessful, package.PackageId,
                                            package.Version.ToNormalizedString(), string.Join(" ", package.CommandNames)));
                }
                catch (ToolPackageException e)
                {
                    toolPackageExceptions.Add(package.PackageId, e);
                }
            }

            EnsureNoCommandNameCollision(dictionary);

            _localToolsResolverCache.Save(dictionary, _nugetGlobalPackagesFolder);

            return(PrintConclusionAndReturn(dictionary.Count() > 0, toolPackageExceptions, errorMessages, successMessages));
        }
Ejemplo n.º 22
0
        public override int Execute()
        {
            var global   = _options.ValueOrDefault <bool>("global");
            var toolPath = _options.SingleArgumentOrDefault("tool-path");

            if (string.IsNullOrWhiteSpace(toolPath) && !global)
            {
                throw new GracefulException(LocalizableStrings.UninstallToolCommandNeedGlobalOrToolPath);
            }

            if (!string.IsNullOrWhiteSpace(toolPath) && global)
            {
                throw new GracefulException(LocalizableStrings.UninstallToolCommandInvalidGlobalAndToolPath);
            }

            DirectoryPath?toolDirectoryPath = null;

            if (!string.IsNullOrWhiteSpace(toolPath))
            {
                toolDirectoryPath = new DirectoryPath(toolPath);
            }

            IToolPackageStore    toolPackageStore    = _createToolPackageStoreAndInstaller(toolDirectoryPath);
            IShellShimRepository shellShimRepository = _createShellShimRepository(toolDirectoryPath);

            var          packageId = new PackageId(_options.Arguments.Single());
            IToolPackage package   = null;

            try
            {
                package = toolPackageStore.EnumeratePackageVersions(packageId).SingleOrDefault();
                if (package == null)
                {
                    throw new GracefulException(
                              messages: new[]
                    {
                        string.Format(
                            LocalizableStrings.ToolNotInstalled,
                            packageId),
                    },
                              isUserError: false);
                }
            }
            catch (InvalidOperationException)
            {
                throw new GracefulException(
                          messages: new[]
                {
                    string.Format(
                        LocalizableStrings.ToolHasMultipleVersionsInstalled,
                        packageId),
                },
                          isUserError: false);
            }

            try
            {
                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           TimeSpan.Zero))
                {
                    foreach (var command in package.Commands)
                    {
                        shellShimRepository.RemoveShim(command.Name);
                    }

                    package.Uninstall();

                    scope.Complete();
                }

                _reporter.WriteLine(
                    string.Format(
                        LocalizableStrings.UninstallSucceeded,
                        package.Id,
                        package.Version.ToNormalizedString()).Green());
                return(0);
            }
            catch (ToolPackageException ex)
            {
                throw new GracefulException(
                          messages: new[]
                {
                    ex.Message
                },
                          verboseMessages: new[] { ex.ToString() },
                          isUserError: false);
            }
            catch (Exception ex) when(ex is ToolConfigurationException || ex is ShellShimException)
            {
                throw new GracefulException(
                          messages: new[]
                {
                    string.Format(
                        LocalizableStrings.FailedToUninstallTool,
                        packageId,
                        ex.Message)
                },
                          verboseMessages: new[] { ex.ToString() },
                          isUserError: false);
            }
        }
Ejemplo n.º 23
0
        public override int Execute()
        {
            if (string.IsNullOrWhiteSpace(_toolPath) && !_global)
            {
                throw new GracefulException(LocalizableStrings.InstallToolCommandNeedGlobalOrToolPath);
            }

            if (!string.IsNullOrWhiteSpace(_toolPath) && _global)
            {
                throw new GracefulException(LocalizableStrings.InstallToolCommandInvalidGlobalAndToolPath);
            }

            if (_configFilePath != null && !File.Exists(_configFilePath))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.NuGetConfigurationFileDoesNotExist,
                              Path.GetFullPath(_configFilePath)));
            }


            VersionRange versionRange = null;

            if (!string.IsNullOrEmpty(_packageVersion) && !VersionRange.TryParse(_packageVersion, out versionRange))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.InvalidNuGetVersionRange,
                              _packageVersion));
            }

            DirectoryPath?toolPath = null;

            if (_toolPath != null)
            {
                toolPath = new DirectoryPath(_toolPath);
            }

            (IToolPackageStore toolPackageStore, IToolPackageInstaller toolPackageInstaller) =
                _createToolPackageStoreAndInstaller(toolPath);
            IShellShimRepository shellShimRepository = _createShellShimRepository(toolPath);

            // Prevent installation if any version of the package is installed
            if (toolPackageStore.EnumeratePackageVersions(_packageId).FirstOrDefault() != null)
            {
                _errorReporter.WriteLine(string.Format(LocalizableStrings.ToolAlreadyInstalled, _packageId).Red());
                return(1);
            }

            FilePath?configFile = null;

            if (_configFilePath != null)
            {
                configFile = new FilePath(_configFilePath);
            }

            try
            {
                IToolPackage package = null;
                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           TimeSpan.Zero))
                {
                    package = toolPackageInstaller.InstallPackage(
                        packageId: _packageId,
                        versionRange: versionRange,
                        targetFramework: _framework,
                        nugetConfig: configFile,
                        additionalFeeds: _source,
                        verbosity: _verbosity);

                    foreach (var command in package.Commands)
                    {
                        shellShimRepository.CreateShim(command.Executable, command.Name, package.PackagedShims);
                    }

                    scope.Complete();
                }

                foreach (string w in package.Warnings)
                {
                    _reporter.WriteLine(w.Yellow());
                }

                if (_global)
                {
                    _environmentPathInstruction.PrintAddPathInstructionIfPathDoesNotExist();
                }

                _reporter.WriteLine(
                    string.Format(
                        LocalizableStrings.InstallationSucceeded,
                        string.Join(", ", package.Commands.Select(c => c.Name)),
                        package.Id,
                        package.Version.ToNormalizedString()).Green());
                return(0);
            }
            catch (Exception ex) when(InstallToolCommandLowLevelErrorConverter.ShouldConvertToUserFacingError(ex))
            {
                throw new GracefulException(
                          messages: InstallToolCommandLowLevelErrorConverter.GetUserFacingMessages(ex, _packageId),
                          verboseMessages: new[] { ex.ToString() },
                          isUserError: false);
            }
        }
Ejemplo n.º 24
0
        public override int Execute()
        {
            ValidateArguments();

            DirectoryPath?toolPath = null;

            if (_toolPath != null)
            {
                toolPath = new DirectoryPath(_toolPath);
            }

            (IToolPackageStore toolPackageStore, IToolPackageInstaller toolPackageInstaller) =
                _createToolPackageStoreAndInstaller(toolPath);
            IShellShimRepository shellShimRepository = _createShellShimRepository(toolPath);


            IToolPackage oldPackage;

            try
            {
                oldPackage = toolPackageStore.EnumeratePackageVersions(_packageId).SingleOrDefault();
                if (oldPackage == null)
                {
                    throw new GracefulException(
                              messages: new[]
                    {
                        string.Format(
                            LocalizableStrings.ToolNotInstalled,
                            _packageId),
                    },
                              isUserError: false);
                }
            }
            catch (InvalidOperationException)
            {
                throw new GracefulException(
                          messages: new[]
                {
                    string.Format(
                        LocalizableStrings.ToolHasMultipleVersionsInstalled,
                        _packageId),
                },
                          isUserError: false);
            }

            FilePath?configFile = null;

            if (_configFilePath != null)
            {
                configFile = new FilePath(_configFilePath);
            }

            using (var scope = new TransactionScope(
                       TransactionScopeOption.Required,
                       TimeSpan.Zero))
            {
                RunWithHandlingUninstallError(() =>
                {
                    foreach (CommandSettings command in oldPackage.Commands)
                    {
                        shellShimRepository.RemoveShim(command.Name);
                    }

                    oldPackage.Uninstall();
                });

                RunWithHandlingInstallError(() =>
                {
                    IToolPackage newInstalledPackage = toolPackageInstaller.InstallPackage(
                        packageId: _packageId,
                        targetFramework: _framework,
                        nugetConfig: configFile,
                        source: _source,
                        verbosity: _verbosity);

                    foreach (CommandSettings command in newInstalledPackage.Commands)
                    {
                        shellShimRepository.CreateShim(command.Executable, command.Name);
                    }

                    PrintSuccessMessage(oldPackage, newInstalledPackage);
                });

                scope.Complete();
            }

            return(0);
        }
Ejemplo n.º 25
0
        public override int Execute()
        {
            if (!_global)
            {
                throw new GracefulException(LocalizableStrings.InstallToolCommandOnlySupportGlobal);
            }

            if (_configFilePath != null && !File.Exists(_configFilePath))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.NuGetConfigurationFileDoesNotExist,
                              Path.GetFullPath(_configFilePath)));
            }

            VersionRange versionRange = null;

            if (!string.IsNullOrEmpty(_packageVersion) && !VersionRange.TryParse(_packageVersion, out versionRange))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.InvalidNuGetVersionRange,
                              _packageVersion));
            }

            if (_toolPackageStore.EnumeratePackageVersions(_packageId).FirstOrDefault() != null)
            {
                _errorReporter.WriteLine(string.Format(LocalizableStrings.ToolAlreadyInstalled, _packageId).Red());
                return(1);
            }

            FilePath?configFile = null;

            if (_configFilePath != null)
            {
                configFile = new FilePath(_configFilePath);
            }

            try
            {
                IToolPackage package = null;
                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           TimeSpan.Zero))
                {
                    package = _toolPackageInstaller.InstallPackage(
                        packageId: _packageId,
                        versionRange: versionRange,
                        targetFramework: _framework,
                        nugetConfig: configFile,
                        source: _source,
                        verbosity: _verbosity);

                    foreach (var command in package.Commands)
                    {
                        _shellShimRepository.CreateShim(command.Executable, command.Name);
                    }

                    scope.Complete();
                }

                _environmentPathInstruction.PrintAddPathInstructionIfPathDoesNotExist();

                _reporter.WriteLine(
                    string.Format(
                        LocalizableStrings.InstallationSucceeded,
                        string.Join(", ", package.Commands.Select(c => c.Name)),
                        package.Id,
                        package.Version.ToNormalizedString()).Green());
                return(0);
            }
            catch (ToolPackageException ex)
            {
                if (Reporter.IsVerbose)
                {
                    Reporter.Verbose.WriteLine(ex.ToString().Red());
                }

                _errorReporter.WriteLine(ex.Message.Red());
                _errorReporter.WriteLine(string.Format(LocalizableStrings.ToolInstallationFailed, _packageId).Red());
                return(1);
            }
            catch (ToolConfigurationException ex)
            {
                if (Reporter.IsVerbose)
                {
                    Reporter.Verbose.WriteLine(ex.ToString().Red());
                }

                _errorReporter.WriteLine(
                    string.Format(
                        LocalizableStrings.InvalidToolConfiguration,
                        ex.Message).Red());
                _errorReporter.WriteLine(string.Format(LocalizableStrings.ToolInstallationFailedContactAuthor, _packageId).Red());
                return(1);
            }
            catch (ShellShimException ex)
            {
                if (Reporter.IsVerbose)
                {
                    Reporter.Verbose.WriteLine(ex.ToString().Red());
                }

                _errorReporter.WriteLine(
                    string.Format(
                        LocalizableStrings.FailedToCreateToolShim,
                        _packageId,
                        ex.Message).Red());
                _errorReporter.WriteLine(string.Format(LocalizableStrings.ToolInstallationFailed, _packageId).Red());
                return(1);
            }
        }
Ejemplo n.º 26
0
        public override int Execute()
        {
            ValidateArguments();

            DirectoryPath?toolPath = null;

            if (!string.IsNullOrEmpty(_toolPath))
            {
                toolPath = new DirectoryPath(_toolPath);
            }

            VersionRange versionRange = null;

            if (!string.IsNullOrEmpty(_packageVersion) && !VersionRange.TryParse(_packageVersion, out versionRange))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.InvalidNuGetVersionRange,
                              _packageVersion));
            }

            (IToolPackageStore toolPackageStore,
             IToolPackageStoreQuery toolPackageStoreQuery,
             IToolPackageInstaller toolPackageInstaller,
             IToolPackageUninstaller toolPackageUninstaller) = _createToolPackageStoreInstallerUninstaller(toolPath, _forwardRestoreArguments);

            IShellShimRepository shellShimRepository = _createShellShimRepository(toolPath);

            IToolPackage oldPackageNullable = GetOldPackage(toolPackageStoreQuery);

            using (var scope = new TransactionScope(
                       TransactionScopeOption.Required,
                       TimeSpan.Zero))
            {
                if (oldPackageNullable != null)
                {
                    RunWithHandlingUninstallError(() =>
                    {
                        foreach (RestoredCommand command in oldPackageNullable.Commands)
                        {
                            shellShimRepository.RemoveShim(command.Name);
                        }

                        toolPackageUninstaller.Uninstall(oldPackageNullable.PackageDirectory);
                    });
                }

                RunWithHandlingInstallError(() =>
                {
                    IToolPackage newInstalledPackage = toolPackageInstaller.InstallPackage(
                        new PackageLocation(nugetConfig: GetConfigFile(), additionalFeeds: _additionalFeeds),
                        packageId: _packageId,
                        targetFramework: _framework,
                        versionRange: versionRange,
                        verbosity: _verbosity);

                    EnsureVersionIsHigher(oldPackageNullable, newInstalledPackage);

                    foreach (RestoredCommand command in newInstalledPackage.Commands)
                    {
                        shellShimRepository.CreateShim(command.Executable, command.Name);
                    }

                    PrintSuccessMessage(oldPackageNullable, newInstalledPackage);
                });

                scope.Complete();
            }

            return(0);
        }
Ejemplo n.º 27
0
        public override int Execute()
        {
            if (!_options.ValueOrDefault <bool>("global"))
            {
                throw new GracefulException(LocalizableStrings.UninstallToolCommandOnlySupportsGlobal);
            }

            var          packageId = _options.Arguments.Single();
            IToolPackage package   = null;

            try
            {
                package = _toolPackageStore.GetInstalledPackages(packageId).SingleOrDefault();
                if (package == null)
                {
                    _errorReporter.WriteLine(
                        string.Format(
                            LocalizableStrings.ToolNotInstalled,
                            packageId).Red());
                    return(1);
                }
            }
            catch (InvalidOperationException)
            {
                _errorReporter.WriteLine(
                    string.Format(
                        LocalizableStrings.ToolHasMultipleVersionsInstalled,
                        packageId).Red());
                return(1);
            }

            try
            {
                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           TimeSpan.Zero))
                {
                    foreach (var command in package.Commands)
                    {
                        _shellShimRepository.RemoveShim(command.Name);
                    }

                    package.Uninstall();

                    scope.Complete();
                }

                _reporter.WriteLine(
                    string.Format(
                        LocalizableStrings.UninstallSucceeded,
                        package.PackageId,
                        package.PackageVersion).Green());
                return(0);
            }
            catch (ToolPackageException ex)
            {
                if (Reporter.IsVerbose)
                {
                    Reporter.Verbose.WriteLine(ex.ToString().Red());
                }

                _errorReporter.WriteLine(ex.Message.Red());
                return(1);
            }
            catch (Exception ex) when(ex is ToolConfigurationException || ex is ShellShimException)
            {
                if (Reporter.IsVerbose)
                {
                    Reporter.Verbose.WriteLine(ex.ToString().Red());
                }

                _errorReporter.WriteLine(
                    string.Format(
                        LocalizableStrings.FailedToUninstallTool,
                        packageId,
                        ex.Message).Red());
                return(1);
            }
        }
Ejemplo n.º 28
0
        public override int Execute()
        {
            if (_configFilePath != null && !File.Exists(_configFilePath))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.NuGetConfigurationFileDoesNotExist,
                              Path.GetFullPath(_configFilePath)));
            }

            VersionRange versionRange = null;

            if (!string.IsNullOrEmpty(_packageVersion) && !VersionRange.TryParse(_packageVersion, out versionRange))
            {
                throw new GracefulException(
                          string.Format(
                              LocalizableStrings.InvalidNuGetVersionRange,
                              _packageVersion));
            }

            FilePath?configFile = null;

            if (_configFilePath != null)
            {
                configFile = new FilePath(_configFilePath);
            }

            string targetFramework = BundledTargetFramework.GetTargetFrameworkMoniker();

            try
            {
                FilePath manifestFile = GetManifestFilePath();

                IToolPackage toolDownloadedPackage =
                    _toolPackageInstaller.InstallPackageToExternalManagedLocation(
                        new PackageLocation(
                            nugetConfig: configFile,
                            additionalFeeds: _sources,
                            rootConfigDirectory: manifestFile.GetDirectoryPath()),
                        _packageId,
                        versionRange,
                        targetFramework,
                        verbosity: _verbosity);

                _toolManifestEditor.Add(
                    manifestFile,
                    toolDownloadedPackage.Id,
                    toolDownloadedPackage.Version,
                    toolDownloadedPackage.Commands.Select(c => c.Name).ToArray());

                foreach (var restoredCommand in toolDownloadedPackage.Commands)
                {
                    _localToolsResolverCache.Save(
                        new Dictionary <RestoredCommandIdentifier, RestoredCommand>
                    {
                        [new RestoredCommandIdentifier(
                             toolDownloadedPackage.Id,
                             toolDownloadedPackage.Version,
                             NuGetFramework.Parse(targetFramework),
                             Constants.AnyRid,
                             restoredCommand.Name)] =
                            restoredCommand
                    });
                }

                _reporter.WriteLine(
                    string.Format(
                        LocalizableStrings.LocalToolInstallationSucceeded,
                        string.Join(", ", toolDownloadedPackage.Commands.Select(c => c.Name)),
                        toolDownloadedPackage.Id,
                        toolDownloadedPackage.Version.ToNormalizedString(),
                        manifestFile.Value).Green());

                return(0);
            }
            catch (Exception ex) when(InstallToolCommandLowLevelErrorConverter.ShouldConvertToUserFacingError(ex))
            {
                throw new GracefulException(
                          messages: InstallToolCommandLowLevelErrorConverter.GetUserFacingMessages(ex, _packageId),
                          verboseMessages: new[] { ex.ToString() },
                          isUserError: false);
            }
        }
        public override int Execute()
        {
            var global   = _parseResult.ValueForOption <bool>(ToolAppliedOption.GlobalOptionAliases.First());
            var toolPath = _parseResult.ValueForOption <string>(ToolAppliedOption.ToolPathOptionAlias);

            DirectoryPath?toolDirectoryPath = null;

            if (!string.IsNullOrWhiteSpace(toolPath))
            {
                if (!Directory.Exists(toolPath))
                {
                    throw new GracefulException(
                              string.Format(
                                  LocalizableStrings.InvalidToolPathOption,
                                  toolPath));
                }

                toolDirectoryPath = new DirectoryPath(toolPath);
            }

            (IToolPackageStore toolPackageStore, IToolPackageStoreQuery toolPackageStoreQuery, IToolPackageUninstaller toolPackageUninstaller)
                = _createToolPackageStoresAndUninstaller(toolDirectoryPath);
            IShellShimRepository shellShimRepository = _createShellShimRepository(toolDirectoryPath);

            var          packageId = new PackageId(_parseResult.ValueForArgument <string>(ToolInstallCommandParser.PackageIdArgument));
            IToolPackage package   = null;

            try
            {
                package = toolPackageStoreQuery.EnumeratePackageVersions(packageId).SingleOrDefault();
                if (package == null)
                {
                    throw new GracefulException(
                              messages: new[]
                    {
                        string.Format(
                            LocalizableStrings.ToolNotInstalled,
                            packageId),
                    },
                              isUserError: false);
                }
            }
            catch (InvalidOperationException)
            {
                throw new GracefulException(
                          messages: new[]
                {
                    string.Format(
                        LocalizableStrings.ToolHasMultipleVersionsInstalled,
                        packageId),
                },
                          isUserError: false);
            }

            try
            {
                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           TimeSpan.Zero))
                {
                    foreach (var command in package.Commands)
                    {
                        shellShimRepository.RemoveShim(command.Name);
                    }

                    toolPackageUninstaller.Uninstall(package.PackageDirectory);

                    scope.Complete();
                }

                _reporter.WriteLine(
                    string.Format(
                        LocalizableStrings.UninstallSucceeded,
                        package.Id,
                        package.Version.ToNormalizedString()).Green());
                return(0);
            }
            catch (Exception ex) when(ToolUninstallCommandLowLevelErrorConverter.ShouldConvertToUserFacingError(ex))
            {
                throw new GracefulException(
                          messages: ToolUninstallCommandLowLevelErrorConverter.GetUserFacingMessages(ex, packageId),
                          verboseMessages: new[] { ex.ToString() },
                          isUserError: false);
            }
        }