diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ec408d..1cfd2cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ 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. +- `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 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..01b7906 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,46 @@ 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. + // The output being written, named in the error: the page and the --json file can fail in one run. + string target = outputPath; + 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."); + target = explicitJsonPath; + 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}' to '{target}': {Printable(ex.Message)}"); + return 3; } - if (serve) + if (serve && !StartServe(outputPath, servePort)) { - StartServe(outputPath, servePort); + return 5; } return ExitCode(diagnostics); @@ -281,7 +287,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 +321,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/src/IOViewer/Exporters/JsonViewerExporter.cs b/src/IOViewer/Exporters/JsonViewerExporter.cs index 078e74f..bb678d1 100644 --- a/src/IOViewer/Exporters/JsonViewerExporter.cs +++ b/src/IOViewer/Exporters/JsonViewerExporter.cs @@ -15,13 +15,22 @@ public static class JsonViewerExporter private static readonly JsonSerializerOptions CompactOptions = Options(indented: false); + /// + /// 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); ArgumentNullException.ThrowIfNull(filePath); + 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); - Export(doc, fs, indented); + 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 950be95..19031c5 100644 --- a/tests/IOViewer.Tests/JsonAndImportTests.cs +++ b/tests/IOViewer.Tests/JsonAndImportTests.cs @@ -82,6 +82,98 @@ 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 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 + { + 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 ee95a96..ff4b193 100644 --- a/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs +++ b/tests/IOViewer.Tests/ModelAndCliIntegrationTests.cs @@ -51,6 +51,84 @@ 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 inFile = Path.Combine(fileAsFolder, "viewer.html"); + (string[] Args, string Target)[] runs = + [ + ([obj, "-o", folderAsHtml], folderAsHtml), + ([obj, "-o", folderAsJson], folderAsJson), + ([obj, "-o", html, "--json", folderAsJson], folderAsJson), + ([obj, "-o", inFile], inFile), + ]; + foreach (var (args, target) in runs) + { + 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, whatever the exception says. + Assert.StartsWith($"Error: Failed to export '{obj}' to '{target}': ", 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() {