use std::{
fs,
path::{Component, Path},
time::Duration,
};
use same_same::{KnownFormatter, Named, NamedSet, Settings};
use serde::Deserialize;
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(super) struct FormatSection {
formatter: Option<String>,
config: Option<String>,
settings: Option<toml::Value>,
plugins: Option<Vec<String>>,
command: Option<Vec<String>>,
detect: Option<bool>,
timeout: Option<i64>,
same: Option<Vec<String>>,
}
const SETTINGS_TABLE: &str = "format.settings must be internal-with-overrides, as-written, or internal-only, not a table: put the formatter's settings in its configuration file, and name that file with format.config";
pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(10);
pub const CURRENT: [Named; 6] = [
Named::KeyOrder,
Named::CommentPlace,
Named::ImportOrder,
Named::LineEndings,
Named::ByteOrderMark,
Named::ClassOrder,
];
pub const COUNTED: [Named; 1] = [Named::Yaml11Value];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormatRule {
Formatter {
formatter: KnownFormatter,
config: Option<String>,
settings: Settings,
plugins: Vec<String>,
},
Command {
argv: Vec<String>,
config: Option<String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatConfig {
pub rule: Option<FormatRule>,
pub detect: bool,
pub timeout: Duration,
pub same: NamedSet,
}
impl Default for FormatConfig {
fn default() -> FormatConfig {
FormatConfig {
rule: None,
detect: false,
timeout: FORMAT_TIMEOUT,
same: CURRENT.iter().fold(NamedSet::new(), |mut set, &named| {
set.insert(named);
set
}),
}
}
}
impl FormatSection {
pub(super) fn resolve(self) -> Result<FormatConfig, String> {
let config = self.config.as_deref().map(config_path).transpose()?;
let rule = match (self.formatter, self.command) {
(Some(_), Some(_)) => {
return Err(
"format.formatter and format.command are both set; set one of them".into(),
);
}
(Some(name), None) => {
let formatter = KnownFormatter::from_name(&name).ok_or_else(|| {
format!(
"format.formatter must be oxfmt, prettier, biome, or dprint, not `{name}`"
)
})?;
let settings = match self.settings {
None => Settings::default(),
Some(toml::Value::String(way)) => Settings::from_name(&way).ok_or_else(|| {
format!("format.settings must be internal-with-overrides, as-written, or internal-only, not `{way}`")
})?,
Some(_) => {
return Err(SETTINGS_TABLE.into());
}
};
if self.plugins.is_some() && formatter != KnownFormatter::Prettier {
return Err(format!(
"format.plugins needs format.formatter = \"prettier\", not `{name}`"
));
}
let plugins = self.plugins.unwrap_or_default();
Some(FormatRule::Formatter {
formatter,
config,
settings,
plugins,
})
}
(None, command) => {
if self.settings.as_ref().is_some_and(toml::Value::is_table) {
return Err(SETTINGS_TABLE.into());
}
if self.settings.is_some() || self.plugins.is_some() {
return Err("format.settings and format.plugins need format.formatter".into());
}
match command {
None if config.is_some() => {
return Err("format.config needs format.formatter or format.command".into());
}
None => None,
Some(argv) => Some(command_rule(argv, config)?),
}
}
};
let timeout = match self.timeout {
None => FORMAT_TIMEOUT,
Some(secs) => u64::try_from(secs)
.ok()
.filter(|s| *s > 0)
.map(Duration::from_secs)
.ok_or("format.timeout must be a whole number of seconds above 0")?,
};
let mut same = FormatConfig::default().same;
for name in self.same.unwrap_or_default() {
match Named::from_name(&name).filter(|n| COUNTED.contains(n)) {
Some(named) => same.insert(named),
None => {
return Err(format!(
"format.same can name only yaml11-value, not `{name}`"
));
}
}
}
Ok(FormatConfig {
rule,
detect: self.detect.unwrap_or(false),
timeout,
same,
})
}
}
pub fn format_config(root: &crate::RepoRoot) -> FormatConfig {
#[derive(Deserialize)]
struct File {
#[serde(default)]
format: FormatSection,
}
std::fs::read_to_string(super::config_path().to_fs(root))
.ok()
.and_then(|text| toml::from_str::<toml::Table>(&text).ok())
.and_then(|mut table| {
let format = table
.remove("format")
.unwrap_or(toml::Value::Table(toml::Table::new()));
let mut file = toml::Table::new();
file.insert("format".into(), format);
File::deserialize(toml::Value::Table(file)).ok()
})
.and_then(|file| file.format.resolve().ok())
.and_then(|format| format.check_files(root).ok())
.unwrap_or_default()
}
impl FormatConfig {
pub(super) fn check_files(self, root: &crate::RepoRoot) -> Result<FormatConfig, String> {
let root = root.as_path();
let (config, program, plugins): (Option<&str>, Option<&str>, &[String]) = match &self.rule {
Some(FormatRule::Formatter {
config, plugins, ..
}) => (config.as_deref(), None, plugins),
Some(FormatRule::Command { argv, config }) => (
config.as_deref(),
argv.first()
.map(String::as_str)
.filter(|p| p.contains(['/', '\\']) && !absolute(p)),
&[],
),
None => (None, None, &[]),
};
if let Some(file) = config {
if leaves(root, file) {
return Err(format!(
"format.config `{file}` lies outside the repository"
));
}
if !root.join(file).is_file() {
return Err(format!(
"format.config `{file}` is no file of the repository"
));
}
}
if let Some(program) = program.filter(|p| leaves(root, p)) {
return Err(format!(
"format.command's program `{program}` lies outside the repository"
));
}
if let Some(plugin) = plugins
.iter()
.find(|p| climbs(p) || (names_a_path(p) && leaves(root, p)))
{
return Err(format!(
"format.plugins `{plugin}` lies outside the repository"
));
}
Ok(self)
}
}
fn names_a_path(plugin: &str) -> bool {
absolute(plugin)
|| ["./", "../", ".\\", "..\\"]
.iter()
.any(|start| plugin.starts_with(start))
}
fn absolute(path: &str) -> bool {
path.starts_with(['/', '\\']) || Path::new(path).is_absolute()
}
fn climbs(path: &str) -> bool {
path.split(['/', '\\']).any(|part| part == "..")
}
fn leaves(root: &Path, path: &str) -> bool {
let Ok(base) = fs::canonicalize(root) else {
return false;
};
if climbs(path) {
return true;
}
let given = Path::new(path);
if absolute(path) {
return fs::canonicalize(given).map_or_else(
|_| !given.starts_with(root),
|real| !real.starts_with(&base),
);
}
let mut at = root.to_path_buf();
for part in given.components() {
match part {
Component::CurDir => continue,
Component::Normal(name) => at.push(name),
Component::ParentDir | Component::RootDir | Component::Prefix(_) => return true,
}
match fs::canonicalize(&at) {
Ok(real) if !real.starts_with(&base) => return true,
Ok(_) => {}
Err(_) => return false,
}
}
false
}
fn command_rule(argv: Vec<String>, config: Option<String>) -> Result<FormatRule, String> {
let files = argv.iter().skip(1).any(|a| a == "{files}");
let file = argv.iter().skip(1).any(|a| a.contains("{file}"));
if argv.first().is_none_or(String::is_empty) || !(files || file) {
return Err(
"format.command must name a program and have an element `{files}` or `{file}`".into(),
);
}
if files && file {
return Err("format.command names both `{file}` and `{files}`".into());
}
if config.is_none() && argv.iter().any(|a| a.contains("{settings}")) {
return Err("format.command names `{settings}`, which needs format.config".into());
}
Ok(FormatRule::Command { argv, config })
}
fn config_path(config: &str) -> Result<String, String> {
let path = config.trim_start_matches('/');
let inside = !path.is_empty()
&& !path.contains(['\\', ':'])
&& path
.split('/')
.all(|part| !part.is_empty() && part != "." && part != "..");
if inside {
Ok(path.to_string())
} else {
Err(format!(
"format.config must be a path inside the repository, not `{config}`"
))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn read(text: &str) -> Result<FormatConfig, String> {
#[derive(Deserialize)]
struct File {
format: FormatSection,
}
toml::from_str::<File>(text)
.map_err(|e| e.to_string())?
.format
.resolve()
}
#[test]
fn reads_the_format_table() {
for text in [
"[format]\ncommand = []\n",
"[format]\ncommand = [\"prettier\", \"--write\"]\n",
"[format]\ncommand = [\"\", \"{files}\"]\n",
"[format]\ncommand = \"prettier {files}\"\n",
"[format]\ncommand = [\"fmt\", \"--config\", \"{settings}\", \"{files}\"]\n",
"[format]\nwidth = 3\n",
"[format]\ntimeout = 0\n",
"[format]\ntimeout = -1\n",
"[format]\ntimeout = 1.5\n",
"[format]\nformatter = \"rustfmt\"\n",
"[format]\nformatter = \"prettier\"\ncommand = [\"fmt\", \"{files}\"]\n",
"[format]\nformatter = \"prettier\"\nsettings = \"sorted\"\n",
"[format]\nformatter = \"prettier\"\nsettings = { printWidth = 80 }\n",
"[format]\nformatter = \"oxfmt\"\nplugins = [\"x\"]\n",
"[format]\nformatter = \"biome\"\nplugins = []\n",
"[format]\nsettings = \"as-written\"\n",
"[format]\nconfig = \".prettierrc.json\"\n",
"[format]\nformatter = \"prettier\"\nconfig = \"../x.json\"\n",
"[format]\nsame = [\"key-order\"]\n",
"[format]\nsame = [\"region-indent\"]\n",
"[format]\nsame = [\"yaml-1.1\"]\n",
"[format]\ncommand = [\"fmt\", \"{file}\", \"{files}\"]\n",
"[format]\nformatter = \"prettier\"\nconfig = \"C:/x/.prettierrc.json\"\n",
] {
assert!(read(text).is_err(), "{text:?}");
}
let config = read(
"[format]\nformatter = \"prettier\"\nconfig = \"/.prettierrc.json\"\nplugins = [\"prettier-plugin-sort-json\"]\n",
)
.unwrap();
assert_eq!(
config.rule,
Some(FormatRule::Formatter {
formatter: KnownFormatter::Prettier,
config: Some(".prettierrc.json".into()),
settings: Settings::InternalWithOverrides,
plugins: vec!["prettier-plugin-sort-json".into()],
})
);
assert_eq!(config.timeout, FORMAT_TIMEOUT);
let config =
read("[format]\nformatter = \"biome\"\nsettings = \"internal-only\"\n").unwrap();
assert!(matches!(
config.rule,
Some(FormatRule::Formatter {
settings: Settings::InternalOnly,
..
})
));
let config = read(
"[format]\ncommand = [\"stylelint\", \"--config\", \"{settings}\", \"--fix\", \"{files}\"]\nconfig = \".stylelintrc.json\"\ntimeout = 3\n",
)
.unwrap();
assert!(matches!(config.rule, Some(FormatRule::Command { .. })));
assert_eq!(config.timeout, Duration::from_secs(3));
assert!(read("[format]\ncommand = [\"fmt\", \"--input={file}\"]\n").is_ok());
let config = read("[format]\nsame = [\"yaml11-value\"]\n").unwrap();
assert!(config.same.contains(Named::Yaml11Value));
assert!(config.same.contains(Named::KeyOrder));
let default = read("[format]\n").unwrap();
assert_eq!(default, FormatConfig::default());
assert!(!default.detect, "detection is off by default");
assert!(read("[format]\ndetect = true\n").unwrap().detect);
assert!(read("[format]\ndetect = \"yes\"\n").is_err());
let table = read(
"[format]\ncommand = [\"fmt\", \"{files}\"]\nsettings = { proseWrap = \"never\" }\n",
);
assert!(
table
.unwrap_err()
.ends_with("name that file with format.config")
);
assert!(!default.same.contains(Named::Yaml11Value));
assert!(!default.same.contains(Named::RegionIndent));
}
#[test]
fn the_configuration_file_is_a_file_of_the_repository() {
let dir = crate::test_support::fresh_dir("format-config");
let root = crate::RepoRoot::new(dir.clone());
let config =
read("[format]\nformatter = \"prettier\"\nconfig = \".prettierrc.json\"\n").unwrap();
assert!(config.clone().check_files(&root).is_err());
crate::test_support::write(&dir, ".prettierrc.json", "{}\n");
assert_eq!(config.clone().check_files(&root), Ok(config));
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(unix)]
#[test]
fn a_file_of_the_table_stays_in_the_repository() {
use std::os::unix::fs::symlink;
let outside = crate::test_support::fresh_dir("format-outside");
crate::test_support::write(&outside, "fmt.json", "{}\n");
crate::test_support::write(&outside, "bin/fmt.sh", "#!/bin/sh\n");
crate::test_support::write(&outside, "plugin.js", "\n");
let dir = crate::test_support::fresh_dir("format-links");
let root = crate::RepoRoot::new(dir.clone());
symlink(outside.join("fmt.json"), dir.join("fmt.json")).unwrap();
symlink(&outside, dir.join("out")).unwrap();
crate::test_support::write(&dir, "conf/inside.json", "{}\n");
symlink(dir.join("conf/inside.json"), dir.join("inside.json")).unwrap();
let check = |text: &str| read(text).unwrap().check_files(&root);
for text in [
"[format]\ncommand = [\"fmt\", \"{settings}\", \"{files}\"]\nconfig = \"fmt.json\"\n",
"[format]\nformatter = \"oxfmt\"\nconfig = \"out/fmt.json\"\n",
"[format]\ncommand = [\"./out/bin/fmt.sh\", \"{files}\"]\n",
"[format]\ncommand = [\"../fmt.sh\", \"{files}\"]\n",
"[format]\nformatter = \"prettier\"\nplugins = [\"./out/plugin.js\"]\n",
] {
let error = check(text).expect_err(text);
assert!(
error.contains("lies outside the repository"),
"{text}: {error}"
);
}
for text in [
"[format]\nformatter = \"oxfmt\"\nconfig = \"inside.json\"\n",
"[format]\ncommand = [\"./conf/fmt.sh\", \"{files}\"]\n",
"[format]\nformatter = \"prettier\"\nplugins = [\"prettier-plugin-sort-json\"]\n",
] {
assert!(check(text).is_ok(), "{text}");
}
crate::test_support::write(
&dir,
".sokf/config.toml",
"[format]\ncommand = [\"fmt\", \"{settings}\", \"{files}\"]\nconfig = \"fmt.json\"\n",
);
assert_eq!(format_config(&root), FormatConfig::default());
std::fs::remove_dir_all(&dir).unwrap();
std::fs::remove_dir_all(&outside).unwrap();
}
}