Skip to content

Bug fix for Publish-PSResource deleting a temp dir that contains a readonly file #543

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 7 commits into from
Nov 30, 2021
18 changes: 17 additions & 1 deletion src/code/PublishPSResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,23 @@ protected override void ProcessRecord()
}
finally {
WriteVerbose(string.Format("Deleting temporary directory '{0}'", outputDir));
Directory.Delete(outputDir, recursive:true);

try
{
Directory.Delete(outputDir, recursive: true);
}
catch (UnauthorizedAccessException)
{
// If an exception was thrown due to an access denied exception, attempt to change file attributes to normal
string[] filesLeftToDelete = Directory.GetFiles(outputDir);
foreach (var file in filesLeftToDelete)
{
File.SetAttributes(file, FileAttributes.Normal);
}

// Try to delete temp files again
Directory.Delete(outputDir, recursive: true);
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions test/PublishPSResource.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -278,4 +278,19 @@ Describe "Test Publish-PSResource" {
$expectedPath = Join-Path -Path $tmpPath -ChildPath "$script:PublishModuleName.$version.nupkg"
(Get-ChildItem $tmpPath).FullName | Should -Be $expectedPath
}

It "Publish a module and clean up properly when file in module is readonly" {
$version = "1.0.0"
New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module"

# Create a readonly file that will throw access denied error if deletion is attempted
$file = Join-Path -Path $script:PublishModuleBase -ChildPath "inaccessiblefile.txt"
New-Item $file -Itemtype file -Force
Set-ItemProperty -Path $file -Name IsReadOnly -Value $true

Publish-PSResource -Path $script:PublishModuleBase -Repository $testRepository2

$expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg"
(Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath
}
}