#[cfg(test)]
use std::process::Command;
use std::{
env, fs,
io::{self, Write},
path::{Path, PathBuf},
};
use ast_merge::{
MergeResult, ProfilePromotionEvaluation, ProfilePromotionStatus,
ProfileSelectionEnforcementMode, ProfileSelectionRequirement,
evaluate_profile_selection_requirement, initial_profile_promotion_policy,
};
use ast_merge_git::{Merge3Request, merge3};
use go_merge::{GoDialect, merge_go};
use plain_merge::merge_text;
use serde_json::json;
mod benchmark_adapter;
mod build_info;
mod conflict_review;
mod external_command;
mod git_install;
mod path_safety;
mod staged_file;
mod typed_driver;
const EXIT_SUCCESS: i32 = 0;
const EXIT_UNRESOLVED_CONFLICT: i32 = 1;
const EXIT_USER_ERROR: i32 = 2;
const EXIT_INTERNAL_ERROR: i32 = 3;
#[derive(Debug)]
struct MergeDriverOptions {
ancestor: String,
current: String,
other: String,
path_name: Option<String>,
output: Option<String>,
strict: bool,
fallback: String,
check_only: bool,
exit_code: bool,
report_path: Option<String>,
profile_id: Option<String>,
profile_report: bool,
require_profile_status: Option<String>,
provider_id: Option<String>,
backend_id: Option<String>,
family: Option<String>,
dialect: Option<String>,
required_capabilities: Vec<String>,
conflict_policy: Option<String>,
fallback_explicit: bool,
}
#[derive(Debug, Default)]
struct PathSettings {
language: Option<String>,
conflict_marker_size: usize,
profile_id: Option<String>,
require_profile_status: Option<String>,
}
#[derive(Debug, Default)]
struct DiffDriverOptions {
git_protocol: bool,
path_name: Option<String>,
old_path: String,
new_path: String,
provider_id: Option<String>,
backend_id: Option<String>,
profile_id: Option<String>,
family: Option<String>,
dialect: Option<String>,
required_capabilities: Vec<String>,
require_profile_status: Option<String>,
report_path: Option<String>,
json: bool,
exit_code: bool,
}
#[derive(Debug)]
struct ConflictDiffOptions {
path_name: Option<String>,
file_path: String,
exit_code: bool,
json: bool,
}
#[derive(Debug)]
struct GitInstallOptions {
scope: GitInstallScope,
profile: GitInstallProfile,
check: bool,
undo: bool,
dry_run: bool,
json: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum GitInstallScope {
Local,
Global,
IncludeFile,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum GitInstallProfile {
SemanticDiff,
BuiltinDiff,
}
#[derive(Debug)]
struct MergeDriverResult {
ok: bool,
diagnostics: Vec<ast_merge::Diagnostic>,
output: Option<String>,
change_classifications: Vec<ast_merge_git::ChangeClassification>,
owned_regions: Vec<ast_merge_git::OwnedRegionReport>,
render_report: Option<ast_merge_git::Merge3RenderReport>,
profile: Option<ast_merge_git::Merge3Profile>,
reparse_after_render: Option<bool>,
formatting_preservation: Option<ast_merge_git::FormattingPreservation>,
secondary_formatting_metrics: Option<ast_merge_git::SecondaryFormattingMetrics>,
default_driver_evaluation: Option<ast_merge_git::DefaultDriverEvaluation>,
}
fn main() {
let native_args = env::args_os().skip(1).collect::<Vec<_>>();
if let Some(code) =
external_command::dispatch(&native_args, env!("CARGO_BIN_NAME") == "smorg-rs")
{
std::process::exit(code);
}
let args =
match native_args.into_iter().map(|arg| arg.into_string()).collect::<Result<Vec<_>, _>>() {
Ok(args) => args,
Err(_) => {
eprintln!("smorg: built-in command arguments must be UTF-8");
std::process::exit(EXIT_USER_ERROR);
}
};
let mut stdout = io::stdout();
let mut stderr = io::stderr();
std::process::exit(run(&args, &mut stdout, &mut stderr));
}
fn run(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
let Some(command) = args.first() else {
print_usage(stderr);
return EXIT_USER_ERROR;
};
match command.as_str() {
"--version" => run_version(&args[1..], stdout, stderr),
"benchmark-provider-merge3" => benchmark_adapter::run_merge3_files(&args[1..], stderr),
"benchmark-provider-diff" => benchmark_adapter::run_diff_files(&args[1..], stdout, stderr),
"benchmark-provider-merge2" => {
benchmark_adapter::run_merge2_files(&args[1..], stdout, stderr)
}
"benchmark-provider-session" => run_benchmark_provider_session(stdout, stderr),
"merge-driver" => run_merge_driver(&args[1..], stdout, stderr),
"diff-driver" => run_diff_driver(&args[1..], stdout, stderr),
"conflicts" => run_conflicts(&args[1..], stdout, stderr),
"languages" => run_languages(&args[1..], stdout, stderr),
"git" => run_git(&args[1..], stdout, stderr),
"help" | "-h" | "--help" => {
print_usage(stdout);
EXIT_SUCCESS
}
_ if args.len() >= 4 => benchmark_adapter::run_merge3_files(args, stderr),
_ => {
let _ = writeln!(stderr, "unknown command {command:?}");
print_usage(stderr);
EXIT_USER_ERROR
}
}
}
fn print_usage(out: &mut dyn Write) {
let _ = writeln!(out, "smorg: StructuredMerge kernel CLI (compatibility alias: smorg-rs)");
let _ = writeln!(out, "Both executable names accept the commands below.");
let _ = writeln!(out, "Version identity: smorg --version [--json]");
let _ = writeln!(out, "External dispatch: smorg NAME ARGS... executes smorg-NAME on PATH.");
let _ = writeln!(
out,
"Explicit benchmark merge: smorg benchmark-provider-merge3 BASE OURS THEIRS PATH"
);
let _ = writeln!(
out,
"Unlabelled positional benchmark arguments remain supported only by smorg-rs."
);
let _ = writeln!(out, "usage: smorg-rs benchmark-provider-session");
let _ = writeln!(out, " smorg-rs benchmark-provider-merge2 INCOMING CURRENT PATH");
let _ = writeln!(out, " smorg-rs benchmark-provider-diff BEFORE AFTER PATH");
let _ = writeln!(
out,
"usage: smorg-rs merge-driver [--path-name PATH] [--output PATH] [--report PATH] [--strict] [--fallback=none|line|local|full-file] %O %A %B [%P]"
);
let _ = writeln!(
out,
" smorg-rs merge-driver --ancestor %O --current %A --other %B --path-name %P"
);
let _ = writeln!(out, " smorg-rs diff-driver [--path-name PATH] OLD NEW");
let _ = writeln!(
out,
"Typed diff: --provider ID --backend kernel.tslp.LANGUAGE --profile ID [--json] [--report FILE] [--exit-code]"
);
let _ = writeln!(
out,
"Typed merge lane: --provider ID --backend kernel.tslp.LANGUAGE --profile ID"
);
let _ = writeln!(
out,
" [--family FAMILY] [--dialect DIALECT] [--require-capability NAME] (repeatable)"
);
let _ = writeln!(out, " [--conflict-policy leave-ours|write] [--check-only [--exit-code]]");
let _ = writeln!(
out,
" Cached grammars only; no fallback; 8 MiB aggregate input limit. No typed default selection yet."
);
let _ = writeln!(
out,
" smorg-rs diff-driver PATH OLD-FILE OLD-HEX OLD-MODE NEW-FILE NEW-HEX NEW-MODE [OLD-PREFIX NEW-PREFIX]"
);
let _ = writeln!(
out,
" smorg-rs conflicts diff [--path-name PATH] [--exit-code] [--json] FILE"
);
let _ = writeln!(out, " smorg-rs languages --gitattributes");
let _ = writeln!(
out,
" smorg-rs git install [--scope local|global|include-file] [--profile semantic-diff|builtin-diff] [--check] [--undo] [--dry-run] [--json]"
);
}
fn run_version(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
if !args.is_empty() && args != ["--json"] {
let _ = writeln!(stderr, "--version accepts only an optional --json flag");
return EXIT_USER_ERROR;
}
let manifest = match structuredmerge_core::capability_manifest(
Vec::new(),
structuredmerge_core::ParseLimits {
max_batch_items: 1,
max_input_bytes: 1,
max_nodes: 1,
max_diagnostics: 1,
timeout_millis: None,
},
) {
Ok(manifest) => manifest,
Err(error) => {
let _ = writeln!(stderr, "cannot obtain linked kernel identity: {error}");
return EXIT_INTERNAL_ERROR;
}
};
let result = if args.is_empty() {
writeln!(
stdout,
"{} {} (kernel {})",
env!("CARGO_BIN_NAME"),
env!("CARGO_PKG_VERSION"),
manifest.kernel_version
)
} else {
let value = json!({
"schema": "structuredmerge.cli-version/v1",
"executable": env!("CARGO_BIN_NAME"),
"package": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
"kernel_version": manifest.kernel_version,
"cli_contract": "structuredmerge.cli/v1",
"build": build_info::value(),
"compiled_providers": structuredmerge_core::artifact_inventory::compiled_provider_inventory(),
});
serde_json::to_writer(&mut *stdout, &value)
.map_err(io::Error::other)
.and_then(|()| writeln!(stdout))
};
if let Err(error) = result {
let _ = writeln!(stderr, "cannot write version identity: {error}");
EXIT_INTERNAL_ERROR
} else {
EXIT_SUCCESS
}
}
fn run_benchmark_provider_session(stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
let stdin = io::stdin();
let mut input = io::BufReader::new(stdin.lock());
match benchmark_adapter::serve(&mut input, stdout) {
Ok(()) => EXIT_SUCCESS,
Err(message) => {
let _ = writeln!(stderr, "smorg-rs: benchmark_adapter: {message}");
EXIT_INTERNAL_ERROR
}
}
}
fn run_merge_driver(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
if args == ["--help"] || args == ["-h"] {
print_usage(stdout);
return EXIT_SUCCESS;
}
let Some(options) = parse_merge_driver_options(args, stderr) else {
return EXIT_USER_ERROR;
};
if let Some(report) = &options.report_path {
match path_safety::report_is_distinct(
report,
&[
&options.ancestor,
&options.current,
&options.other,
options.output.as_deref().unwrap_or(&options.current),
],
) {
Ok(true) => {}
Ok(false) => {
let _ = writeln!(stderr, "report path aliases an input or merge output");
return EXIT_USER_ERROR;
}
Err(error) => {
let _ = writeln!(stderr, "cannot validate report path: {error}");
return EXIT_USER_ERROR;
}
}
}
if options.provider_id.is_some()
|| options.backend_id.is_some()
|| options.family.is_some()
|| options.dialect.is_some()
|| !options.required_capabilities.is_empty()
|| options.conflict_policy.is_some()
|| options.profile_id.as_deref().is_some_and(|id| id.starts_with("kernel."))
{
return typed_driver::run_merge(&options, stderr);
}
let ancestor_source = match fs::read_to_string(&options.ancestor) {
Ok(source) => source,
Err(error) => {
let _ = writeln!(stderr, "read ancestor: {error}");
return EXIT_USER_ERROR;
}
};
let current_source = match fs::read_to_string(&options.current) {
Ok(source) => source,
Err(error) => {
let _ = writeln!(stderr, "read current: {error}");
return EXIT_USER_ERROR;
}
};
let other_source = match fs::read_to_string(&options.other) {
Ok(source) => source,
Err(error) => {
let _ = writeln!(stderr, "read other: {error}");
return EXIT_USER_ERROR;
}
};
let effective_path = options.effective_path();
let settings = load_path_settings(&effective_path);
let profile_id = options.profile_id.as_deref().or(settings.profile_id.as_deref());
let require_profile_status =
options.require_profile_status.as_deref().or(settings.require_profile_status.as_deref());
let profile_exit = report_and_enforce_profile(
profile_id,
options.profile_report,
require_profile_status,
stdout,
stderr,
);
if profile_exit != EXIT_SUCCESS {
return profile_exit;
}
let mut result = merge_by_path(
&effective_path,
settings.language.as_deref(),
settings.conflict_marker_size,
if options.strict { "none" } else { &options.fallback },
&ancestor_source,
¤t_source,
&other_source,
);
let mut fallbacks = Vec::new();
let language = normalize_language(settings.language.as_deref(), &effective_path);
if merge_driver_fallback_eligible(&result, &options, &language) {
(result, fallbacks) = apply_merge_fallbacks(
result,
&options.fallback,
settings.conflict_marker_size,
&ancestor_source,
¤t_source,
&other_source,
);
}
if !result.ok {
print_diagnostics(stderr, &result);
if result.output.is_none() && !options.strict && options.fallback != "none" {
fallbacks.push(json!({
"mode": "full_file",
"requested_mode": options.fallback,
"reason": fallback_reason(&result.diagnostics),
"applied": true
}));
result.output = Some(full_file_conflict_output(
settings.conflict_marker_size,
&ancestor_source,
¤t_source,
&other_source,
));
}
} else if result.output.is_none() {
let _ = writeln!(stderr, "merge completed without output");
return EXIT_INTERNAL_ERROR;
}
let exit_code = if !result.ok
|| (options.check_only
&& options.exit_code
&& result.output.as_deref() != Some(current_source.as_str()))
{
EXIT_UNRESOLVED_CONFLICT
} else {
EXIT_SUCCESS
};
let staged_output = if options.check_only {
None
} else if let Some(output) = &result.output {
let path = options.output.as_deref().unwrap_or(&options.current);
match staged_file::StagedFile::new(path, output.as_bytes()) {
Ok(staged) => Some(staged),
Err(error) => {
let _ = writeln!(stderr, "stage output: {error}");
return EXIT_INTERNAL_ERROR;
}
}
} else {
None
};
let staged_report = match stage_merge_driver_machine_report(
options.report_path.as_deref(),
&effective_path,
exit_code,
&fallbacks,
&result,
) {
Ok(staged) => staged,
Err(error) => {
let _ = writeln!(stderr, "stage report: {error}");
return EXIT_INTERNAL_ERROR;
}
};
if let Some(report) = staged_report {
if let Err(error) = report.commit() {
let _ = writeln!(stderr, "commit report: {error}");
return EXIT_INTERNAL_ERROR;
}
}
if let Some(output) = staged_output {
if let Err(error) = output.commit() {
let _ = writeln!(stderr, "commit output: {error}");
return EXIT_INTERNAL_ERROR;
}
}
exit_code
}
fn stage_merge_driver_machine_report(
report_path: Option<&str>,
path_name: &str,
exit_code: i32,
fallbacks: &[serde_json::Value],
result: &MergeDriverResult,
) -> io::Result<Option<staged_file::StagedFile>> {
let Some(report_path) = report_path else {
return Ok(None);
};
let report = json!({
"command": "merge-driver",
"path_name": path_name,
"ok": result.ok,
"exit_code": exit_code,
"fallbacks": fallbacks,
"change_classifications": result.change_classifications,
"owned_regions": result.owned_regions,
"render_report": result.render_report,
"reparse_after_render": result.reparse_after_render,
"formatting_preservation": result.formatting_preservation,
"secondary_formatting_metrics": result.secondary_formatting_metrics,
"default_driver_evaluation": result.default_driver_evaluation,
"profile": result.profile,
"diagnostics": result.diagnostics,
"output_commit_verified": false
});
let mut source = serde_json::to_vec_pretty(&report).map_err(io::Error::other)?;
source.push(b'\n');
staged_file::StagedFile::new(report_path, &source).map(Some)
}
fn fallback_reason(diagnostics: &[ast_merge::Diagnostic]) -> String {
diagnostics.first().map_or_else(
|| "structured_merge_failed".to_string(),
|diagnostic| match serde_json::to_value(diagnostic.category) {
Ok(serde_json::Value::String(category)) => category,
_ => "structured_merge_failed".to_string(),
},
)
}
fn full_file_conflict_output(
marker_size: usize,
ancestor_source: &str,
current_source: &str,
other_source: &str,
) -> String {
let marker_size = marker_size.max(1);
[
format!("{} ours", "<".repeat(marker_size)),
current_source.to_string(),
format!("{} base", "|".repeat(marker_size)),
ancestor_source.to_string(),
"=".repeat(marker_size),
other_source.to_string(),
format!("{} theirs", ">".repeat(marker_size)),
String::new(),
]
.join("\n")
}
fn parse_merge_driver_options(
args: &[String],
stderr: &mut dyn Write,
) -> Option<MergeDriverOptions> {
let mut ancestor = None;
let mut current = None;
let mut other = None;
let mut path_name = None;
let mut output = None;
let mut strict = false;
let mut fallback = "full-file".to_string();
let mut check_only = false;
let mut exit_code = false;
let mut report_path = None;
let mut profile_id = None;
let mut profile_report = false;
let mut require_profile_status = None;
let mut provider_id = None;
let mut backend_id = None;
let mut family = None;
let mut dialect = None;
let mut required_capabilities = Vec::new();
let mut conflict_policy = None;
let mut positionals = Vec::new();
let mut seen_options = std::collections::BTreeSet::new();
let mut index = 0;
while index < args.len() {
if args[index] == "--" {
positionals.extend(args[index + 1..].iter().cloned());
break;
}
if args[index].starts_with("--") {
let key = if args[index].starts_with("--fallback=") {
"--fallback"
} else {
args[index].as_str()
};
if key != "--require-capability" && !seen_options.insert(key) {
let _ = writeln!(stderr, "duplicate merge-driver option {key:?}");
return None;
}
}
if matches!(
args[index].as_str(),
"--ancestor"
| "--current"
| "--other"
| "--path-name"
| "--output"
| "--report"
| "--profile"
| "--require-profile-status"
| "--fallback"
| "--provider"
| "--backend"
| "--family"
| "--dialect"
| "--require-capability"
| "--conflict-policy"
) && args.get(index + 1).is_none_or(|value| value.is_empty() || value.starts_with("--"))
{
let _ = writeln!(stderr, "merge-driver option {:?} requires a value", args[index]);
return None;
}
match args[index].as_str() {
"--provider" => {
index += 1;
provider_id = args.get(index).cloned();
}
"--backend" => {
index += 1;
backend_id = args.get(index).cloned();
}
"--family" => {
index += 1;
family = args.get(index).cloned();
}
"--dialect" => {
index += 1;
dialect = args.get(index).cloned();
}
"--require-capability" => {
index += 1;
required_capabilities.push(args[index].clone());
}
"--conflict-policy" => {
index += 1;
conflict_policy = args.get(index).cloned();
}
"--ancestor" => {
index += 1;
ancestor = args.get(index).cloned();
}
"--current" => {
index += 1;
current = args.get(index).cloned();
}
"--other" => {
index += 1;
other = args.get(index).cloned();
}
"--path-name" => {
index += 1;
path_name = args.get(index).cloned();
}
"--output" => {
index += 1;
output = args.get(index).cloned();
}
"--report" => {
index += 1;
report_path = args.get(index).cloned();
}
"--strict" => strict = true,
"--check-only" => check_only = true,
"--exit-code" => exit_code = true,
"--profile" => {
index += 1;
profile_id = args.get(index).cloned();
}
"--profile-report" => profile_report = true,
"--require-profile-status" => {
index += 1;
require_profile_status = args.get(index).cloned();
}
value if value.starts_with("--fallback=") => {
fallback = value.trim_start_matches("--fallback=").to_string();
}
"--fallback" => {
index += 1;
fallback = args.get(index).cloned().unwrap_or_default();
}
value if value.starts_with("--") => {
let _ = writeln!(stderr, "unknown merge-driver option {value:?}");
return None;
}
value => positionals.push(value.to_string()),
}
index += 1;
}
let named_sources = ancestor.is_some() || current.is_some() || other.is_some();
if named_sources {
if ancestor.is_none() || current.is_none() || other.is_none() || !positionals.is_empty() {
let _ = writeln!(stderr, "provide all three named sources without positional sources");
return None;
}
} else {
if !(3..=4).contains(&positionals.len()) || positionals.iter().any(String::is_empty) {
let _ = writeln!(stderr, "merge-driver requires BASE OURS THEIRS and optional PATH");
return None;
}
if positionals.len() == 4 && path_name.is_some() {
let _ = writeln!(stderr, "logical path cannot be both positional and --path-name");
return None;
}
ancestor = positionals.first().cloned();
current = positionals.get(1).cloned();
other = positionals.get(2).cloned();
path_name = path_name.or_else(|| positionals.get(3).cloned());
}
if !["none", "line", "local", "full-file"].contains(&fallback.as_str()) {
let _ = writeln!(stderr, "unsupported fallback mode {fallback:?}");
return None;
}
Some(MergeDriverOptions {
ancestor: ancestor?,
current: current?,
other: other?,
path_name,
output,
strict,
fallback,
check_only,
exit_code,
report_path,
profile_id,
profile_report,
require_profile_status,
provider_id,
backend_id,
family,
dialect,
required_capabilities,
conflict_policy,
fallback_explicit: seen_options.contains("--fallback"),
})
}
fn report_and_enforce_profile(
profile_id: Option<&str>,
profile_report: bool,
require_status: Option<&str>,
stdout: &mut dyn Write,
stderr: &mut dyn Write,
) -> i32 {
if profile_id.is_none() && require_status.is_none() && !profile_report {
return EXIT_SUCCESS;
}
let profile_id = profile_id.unwrap_or(ast_merge::PROMOTION_PROFILE_JSON_KEYED_OBJECT);
let evaluation = ProfilePromotionEvaluation {
profile_id: profile_id.to_string(),
status: ProfilePromotionStatus::Available,
blocking_reasons: vec![
"profile promotion evidence is not loaded by this CLI command".to_string(),
],
diagnostics: vec![],
};
let minimum_profile_status = match require_status {
Some("recommended") => ProfilePromotionStatus::Recommended,
Some("default") => ProfilePromotionStatus::Default,
Some("available") | None => ProfilePromotionStatus::Available,
Some(value) => {
let _ = writeln!(stderr, "unsupported required profile status {value:?}");
return EXIT_USER_ERROR;
}
};
let requirement = ProfileSelectionRequirement {
profile_id: profile_id.to_string(),
promotion_policy_id: initial_profile_promotion_policy().policy_id,
minimum_profile_status,
enforcement_mode: if require_status.is_some() {
ProfileSelectionEnforcementMode::Required
} else {
ProfileSelectionEnforcementMode::Advisory
},
};
let decision = evaluate_profile_selection_requirement(&requirement, None, &evaluation);
if profile_report {
let _ = writeln!(stdout, "{}", serde_json::to_string(&decision).unwrap());
}
if !decision.allowed {
let _ = writeln!(stderr, "{}", decision.blocking_reasons[0]);
return EXIT_USER_ERROR;
}
EXIT_SUCCESS
}
fn preflight_selection(
request: &structuredmerge_core::OperationRequest,
inventory: &structuredmerge_core::artifact_inventory::CompiledProviderInventory,
) -> Result<serde_json::Value, String> {
let provider = request
.provider_selection
.provider_id
.as_deref()
.ok_or_else(|| "preflight requires an explicit workflow provider ID".to_string())?;
let workflow = inventory
.workflows
.iter()
.find(|descriptor| descriptor.provider_id == provider)
.ok_or_else(|| format!("unknown workflow provider {provider}"))?;
let backend = request
.parser_selection
.backend
.as_deref()
.ok_or_else(|| "preflight requires an explicit parser backend".to_string())?;
let parser = inventory
.parsers
.iter()
.find(|descriptor| descriptor.id == backend)
.ok_or_else(|| format!("unknown parser provider {backend}"))?;
let language = parser
.languages
.first()
.cloned()
.ok_or_else(|| format!("parser provider {backend} declares no language"))?;
let parser_inventory =
structuredmerge_core::parser_registry_inventory().map_err(|error| error.to_string())?;
if !parser_inventory.providers.iter().any(|descriptor| descriptor.id == backend) {
structuredmerge_core::register_cached_language_pack_parser(
backend.to_string(),
language.clone(),
)
.map_err(|error| error.to_string())?;
}
let operation = match request.operation.kind() {
structuredmerge_core::OperationKind::Analyze => "analyze",
structuredmerge_core::OperationKind::Diff2 => "diff2",
structuredmerge_core::OperationKind::Merge2 => "merge2",
structuredmerge_core::OperationKind::Merge3 => "merge3",
};
let query = structuredmerge_core::MergeSelectionRequest {
provider_id: Some(provider.to_string()),
family: request
.provider_selection
.family
.clone()
.unwrap_or_else(|| workflow.family.clone()),
operation: operation.to_string(),
dialect: request.provider_selection.dialect.clone(),
profile: request.provider_selection.profile_id.clone(),
required_capabilities: request.provider_selection.required_capabilities.clone(),
required_preservation: vec![],
parser: structuredmerge_core::ParserSelectionRequest {
language,
dialect: request.provider_selection.dialect.clone(),
options: structuredmerge_core::ParseOptions::default(),
selection: structuredmerge_core::ParserSelection {
backend_id: Some(backend.to_string()),
preference: request.parser_selection.preference.clone(),
required_capabilities: request.parser_selection.required_capabilities.clone(),
},
},
};
let limits = structuredmerge_core::WorkflowLimits {
max_operations: 1,
max_request_bytes: 2 * 1024 * 1024,
max_response_bytes: 2 * 1024 * 1024,
parse: structuredmerge_core::ParseLimits {
max_batch_items: 1,
max_input_bytes: 8 * 1024 * 1024,
max_nodes: 1_000_000,
max_diagnostics: 1_000,
timeout_millis: Some(5_000),
},
};
let reports = structuredmerge_core::workflow_selection_reports(vec![query], limits)
.map_err(|error| error.to_string())?;
Ok(json!({
"provider_id": provider,
"parser_id": backend,
"selection": reports,
"registry_generation": structuredmerge_core::workflow_registry_inventory()
.map_err(|error| error.to_string())?
.generation,
"parser_registry_generation": structuredmerge_core::parser_registry_inventory()
.map_err(|error| error.to_string())?
.generation,
}))
}
fn run_languages(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
match args {
[arg] if arg == "--gitattributes" => {
for line in [
"*.go merge=smorg-rs diff=smorg-rs smorg.language=go",
"*.json merge=smorg-rs diff=smorg-rs smorg.language=json",
"*.jsonc merge=smorg-rs diff=smorg-rs smorg.language=jsonc",
] {
let _ = writeln!(stdout, "{line}");
}
EXIT_SUCCESS
}
[arg] if arg == "--json" => {
let inventory = structuredmerge_core::artifact_inventory::compiled_provider_inventory();
let value = json!({
"schema": "structuredmerge.cli-report/v1",
"command": "languages",
"cli": {
"executable": env!("CARGO_BIN_NAME"),
"package": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
"kernel_version": inventory.kernel_version,
"cli_contract": "structuredmerge.cli/v1",
},
"outcome": "clean",
"exit_code": EXIT_SUCCESS,
"operation_result": null,
"availability": {
"schema": "structuredmerge.cli-availability/v1",
"runtime_availability_checked": inventory.runtime_availability_checked,
"compiled_providers": inventory,
},
"conflict_review": null,
"git_install": null,
"output_commit_verified": false,
"diagnostics": [],
});
if let Err(error) = serde_json::to_writer(&mut *stdout, &value) {
let _ = writeln!(stderr, "cannot write languages report: {error}");
return EXIT_INTERNAL_ERROR;
}
if let Err(error) = writeln!(stdout) {
let _ = writeln!(stderr, "cannot write languages report: {error}");
return EXIT_INTERNAL_ERROR;
}
EXIT_SUCCESS
}
_ if args.first().is_some_and(|arg| arg == "--inspect") => {
let json_output = args.iter().any(|arg| arg == "--json");
let Some(provider_id) = args.get(1).filter(|id| !id.is_empty()) else {
let _ = writeln!(stderr, "languages --inspect requires a provider ID");
return EXIT_USER_ERROR;
};
let Some(kind_pos) = args.iter().position(|arg| arg == "--kind") else {
let _ = writeln!(stderr, "languages --inspect requires --kind parser|workflow");
return EXIT_USER_ERROR;
};
let Some(kind) = args.get(kind_pos + 1).map(String::as_str) else {
let _ = writeln!(stderr, "languages --inspect requires --kind parser|workflow");
return EXIT_USER_ERROR;
};
if !matches!(kind, "parser" | "workflow")
|| kind_pos != 2
|| args.iter().filter(|arg| arg.as_str() == "--kind").count() != 1
|| args.iter().filter(|arg| arg.as_str() == "--json").count() > 1
|| args.len() > kind_pos + 3
|| args.get(kind_pos + 2).is_some_and(|arg| arg != "--json")
{
let _ = writeln!(
stderr,
"languages --inspect syntax: --inspect ID --kind parser|workflow [--json]"
);
return EXIT_USER_ERROR;
}
let inventory = structuredmerge_core::artifact_inventory::compiled_provider_inventory();
let descriptor = match kind {
"parser" => inventory
.parsers
.iter()
.find(|descriptor| descriptor.id == *provider_id)
.map(|descriptor| json!(descriptor)),
"workflow" => inventory
.workflows
.iter()
.find(|descriptor| descriptor.provider_id == *provider_id)
.map(|descriptor| json!(descriptor)),
_ => unreachable!(),
};
let Some(descriptor) = descriptor else {
if json_output {
let value = json!({
"schema": "structuredmerge.cli-report/v1",
"command": "languages.inspect",
"cli": {
"executable": env!("CARGO_BIN_NAME"),
"package": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
"kernel_version": inventory.kernel_version,
"cli_contract": "structuredmerge.cli/v1",
},
"outcome": "error",
"exit_code": EXIT_USER_ERROR,
"operation_result": null,
"availability": null,
"conflict_review": null,
"git_install": null,
"output_commit_verified": false,
"diagnostics": [{"code": "provider.unknown", "message": format!("unknown {kind} provider {provider_id}")}],
});
let _ = serde_json::to_writer(&mut *stdout, &value);
let _ = writeln!(stdout);
} else {
let _ = writeln!(stderr, "unknown {kind} provider {provider_id}");
}
return EXIT_USER_ERROR;
};
if json_output {
let value = json!({
"schema": "structuredmerge.cli-report/v1",
"command": "languages.inspect",
"cli": {
"executable": env!("CARGO_BIN_NAME"),
"package": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
"kernel_version": inventory.kernel_version,
"cli_contract": "structuredmerge.cli/v1",
},
"outcome": "clean",
"exit_code": EXIT_SUCCESS,
"operation_result": null,
"availability": {
"schema": "structuredmerge.cli-availability/v1",
"runtime_availability_checked": false,
"state": "compiled",
"selectable": false,
"provider_kind": kind,
"provider_id": provider_id,
"descriptor": descriptor,
},
"conflict_review": null,
"git_install": null,
"output_commit_verified": false,
"diagnostics": [],
});
if serde_json::to_writer(&mut *stdout, &value).is_err() || writeln!(stdout).is_err()
{
let _ = writeln!(stderr, "cannot write provider inspection report");
return EXIT_INTERNAL_ERROR;
}
} else {
let _ = writeln!(
stdout,
"{kind} provider {provider_id}: compiled (runtime availability not checked)"
);
}
EXIT_SUCCESS
}
_ if args.first().is_some_and(|arg| arg == "--preflight") => {
let json_output = args.iter().any(|arg| arg == "--json");
if args.len() < 2
|| args.len() > 3
|| args.iter().filter(|arg| arg.as_str() == "--json").count() > 1
|| args.get(2).is_some_and(|arg| arg != "--json")
{
let _ = writeln!(stderr, "languages --preflight syntax: REQUEST.json [--json]");
return EXIT_USER_ERROR;
}
let request_path = &args[1];
const PREFLIGHT_INPUT_LIMIT: usize = 2 * 1024 * 1024;
let input = match fs::read(request_path) {
Ok(input) if input.len() <= PREFLIGHT_INPUT_LIMIT => input,
Ok(_) => {
if !json_output {
let _ = writeln!(stderr, "preflight request exceeds 2 MiB");
}
return EXIT_USER_ERROR;
}
Err(error) => {
if !json_output {
let _ = writeln!(stderr, "cannot read preflight request: {error}");
}
return EXIT_USER_ERROR;
}
};
let inventory = structuredmerge_core::artifact_inventory::compiled_provider_inventory();
let base_cli = || {
json!({
"executable": env!("CARGO_BIN_NAME"),
"package": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
"kernel_version": inventory.kernel_version,
"cli_contract": "structuredmerge.cli/v1",
})
};
let parsed = serde_json::from_slice::<structuredmerge_core::OperationRequest>(&input)
.map_err(|error| error.to_string());
let validated = parsed.and_then(|request| {
let selection_request = request.clone();
request
.validate(8 * 1024 * 1024, |_, _| {
Err("preflight requires inline source content or bytes".to_string())
})
.map(|_| selection_request)
.map_err(|error| error.to_string())
});
let (outcome, exit_code, diagnostic, preflight_validated, selection_checked, selection) =
match validated {
Ok(request) => match preflight_selection(&request, &inventory) {
Ok(selection) => (
"unsupported",
EXIT_USER_ERROR,
json!({"code": "provider.runtime_unavailable", "message": "provider selection was evaluated, but runtime availability is not authenticated; preflight cannot authorize execution"}),
true,
true,
Some(selection),
),
Err(error) => (
"unsupported",
EXIT_USER_ERROR,
json!({"code": "provider.selection_unavailable", "message": error}),
true,
true,
None,
),
},
Err(error) => (
"error",
EXIT_USER_ERROR,
json!({"code": "preflight.invalid_request", "message": error}),
false,
false,
None,
),
};
if json_output {
let value = json!({
"schema": "structuredmerge.cli-report/v1",
"command": "languages.preflight",
"cli": base_cli(),
"outcome": outcome,
"exit_code": exit_code,
"operation_result": null,
"availability": {
"schema": "structuredmerge.cli-availability/v1",
"runtime_availability_checked": false,
"state": "unavailable",
"selectable": false,
"preflight_validated": preflight_validated,
"selection_checked": selection_checked,
"request_path": request_path,
"registry_generation": null,
"provider_id": null,
"parser_id": null,
"selection": selection,
"diagnostics": [diagnostic.clone()],
},
"conflict_review": null,
"git_install": null,
"output_commit_verified": false,
"diagnostics": [diagnostic],
});
if serde_json::to_writer(&mut *stdout, &value).is_err() || writeln!(stdout).is_err()
{
let _ = writeln!(stderr, "cannot write preflight report");
return EXIT_INTERNAL_ERROR;
}
} else {
let _ = writeln!(stderr, "preflight {outcome}: {}", diagnostic["message"]);
}
exit_code
}
_ => {
let _ = writeln!(stderr, "languages accepts --json or --gitattributes");
EXIT_USER_ERROR
}
}
}
fn run_git(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
let Some(subcommand) = args.first() else {
return git_install_usage(stderr);
};
if subcommand != "install" {
return git_install_usage(stderr);
}
if args[1..] == ["--help"] || args[1..] == ["-h"] {
return if writeln!(stdout, "usage: smorg git install [--scope local|global|include-file] [--profile semantic-diff|builtin-diff] [--check|--undo] [--dry-run] [--json]").is_ok() { 0 } else { 3 };
}
let Some(options) = parse_git_install_options(&args[1..], stderr) else {
return EXIT_USER_ERROR;
};
git_install::run(&options, stdout, stderr)
}
fn git_install_usage(stderr: &mut dyn Write) -> i32 {
let _ = writeln!(
stderr,
"usage: smorg-rs git install [--scope local|global|include-file] [--profile semantic-diff|builtin-diff] [--check] [--undo] [--dry-run] [--json]"
);
EXIT_USER_ERROR
}
fn parse_git_install_options(args: &[String], stderr: &mut dyn Write) -> Option<GitInstallOptions> {
let mut options = GitInstallOptions {
scope: GitInstallScope::Local,
profile: GitInstallProfile::SemanticDiff,
check: false,
undo: false,
dry_run: false,
json: false,
};
let mut index = 0;
let mut seen = std::collections::BTreeSet::new();
while index < args.len() {
if !seen.insert(args[index].as_str()) {
let _ = writeln!(stderr, "duplicate git install option {:?}", args[index]);
return None;
}
match args[index].as_str() {
"--scope" => {
index += 1;
options.scope = match args.get(index).map(String::as_str) {
Some("local") => GitInstallScope::Local,
Some("global") => GitInstallScope::Global,
Some("include-file") => GitInstallScope::IncludeFile,
value => {
let _ = writeln!(stderr, "invalid git install scope {value:?}");
return None;
}
};
}
"--profile" => {
index += 1;
options.profile = match args.get(index).map(String::as_str) {
Some("semantic-diff") => GitInstallProfile::SemanticDiff,
Some("builtin-diff") => GitInstallProfile::BuiltinDiff,
value => {
let _ = writeln!(stderr, "invalid git install profile {value:?}");
return None;
}
};
}
"--check" => options.check = true,
"--undo" => options.undo = true,
"--dry-run" => options.dry_run = true,
"--json" => options.json = true,
value => {
let _ = writeln!(stderr, "unknown git install option {value:?}");
return None;
}
}
index += 1;
}
if options.check && (options.undo || options.dry_run) {
let _ = writeln!(stderr, "--check cannot be combined with --undo or --dry-run");
return None;
}
Some(options)
}
fn git_attribute_lines(profile: GitInstallProfile) -> Vec<String> {
match profile {
GitInstallProfile::SemanticDiff => semantic_git_attribute_lines(),
GitInstallProfile::BuiltinDiff => builtin_git_attribute_lines(),
}
}
fn semantic_git_attribute_lines() -> Vec<String> {
vec![
"*.go merge=smorg-rs diff=smorg-rs smorg.language=go".to_string(),
"*.json merge=smorg-rs diff=smorg-rs smorg.language=json".to_string(),
"*.jsonc merge=smorg-rs diff=smorg-rs smorg.language=jsonc".to_string(),
]
}
fn builtin_git_attribute_lines() -> Vec<String> {
vec![
"*.go diff=go".to_string(),
"*.json diff=json".to_string(),
"*.jsonc diff=json".to_string(),
]
}
fn forge_diagnostics() -> Vec<serde_json::Value> {
let mut diagnostic = typed_driver::adapter_diagnostic(
structuredmerge_core::PortableCategory::UnsupportedFeature,
"git.forge_ignores_external_diff_drivers",
"Git hosting forges generally ignore external diff drivers; install them locally.".into(),
);
diagnostic.severity = structuredmerge_core::DiagnosticSeverity::Warning;
diagnostic.blocking = false;
let mut value = serde_json::to_value(diagnostic).unwrap();
value["key"] = json!("forge_ignores_external_diff_drivers");
vec![value]
}
impl GitInstallScope {
fn as_str(self) -> &'static str {
match self {
GitInstallScope::Local => "local",
GitInstallScope::Global => "global",
GitInstallScope::IncludeFile => "include-file",
}
}
}
impl GitInstallProfile {
fn as_str(self) -> &'static str {
match self {
GitInstallProfile::SemanticDiff => "semantic-diff",
GitInstallProfile::BuiltinDiff => "builtin-diff",
}
}
}
fn run_diff_driver(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
if args == ["--help"] || args == ["-h"] {
print_usage(stdout);
return EXIT_SUCCESS;
}
let Some(options) = parse_diff_driver_options(args, stderr) else {
return EXIT_USER_ERROR;
};
if options.provider_id.is_some()
|| options.backend_id.is_some()
|| options.profile_id.is_some()
|| options.family.is_some()
|| options.dialect.is_some()
|| !options.required_capabilities.is_empty()
|| options.require_profile_status.is_some()
|| options.report_path.is_some()
|| options.json
|| options.exit_code
{
if let Some(report) = &options.report_path {
match path_safety::report_is_distinct(report, &[&options.old_path, &options.new_path]) {
Ok(true) => {}
result => {
let _ = writeln!(stderr, "unsafe diff report path: {result:?}");
return EXIT_USER_ERROR;
}
}
}
return typed_driver::run_diff(&options, stdout, stderr);
}
let old_source = match fs::read_to_string(&options.old_path) {
Ok(source) => source,
Err(error) => {
let _ = writeln!(stderr, "read old file: {error}");
return EXIT_USER_ERROR;
}
};
let new_source = match fs::read_to_string(&options.new_path) {
Ok(source) => source,
Err(error) => {
let _ = writeln!(stderr, "read new file: {error}");
return EXIT_USER_ERROR;
}
};
print_structured_diff(stdout, &options.effective_path(), &old_source, &new_source);
EXIT_SUCCESS
}
fn parse_diff_driver_options(args: &[String], stderr: &mut dyn Write) -> Option<DiffDriverOptions> {
let mut path_name = None;
let mut options = DiffDriverOptions::default();
let mut seen = std::collections::BTreeSet::new();
let mut positionals = Vec::new();
let mut index = 0;
while index < args.len() {
if args[index] == "--" {
positionals.extend(args[index + 1..].iter().cloned());
break;
}
let flag = args[index].as_str();
if flag.starts_with("--") && flag != "--require-capability" && !seen.insert(flag) {
let _ = writeln!(stderr, "duplicate diff-driver option {flag}");
return None;
}
if matches!(
flag,
"--provider"
| "--backend"
| "--profile"
| "--family"
| "--dialect"
| "--require-capability"
| "--require-profile-status"
| "--report"
) {
let Some(value) = args.get(index + 1).filter(|v| !v.is_empty() && !v.starts_with("--"))
else {
let _ = writeln!(stderr, "diff-driver option {flag} requires a value");
return None;
};
match flag {
"--provider" => options.provider_id = Some(value.clone()),
"--backend" => options.backend_id = Some(value.clone()),
"--profile" => options.profile_id = Some(value.clone()),
"--family" => options.family = Some(value.clone()),
"--dialect" => options.dialect = Some(value.clone()),
"--require-capability" => options.required_capabilities.push(value.clone()),
"--require-profile-status" => options.require_profile_status = Some(value.clone()),
"--report" => options.report_path = Some(value.clone()),
_ => unreachable!(),
}
index += 2;
continue;
}
match args[index].as_str() {
"--json" => options.json = true,
"--exit-code" => options.exit_code = true,
"--path-name" => {
if path_name.is_some()
|| args
.get(index + 1)
.is_none_or(|value| value.is_empty() || value.starts_with("--"))
{
let _ = writeln!(stderr, "diff-driver requires one nonempty --path-name value");
return None;
}
index += 1;
path_name = args.get(index).cloned();
}
value if value.starts_with("--") => {
let _ = writeln!(stderr, "unknown diff-driver option {value:?}");
return None;
}
value => positionals.push(value.to_string()),
}
index += 1;
}
match positionals.len() {
2 if positionals.iter().all(|value| !value.is_empty()) => Some(DiffDriverOptions {
path_name,
old_path: positionals[0].clone(),
new_path: positionals[1].clone(),
..options
}),
7 | 9
if path_name.is_none()
&& [0, 1, 4].iter().all(|index| !positionals[*index].is_empty()) =>
{
Some(DiffDriverOptions {
git_protocol: true,
path_name: path_name.or_else(|| Some(positionals[0].clone())),
old_path: positionals[1].clone(),
new_path: positionals[4].clone(),
..options
})
}
_ => {
let _ = writeln!(stderr, "diff-driver requires either 2, 7, or 9 positional arguments");
None
}
}
}
impl DiffDriverOptions {
fn effective_path(&self) -> String {
self.path_name.clone().unwrap_or_else(|| self.new_path.clone())
}
}
fn print_structured_diff(
stdout: &mut dyn Write,
path_name: &str,
old_source: &str,
new_source: &str,
) {
let _ = writeln!(stdout, "structured-diff {path_name}");
if old_source == new_source {
let _ = writeln!(stdout, "status unchanged");
return;
}
let _ = writeln!(stdout, "status changed");
let _ = writeln!(stdout, "old-lines {}", line_count(old_source));
let _ = writeln!(stdout, "new-lines {}", line_count(new_source));
print_structured_diff_review_hunk(stdout, path_name, old_source, new_source);
}
fn print_structured_diff_review_hunk(
stdout: &mut dyn Write,
path_name: &str,
old_source: &str,
new_source: &str,
) {
let old_lines = diff_source_lines(old_source);
let new_lines = diff_source_lines(new_source);
let _ = writeln!(stdout, "review-diff unified");
let _ = writeln!(stdout, "--- a/{path_name}");
let _ = writeln!(stdout, "+++ b/{path_name}");
let _ = writeln!(stdout, "@@ -1,{} +1,{} @@", old_lines.len(), new_lines.len());
for line in old_lines {
write_diff_line(stdout, "-", line);
}
for line in new_lines {
write_diff_line(stdout, "+", line);
}
}
fn diff_source_lines(source: &str) -> Vec<&str> {
if source.is_empty() { Vec::new() } else { source.split_inclusive('\n').collect() }
}
fn write_diff_line(stdout: &mut dyn Write, prefix: &str, line: &str) {
let _ = write!(stdout, "{prefix}{line}");
if !line.ends_with('\n') {
let _ = writeln!(stdout);
}
}
fn line_count(source: &str) -> usize {
if source.is_empty() {
0
} else if source.ends_with('\n') {
source.matches('\n').count()
} else {
source.matches('\n').count() + 1
}
}
fn run_conflicts(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
let Some(subcommand) = args.first() else {
let _ = writeln!(stderr, "conflicts requires a subcommand");
return EXIT_USER_ERROR;
};
match subcommand.as_str() {
"diff" => run_conflicts_diff(&args[1..], stdout, stderr),
_ => {
let _ = writeln!(stderr, "unknown conflicts subcommand {subcommand:?}");
EXIT_USER_ERROR
}
}
}
fn run_conflicts_diff(args: &[String], stdout: &mut dyn Write, stderr: &mut dyn Write) -> i32 {
if args == ["--help"] || args == ["-h"] {
return if writeln!(
stdout,
"usage: smorg conflicts diff [--path-name PATH] [--exit-code] [--json] FILE"
)
.is_ok()
{
0
} else {
3
};
}
let Some(options) = parse_conflicts_diff_options(args, stderr) else {
return EXIT_USER_ERROR;
};
conflict_review::run(&options, stdout, stderr)
}
fn parse_conflicts_diff_options(
args: &[String],
stderr: &mut dyn Write,
) -> Option<ConflictDiffOptions> {
let mut path_name = None;
let mut exit_code = false;
let mut json = false;
let mut seen = std::collections::BTreeSet::new();
let mut positionals = Vec::new();
let mut index = 0;
while index < args.len() {
if args[index] == "--" {
positionals.extend(args[index + 1..].iter().cloned());
break;
}
if args[index].starts_with("--") && !seen.insert(args[index].as_str()) {
let _ = writeln!(stderr, "duplicate conflicts diff option {:?}", args[index]);
return None;
}
match args[index].as_str() {
"--path-name" => {
index += 1;
if args.get(index).is_none_or(|value| value.is_empty() || value.starts_with("--")) {
let _ = writeln!(stderr, "--path-name requires a nonempty value");
return None;
}
path_name = args.get(index).cloned();
}
"--exit-code" => exit_code = true,
"--json" => json = true,
value if value.starts_with("--") => {
let _ = writeln!(stderr, "unknown conflicts diff option {value:?}");
return None;
}
value => positionals.push(value.to_string()),
}
index += 1;
}
if positionals.len() != 1 || positionals[0].is_empty() {
let _ = writeln!(stderr, "conflicts diff requires exactly one file path");
return None;
}
Some(ConflictDiffOptions { path_name, file_path: positionals[0].clone(), exit_code, json })
}
impl MergeDriverOptions {
fn effective_path(&self) -> String {
self.path_name.clone().unwrap_or_else(|| self.current.clone())
}
}
fn merge_by_path(
path_name: &str,
language: Option<&str>,
conflict_marker_size: usize,
fallback_policy: &str,
ancestor_source: &str,
current_source: &str,
other_source: &str,
) -> MergeDriverResult {
match normalize_language(language, path_name).as_str() {
"go" => merge_driver_result(merge_go(other_source, current_source, GoDialect::Go)),
"json" | "jsonc" | "json5" => merge3_result(merge3(&Merge3Request {
base_source: ancestor_source.to_string(),
ours_source: current_source.to_string(),
theirs_source: other_source.to_string(),
path_name: Some(path_name.to_string()),
language: Some(normalize_language(language, path_name)),
dialect: Some(normalize_language(language, path_name)),
profile_id: Some("json.keyed-object".to_string()),
fallback_policy: Some(fallback_policy.to_string()),
conflict_marker_size: Some(conflict_marker_size),
render_policy: Some("source_preserving_edits".to_string()),
})),
language => unsupported_language_result(language, path_name),
}
}
fn unsupported_language_result(language: &str, path_name: &str) -> MergeDriverResult {
merge_driver_result(MergeResult {
ok: false,
diagnostics: vec![ast_merge::Diagnostic {
severity: ast_merge::DiagnosticSeverity::Error,
category: ast_merge::DiagnosticCategory::UnsupportedFeature,
message: format!(
"no structured merge driver is configured for {language:?} at {path_name}"
),
path: None,
review: None,
}],
output: None,
policies: vec![],
})
}
fn has_structured_provider(language: &str) -> bool {
matches!(language, "go" | "json" | "jsonc" | "json5")
}
fn merge_driver_fallback_eligible(
result: &MergeDriverResult,
options: &MergeDriverOptions,
language: &str,
) -> bool {
!result.ok
&& !options.strict
&& options.fallback != "none"
&& !has_structured_provider(language)
}
fn apply_merge_fallbacks(
result: MergeDriverResult,
requested_mode: &str,
marker_size: usize,
ancestor_source: &str,
current_source: &str,
other_source: &str,
) -> (MergeDriverResult, Vec<serde_json::Value>) {
let reason = fallback_reason(&result.diagnostics);
let git = merge_git_file_fallback(marker_size, ancestor_source, current_source, other_source);
if git.output.is_some() {
let fallbacks = vec![json!({
"mode": "git_merge_file", "requested_mode": requested_mode,
"reason": reason, "applied": true
})];
return (merge_fallback_result(result, git), fallbacks);
}
let plain = merge_text(other_source, current_source);
if plain.ok && plain.output.is_some() {
let git_reason = fallback_reason(&git.diagnostics);
let fallbacks = vec![
json!({"mode": "git_merge_file", "requested_mode": requested_mode,
"reason": reason, "applied": false}),
json!({"mode": "plain_text", "requested_mode": requested_mode,
"reason": git_reason, "applied": true}),
];
return (merge_fallback_result(result, merge_driver_result(plain)), fallbacks);
}
(result, vec![])
}
fn merge_fallback_result(
original: MergeDriverResult,
fallback: MergeDriverResult,
) -> MergeDriverResult {
let mut diagnostics = original.diagnostics;
diagnostics.extend(fallback.diagnostics);
MergeDriverResult { diagnostics, ..fallback }
}
fn merge_git_file_fallback(
marker_size: usize,
ancestor_source: &str,
current_source: &str,
other_source: &str,
) -> MergeDriverResult {
let failure = |category: ast_merge::DiagnosticCategory, message: String| {
merge_driver_result(MergeResult {
ok: false,
diagnostics: vec![ast_merge::Diagnostic {
severity: ast_merge::DiagnosticSeverity::Error,
category,
message,
path: None,
review: None,
}],
output: None,
policies: vec![],
})
};
let directory = std::env::temp_dir().join(format!(
"smorg-merge-file-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_nanos())
));
if let Err(error) = fs::create_dir(&directory) {
return failure(ast_merge::DiagnosticCategory::UnsupportedFeature, error.to_string());
}
let result = (|| {
let files =
[("current", current_source), ("base", ancestor_source), ("other", other_source)]
.map(|(name, source)| (directory.join(name), source));
for (path, source) in &files {
fs::write(path, source)?;
}
std::process::Command::new("git")
.args(["merge-file", "-p", "-L", "ours", "-L", "base", "-L", "theirs"])
.arg(format!("--marker-size={marker_size}"))
.args(files.iter().map(|(path, _)| path))
.output()
})();
let _ = fs::remove_dir_all(&directory);
match result {
Ok(output) if output.status.code().is_some_and(|code| (0..=127).contains(&code)) => {
let clean = output.status.success();
let mut merged = merge_driver_result(MergeResult {
ok: clean,
diagnostics: vec![],
output: Some(String::from_utf8_lossy(&output.stdout).into_owned()),
policies: vec![],
});
if !clean {
merged.diagnostics.push(ast_merge::Diagnostic {
severity: ast_merge::DiagnosticSeverity::Error,
category: ast_merge::DiagnosticCategory::MergeConflict,
message: "git merge-file reported unresolved conflicts".to_string(),
path: None,
review: None,
});
}
merged
}
Ok(output) => failure(
ast_merge::DiagnosticCategory::UnsupportedFeature,
format!("git merge-file failed: {}", String::from_utf8_lossy(&output.stderr).trim()),
),
Err(error) => failure(ast_merge::DiagnosticCategory::UnsupportedFeature, error.to_string()),
}
}
fn merge_driver_result(result: MergeResult<String>) -> MergeDriverResult {
MergeDriverResult {
ok: result.ok,
diagnostics: result.diagnostics,
output: result.output,
change_classifications: vec![],
owned_regions: vec![],
render_report: None,
profile: None,
reparse_after_render: None,
formatting_preservation: None,
secondary_formatting_metrics: None,
default_driver_evaluation: None,
}
}
fn merge3_result(result: ast_merge_git::Merge3Response) -> MergeDriverResult {
let reparse_after_render = result.reparse_after_render;
let formatting_preservation = Some(result.formatting_preservation);
let secondary_formatting_metrics = Some(result.secondary_formatting_metrics);
let default_driver_evaluation = Some(result.default_driver_evaluation);
if result.ok {
MergeDriverResult {
ok: true,
diagnostics: result.diagnostics,
output: result.merged_source,
change_classifications: result.change_classifications,
owned_regions: result.owned_regions,
render_report: Some(result.render_report),
profile: Some(result.profile),
reparse_after_render,
formatting_preservation,
secondary_formatting_metrics,
default_driver_evaluation,
}
} else if result.conflicted_source.is_some() {
MergeDriverResult {
ok: false,
diagnostics: result.diagnostics,
output: result.conflicted_source,
change_classifications: result.change_classifications,
owned_regions: result.owned_regions,
render_report: Some(result.render_report),
profile: Some(result.profile),
reparse_after_render,
formatting_preservation,
secondary_formatting_metrics,
default_driver_evaluation,
}
} else {
MergeDriverResult {
ok: false,
diagnostics: result.diagnostics,
output: None,
change_classifications: result.change_classifications,
owned_regions: result.owned_regions,
render_report: Some(result.render_report),
profile: Some(result.profile),
reparse_after_render,
formatting_preservation,
secondary_formatting_metrics,
default_driver_evaluation,
}
}
}
fn normalize_language(language: Option<&str>, path_name: &str) -> String {
match language.unwrap_or_default().trim().to_ascii_lowercase().as_str() {
"go" | "golang" => return "go".to_string(),
"json" => return "json".to_string(),
"jsonc" | "json with comments" => return "jsonc".to_string(),
"json5" => return "json5".to_string(),
"plain" | "text" | "plaintext" | "text/plain" => return "text".to_string(),
_ => {}
}
match Path::new(path_name).extension().and_then(|extension| extension.to_str()) {
Some("go") => "go".to_string(),
Some("json") => "json".to_string(),
Some("jsonc") => "jsonc".to_string(),
Some("json5") => "json5".to_string(),
_ => "text".to_string(),
}
}
fn load_path_settings(path_name: &str) -> PathSettings {
let mut settings = PathSettings {
language: None,
conflict_marker_size: 7,
profile_id: None,
require_profile_status: None,
};
for attributes_path in attribute_files_for_path(path_name) {
let Ok(source) = fs::read_to_string(attributes_path) else {
continue;
};
apply_attributes(&mut settings, path_name, &source);
}
settings
}
fn attribute_files_for_path(path_name: &str) -> Vec<PathBuf> {
let clean_path = PathBuf::from(path_name);
let Some(parent) = clean_path.parent() else {
return vec![PathBuf::from(".gitattributes")];
};
if parent.as_os_str().is_empty() || parent.is_absolute() || path_name.starts_with("..") {
return vec![PathBuf::from(".gitattributes")];
}
let mut files = vec![PathBuf::from(".gitattributes")];
let mut current = PathBuf::new();
for component in parent.components() {
current.push(component.as_os_str());
files.push(current.join(".gitattributes"));
}
files
}
fn apply_attributes(settings: &mut PathSettings, path_name: &str, source: &str) {
for raw_line in source.lines() {
let line = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let fields = line.split_whitespace().collect::<Vec<_>>();
if fields.len() < 2 || !attribute_pattern_matches(fields[0], path_name) {
continue;
}
for field in fields.iter().skip(1) {
let Some((key, value)) = field.split_once('=') else {
continue;
};
match key {
"smorg.language" | "linguist-language" => {
settings.language = Some(value.to_string());
}
"smorg.profile" => {
settings.profile_id = Some(value.to_string());
}
"smorg.requireProfileStatus" => {
settings.require_profile_status = Some(value.to_string());
}
"conflict-marker-size" => {
if let Ok(marker_size) = value.parse::<usize>() {
if marker_size > 0 {
settings.conflict_marker_size = marker_size;
}
}
}
_ => {}
}
}
}
}
fn attribute_pattern_matches(pattern: &str, path_name: &str) -> bool {
if pattern == path_name {
return true;
}
if !pattern.contains('/') {
return Path::new(path_name)
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| simple_glob_matches(pattern, name));
}
simple_glob_matches(pattern, path_name)
}
fn simple_glob_matches(pattern: &str, value: &str) -> bool {
if pattern == "*" {
return true;
}
if let Some((prefix, suffix)) = pattern.split_once('*') {
return value.starts_with(prefix) && value.ends_with(suffix);
}
pattern == value
}
fn print_diagnostics(stderr: &mut dyn Write, result: &MergeDriverResult) {
for diagnostic in &result.diagnostics {
let category = serde_json::to_value(diagnostic.category)
.ok()
.and_then(|value| value.as_str().map(str::to_string))
.unwrap_or_else(|| "process".to_string());
let _ = writeln!(stderr, "{category}: {}", diagnostic.message);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn version_output_failure_is_an_internal_error_not_success() {
struct Unwritable;
impl Write for Unwritable {
fn write(&mut self, _bytes: &[u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected output failure"))
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
for args in [vec![], vec!["--json".to_string()]] {
let mut stderr = Vec::new();
assert_eq!(run_version(&args, &mut Unwritable, &mut stderr), EXIT_INTERNAL_ERROR);
assert!(String::from_utf8(stderr).unwrap().contains("cannot write version identity"));
}
}
use serde_json::Value;
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
static TEST_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
struct TestDir {
path: PathBuf,
previous: PathBuf,
_guard: MutexGuard<'static, ()>,
}
impl TestDir {
fn new() -> Self {
let guard = TEST_MUTEX
.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let previous = env::current_dir().expect("current dir");
let unique =
SystemTime::now().duration_since(UNIX_EPOCH).expect("system clock").as_nanos();
let path = env::temp_dir().join(format!("smorg-rs-test-{unique}"));
fs::create_dir_all(&path).expect("create temp dir");
env::set_current_dir(&path).expect("chdir temp");
Self { path, previous, _guard: guard }
}
fn write(&self, name: &str, source: &str) -> String {
let path = self.path.join(name);
fs::write(&path, source).expect("write test file");
path.to_string_lossy().to_string()
}
}
impl Drop for TestDir {
fn drop(&mut self) {
env::set_current_dir(&self.previous).expect("restore current dir");
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn merge_driver_updates_current_file() {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.json", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.tmp", r#"{"name":"structuredmerge","current":true}"#);
let other = dir.write("other.tmp", r#"{"name":"structuredmerge","other":true}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--path-name".to_string(),
"package.json".to_string(),
ancestor,
current.clone(),
other,
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let merged = fs::read_to_string(current).expect("read current file");
assert!(merged.contains(r#""current":true"#), "{merged}");
assert!(merged.contains(r#""other":true"#), "{merged}");
assert!(stdout.is_empty(), "merge-driver should keep stdout quiet");
}
fn run_unsupported_merge(
extra: &[&str],
base: &str,
ours: &str,
theirs: &str,
) -> (i32, String, serde_json::Value) {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.sh", base);
let current = dir.write("current.tmp", ours);
let other = dir.write("other.tmp", theirs);
let report = dir.write("report.json", "");
let mut args: Vec<String> =
["merge-driver", "--path-name", "tests/run.sh", "--report"].map(String::from).into();
args.push(report.clone());
args.extend(extra.iter().map(|arg| arg.to_string()));
args.extend([ancestor, current.clone(), other]);
let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
let exit = run(&args, &mut stdout, &mut stderr);
let merged = fs::read_to_string(current).expect("read current file");
let report: serde_json::Value =
serde_json::from_str(&fs::read_to_string(report).expect("report")).expect("json");
(exit, merged, report)
}
const SH_BASE: &str = "#!/usr/bin/env bash\n# Tags: a\n\nrun one\nrun two\n";
#[test]
fn unsupported_language_uses_git_merge_file_and_preserves_lines() {
let (exit, merged, report) = run_unsupported_merge(
&[],
SH_BASE,
"#!/usr/bin/env bash\n# Tags: b\n\nrun one\nrun two\n",
"#!/usr/bin/env bash\n# Tags: a\n\nrun one\nrun two --fast\n",
);
assert_eq!(exit, EXIT_SUCCESS);
assert_eq!(merged, "#!/usr/bin/env bash\n# Tags: b\n\nrun one\nrun two --fast\n");
assert_eq!(report["fallbacks"][0]["mode"], "git_merge_file");
assert_eq!(report["fallbacks"][0]["applied"], true);
}
#[test]
fn unsupported_language_overlapping_edits_leave_conflict_markers() {
let (exit, merged, report) = run_unsupported_merge(
&[],
SH_BASE,
"#!/usr/bin/env bash\n# Tags: b\n\nrun one\nrun two\n",
"#!/usr/bin/env bash\n# Tags: c\n\nrun one\nrun two\n",
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
assert!(merged.contains("<<<<<<< ours\n# Tags: b\n"), "{merged}");
assert!(merged.contains("=======\n# Tags: c\n>>>>>>> theirs\n"), "{merged}");
assert_eq!(report["fallbacks"][0]["mode"], "git_merge_file");
}
#[test]
fn unsupported_language_with_fallback_none_does_not_rewrite() {
let ours = "#!/usr/bin/env bash\n# Tags: b\n\nrun one\nrun two\n";
let (exit, merged, report) = run_unsupported_merge(
&["--fallback", "none"],
SH_BASE,
ours,
"#!/usr/bin/env bash\n# Tags: a\n\nrun one\nrun two --fast\n",
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
assert_eq!(merged, ours);
assert_eq!(report["fallbacks"].as_array().map_or(0, Vec::len), 0);
}
#[test]
fn merge_driver_uses_smorg_language_attribute() {
let dir = TestDir::new();
fs::write(".gitattributes", "*.data smorg.language=json\n").expect("write attributes");
let ancestor = dir.write("ancestor.tmp", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.tmp", r#"{"name":"structuredmerge","current":true}"#);
let other = dir.write("other.tmp", r#"{"name":"structuredmerge","other":true}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
ancestor,
current.clone(),
other,
"package.data".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let merged = fs::read_to_string(current).expect("read current file");
assert!(merged.contains(r#""current":true"#), "{merged}");
assert!(merged.contains(r#""other":true"#), "{merged}");
}
#[test]
fn git_install_writes_local_semantic_attributes() {
let _dir = TestDir::new();
let fixture = read_git_install_report_fixture();
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&["git".to_string(), "install".to_string(), "--json".to_string()],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let report: Value = serde_json::from_slice(&stdout).expect("json report");
assert_eq!(report["report_version"], fixture["report"]["report_version"]);
assert_eq!(report["ok"], fixture["report"]["ok"]);
assert_eq!(report["profile"], fixture["report"]["profile"]);
assert_eq!(report["scope"], fixture["report"]["scope"]);
let step = &report["install_steps"][0];
assert_eq!(step["name"], fixture["report"]["step"]["name"]);
assert_eq!(step["status"], fixture["report"]["step"]["status"]);
let diagnostics = step["diagnostics"].as_array().expect("diagnostics");
let diagnostic_keys = diagnostics
.iter()
.filter_map(|diagnostic| diagnostic["key"].as_str())
.collect::<Vec<_>>();
for expected_key in
fixture["report"]["diagnostic_keys"].as_array().expect("diagnostic_keys")
{
assert!(diagnostic_keys.contains(&expected_key.as_str().unwrap()));
}
let attributes = fs::read_to_string(".gitattributes").expect("read attributes");
assert!(
attributes.contains(
fixture["implementations"]["rust"]["attribute_contains"].as_str().unwrap()
),
"{attributes}"
);
}
#[test]
fn git_install_supports_builtin_profile() {
let _dir = TestDir::new();
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"git".to_string(),
"install".to_string(),
"--profile".to_string(),
"builtin-diff".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let output = String::from_utf8(stdout).expect("utf8 output");
assert!(output.contains("git install: succeeded builtin-diff local"));
let attributes = fs::read_to_string(".gitattributes").expect("read attributes");
assert!(attributes.contains("*.json diff=json"));
}
#[test]
fn strict_failure_returns_conflict_exit_code() {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.json", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.json", r#"{"name":"#);
let other = dir.write("other.json", r#"{"other":true}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--strict".to_string(),
ancestor,
current,
other,
"package.json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
assert!(
String::from_utf8_lossy(&stderr).contains("parse_error:"),
"stderr={}",
String::from_utf8_lossy(&stderr)
);
assert!(
String::from_utf8_lossy(&stderr).contains("ours parse error"),
"stderr={}",
String::from_utf8_lossy(&stderr)
);
}
#[test]
fn full_file_fallback_writes_conflict_markers() {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.json", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.json", r#"{"name":"#);
let other = dir.write("other.json", r#"{"other":true}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
ancestor,
current.clone(),
other,
"package.json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
let current_source = fs::read_to_string(current).expect("read current");
for needle in ["<<<<<<< ours", "||||||| base", "=======", ">>>>>>> theirs"] {
assert!(
current_source.contains(needle),
"current_source missing {needle:?}: {current_source}"
);
}
assert!(
String::from_utf8_lossy(&stderr).contains("parse_error:"),
"stderr={}",
String::from_utf8_lossy(&stderr)
);
}
#[test]
fn merge_driver_conforms_to_git_driver_fallback_fixture() {
let fixture = read_git_driver_fallback_fixture();
let cases = fixture["cases"].as_array().expect("fixture cases should be an array");
for case in cases {
let dir = TestDir::new();
let ancestor =
dir.write("ancestor.json", case["base_source"].as_str().expect("base source"));
let current =
dir.write("current.json", case["ours_source"].as_str().expect("ours source"));
let other =
dir.write("other.json", case["theirs_source"].as_str().expect("theirs source"));
let report_path = dir.path.join("merge-report.json").to_string_lossy().to_string();
let mut args = vec!["merge-driver".to_string()];
if case["options"]["strict"].as_bool().unwrap_or(false) {
args.push("--strict".to_string());
}
if let Some(fallback) = case["options"]["fallback"].as_str() {
if fallback != "full-file" {
args.push("--fallback".to_string());
args.push(fallback.to_string());
}
}
args.push("--report".to_string());
args.push(report_path.clone());
args.extend([
ancestor,
current.clone(),
other,
case["path_name"].as_str().unwrap().to_string(),
]);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(&args, &mut stdout, &mut stderr);
let expected = &case["expected"];
assert_eq!(
exit,
expected["exit_code"].as_i64().expect("exit code") as i32,
"case={} stderr={}",
case["case_id"].as_str().unwrap_or_default(),
String::from_utf8_lossy(&stderr)
);
let current_source = fs::read_to_string(current).expect("read current");
if let Some(expected_source) =
expected.get("merged_source").and_then(|source| source.as_str())
{
assert_eq!(current_source, expected_source, "case={}", case["case_id"]);
}
if let Some(needles) =
expected.get("source_contains").and_then(|source| source.as_array())
{
for needle in needles {
let needle = needle.as_str().expect("source needle");
assert!(
current_source.contains(needle),
"case={} source={current_source}",
case["case_id"]
);
}
}
for needle in expected["stderr_contains"].as_array().expect("stderr contains") {
let needle = needle.as_str().expect("stderr needle");
assert!(
String::from_utf8_lossy(&stderr).contains(needle),
"case={} stderr={}",
case["case_id"],
String::from_utf8_lossy(&stderr)
);
}
if let Some(needles) =
expected.get("stderr_not_contains").and_then(|value| value.as_array())
{
for needle in needles {
let needle = needle.as_str().expect("stderr needle");
assert!(
!String::from_utf8_lossy(&stderr).contains(needle),
"case={} stderr={}",
case["case_id"],
String::from_utf8_lossy(&stderr)
);
}
}
assert_fallback_machine_report(&report_path, &expected["machine_report"]);
}
}
#[test]
fn strict_json_conflicts_render_only_the_tree_haver_owned_region() {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.json", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.json", r#"{"name":"ours"}"#);
let other = dir.write("other.json", r#"{"name":"theirs"}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--strict".to_string(),
ancestor,
current.clone(),
other,
"package.json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
assert!(
String::from_utf8_lossy(&stderr).contains("merge_conflict:"),
"stderr={}",
String::from_utf8_lossy(&stderr)
);
let current_source = fs::read_to_string(current).expect("read current");
assert!(current_source.contains("<<<<<<< ours"));
assert!(current_source.contains(r#"{"name":"ours"}"#));
assert!(current_source.contains("||||||| base"));
assert!(current_source.contains(r#"{"name":"structuredmerge"}"#));
assert!(current_source.contains(">>>>>>> theirs"));
}
#[test]
fn merge_driver_report_carries_tree_haver_owned_regions() {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.json", r#"{"name":"demo","enabled":true}"#);
let current = dir.write("current.json", r#"{"name":"demo","enabled":false}"#);
let other = dir.write("other.json", r#"{"name":"demo","enabled":"yes"}"#);
let report_path = dir.path.join("merge-report.json").to_string_lossy().to_string();
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--report".to_string(),
report_path.clone(),
ancestor,
current,
other,
"package.json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
let report_source = fs::read_to_string(report_path).expect("read machine report");
let report: Value = serde_json::from_str(&report_source).expect("parse machine report");
assert_eq!(report["render_report"]["strategy"], "owned_region_conflict_markers");
assert_eq!(report["render_report"]["backend_id"], "tree-sitter-language-pack");
assert_eq!(report["render_report"]["parser_identity"], "tree-haver");
assert_eq!(report["change_classifications"], serde_json::json!([]));
assert_eq!(report["owned_regions"].as_array().map(Vec::len), Some(1));
assert_eq!(report["owned_regions"][0]["owner_path"], "/enabled");
assert_eq!(report["owned_regions"][0]["region_kind"], "node");
assert_eq!(report["profile"]["profile_id"], "json.keyed-object");
assert_eq!(report["profile"]["language"], "json");
assert!(report["formatting_preservation"]["line_diff_score"].is_number());
assert!(report["default_driver_evaluation"]["status"].is_string());
}
#[test]
fn merge_driver_conforms_to_supported_git_driver_json_integration_cases() {
if Command::new("git").arg("--version").output().is_err() {
return;
}
let fixture = read_git_driver_json_fixture();
let cases = fixture["cases"].as_array().expect("fixture cases should be an array");
for case in cases {
let dir = TestDir::new();
run_git(&dir.path, &["init"]);
run_git(&dir.path, &["config", "user.email", "smorg-rs@example.invalid"]);
run_git(&dir.path, &["config", "user.name", "smorg-rs test"]);
dir.write(".gitattributes", "*.json merge=smorg-rs smorg.language=json\n");
let path_name = case["path_name"].as_str().expect("path_name should be a string");
dir.write(
path_name,
case["base_source"].as_str().expect("base_source should be a string"),
);
run_git(&dir.path, &["add", "."]);
run_git(&dir.path, &["commit", "-m", "base"]);
let ancestor =
dir.write("ancestor.tmp", case["base_source"].as_str().expect("base source"));
let current = dir.write(path_name, case["ours_source"].as_str().expect("ours source"));
let other =
dir.write("other.tmp", case["theirs_source"].as_str().expect("theirs source"));
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--strict".to_string(),
ancestor,
current.clone(),
other,
path_name.to_string(),
],
&mut stdout,
&mut stderr,
);
let expected = &case["expected"];
assert_eq!(
exit,
expected["exit_code"].as_i64().expect("exit_code should be an integer") as i32,
"case={} stderr={}",
case["case_id"].as_str().unwrap_or_default(),
String::from_utf8_lossy(&stderr)
);
for needle in expected["stderr_contains"].as_array().expect("stderr_contains array") {
let needle = needle.as_str().expect("stderr needle should be a string");
assert!(
String::from_utf8_lossy(&stderr).contains(needle),
"case={} stderr={}",
case["case_id"].as_str().unwrap_or_default(),
String::from_utf8_lossy(&stderr)
);
}
let merged_source = fs::read_to_string(¤t).expect("read current");
if let Some(merged_json) = expected.get("merged_json") {
let merged: Value =
serde_json::from_str(&merged_source).expect("merged output should parse");
assert_eq!(
&merged,
merged_json,
"case={}",
case["case_id"].as_str().unwrap_or_default()
);
} else if let Some(expected_source) =
expected.get("merged_source").and_then(|source| source.as_str())
{
assert_eq!(
merged_source,
expected_source,
"case={}",
case["case_id"].as_str().unwrap_or_default()
);
}
if let Some(needles) =
expected.get("conflicted_source_contains").and_then(|source| source.as_array())
{
for needle in needles {
let needle =
needle.as_str().expect("conflicted source needle should be a string");
assert!(
merged_source.contains(needle),
"case={} source={merged_source}",
case["case_id"].as_str().unwrap_or_default()
);
}
}
}
}
fn read_git_driver_json_fixture() -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(
"../../../fixtures/diagnostics/slice-951-git-driver-json-integration/git-driver-json-integration.json",
);
let source = fs::read_to_string(&path)
.unwrap_or_else(|error| panic!("read fixture {}: {error}", path.display()));
serde_json::from_str(&source).expect("fixture should parse")
}
fn read_git_driver_fallback_fixture() -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(
"../../../fixtures/diagnostics/slice-954-git-driver-fallback/git-driver-fallback.json",
);
let source = fs::read_to_string(&path)
.unwrap_or_else(|error| panic!("read fixture {}: {error}", path.display()));
serde_json::from_str(&source).expect("fixture should parse")
}
fn read_git_install_report_fixture() -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(
"../../../fixtures/diagnostics/slice-1017-git-driver-opt-in-setup/git-install-report.json",
);
let source = fs::read_to_string(&path)
.unwrap_or_else(|error| panic!("read fixture {}: {error}", path.display()));
serde_json::from_str(&source).expect("fixture should parse")
}
fn assert_fallback_machine_report(report_path: &str, expected: &Value) {
let report_source = fs::read_to_string(report_path).expect("read machine report");
let report: Value = serde_json::from_str(&report_source).expect("parse machine report");
assert_eq!(report["ok"], expected["ok"]);
assert_eq!(report["exit_code"], expected["exit_code"]);
assert_eq!(report["fallbacks"], expected["fallbacks"]);
let diagnostics = serde_json::to_string(&report["diagnostics"]).expect("diagnostics json");
for needle in expected["diagnostics_contain"].as_array().expect("diagnostics") {
let needle = needle.as_str().expect("diagnostic needle");
assert!(
diagnostics.contains(needle),
"diagnostics should contain {needle:?}: {diagnostics}"
);
}
if let Some(required_fields) =
expected.get("required_fields").and_then(|value| value.as_array())
{
for field in required_fields {
let field = field.as_str().expect("required field should be a string");
assert!(
report.get(field).is_some(),
"report missing required field {field:?}: {report}"
);
}
}
}
fn run_git(dir: &Path, args: &[&str]) {
let output = Command::new("git")
.args(args)
.current_dir(dir)
.env("GIT_CONFIG_NOSYSTEM", "1")
.output()
.expect("git should run");
assert!(
output.status.success(),
"git {} failed:\n{}{}",
args.join(" "),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn check_only_exit_code_reports_pending_change_without_writing() {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.json", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.json", r#"{"name":"structuredmerge","current":true}"#);
let other = dir.write("other.json", r#"{"name":"structuredmerge","other":true}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--check-only".to_string(),
"--exit-code".to_string(),
ancestor,
current.clone(),
other,
"package.json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
let current_source = fs::read_to_string(current).expect("read current file");
assert!(!current_source.contains(r#""other":true"#), "{current_source}");
}
#[test]
fn profile_report_and_required_status_blocks_merge() {
let dir = TestDir::new();
let ancestor = dir.write("ancestor.json", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.json", r#"{"name":"structuredmerge","current":true}"#);
let other = dir.write("other.json", r#"{"name":"structuredmerge","other":true}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--profile".to_string(),
"json.keyed-object".to_string(),
"--profile-report".to_string(),
"--require-profile-status".to_string(),
"recommended".to_string(),
ancestor,
current,
other,
"package.json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_USER_ERROR);
assert!(
String::from_utf8_lossy(&stdout).contains(r#""rejection_code":"profile_status_unmet""#)
);
assert!(
String::from_utf8_lossy(&stderr)
.contains("profile status available is below required recommended")
);
}
#[test]
fn merge_driver_uses_smorg_profile_attributes() {
let dir = TestDir::new();
fs::write(
".gitattributes",
"*.json smorg.profile=json.keyed-object smorg.requireProfileStatus=recommended\n",
)
.expect("write attributes");
let ancestor = dir.write("ancestor.json", r#"{"name":"structuredmerge"}"#);
let current = dir.write("current.json", r#"{"name":"structuredmerge","current":true}"#);
let other = dir.write("other.json", r#"{"name":"structuredmerge","other":true}"#);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"merge-driver".to_string(),
"--profile-report".to_string(),
ancestor,
current,
other,
"package.json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_USER_ERROR);
let report = String::from_utf8_lossy(&stdout);
assert!(report.contains(r#""profile_id":"json.keyed-object""#), "{report}");
assert!(report.contains(r#""rejection_code":"profile_status_unmet""#), "{report}");
}
#[test]
fn languages_prints_gitattributes() {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&["languages".to_string(), "--gitattributes".to_string()],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let output = String::from_utf8(stdout).expect("utf8 output");
assert!(output.contains("*.go merge=smorg-rs diff=smorg-rs smorg.language=go"));
assert!(output.contains("*.json merge=smorg-rs diff=smorg-rs smorg.language=json"));
}
#[test]
fn languages_json_reports_compiled_inventory_without_claiming_runtime_availability() {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(&["languages".to_string(), "--json".to_string()], &mut stdout, &mut stderr);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let report: serde_json::Value = serde_json::from_slice(&stdout).expect("JSON report");
assert_eq!(report["schema"], "structuredmerge.cli-report/v1");
assert_eq!(report["command"], "languages");
assert_eq!(report["cli"]["cli_contract"], "structuredmerge.cli/v1");
assert_eq!(report["availability"]["runtime_availability_checked"], false);
assert!(report["availability"]["compiled_providers"]["workflows"].is_array());
}
#[test]
fn languages_inspect_preserves_parser_workflow_kind_and_compiled_state() {
let inventory = structuredmerge_core::artifact_inventory::compiled_provider_inventory();
let parser_id = inventory.parsers.first().expect("compiled parser").id.clone();
let workflow_id =
inventory.workflows.first().expect("compiled workflow").provider_id.clone();
for (kind, provider_id) in [("parser", parser_id), ("workflow", workflow_id)] {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"languages".to_string(),
"--inspect".to_string(),
provider_id.clone(),
"--kind".to_string(),
kind.to_string(),
"--json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let report: serde_json::Value = serde_json::from_slice(&stdout).expect("JSON report");
assert_eq!(report["command"], "languages.inspect");
assert_eq!(report["availability"]["provider_kind"], kind);
assert_eq!(report["availability"]["provider_id"], provider_id);
assert_eq!(report["availability"]["state"], "compiled");
assert_eq!(report["availability"]["selectable"], false);
assert_eq!(report["availability"]["runtime_availability_checked"], false);
}
}
#[test]
fn languages_inspect_unknown_provider_fails_explicitly() {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"languages".to_string(),
"--inspect".to_string(),
"unknown.provider".to_string(),
"--kind".to_string(),
"workflow".to_string(),
"--json".to_string(),
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_USER_ERROR);
let report: serde_json::Value = serde_json::from_slice(&stdout).expect("JSON report");
assert_eq!(report["outcome"], "error");
assert_eq!(report["diagnostics"][0]["code"], "provider.unknown");
}
#[test]
fn languages_preflight_validates_inline_request_but_never_claims_runtime_authority() {
let dir = TestDir::new();
let request = json!({
"schema": "structuredmerge.operation-request/v1",
"request_id": "preflight-test",
"operation": "analyze",
"policy": {},
"provider_selection": {
"provider_id": "kernel.json",
"family": "json",
"dialect": "json",
"profile_id": "kernel.json.nested.v1",
"required_capabilities": []
},
"parser_selection": {
"backend": "kernel.tslp.json",
"preference": [],
"required_capabilities": []
},
"sources": {
"source": {
"source_id": "source:json:preflight",
"role": "source",
"byte_length": 2,
"sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
"encoding": "utf-8",
"content": "{}"
}
},
"extensions": [],
"metadata": {}
});
let path = dir.write("request.json", &request.to_string());
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&["languages".into(), "--preflight".into(), path, "--json".into()],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_USER_ERROR, "stderr={}", String::from_utf8_lossy(&stderr));
let report: Value = serde_json::from_slice(&stdout).expect("JSON report");
assert_eq!(report["command"], "languages.preflight");
assert_eq!(report["outcome"], "unsupported");
assert_eq!(report["availability"]["preflight_validated"], true);
assert_eq!(report["availability"]["selection_checked"], true);
}
#[test]
fn languages_preflight_rejects_valid_request_without_runtime_probe() {
let dir = TestDir::new();
let request = json!({
"schema": "structuredmerge.operation-request/v1",
"request_id": "preflight-test",
"operation": "analyze",
"policy": {},
"provider_selection": {
"provider_id": "kernel.json",
"family": "json",
"dialect": "json",
"profile_id": "kernel.json.nested.v1",
"required_capabilities": []
},
"parser_selection": {
"backend": "kernel.tslp.json",
"preference": [],
"required_capabilities": []
},
"sources": {
"source": {
"source_id": "source:json:preflight",
"role": "source",
"byte_length": 2,
"sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77f3f7f5f6f2e7f9b5f7f",
"encoding": "utf-8",
"content": "{}"
}
},
"extensions": [],
"metadata": {}
});
let path = dir.write("request.json", &request.to_string());
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&["languages".into(), "--preflight".into(), path, "--json".into()],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_USER_ERROR, "stderr={}", String::from_utf8_lossy(&stderr));
let report: Value = serde_json::from_slice(&stdout).expect("JSON report");
assert_eq!(report["command"], "languages.preflight");
assert_eq!(report["outcome"], "error");
assert_eq!(report["availability"]["selection_checked"], false);
assert_eq!(report["diagnostics"][0]["code"], "preflight.invalid_request");
}
#[test]
fn diff_driver_accepts_two_argument_form() {
let dir = TestDir::new();
let old_path = dir.write("old.go", "package main\n\nfunc Old() {}\n");
let new_path = dir.write("new.go", "package main\n\nfunc New() {}\n");
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"diff-driver".to_string(),
"--path-name".to_string(),
"main.go".to_string(),
old_path,
new_path,
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let output = String::from_utf8(stdout).expect("utf8 output");
assert!(output.contains("structured-diff main.go"), "{output}");
assert!(output.contains("status changed"), "{output}");
for fragment in
["review-diff unified", "@@ -1,3 +1,3 @@", "-func Old() {}", "+func New() {}"]
{
assert!(output.contains(fragment), "{output}");
}
}
#[test]
fn diff_driver_accepts_git_external_diff_forms() {
for argument_count in [7, 9] {
let dir = TestDir::new();
let old_path = dir.write("old.json", r#"{"old":true}"#);
let new_path = dir.write("new.json", r#"{"new":true}"#);
let mut args = vec![
"diff-driver".to_string(),
"package.json".to_string(),
old_path,
"abc123".to_string(),
"100644".to_string(),
new_path,
"def456".to_string(),
"100644".to_string(),
];
if argument_count == 9 {
args.push("a/".to_string());
args.push("b/".to_string());
}
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(&args, &mut stdout, &mut stderr);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let output = String::from_utf8(stdout).expect("utf8 output");
assert!(output.contains("structured-diff package.json"), "{output}");
for fragment in
["review-diff unified", "@@ -1,1 +1,1 @@", r#"-{"old":true}"#, r#"+{"new":true}"#]
{
assert!(output.contains(fragment), "{output}");
}
}
}
#[test]
fn conflicts_diff_reports_regions_and_exit_code() {
let dir = TestDir::new();
let conflicted = dir.write(
"conflicted.go",
"package main\n<<<<<<< ours\nfunc Current() {}\n=======\nfunc Other() {}\n>>>>>>> theirs\n",
);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"conflicts".to_string(),
"diff".to_string(),
"--path-name".to_string(),
"main.go".to_string(),
"--exit-code".to_string(),
conflicted,
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_UNRESOLVED_CONFLICT);
let output = String::from_utf8(stdout).expect("utf8 output");
assert!(output.contains("conflicts main.go"), "{output}");
assert!(output.contains("count 1"), "{output}");
assert!(output.contains("conflict 1 lines 2-6 separator 4"), "{output}");
}
#[test]
fn conflicts_diff_uses_conflict_marker_size_attribute() {
let dir = TestDir::new();
fs::write(".gitattributes", "*.go conflict-marker-size=9\n").expect("write attributes");
let conflicted =
dir.write("conflicted.go", "<<<<<<<<< ours\nx\n=========\ny\n>>>>>>>>> theirs\n");
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let exit = run(
&[
"conflicts".to_string(),
"diff".to_string(),
"--path-name".to_string(),
"conflicted.go".to_string(),
conflicted,
],
&mut stdout,
&mut stderr,
);
assert_eq!(exit, EXIT_SUCCESS, "stderr={}", String::from_utf8_lossy(&stderr));
let output = String::from_utf8(stdout).expect("utf8 output");
assert!(output.contains("count 1"), "{output}");
}
}