use std::path::Path;
use loftspec::codec;
use loftspec::document::Document;
use loftspec::ids::DocumentId;
use loftspec_store::FileStore;
use loftspec_store::repository::GitCommand;
use serde_json::json;
use crate::finish::Finished;
use crate::out::outln;
use crate::stop::Stop;
use crate::{json, merge_driver, skill};
const SCHEMA: &str = "loft-init/1";
pub fn run(root: &Path, with_skill: bool, as_json: bool) -> Finished {
let document = Document::empty(DocumentId::mint());
if let Err(error) =
FileStore::open(root).and_then(|store| store.create(codec::write(&document)))
{
return Stop::from(error).exit(SCHEMA, as_json);
}
let skills = if with_skill {
match skill::install(root) {
Ok(skills) => skills,
Err(error) => {
return json::stop(SCHEMA, vec![skill::error_json(&error)], &error, as_json);
}
}
} else {
Vec::new()
};
let key = document.id.to_string();
if as_json {
let fields = json!({ "created": "spec/", "documentKey": key, "skills": skills });
json::print(&json::result(SCHEMA, "created", fields, Vec::new()));
} else {
outln!("created spec/, document key {key}");
skill::report(&skills);
if let Some(suggestion) = merge_driver::suggestion(&GitCommand::default(), root) {
outln!("{suggestion}");
}
}
Finished::success("created")
}