Skip to content

Code clean up pass #547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/code/ArgumentCompleter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.ComponentModel;
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.PowerShell.PowerShellGet.UtilClasses;
Expand Down
3 changes: 1 addition & 2 deletions src/code/GetHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using System.Management.Automation;

using Dbg = System.Diagnostics.Debug;
using static Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo;

namespace Microsoft.PowerShell.PowerShellGet.Cmdlets
{
Expand Down Expand Up @@ -196,7 +195,7 @@ public PSResourceInfo OutputPackageObject(string pkgPath, Dictionary<string,PSRe

// Read metadata from XML and parse into PSResourceInfo object
_cmdletPassedIn.WriteVerbose(string.Format("Reading package metadata from: '{0}'", xmlFilePath));
if (TryRead(xmlFilePath, out PSResourceInfo psGetInfo, out string errorMsg))
if (PSResourceInfo.TryRead(xmlFilePath, out PSResourceInfo psGetInfo, out string errorMsg))
{
return psGetInfo;
}
Expand Down
11 changes: 5 additions & 6 deletions src/code/GetPSResourceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,8 @@ namespace Microsoft.PowerShell.PowerShellGet.Cmdlets
/// By default it will return all registered repositories, or if the -Name parameter argument is specified then it wil return the repository with that name.
/// It returns PSRepositoryInfo objects which describe each resource item found.
/// </summary>

[Cmdlet(VerbsCommon.Get,
"PSResourceRepository")]
public sealed
class GetPSResourceRepository : PSCmdlet
[Cmdlet(VerbsCommon.Get, "PSResourceRepository")]
public sealed class GetPSResourceRepository : PSCmdlet
{
#region Parameters

Expand All @@ -40,9 +37,11 @@ protected override void BeginProcessing()
{
RepositorySettings.CheckRepositoryStore();
}

protected override void ProcessRecord()
{
string nameArrayAsString = (Name == null || !Name.Any() || string.Equals(Name[0], "*") || Name[0] == null) ? "all" : string.Join(", ", Name);
string nameArrayAsString = (Name == null || !Name.Any() || string.Equals(Name[0], "*") || Name[0] == null)
? "all" : string.Join(", ", Name);
WriteVerbose(String.Format("reading repository: {0}. Calling Read() API now", nameArrayAsString));
List<PSRepositoryInfo> items = RepositorySettings.Read(Name, out string[] errorList);

Expand Down
89 changes: 51 additions & 38 deletions src/code/InstallHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ private List<string> InstallPackage(
bool isLocalRepo)
{
List<string> pkgsSuccessfullyInstalled = new List<string>();
foreach (PSResourceInfo p in pkgsToInstall)
foreach (PSResourceInfo pkgInfo in pkgsToInstall)
{
var tempInstallPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
try
Expand All @@ -300,23 +300,24 @@ private List<string> InstallPackage(
// TODO: are there Linux accommodations we need to consider here?
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;

_cmdletPassedIn.WriteVerbose(string.Format("Begin installing package: '{0}'", p.Name));
_cmdletPassedIn.WriteVerbose(string.Format("Begin installing package: '{0}'", pkgInfo.Name));

// TODO: add progress bar here

// Create PackageIdentity in order to download
string createFullVersion = p.Version.ToString();
if (p.IsPrerelease)
string createFullVersion = pkgInfo.Version.ToString();
if (pkgInfo.IsPrerelease)
{
createFullVersion = p.Version.ToString() + "-" + p.PrereleaseLabel;
createFullVersion = pkgInfo.Version.ToString() + "-" + pkgInfo.PrereleaseLabel;
}

if (!NuGetVersion.TryParse(createFullVersion, out NuGetVersion pkgVersion))
{
_cmdletPassedIn.WriteVerbose(string.Format("Error parsing package '{0}' version '{1}' into a NuGetVersion", p.Name, p.Version.ToString()));
_cmdletPassedIn.WriteVerbose(string.Format("Error parsing package '{0}' version '{1}' into a NuGetVersion",
pkgInfo.Name, pkgInfo.Version.ToString()));
continue;
}
var pkgIdentity = new PackageIdentity(p.Name, pkgVersion);
var pkgIdentity = new PackageIdentity(pkgInfo.Name, pkgVersion);
var cacheContext = new SourceCacheContext();

if (isLocalRepo)
Expand Down Expand Up @@ -352,7 +353,9 @@ private List<string> InstallPackage(
result.PackageReader.CopyFiles(
destination: tempInstallPath,
packageFiles: result.PackageReader.GetFiles(),
extractFile: (new PackageFileExtractor(result.PackageReader.GetFiles(), packageExtractionContext.XmlDocFileSaveMode)).ExtractPackageFile,
extractFile: new PackageFileExtractor(
result.PackageReader.GetFiles(),
packageExtractionContext.XmlDocFileSaveMode).ExtractPackageFile,
logger: NullLogger.Instance,
token: _cancellationToken);
result.Dispose();
Expand Down Expand Up @@ -409,8 +412,8 @@ private List<string> InstallPackage(
string tempDirNameVersion = isLocalRepo ? tempInstallPath : Path.Combine(tempInstallPath, pkgIdentity.Id.ToLower(), newVersion);
var version4digitNoPrerelease = pkgIdentity.Version.Version.ToString();
string moduleManifestVersion = string.Empty;
var scriptPath = Path.Combine(tempDirNameVersion, (p.Name + ".ps1"));
var modulePath = Path.Combine(tempDirNameVersion, (p.Name + ".psd1"));
var scriptPath = Path.Combine(tempDirNameVersion, pkgInfo.Name + ".ps1");
var modulePath = Path.Combine(tempDirNameVersion, pkgInfo.Name + ".psd1");
// Check if the package is a module or a script
var isModule = File.Exists(modulePath);

Expand All @@ -436,20 +439,20 @@ private List<string> InstallPackage(
moduleManifestVersion = parsedMetadataHashtable["ModuleVersion"] as string;

// Accept License verification
if (!_savePkg && !CallAcceptLicense(p, moduleManifest, tempInstallPath, newVersion))
if (!_savePkg && !CallAcceptLicense(pkgInfo, moduleManifest, tempInstallPath, newVersion))
{
continue;
}

// If NoClobber is specified, ensure command clobbering does not happen
if (_noClobber && !DetectClobber(p.Name, tempDirNameVersion, parsedMetadataHashtable))
if (_noClobber && !DetectClobber(pkgInfo.Name, parsedMetadataHashtable))
{
continue;
}
}

// Delete the extra nupkg related files that are not needed and not part of the module/script
DeleteExtraneousFiles(tempInstallPath, pkgIdentity, tempDirNameVersion);
DeleteExtraneousFiles(pkgIdentity, tempDirNameVersion);

string installPath;
if (_savePkg)
Expand All @@ -468,20 +471,29 @@ private List<string> InstallPackage(

if (_includeXML)
{
CreateMetadataXMLFile(tempDirNameVersion, installPath, repoName, p, isModule);
CreateMetadataXMLFile(tempDirNameVersion, installPath, pkgInfo, isModule);
}

MoveFilesIntoInstallPath(p, isModule, isLocalRepo, tempDirNameVersion, tempInstallPath, installPath, newVersion, moduleManifestVersion, normalizedVersionNoPrereleaseLabel, version4digitNoPrerelease, scriptPath);
MoveFilesIntoInstallPath(
pkgInfo,
isModule,
isLocalRepo,
tempDirNameVersion,
tempInstallPath,
installPath,
newVersion,
moduleManifestVersion,
scriptPath);

_cmdletPassedIn.WriteVerbose(String.Format("Successfully installed package '{0}' to location '{1}'", p.Name, installPath));
pkgsSuccessfullyInstalled.Add(p.Name);
_cmdletPassedIn.WriteVerbose(String.Format("Successfully installed package '{0}' to location '{1}'", pkgInfo.Name, installPath));
pkgsSuccessfullyInstalled.Add(pkgInfo.Name);
}
catch (Exception e)
{
_cmdletPassedIn.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Unable to successfully install package '{p.Name}': '{e.Message}'",
message: $"Unable to successfully install package '{pkgInfo.Name}': '{e.Message}'",
innerException: e),
"InstallPackageFailed",
ErrorCategory.InvalidOperation,
Expand Down Expand Up @@ -584,7 +596,7 @@ private bool CallAcceptLicense(PSResourceInfo p, string moduleManifest, string t
return success;
}

private bool DetectClobber(string pkgName, string tempDirNameVersion, Hashtable parsedMetadataHashtable)
private bool DetectClobber(string pkgName, Hashtable parsedMetadataHashtable)
{
// Get installed modules, then get all possible paths
bool foundClobber = false;
Expand All @@ -608,10 +620,12 @@ private bool DetectClobber(string pkgName, string tempDirNameVersion, Hashtable
duplicateCmdlets = listOfCmdlets.Where(cmdlet => pkg.Includes.Cmdlet.Contains(cmdlet)).ToList();

}

if (pkg.Includes.Command != null && pkg.Includes.Command.Any())
{
duplicateCmds = listOfCmdlets.Where(commands => pkg.Includes.Command.Contains(commands, StringComparer.InvariantCultureIgnoreCase)).ToList();
}

if (duplicateCmdlets.Any() || duplicateCmds.Any())
{

Expand All @@ -634,7 +648,7 @@ private bool DetectClobber(string pkgName, string tempDirNameVersion, Hashtable
return foundClobber;
}

private void CreateMetadataXMLFile(string dirNameVersion, string installPath, string repoName, PSResourceInfo pkg, bool isModule)
private void CreateMetadataXMLFile(string dirNameVersion, string installPath, PSResourceInfo pkg, bool isModule)
{
// Script will have a metadata file similar to: "TestScript_InstalledScriptInfo.xml"
// Modules will have the metadata file: "PSGetModuleInfo.xml"
Expand All @@ -654,14 +668,14 @@ private void CreateMetadataXMLFile(string dirNameVersion, string installPath, st
}
}

private void DeleteExtraneousFiles(string tempInstallPath, PackageIdentity pkgIdentity, string dirNameVersion)
private void DeleteExtraneousFiles(PackageIdentity pkgIdentity, string dirNameVersion)
{
// Deleting .nupkg SHA file, .nuspec, and .nupkg after unpacking the module
var pkgIdString = pkgIdentity.ToString();
var nupkgSHAToDelete = Path.Combine(dirNameVersion, (pkgIdString + ".nupkg.sha512"));
var nuspecToDelete = Path.Combine(dirNameVersion, (pkgIdentity.Id + ".nuspec"));
var nupkgToDelete = Path.Combine(dirNameVersion, (pkgIdString + ".nupkg"));
var nupkgMetadataToDelete = Path.Combine(dirNameVersion, (pkgIdString + ".nupkg.metadata"));
var nupkgSHAToDelete = Path.Combine(dirNameVersion, pkgIdString + ".nupkg.sha512");
var nuspecToDelete = Path.Combine(dirNameVersion, pkgIdentity.Id + ".nuspec");
var nupkgToDelete = Path.Combine(dirNameVersion, pkgIdString + ".nupkg");
var nupkgMetadataToDelete = Path.Combine(dirNameVersion, pkgIdString + ".nupkg.metadata");
var contentTypesToDelete = Path.Combine(dirNameVersion, "[Content_Types].xml");
var relsDirToDelete = Path.Combine(dirNameVersion, "_rels");
var packageDirToDelete = Path.Combine(dirNameVersion, "package");
Expand Down Expand Up @@ -725,25 +739,23 @@ private bool TryDeleteDirectory(
}

private void MoveFilesIntoInstallPath(
PSResourceInfo p,
PSResourceInfo pkgInfo,
bool isModule,
bool isLocalRepo,
string dirNameVersion,
string tempInstallPath,
string installPath,
string newVersion,
string moduleManifestVersion,
string nupkgVersion,
string versionWithoutPrereleaseTag,
string scriptPath)
{
// Creating the proper installation path depending on whether pkg is a module or script
var newPathParent = isModule ? Path.Combine(installPath, p.Name) : installPath;
var finalModuleVersionDir = isModule ? Path.Combine(installPath, p.Name, moduleManifestVersion) : installPath; // versionWithoutPrereleaseTag
var newPathParent = isModule ? Path.Combine(installPath, pkgInfo.Name) : installPath;
var finalModuleVersionDir = isModule ? Path.Combine(installPath, pkgInfo.Name, moduleManifestVersion) : installPath;

// If script, just move the files over, if module, move the version directory over
var tempModuleVersionDir = (!isModule || isLocalRepo) ? dirNameVersion
: Path.Combine(tempInstallPath, p.Name.ToLower(), newVersion);
: Path.Combine(tempInstallPath, pkgInfo.Name.ToLower(), newVersion);

_cmdletPassedIn.WriteVerbose(string.Format("Installation source path is: '{0}'", tempModuleVersionDir));
_cmdletPassedIn.WriteVerbose(string.Format("Installation destination path is: '{0}'", finalModuleVersionDir));
Expand Down Expand Up @@ -774,11 +786,12 @@ private void MoveFilesIntoInstallPath(
Utils.MoveDirectory(tempModuleVersionDir, finalModuleVersionDir);
}
}
else {
else
{
if (!_savePkg)
{
// Need to delete old xml files because there can only be 1 per script
var scriptXML = p.Name + "_InstalledScriptInfo.xml";
var scriptXML = pkgInfo.Name + "_InstalledScriptInfo.xml";
_cmdletPassedIn.WriteVerbose(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(installPath, "InstalledScriptInfos", scriptXML))));
if (File.Exists(Path.Combine(installPath, "InstalledScriptInfos", scriptXML)))
{
Expand All @@ -790,16 +803,16 @@ private void MoveFilesIntoInstallPath(
Utils.MoveFiles(Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, "InstalledScriptInfos", scriptXML));

// Need to delete old script file, if that exists
_cmdletPassedIn.WriteVerbose(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(finalModuleVersionDir, p.Name + ".ps1"))));
if (File.Exists(Path.Combine(finalModuleVersionDir, p.Name + ".ps1")))
_cmdletPassedIn.WriteVerbose(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1"))));
if (File.Exists(Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1")))
{
_cmdletPassedIn.WriteVerbose(string.Format("Deleting script file"));
File.Delete(Path.Combine(finalModuleVersionDir, p.Name + ".ps1"));
File.Delete(Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1"));
}
}

_cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", scriptPath, Path.Combine(finalModuleVersionDir, p.Name + ".ps1")));
Utils.MoveFiles(scriptPath, Path.Combine(finalModuleVersionDir, p.Name + ".ps1"));
_cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", scriptPath, Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1")));
Utils.MoveFiles(scriptPath, Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1"));
}
}

Expand Down
16 changes: 12 additions & 4 deletions src/code/NuGetLogger.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using NuGet.Common;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using NuGet.Common;

// This class is needed for
public class NuGetLogger : ILogger
#region NuGetLogger

internal class NuGetLogger : ILogger
{
private readonly ITestOutputHelper _output;

Expand Down Expand Up @@ -175,16 +176,21 @@ public async Task LogAsync(ILogMessage message)
}
}

#endregion

#region ITestOutputHelper

// Summary:
// Represents a class which can be used to provide test output.
public interface ITestOutputHelper
internal interface ITestOutputHelper
{
// Summary:
// Adds a line of text to the output.
// Parameters:
// message:
// The message
void WriteLine(string message);

// Summary:
// Formats a line of text and adds it to the output.
// Parameters:
Expand All @@ -194,3 +200,5 @@ public interface ITestOutputHelper
// The format arguments
void WriteLine(string format, params object[] args);
}

#endregion
1 change: 1 addition & 0 deletions src/code/PSRepositoryInfo.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Management.Automation;

Expand Down
Loading