use crate::{
store::definitions::{Artifact, HumanTool},
types::ArtifactName,
};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
use crate::config::Builtin;
const ROOT: &str = ".";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Runs {
Command(String),
Viewer,
Open(PathBuf),
OpenUrl(String),
Read(PathBuf),
List(PathBuf),
Section { file: PathBuf, heading: String },
Help(String),
}
impl Runs {
pub(super) fn parse(
artifacts: &BTreeMap<ArtifactName, Artifact>,
owner: &ArtifactName,
tool: &HumanTool,
) -> Self {
let (builtin, command, args) = match tool {
HumanTool::Viewer(_) => return Self::Viewer,
HumanTool::Command(tool) => (None, tool.command.as_str(), tool.args.as_slice()),
HumanTool::Builtin(tool) => (Some(tool.builtin), "", tool.args.as_slice()),
};
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let place = |id: &str| {
let artifact = artifacts.get(id)?;
let path = artifact.path.value()?;
Some(match artifact.kind.value() {
Some(crate::config::ArtifactKind::File) => Place {
path: path.clone(),
file: true,
},
Some(crate::config::ArtifactKind::Aspect) => Place {
path: path.clone(),
file: false,
},
_ => Place {
path: path.clone(),
file: false,
},
})
};
Self::of(builtin, command, &args, &place, owner)
}
pub(super) fn declared(
artifacts: &BTreeMap<ArtifactName, crate::config::Artifact>,
owner: &ArtifactName,
tool: &crate::config::HumanTool,
) -> Self {
use crate::config::HumanTool;
let (builtin, command, args) = match tool {
HumanTool::Viewer(_) => return Self::Viewer,
HumanTool::Command(tool) => (None, tool.command.as_str(), tool.args.as_slice()),
HumanTool::Builtin(tool) => (Some(tool.builtin), "", tool.args.as_slice()),
};
let args: Vec<String> = args.iter().map(ToString::to_string).collect();
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let place = |id: &str| {
let artifact = artifacts.get(id)?;
Some(Place {
path: artifact.path.clone(),
file: artifact.kind() == crate::config::ArtifactKind::File,
})
};
Self::of(builtin, command, &args, &place, owner)
}
fn of(
builtin: Option<Builtin>,
command: &str,
args: &[&str],
place: &dyn Fn(&str) -> Option<Place>,
owner: &ArtifactName,
) -> Self {
let target = |arg| logical(place, owner, arg);
match (builtin, args) {
(Some(Builtin::Open), [url]) if artifactize_tools::builtin::is_url(url) => {
Self::OpenUrl((*url).to_owned())
}
(Some(Builtin::Open), [arg]) => match target(arg) {
Target::Live(url) if artifactize_tools::builtin::is_url(&url) => Self::OpenUrl(url),
target => Self::Open(target.into_path()),
},
(Some(Builtin::Read), [arg]) => Self::Read(target(arg).into_path()),
(Some(Builtin::List), [arg]) => Self::List(target(arg).into_path()),
(Some(Builtin::Section), [arg, heading]) => Self::Section {
file: target(arg).into_path(),
heading: (*heading).to_owned(),
},
(Some(Builtin::Help), [program, subcommands @ ..]) => {
let program = crate::platform::program_text(program);
Self::Help(super::shell(
std::iter::once(program.as_str()).chain(subcommands.iter().copied()),
))
}
_ => {
let program = builtin
.map(|builtin| {
match builtin {
Builtin::Read => "read",
Builtin::List => "list",
Builtin::Glob => "glob",
Builtin::Grep => "grep",
Builtin::ViewImage => "view_image",
Builtin::Section => "section",
Builtin::Help => "help",
Builtin::Open => "open",
Builtin::Graph => "graph",
Builtin::Declarations => "declarations",
}
.to_owned()
})
.unwrap_or_else(|| crate::platform::program_text(command));
Self::Command(super::shell(
std::iter::once(program.as_str()).chain(args.iter().copied()),
))
}
}
}
pub fn line(&self) -> String {
match self {
Self::Viewer => "Open Artifact Viewer".into(),
Self::Command(command) => format!("$ {command}"),
Self::Open(path) => format!(
"opens {} in its default app",
crate::platform::path_text(path)
),
Self::OpenUrl(url) => format!("opens {url} in the browser"),
Self::Read(path) => format!("prints {}", crate::platform::path_text(path)),
Self::List(path) => format!("lists {}", folder(&crate::platform::path_text(path))),
Self::Section { file, heading } => format!(
"prints section \"{heading}\" of {}",
crate::platform::path_text(file)
),
Self::Help(program) => format!("prints {program} --help"),
}
}
}
struct Place {
path: crate::config::Target,
file: bool,
}
fn folder(path: &str) -> String {
if path.ends_with('/') {
path.to_owned()
} else {
format!("{path}/")
}
}
enum Target {
Path(PathBuf),
Live(String),
}
impl Target {
fn into_path(self) -> PathBuf {
match self {
Self::Path(path) => path,
Self::Live(address) => PathBuf::from(address),
}
}
}
fn logical(place: &dyn Fn(&str) -> Option<Place>, owner: &ArtifactName, arg: &str) -> Target {
let (id, rest) = match arg.strip_prefix('{').and_then(|arg| arg.split_once('}')) {
Some(("artifactPath", rest)) => (owner.as_str(), rest),
Some((name, rest)) => (name, rest),
None => (owner.as_str(), arg),
};
let rest = rest.strip_prefix('/').unwrap_or(rest);
let Some(artifact) = place(id) else {
return Target::Path(PathBuf::from(arg));
};
if let Some(uri) = artifact.path.uri() {
return Target::Live(if rest.is_empty() {
uri.to_string()
} else {
format!("{uri}/{rest}")
});
}
let path = artifact
.path
.local()
.expect("a non-Live target has a local path");
if rest.is_empty() {
return Target::Path(if path.as_os_str().is_empty() {
PathBuf::from(ROOT)
} else {
path.to_owned()
});
}
let base = if artifact.file {
path.parent().unwrap_or(Path::new(""))
} else {
path
};
Target::Path(base.join(rest))
}