Skip to content

More code clean up for next release #548

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 18, 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: 2 additions & 1 deletion src/code/FindHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,8 @@ private IEnumerable<PSResourceInfo> SearchFromRepository(
resourceSearch = repository.GetResourceAsync<PackageSearchResource>().GetAwaiter().GetResult();
resourceMetadata = repository.GetResourceAsync<PackageMetadataResource>().GetAwaiter().GetResult();
}
catch (Exception e){
catch (Exception e)
{
Utils.WriteVerboseOnCmdlet(_cmdletPassedIn, "Error retrieving resource from repository: " + e.Message);
}

Expand Down
88 changes: 29 additions & 59 deletions src/code/PSResourceInfo.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
using System.Text.RegularExpressions;
using System.Linq;
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using NuGet.Versioning;
using NuGet.Protocol.Core.Types;
using System;
using System.Collections;
using System.Collections.Generic;
using Dbg = System.Diagnostics.Debug;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using NuGet.Packaging;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;

using Dbg = System.Diagnostics.Debug;

namespace Microsoft.PowerShell.PowerShellGet.UtilClasses
{
Expand All @@ -20,9 +19,6 @@ namespace Microsoft.PowerShell.PowerShellGet.UtilClasses
[Flags]
public enum ResourceType
{
// 00001 -> M
// 00100 -> C
// 00101 -> M, C
None = 0x0,
Module = 0x1,
Script = 0x2,
Expand Down Expand Up @@ -204,18 +200,18 @@ public sealed class PSCommandResourceInfo
{
// this object will represent a Command or DSCResource
// included by the PSResourceInfo property

#region Properties

public string Name { get; }

public PSResourceInfo ParentResource { get; }

#endregion

#region Constructor

/// <summary>
/// Constructor
///
/// </summary>
/// <param name="name">Name of the command or DSC resource</param>
/// <param name="parentResource">the parent module resource the command or dsc resource belongs to</param>
Expand Down Expand Up @@ -325,6 +321,7 @@ private PSResourceInfo(
#endregion

#region Private fields

private static readonly char[] Delimeter = {' ', ','};

#endregion
Expand Down Expand Up @@ -498,7 +495,6 @@ private static Version GetVersionInfo(
return GetProperty<Version>(nameof(PSResourceInfo.Version), psObjectInfo);
}


public static bool TryConvert(
IPackageSearchMetadata metadataToParse,
out PSResourceInfo psGetInfo,
Expand Down Expand Up @@ -620,38 +616,11 @@ private static T GetProperty<T>(
}
}

private static string GetPrereleaseLabel(Version version)
{
string versionAsString = version.ToString();

if (!versionAsString.Contains("-"))
{
// no prerelease label present
return String.Empty;
}

string[] prereleaseParsed = versionAsString.Split('-');
if (prereleaseParsed.Length <= 1)
{
return String.Empty;
}

string prereleaseString = prereleaseParsed[1];
Regex prereleasePattern = new Regex("^[a-zA-Z0-9]+$");
if (!prereleasePattern.IsMatch(prereleaseString))
{
return String.Empty;
}

return prereleaseString;
}

private static Dependency[] GetDependencies(ArrayList dependencyInfos)
{
List<Dependency> dependenciesFound = new List<Dependency>();
if (dependencyInfos == null) { return dependenciesFound.ToArray(); }


foreach(PSObject dependencyObj in dependencyInfos)
{
// The dependency object can be a string or a hashtable
Expand Down Expand Up @@ -734,14 +703,12 @@ private static Dependency[] GetDependencies(ArrayList dependencyInfos)
else if (dependencyObj.Properties["Name"] != null)
{
string name = dependencyObj.Properties["Name"].Value.ToString();

string version = string.Empty;
VersionRange versionRange = VersionRange.All;

if (dependencyObj.Properties["VersionRange"] != null)
{
version = dependencyObj.Properties["VersionRange"].Value.ToString();
VersionRange.TryParse(version, out versionRange);
VersionRange.TryParse(
dependencyObj.Properties["VersionRange"].Value.ToString(),
out versionRange);
}

dependenciesFound.Add(new Dependency(name, versionRange));
Expand All @@ -756,7 +723,6 @@ private static string ConcatenateVersionWithPrerelease(string version, string pr
return Utils.GetNormalizedVersionString(version, prerelease);
}


#region Parse Metadata private static methods

private static string ParseMetadataAuthor(IPackageSearchMetadata pkg)
Expand All @@ -782,10 +748,11 @@ private static Dependency[] ParseMetadataDependencies(IPackageSearchMetadata pkg
depVersionRange = pkgDependencyItem.VersionRange;
}

Dependency currentDependency = new Dependency(pkgDependencyItem.Id, depVersionRange);
dependencies.Add(currentDependency);
dependencies.Add(
new Dependency(pkgDependencyItem.Id, depVersionRange));
}
}

return dependencies.ToArray();
}

Expand Down Expand Up @@ -828,25 +795,25 @@ private static Uri ParseMetadataProjectUri(IPackageSearchMetadata pkg)

private static DateTime? ParseMetadataPublishedDate(IPackageSearchMetadata pkg)
{
DateTime? publishDate = null;
DateTimeOffset? pkgPublishedDate = pkg.Published;
if (pkgPublishedDate.HasValue)
if (pkg.Published.HasValue)
{
publishDate = pkgPublishedDate.Value.DateTime;
return pkg.Published.Value.DateTime;
}
return publishDate;

return null;
}

private static string[] ParseMetadataTags(IPackageSearchMetadata pkg)
{
return pkg.Tags.Split(Delimeter, StringSplitOptions.RemoveEmptyEntries);
}

private static ResourceType ParseMetadataType(IPackageSearchMetadata pkg,
string repoName,
ResourceType? pkgType,
out ArrayList commandNames,
out ArrayList dscResourceNames)
private static ResourceType ParseMetadataType(
IPackageSearchMetadata pkg,
string repoName,
ResourceType? pkgType,
out ArrayList commandNames,
out ArrayList dscResourceNames)
{
// possible type combinations:
// M, C
Expand Down Expand Up @@ -875,19 +842,21 @@ private static ResourceType ParseMetadataType(IPackageSearchMetadata pkg,
// if Name contains wildcard, currently Script and Module tags should be set properly, but need to account for Command and DscResource types too
// if Name does not contain wildcard, GetMetadataAsync() was used, PSGallery only is searched (and pkg will successfully be found
// and returned from there) before PSGalleryScripts can be searched
foreach(string tag in tags)
foreach (string tag in tags)
{
if(String.Equals(tag, "PSScript", StringComparison.InvariantCultureIgnoreCase))
{
// clear default Module tag, because a Script resource cannot be a Module resource also
currentPkgType &= ~ResourceType.Module;
currentPkgType |= ResourceType.Script;
}

if (tag.StartsWith("PSCommand_", StringComparison.InvariantCultureIgnoreCase))
{
currentPkgType |= ResourceType.Command;
commandNames.Add(tag.Split('_')[1]);
}

if (tag.StartsWith("PSDscResource_", StringComparison.InvariantCultureIgnoreCase))
{
currentPkgType |= ResourceType.DscResource;
Expand All @@ -904,6 +873,7 @@ private static Version ParseMetadataVersion(IPackageSearchMetadata pkg)
{
return pkg.Identity.Version.Version;
}

return null;
}

Expand Down Expand Up @@ -999,7 +969,7 @@ public static void WritePSGetResourceInfo(
{
if (psObjectGetInfo.BaseObject is PSResourceInfo psGetInfo)
{
if (! psGetInfo.TryWrite(filePath, out string errorMsg))
if (!psGetInfo.TryWrite(filePath, out string errorMsg))
{
throw new PSInvalidOperationException(errorMsg);
}
Expand Down
51 changes: 28 additions & 23 deletions src/code/RepositorySettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,15 @@
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Xml;
using System.Xml.Linq;

using Dbg = System.Diagnostics.Debug;

namespace Microsoft.PowerShell.PowerShellGet.UtilClasses
{
/// <summary>
/// The class contains basic information of a repository path settings as well as methods to
/// perform CRUD operations on the repository store file.
/// perform Create/Read/Update/Delete operations on the repository store file.
/// </summary>

internal static class RepositorySettings
{
#region Members
Expand Down Expand Up @@ -52,8 +50,7 @@ public static void CheckRepositoryStore()
}

XDocument newRepoXML = new XDocument(
new XElement("configuration")
);
new XElement("configuration"));
newRepoXML.Save(FullRepositoryPath);
}
catch (Exception e)
Expand All @@ -69,7 +66,7 @@ public static void CheckRepositoryStore()
// Open file (which should exist now), if cannot/is corrupted then throw error
try
{
XDocument.Load(FullRepositoryPath);
LoadXDocument(FullRepositoryPath);
}
catch (Exception e)
{
Expand All @@ -84,13 +81,10 @@ public static void CheckRepositoryStore()
/// <param name="sectionName"></param>
public static PSRepositoryInfo Add(string repoName, Uri repoURL, int repoPriority, bool repoTrusted)
{
Dbg.Assert(!string.IsNullOrEmpty(repoName), "Repository name cannot be null or empty");
Dbg.Assert(!string.IsNullOrEmpty(repoURL.ToString()), "Repository URL cannot be null or empty");

try
{
// Open file
XDocument doc = XDocument.Load(FullRepositoryPath);
XDocument doc = LoadXDocument(FullRepositoryPath);
if (FindRepositoryElement(doc, repoName) != null)
{
throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName));
Expand Down Expand Up @@ -128,13 +122,11 @@ public static PSRepositoryInfo Add(string repoName, Uri repoURL, int repoPriorit
/// </summary>
public static PSRepositoryInfo Update(string repoName, Uri repoURL, int repoPriority, bool? repoTrusted)
{
Dbg.Assert(!string.IsNullOrEmpty(repoName), "Repository name cannot be null or empty");

PSRepositoryInfo updatedRepo;
try
{
// Open file
XDocument doc = XDocument.Load(FullRepositoryPath);
XDocument doc = LoadXDocument(FullRepositoryPath);
XElement node = FindRepositoryElement(doc, repoName);
if (node == null)
{
Expand Down Expand Up @@ -196,18 +188,11 @@ public static PSRepositoryInfo Update(string repoName, Uri repoURL, int repoPrio
public static void Remove(string[] repoNames, out string[] errorList)
{
List<string> tempErrorList = new List<string>();

// Check to see if information we're trying to remove from the repository is valid
if (repoNames == null || repoNames.Length == 0)
{
throw new ArgumentException("Repository name cannot be null or empty");
}

XDocument doc;
try
{
// Open file
doc = XDocument.Load(FullRepositoryPath);
doc = LoadXDocument(FullRepositoryPath);
}
catch (Exception e)
{
Expand Down Expand Up @@ -244,7 +229,7 @@ public static List<PSRepositoryInfo> Read(string[] repoNames, out string[] error
try
{
// Open file
doc = XDocument.Load(FullRepositoryPath);
doc = LoadXDocument(FullRepositoryPath);
}
catch (Exception e)
{
Expand Down Expand Up @@ -323,6 +308,26 @@ private static XElement FindRepositoryElement(XDocument doc, string name)
StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
}

private static readonly XmlReaderSettings XDocReaderSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Prohibit, // Disallow any DTD elements
XmlResolver = null, // Do not resolve external links
CheckCharacters = true,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
IgnoreWhitespace = true,
MaxCharactersFromEntities = 1024,
MaxCharactersInDocument = 512 * 1024 * 1024, // 512M characters = 1GB
ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None,
ValidationType = ValidationType.None
};

private static XDocument LoadXDocument(string filePath)
{
using var xmlReader = XmlReader.Create(filePath, XDocReaderSettings);
return XDocument.Load(xmlReader);
}

#endregion
}
}
Loading