From d323e8dca719d9131540612dce564cf9d3d96190 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:18:16 +0300 Subject: [PATCH 1/3] Exit with code 3 when an output cannot be written and 5 when --serve fails An I/O or access error while writing the page, the JSON output or the --json file ended the tool with an unhandled exception; one handler around all exports now reports it and returns 3. A preview server that could not start or failed left the exit code at 0 (or 4); it now gives the new code 5, after the output is written. The help, the README and the changelog list the codes. --- CHANGELOG.md | 9 +++ README.md | 4 +- src/IOViewer.Cli/Program.cs | 58 +++++++------- .../ModelAndCliIntegrationTests.cs | 76 +++++++++++++++++++ 4 files changed, 120 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ec408d..22550e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ API between minor releases. ## [Unreleased] +### Fixed +- `ioviewer`: an output that cannot be written (a locked file, a read-only folder, a folder where the file should be or + a file where its folder should be) ends the run with `Error: Failed to export` and exit code 3 for the page, the + JSON output and the `--json` file alike. Before, only the page caught rejected data, and an I/O error ended the tool + with an unhandled exception. +- `ioviewer --serve`: when the preview server cannot start (a port in use or out of range) or fails while serving, the + tool exits with the new code 5 after printing the error; the output has been written. Before, it exited with 0, or 4 + for an engine error. + ## [0.3.0] - 2026-11-13 Version 0.3.0 builds the viewer on the scene model of the [IOScene](https://github.com/IOExtend/IOScene) package diff --git a/README.md b/README.md index 9fdcb68..b775a9f 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,9 @@ ioviewer model.glb -o model.json Diagnostics and progress go to standard error, including what IfcIO or RvtIO could not convert (one warning or error per kind, with its count). When the engine reported an error, elements may be missing: the output is still written and -the exit code is 4. Run `ioviewer --help` for the full list of options and exit codes. +the exit code is 4. An output that cannot be written gives exit code 3, and a `--serve` preview server that cannot start +or fails gives exit code 5 after the output is written; codes 3 and 5 take precedence over 4. Run `ioviewer --help` for +the full list of options and exit codes. ## Library diff --git a/src/IOViewer.Cli/Program.cs b/src/IOViewer.Cli/Program.cs index 1d3466d..dc50869 100644 --- a/src/IOViewer.Cli/Program.cs +++ b/src/IOViewer.Cli/Program.cs @@ -47,8 +47,10 @@ is reported as warnings or errors. 0 Success 1 Usage error (missing or invalid arguments) 2 File not found - 3 Data format error or parsing failure + 3 Data format error, parsing failure, or an output that cannot be written 4 Output written, but IfcIO or RvtIO reported an error: elements may be missing + 5 Output written, but the --serve preview server could not start or failed + Codes 3 and 5 take precedence over 4. """; public static int Main(string[] args) @@ -192,7 +194,6 @@ public static int Main(string[] args) doc.Title = customTitle; } - EnsureParentDirectory(outputPath); var options = new HtmlViewerOptions { Title = doc.Title, @@ -203,41 +204,43 @@ public static int Main(string[] args) IncludeTimeLiner = includeTimeLiner }; - if (outputPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) - { - JsonViewerExporter.Save(doc, outputPath); - Console.WriteLine($"Exported JSON snapshot to '{outputPath}' ({doc.Scene.Instances.Count} meshes, {doc.Scene.Elements.Count} elements) in {sw.ElapsedMilliseconds} ms."); - } - else + // Data the exporters reject, and an output file or folder that cannot be written, end the run with code 3. + try { - try + EnsureParentDirectory(outputPath); + if (outputPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) { - HtmlViewerExporter.Save(doc, outputPath, options); + JsonViewerExporter.Save(doc, outputPath); + Console.WriteLine($"Exported JSON snapshot to '{outputPath}' ({doc.Scene.Instances.Count} meshes, {doc.Scene.Elements.Count} elements) in {sw.ElapsedMilliseconds} ms."); } - catch (Exception ex) when (ex is InvalidDataException or ArgumentException) + else { - Console.Error.WriteLine($"Error: Failed to export '{inputPath}': {Printable(ex.Message)}"); - return 3; + HtmlViewerExporter.Save(doc, outputPath, options); + var fi = new FileInfo(outputPath); + Console.WriteLine($"Exported standalone 3D HTML viewer to '{outputPath}' ({fi.Length / 1024:N0} KB, {doc.Scene.Instances.Count} meshes) in {sw.ElapsedMilliseconds} ms."); + int undrawn = ViewerPayloadWriter.UndrawnInstances(doc.Scene); + if (undrawn > 0) + { + Console.Error.WriteLine($"Warning: {undrawn} meshes of lines, points or an unknown kind are not shown; the viewer draws triangles only."); + } } - var fi = new FileInfo(outputPath); - Console.WriteLine($"Exported standalone 3D HTML viewer to '{outputPath}' ({fi.Length / 1024:N0} KB, {doc.Scene.Instances.Count} meshes) in {sw.ElapsedMilliseconds} ms."); - int undrawn = ViewerPayloadWriter.UndrawnInstances(doc.Scene); - if (undrawn > 0) + + if (!string.IsNullOrEmpty(explicitJsonPath)) { - Console.Error.WriteLine($"Warning: {undrawn} meshes of lines, points or an unknown kind are not shown; the viewer draws triangles only."); + EnsureParentDirectory(explicitJsonPath); + JsonViewerExporter.Save(doc, explicitJsonPath); + Console.WriteLine($"Exported JSON snapshot to '{explicitJsonPath}'."); } } - - if (!string.IsNullOrEmpty(explicitJsonPath)) + catch (Exception ex) when (ex is InvalidDataException or ArgumentException or IOException or UnauthorizedAccessException) { - EnsureParentDirectory(explicitJsonPath); - JsonViewerExporter.Save(doc, explicitJsonPath); - Console.WriteLine($"Exported JSON snapshot to '{explicitJsonPath}'."); + Console.Error.WriteLine($"Error: Failed to export '{inputPath}': {Printable(ex.Message)}"); + return 3; } - if (serve) + if (serve && !StartServe(outputPath, servePort)) { - StartServe(outputPath, servePort); + return 5; } return ExitCode(diagnostics); @@ -281,7 +284,8 @@ internal static string Printable(string text) => string.Concat(text.EnumerateRunes().Select(r => Rune.IsControl(r) || Rune.GetUnicodeCategory(r) == UnicodeCategory.Format ? "?" : r.ToString())); - private static void StartServe(string htmlPath, int port) + // Serves the page until the process is stopped; false when the server could not start or failed. + private static bool StartServe(string htmlPath, int port) { string url = $"http://localhost:{port}/"; Console.WriteLine($"Starting local HTTP preview server at {url}..."); @@ -314,7 +318,9 @@ private static void StartServe(string htmlPath, int port) catch (Exception ex) { Console.Error.WriteLine($"HTTP Server error: {ex.Message}"); + return false; } + return true; } private static void EnsureParentDirectory(string path) diff --git a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs index ee95a96..b3133d3 100644 --- a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs +++ b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs @@ -51,6 +51,82 @@ f 3 1 4 } } + private const string Triangle = """ + v 0 0 0 + v 1 0 0 + v 0 1 0 + f 1 2 3 + """; + + [Fact] + public void Cli_AnOutputThatCannotBeWritten_GivesExitCode3() + { + string root = Path.Combine(Path.GetTempPath(), $"test_cli_{Guid.NewGuid():N}"); + string obj = Path.Combine(root, "model.obj"); + string html = Path.Combine(root, "viewer.html"); + string folderAsHtml = Path.Combine(root, "folder.html"); + string folderAsJson = Path.Combine(root, "folder.json"); + string fileAsFolder = Path.Combine(root, "file"); + using var errors = new StringWriter(); + var origErr = Console.Error; + try + { + Directory.CreateDirectory(folderAsHtml); + Directory.CreateDirectory(folderAsJson); + File.WriteAllText(obj, Triangle); + File.WriteAllText(fileAsFolder, ""); + Console.SetError(errors); + + // The page, the JSON output, the --json file and the output folder: each where a file or folder cannot be written. + string[][] runs = + [ + [obj, "-o", folderAsHtml], + [obj, "-o", folderAsJson], + [obj, "-o", html, "--json", folderAsJson], + [obj, "-o", Path.Combine(fileAsFolder, "viewer.html")], + ]; + foreach (var run in runs) + { + errors.GetStringBuilder().Clear(); + int code = Program.Main(run); + Assert.True(code == 3, $"{string.Join(' ', run)}: exit code {code}, {errors}"); + Assert.StartsWith("Error: Failed to export", errors.ToString()); + } + } + finally + { + Console.SetError(origErr); + if (Directory.Exists(root)) Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void Cli_ServeThatCannotStart_GivesExitCode5AfterThePageIsWritten() + { + string obj = Path.Combine(Path.GetTempPath(), $"test_model_{Guid.NewGuid():N}.obj"); + string html = Path.ChangeExtension(obj, ".html"); + using var errors = new StringWriter(); + var origErr = Console.Error; + try + { + File.WriteAllText(obj, Triangle); + Console.SetError(errors); + + // No server listens on a port above 65535, so the preview server fails before it opens a browser. + int code = Program.Main([obj, "-o", html, "--serve", "70000"]); + + Assert.Equal(5, code); + Assert.True(File.Exists(html)); + Assert.Contains("HTTP Server error", errors.ToString()); + } + finally + { + Console.SetError(origErr); + if (File.Exists(obj)) File.Delete(obj); + if (File.Exists(html)) File.Delete(html); + } + } + [Fact] public void Cli_ConvertObjToJson_CreatesValidJsonSnapshot() { From 058686e86f27a6ed3fea1b3a63f236ec9eb12333 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:01:58 +0300 Subject: [PATCH 2/3] Keep an existing JSON file when its export fails JsonViewerExporter.Save opened the target with FileMode.Create before it serialised, so data the serializer rejects emptied an existing file. It now writes a temporary file beside the target and moves it over the target when complete, as IOScene's SceneJson.Save does. The exception of a failed move does not name the file, so the export error of ioviewer names the output that failed. --- CHANGELOG.md | 6 +++++ src/IOViewer.Cli/Program.cs | 5 +++- src/IOViewer/Exporters/JsonViewerExporter.cs | 20 +++++++++++++--- tests/IOViewer.Tests/JsonAndImportTests.cs | 23 +++++++++++++++++++ .../ModelAndCliIntegrationTests.cs | 21 +++++++++-------- 5 files changed, 62 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22550e7..0ee6af9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,12 @@ API between minor releases. - `ioviewer --serve`: when the preview server cannot start (a port in use or out of range) or fails while serving, the tool exits with the new code 5 after printing the error; the output has been written. Before, it exited with 0, or 4 for an engine error. +- `JsonViewerExporter.Save` writes the file beside the target and moves it over the target when complete, so data the + serializer rejects (such as a non-finite coordinate) or a failed write leaves an existing file as it was; before, the + file was emptied first (the HTML export already kept the file when it rejected the data). It now needs permission to + create a file in the target's folder, and it replaces the target: a symbolic link is replaced, not written through. + The JSON outputs of `ioviewer` (`-o *.json`, `--json`) get this too, and its export error names the output that + failed: `Error: Failed to export '' to '': ...`. ## [0.3.0] - 2026-11-13 diff --git a/src/IOViewer.Cli/Program.cs b/src/IOViewer.Cli/Program.cs index dc50869..2ca6d93 100644 --- a/src/IOViewer.Cli/Program.cs +++ b/src/IOViewer.Cli/Program.cs @@ -205,6 +205,8 @@ public static int Main(string[] args) }; // Data the exporters reject, and an output file or folder that cannot be written, end the run with code 3. + // The output being written, named in the error: an exception of a file move does not name it. + string target = outputPath; try { EnsureParentDirectory(outputPath); @@ -227,6 +229,7 @@ public static int Main(string[] args) if (!string.IsNullOrEmpty(explicitJsonPath)) { + target = explicitJsonPath; EnsureParentDirectory(explicitJsonPath); JsonViewerExporter.Save(doc, explicitJsonPath); Console.WriteLine($"Exported JSON snapshot to '{explicitJsonPath}'."); @@ -234,7 +237,7 @@ public static int Main(string[] args) } catch (Exception ex) when (ex is InvalidDataException or ArgumentException or IOException or UnauthorizedAccessException) { - Console.Error.WriteLine($"Error: Failed to export '{inputPath}': {Printable(ex.Message)}"); + Console.Error.WriteLine($"Error: Failed to export '{inputPath}' to '{target}': {Printable(ex.Message)}"); return 3; } diff --git a/src/IOViewer/Exporters/JsonViewerExporter.cs b/src/IOViewer/Exporters/JsonViewerExporter.cs index 078e74f..febce9a 100644 --- a/src/IOViewer/Exporters/JsonViewerExporter.cs +++ b/src/IOViewer/Exporters/JsonViewerExporter.cs @@ -15,13 +15,27 @@ public static class JsonViewerExporter private static readonly JsonSerializerOptions CompactOptions = Options(indented: false); + /// + /// Writes viewer JSON to a file. The file is written beside the target first and moved over it when complete, so a + /// failed write, such as data the serializer rejects, leaves an existing file as it was. It needs permission to + /// create a file in the target's folder, and it replaces the target: a symbolic link is replaced, not written through. + /// public static void Save(ViewerDocument doc, string filePath, bool indented = true) { ArgumentNullException.ThrowIfNull(doc); - ArgumentNullException.ThrowIfNull(filePath); + ArgumentException.ThrowIfNullOrEmpty(filePath); - using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); - Export(doc, fs, indented); + string temporary = filePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + using (var fs = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) Export(doc, fs, indented); + File.Move(temporary, filePath, overwrite: true); + } + catch + { + if (File.Exists(temporary)) File.Delete(temporary); + throw; + } } public static void Export(ViewerDocument doc, Stream stream, bool indented = true) diff --git a/tests/IOViewer.Tests/JsonAndImportTests.cs b/tests/IOViewer.Tests/JsonAndImportTests.cs index 950be95..4fc4258 100644 --- a/tests/IOViewer.Tests/JsonAndImportTests.cs +++ b/tests/IOViewer.Tests/JsonAndImportTests.cs @@ -82,6 +82,29 @@ public void ViewerJson_CompactAndFile_ReadBack() } } + [Fact] + public void ViewerJson_SaveOfDataTheSerializerRejects_LeavesAnExistingFileAsItWas() + { + var scene = new SceneDocument(); + scene.AddMesh("bad", [new Vector3d(double.PositiveInfinity, 0, 0), new Vector3d(1, 0, 0), new Vector3d(0, 1, 0)], [0, 1, 2], null); + string folder = Path.Combine(Path.GetTempPath(), $"ioviewer_test_{Guid.NewGuid():N}"); + string path = Path.Combine(folder, "viewer.json"); + try + { + Directory.CreateDirectory(folder); + File.WriteAllText(path, "previous"); + + Assert.ThrowsAny(() => JsonViewerExporter.Save(new ViewerDocument(scene), path)); + + Assert.Equal("previous", File.ReadAllText(path)); + Assert.Equal(path, Assert.Single(Directory.GetFiles(folder))); // no temporary file is left behind + } + finally + { + if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true); + } + } + [Theory] [InlineData("""{"Kind":"ioviewer","Format":3,"Scene":{"Kind":"ioscene","Format":1}}""", "IOViewer JSON format 3 is newer than this version reads")] [InlineData("""{"Format":2,"Kind":"ioviewer","Scene":{"Kind":"ioscene","Format":99}}""", "IOScene format 99 is not supported")] diff --git a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs index b3133d3..82e5f79 100644 --- a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs +++ b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs @@ -78,19 +78,22 @@ public void Cli_AnOutputThatCannotBeWritten_GivesExitCode3() Console.SetError(errors); // The page, the JSON output, the --json file and the output folder: each where a file or folder cannot be written. - string[][] runs = + string inFile = Path.Combine(fileAsFolder, "viewer.html"); + (string[] Args, string Target)[] runs = [ - [obj, "-o", folderAsHtml], - [obj, "-o", folderAsJson], - [obj, "-o", html, "--json", folderAsJson], - [obj, "-o", Path.Combine(fileAsFolder, "viewer.html")], + ([obj, "-o", folderAsHtml], folderAsHtml), + ([obj, "-o", folderAsJson], folderAsJson), + ([obj, "-o", html, "--json", folderAsJson], folderAsJson), + ([obj, "-o", inFile], inFile), ]; - foreach (var run in runs) + foreach (var (args, target) in runs) { errors.GetStringBuilder().Clear(); - int code = Program.Main(run); - Assert.True(code == 3, $"{string.Join(' ', run)}: exit code {code}, {errors}"); - Assert.StartsWith("Error: Failed to export", errors.ToString()); + int code = Program.Main(args); + Assert.True(code == 3, $"{string.Join(' ', args)}: exit code {code}, {errors}"); + // The error names the output that failed, also when the exception of a file move does not. + Assert.StartsWith($"Error: Failed to export '{obj}' to '{target}': ", errors.ToString()); + Assert.Empty(Directory.GetFiles(root, "*.tmp")); } } finally From 58670c834c9c0e998043f76d2deab5a16c7294ad Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:26:08 +0300 Subject: [PATCH 3/3] Rewrite the JSON file in place after a serialization that writes nothing Writing a temporary file and moving it over the target replaced the target's own permissions with those a new file in the folder gets, and appended 37 characters to the name, so a valid long name failed. JsonViewerExporter.Save now serializes once into Stream.Null, which throws for data the serializer rejects before the file is opened, and then rewrites the file in place as before. Tests pin that a file keeps its permissions and that the longest valid name is written. --- CHANGELOG.md | 11 ++- src/IOViewer.Cli/Program.cs | 2 +- src/IOViewer/Exporters/JsonViewerExporter.cs | 25 +++---- tests/IOViewer.Tests/JsonAndImportTests.cs | 71 ++++++++++++++++++- .../ModelAndCliIntegrationTests.cs | 3 +- 5 files changed, 87 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ee6af9..1cfd2cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,12 +14,11 @@ API between minor releases. - `ioviewer --serve`: when the preview server cannot start (a port in use or out of range) or fails while serving, the tool exits with the new code 5 after printing the error; the output has been written. Before, it exited with 0, or 4 for an engine error. -- `JsonViewerExporter.Save` writes the file beside the target and moves it over the target when complete, so data the - serializer rejects (such as a non-finite coordinate) or a failed write leaves an existing file as it was; before, the - file was emptied first (the HTML export already kept the file when it rejected the data). It now needs permission to - create a file in the target's folder, and it replaces the target: a symbolic link is replaced, not written through. - The JSON outputs of `ioviewer` (`-o *.json`, `--json`) get this too, and its export error names the output that - failed: `Error: Failed to export '' to '': ...`. +- `JsonViewerExporter.Save` serializes the data once before it opens the file, so data the serializer rejects (such as + a non-finite coordinate) leaves an existing file as it was, as the HTML export already did; before, the file was + emptied first. The file is still rewritten in place and keeps its permissions. The JSON outputs of `ioviewer` + (`-o *.json`, `--json`) get this too, and its export error names the output that failed: + `Error: Failed to export '' to '': ...`. ## [0.3.0] - 2026-11-13 diff --git a/src/IOViewer.Cli/Program.cs b/src/IOViewer.Cli/Program.cs index 2ca6d93..01b7906 100644 --- a/src/IOViewer.Cli/Program.cs +++ b/src/IOViewer.Cli/Program.cs @@ -205,7 +205,7 @@ public static int Main(string[] args) }; // Data the exporters reject, and an output file or folder that cannot be written, end the run with code 3. - // The output being written, named in the error: an exception of a file move does not name it. + // The output being written, named in the error: the page and the --json file can fail in one run. string target = outputPath; try { diff --git a/src/IOViewer/Exporters/JsonViewerExporter.cs b/src/IOViewer/Exporters/JsonViewerExporter.cs index febce9a..bb678d1 100644 --- a/src/IOViewer/Exporters/JsonViewerExporter.cs +++ b/src/IOViewer/Exporters/JsonViewerExporter.cs @@ -16,26 +16,21 @@ public static class JsonViewerExporter private static readonly JsonSerializerOptions CompactOptions = Options(indented: false); /// - /// Writes viewer JSON to a file. The file is written beside the target first and moved over it when complete, so a - /// failed write, such as data the serializer rejects, leaves an existing file as it was. It needs permission to - /// create a file in the target's folder, and it replaces the target: a symbolic link is replaced, not written through. + /// Writes viewer JSON to a file. The data is serialized once before the file is opened, so data the serializer + /// rejects, such as a non-finite coordinate, leaves an existing file as it was. The file is then rewritten in place + /// and keeps its permissions. /// public static void Save(ViewerDocument doc, string filePath, bool indented = true) { ArgumentNullException.ThrowIfNull(doc); - ArgumentException.ThrowIfNullOrEmpty(filePath); + ArgumentNullException.ThrowIfNull(filePath); - string temporary = filePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; - try - { - using (var fs = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) Export(doc, fs, indented); - File.Move(temporary, filePath, overwrite: true); - } - catch - { - if (File.Exists(temporary)) File.Delete(temporary); - throw; - } + var file = ViewerJsonFile.From(doc); + var options = indented ? DefaultOptions : CompactOptions; + // A pass that writes nothing: the serializer throws here, before the target is truncated, as it would below. + JsonSerializer.Serialize(Stream.Null, file, options); + using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); + JsonSerializer.Serialize(fs, file, options); } public static void Export(ViewerDocument doc, Stream stream, bool indented = true) diff --git a/tests/IOViewer.Tests/JsonAndImportTests.cs b/tests/IOViewer.Tests/JsonAndImportTests.cs index 4fc4258..19031c5 100644 --- a/tests/IOViewer.Tests/JsonAndImportTests.cs +++ b/tests/IOViewer.Tests/JsonAndImportTests.cs @@ -97,7 +97,76 @@ public void ViewerJson_SaveOfDataTheSerializerRejects_LeavesAnExistingFileAsItWa Assert.ThrowsAny(() => JsonViewerExporter.Save(new ViewerDocument(scene), path)); Assert.Equal("previous", File.ReadAllText(path)); - Assert.Equal(path, Assert.Single(Directory.GetFiles(folder))); // no temporary file is left behind + Assert.Equal(path, Assert.Single(Directory.GetFiles(folder))); // no other file is created + } + finally + { + if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true); + } + } + + [Fact] + public void ViewerJson_Save_RewritesAnExistingFileInPlace_KeepingItsPermissions() + { + string folder = Path.Combine(Path.GetTempPath(), $"ioviewer_test_{Guid.NewGuid():N}"); + string path = Path.Combine(folder, "viewer.json"); + try + { + Directory.CreateDirectory(folder); + File.WriteAllText(path, "previous"); + string before = Restrict(path); + + JsonViewerExporter.Save(SampleDocument(), path); + + Assert.Equal(before, Permissions(path)); + Assert.StartsWith("{", File.ReadAllText(path), StringComparison.Ordinal); + } + finally + { + if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true); + } + + // Permissions a new file in the folder never gets: only the current user, not inherited from the folder (Windows); + // 0700 (Unix: a new file is created 0666 under the umask, so it never has an execute bit). + static string Restrict(string file) + { + if (OperatingSystem.IsWindows()) + { + var security = new System.Security.AccessControl.FileSecurity(); + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule( + System.Security.Principal.WindowsIdentity.GetCurrent().User!, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); + new FileInfo(file).SetAccessControl(security); + } + else + { + File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + return Permissions(file); + } + + static string Permissions(string file) => OperatingSystem.IsWindows() + ? new FileInfo(file).GetAccessControl().GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.Access) + : File.GetUnixFileMode(file).ToString(); + } + + [Fact] + public void ViewerJson_Save_WritesAnyValidFileName() + { + string folder = Path.Combine(Path.GetTempPath(), $"ioviewer_test_{Guid.NewGuid():N}"); + // 255 characters, the longest valid name: no suffix fits on it, such as that of a temporary file beside it. + string path = Path.Combine(folder, new string('n', 250) + ".json"); + try + { + Directory.CreateDirectory(folder); + File.WriteAllText(path, "previous"); + + JsonViewerExporter.Save(SampleDocument(), path); + + Assert.StartsWith("{", File.ReadAllText(path), StringComparison.Ordinal); + Assert.Equal(path, Assert.Single(Directory.GetFiles(folder))); } finally { diff --git a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs index 82e5f79..ff4b193 100644 --- a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs +++ b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs @@ -91,9 +91,8 @@ public void Cli_AnOutputThatCannotBeWritten_GivesExitCode3() errors.GetStringBuilder().Clear(); int code = Program.Main(args); Assert.True(code == 3, $"{string.Join(' ', args)}: exit code {code}, {errors}"); - // The error names the output that failed, also when the exception of a file move does not. + // The error names the output that failed, whatever the exception says. Assert.StartsWith($"Error: Failed to export '{obj}' to '{target}': ", errors.ToString()); - Assert.Empty(Directory.GetFiles(root, "*.tmp")); } } finally