Skip to content
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ API between minor releases.

## [Unreleased]

### Fixed

- Save the requested report before publishing a downgraded RVT so the same output path can be retried after a report write failure.

## [0.7.0] - 2026-12-04

### Added
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ each step as the input for the next one.
Older Revit releases cannot represent every newer record. A conversion with
known omitted record owners requires `--allow-loss` and a JSON `--report`.
The report lists affected record owners and known project and analytical omissions.
When a report is requested, the CLI publishes the RVT after saving the report.
Review the report and open the output in the target Revit release before relying
on it. `--restore-legacy-analytics` applies only when writing Revit 2022 from a
Revit 2023 or later project. It requires an earlier Revit 2022 revision of the
Expand Down
20 changes: 15 additions & 5 deletions src/RvtIO.Cli/DowngradeCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ internal static class DowngradeCommand
internal const string ReportSchema = "rvtio-downgrade-check/1";
internal const string WriteReportSchema = "rvtio-downgrade/1";

private sealed class ReportWriteFailedException : Exception { }

private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
Expand Down Expand Up @@ -103,7 +105,13 @@ internal static int Run(string[] args, TextWriter output, TextWriter error)
try
{
written = DowngradeWriter.Write(source, profile, outputPath, rule, includeOmittedAnalytics: reportPath is not null,
restoreLegacyAnalytics: restoreLegacyAnalytics, allowLoss: allowLoss);
restoreLegacyAnalytics: restoreLegacyAnalytics, allowLoss: allowLoss,
beforePublish: reportPath is null ? null : prepared =>
{
if (WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, prepared),
RvtExitCodes.Success) != RvtExitCodes.Success)
throw new ReportWriteFailedException();
});
if (written.RestoredAnalyticalMembers is { } restored)
output.WriteLine($"Restored analytical members: {restored.Count.ToString(inv)}. Panels: {(written.RestoredAnalyticalPanels?.Count ?? 0).ToString(inv)}. Point supports: {(written.RestoredPointSupports?.Count ?? 0).ToString(inv)}. Line supports: {(written.RestoredLineSupports?.Count ?? 0).ToString(inv)}.");
if (written.RestoredAnalyticalOpenings is { Count: > 0 } openings)
Expand All @@ -113,6 +121,10 @@ internal static int Run(string[] args, TextWriter output, TextWriter error)
error.WriteLine($"warning: Downgrade omits {boundaries.ToString(inv)} boundary conditions. See omittedProjectElements in the write report.");
output.WriteLine($"Downgraded: {Path.GetFileName(written.OutputPath)} (release {written.SourceRelease} to {written.TargetRelease}, {written.EditedClasses.ToString(inv)} classes edited, {written.ReplacedStreams.ToString(inv)} streams replaced)");
}
catch (ReportWriteFailedException)
{
return RvtExitCodes.Usage;
}
catch (DowngradeRefusedException exception)
{
return End(error, reportPath, Refused, exception.Kind, exception.Message, sourceName, profileName, rule, outputPath);
Expand All @@ -137,10 +149,8 @@ internal static int Run(string[] args, TextWriter output, TextWriter error)
};
return WriteReport(error, reportPath, failed, RvtExitCodes.InputError);
}
if (!check)
return WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, written), RvtExitCodes.Success);
output.WriteLine("Check and write done" + (reportPath == null ? "." : $" except the report {reportPath}."));
return WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, written), RvtExitCodes.Success);
if (check) output.WriteLine("Check and write done.");
return RvtExitCodes.Success;
}

output.WriteLine("Check only: no file was written" + (reportPath == null ? "." : $" except the report {reportPath}."));
Expand Down
4 changes: 3 additions & 1 deletion src/RvtIO/Writing/ContainerRewriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,13 @@ internal static class ContainerRewriter
/// <paramref name="replacements"/> (its path, for example <c>Formats/Latest</c>; names compare without regard to case, as in the
/// container) holds the given bytes.</summary>
/// <param name="beforeCheck">Called with the path of the temporary file once it is written and before it is read back; tests change the file there.</param>
/// <param name="beforePublish">Called after verification, before the temporary file is moved to its final path.</param>
/// <exception cref="ArgumentException">A key names no stream of the source (it may name a storage), or two keys name the same stream.</exception>
/// <exception cref="IOException">The output exists (the source itself included), its folder is missing, the source is open for writing in
/// another process (Windows only), or a file cannot be read or written.</exception>
/// <exception cref="InvalidDataException">The source directory is damaged, or the written file differs from what was meant to be written.</exception>
internal static ContainerRewriteResult Rewrite(string sourcePath, string outputPath, IReadOnlyDictionary<string, byte[]> replacements,
Action<string>? beforeCheck = null)
Action<string>? beforeCheck = null, Action? beforePublish = null)
{
var replacementByName = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, bytes) in replacements)
Expand All @@ -81,6 +82,7 @@ internal static ContainerRewriteResult Rewrite(string sourcePath, string outputP
var result = WriteTemporary(sourcePath, temporary, replacementByName);
beforeCheck?.Invoke(temporary);
CheckWritten(temporary, result.Entries, result.RootStorage);
beforePublish?.Invoke();
File.Move(temporary, output, overwrite: false);
return result;
}
Expand Down
20 changes: 12 additions & 8 deletions src/RvtIO/Writing/DowngradeWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,22 @@ internal sealed record DowngradeWriteResult(

internal static DowngradeWriteResult Write(
string sourcePath, string profilePath, string outputPath, GuidRule rule, bool includeOmittedAnalytics = false,
bool restoreLegacyAnalytics = false, bool allowLoss = false)
bool restoreLegacyAnalytics = false, bool allowLoss = false, Action<DowngradeWriteResult>? beforePublish = null)
{
var planResult = DowngradePlanner.Plan(sourcePath, profilePath, rule);
if (restoreLegacyAnalytics && (planResult.SourceRelease < 2023 || planResult.TargetRelease != 2022))
throw new DowngradeRefusedException("unsupported-analytical-restore",
"Legacy analytical restoration requires a Revit 2023 or newer source and its historical Revit 2022 project as the target profile.");
int sourceWidth = SchemaRelease.IdWidth(planResult.SourceRelease)!.Value;
int targetWidth = SchemaRelease.IdWidth(planResult.TargetRelease)!.Value;
return Transcode(sourcePath, profilePath, outputPath, planResult, sourceWidth, targetWidth, includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss);
return Transcode(sourcePath, profilePath, outputPath, planResult, sourceWidth, targetWidth,
includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish);
}

private static DowngradeWriteResult Transcode(
string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult,
int sourceWidth, int targetWidth, bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss)
int sourceWidth, int targetWidth, bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss,
Action<DowngradeWriteResult>? beforePublish)
{
var plan = planResult.Plan;
SchemaDocument sourceDoc, profileDoc;
Expand Down Expand Up @@ -495,17 +497,19 @@ private static DowngradeWriteResult Transcode(
throw new DowngradeRefusedException("loss-not-allowed",
$"The conversion omits records for {omittedOwners.Count} owners. Use --allow-loss with --report to write the file and review the omissions.");

var rewrite = ContainerRewriter.Rewrite(sourcePath, outputPath, replacements,
temporary => Verify(temporary, planResult.TargetRelease, profileSchemaBytes));

return new DowngradeWriteResult(outputPath, planResult.SourceRelease, planResult.TargetRelease, plan.Edits.Count,
rewrite.Replaced, omittedProjectElements, omittedOwners.Order().ToArray(), includeOmittedAnalytics && analysis.Count != 0 ? analysis : null,
var result = new DowngradeWriteResult(outputPath, planResult.SourceRelease, planResult.TargetRelease, plan.Edits.Count,
replacements.Count, omittedProjectElements, omittedOwners.Order().ToArray(), includeOmittedAnalytics && analysis.Count != 0 ? analysis : null,
restoreLegacyAnalytics ? restored?.Members ?? [] : null, restoreLegacyAnalytics ? restored?.PointSupports ?? [] : null,
restoreLegacyAnalytics ? restored?.Panels ?? [] : null, restoreLegacyAnalytics ? restored?.Openings ?? [] : null,
restoreLegacyAnalytics ? restored?.LineSupports ?? [] : null,
restoreLegacyAnalytics ? restored?.AttachedNodes ?? [] : null, archivedEnergyAnalysisRecords,
restoreLegacyAnalytics ? restored?.LineLoads ?? [] : null);

ContainerRewriter.Rewrite(sourcePath, outputPath, replacements,
temporary => Verify(temporary, planResult.TargetRelease, profileSchemaBytes),
beforePublish is null ? null : () => beforePublish(result));
return result;

void Subtract(string name, int count)
{
if (count == 0 || omittedProjectElements is null) return;
Expand Down
28 changes: 28 additions & 0 deletions tests/RvtIO.Tests/DowngradeWriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -668,4 +668,32 @@ public void Cli_Output_CrossWidth_WritesFile_WithExit0()
var doc = RvtDocument.Open(output);
Assert.NotNull(doc.RawData);
}

[Fact]
public void Cli_LossReportFailure_LeavesNoOutput_AndCanBeRetried()
{
string source = Synthetic(2027, "source.rvt");
string profile = Synthetic(2020, "profile.rvt");
string output = P("output.rvt");
string reportDirectory = P("missing-dir");
string report = Path.Combine(reportDirectory, "loss.json");
string[] args = [source, "--target-profile", profile, "--output", output, "--allow-loss", "--report", report];
using var stdout = new StringWriter();
using var stderr = new StringWriter();

Assert.Equal(1, DowngradeCommand.Run(args, stdout, stderr));
Assert.Contains("the report cannot be written", stderr.ToString());
Assert.False(File.Exists(output));
Assert.DoesNotContain("Downgraded:", stdout.ToString());
Assert.Equal(2, Directory.EnumerateFileSystemEntries(_folder).Count());

Directory.CreateDirectory(reportDirectory);
Assert.Equal(0, DowngradeCommand.Run(args, stdout, stderr));
Assert.True(File.Exists(output));
Assert.Contains("Downgraded:", stdout.ToString());
using var doc = JsonDocument.Parse(File.ReadAllText(report));
Assert.Equal("ok", doc.RootElement.GetProperty("status").GetString());
Assert.Equal("output.rvt", doc.RootElement.GetProperty("output").GetProperty("file").GetString());
Assert.Contains("202", doc.RootElement.GetProperty("omittedRecordOwners").EnumerateArray().Select(owner => owner.GetString()));
}
}
Loading