use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use serde_json::Value;
use serde_json::json;
use sha2::Digest;
use sha2::Sha256;
use crate::CliError;
use crate::command::ConsumerInitRequest;
use crate::config::CONFIG_FILENAME;
use crate::installer::CONSUMER_BOOTSTRAP_ASSET;
const GENERATED_FILE_HEADER: &str =
"# Generated by sc-lint; user edits are preserved by future init runs.\n";
const KNOWN_PRIOR_RELEASE_BOOTSTRAP_SHA256: &[[u8; 32]] = &[[
0x5e, 0x26, 0xb4, 0xab, 0x0d, 0x8f, 0xaf, 0xbe, 0x85, 0x6a, 0x94, 0x08, 0x9d, 0x3b, 0x57, 0x5b,
0x10, 0x16, 0x42, 0x58, 0x77, 0x6c, 0x4c, 0x5c, 0x82, 0x8f, 0xec, 0xd9, 0x80, 0x2a, 0x76, 0xdb,
]];
static TEMP_FILE_SEQUENCE: AtomicU64 = AtomicU64::new(0);
const CONSUMER_JUSTFILE_ASSET: &str = include_str!("../assets/consumer-Justfile");
const CANONICAL_CONSUMER_CONFIG_ASSET: &str = include_str!("../assets/consumer-config.toml");
const CONFIG_VERSION_TOKEN: &str = "{{SC_LINT_VERSION}}";
pub(crate) const BINARY_NOT_FOUND_RECOVERY: &str = "Run `just setup` (or your repository's sc-lint installer) to create or repair a compatible installation.";
pub(crate) const DOCS_SETUP_REFERENCE: &str = "sc-lint docs setup";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ManagedFileState {
Current,
Missing,
RefreshablePriorRelease,
UserModified,
}
#[expect(
clippy::result_large_err,
reason = "Consumer initialization preserves the shared top-level CliError contract."
)]
pub(crate) fn run_consumer_init(request: ConsumerInitRequest) -> Result<Value, CliError> {
let root = std::env::current_dir().map_err(|error| {
CliError::config("failed to read current directory for consumer initialization")
.with_source(error)
.with_suggested_action(
"Change to the consumer repository and rerun `sc-lint init --just`.",
)
.with_documentation(DOCS_SETUP_REFERENCE)
})?;
run_consumer_init_at(&root, request)
}
#[expect(
clippy::result_large_err,
reason = "Consumer integration file ownership errors use the shared top-level CliError contract."
)]
pub(crate) fn run_consumer_init_at(
root: &Path,
request: ConsumerInitRequest,
) -> Result<Value, CliError> {
validate_consumer_init_request(request)?;
let files = consumer_integration_files(root);
let mut preserved = Vec::new();
let mut missing = Vec::new();
let mut refresh = Vec::new();
let mut conflicts = Vec::new();
for file in &files {
match classify_file(file)? {
ManagedFileState::Current => preserved.push(file.path.clone()),
ManagedFileState::Missing => missing.push(file.path.clone()),
ManagedFileState::RefreshablePriorRelease => {
refresh.push(file.path.clone());
}
ManagedFileState::UserModified => conflicts.push(file.path.clone()),
}
}
let write_needed = missing;
if !conflicts.is_empty() {
return Err(CliError::config("consumer integration contains user-owned file conflicts")
.with_code("CLI.SC_LINT_INTEGRATION_CONFLICT")
.with_detail("conflicts", paths_to_json(&conflicts))
.with_cause("one or more product-managed paths differ from the canonical integration" )
.with_suggested_action(
"Move or remove the conflicting file, then rerun `sc-lint init --just`; sc-lint will not overwrite it.",
)
.with_documentation(DOCS_SETUP_REFERENCE));
}
if request.check && (!write_needed.is_empty() || !refresh.is_empty()) {
let mut outdated = write_needed.clone();
outdated.extend(refresh.iter().cloned());
return Err(CliError::config("consumer integration is not current")
.with_code("CLI.SC_LINT_INTEGRATION_OUTDATED")
.with_detail("outdated", paths_to_json(&outdated))
.with_cause(
"one or more product-managed integration files are missing or from a prior release",
)
.with_suggested_action(
"Run `sc-lint init --just` to create or refresh the managed files.",
)
.with_documentation(DOCS_SETUP_REFERENCE));
}
if !request.check && !request.dry_run {
for file in &files {
if write_needed.contains(&file.path) || refresh.contains(&file.path) {
if let Some(parent) = file.path.parent() {
fs::create_dir_all(parent).map_err(|error| {
CliError::config(format!(
"failed to create consumer integration directory `{}`",
parent.display()
))
.with_source(error)
.with_suggested_action(
"Check directory permissions, then rerun `sc-lint init --just`.",
)
.with_documentation(DOCS_SETUP_REFERENCE)
})?;
}
write_file_atomically(&file.path, file.contents.as_bytes()).map_err(|error| {
CliError::config(format!(
"failed to write consumer integration file `{}`",
file.path.display()
))
.with_source(error)
.with_suggested_action(
"Check file permissions, then rerun `sc-lint init --just`.",
)
.with_documentation(DOCS_SETUP_REFERENCE)
})?;
}
}
}
Ok(init_result(
request,
&files,
&preserved,
&write_needed,
&refresh,
))
}
fn init_status(
request: ConsumerInitRequest,
created: &[PathBuf],
refreshed: &[PathBuf],
) -> &'static str {
if !refreshed.is_empty() {
if request.dry_run {
"would_update"
} else {
"updated"
}
} else if created.is_empty() {
"current"
} else if request.dry_run {
"would_create"
} else {
"created"
}
}
fn init_result(
request: ConsumerInitRequest,
files: &[ConsumerIntegrationFile],
preserved: &[PathBuf],
created: &[PathBuf],
refreshed: &[PathBuf],
) -> Value {
json!({
"status": init_status(request, created, refreshed),
"managed_files": files.iter().map(|file| file.path.display().to_string()).collect::<Vec<_>>(),
"preserved_files": paths_to_strings(preserved),
"created_files": paths_to_strings(created),
"refreshed_files": paths_to_strings(refreshed),
"check": request.check,
"dry_run": request.dry_run,
"summary": "consumer integration templates are seeded; bootstrap is managed by sc-lint",
})
}
#[expect(
clippy::result_large_err,
reason = "Consumer initialization request validation uses the shared CliError contract."
)]
fn validate_consumer_init_request(request: ConsumerInitRequest) -> Result<(), CliError> {
if !request.just {
return Err(CliError::usage("`sc-lint init` requires `--just`")
.with_suggested_action(
"Run `sc-lint init --just` to create the canonical consumer integration.",
)
.with_documentation(DOCS_SETUP_REFERENCE));
}
if request.check && request.dry_run {
return Err(
CliError::usage("`--check` and `--dry-run` cannot be combined")
.with_suggested_action(
"Use either `--check` or `--dry-run`, then rerun `sc-lint init --just`.",
)
.with_documentation(DOCS_SETUP_REFERENCE),
);
}
Ok(())
}
struct ConsumerIntegrationFile {
path: PathBuf,
contents: String,
kind: ManagedFileKind,
}
pub(crate) fn consumer_integration_path(root: &Path, components: &[&str]) -> PathBuf {
components
.iter()
.fold(root.to_path_buf(), |path, component| path.join(component))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ManagedFileKind {
Config,
Static,
Bootstrap,
}
fn consumer_integration_files(root: &Path) -> Vec<ConsumerIntegrationFile> {
vec![
ConsumerIntegrationFile {
path: consumer_integration_path(root, &[CONFIG_FILENAME]),
contents: canonical_consumer_config(),
kind: ManagedFileKind::Config,
},
ConsumerIntegrationFile {
path: consumer_integration_path(root, &["Justfile"]),
contents: format!("{GENERATED_FILE_HEADER}{CONSUMER_JUSTFILE_ASSET}"),
kind: ManagedFileKind::Static,
},
ConsumerIntegrationFile {
path: consumer_integration_path(root, &[".sc-lint", "bootstrap.py"]),
contents: CONSUMER_BOOTSTRAP_ASSET.to_string(),
kind: ManagedFileKind::Bootstrap,
},
]
}
#[expect(
clippy::result_large_err,
reason = "Consumer file inspection returns the shared top-level CliError contract."
)]
fn classify_file(file: &ConsumerIntegrationFile) -> Result<ManagedFileState, CliError> {
let is_symlink = match fs::symlink_metadata(&file.path) {
Ok(metadata) => metadata.file_type().is_symlink(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(ManagedFileState::Missing);
}
Err(error) => {
return Err(CliError::config(format!(
"failed to inspect consumer integration file `{}`",
file.path.display()
))
.with_source(error)
.with_suggested_action("Check file permissions, then rerun `sc-lint init --just`.")
.with_documentation(DOCS_SETUP_REFERENCE));
}
};
if file.kind != ManagedFileKind::Bootstrap {
return Ok(ManagedFileState::Current);
}
match fs::read_to_string(&file.path) {
Ok(actual) if normalize_line_endings(&actual) == normalize_line_endings(&file.contents) => {
Ok(ManagedFileState::Current)
}
Ok(actual) if is_known_prior_release_bootstrap(&actual) => {
Ok(ManagedFileState::RefreshablePriorRelease)
}
Ok(_) => Ok(ManagedFileState::UserModified),
Err(error) if error.kind() == std::io::ErrorKind::NotFound && is_symlink => {
Ok(ManagedFileState::UserModified)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(ManagedFileState::Missing),
Err(error) => Err(CliError::config(format!(
"failed to inspect consumer integration file `{}`",
file.path.display()
))
.with_source(error)
.with_suggested_action("Check file permissions, then rerun `sc-lint init --just`.")
.with_documentation(DOCS_SETUP_REFERENCE)),
}
}
fn normalize_line_endings(contents: &str) -> String {
contents.replace("\r\n", "\n")
}
fn is_known_prior_release_bootstrap(actual: &str) -> bool {
let normalized = normalize_line_endings(actual);
let digest: [u8; 32] = Sha256::digest(normalized.as_bytes()).into();
KNOWN_PRIOR_RELEASE_BOOTSTRAP_SHA256.contains(&digest)
}
fn write_file_atomically(path: &Path, contents: &[u8]) -> io::Result<()> {
let destination = match fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_symlink() => fs::canonicalize(path)?,
Ok(_) => path.to_path_buf(),
Err(error) if error.kind() == io::ErrorKind::NotFound => path.to_path_buf(),
Err(error) => return Err(error),
};
write_file_atomically_with(&destination, contents, |file, contents| {
file.write_all(contents)
})
}
fn write_file_atomically_with(
path: &Path,
contents: &[u8],
write_contents: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
) -> io::Result<()> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let permissions = match fs::metadata(path) {
Ok(metadata) => Some(metadata.permissions()),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => return Err(error),
};
let (temporary_path, mut temporary_file) = create_temporary_sibling(parent)?;
let write_result = (|| {
write_contents(&mut temporary_file, contents)?;
if let Some(permissions) = permissions {
temporary_file.set_permissions(permissions)?;
}
temporary_file.sync_all()?;
Ok(())
})();
drop(temporary_file);
if let Err(error) = write_result {
let _ = fs::remove_file(&temporary_path);
return Err(error);
}
if let Err(error) = fs::rename(&temporary_path, path) {
let _ = fs::remove_file(&temporary_path);
return Err(error);
}
sync_parent_directory(parent)
}
#[cfg(unix)]
fn sync_parent_directory(parent: &Path) -> io::Result<()> {
File::open(parent)?.sync_all()
}
#[cfg(not(unix))]
fn sync_parent_directory(_parent: &Path) -> io::Result<()> {
Ok(())
}
fn create_temporary_sibling(parent: &Path) -> io::Result<(PathBuf, File)> {
loop {
let sequence = TEMP_FILE_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let name = format!(".sc-lint-init-{}-{sequence}.tmp", std::process::id());
let path = parent.join(name);
match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => return Ok((path, file)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
fn canonical_consumer_config() -> String {
format!(
"{GENERATED_FILE_HEADER}{}",
CANONICAL_CONSUMER_CONFIG_ASSET.replace(CONFIG_VERSION_TOKEN, env!("CARGO_PKG_VERSION"))
)
}
fn paths_to_strings(paths: &[PathBuf]) -> Vec<String> {
paths
.iter()
.map(|path| path.display().to_string())
.collect()
}
fn paths_to_json(paths: &[PathBuf]) -> Value {
json!(paths_to_strings(paths))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generated_config_uses_the_single_canonical_asset() {
let generated = canonical_consumer_config();
assert!(generated.starts_with(GENERATED_FILE_HEADER));
assert_eq!(
generated.trim_start_matches(GENERATED_FILE_HEADER),
CANONICAL_CONSUMER_CONFIG_ASSET
.replace(CONFIG_VERSION_TOKEN, env!("CARGO_PKG_VERSION"))
);
}
#[test]
fn consumer_templates_are_preserved_whatever_their_content() {
let fixture = tempfile::TempDir::new().expect("fixture");
let files = consumer_integration_files(fixture.path());
for file in &files {
if let Some(parent) = file.path.parent() {
fs::create_dir_all(parent).expect("managed file parent");
}
fs::write(&file.path, to_crlf(&file.contents)).expect("CRLF generated file");
assert_eq!(
classify_file(file).expect("classify CRLF generated file"),
ManagedFileState::Current,
"{}",
file.path.display()
);
}
let config = &files[0];
fs::write(
&config.path,
"[tool.sc-lint]\nminimum_version = \"0.0.0\"\n",
)
.expect("edited config");
assert_eq!(
classify_file(config).expect("classify edited config"),
ManagedFileState::Current
);
let justfile = &files[1];
fs::write(&justfile.path, "consumer-owned\n").expect("consumer Justfile");
assert_eq!(
classify_file(justfile).expect("classify consumer Justfile"),
ManagedFileState::Current
);
}
#[test]
fn prior_release_bootstrap_refreshes_while_consumer_templates_are_preserved() {
const LEGACY_0_8_4_GENERATED_CONFIG: &str = concat!(
"# Managed by sc-lint; regenerate with `sc-lint init --just`.\n",
"[tool.sc-lint]\n",
"minimum_version = \"0.8.4\"\n\n",
"[[tool.sc-lint.lint]]\n",
"name = \"fmt\"\n",
"command = [\"cargo\", \"fmt\", \"--all\", \"--check\"]\n",
);
let legacy_bootstrap = include_str!("../tests/fixtures/consumer-bootstrap-v0.8.4.py");
for legacy_config in [
LEGACY_0_8_4_GENERATED_CONFIG.to_owned(),
to_crlf(LEGACY_0_8_4_GENERATED_CONFIG),
] {
let crlf = legacy_config.contains("\r\n");
let fixture = tempfile::TempDir::new().expect("fixture");
let config_path = consumer_integration_path(fixture.path(), &[CONFIG_FILENAME]);
fs::write(&config_path, &legacy_config).expect("legacy config");
let justfile_path = consumer_integration_path(fixture.path(), &["Justfile"]);
fs::write(&justfile_path, "consumer-owned\n").expect("consumer Justfile");
let bootstrap_dir = consumer_integration_path(fixture.path(), &[".sc-lint"]);
fs::create_dir(&bootstrap_dir).expect("bootstrap directory");
let bootstrap_path =
consumer_integration_path(fixture.path(), &[".sc-lint", "bootstrap.py"]);
let bootstrap = if crlf {
to_crlf(legacy_bootstrap)
} else {
legacy_bootstrap.to_owned()
};
fs::write(&bootstrap_path, bootstrap).expect("bootstrap");
let expected_bootstrap = fs::read(&bootstrap_path).expect("prior bootstrap bytes");
let dry_run = run_consumer_init_at(
fixture.path(),
ConsumerInitRequest {
just: true,
check: false,
dry_run: true,
},
)
.expect("dry-run recognizes prior bootstrap");
assert_eq!(dry_run["status"], "would_update");
assert_eq!(
dry_run["refreshed_files"],
json!([bootstrap_path.display().to_string()])
);
assert_eq!(
dry_run["preserved_files"],
json!([
config_path.display().to_string(),
justfile_path.display().to_string()
])
);
assert_eq!(
fs::read(&bootstrap_path).expect("dry-run leaves prior bootstrap"),
expected_bootstrap
);
let result = run_consumer_init_at(
fixture.path(),
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
)
.expect("prior release bootstrap is refreshed");
assert_eq!(result["status"], "updated");
assert_eq!(
result["refreshed_files"],
json!([bootstrap_path.display().to_string()])
);
assert_eq!(
fs::read_to_string(&config_path).expect("config remains consumer-owned"),
legacy_config
);
assert_eq!(
fs::read_to_string(&bootstrap_path).expect("refreshed bootstrap"),
CONSUMER_BOOTSTRAP_ASSET
);
fs::write(&justfile_path, "consumer edit\n").expect("edited Justfile");
let edited = run_consumer_init_at(
fixture.path(),
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
)
.expect("edited Justfile is consumer-owned");
assert_eq!(edited["status"], "current");
assert_eq!(
fs::read_to_string(&justfile_path).expect("consumer Justfile"),
"consumer edit\n"
);
let edited_bootstrap = legacy_bootstrap.replace(
"#!/usr/bin/env python3\n",
"#!/usr/bin/env python3\n# user-owned edit\n",
);
fs::write(
&bootstrap_path,
if crlf {
to_crlf(&edited_bootstrap)
} else {
edited_bootstrap
},
)
.expect("edited bootstrap");
let error = run_consumer_init_at(
fixture.path(),
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
)
.expect_err("edited bootstrap is product drift");
assert_eq!(error.code(), "CLI.SC_LINT_INTEGRATION_CONFLICT");
assert_eq!(error.exit_code(), crate::consts::EXIT_CONFIG);
}
}
fn to_crlf(contents: &str) -> String {
normalize_line_endings(contents).replace('\n', "\r\n")
}
#[cfg(windows)]
fn assert_windows_path_list(
root: &Path,
result: &Value,
field: &str,
expected_components: &[&[&str]],
) {
let actual = result
.get(field)
.and_then(Value::as_array)
.unwrap_or_else(|| panic!("{field} must be an array"));
assert!(!actual.is_empty(), "{field} must not be unexpectedly empty");
let actual = actual
.iter()
.map(|path| {
path.as_str()
.unwrap_or_else(|| panic!("{field} has non-string path"))
})
.collect::<Vec<_>>();
let expected = expected_components
.iter()
.map(|components| {
components
.iter()
.fold(root.to_path_buf(), |path, component| path.join(component))
.display()
.to_string()
})
.collect::<Vec<_>>();
let alternate_separator = if std::path::MAIN_SEPARATOR == '\\' {
'/'
} else {
'\\'
};
for path in &actual {
assert!(
!path.contains(alternate_separator),
"{field} contains a non-native separator: {path}"
);
}
assert_eq!(actual, expected, "unexpected native paths in {field}");
}
#[cfg(windows)]
#[test]
fn init_created_and_preserved_paths_match_native_windows_paths() {
let fixture = tempfile::TempDir::new().expect("fixture");
let create_request = ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
};
let created = run_consumer_init_at(fixture.path(), create_request).expect("create files");
let all_components: &[&[&str]] = &[
&[CONFIG_FILENAME],
&["Justfile"],
&[".sc-lint", "bootstrap.py"],
];
assert_windows_path_list(fixture.path(), &created, "managed_files", all_components);
assert_windows_path_list(fixture.path(), &created, "created_files", all_components);
let current = run_consumer_init_at(fixture.path(), create_request).expect("current files");
assert_windows_path_list(fixture.path(), ¤t, "managed_files", all_components);
assert_windows_path_list(fixture.path(), ¤t, "preserved_files", all_components);
}
#[test]
fn failed_atomic_refresh_keeps_existing_file_and_cleans_temporary_file() {
let fixture = tempfile::TempDir::new().expect("fixture");
let target = consumer_integration_path(fixture.path(), &[".sc-lint", "bootstrap.py"]);
fs::create_dir_all(target.parent().expect("bootstrap parent"))
.expect("create bootstrap directory");
fs::write(&target, b"prior bootstrap").expect("write prior bootstrap");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&target, fs::Permissions::from_mode(0o755))
.expect("make prior bootstrap executable");
}
let error = write_file_atomically_with(&target, b"replacement", |temporary, _| {
temporary.write_all(b"partial")?;
Err(io::Error::other("injected temp-file write failure"))
})
.expect_err("injected temp write fails");
assert_eq!(error.kind(), io::ErrorKind::Other);
assert_eq!(
fs::read(&target).expect("prior bootstrap remains"),
b"prior bootstrap"
);
assert_eq!(
fs::read_dir(target.parent().expect("bootstrap parent"))
.expect("bootstrap directory entries")
.count(),
1,
"failed temp file is removed"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_ne!(
fs::metadata(&target)
.expect("prior metadata")
.permissions()
.mode()
& 0o111,
0,
"existing executable permission survives failure"
);
}
write_file_atomically(&target, b"replacement").expect("atomic refresh succeeds");
assert_eq!(
fs::read(&target).expect("refreshed bootstrap"),
b"replacement"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_ne!(
fs::metadata(&target)
.expect("refreshed metadata")
.permissions()
.mode()
& 0o111,
0,
"executable permission survives refresh"
);
}
}
#[cfg(unix)]
#[test]
fn init_refreshes_symlink_target_without_replacing_managed_link() {
use std::os::unix::fs::symlink;
let fixture = tempfile::TempDir::new().expect("fixture");
let files = consumer_integration_files(fixture.path());
fs::write(&files[0].path, &files[0].contents).expect("current config");
fs::write(&files[1].path, &files[1].contents).expect("current Justfile");
let bootstrap_link = &files[2].path;
fs::create_dir_all(bootstrap_link.parent().expect("bootstrap parent"))
.expect("create bootstrap directory");
let bootstrap_target = bootstrap_link
.parent()
.expect("bootstrap parent")
.join("prior-bootstrap.py");
fs::write(
&bootstrap_target,
include_str!("../tests/fixtures/consumer-bootstrap-v0.8.4.py"),
)
.expect("v0.8.4 target");
symlink("prior-bootstrap.py", bootstrap_link).expect("link managed bootstrap");
let result = run_consumer_init_at(
fixture.path(),
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
)
.expect("refresh symlink target");
assert_eq!(result["status"], "updated");
assert_eq!(
result["refreshed_files"],
json!([bootstrap_link.display().to_string()])
);
assert!(
fs::symlink_metadata(bootstrap_link)
.expect("managed symlink remains")
.file_type()
.is_symlink()
);
assert_eq!(
fs::read_link(bootstrap_link).expect("symlink target remains"),
PathBuf::from("prior-bootstrap.py")
);
assert_eq!(
fs::read_to_string(&bootstrap_target).expect("target refreshed"),
CONSUMER_BOOTSTRAP_ASSET
);
}
#[cfg(unix)]
#[test]
fn init_reports_dangling_managed_symlink_as_conflict() {
use std::os::unix::fs::symlink;
let fixture = tempfile::TempDir::new().expect("fixture");
let files = consumer_integration_files(fixture.path());
fs::write(&files[0].path, &files[0].contents).expect("current config");
fs::write(&files[1].path, &files[1].contents).expect("current Justfile");
let bootstrap_link = &files[2].path;
fs::create_dir_all(bootstrap_link.parent().expect("bootstrap parent"))
.expect("create bootstrap directory");
symlink("missing-bootstrap.py", bootstrap_link).expect("create dangling link");
let error = run_consumer_init_at(
fixture.path(),
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
)
.expect_err("dangling managed link is user-owned");
assert_eq!(error.code(), "CLI.SC_LINT_INTEGRATION_CONFLICT");
assert_eq!(
error.details["conflicts"],
json!([bootstrap_link.display().to_string()])
);
assert!(
fs::symlink_metadata(bootstrap_link)
.expect("dangling managed symlink remains")
.file_type()
.is_symlink()
);
assert!(
!bootstrap_link
.parent()
.expect("bootstrap parent")
.join("missing-bootstrap.py")
.exists()
);
}
#[test]
fn version_bumped_generated_config_is_current_but_never_overwritten() {
let fixture = tempfile::TempDir::new().expect("fixture");
let request = ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
};
run_consumer_init_at(fixture.path(), request).expect("initial integration");
let config_path = fixture.path().join(CONFIG_FILENAME);
let old = fs::read_to_string(&config_path)
.expect("generated config")
.replace(env!("CARGO_PKG_VERSION"), "0.0.0");
fs::write(&config_path, old).expect("old generated config");
let expected_bytes = fs::read(&config_path).expect("old generated config bytes");
let expected_modified = fs::metadata(&config_path)
.expect("old generated config metadata")
.modified()
.expect("old generated config modification time");
for request in [
ConsumerInitRequest {
just: true,
check: true,
dry_run: false,
},
ConsumerInitRequest {
just: true,
check: false,
dry_run: true,
},
request,
] {
let result = run_consumer_init_at(fixture.path(), request)
.expect("version-only generated config remains current");
assert_eq!(result["status"], "current");
assert_eq!(
fs::read(&config_path).expect("unchanged config bytes"),
expected_bytes
);
assert_eq!(
fs::metadata(&config_path)
.expect("unchanged config metadata")
.modified()
.expect("unchanged config modification time"),
expected_modified
);
}
}
fn managed_bytes(root: &Path) -> Vec<Vec<u8>> {
consumer_integration_files(root)
.iter()
.map(|file| fs::read(&file.path).expect("managed file bytes"))
.collect()
}
fn create_integration(root: &Path) {
run_consumer_init_at(
root,
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
)
.expect("initial integration");
}
fn assert_consumer_templates_survive(edits: &[(&str, &str)]) {
let fixture = tempfile::TempDir::new().expect("fixture");
create_integration(fixture.path());
for (name, text) in edits {
let path = consumer_integration_path(fixture.path(), &[name]);
let mut contents = fs::read_to_string(&path).expect("generated template");
contents.push_str(text);
fs::write(&path, contents).expect("consumer edit");
}
let snapshot = managed_bytes(fixture.path());
for request in [
ConsumerInitRequest {
just: true,
check: true,
dry_run: false,
},
ConsumerInitRequest {
just: true,
check: false,
dry_run: true,
},
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
] {
let result = run_consumer_init_at(fixture.path(), request)
.expect("consumer edits to the templates are never a conflict");
assert_eq!(result["status"], "current");
assert_eq!(managed_bytes(fixture.path()), snapshot);
}
}
const DB_PREPARE_RECIPE: &str = "\ndb-prepare:\n echo prepare\n";
const JUSTFILE_IMPORT: &str = "\nimport \"extra.just\"\n";
const ANALYZER_ROW: &str = "\n[tool.sc-lint.analyzers.boundary]\nrules = []\n";
const PROFILE_TABLES: &str =
"\n[tool.sc-lint.lint_profiles]\ndefault = [\"fmt\"]\nfull = [\"fmt\", \"clippy\"]\n";
#[test]
fn appended_db_prepare_recipe_survives_init_849() {
assert_consumer_templates_survive(&[("Justfile", DB_PREPARE_RECIPE)]);
}
#[test]
fn appended_justfile_import_survives_init_849() {
assert_consumer_templates_survive(&[("Justfile", JUSTFILE_IMPORT)]);
}
#[test]
fn appended_analyzer_row_survives_init_849() {
assert_consumer_templates_survive(&[(CONFIG_FILENAME, ANALYZER_ROW)]);
}
#[test]
fn appended_profile_tables_survive_init_849() {
assert_consumer_templates_survive(&[(CONFIG_FILENAME, PROFILE_TABLES)]);
}
#[test]
fn all_consumer_edits_together_survive_init_849() {
assert_consumer_templates_survive(&[
("Justfile", DB_PREPARE_RECIPE),
("Justfile", JUSTFILE_IMPORT),
(CONFIG_FILENAME, ANALYZER_ROW),
(CONFIG_FILENAME, PROFILE_TABLES),
]);
}
#[test]
fn bootstrap_edit_is_still_a_config_conflict_exiting_3_849() {
let fixture = tempfile::TempDir::new().expect("fixture");
create_integration(fixture.path());
let bootstrap = consumer_integration_path(fixture.path(), &[".sc-lint", "bootstrap.py"]);
fs::write(
&bootstrap,
format!("{CONSUMER_BOOTSTRAP_ASSET}# consumer edit\n"),
)
.expect("bootstrap edit");
let snapshot = managed_bytes(fixture.path());
let error = run_consumer_init_at(
fixture.path(),
ConsumerInitRequest {
just: true,
check: false,
dry_run: false,
},
)
.expect_err("bootstrap edit is product drift");
assert_eq!(error.code(), "CLI.SC_LINT_INTEGRATION_CONFLICT");
assert_eq!(error.exit_code(), crate::consts::EXIT_CONFIG);
assert_eq!(managed_bytes(fixture.path()), snapshot);
}
}