Skip to content

Commit 75fe624

Browse files
Ensure that exception is not swallowed by finally block (#1569)
1 parent 136fb95 commit 75fe624

File tree

4 files changed

+96
-58
lines changed

4 files changed

+96
-58
lines changed

src/code/InstallHelper.cs

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ public IEnumerable<PSResourceInfo> BeginInstallPackages(
9595
{
9696
_cmdletPassedIn.WriteDebug("In InstallHelper::BeginInstallPackages()");
9797
_cmdletPassedIn.WriteDebug(string.Format("Parameters passed in >>> Name: '{0}'; VersionRange: '{1}'; NuGetVersion: '{2}'; VersionType: '{3}'; Version: '{4}'; Prerelease: '{5}'; Repository: '{6}'; " +
98-
"AcceptLicense: '{7}'; Quiet: '{8}'; Reinstall: '{9}'; TrustRepository: '{10}'; NoClobber: '{11}'; AsNupkg: '{12}'; IncludeXml '{13}'; SavePackage '{14}'; TemporaryPath '{15}'; SkipDependencyCheck: '{16}'; " +
98+
"AcceptLicense: '{7}'; Quiet: '{8}'; Reinstall: '{9}'; TrustRepository: '{10}'; NoClobber: '{11}'; AsNupkg: '{12}'; IncludeXml '{13}'; SavePackage '{14}'; TemporaryPath '{15}'; SkipDependencyCheck: '{16}'; " +
9999
"AuthenticodeCheck: '{17}'; PathsToInstallPkg: '{18}'; Scope '{19}'",
100100
string.Join(",", names),
101101
versionRange != null ? (versionRange.OriginalString != null ? versionRange.OriginalString : string.Empty) : string.Empty,
@@ -265,7 +265,7 @@ private List<PSResourceInfo> ProcessRepositories(
265265
List<string> repositoryNamesToSearch = new List<string>();
266266
bool sourceTrusted = false;
267267

268-
// Loop through all the repositories provided (in priority order) until there no more packages to install.
268+
// Loop through all the repositories provided (in priority order) until there no more packages to install.
269269
for (int i = 0; i < listOfRepositories.Count && _pkgNamesToInstall.Count > 0; i++)
270270
{
271271
PSRepositoryInfo currentRepository = listOfRepositories[i];
@@ -614,7 +614,7 @@ private List<PSResourceInfo> InstallPackages(
614614
depFindFailed = true;
615615
continue;
616616
}
617-
617+
618618
if (String.Equals(depPkg.Name, parentPkgObj.Name, StringComparison.OrdinalIgnoreCase))
619619
{
620620
continue;
@@ -683,6 +683,16 @@ private List<PSResourceInfo> InstallPackages(
683683
}
684684
}
685685
}
686+
catch (Exception e)
687+
{
688+
_cmdletPassedIn.WriteError(new ErrorRecord(
689+
e,
690+
"InstallPackageFailure",
691+
ErrorCategory.InvalidOperation,
692+
_cmdletPassedIn));
693+
694+
throw e;
695+
}
686696
finally
687697
{
688698
DeleteInstallationTempPath(tempInstallPath);
@@ -754,14 +764,14 @@ private Hashtable BeginPackageInstall(
754764
if (currentResult.exception != null && !currentResult.exception.Message.Equals(string.Empty))
755765
{
756766
errRecord = new ErrorRecord(
757-
currentResult.exception,
758-
"FindConvertToPSResourceFailure",
759-
ErrorCategory.ObjectNotFound,
767+
currentResult.exception,
768+
"FindConvertToPSResourceFailure",
769+
ErrorCategory.ObjectNotFound,
760770
_cmdletPassedIn);
761771
}
762772
else if (searchVersionType == VersionType.VersionRange)
763773
{
764-
// Check to see if version falls within version range
774+
// Check to see if version falls within version range
765775
PSResourceInfo foundPkg = currentResult.returnedObject;
766776
string versionStr = $"{foundPkg.Version}";
767777
if (foundPkg.IsPrerelease)
@@ -800,7 +810,7 @@ private Hashtable BeginPackageInstall(
800810
if (_packagesOnMachine.Contains(currPkgNameVersion))
801811
{
802812
_cmdletPassedIn.WriteWarning($"Resource '{pkgToInstall.Name}' with version '{pkgVersion}' is already installed. If you would like to reinstall, please run the cmdlet again with the -Reinstall parameter");
803-
813+
804814
// Remove from tracking list of packages to install.
805815
_pkgNamesToInstall.RemoveAll(x => x.Equals(pkgToInstall.Name, StringComparison.InvariantCultureIgnoreCase));
806816

@@ -1166,7 +1176,7 @@ private bool TrySaveNupkgToTempPath(
11661176

11671177
/// <summary>
11681178
/// Extracts files from .nupkg
1169-
/// Similar functionality as System.IO.Compression.ZipFile.ExtractToDirectory,
1179+
/// Similar functionality as System.IO.Compression.ZipFile.ExtractToDirectory,
11701180
/// but while ExtractToDirectory cannot overwrite files, this method can.
11711181
/// </summary>
11721182
private bool TryExtractToDirectory(string zipPath, string extractPath, out ErrorRecord error)

src/code/PublishPSResource.cs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
2323
/// <summary>
2424
/// Publishes a module, script, or nupkg to a designated repository.
2525
/// </summary>
26-
[Cmdlet(VerbsData.Publish,
27-
"PSResource",
26+
[Cmdlet(VerbsData.Publish,
27+
"PSResource",
2828
SupportsShouldProcess = true)]
2929
[Alias("pbres")]
3030
public sealed class PublishPSResource : PSCmdlet
@@ -505,6 +505,14 @@ out string[] _
505505
}
506506
}
507507
}
508+
catch (Exception e)
509+
{
510+
ThrowTerminatingError(new ErrorRecord(
511+
e,
512+
"PublishPSResourceError",
513+
ErrorCategory.NotSpecified,
514+
this));
515+
}
508516
finally
509517
{
510518
WriteVerbose(string.Format("Deleting temporary directory '{0}'", outputDir));
@@ -806,7 +814,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash)
806814
if (!parsedMetadataHash.ContainsKey("requiredmodules"))
807815
{
808816
return null;
809-
}
817+
}
810818
LanguagePrimitives.TryConvertTo<object[]>(parsedMetadataHash["requiredmodules"], out object[] requiredModules);
811819

812820
// Required modules can be:
@@ -839,7 +847,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash)
839847
dependenciesHash.Add(moduleName, string.Empty);
840848
}
841849
}
842-
var externalModuleDeps = parsedMetadataHash.ContainsKey("ExternalModuleDependencies") ?
850+
var externalModuleDeps = parsedMetadataHash.ContainsKey("ExternalModuleDependencies") ?
843851
parsedMetadataHash["ExternalModuleDependencies"] : null;
844852

845853
if (externalModuleDeps != null && LanguagePrimitives.TryConvertTo<string[]>(externalModuleDeps, out string[] externalModuleNames))
@@ -1130,7 +1138,7 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o
11301138
WriteVerbose(string.Format("Successfully published the resource to '{0}'", repoUri));
11311139
error = null;
11321140
success = true;
1133-
1141+
11341142
return success;
11351143
}
11361144

@@ -1154,7 +1162,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi
11541162

11551163
var networkCred = Credential == null ? _networkCredential : Credential.GetNetworkCredential();
11561164
string key;
1157-
1165+
11581166
if (packageSource == null)
11591167

11601168
{
@@ -1177,7 +1185,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi
11771185
isPasswordClearText: true,
11781186
String.Empty));
11791187
}
1180-
1188+
11811189
#endregion
11821190
}
11831191
}

src/code/UpdateModuleManifest.cs

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,14 @@ private void CreateModuleManifestHelper(Hashtable parsedMetadata, string resolve
668668
WriteVerbose($"Moving '{tmpModuleManifestPath}' to '{resolvedManifestPath}'");
669669
Utils.MoveFiles(tmpModuleManifestPath, resolvedManifestPath, overwrite: true);
670670
}
671+
catch (Exception e)
672+
{
673+
errorRecord = new ErrorRecord(
674+
e,
675+
"CreateModuleManifestFailed",
676+
ErrorCategory.InvalidOperation,
677+
this);
678+
}
671679
finally {
672680
// Clean up temp file if move fails
673681
if (File.Exists(tmpModuleManifestPath))
@@ -970,7 +978,7 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string
970978
"ErrorCreatingTempDir",
971979
ErrorCategory.InvalidData,
972980
this);
973-
981+
974982
return;
975983
}
976984

@@ -1007,7 +1015,7 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string
10071015

10081016
string privateDataString = GetPrivateDataString(tags, licenseUri, projectUri, iconUri, releaseNotes, prerelease, requireLicenseAcceptance, externalModuleDependencies);
10091017

1010-
// create new file in tmp path for updated module manifest (i.e updated with PrivateData entry)
1018+
// create new file in tmp path for updated module manifest (i.e updated with PrivateData entry)
10111019
string newTmpModuleManifestPath = System.IO.Path.Combine(tmpParentPath, "Updated" + System.IO.Path.GetFileName(resolvedManifestPath));
10121020
if (!TryCreateNewPsd1WithUpdatedPrivateData(privateDataString, tmpModuleManifestPath, newTmpModuleManifestPath, out errorRecord))
10131021
{
@@ -1020,6 +1028,14 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string
10201028
WriteVerbose($"Moving '{newTmpModuleManifestPath}' to '{resolvedManifestPath}'");
10211029
Utils.MoveFiles(newTmpModuleManifestPath, resolvedManifestPath, overwrite: true);
10221030
}
1031+
catch (Exception e)
1032+
{
1033+
errorRecord = new ErrorRecord(
1034+
e,
1035+
"CreateModuleManifestForWinPSFailed",
1036+
ErrorCategory.InvalidOperation,
1037+
this);
1038+
}
10231039
finally {
10241040
// Clean up temp file if move fails
10251041
if (File.Exists(tmpModuleManifestPath))
@@ -1043,7 +1059,7 @@ private string GetPrivateDataString(string[] tags, Uri licenseUri, Uri projectUr
10431059
{
10441060
/**
10451061
Example PrivateData
1046-
1062+
10471063
PrivateData = @{
10481064
PSData = @{
10491065
# Tags applied to this module. These help with module discovery in online galleries.
@@ -1069,15 +1085,15 @@ Example PrivateData
10691085
10701086
# External dependent modules of this module
10711087
ExternalModuleDependencies = @('ModuleDep1, 'ModuleDep2')
1072-
1088+
10731089
} # End of PSData hashtable
1074-
1090+
10751091
} # End of PrivateData hashtable
10761092
*/
10771093

10781094
string tagsString = string.Join(", ", tags.Select(item => "'" + item + "'"));
10791095
string tagLine = tags.Length != 0 ? $"Tags = @({tagsString})" : "# Tags = @()";
1080-
1096+
10811097
string licenseUriLine = licenseUri == null ? "# LicenseUri = ''" : $"LicenseUri = '{licenseUri.ToString()}'";
10821098
string projectUriLine = projectUri == null ? "# ProjectUri = ''" : $"ProjectUri = '{projectUri.ToString()}'";
10831099
string iconUriLine = iconUri == null ? "# IconUri = ''" : $"IconUri = '{iconUri.ToString()}'";
@@ -1089,7 +1105,7 @@ Example PrivateData
10891105

10901106
string externalModuleDependenciesString = string.Join(", ", externalModuleDependencies.Select(item => "'" + item + "'"));
10911107
string externalModuleDependenciesLine = externalModuleDependencies.Length == 0 ? "# ExternalModuleDependencies = @()" : $"ExternalModuleDependencies = @({externalModuleDependenciesString})";
1092-
1108+
10931109
string initialPrivateDataString = "PrivateData = @{" + System.Environment.NewLine + "PSData = @{" + System.Environment.NewLine;
10941110

10951111
string privateDataString = $@"
@@ -1157,7 +1173,7 @@ private bool TryCreateNewPsd1WithUpdatedPrivateData(string privateDataString, st
11571173
{
11581174
leftBracket--;
11591175
}
1160-
1176+
11611177
if (leftBracket == 0)
11621178
{
11631179
privateDataEndLine = i;
@@ -1173,7 +1189,7 @@ private bool TryCreateNewPsd1WithUpdatedPrivateData(string privateDataString, st
11731189
"PrivateDataEntryParsingError",
11741190
ErrorCategory.InvalidOperation,
11751191
this);
1176-
1192+
11771193
return false;
11781194
}
11791195

0 commit comments

Comments
 (0)