Skip to content
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

Workaround for NullReferenceException when extracting multiple 7zip archives simultaneously on PS 7.4.0 #89

Merged
merged 6 commits into from
Jan 7, 2024
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
2 changes: 1 addition & 1 deletion 7Zip4Powershell/7Zip4Powershell.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="JetBrains.Annotations" Version="2022.3.1" />
<PackageReference Include="JetBrains.Annotations" Version="2023.3.0" />
<PackageReference Include="PowerShellStandard.Library" Version="5.1.1" />
<PackageReference Include="Squid-Box.SevenZipSharp" Version="1.6.1.23" />
</ItemGroup>
Expand Down
38 changes: 18 additions & 20 deletions 7Zip4Powershell/Compress7Zip.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class Compress7Zip : ThreadedCmdlet {
public string Path { get; set; }

[Parameter(Position = 2, Mandatory = false, HelpMessage = "The filter to be applied if Path points to a directory")]
public string Filter { get; set; } = "*";
public string Filter { get; set; }

[Parameter(HelpMessage = "Output path for a compressed archive")]
public string OutputPath { get; set; }
Expand Down Expand Up @@ -230,17 +230,24 @@ public override void Execute() {
var archiveFileName = System.IO.Path.GetFullPath(System.IO.Path.Combine(outputPath, System.IO.Path.GetFileName(_cmdlet.ArchiveFileName)));

var activity = directoryOrFiles.Length > 1
? $"Compressing {directoryOrFiles.Length} Files to {archiveFileName}"
: $"Compressing {directoryOrFiles[0]} to {archiveFileName}";
? $"Compressing {directoryOrFiles.Length} files to \"{archiveFileName}\""
: $"Compressing \"{directoryOrFiles[0]}\" to \"{archiveFileName}\"";

var currentStatus = "Compressing";

// Reuse ProgressRecord instance insead of creating new one on each progress update
Progress = new ProgressRecord(Environment.CurrentManagedThreadId, activity, currentStatus) { PercentComplete = 0 };

compressor.FilesFound += (sender, args) =>
Write($"{args.Value} files found for compression");
compressor.Compressing += (sender, args) =>
WriteProgress(new ProgressRecord(0, activity, currentStatus) { PercentComplete = args.PercentDone });
compressor.Compressing += (sender, args) => {
Progress.PercentComplete = args.PercentDone;
WriteProgress(Progress);
};

compressor.FileCompressionStarted += (sender, args) => {
currentStatus = $"Compressing {args.FileName}";
Write($"Compressing {args.FileName}");
Write($"Compressing \"{args.FileName}\"");
};

if (directoryOrFiles.Any(path => new FileInfo(path).Exists)) {
Expand All @@ -253,28 +260,19 @@ public override void Execute() {
} else {
compressor.CompressFiles(archiveFileName, directoryOrFiles);
}
}
if (directoryOrFiles.Any(path => new DirectoryInfo(path).Exists)) {
} else if (directoryOrFiles.Any(path => new DirectoryInfo(path).Exists)) {
if (directoryOrFiles.Length > 1) {
throw new ArgumentException("Only one directory allowed as input");
}
var recursion = !_cmdlet.DisableRecursion.IsPresent;
if (_cmdlet.Filter != null) {
if (HasPassword) {
compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet._password, _cmdlet.Filter, recursion);
} else {
compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, null, _cmdlet.Filter, recursion);
}
var filter = string.IsNullOrWhiteSpace(_cmdlet.Filter) ? "*" : _cmdlet.Filter;
if (HasPassword) {
compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet._password, filter, recursion);
} else {
if (HasPassword) {
compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet._password, null, recursion);
} else {
compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, null, null, recursion);
}
compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, null, filter, recursion);
}
}

WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed });
Write("Compression finished");
}
}
Expand Down
18 changes: 11 additions & 7 deletions 7Zip4Powershell/Expand7Zip.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,23 +62,27 @@ public override void Execute() {
var targetPath = new FileInfo(Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.TargetPath)).FullName;
var archiveFileName = new FileInfo(Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.ArchiveFileName)).FullName;

var activity = $"Extracting {Path.GetFileName(archiveFileName)} to {targetPath}";
var activity = $"Extracting \"{Path.GetFileName(archiveFileName)}\" to \"{targetPath}\"";
var statusDescription = "Extracting";

Write($"Extracting archive {archiveFileName}");
WriteProgress(new ProgressRecord(0, activity, statusDescription) { PercentComplete = 0 });
Write($"Extracting archive \"{archiveFileName}\"");

// Reuse ProgressRecord instance insead of creating new one on each progress update
Progress = new ProgressRecord(Environment.CurrentManagedThreadId, activity, statusDescription) { PercentComplete = 0 };

using (var extractor = CreateExtractor(archiveFileName)) {
extractor.Extracting += (sender, args) =>
WriteProgress(new ProgressRecord(0, activity, statusDescription) { PercentComplete = args.PercentDone });
extractor.Extracting += (sender, args) => {
Progress.PercentComplete = args.PercentDone;
WriteProgress(Progress);
};

extractor.FileExtractionStarted += (sender, args) => {
statusDescription = $"Extracting file {args.FileInfo.FileName}";
statusDescription = $"Extracting file \"{args.FileInfo.FileName}\"";
Write(statusDescription);
};
extractor.ExtractArchive(targetPath);
}

WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed });
Write("Extraction finished");
}

Expand Down
19 changes: 15 additions & 4 deletions 7Zip4Powershell/ThreadedCmdlet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,36 @@ protected override void EndProcessing() {
foreach (var o in queue.GetConsumingEnumerable()) {
var record = o as ProgressRecord;
var errorRecord = o as ErrorRecord;

if (record != null) {
WriteProgress(record);
} else if (errorRecord != null) {
WriteError(errorRecord);
} else if (o is string) {
WriteVerbose((string) o);
} else if (o is string s) {
WriteVerbose(s);
} else {
WriteObject(o);
}
}

_thread.Join();

try {
worker.Progress.StatusDescription = "Finished";
worker.Progress.RecordType = ProgressRecordType.Completed;
WriteProgress(worker.Progress);
} catch (NullReferenceException) {
// Possible bug in PowerShell 7.4.0 leading to a null reference exception being thrown on ProgressPane completion
// This is not happening on PowerShell 5.1
}
}

private static Thread StartBackgroundThread(CmdletWorker worker) {
var thread = new Thread(() => {
try {
worker.Execute();
} catch (Exception ex) {
worker.Queue.Add(new ProgressRecord(0, "err01", "Exception") { RecordType = ProgressRecordType.Completed });
worker.Queue.Add(new ErrorRecord(ex, "err01", ErrorCategory.NotSpecified, worker));
worker.Queue.Add(new ErrorRecord(ex, "7Zip4PowerShellException", ErrorCategory.NotSpecified, worker));
}
finally {
worker.Queue.CompleteAdding();
Expand All @@ -59,6 +68,8 @@ protected override void StopProcessing() {
public abstract class CmdletWorker {
public BlockingCollection<object> Queue { get; set; }

public ProgressRecord Progress { get; set; }

protected void Write(string text) {
Queue.Add(text);
}
Expand Down