//! The `onetaskgraph` command.
//!
//! Every user-facing journey is proven by driving this binary as a subprocess and
//! asserting on its exit code, stdout and stderr — see `tests/`. Nothing in here is
//! proven by calling it in-process, because the thing being checked is what a user's
//! shell sees.
mod cli;
mod render;
mod rendered;
mod template;
mod update;
use std::io::{self, Write};
use std::process::ExitCode;
use std::str::FromStr as _;
use std::sync::OnceLock;
use clap::{CommandFactory as _, Parser};
use onetaskgraph_core::config::{self, Layer};
use onetaskgraph_core::{
CopyItems, CopyRequest, CopyScope, Delivered, DeliveryOutcome, DependencyRequest,
DocumentFilters, DocumentRequest, Engine, Environment, Failure, FailureDocument, Filters,
GlobalId, LabelRequest, Loaded, MatchBy, OutputFormat, PageToken, Paging, ProjectRequest,
ProjectSelector, QueryResponse, RenderedRecord, SearchRequest, SourceFailure, TaskRequest,
};
use onetaskgraph_plugin_api::{
CommentBody, LabelFilter, MetadataKey, MetadataRecord, NativeId, NewComment, SharedClock,
SourceName, TextQuery, system_clock,
};
use onetaskgraph_status_options::{
FieldsReport, GitHubProjectsConfig, SetupMode, StatusOptionsReport,
};
use serde::Serialize;
use crate::cli::{
Cli, Command, CommentCommand, ConfigCommand, ContentCommand, CopyArgs, DependencyArgs,
DocumentCommand, DocumentFilterArgs, FilterArgs, LabelCommand, MetadataCommand,
MetadataSetArgs, PageArgs, PriorityCommand, ProjectCommand, SelectionArgs, ShowArgs,
SourcesCommand, StatusCommand, TaskCommand,
};
/// Everything asked for was answered, by every source asked. Nothing else exits `0`.
const EXIT_OK: u8 = 0;
/// Something went wrong while doing what was asked. Distinct from [`EXIT_USAGE`], so a
/// caller can tell "you typed it wrong" from "it broke".
const EXIT_FAILURE: u8 = 1;
/// The invocation itself was wrong. Clap's own code for that, used here too: a `--set`
/// that is not `PATH=VALUE` is the same kind of mistake as an unknown flag, and a caller
/// that branches on the code cannot be asked to know which of the two spotted it.
const EXIT_USAGE: u8 = 2;
/// The query ran, some sources answered and at least one did not. A distinct code
/// because a caller scripting around this has to be able to tell a partial answer from a
/// complete one without parsing prose — `--allow-partial` is how a caller says it will
/// accept the answer anyway, and then this run exits `EXIT_OK` instead.
///
/// A write that landed and could not keep a task it delivers in step exits this too: what the
/// command was asked to do happened, and part of what follows from it did not.
const EXIT_PARTIAL: u8 = 4;
/// One thread is enough: the concurrency the engine needs is several sources waiting on
/// I/O at once, which one thread interleaves, not several sources computing at once.
#[tokio::main(flavor = "current_thread")]
async fn main() -> ExitCode {
let cli = Cli::parse();
if let Command::PluginServe { source } = &cli.command {
let input = io::BufReader::new(io::stdin().lock());
return match onetaskgraph_core::serve_plugin(input, io::stdout().lock(), *source).await {
Ok(()) => ExitCode::SUCCESS,
Err(error) => fail(&error.to_string(), EXIT_FAILURE),
};
}
// The configuration flags are global — they parse on every verb, because every verb
// the engine adds will read them — so the layer they make is built before any verb
// runs. A malformed `--set` is then refused wherever it was written rather than only
// on the verbs that happen to read the configuration today, and it is refused as the
// typing mistake it is.
let flags = match cli.overrides.layer() {
Ok(flags) => flags,
Err(message) => return fail(&message, EXIT_USAGE),
};
let environment = Environment::from_process();
// Settled once, before any source is built: every in-process source this run builds paces
// and backs off on this one clock — the real one unless a test put this process on a
// simulated clock, which it attaches to here, as the client the variable names.
match onetaskgraph_core::process_clock(&environment) {
Ok(clock) => {
let _ = CLOCK.set(clock);
}
Err(message) => return fail(&message, EXIT_FAILURE),
}
// Every verb validates the configuration it was handed, including the verbs that do
// not read it. An unknown field, an unusable value, a plugin this build does not
// have and a source name that breaks the pattern are mistakes wherever they were
// written, and a verb that answered anyway would drop them in silence — which is the
// one outcome this configuration layer is not allowed to have.
let loaded = match load(&flags, &environment) {
Ok(loaded) => loaded,
Err(failure) => {
let asked = config::requested_output(
std::env::current_dir().ok().as_deref(),
&environment,
&flags,
);
return failed(&failure, asked);
}
};
match run(&cli.command, &loaded, &mut io::stdout().lock()).await {
Ok(code) => ExitCode::from(code),
Err(failure) => failed(&failure, loaded.config.output()),
}
}
/// Report `message` on stderr and exit with `code`.
///
/// Best effort, never a panic: a standard error that has gone away — the terminal a prompt was
/// on hung up — cannot be told why, and the exit code still says the run failed.
fn fail(message: &str, code: u8) -> ExitCode {
let _ = writeln!(io::stderr(), "onetaskgraph: {message}");
ExitCode::from(code)
}
/// Report a failed command, and exit [`EXIT_FAILURE`].
///
/// The stderr line is the same whatever the output format. Under machine output the
/// failure is also written to stdout as the one [`FailureDocument`] a caller branches on —
/// and as nothing else, because stdout is where a caller reads an answer and one document
/// is what it parses. A usage failure never reaches here: it is the invocation that was
/// wrong, and [`fail`] reports it at [`EXIT_USAGE`] with no document.
fn failed(failure: &Failure, output: OutputFormat) -> ExitCode {
let code = fail(failure.message(), EXIT_FAILURE);
if output == OutputFormat::Json {
let document = FailureDocument {
failure: failure.clone(),
};
// Best effort, and deliberately silent: the stderr line above already said why the
// command failed, and a reader that has gone away cannot be told anything more.
if let Ok(rendered) = json(&document, "the failure") {
let _ = emit(&mut io::stdout().lock(), &rendered, "the failure");
}
}
code
}
/// Render what one command answers with and write it to `out`.
///
/// Rendering and writing are separate on purpose, and every verb shares the one write:
/// a closed reader is the same failure whichever verb was writing, and one path is one
/// path to get right.
async fn run(command: &Command, loaded: &Loaded, out: &mut impl Write) -> Result<u8, Failure> {
// One match over every verb rather than a pre-dispatch and a second match: two
// matches over one enum means one of them owes an answer for arms it never receives,
// and an arm nothing can reach is an arm nothing checks. The engine is built inside
// the arms that need one, so `schema` and `config show` still answer on a host where
// a source cannot be built at all.
match command {
Command::PluginServe { .. } => unreachable!("plugin serving is dispatched before config"),
Command::Schema => {
emit(out, schema_bundle()?.trim_end(), "the schema bundle")?;
Ok(EXIT_OK)
}
Command::Config {
command: ConfigCommand::Show,
} => {
emit(
out,
effective_config(loaded)?.trim_end(),
"the configuration",
)?;
Ok(EXIT_OK)
}
Command::Sources {
command: SourcesCommand::List,
} => {
let listings = engine(loaded).listing();
let rendered = match loaded.config.output() {
OutputFormat::Text => render::sources(&listings),
OutputFormat::Json => json(&listings, "the sources")?,
};
emit(out, rendered.trim_end(), "the sources")?;
Ok(EXIT_OK)
}
Command::Sources {
command: SourcesCommand::Route(args),
} => {
// Configuration alone: no engine is built, so no source is constructed or asked.
let route = source_route(loaded, &args.source, &args.repository)?;
let rendered = match loaded.config.output() {
OutputFormat::Text => render::source_route(&route),
OutputFormat::Json => json(&route, "the route")?,
};
emit(out, rendered.trim_end(), "the route")?;
Ok(EXIT_OK)
}
Command::Sources {
command: SourcesCommand::StatusOptions(args),
} => {
let (name, config) = github_projects_source(loaded, &args.source, "status-options")?;
let report = onetaskgraph_status_options::reconcile(
&name,
config,
&loaded.secrets,
setup_mode(args.apply),
)
.await
.map_err(|error| {
Failure::decided("status-options", format!("source {name}: {error}"))
})?;
let rendered = match loaded.config.output() {
OutputFormat::Json => json(&report, "the status-options report")?,
OutputFormat::Text => render::status_options(&report),
};
emit(out, rendered.trim_end(), "the status-options report")?;
Ok(EXIT_OK)
}
Command::Sources {
command: SourcesCommand::Fields(args),
} => {
if let Some((name, config)) = linear_source(loaded, &args.source)? {
let report =
onetaskgraph_linear::status_names(&name, config, &loaded.secrets, args.apply)
.await
.map_err(|error| {
Failure::decided("fields", format!("source {name}: {error}"))
})?;
let rendered = match loaded.config.output() {
OutputFormat::Json => json(&report, "the fields report")?,
OutputFormat::Text => render::status_names(&report),
};
emit(out, rendered.trim_end(), "the fields report")?;
if let Some(refused) = &report.refused {
let kind = match refused.kind {
onetaskgraph_plugin_api::ItemKind::Task => "task",
onetaskgraph_plugin_api::ItemKind::Project => "project",
};
return Err(Failure::decided(
"fields",
format!(
"source {name}: the create of the {kind} status {:?} failed: {}; \
every name the report marks created was created before it.\n\
next: fix what that names (a key without permission to change \
team or workspace settings, say), then run `onetaskgraph sources \
fields {name} --apply` again, which creates only what is still \
missing.",
refused.name.as_str(),
refused.message
),
));
}
return Ok(EXIT_OK);
}
let (name, config) = github_projects_source(loaded, &args.source, "fields")?;
let report = onetaskgraph_status_options::reconcile_fields(
&name,
config,
&loaded.secrets,
setup_mode(args.apply),
)
.await
.map_err(|error| Failure::decided("fields", format!("source {name}: {error}")))?;
let rendered = match loaded.config.output() {
OutputFormat::Json => json(&report, "the fields report")?,
OutputFormat::Text => render::fields(&report),
};
emit(out, rendered.trim_end(), "the fields report")?;
Ok(EXIT_OK)
}
Command::Task {
command: TaskCommand::List(args),
} => {
let engine = engine(loaded);
let project = selector(&engine, args.project.as_deref(), args.no_project);
if args.members && !matches!(project, ProjectSelector::Qualified(_)) {
return Err(Failure::decided(
"members-unqualified",
format!(
"--members reads the member projects one home names, so --project \
has to name that home by its qualified id, and {:?} is not one\n\
next: write --project <source>:<project-id>.",
args.project.as_deref().unwrap_or_default()
),
));
}
let request = TaskRequest {
sources: selection(&args.selection)?,
filters: filters(&args.filters)?,
project,
priorities: args
.priority
.iter()
.map(|priority| priority.priority())
.collect(),
commented_since: args.commented_since,
metadata: args.metadata.clone(),
origin: args.origin.clone(),
include_members: args.members,
paging: paging(loaded, &args.paging)?,
};
let response = engine
.tasks(&request)
.await
.map_err(|error| Failure::from(&error))?;
respond(out, loaded, response, render::tasks, &args.paging, "tasks")
}
Command::Task {
command: TaskCommand::Show(args),
} => {
let id = qualified(&args.item.id)?;
let detail = if args.no_comments {
engine(loaded)
.task_without_comments(&id)
.await
.map_err(|error| Failure::from(&error))?
} else {
engine(loaded)
.task_detail(&id)
.await
.map_err(|error| Failure::from(&error))?
};
// The comments ride beside the task in the machine rendering, and after its body
// in the human one — and not at all for a source whose tasks have none.
let comments = detail.comments.as_deref();
let assets = detail.assets.as_deref();
show_rendered(
out,
loaded,
&detail.response,
&detail,
|task| render::task_with_comments(task, comments, assets),
&args.item,
"task",
)
}
Command::Task {
command: TaskCommand::ShowMany(args),
} => {
let ids = args
.ids
.iter()
.map(|id| qualified(id))
.collect::<Result<Vec<_>, _>>()?;
let details = engine(loaded).task_details(&ids, !args.no_comments).await;
let rendered = match loaded.config.output() {
OutputFormat::Json => json(&details, "the tasks")?,
OutputFormat::Text => render::task_details(&ids, &details),
};
emit(out, rendered.trim_end(), "the tasks")?;
Ok(details_exit(&ids, &details))
}
Command::Task {
command: TaskCommand::Comment { command },
} => comment(out, loaded, command).await,
Command::Task {
command:
TaskCommand::Status {
command: StatusCommand::Set(args),
},
} => {
let task = qualified(&args.id)?;
let set = engine(loaded)
.set_task_status(&task, args.category.category())
.await
.map_err(|error| Failure::from(&error))?;
let rendered = rendering(loaded, &set, render::status_set, "the status")?;
emit(out, rendered.trim_end(), "the status")?;
Ok(delivery_exit(&set.delivered))
}
Command::Task {
command:
TaskCommand::Priority {
command: PriorityCommand::Set(args),
},
} => {
let task = qualified(&args.id)?;
let set = engine(loaded)
.set_task_priority(&task, args.priority.priority())
.await
.map_err(|error| Failure::from(&error))?;
let rendered = rendering(loaded, &set, render::priority_set, "the priority")?;
emit(out, rendered.trim_end(), "the priority")?;
Ok(EXIT_OK)
}
Command::Task {
command:
TaskCommand::Content {
command: ContentCommand::Set(args),
},
} => {
// The file is read, and refused, before anything is built or asked: a content
// write that could not be read reaches no source.
let task = qualified(&args.id)?;
let content = content(&args.file)?;
let set = engine(loaded)
.set_task_content(&task, &content)
.await
.map_err(|error| Failure::from(&error))?;
let rendered = rendering(loaded, &set, render::content_set, "the content")?;
emit(out, rendered.trim_end(), "the content")?;
Ok(EXIT_OK)
}
Command::Task {
command:
TaskCommand::Metadata {
command: MetadataCommand::Set(args),
},
} => metadata_set(out, loaded, MetadataRecord::Task, args).await,
Command::Project {
command:
ProjectCommand::Metadata {
command: MetadataCommand::Set(args),
},
} => metadata_set(out, loaded, MetadataRecord::Project, args).await,
Command::Task {
command: TaskCommand::Update(args),
} => update::update_task(out, loaded, args).await,
Command::Task {
command: TaskCommand::Create(args),
} => rendered::create_task(out, loaded, args).await,
Command::Task {
command: TaskCommand::Render(args),
} => {
rendered::regenerate(
out,
loaded,
RenderedRecord::Task,
&args.render,
&args.assets.asset,
)
.await
}
Command::Task {
command: TaskCommand::Answers(args),
} => rendered::stored(out, loaded, RenderedRecord::Task, args).await,
Command::Project {
command: ProjectCommand::Create(args),
} => rendered::create_project(out, loaded, args).await,
Command::Project {
command: ProjectCommand::Render(args),
} => rendered::regenerate(out, loaded, RenderedRecord::Project, args, &[]).await,
Command::Project {
command: ProjectCommand::Answers(args),
} => rendered::stored(out, loaded, RenderedRecord::Project, args).await,
Command::Document {
command: DocumentCommand::Create(args),
} => rendered::create_document(out, loaded, args).await,
Command::Document {
command: DocumentCommand::Render(args),
} => {
rendered::regenerate(
out,
loaded,
RenderedRecord::Document,
&args.render,
&args.assets.asset,
)
.await
}
Command::Document {
command: DocumentCommand::Answers(args),
} => rendered::stored(out, loaded, RenderedRecord::Document, args).await,
Command::Document {
command:
DocumentCommand::Metadata {
command: MetadataCommand::Set(args),
},
} => metadata_set(out, loaded, MetadataRecord::Document, args).await,
Command::Task {
command: TaskCommand::Deps(args),
} => {
let request = dependency_request(loaded, args)?;
let response = engine(loaded)
.task_dependencies(&request)
.await
.map_err(|error| Failure::from(&error))?;
respond(
out,
loaded,
response,
render::edges,
&args.paging,
"dependencies",
)
}
Command::Task {
command: TaskCommand::Copy(args),
} => {
let mut request = copy_request(
args.id.iter().map(String::as_str),
CopyScope::Tasks,
&args.copy,
)?;
request.create = args.create;
copy(out, loaded, &request).await
}
Command::Project {
command: ProjectCommand::Copy(args),
} => {
let members = args
.member
.iter()
.map(|member| qualified(member))
.collect::<Result<Vec<_>, _>>()?;
let scope = match CopyItems::new(members) {
Some(members) => CopyScope::Members(members),
None => CopyScope::Projects {
tasks: !args.no_tasks,
},
};
let request = copy_request(std::iter::once(args.id.as_str()), scope, &args.copy)?;
copy(out, loaded, &request).await
}
Command::Project {
command: ProjectCommand::List(args),
} => {
let request = ProjectRequest {
sources: selection(&args.selection)?,
filters: filters(&args.filters)?,
paging: paging(loaded, &args.paging)?,
};
let response = engine(loaded)
.projects(&request)
.await
.map_err(|error| Failure::from(&error))?;
respond(
out,
loaded,
response,
render::projects,
&args.paging,
"projects",
)
}
Command::Project {
command: ProjectCommand::Show(args),
} => {
let response = engine(loaded)
.project(&qualified(&args.id)?)
.await
.map_err(|error| Failure::from(&error))?;
show(
out,
loaded,
response,
render::project_detail,
args,
"project",
)
}
Command::Project {
command: ProjectCommand::Deps(args),
} => {
let request = dependency_request(loaded, args)?;
let response = engine(loaded)
.project_dependencies(&request)
.await
.map_err(|error| Failure::from(&error))?;
respond(
out,
loaded,
response,
render::edges,
&args.paging,
"dependencies",
)
}
Command::Document {
command: DocumentCommand::List(args),
} => {
let engine = engine(loaded);
let request = DocumentRequest {
sources: selection(&args.selection)?,
filters: document_filters(&args.filters),
project: selector(&engine, args.project.as_deref(), args.no_project),
paging: paging(loaded, &args.paging)?,
};
let response = engine
.documents(&request)
.await
.map_err(|error| Failure::from(&error))?;
respond(
out,
loaded,
response,
render::documents,
&args.paging,
"documents",
)
}
Command::Document {
command: DocumentCommand::Show(args),
} => {
let detail = engine(loaded)
.document_detail(&qualified(&args.id)?)
.await
.map_err(|error| Failure::from(&error))?;
// The assets ride beside the document in the machine rendering, and after its body
// in the human one.
let assets = detail.assets.as_deref();
show_rendered(
out,
loaded,
&detail.response,
&detail,
|document| render::document_with_assets(document, assets),
args,
"document",
)
}
Command::Document {
command: DocumentCommand::Copy(args),
} => {
let request = copy_request(
args.id.iter().map(String::as_str),
CopyScope::Documents,
&args.copy,
)?;
copy(out, loaded, &request).await
}
Command::Label {
command: LabelCommand::List(args),
} => {
let request = LabelRequest {
sources: selection(&args.selection)?,
paging: paging(loaded, &args.paging)?,
};
let response = engine(loaded)
.labels(&request)
.await
.map_err(|error| Failure::from(&error))?;
respond(
out,
loaded,
response,
render::labels,
&args.paging,
"labels",
)
}
Command::Template { command } => template::run(out, loaded, command),
Command::Search(args) => {
let request = SearchRequest {
sources: selection(&args.selection)?,
text: TextQuery {
terms: args.text.clone(),
fields: args.fields.fields(),
},
kind: args.kind.kind(),
paging: paging(loaded, &args.paging)?,
};
let response = engine(loaded)
.search(&request)
.await
.map_err(|error| Failure::from(&error))?;
respond(
out,
loaded,
response,
render::hits,
&args.paging,
"the search",
)
}
}
}
/// The process's one clock, settled in `main` before any source is built.
static CLOCK: OnceLock<SharedClock> = OnceLock::new();
fn engine(loaded: &Loaded) -> Engine {
Engine::build_with_clock(
&loaded.config,
&loaded.secrets,
CLOCK.get_or_init(system_clock),
)
}
/// Write one page, report the sources that could not contribute, and say what the run
/// amounts to.
///
/// The failures go to standard error rather than into the rendered rows, so a text
/// answer piped into another program stays rows and nothing else while the person
/// running it still learns that a source was missing.
fn respond<T: Serialize>(
out: &mut impl Write,
loaded: &Loaded,
response: QueryResponse<T>,
text: impl FnOnce(&[T]) -> String,
paging: &PageArgs,
what: &str,
) -> Result<u8, Failure> {
let rendered = match loaded.config.output() {
OutputFormat::Text => {
let mut rendered = text(&response.items);
if paging.explain {
rendered.push('\n');
rendered.push_str(&render::plan(&response.plan));
}
// Without this a caller reading a terminal has no way to reach page two: the
// token is the engine's own encoding and there is nothing else to type.
if let Some(next) = &response.next {
rendered.push_str(&format!("\nnext page: --page {next}\n"));
}
rendered
}
// The plan and the failures are fields of the response itself here, so
// `--explain` adds nothing a machine reader did not already have.
OutputFormat::Json => json(&response, what)?,
};
emit(out, rendered.trim_end(), what)?;
Ok(report(&response.errors, paging.allow_partial))
}
/// Write one item, or say plainly that there is no such item.
fn show<T: Serialize>(
out: &mut impl Write,
loaded: &Loaded,
response: QueryResponse<T>,
text: impl FnOnce(&T) -> String,
args: &ShowArgs,
what: &str,
) -> Result<u8, Failure> {
show_rendered(out, loaded, &response, &response, text, args, what)
}
/// [`show`], where the machine rendering is a document that carries the response rather than
/// the response itself — `task show`, whose document carries the task's comments beside it.
fn show_rendered<T>(
out: &mut impl Write,
loaded: &Loaded,
response: &QueryResponse<T>,
machine: &impl Serialize,
text: impl FnOnce(&T) -> String,
args: &ShowArgs,
what: &str,
) -> Result<u8, Failure> {
match (response.items.first(), response.errors.is_empty()) {
(None, true) => Err(Failure::decided(
"no-such-item",
format!(
"no {what} with that id\n\
next: check the id, or list what is there — `onetaskgraph {what} list` \
reports every {what} the configured sources hold."
),
)),
_ => {
let rendered = match loaded.config.output() {
OutputFormat::Text => {
let mut rendered = response.items.first().map(text).unwrap_or_default();
if args.explain {
rendered.push('\n');
rendered.push_str(&render::plan(&response.plan));
}
rendered
}
OutputFormat::Json => json(machine, what)?,
};
emit(out, rendered.trim_end(), what)?;
Ok(report(&response.errors, args.allow_partial))
}
}
}
/// Where an item with `repositories`, written to the source named `source`, would land.
fn source_route(
loaded: &Loaded,
source: &str,
repositories: &[onetaskgraph_plugin_api::Repository],
) -> Result<onetaskgraph_core::config::SourceRoute, Failure> {
let unknown = || {
Failure::from(&onetaskgraph_core::EngineError::UnknownSource {
name: source.to_owned(),
configured: loaded
.config
.sources()
.keys()
.map(SourceName::as_str)
.collect::<Vec<_>>()
.join(", "),
})
};
let name = SourceName::try_from(source.to_owned()).map_err(|_| unknown())?;
if !loaded.config.sources().contains_key(&name) {
return Err(unknown());
}
Ok(onetaskgraph_core::config::SourceRoute {
placement: loaded.config.routes().place(&name, repositories),
source: name,
})
}
/// The configured `github-projects` source a guarded board setup verb names, and its
/// configuration, refused with `verb` as the failure's kind when there is no such source or it
/// is not a `github-projects` one.
fn github_projects_source(
loaded: &Loaded,
source: &str,
verb: &str,
) -> Result<(SourceName, GitHubProjectsConfig), Failure> {
// llmlint: ignore-block[changed_behavior_has_e2e] The status-options and fields journeys
// drive this boundary through unknown and wrong-plugin sources. Invalid source tokens and
// malformed plugin configuration are the shared configuration boundary's existing
// validation, while construction errors are exercised by this plugin's configuration tests
// rather than duplicated for each CLI verb.
let name = SourceName::try_from(source.to_owned())
.map_err(|message| Failure::decided("invalid-source", message.to_string()))?;
let configured =
loaded.config.sources().get(&name).ok_or_else(|| {
Failure::decided(verb, format!("no configured source is named {name}"))
})?;
if configured.plugin() != onetaskgraph_core::PluginKind::GithubProjects {
// `fields` reads a Linear source too, which `linear_source` took before this.
let available = if verb == "fields" {
"github-projects and linear sources"
} else {
"github-projects sources"
};
return Err(Failure::decided(
verb,
format!(
"source {name} uses plugin {}, not github-projects; {verb} is only available for {available}",
configured.plugin()
),
));
}
let config: GitHubProjectsConfig = serde_json::from_value(configured.config().clone())
.map_err(|error| Failure::decided(verb, format!("source {name}: {error}")))?;
// llmlint: ignore-end[changed_behavior_has_e2e]
Ok((name, config))
}
/// The configured `linear` source `source` names, with its configuration, or `None` when it
/// names a source of another plugin — which `github_projects_source` then answers for.
fn linear_source(
loaded: &Loaded,
source: &str,
) -> Result<Option<(SourceName, onetaskgraph_linear::LinearConfig)>, Failure> {
let Ok(name) = SourceName::try_from(source.to_owned()) else {
return Ok(None);
};
let Some(configured) = loaded.config.sources().get(&name) else {
return Ok(None);
};
if configured.plugin() != onetaskgraph_core::PluginKind::Linear {
return Ok(None);
}
let config = serde_json::from_value(configured.config().clone())
.map_err(|error| Failure::decided("fields", format!("source {name}: {error}")))?;
Ok(Some((name, config)))
}
/// Whether a guarded board setup verb plans or applies, from its `--apply` flag.
fn setup_mode(apply: bool) -> SetupMode {
if apply {
SetupMode::Apply
} else {
SetupMode::Plan
}
}
/// Drive one comment verb and write what it answered.
///
/// Each is one call to one source, so there is no partial answer to report: a refusal is
/// the command failing, with the engine's own problem and next action.
async fn comment(
out: &mut impl Write,
loaded: &Loaded,
command: &CommentCommand,
) -> Result<u8, Failure> {
let rendered = match command {
CommentCommand::Add(args) => {
// The body is read and refused before anything is built or read, so an empty
// one never reaches a source.
let comment = NewComment {
body: body(args.body_file.as_deref())?,
author: args.author.clone(),
};
let task = qualified(&args.id)?;
let added = engine(loaded)
.add_comment(&task, &comment)
.await
.map_err(|error| Failure::from(&error))?;
rendering(loaded, &added, render::comment, "the comment")?
}
CommentCommand::List(args) => {
let task = qualified(&args.id)?;
let listed = engine(loaded)
.comments(&task)
.await
.map_err(|error| Failure::from(&error))?;
rendering(loaded, &listed, render::comments, "the comments")?
}
CommentCommand::Edit(args) => {
let body = body(args.body_file.as_deref())?;
let task = qualified(&args.id)?;
let edited = engine(loaded)
.edit_comment(&task, &args.comment_id, &body)
.await
.map_err(|error| Failure::from(&error))?;
rendering(loaded, &edited, render::comment, "the comment")?
}
CommentCommand::Delete(args) => {
let task = qualified(&args.id)?;
let deleted = engine(loaded)
.delete_comment(&task, &args.comment_id)
.await
.map_err(|error| Failure::from(&error))?;
rendering(loaded, &deleted, render::deleted, "the deletion")?
}
};
emit(out, rendered.trim_end(), "the comment")?;
Ok(EXIT_OK)
}
/// One answer, in the format the configuration asks for.
fn rendering<T: Serialize>(
loaded: &Loaded,
value: &T,
text: impl FnOnce(&T) -> String,
what: &str,
) -> Result<String, Failure> {
match loaded.config.output() {
OutputFormat::Text => Ok(text(value)),
OutputFormat::Json => json(value, what),
}
}
/// A comment's body, read byte for byte from `path`, or from standard input without one.
///
/// Never trimmed and never normalised: a trailing newline is part of what was written. Text
/// that is not UTF-8 is refused rather than repaired, because a repaired body is not the one
/// the caller wrote.
fn body(path: Option<&std::path::Path>) -> Result<CommentBody, Failure> {
let (bytes, from) = match path {
Some(path) => (
std::fs::read(path).map_err(|error| {
Failure::decided(
"comment-body",
format!(
"--body-file {}: could not read it: {error}\n\
next: name a readable file, or leave --body-file out and pass the body on \
standard input.",
path.display()
),
)
})?,
format!("--body-file {}", path.display()),
),
None => {
let mut bytes = Vec::new();
io::Read::read_to_end(&mut io::stdin().lock(), &mut bytes).map_err(|error| {
Failure::decided(
"comment-body",
format!(
"could not read the comment body from standard input: {error}\n\
next: pass the body with --body-file PATH instead."
),
)
})?;
(bytes, "standard input".to_owned())
}
};
let text = String::from_utf8(bytes).map_err(|error| {
Failure::decided(
"comment-body",
format!(
"the comment body on {from} is not UTF-8 text: {error}\n\
next: save the body as UTF-8 and pass it again."
),
)
})?;
CommentBody::new(text).map_err(|_| {
Failure::decided(
"comment-body",
format!(
"the comment body on {from} is empty, and a comment has to say something\n\
next: write the comment's text to {from} and run the command again."
),
)
})
}
/// A task's new content, read byte for byte from `path`.
///
/// Never trimmed and never normalised, for the reason a comment body is not: a trailing
/// newline is part of what was written. Text that is not UTF-8 is refused rather than
/// repaired. An empty file is content like any other — it empties the task's body.
fn content(path: &std::path::Path) -> Result<String, Failure> {
let bytes = std::fs::read(path).map_err(|error| {
Failure::decided(
"content-file",
format!(
"--file {}: could not read it: {error}\n\
next: name a readable file holding the task's new content.",
path.display()
),
)
})?;
String::from_utf8(bytes).map_err(|error| {
Failure::decided(
"content-file",
format!(
"the content in --file {} is not UTF-8 text: {error}\n\
next: save the content as UTF-8 and pass it again.",
path.display()
),
)
})
}
/// Drive the engine's own copy API and write what it did.
///
/// The command line has no copy path of its own: this builds the one public request type
/// and calls the one public method, so a copy typed at a shell and a copy a Rust caller
/// makes cannot answer differently.
async fn copy(out: &mut impl Write, loaded: &Loaded, request: &CopyRequest) -> Result<u8, Failure> {
let report = engine(loaded)
.copy(request)
.await
.map_err(|error| Failure::from(&error))?;
let rendered = match loaded.config.output() {
OutputFormat::Text => render::copied(&report),
OutputFormat::Json => json(&report, "the copy")?,
};
emit(out, rendered.trim_end(), "the copy")?;
Ok(delivery_exit(&report.delivered))
}
/// Set one metadata key of one record.
///
/// The id, the key and the value are each refused, with the next action, before the engine is
/// built — so a mistake in any of them reaches no source, a spawned plugin included.
async fn metadata_set(
out: &mut impl Write,
loaded: &Loaded,
record: MetadataRecord,
args: &MetadataSetArgs,
) -> Result<u8, Failure> {
let id = qualified(&args.id)?;
let key = metadata_key(&args.key)?;
let value = metadata_value(&args.value)?;
let engine = engine(loaded);
let set = match record {
MetadataRecord::Task => engine.set_task_metadata(&id, &key, &value).await,
MetadataRecord::Project => engine.set_project_metadata(&id, &key, &value).await,
MetadataRecord::Document => engine.set_document_metadata(&id, &key, &value).await,
}
.map_err(|error| Failure::from(&error))?;
let rendered = rendering(loaded, &set, render::metadata_set, "the metadata key")?;
emit(out, rendered.trim_end(), "the metadata key")?;
Ok(EXIT_OK)
}
/// A `metadata set` key, refused by name when it is not a caller's own dotted key.
fn metadata_key(key: &str) -> Result<MetadataKey, Failure> {
MetadataKey::new(key).map_err(|message| Failure::decided("invalid-metadata-key", message))
}
/// A `metadata set` value, parsed strictly as one JSON value.
fn metadata_value(value: &str) -> Result<serde_json::Value, Failure> {
serde_json::from_str(value).map_err(|error| {
Failure::decided(
"invalid-metadata-value",
format!(
"the value {value:?} is not JSON: {error}\n\
next: pass exactly one JSON value — quote a string as '\"text\"', and write \
true, false, null, a number, an array or an object as JSON spells them."
),
)
})
}
/// Name every delivered task a write could not keep in step, and say what the exit code will
/// mean.
///
/// The write itself landed, which is why this is [`EXIT_PARTIAL`] rather than a failure: the
/// answer on standard output is the whole of what happened, and standard error says which
/// part of what follows from it did not.
fn delivery_exit(delivered: &[Delivered]) -> u8 {
let mut failed = false;
for entry in delivered {
if let DeliveryOutcome::Failed { failure, .. } = &entry.outcome {
failed = true;
eprintln!(
"onetaskgraph: task {} could not be kept in step with {}: {}",
entry.ticket,
entry.deliverer,
failure.message()
);
}
}
if !failed {
return EXIT_OK;
}
eprintln!(
"onetaskgraph: next: the write itself landed; fix what each task above names, then run \
the same command again — every write of the task re-evaluates what it delivers."
);
EXIT_PARTIAL
}
/// One copy, as a verb that takes one reads it.
fn copy_request<'a>(
ids: impl Iterator<Item = &'a str>,
scope: CopyScope,
args: &CopyArgs,
) -> Result<CopyRequest, Failure> {
let items = ids.map(qualified).collect::<Result<Vec<_>, _>>()?;
Ok(CopyRequest {
items: CopyItems::new(items).ok_or_else(|| {
Failure::decided(
"no-id",
"no id to copy\n\
next: name at least one qualified id — `onetaskgraph task list` reports them.",
)
})?,
scope,
destination: SourceName::new(args.to.clone()).map_err(|error| {
Failure::decided(
"invalid-source-name",
format!(
"--to {}: {error}\n\
next: name a configured source — `onetaskgraph sources list` reports \
them.",
args.to
),
)
})?,
match_by: args.match_by.as_deref().map(MatchBy::parse),
recreate: args.recreate,
// Only `task copy` takes `--create`; it sets this on the request it builds.
create: false,
dry_run: args.dry_run,
})
}
/// Name every source that could not answer, and say what the exit code will mean.
fn report(errors: &[SourceFailure], allow_partial: bool) -> u8 {
if errors.is_empty() {
return EXIT_OK;
}
for failure in errors {
eprintln!(
"onetaskgraph: source {} could not answer: {}",
failure.source, failure.error
);
}
if allow_partial {
eprintln!(
"onetaskgraph: the answer above is partial, and --allow-partial says that is \
acceptable."
);
return EXIT_OK;
}
eprintln!(
"onetaskgraph: next: fix the source(s) named above — `onetaskgraph sources list` \
reports each one's state — or re-run with --allow-partial to accept an answer \
without them."
);
EXIT_PARTIAL
}
/// The exit status of `task show-many`: success when every detail read cleanly, and the
/// partial answer's status — each failure named on standard error — when any carries an
/// error. There is no `--allow-partial` to accept one, because the status is the one place a
/// caller reads, without parsing the details, whether every id was read.
fn details_exit(ids: &[GlobalId], details: &onetaskgraph_core::TaskDetails) -> u8 {
let mut failed = false;
for (id, detail) in ids.iter().zip(&details.details) {
for failure in &detail.response.errors {
failed = true;
eprintln!(
"onetaskgraph: {id}: source {} could not answer: {}",
failure.source, failure.error
);
}
}
if !failed {
return EXIT_OK;
}
eprintln!(
"onetaskgraph: next: each id above carries its failure in its own detail's `errors`; \
fix what it names and show that id again — the details of every other id are whole."
);
EXIT_PARTIAL
}
/// The sources a request addresses, checked against the pattern a name must match.
fn selection(args: &SelectionArgs) -> Result<Vec<SourceName>, Failure> {
args.source
.iter()
.map(|name| {
SourceName::new(name.clone()).map_err(|error| {
Failure::decided(
"invalid-source-name",
format!(
"--source {name}: {error}\n\
next: name a configured source — `onetaskgraph sources list` \
reports them."
),
)
})
})
.collect()
}
/// The filters a list verb was given.
fn filters(args: &FilterArgs) -> Result<Filters, Failure> {
Ok(Filters {
text: args.search.as_ref().map(|terms| TextQuery {
terms: terms.clone(),
fields: args.fields.fields(),
}),
labels: LabelFilter {
// Repeating `--label` narrows rather than widens: a second one is a second
// requirement, which is what a repeated filter flag means everywhere else.
all_of: args.label.clone(),
none_of: args.not_label.clone(),
any_of: Vec::new(),
},
statuses: args.status.iter().map(|status| status.category()).collect(),
})
}
/// The filters a document list was given.
///
/// No statuses: a document has no status, so there is nothing here for one to compare
/// against and no flag that could set one.
fn document_filters(args: &DocumentFilterArgs) -> DocumentFilters {
DocumentFilters {
text: args.search.as_ref().map(|terms| TextQuery {
terms: terms.clone(),
fields: args.fields.fields(),
}),
labels: LabelFilter {
// Repeating `--label` narrows rather than widens, exactly as it does for tasks.
all_of: args.label.clone(),
none_of: args.not_label.clone(),
any_of: Vec::new(),
},
}
}
/// Which project a `task list` was narrowed to.
///
/// A qualified id names one project of one source and narrows the query to it; anything
/// else is a native id every selected source is asked about. Which of the two a string is
/// depends on whether its prefix names a **configured source**, which is why this needs
/// the engine: `urn:project:1` is a native id full of colons on a host with no source
/// called `urn`, and only a host that has one reads it as qualified.
fn selector(engine: &Engine, project: Option<&str>, orphans: bool) -> ProjectSelector {
if orphans {
return ProjectSelector::Orphans;
}
let Some(project) = project else {
return ProjectSelector::Any;
};
match GlobalId::from_str(project) {
Ok(id) if engine.has(&id.source) => ProjectSelector::Qualified(id),
Ok(_) | Err(_) => ProjectSelector::Native(NativeId::from(project)),
}
}
/// One qualified id, as a verb that takes one reads it.
fn qualified(id: &str) -> Result<GlobalId, Failure> {
GlobalId::from_str(id).map_err(|error| {
Failure::decided(
"invalid-id",
format!(
"{error}\n\
next: qualify the id with the source it belongs to — `onetaskgraph sources \
list` reports the configured names."
),
)
})
}
/// Which page a verb was asked for.
fn paging(loaded: &Loaded, args: &PageArgs) -> Result<Paging, Failure> {
let limit = args.limit.unwrap_or_else(|| loaded.config.page_size());
let token = args
.page
.as_ref()
.map(|raw| {
PageToken::parse(raw.clone()).map_err(|error| {
Failure::decided(
"page-token",
format!(
"--page: {error}\n\
next: pass a token exactly as a previous page reported it, or drop \
--page to start the walk again."
),
)
})
})
.transpose()?;
Ok(Paging { limit, token })
}
/// One dependency walk, as a verb that takes one reads it.
fn dependency_request(
loaded: &Loaded,
args: &DependencyArgs,
) -> Result<DependencyRequest, Failure> {
Ok(DependencyRequest {
id: qualified(&args.id)?,
direction: args.direction.direction(),
paging: paging(loaded, &args.paging)?,
})
}
/// One value as pretty-printed JSON.
fn json(value: &impl Serialize, what: &str) -> Result<String, Failure> {
serde_json::to_string_pretty(value)
.map_err(|error| Failure::decided("render", format!("could not render {what}: {error}")))
}
fn json_value(value: impl Serialize, what: &str) -> Result<serde_json::Value, Failure> {
serde_json::to_value(value)
.map_err(|error| Failure::decided("render", format!("could not render {what}: {error}")))
}
/// The schema bundle as pretty-printed JSON.
fn schema_bundle() -> Result<String, Failure> {
let mut bundle = onetaskgraph_core::schema_bundle();
bundle["roots"]["StatusOptionsReport"] = json_value(
schemars::schema_for!(StatusOptionsReport),
"the status-options schema",
)?;
bundle["roots"]["FieldsReport"] =
json_value(schemars::schema_for!(FieldsReport), "the fields schema")?;
// llmlint: ignore-block[code_lands_in_the_domain_that_owns_it] The schema is the Linear plugin's own `StatusNamesReport`, not restated here; what lives here is its registration as the root of what `sources fields` prints for a Linear source, beside the two GitHub Projects reports that verb already registers above. `sources fields` is this binary's verb, the engine crate names no binary output, and a plugin may not depend on the engine (AGENTS.md), so the binary is the one crate that can join a plugin's report to the bundle both SDKs are generated from.
bundle["roots"]["StatusNamesReport"] = json_value(
schemars::schema_for!(onetaskgraph_linear::StatusNamesReport),
"the status names schema",
)?;
// llmlint: ignore-end[code_lands_in_the_domain_that_owns_it]
bundle["commands"] = json_value(public_commands()?, "the command surface")?;
json(&bundle, "the schema bundle")
}
/// Every public leaf command, derived from the same clap tree that parses invocations.
#[derive(Serialize)]
#[serde(transparent)]
struct PublicCommand(String);
impl PublicCommand {
fn try_new(path: String) -> Result<Self, Failure> {
if path.is_empty() || path.split(' ').any(|part| part.is_empty()) {
return Err(Failure::decided(
"render",
format!("invalid public command path {path:?}"),
));
}
Ok(Self(path))
}
}
fn public_commands() -> Result<Vec<PublicCommand>, Failure> {
fn leaves(
command: &clap::Command,
prefix: &str,
commands: &mut Vec<PublicCommand>,
) -> Result<(), Failure> {
let visible: Vec<_> = command
.get_subcommands()
.filter(|child| !child.is_hide_set())
.collect();
if visible.is_empty() {
if !prefix.is_empty() {
commands.push(PublicCommand::try_new(prefix.to_owned())?);
}
return Ok(());
}
for child in visible {
let path = if prefix.is_empty() {
child.get_name().to_owned()
} else {
format!("{prefix} {}", child.get_name())
};
leaves(child, &path, commands)?;
}
Ok(())
}
let mut commands = Vec::new();
leaves(&Cli::command(), "", &mut commands)?;
Ok(commands)
}
/// The effective configuration, in the format it asks for.
fn effective_config(loaded: &Loaded) -> Result<String, Failure> {
match loaded.config.output() {
OutputFormat::Text => Ok(loaded.effective.render_text()),
OutputFormat::Json => json(&loaded.effective, "the configuration"),
}
}
/// Load the configuration: documents, then the environment, then these flags.
fn load(flags: &Layer, environment: &Environment) -> Result<Loaded, Failure> {
let working_directory = std::env::current_dir().map_err(|error| {
Failure::decided(
"working-directory",
format!(
"could not read the working directory: {error}\n\
next: run this from a directory that still exists."
),
)
})?;
config::load(&working_directory, environment, flags).map_err(|error| Failure::from(&error))
}
/// Write `rendered` and a newline, reporting a failed write rather than dying at drop.
///
/// The flush is explicit: a user piping into `head` closes the reader early, and a
/// buffered write that fails at drop would exit zero having emitted a truncated
/// document that a generator would then happily consume.
fn emit(out: &mut impl Write, rendered: &str, what: &str) -> Result<(), Failure> {
let unwritten =
|error: io::Error| Failure::decided("write", format!("could not write {what}: {error}"));
writeln!(out, "{rendered}").map_err(unwritten)?;
out.flush().map_err(unwritten)
}
#[cfg(test)]
mod tests {
use super::*;
/// The command line's priority vocabulary is the contract's, in its order and spelling.
///
/// `PriorityArg` mirrors `Priority` so clap can derive its parser; its `priority` is a
/// wildcard-free match, so a variant added here fails to compile until it is mapped, and
/// this reconciles the two the other way, so a priority the contract gains is one the
/// command line cannot silently lack.
#[test]
fn the_command_lines_priorities_are_the_contracts() {
use clap::ValueEnum as _;
use onetaskgraph_plugin_api::Priority;
let spelled: Vec<(String, Priority)> = crate::cli::PriorityArg::value_variants()
.iter()
.map(|arg| {
(
arg.to_possible_value()
.expect("every variant is spelled")
.get_name()
.to_owned(),
arg.priority(),
)
})
.collect();
let contract: Vec<(String, Priority)> = Priority::ALL
.iter()
.map(|priority| (priority.as_str().to_owned(), *priority))
.collect();
assert_eq!(spelled, contract);
}
struct RefusesSerialization;
impl Serialize for RefusesSerialization {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Err(serde::ser::Error::custom("serialization refused"))
}
}
#[test]
fn a_json_value_reports_a_serialization_failure() {
let failure =
json_value(RefusesSerialization, "the test value").expect_err("serialization fails");
assert_eq!(
failure.message(),
"could not render the test value: serialization refused"
);
}
/// Render and write the schema bundle exactly as [`run`] does for that verb.
///
/// The two steps rather than `run` itself, because `run` first loads the
/// configuration — real documents, the real environment — and these tests are about
/// the rendering and the write path, not about what happens to be on this machine.
/// What `run` does with the configuration is proven where it can be proven honestly:
/// by the journeys in `tests/configuration.rs`, which drive this binary as a
/// subprocess against a sandboxed host.
fn write_schema_bundle(out: &mut impl Write) -> Result<(), Failure> {
emit(out, schema_bundle()?.trim_end(), "the schema bundle")
}
#[test]
fn the_schema_verb_writes_a_bundle_with_every_contract_root() {
let mut out = Vec::new();
write_schema_bundle(&mut out).expect("the bundle renders");
let bundle: serde_json::Value =
serde_json::from_slice(&out).expect("the bundle is valid JSON");
assert!(bundle["roots"]["Task"].is_object());
assert!(bundle["roots"]["StatusOptionsReport"].is_object());
assert!(bundle["roots"]["FieldsReport"].is_object());
assert!(bundle["plugin_config"]["in-memory"].is_object());
assert_eq!(
bundle["commands"],
serde_json::json!([
"schema",
"config show",
"sources list",
"sources status-options",
"sources fields",
"sources route",
"task list",
"task show",
"task show-many",
"task deps",
"task copy",
"task comment add",
"task comment list",
"task comment edit",
"task comment delete",
"task status set",
"task priority set",
"task content set",
"task metadata set",
"task update",
"task create",
"task render",
"task answers",
"project list",
"project show",
"project deps",
"project copy",
"project metadata set",
"project create",
"project render",
"project answers",
"document list",
"document show",
"document copy",
"document metadata set",
"document create",
"document render",
"document answers",
"label list",
"search",
"template variables",
"template render"
])
);
}
/// A sink that refuses the write when `fail_on_write` is set and the flush
/// otherwise, standing in for a reader that went away mid-write and for one that
/// went away between the write and the flush — the two ways
/// `onetaskgraph <verb> | head -1` ends. Every verb writes through the one `emit`
/// below, so driving it for one verb covers the path all of them take.
struct Failing {
fail_on_write: bool,
}
impl Write for Failing {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.fail_on_write {
Err(io::Error::other("the pipe is closed"))
} else {
Ok(buf.len())
}
}
fn flush(&mut self) -> io::Result<()> {
Err(io::Error::other("the pipe closed before the flush"))
}
}
#[test]
fn a_verb_reports_a_failed_write_rather_than_panicking() {
let mut sink = Failing {
fail_on_write: true,
};
let failure = write_schema_bundle(&mut sink).expect_err("writes refused");
let message = failure.message();
assert!(
message.contains("could not write the schema bundle"),
"{message}"
);
}
#[test]
fn a_verb_reports_a_failed_flush_rather_than_exiting_zero_on_a_truncated_document() {
// The dangerous case: the write is buffered and "succeeds", so without an
// explicit flush the process would exit zero having emitted nothing.
let mut sink = Failing {
fail_on_write: false,
};
let failure = write_schema_bundle(&mut sink).expect_err("flushes refused");
let message = failure.message();
assert!(
message.contains("could not write the schema bundle"),
"{message}"
);
}
}