use std::fmt;
use std::io;
use std::path::Path;
use crumbkit::schemars::{Schema, SchemaGenerator};
use crumbkit::serde::Serializer;
use crumbkit::{Document, Listing, Row, Shown};
use schemars::JsonSchema;
use serde::Serialize;
use starmap::Name;
use crate::Failed;
use crate::cli::{InitArgs, SpecFile};
use crate::files;
use crate::scan;
use crate::spec::SpecFailure;
#[cfg(test)]
mod tests;
pub(crate) const INIT: Document<Listing<Guess>> = Document::new(
"starmap",
"init",
1,
"Each variable that src reads, with the guesses that init writes to the spec.",
);
const INHERITED: &[&str] = &["HOME", "PATH", "LANG", "TZ"];
const SECRET_WORDS: &[&str] = &["TOKEN", "SECRET", "KEY", "PASSWORD"];
const FORM_ENDINGS: &[(&str, &str)] = &[
("_PORT", "port"),
("_URL", "url"),
("_DIR", "path"),
("_PATH", "path"),
("_FILE", "path"),
("_HOME", "path"),
];
const HEADER: &str = "\
# starmap init wrote this file from the variables that the source reads.
# Each value that ends in ? is a guess. Confirm or correct each one, delete
# its ?, and write each purpose. starmap check refuses the file until then.
";
#[derive(Debug, Serialize, JsonSchema)]
pub(crate) struct Guess {
name: String,
#[serde(rename = "type")]
form: String,
unset: String,
show: String,
source: String,
read_at: Places,
}
impl Row for Guess {
const COLUMNS: &'static [&'static str] = &["name", "type", "unset", "source", "read_at"];
const LONG_COLUMNS: &'static [&'static str] = &["show"];
const UNCUT_COLUMNS: &'static [&'static str] = &["name"];
}
#[derive(Debug)]
pub(crate) struct Places(Vec<String>);
impl fmt::Display for Places {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0.join(" "))
}
}
impl Shown for Places {
fn json<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
fn schema(generator: &mut SchemaGenerator) -> Schema {
Vec::<String>::json_schema(generator)
}
}
crumbkit::shown!(Places);
pub(crate) fn init(args: &InitArgs, dry_run: bool) -> Result<Listing<Guess>, Failed> {
let path = &args.spec;
let file = path.display().to_string();
if files::exists(path) {
return Err(SpecFailure::Exists { file }.into());
}
let src = path.parent().unwrap_or(Path::new("")).join("src");
let guesses: Vec<Guess> = scan::scan(&src)?
.into_iter()
.map(|(name, places)| guess(name, places))
.collect();
let count = guesses.len();
let noun = if count == 1 { "variable" } else { "variables" };
let src = src.display();
let listing = if dry_run {
Listing::new(guesses, count)
.note(format!(
"{src} reads {count} {noun}, and init wrote nothing."
))
.next(SpecFile::call(&["init"], &file), "writes the file.")
} else {
files::write_new(path, &spec_text(&guesses)).map_err(|error| {
if error.kind() == io::ErrorKind::AlreadyExists {
SpecFailure::Exists { file: file.clone() }
} else {
SpecFailure::Unwritable {
file: file.clone(),
error,
}
}
})?;
Listing::new(guesses, count)
.note(format!(
"Wrote {file} with {count} {noun} that {src} reads. Each value marked ? is a guess."
))
.next(
SpecFile::call(&["check"], &file),
"refuses the file until each guess is confirmed and its ? deleted.",
)
};
Ok(listing.described(noun))
}
fn guess(name: Name, places: Vec<String>) -> Guess {
let text = name.as_str();
let inherited = INHERITED.contains(&text) || text.starts_with("XDG_");
let secret = !inherited && text.split('_').any(|word| SECRET_WORDS.contains(&word));
let form = FORM_ENDINGS
.iter()
.find(|(ending, _)| !secret && text.ends_with(ending))
.map_or("string", |(_, form)| form);
let (unset, show, source) = if secret {
("optional", "withheld", "secret")
} else if inherited {
("optional", "shown", "inherited")
} else {
("required", "shown", "setting")
};
Guess {
name: text.to_owned(),
form: format!("{form}?"),
unset: format!("{unset}?"),
show: format!("{show}?"),
source: format!("{source}?"),
read_at: Places(places),
}
}
fn spec_text(guesses: &[Guess]) -> String {
let mut text = HEADER.to_owned();
for guess in guesses {
let places = guess.read_at.0.join(", ");
text.push_str(&format!(
"\n[variables.{}]\n# Read at {}.\npurpose = \"?\"\ntype = \"{}\"\nunset = \"{}\"\nshow = \"{}\"\nsource = \"{}\"\n",
guess.name,
places.escape_debug(),
guess.form,
guess.unset,
guess.show,
guess.source,
));
}
text
}