use cap_std::fs::Dir;
use oakum::plan::Versioning;
use super::fs::read_text;
use super::owned_files::{ConfigSettings, PrivatePackages};
use super::tag_shape::ReadableTemplate;
use super::CliError;
const SOURCE_FILES: [&str; 2] = [".changeset/config.json", ".bumpy/_config.json"];
const PRIVATE_PACKAGES: &str = "privatePackages";
const VERSION_COMMIT_MESSAGE: &str = "versionCommitMessage";
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum CarriedMessage {
Absent,
SameAsDefault,
Unwritable(Refusal),
Carried(String),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Refusal {
Empty,
WhitespaceOnly,
ControlCharacter,
TemplateSyntax,
ModulePath,
}
impl Refusal {
fn because(self) -> &'static str {
match self {
Self::Empty => "it states an empty message",
Self::WhitespaceOnly => {
"it is only whitespace, and `ci version-pr` refuses a message that renders to nothing"
}
Self::ControlCharacter => {
"it holds a control character, which no commit headline should carry"
}
Self::TemplateSyntax => {
"it holds template syntax, and `commit-message` is rendered as a template rather than written literally"
}
Self::ModulePath => {
"it names a module rather than a message, and oakum runs no such module"
}
}
}
fn owed_to_the_reader(self) -> bool {
self != Self::Empty
}
}
#[derive(Debug)]
pub(super) struct SourceConfig {
pub(super) file: &'static str,
pub(super) dropped: Vec<String>,
commit_message: CarriedMessage,
private_packages: Option<PrivatePackages>,
}
impl SourceConfig {
pub(super) fn carried_private_packages(&self) -> Option<PrivatePackages> {
self.private_packages.filter(|private| private.any())
}
}
pub(super) fn read_source_configs(dir: &Dir) -> (Vec<SourceConfig>, Vec<String>) {
let mut configs = Vec::new();
let mut unreadable = Vec::new();
for file in SOURCE_FILES {
let outcome = match read_text(dir, file) {
Ok(None) => continue,
Ok(Some(body)) => parse_source_config(file, &body),
Err(err) => Err(err),
};
match outcome {
Ok(config) => configs.push(config),
Err(err) => unreadable.push(format!(
"could not use `{file}` ({err}); no settings carried from it, \
including `{PRIVATE_PACKAGES}` if it set one"
)),
}
}
(configs, unreadable)
}
pub(super) fn migrated_settings(
versioning: Versioning,
configs: &[SourceConfig],
tag_format: Option<ReadableTemplate>,
) -> ConfigSettings {
ConfigSettings {
change_files: true,
conventional_commits: true,
versioning,
private_packages: carried_private_packages(configs),
tag_format,
commit_message: carried_commit_message(configs),
}
}
const LOSSY_MAPPINGS: [(&str, &str); 1] = [("changelog", "template")];
const CONSEQUENTIAL_DROPS: [(&str, &str); 1] = [(
"gitUser",
"it set who authored release commits and tags; oakum has no identity key. `git config user.name` / `user.email` in that job decides the tagger; the version commit is written through the GitHub API and carries the token's own account, which no git config can change",
)];
pub(super) fn consequential_drop_steps(configs: &[SourceConfig]) -> Vec<String> {
let mut steps = Vec::new();
for config in configs {
for (source_key, consequence) in CONSEQUENTIAL_DROPS {
if config.dropped.iter().any(|key| key == source_key) {
steps.push(format!(
"- `{source_key}` from `{}` was not carried over: {consequence}",
config.file
));
}
}
}
steps
}
pub(super) fn lossy_mapping_steps(configs: &[SourceConfig]) -> Vec<String> {
let mut steps = Vec::new();
for config in configs {
for (source_key, oakum_key) in LOSSY_MAPPINGS {
if config.dropped.iter().any(|key| key == source_key) {
steps.push(format!(
"- decide what `{source_key}` from `{}` should become: oakum's nearest setting is `{oakum_key}`, which does not mean the same thing, so oakum wrote neither",
config.file
));
}
}
}
steps
}
pub(super) fn knope_scope_steps(dir: &Dir) -> Vec<String> {
let could_not = |err: &dyn std::fmt::Display| {
vec![format!(
"- could not look for knope `scopes` lists in `knope.toml` ({err}); any it had were not carried over"
)]
};
let body = match read_text(dir, "knope.toml") {
Ok(Some(body)) => body,
Ok(None) => return Vec::new(),
Err(err) => return could_not(&err),
};
let config: toml::Value = match toml::from_str(&body) {
Ok(config) => config,
Err(err) => return could_not(&err.message()),
};
let mut lists: Vec<(Option<&str>, &toml::Value)> = Vec::new();
if let Some(scopes) = config
.get("package")
.and_then(|package| package.get("scopes"))
{
lists.push((None, scopes));
}
if let Some(packages) = config.get("packages").and_then(toml::Value::as_table) {
for (name, package) in packages {
if let Some(scopes) = package.get("scopes") {
lists.push((Some(name), scopes));
}
}
}
lists
.into_iter()
.filter(|(_, scopes)| scopes.as_array().is_none_or(|items| !items.is_empty()))
.map(|(name, scopes)| {
let named: Vec<String> = scopes
.as_array()
.into_iter()
.flatten()
.filter_map(toml::Value::as_str)
.map(|scope| format!("`{scope}`"))
.collect();
let listed = if named.is_empty() {
String::from("not a list of names")
} else {
named.join(", ")
};
let whose = name.map_or_else(|| String::from("the package"), |name| format!("`{name}`"));
format!(
"- knope `scopes` for {whose} ({listed}) were not carried over: oakum maps no scope to a package, so a commit whose scope names no package is attributed by the files it changes"
)
})
.collect()
}
fn carried_commit_message(configs: &[SourceConfig]) -> Option<String> {
chosen_commit_message(configs).map(|(_, message)| message.to_owned())
}
pub(super) fn commit_message_steps(configs: &[SourceConfig]) -> Vec<String> {
configs
.iter()
.filter_map(|config| match &config.commit_message {
CarriedMessage::Absent | CarriedMessage::Carried(_) => None,
CarriedMessage::SameAsDefault if carried_commit_message(configs).is_none() => {
Some(format!(
"- `{VERSION_COMMIT_MESSAGE}` in `{}` is what oakum writes anyway, so no `commit-message` line was needed",
config.file
))
}
CarriedMessage::SameAsDefault => Some(format!(
"- `{VERSION_COMMIT_MESSAGE}` in `{}` was not carried: another source file states one oakum wrote instead",
config.file
)),
CarriedMessage::Unwritable(refusal) if refusal.owed_to_the_reader() => {
Some(match chosen_commit_message(configs) {
Some((chosen, _)) => format!(
"- restore `{VERSION_COMMIT_MESSAGE}` from `{}` by hand only if you want it instead of the one oakum wrote from `{chosen}`: oakum could not carry it because {}",
config.file,
refusal.because()
),
None => format!(
"- restore `{VERSION_COMMIT_MESSAGE}` from `{}` by hand: oakum could not carry it because {}",
config.file,
refusal.because()
),
})
}
CarriedMessage::Unwritable(refusal) => Some(format!(
"- `{VERSION_COMMIT_MESSAGE}` in `{}` was not carried: {}",
config.file,
refusal.because()
)),
})
.collect()
}
pub(super) fn chosen_commit_message(configs: &[SourceConfig]) -> Option<(&'static str, &str)> {
configs
.iter()
.find_map(|config| match &config.commit_message {
CarriedMessage::Carried(message) => Some((config.file, message.as_str())),
_ => None,
})
}
pub(super) fn shadowed_commit_messages(configs: &[SourceConfig]) -> Vec<String> {
let mut steps = Vec::new();
let mut winner = None;
for config in configs {
let CarriedMessage::Carried(_) = &config.commit_message else {
continue;
};
match winner {
None => winner = Some(config.file),
Some(chosen) => steps.push(format!(
"- `{VERSION_COMMIT_MESSAGE}` in `{}` was not carried: `{chosen}` states one too, and oakum writes a single `commit-message`",
config.file
)),
}
}
steps
}
fn looks_like_a_module_path(message: &str) -> bool {
message.starts_with("./")
|| message.starts_with("../")
|| [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
.iter()
.any(|suffix| message.ends_with(suffix))
}
fn read_commit_message(object: &serde_json::Map<String, serde_json::Value>) -> CarriedMessage {
let Some(message) = object
.get(VERSION_COMMIT_MESSAGE)
.and_then(serde_json::Value::as_str)
else {
return CarriedMessage::Absent;
};
let trimmed = message.trim();
if trimmed == super::ci::DEFAULT_COMMIT {
return CarriedMessage::SameAsDefault;
}
if let Some(refusal) = refuses_carrying(message, trimmed) {
return CarriedMessage::Unwritable(refusal);
}
CarriedMessage::Carried(trimmed.to_owned())
}
fn refuses_carrying(stated: &str, trimmed: &str) -> Option<Refusal> {
if stated.is_empty() {
return Some(Refusal::Empty);
}
if trimmed.is_empty() {
return Some(Refusal::WhitespaceOnly);
}
if trimmed.chars().any(char::is_control) {
return Some(Refusal::ControlCharacter);
}
if ["{{", "{%", "{#"]
.iter()
.any(|sigil| trimmed.contains(sigil))
{
return Some(Refusal::TemplateSyntax);
}
if looks_like_a_module_path(trimmed) {
return Some(Refusal::ModulePath);
}
None
}
pub(super) fn carried_private_packages(configs: &[SourceConfig]) -> PrivatePackages {
configs
.iter()
.filter_map(|config| config.private_packages)
.fold(PrivatePackages::default(), PrivatePackages::union)
}
fn parse_source_config(
file: &'static str,
body: &str,
) -> Result<SourceConfig, Box<dyn std::error::Error>> {
let value: serde_json::Value = serde_json::from_str(body)
.map_err(|err| CliError::new(format!("`{file}` is not valid JSON: {err}")))?;
let Some(object) = value.as_object() else {
return Err(Box::new(CliError::new(format!(
"`{file}` is not a JSON object"
))));
};
let private_packages = object
.get(PRIVATE_PACKAGES)
.map(|value| parse_private_packages(file, value))
.transpose()?;
let commit_message = read_commit_message(object);
let carried: &[&str] = if commit_message == CarriedMessage::Absent {
&[PRIVATE_PACKAGES]
} else {
&[PRIVATE_PACKAGES, VERSION_COMMIT_MESSAGE]
};
let mut dropped: Vec<String> = object
.keys()
.filter(|key| !carried.contains(&key.as_str()))
.cloned()
.collect();
dropped.sort();
Ok(SourceConfig {
file,
dropped,
commit_message,
private_packages,
})
}
fn parse_private_packages(
file: &'static str,
value: &serde_json::Value,
) -> Result<PrivatePackages, Box<dyn std::error::Error>> {
if let serde_json::Value::Bool(on) = value {
return Ok(PrivatePackages {
version: *on,
tag: *on,
});
}
let Some(object) = value.as_object() else {
return Err(Box::new(CliError::new(format!(
"`{PRIVATE_PACKAGES}` in `{file}` is neither an object nor a boolean"
))));
};
Ok(PrivatePackages {
version: axis(file, object, "version")?,
tag: axis(file, object, "tag")?,
})
}
fn axis(
file: &'static str,
object: &serde_json::Map<String, serde_json::Value>,
name: &str,
) -> Result<bool, Box<dyn std::error::Error>> {
match object.get(name) {
None => Ok(false),
Some(serde_json::Value::Bool(on)) => Ok(*on),
Some(other) => Err(Box::new(CliError::new(format!(
"`{PRIVATE_PACKAGES}.{name}` in `{file}` is `{other}`, not a boolean"
)))),
}
}
#[cfg(test)]
mod reading {
use super::{carried_private_packages, parse_source_config};
use crate::cli::owned_files::PrivatePackages;
fn parse(file: &'static str, body: &str) -> super::SourceConfig {
parse_source_config(file, body).expect("source config")
}
#[test]
fn private_packages_is_carried_and_never_reported_as_dropped() {
let config = parse(
".bumpy/_config.json",
r#"{"privatePackages": {"version": true, "tag": true}, "baseBranch": "main"}"#,
);
assert_eq!(
config.carried_private_packages(),
Some(PrivatePackages {
version: true,
tag: true
})
);
assert_eq!(config.dropped, vec![String::from("baseBranch")]);
}
#[test]
fn axes_are_independent_and_a_missing_axis_is_off() {
let config = parse(
".changeset/config.json",
r#"{"privatePackages": {"tag": true}}"#,
);
assert_eq!(
config.carried_private_packages(),
Some(PrivatePackages {
version: false,
tag: true
})
);
}
#[test]
fn both_axes_off_matches_the_default_so_nothing_is_announced() {
let config = parse(
".changeset/config.json",
r#"{"privatePackages": {"version": false, "tag": false}}"#,
);
assert_eq!(config.carried_private_packages(), None);
assert!(config.dropped.is_empty(), "{:?}", config.dropped);
}
#[test]
fn a_source_without_the_key_carries_nothing() {
let config = parse(".changeset/config.json", r#"{"access": "public"}"#);
assert_eq!(config.carried_private_packages(), None);
assert_eq!(config.dropped, vec![String::from("access")]);
assert_eq!(
carried_private_packages(&[config]),
PrivatePackages::default()
);
}
#[test]
fn two_sources_union_their_axes() {
let carried = carried_private_packages(&[
parse(
".changeset/config.json",
r#"{"privatePackages": {"version": true}}"#,
),
parse(
".bumpy/_config.json",
r#"{"privatePackages": {"tag": true}}"#,
),
]);
assert_eq!(
carried,
PrivatePackages {
version: true,
tag: true
}
);
}
#[test]
fn a_non_boolean_axis_refuses_and_names_the_file() {
let err = parse_source_config(
".bumpy/_config.json",
r#"{"privatePackages": {"version": "yes"}}"#,
)
.expect_err("non-boolean axis");
assert_eq!(
err.to_string(),
"`privatePackages.version` in `.bumpy/_config.json` is `\"yes\"`, not a boolean"
);
}
#[test]
fn a_private_packages_that_is_neither_object_nor_boolean_refuses() {
let err = parse_source_config(".bumpy/_config.json", r#"{"privatePackages": "yes"}"#)
.expect_err("a string is neither");
assert_eq!(
err.to_string(),
"`privatePackages` in `.bumpy/_config.json` is neither an object nor a boolean"
);
}
#[test]
fn a_changesets_boolean_private_packages_opts_both_axes_in() {
let carried = carried_private_packages(&[parse(
".changeset/config.json",
r#"{"privatePackages": true}"#,
)]);
assert_eq!(
carried,
PrivatePackages {
version: true,
tag: true
}
);
let off = carried_private_packages(&[parse(
".changeset/config.json",
r#"{"privatePackages": false}"#,
)]);
assert_eq!(off, PrivatePackages::default());
}
#[test]
fn a_non_object_config_refuses_and_names_the_file() {
let err = parse_source_config(".bumpy/_config.json", "[]").expect_err("array");
assert_eq!(
err.to_string(),
"`.bumpy/_config.json` is not a JSON object"
);
let err = parse_source_config(".bumpy/_config.json", "{").expect_err("truncated");
assert!(
err.to_string()
.starts_with("`.bumpy/_config.json` is not valid JSON: "),
"{err}"
);
}
#[test]
fn an_explicit_null_axis_refuses_like_any_other_non_boolean() {
let err = parse_source_config(
".bumpy/_config.json",
r#"{"privatePackages": {"version": null}}"#,
)
.expect_err("null is not a boolean");
assert!(err.to_string().contains("not a boolean"), "{err}");
}
#[test]
fn git_user_is_named_as_a_consequential_drop_not_only_a_dropped_key() {
let config = super::SourceConfig {
file: ".bumpy/_config.json",
dropped: vec![String::from("baseBranch"), String::from("gitUser")],
commit_message: super::CarriedMessage::Absent,
private_packages: None,
};
let steps = super::consequential_drop_steps(std::slice::from_ref(&config));
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("`gitUser`"), "{steps:?}");
assert!(
steps[0].contains("who authored release commits"),
"{steps:?}"
);
assert!(!steps[0].contains("baseBranch"), "{steps:?}");
let quiet = super::SourceConfig {
file: ".bumpy/_config.json",
dropped: vec![String::from("baseBranch")],
commit_message: super::CarriedMessage::Absent,
private_packages: None,
};
let steps = super::consequential_drop_steps(&[quiet]);
assert!(steps.is_empty(), "{steps:?}");
}
}