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 '