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::cli::{InitArgs, SpecFile};
use crate::clippy;
use crate::files;
use crate::scan::{self, Dirs};
use crate::spec::{self, Located, 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.",
)
.when_empty("init lists no variables");
const INHERITED: &[&str] = &["HOME", "PATH", "LANG", "TZ"];
const SECRET_WORDS: &[&str] = &["TOKEN", "SECRET", "KEY", "PASSWORD"];
const TYPE_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")]
ty: 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>, crumbkit::Error> {
let path = &args.spec;
let given = path.display().to_string();
let located = locate(path)?;
let file = located.file.display().to_string();
let exists = || SpecFailure::Exists {
file: file.clone(),
pointer: located.pointer.clone(),
};
if files::exists(&located.file) {
return Err(exists().into());
}
let scanned = scan::scan_all(&located.src)?;
let bans: Vec<clippy::Ban> = clippy::open(path, &scanned.rust)
.into_iter()
.collect::<Result<_, _>>()?;
let banned = clippy::sentences(&bans, dry_run);
let guesses: Vec<Guess> = scanned
.reads
.into_iter()
.map(|(name, places)| guess(name, places))
.collect();
let count = guesses.len();
let noun = if count == 1 { "variable" } else { "variables" };
let src = Dirs(&located.src);
let reads = src.verb("reads", "read");
let listing = if dry_run {
Listing::new(guesses, count)
.note(format!(
"{src} {reads} {count} {noun}, and init wrote nothing.\n{banned}"
))
.next(SpecFile::call(&["init"], &given), "writes the file.")
} else {
files::write_new(&located.file, &spec_text(&guesses)).map_err(|error| {
if error.kind() == io::ErrorKind::AlreadyExists {
exists()
} else {
SpecFailure::Unwritable {
file: file.clone(),
error,
}
}
})?;
for ban in bans {
ban.write(path)?;
}
Listing::new(guesses, count)
.note(format!(
"Wrote {file} with {count} {noun} that {src} {reads}. Each value marked ? is a guess.\n{banned}"
))
.next(
SpecFile::call(&["check"], &given),
"refuses the file until each guess is confirmed and its ? deleted.",
)
};
Ok(listing.described(noun))
}
pub(crate) fn ban(args: &InitArgs, dry_run: bool) -> Result<Listing<Guess>, crumbkit::Error> {
let located = spec::locate(&args.spec)?;
let bans: Vec<clippy::Ban> = clippy::open(&args.spec, &scan::scan_all(&located.src)?.rust)
.into_iter()
.collect::<Result<_, _>>()?;
let banned = clippy::sentences(&bans, dry_run);
if !dry_run {
for ban in bans {
ban.write(&args.spec)?;
}
}
Ok(Listing::new(Vec::new(), 0).note(banned))
}
fn locate(path: &Path) -> Result<Located, SpecFailure> {
let exists = |pointer| SpecFailure::Exists {
file: path.display().to_string(),
pointer,
};
if !files::exists(path) {
return spec::locate(path);
}
match spec::locate(path) {
Ok(located) if located.pointer.is_some() => Ok(located),
Ok(_) | Err(_) => Err(exists(None)),
}
}
fn guess(name: Name, places: Vec<String>) -> Guess {
let text = name.as_str();
let upper = text.to_ascii_uppercase();
let inherited = INHERITED.contains(&upper.as_str()) || upper.starts_with("XDG_");
let secret = !inherited && upper.split('_').any(|word| SECRET_WORDS.contains(&word));
let ty = TYPE_ENDINGS
.iter()
.find(|(ending, _)| !secret && upper.ends_with(ending))
.map_or("string", |(_, ty)| ty);
let (unset, show, source) = if secret {
("optional", "withheld", "secret")
} else if inherited {
("optional", "shown", "inherited")
} else {
("required", "shown", "setting")
};
Guess {
name: text.to_owned(),
ty: format!("{ty}?"),
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.ty,
guess.unset,
guess.show,
guess.source,
));
}
text
}