use nichlink_build_method::scaffold;
pub(crate) fn snippets(args: &mut impl Iterator<Item = String>) -> Result<(), String> {
let mut directory: Option<String> = None;
let mut editor = scaffold::Editor::Vscode;
let mut auto = false;
let mut stdout = false;
let args = args.by_ref();
let mut args = args.peekable();
while let Some(arg) = args.next() {
match arg.as_str() {
"--stdout" => stdout = true,
"--editor" => {
let name = args.next().ok_or("--editor requires a name")?;
if name == "auto" {
auto = true;
continue;
}
let accepted = scaffold::Editor::ALL
.iter()
.map(|editor| editor.name())
.collect::<Vec<_>>()
.join(", ");
editor = scaffold::Editor::parse(&name).ok_or_else(|| {
format!("unknown editor '{name}' (accepted: {accepted}, auto)")
})?;
}
_ if arg.starts_with('-') => return Err(format!("unexpected argument '{arg}'")),
_ if directory.is_none() => directory = Some(arg),
_ => return Err("snippets accepts at most one path".to_owned()),
}
}
if auto {
if stdout {
return Err(
"--stdout prints one editor's file; pick one with --editor <name>".to_owned(),
);
}
if directory.is_some() {
return Err(
"auto writes each editor's user-level location; use --editor <name> for a \
project file"
.to_owned(),
);
}
let report = scaffold::install_everywhere()?;
for install in &report.installs {
println!(
"nichlink snippets: {} {} ({})",
if install.written { "wrote" } else { "kept" },
install.target.path.display(),
install.target.editor.name()
);
}
if report.nvim_skipped {
println!(
"nichlink snippets: skipped Neovim — its snippet engines match fuzzily, so these \
triggers would also appear at value positions; run `--editor blink` or \
`--editor nvim` if you want them anyway"
);
}
return Ok(());
}
if stdout {
print!("{}", scaffold::editor_snippets(editor));
return Ok(());
}
let path = match editor {
scaffold::Editor::Vscode => {
let directory = directory.unwrap_or_else(|| ".".to_owned());
std::fs::canonicalize(&directory)
.map_err(|error| format!("cannot resolve {directory}: {error}"))?
.join(scaffold::SNIPPET_FILE)
}
scaffold::Editor::Nvim | scaffold::Editor::Blink => {
if directory.is_some() {
return Err(
"nvim snippets live in the editor config; use --stdout to write them \
somewhere else"
.to_owned(),
);
}
let file = match editor {
scaffold::Editor::Blink => scaffold::BLINK_SNIPPET_FILE,
_ => scaffold::NVIM_SNIPPET_FILE,
};
scaffold::nvim_config_dir().join(file)
}
};
let written = scaffold::write_snippets_file(&path, &scaffold::editor_snippets(editor))?;
println!(
"nichlink snippets: {} {}",
if written { "wrote" } else { "kept" },
path.display()
);
Ok(())
}