Skip to content

Commit eb70046

Browse files
adityapatwardhanalerickson
authored andcommitted
Ensure that exception is not swallowed by finally block (#1569)
1 parent 7098286 commit eb70046

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)
@@ -802,7 +812,7 @@ private Hashtable BeginPackageInstall(
802812
if (_packagesOnMachine.Contains(currPkgNameVersion))
803813
{
804814
_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");
805-
815+
806816
// Remove from tracking list of packages to install.
807817
_pkgNamesToInstall.RemoveAll(x => x.Equals(pkgToInstall.Name, StringComparison.InvariantCultureIgnoreCase));
808818

@@ -1168,7 +1178,7 @@ private bool TrySaveNupkgToTempPath(
11681178

11691179
/// <summary>
11701180
/// Extracts files from .nupkg
1171-
/// Similar functionality as System.IO.Compression.ZipFile.ExtractToDirectory,
1181+
/// Similar functionality as System.IO.Compression.ZipFile.ExtractToDirectory,
11721182
/// but while ExtractToDirectory cannot overwrite files, this method can.
11731183
/// </summary>
11741184
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
@@ -488,6 +488,14 @@ out string[] _
488488
return;
489489
}
490490
}
491+
catch (Exception e)
492+
{
493+
ThrowTerminatingError(new ErrorRecord(
494+
e,
495+
"PublishPSResourceError",
496+
ErrorCategory.NotSpecified,
497+
this));
498+
}
491499
finally
492500
{
493501
WriteVerbose(string.Format("Deleting temporary directory '{0}'", outputDir));
@@ -789,7 +797,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash)
789797
if (!parsedMetadataHash.ContainsKey("requiredmodules"))
790798
{
791799
return null;
792-
}
800+
}
793801
LanguagePrimitives.TryConvertTo<object[]>(parsedMetadataHash["requiredmodules"], out object[] requiredModules);
794802

795803
// Required modules can be:
@@ -822,7 +830,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash)
822830
dependenciesHash.Add(moduleName, string.Empty);
823831
}
824832
}
825-
var externalModuleDeps = parsedMetadataHash.ContainsKey("ExternalModuleDependencies") ?
833+
var externalModuleDeps = parsedMetadataHash.ContainsKey("ExternalModuleDependencies") ?
826834
parsedMetadataHash["ExternalModuleDependencies"] : null;
827835

828836
if (externalModuleDeps != null && LanguagePrimitives.TryConvertTo<string[]>(externalModuleDeps, out string[] externalModuleNames))
@@ -1113,7 +1121,7 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o
11131121
WriteVerbose(string.Format("Successfully published the resource to '{0}'", repoUri));
11141122
error = null;
11151123
success = true;
1116-
1124+
11171125
return success;
11181126
}
11191127

@@ -1137,7 +1145,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi
11371145

11381146
var networkCred = Credential == null ? _networkCredential : Credential.GetNetworkCredential();
11391147
string key;
1140-
1148+
11411149
if (packageSource == null)
11421150

11431151
{
@@ -1160,7 +1168,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi
11601168
isPasswordClearText: true,
11611169
String.Empty));
11621170
}
1163-
1171+
11641172
#endregion
11651173
}
11661174
}

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)