public async Task <IReadOnlyList <UninstallResult> > UninstallAsync(IEnumerable <IManagedTemplatePackage> packages, CancellationToken cancellationToken) { _ = packages ?? throw new ArgumentNullException(nameof(packages)); if (!packages.Any()) { return(new List <UninstallResult>()); } using var disposable = await _globalSettings.LockAsync(cancellationToken).ConfigureAwait(false); var packagesInSettings = new List <TemplatePackageData>(await _globalSettings.GetInstalledTemplatePackagesAsync(cancellationToken).ConfigureAwait(false)); var results = await Task.WhenAll(packages.Select(async package => { UninstallResult result = await package.Installer.UninstallAsync(package, this, cancellationToken).ConfigureAwait(false); if (result.Success) { lock (packagesInSettings) { packagesInSettings.RemoveAll(p => p.MountPointUri == package.MountPointUri); } } return(result); })).ConfigureAwait(false); await _globalSettings.SetInstalledTemplatePackagesAsync(packagesInSettings, cancellationToken).ConfigureAwait(false); return(results); }
public async Task <UpdateResult> UpdateAsync(UpdateRequest updateRequest, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken) { _ = updateRequest ?? throw new ArgumentNullException(nameof(updateRequest)); _ = provider ?? throw new ArgumentNullException(nameof(provider)); if (string.IsNullOrWhiteSpace(updateRequest.Version)) { throw new ArgumentException("Version cannot be null or empty", nameof(updateRequest.Version)); } //ensure uninstall is performed UninstallResult uninstallResult = await UninstallAsync(updateRequest.TemplatePackage, provider, cancellationToken).ConfigureAwait(false); if (!uninstallResult.Success) { if (uninstallResult.ErrorMessage is null) { throw new InvalidOperationException($"{nameof(uninstallResult.ErrorMessage)} cannot be null when {nameof(uninstallResult.Success)} is 'true'"); } return(UpdateResult.CreateFailure(updateRequest, uninstallResult.Error, uninstallResult.ErrorMessage)); } var nuGetManagedSource = updateRequest.TemplatePackage as NuGetManagedTemplatePackage; Dictionary <string, string> installationDetails = new Dictionary <string, string>(); if (nuGetManagedSource != null && !string.IsNullOrWhiteSpace(nuGetManagedSource.NuGetSource)) { installationDetails.Add(InstallerConstants.NuGetSourcesKey, nuGetManagedSource.NuGetSource !); } InstallRequest installRequest = new InstallRequest(updateRequest.TemplatePackage.Identifier, updateRequest.Version, details: installationDetails); return(UpdateResult.FromInstallResult(updateRequest, await InstallAsync(installRequest, provider, cancellationToken).ConfigureAwait(false))); }
public static UninstallResult UninstallGeneratorParts(string whereFrom, string _namespace, RMGeneratorCollection collection) { if (collection == null || collection.Parts == null) { return(UninstallResult.normal); } List <RMPackFile> files = collection.RetrieveAllFiles(); UninstallResult retVal = UninstallResult.normal; if (files != null) { foreach (RMPackFile file in files) { if (string.IsNullOrWhiteSpace(file.Path)) { continue; } string concatPath = whereFrom + "\\" + file.Path; if (File.Exists(concatPath)) { Exception ex = null; if (Helper.DeleteFileSafely(concatPath, _namespace, out ex, LoggerMessages.GeneralError.DELETE_UNUSED_FILE_FAILED_ARG) == DeleteFileResult.UserCancelled) { throw ex; } retVal = UninstallResult.genPartsRemoved; } } } return(retVal); }
public async Task CanUninstall_Success() { MockInstallerFactory factory = new MockInstallerFactory(); MockManagedTemplatePackageProvider provider = new MockManagedTemplatePackageProvider(); string installPath = _environmentSettingsHelper.CreateTemporaryFolder(); IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); FolderInstaller folderInstaller = new FolderInstaller(engineEnvironmentSettings, factory); InstallRequest request = new InstallRequest(installPath); InstallResult result = await folderInstaller.InstallAsync(request, provider, CancellationToken.None).ConfigureAwait(false); Assert.True(result.Success); Assert.Equal(request, result.InstallRequest); Assert.Equal(InstallerErrorCode.Success, result.Error); result.ErrorMessage.Should().BeNullOrEmpty(); var source = (FolderManagedTemplatePackage)result.TemplatePackage; source.Should().NotBeNull(); source.MountPointUri.Should().Be(installPath); Directory.Exists(installPath); UninstallResult uninstallResult = await folderInstaller.UninstallAsync(source, provider, CancellationToken.None).ConfigureAwait(false); Assert.True(uninstallResult.Success); Assert.Equal(source, uninstallResult.TemplatePackage); Assert.Equal(InstallerErrorCode.Success, result.Error); result.ErrorMessage.Should().BeNullOrEmpty(); //directory is not removed Directory.Exists(installPath); }
/// <summary> /// Uninstalls a package from the local system. /// </summary> protected override void ProcessRecord() { this.GetPackageAndExecute(CompositeSearchBehavior.LocalCatalogs, (package, version) => { UninstallOptions options = this.GetUninstallOptions(version); UninstallResult result = this.UninstallPackage(package, options); this.WriteObject(result); }); }
static UninstallResult UninstallPackage(RMPackage package, string _namespace, out LogDataList log, bool globalPackage = true, string whereToRemove = null) { UninstallResult retVal = UninstallResult.normal; log = new LogDataList(); if (package.Collections != null) { foreach (RMCollection collection in package.Collections) { RMGeneratorCollection genCollection = collection as RMGeneratorCollection; if (genCollection != null) { if (globalPackage) { whereToRemove = PMFileSystem.MV_Installation_Directory; retVal = Generator.UninstallGeneratorParts(whereToRemove, _namespace, genCollection); genCollection = null; } //ignore this collection if not a global package } else { if (globalPackage) { whereToRemove = PMFileSystem.MV_NewData_Dir; } List <RMPackFile> files = collection.RetrieveAllFiles(); if (files != null) { foreach (RMPackFile file in files) { if (string.IsNullOrWhiteSpace(file.Path)) { continue; } string concatPath = whereToRemove + "\\" + file.Path; if (File.Exists(concatPath)) { Exception ex = null; if (Helper.DeleteFileSafely(concatPath, _namespace, out ex, new DeleteFileLogMessages(deleteFailed: UninstallerMessages.Warning.FileDeleteFailed, logGroup: log)) == DeleteFileResult.FileNotFound) { continue; } } } } } } } return(retVal); }
static UninstallResult ProcDelNonReadXMLPackage(string arg, string installedDir, InstalledPackage installedPackage, ProjectPackMan openedProject, string _namespace, out LogDataList log, bool procEvents = true, UninstallArgType argType = UninstallArgType.UID, bool globalPackage = true, string whereToRemove = null) { log = new LogDataList(); if (argType == UninstallArgType.DirectoryPath || argType == UninstallArgType.XMLPath) { LogDataList outLog = null; RMPackage package = null; if (procEvents && OnPackageUninstallBegin != null) { OnPackageUninstallBegin.Invoke(package, globalPackage, installedDir, installedPackage, openedProject); } RMPackage parsedPackage = null; try { parsedPackage = new RMPackage(arg, _namespace, out outLog); } catch (Exception ex) { log.AppendLogs(outLog); Logger.WriteErrorLog(UninstallerMessages.Error.XML_FILE_INVALID + arg + ".", _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } log.AppendLogs(outLog); UninstallResult res = UninstallPackage(parsedPackage, _namespace, out outLog, globalPackage, whereToRemove); log.AppendLogs(outLog); if (procEvents && OnPackageUninstalled != null) { OnPackageUninstalled.Invoke(package, globalPackage, installedPackage, openedProject); } return(res); } else { try { throw new InvalidArgumentException(argType.GetType(), "argType"); } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.INVALID_PROCDELNONREADXMLPACKAGE_ARG, _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } } }
private async Task <(InstallerErrorCode, string)> EnsureInstallPrerequisites(List <TemplatePackageData> packagesInSettings, string identifier, string?version, IInstaller installer, CancellationToken cancellationToken, bool update = false, bool forceUpdate = false) { var packages = await GetAllTemplatePackagesAsync(cancellationToken).ConfigureAwait(false); //check if the package with same identifier is already installed if (packages.OfType <IManagedTemplatePackage>().FirstOrDefault(s => s.Identifier == identifier && s.Installer == installer) is IManagedTemplatePackage packageToBeUpdated) { //if same version is already installed - return if (!forceUpdate && packageToBeUpdated.Version == version) { return(InstallerErrorCode.AlreadyInstalled, string.Format(LocalizableStrings.GlobalSettingsTemplatePackageProvider_InstallResult_Error_PackageAlreadyInstalled, packageToBeUpdated.DisplayName)); } if (!update) { _logger.LogInformation( string.Format( LocalizableStrings.GlobalSettingsTemplatePackagesProvider_Info_PackageAlreadyInstalled, string.IsNullOrWhiteSpace(packageToBeUpdated.Version) ? packageToBeUpdated.Identifier : $"{packageToBeUpdated.Identifier} ({string.Format(LocalizableStrings.Generic_Version, packageToBeUpdated.Version)})", string.IsNullOrWhiteSpace(version) ? LocalizableStrings.Generic_LatestVersion : string.Format(LocalizableStrings.Generic_Version, version))); } //uninstall previous version first UninstallResult uninstallResult = await installer.UninstallAsync(packageToBeUpdated, this, cancellationToken).ConfigureAwait(false); if (!uninstallResult.Success) { if (uninstallResult.ErrorMessage is null) { throw new InvalidOperationException($"{nameof(uninstallResult.ErrorMessage)} cannot be null when {nameof(uninstallResult.Success)} is 'true'"); } return(InstallerErrorCode.UpdateUninstallFailed, uninstallResult.ErrorMessage); } _logger.LogInformation( string.Format( LocalizableStrings.GlobalSettingsTemplatePackagesProvider_Info_PackageUninstalled, packageToBeUpdated.DisplayName)); lock (packagesInSettings) { packagesInSettings.RemoveAll(p => p.MountPointUri == packageToBeUpdated.MountPointUri); } } return(InstallerErrorCode.Success, string.Empty); }
public Task <UninstallResult> UninstallAsync(IManagedTemplatePackage templatePackage, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken) { _ = templatePackage ?? throw new ArgumentNullException(nameof(templatePackage)); if (!(templatePackage is NuGetManagedTemplatePackage)) { return(Task.FromResult(UninstallResult.CreateFailure(templatePackage, InstallerErrorCode.UnsupportedRequest, $"{templatePackage.Identifier} is not supported by {Factory.Name}"))); } try { _environmentSettings.Host.FileSystem.FileDelete(templatePackage.MountPointUri); return(Task.FromResult(UninstallResult.CreateSuccess(templatePackage))); } catch (Exception ex) { _environmentSettings.Host.LogDiagnosticMessage($"Uninstalling {templatePackage.DisplayName} failed.", DebugLogCategory); _environmentSettings.Host.LogDiagnosticMessage($"Details:{ex.ToString()}", DebugLogCategory); return(Task.FromResult(UninstallResult.CreateFailure(templatePackage, InstallerErrorCode.GenericError, $"Failed to uninstall {templatePackage.DisplayName}, reason: {ex.Message}"))); } }
private async Task <(InstallerErrorCode, string)> EnsureInstallPrerequisites(List <TemplatePackageData> packagesInSettings, string identifier, string version, IInstaller installer, CancellationToken cancellationToken, bool update = false) { var packages = await GetAllTemplatePackagesAsync(cancellationToken).ConfigureAwait(false); //check if the package with same identifier is already installed if (packages.OfType <IManagedTemplatePackage>().FirstOrDefault(s => s.Identifier == identifier && s.Installer == installer) is IManagedTemplatePackage packageToBeUpdated) { //if same version is already installed - return if (packageToBeUpdated.Version == version) { return(InstallerErrorCode.AlreadyInstalled, $"{packageToBeUpdated.DisplayName} is already installed."); } if (!update) { _environmentSettings.Host.LogMessage( string.Format( LocalizableStrings.GlobalSettingsTemplatePackagesProvider_Info_PackageAlreadyInstalled, packageToBeUpdated.Identifier, packageToBeUpdated.Version, string.IsNullOrWhiteSpace(identifier) ? LocalizableStrings.Generic_LatestVersion : string.Format(LocalizableStrings.Generic_Version, version))); } //if different version is installed - uninstall previous version first UninstallResult uninstallResult = await installer.UninstallAsync(packageToBeUpdated, this, cancellationToken).ConfigureAwait(false); if (!uninstallResult.Success) { return(InstallerErrorCode.UpdateUninstallFailed, uninstallResult.ErrorMessage); } _environmentSettings.Host.LogMessage( string.Format( LocalizableStrings.GlobalSettingsTemplatePackagesProvider_Info_PackageUninstalled, packageToBeUpdated.DisplayName)); lock (packagesInSettings) { packagesInSettings.RemoveAll(p => p.MountPointUri == packageToBeUpdated.MountPointUri); } } return(InstallerErrorCode.Success, string.Empty); }
public Task <UninstallResult> UninstallAsync(IManagedTemplatePackage templatePackage, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken) { _ = templatePackage ?? throw new ArgumentNullException(nameof(templatePackage)); if (!(templatePackage is NuGetManagedTemplatePackage)) { return(Task.FromResult(UninstallResult.CreateFailure( templatePackage, InstallerErrorCode.UnsupportedRequest, string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_PackageNotSupported, templatePackage.DisplayName, Factory.Name)))); } try { _environmentSettings.Host.FileSystem.FileDelete(templatePackage.MountPointUri); return(Task.FromResult(UninstallResult.CreateSuccess(templatePackage))); } catch (Exception e) { _logger.LogDebug("Uninstalling {0} failed. Details:{1}", templatePackage.DisplayName, e); return(Task.FromResult(UninstallResult.CreateFailure( templatePackage, InstallerErrorCode.GenericError, string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_UninstallGeneric, templatePackage.DisplayName, e.Message)))); } }
public Task <UninstallResult> UninstallAsync(IManagedTemplatePackage templatePackage, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken) { _ = templatePackage ?? throw new ArgumentNullException(nameof(templatePackage)); return(Task.FromResult(UninstallResult.CreateSuccess(templatePackage))); }
public static void UninstallGlobalPackage(string arg, string _namespace, out LogDataList log, UninstallArgType argType = UninstallArgType.UID, bool renumberParts = true, bool deleteInstallFiles = true, bool procEvents = true) { log = new LogDataList(); Logger.WriteInformationLog(UninstallerMessages.Information.UNINSTALL_PACKAGE_START_G, _namespace); if (string.IsNullOrWhiteSpace(arg)) { try { throw new ArgumentNullException(ExceptionMessages.General.ARG_ARG_NULL); } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.ARG_INVALID, _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } } if (argType == UninstallArgType.DirectoryPath) { arg += "\\" + Vars.INSTALLED_XML_FILENAME; } if ((argType == UninstallArgType.XMLPath || argType == UninstallArgType.DirectoryPath) && !File.Exists(arg)) { try { throw new FileNotFoundExceptionWPath(arg); } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.XML_FILE_NOT_FOUND, _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } } Exception outEx; LogDataList outLog = null; UninstallResult result = UninstallResult.normal; if (GlobalPackages != null) { InstalledPackage installedPackage; if (argType == UninstallArgType.XMLPath || argType == UninstallArgType.DirectoryPath) { installedPackage = GlobalPackages.FindByPath(arg); } else { installedPackage = GlobalPackages.FindByUID(arg); } if (installedPackage != null) { if (installedPackage.Package != null) { if (procEvents && OnPackageUninstallBegin != null) { OnPackageUninstallBegin.Invoke(installedPackage.Package, true, installedPackage.Directory, installedPackage, null); } result = UninstallPackage(installedPackage.Package, _namespace, out outLog); log.AppendLogs(outLog); if (procEvents && OnPackageUninstalled != null) { OnPackageUninstalled.Invoke(installedPackage.Package, true, installedPackage, null); } } else { result = ProcDelNonReadXMLPackage(arg, installedPackage.Directory, installedPackage, null, _namespace, out outLog, procEvents, argType); log.AppendLogs(outLog); } if (deleteInstallFiles) { if (Directory.Exists(installedPackage.Directory)) { string MD5INUID = new DirectoryInfo(installedPackage.Directory).Name; Helper.DeleteFolderSafely(installedPackage.Directory, _namespace, out outEx, new DeleteFolderLogMessages(deleteFailed: UninstallerMessages.Warning.DirectoryUnableDelete, logGroup: log)); NewProject.DeletePackageInstallInfo(MD5INUID, _namespace); } GlobalPackages.Remove(installedPackage); } //else //{ // if (installedPackage.Package != null) // { // installedPackage.Installed = false; // bool successfulCopy = true; // try // { // installedPackage.Package.SaveToFile(installedPackage.XMLPath, _namespace, RMPackage.SaveToFileMode.ExplicitAssetInfo); // } // catch (Exception ex) // { // log.DataList.Add(new RMLogDataWarning(UninstallerMessages.Warning.InstalledXMLUpdateFailedInsStatus(installedPackage.XMLPath), _namespace, ex)); // successfulCopy = false; // } // if (successfulCopy) // NewProject.CopyPackageInstallXML(installedPackage.XMLPath, _namespace, installedPackage.Package); // } //} } else { if (argType == UninstallArgType.UID) { try { throw new PackageNotFoundException(true, ExceptionMessages.General.PackWIDNotFound(arg)); } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.PACKAGE_UID_NOT_FOUND + arg + ".", _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } } string installedDir = null; try { installedDir = Path.GetDirectoryName(arg); } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.INVALID_XML_PATH + arg + ".", _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } result = ProcDelNonReadXMLPackage(arg, installedDir, null, null, _namespace, out outLog, procEvents, argType); } } else { if (argType == UninstallArgType.UID) { try { throw new PackageNotFoundException(true, ExceptionMessages.General.PackWIDNotFound(arg)); } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.PACKAGE_UID_NOT_FOUND + arg + ".", _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } } string installedDir = null; try { installedDir = Path.GetDirectoryName(arg); } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.INVALID_XML_PATH + arg + ".", _namespace, ex, BasicDebugLogger.DebugErrorType.Error); throw; } result = ProcDelNonReadXMLPackage(arg, installedDir, null, null, _namespace, out outLog, procEvents, argType); } outLog = null; try { if (renumberParts && result == UninstallResult.genPartsRemoved) { GeneratorPartsManager.RenumberParts(_namespace, out outLog, true); } } catch (Exception ex) { Logger.WriteErrorLog(UninstallerMessages.Error.GEN_PART_RENUMBER_FAILED, _namespace, ex, BasicDebugLogger.DebugErrorType.CriticalError); throw; } log.AppendLogs(outLog); Logger.WriteInformationLog(UninstallerMessages.Information.UNINSTALL_PACKAGE_DONE_G, _namespace); }