|
| 1 | +[Command( |
| 2 | + Description = "Rewrites a System.IO.Packaging file so the same source package always produces byte-identical output.")] |
| 3 | +public partial class ConvertCommand : ICommand |
| 4 | +{ |
| 5 | + // Every System.IO.Packaging format the library is known to handle: NuGet packages, the Office |
| 6 | + // Open XML documents, and the VSIX container. |
| 7 | + static string[] defaultPatterns = |
| 8 | + [ |
| 9 | + "*.nupkg", |
| 10 | + "*.snupkg", |
| 11 | + "*.vsix", |
| 12 | + "*.docx", |
| 13 | + "*.docm", |
| 14 | + "*.dotx", |
| 15 | + "*.xlsx", |
| 16 | + "*.xlsm", |
| 17 | + "*.xltx", |
| 18 | + "*.pptx", |
| 19 | + "*.pptm", |
| 20 | + "*.potx" |
| 21 | + ]; |
| 22 | + |
| 23 | + [CommandParameter( |
| 24 | + 0, |
| 25 | + Name = "path", |
| 26 | + Description = "Package file, or directory containing packages, to convert. Converted in place unless --target is used.")] |
| 27 | + public required string Input { get; set; } |
| 28 | + |
| 29 | + [CommandOption( |
| 30 | + "target", |
| 31 | + 't', |
| 32 | + Description = "Write results here instead of modifying the input in place. An output file path when the input is a file, otherwise a directory mirroring the input tree.")] |
| 33 | + public string? Target { get; set; } |
| 34 | + |
| 35 | + [CommandOption( |
| 36 | + "pattern", |
| 37 | + 'p', |
| 38 | + Description = "Search patterns applied when the input is a directory. Defaults to every known package extension.")] |
| 39 | + public string[] Patterns { get; set; } = defaultPatterns; |
| 40 | + |
| 41 | + [CommandOption( |
| 42 | + "recursive", |
| 43 | + 'r', |
| 44 | + Description = "Recurse into subdirectories when the input is a directory.")] |
| 45 | + public bool Recursive { get; set; } |
| 46 | + |
| 47 | + [CommandOption( |
| 48 | + "check", |
| 49 | + Description = "Report which packages are not already deterministic without writing anything. Exits with code 1 if any are found.")] |
| 50 | + public bool Check { get; set; } |
| 51 | + |
| 52 | + [CommandOption( |
| 53 | + "continue-on-error", |
| 54 | + Description = "Keep processing the remaining files after a failure, then exit with code 1.")] |
| 55 | + public bool ContinueOnError { get; set; } |
| 56 | + |
| 57 | + [CommandOption( |
| 58 | + "quiet", |
| 59 | + 'q', |
| 60 | + Description = "Suppress per file and summary output. Errors are still written.")] |
| 61 | + public bool Quiet { get; set; } |
| 62 | + |
| 63 | + public async ValueTask ExecuteAsync(IConsole console) |
| 64 | + { |
| 65 | + if (Check && |
| 66 | + Target != null) |
| 67 | + { |
| 68 | + throw new CommandException("--check does not write anything, so it cannot be combined with --target."); |
| 69 | + } |
| 70 | + |
| 71 | + if (Patterns.Length == 0) |
| 72 | + { |
| 73 | + throw new CommandException("--pattern requires at least one value."); |
| 74 | + } |
| 75 | + |
| 76 | + var jobs = FileResolver.Resolve(Input, Target, Patterns, Recursive); |
| 77 | + if (jobs.Count == 0) |
| 78 | + { |
| 79 | + throw new CommandException($"No files matching {string.Join(", ", Patterns)} found in: {Input}"); |
| 80 | + } |
| 81 | + |
| 82 | + var cancel = console.RegisterCancellationHandler(); |
| 83 | + var changed = 0; |
| 84 | + var failed = 0; |
| 85 | + |
| 86 | + foreach (var job in jobs) |
| 87 | + { |
| 88 | + try |
| 89 | + { |
| 90 | + if (await Handle(console, job, cancel)) |
| 91 | + { |
| 92 | + changed++; |
| 93 | + } |
| 94 | + } |
| 95 | + catch (Exception exception) |
| 96 | + when (exception is not OperationCanceledException) |
| 97 | + { |
| 98 | + if (!ContinueOnError) |
| 99 | + { |
| 100 | + throw new CommandException($"{Relative(job.Source)}: {exception.Message}", innerException: exception); |
| 101 | + } |
| 102 | + |
| 103 | + failed++; |
| 104 | + await console.Error.WriteLineAsync($"failed: {Relative(job.Source)}: {exception.Message}"); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + await WriteSummary(console, jobs.Count, changed, failed); |
| 109 | + } |
| 110 | + |
| 111 | + // Returns whether converting altered the package. |
| 112 | + async Task<bool> Handle(IConsole console, FileJob job, Cancel cancel) |
| 113 | + { |
| 114 | + var source = await File.ReadAllBytesAsync(job.Source, cancel); |
| 115 | + |
| 116 | + // Read fully into memory first: an in place run overwrites the file the conversion read from. |
| 117 | + using var sourceStream = new MemoryStream(source, writable: false); |
| 118 | + using var targetStream = await DeterministicPackage.ConvertAsync(sourceStream, cancel); |
| 119 | + |
| 120 | + var converted = targetStream.ToArray(); |
| 121 | + var isChanged = !converted.AsSpan().SequenceEqual(source); |
| 122 | + |
| 123 | + if (Check) |
| 124 | + { |
| 125 | + if (isChanged) |
| 126 | + { |
| 127 | + await Write(console, $"not deterministic: {Relative(job.Source)}"); |
| 128 | + } |
| 129 | + |
| 130 | + return isChanged; |
| 131 | + } |
| 132 | + |
| 133 | + // An unchanged package is left alone on an in place run rather than rewritten with the same |
| 134 | + // bytes, so its timestamp is not disturbed. A separate target always has to be written. |
| 135 | + if (isChanged || |
| 136 | + !job.IsInPlace) |
| 137 | + { |
| 138 | + var directory = Path.GetDirectoryName(job.Target); |
| 139 | + if (directory != null) |
| 140 | + { |
| 141 | + Directory.CreateDirectory(directory); |
| 142 | + } |
| 143 | + |
| 144 | + await File.WriteAllBytesAsync(job.Target, converted, cancel); |
| 145 | + } |
| 146 | + |
| 147 | + var status = isChanged ? "converted" : "unchanged"; |
| 148 | + if (job.IsInPlace) |
| 149 | + { |
| 150 | + await Write(console, $"{status}: {Relative(job.Source)}"); |
| 151 | + } |
| 152 | + else |
| 153 | + { |
| 154 | + await Write(console, $"{status}: {Relative(job.Source)} -> {Relative(job.Target)}"); |
| 155 | + } |
| 156 | + |
| 157 | + return isChanged; |
| 158 | + } |
| 159 | + |
| 160 | + async Task WriteSummary(IConsole console, int total, int changed, int failed) |
| 161 | + { |
| 162 | + if (Check) |
| 163 | + { |
| 164 | + if (changed > 0 || |
| 165 | + failed > 0) |
| 166 | + { |
| 167 | + throw new CommandException($"{Count(total)} checked, {changed} not deterministic{(failed > 0 ? $", {failed} failed" : null)}."); |
| 168 | + } |
| 169 | + |
| 170 | + await Write(console, $"{Count(total)} checked, all deterministic."); |
| 171 | + return; |
| 172 | + } |
| 173 | + |
| 174 | + await Write(console, $"{Count(total)} processed, {changed} converted."); |
| 175 | + |
| 176 | + if (failed > 0) |
| 177 | + { |
| 178 | + throw new CommandException($"{Count(failed)} failed."); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + Task Write(IConsole console, string message) |
| 183 | + { |
| 184 | + if (Quiet) |
| 185 | + { |
| 186 | + return Task.CompletedTask; |
| 187 | + } |
| 188 | + |
| 189 | + return console.Output.WriteLineAsync(message); |
| 190 | + } |
| 191 | + |
| 192 | + static string Count(int value) => value == 1 ? "1 file" : $"{value} files"; |
| 193 | + |
| 194 | + static string Relative(string path) => Path.GetRelativePath(Directory.GetCurrentDirectory(), path); |
| 195 | +} |
0 commit comments