use crate::ui::Style;
use anyhow::{bail, Result};
use eclipse_core::config::{self, process_env, Config, EnvFn};
use eclipse_core::cron::{self, Job, State};
use eclipse_core::runtime::{Agent, AgentEvent};
use eclipse_core::session::now_ms;
use eclipse_core::tools::AllowAll;
use std::path::Path;
pub const DEFAULT_LOGS: usize = 5;
pub fn table(root: &Path, style: &Style) -> Result<String> {
let (jobs, problems) = cron::load_reporting(root)?;
for problem in &problems {
eprintln!("cron: {problem}");
}
let state = cron::load_state(root)?;
let now = now_ms() as i64;
if jobs.is_empty() {
return Ok(format!(
"{}\n add one with `eclipse cron add --name brief --schedule \"daily 07:30\" \\\n\
--prompt \"...\"`, or edit {}",
style.yellow("no jobs are scheduled."),
cron::jobs_path(root).display()
));
}
let name_w = jobs.iter().map(|j| j.name.len()).max().unwrap_or(4).max(4);
let mut out = format!(
"{:<name_w$} {:<18} {:<20} last",
"job",
"schedule",
"next",
name_w = name_w
);
for job in &jobs {
let s = state.get(&job.name);
let next = match cron::next_due_for(job, &state, now) {
None => "— (disabled)".to_string(),
Some(ms) => describe_when(ms, now),
};
let last = match (&s.last_outcome, s.last_started_ms) {
(Some(outcome), Some(at)) => {
format!("{} {}", describe_when_past(at, now), outcome)
}
(None, _) => "never".to_string(),
(Some(outcome), None) => outcome.clone(),
};
out.push_str(&format!(
"\n{:<name_w$} {:<18} {:<20} {}",
job.name,
job.schedule.describe(),
next,
last,
name_w = name_w
));
}
Ok(out)
}
pub fn list(cfg: &Config, root: &Path, json: bool, style: &Style) -> Result<()> {
if let Ok((_, problems)) = cron::load_reporting(root) {
for problem in &problems {
eprintln!("cron: {problem}");
}
}
if json {
let now = now_ms() as i64;
let views = cron::views(root, now)?;
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"now_ms": now,
"jobs_file": cron::jobs_path(root).display().to_string(),
"jobs": views,
}))?
);
return Ok(());
}
println!("{}", table(root, style)?);
if cfg.route_pin.is_some() {
println!(
"\n{}",
style.dim(
"note: --route was given, so this listing is unaffected but `cron run` \
would pin every job to that route"
)
);
}
Ok(())
}
pub async fn run(
cfg: &Config,
root: &Path,
only: Option<&str>,
force: bool,
json: bool,
style: &Style,
) -> Result<i32> {
let jobs = cron::load(root)?;
if jobs.is_empty() {
if only.is_none() {
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"ran": 0,
"jobs": [],
"note": "no jobs are scheduled",
}))?
);
} else {
println!("{}", style.dim("no jobs are scheduled; nothing to do"));
}
return Ok(0);
}
bail!("no jobs are scheduled");
}
let now = now_ms() as i64;
if only.is_none() && !force {
let mut look: State = cron::load_state(root)?;
let seeded = cron::seed_first_seen(&jobs, &mut look, now);
if seeded.is_empty() && cron::due(&jobs, &mut look, now).is_empty() {
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"ran": 0,
"jobs": [],
"note": "nothing to run",
}))?
);
}
return Ok(0);
}
}
let Some(mut tick) = cron::lock(root, now)? else {
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"ran": 0,
"jobs": [],
"note": "a previous run still holds the lock",
}))?
);
} else {
println!(
"{}",
style.dim("a previous run still holds the lock; this tick does nothing")
);
}
return Ok(0);
};
let mut state: State = cron::load_state(root)?;
let seeded = cron::seed_first_seen(&jobs, &mut state, now);
let selected: Vec<Job> = match only {
Some(name) => {
let job = jobs
.iter()
.find(|j| j.name == name)
.ok_or_else(|| {
anyhow::anyhow!("no job named `{name}`; `eclipse cron list` shows the names")
})?
.clone();
vec![job]
}
None => {
let mut due: Vec<Job> = cron::due(&jobs, &mut state, now)
.into_iter()
.cloned()
.collect();
if force {
due = jobs.iter().filter(|j| j.enabled).cloned().collect();
}
due
}
};
if selected.is_empty() && seeded.is_empty() {
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"ran": 0,
"jobs": [],
"note": "nothing to run",
}))?
);
} else if force || only.is_some() {
println!("{}", style.dim("nothing to run"));
}
return Ok(0);
}
if !seeded.is_empty() {
cron::save_state(root, &state)?;
}
if selected.is_empty() {
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"ran": 0,
"jobs": [],
"note": "nothing to run; anchored the jobs added since the last tick",
}))?
);
} else if force || only.is_some() {
println!("{}", style.dim("nothing to run"));
}
return Ok(0);
}
let mut failures = 0usize;
let mut records: Vec<serde_json::Value> = Vec::new();
for job in &selected {
if !tick.touch(now_ms() as i64) {
eprintln!(
"cron: another tick took the lock while this one was working; stopping before `{}`",
job.name
);
break;
}
let started = now_ms() as i64;
state
.jobs
.entry(job.name.clone())
.or_default()
.last_started_ms = Some(started);
state.jobs.entry(job.name.clone()).or_default().runs += 1;
cron::save_state(root, &state)?;
let outcome = run_one(cfg, job).await;
let (body, failed) = match outcome {
Ok((text, hops)) => {
let mut body = format!(
"# {} — {}\n\nschedule {}\n\n",
job.name,
iso_local(started),
job.schedule.describe()
);
if let Some(line) = hops {
body.push_str(&format!("{line}\n\n"));
}
body.push_str("---\n\n");
body.push_str(text.trim_end_matches('\n'));
body.push('\n');
(body, false)
}
Err(e) => {
failures += 1;
let body = format!(
"# {} — failed\n\nstarted {}\n\n---\n\n{}\n",
job.name,
iso_local(started),
e
);
(body, true)
}
};
let mut problems: Vec<String> = Vec::new();
let path = match cron::write_run(root, &job.name, started, &body) {
Ok(path) => Some(path),
Err(e) => {
failures += 1;
problems.push(format!("the run log could not be written: {e}"));
None
}
};
if let Some(deliver) = &job.deliver {
let target = expand_path(deliver);
let written = match target.parent() {
Some(dir) => std::fs::create_dir_all(dir)
.map_err(|e| format!("creating {}: {e}", dir.display())),
None => Ok(()),
}
.and_then(|()| {
let text = if failed {
format!(
"# {} failed at {}\n\n{}\n",
job.name,
iso_local(started),
body
)
} else {
body.clone()
};
std::fs::write(&target, text)
.map_err(|e| format!("writing {}: {e}", target.display()))
});
if let Err(e) = written {
failures += 1;
problems.push(format!("the delivery to {deliver} failed: {e}"));
}
}
if !problems.is_empty() {
if let Some(path) = &path {
let mut text = String::from("\n");
for problem in &problems {
text.push_str(&format!("- {problem}\n"));
}
if let Ok(mut file) = std::fs::OpenOptions::new().append(true).open(path) {
let _ = std::io::Write::write_all(&mut file, text.as_bytes());
}
}
if !json {
for problem in &problems {
println!("{} {}", style.red("problem:"), problem);
}
}
}
let finished = now_ms() as i64;
{
let entry = state.jobs.entry(job.name.clone()).or_default();
entry.last_finished_ms = Some(finished);
entry.last_outcome = Some(if failed {
"failed".to_string()
} else {
"ok".to_string()
});
}
cron::save_state(root, &state)?;
if json {
records.push(serde_json::json!({
"name": job.name,
"ok": !failed,
"outcome": if failed { "failed" } else { "ok" },
"started_ms": started,
"finished_ms": finished,
"log": path.as_ref().map(|p| p.display().to_string()),
"problems": problems,
}));
continue;
}
let mark = if failed {
style.red("failed")
} else {
style.green("ok")
};
println!(
"{} {} {}",
mark,
job.name,
style
.dim(&path.map_or_else(|| "<no run log>".to_string(), |p| p.display().to_string()))
);
}
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"ran": records.len(),
"failed": failures,
"jobs": records,
}))?
);
}
Ok(if failures > 0 { 1 } else { 0 })
}
fn job_config(cfg: &Config, job: &Job) -> Result<Config> {
let mut job_cfg = cfg.clone();
if let Some(route) = &job.route {
job_cfg.pin_route(Some(route), &process_env)?;
}
if let Some(workdir) = &job.workdir {
job_cfg.tools.workspace_root = Some(expand_path(workdir));
}
Ok(job_cfg)
}
async fn run_one(cfg: &Config, job: &Job) -> Result<(String, Option<String>)> {
let job_cfg = job_config(cfg, job)?;
let agent = Agent::from_config(&job_cfg)?;
let shape =
crate::resolve_schema(job.schema.as_deref(), &job_cfg)?.map(crate::Shape::parse_json);
let mut prompt = String::new();
if !job.skills.is_empty() {
let names: Vec<String> = job.skills.iter().map(|s| format!("`{s}`")).collect();
prompt.push_str(&format!(
"Load these skills with the skill_view tool before you start: {}.\n\n",
names.join(", ")
));
}
prompt.push_str(&job.prompt);
let turns = std::sync::Mutex::new(Vec::<String>::new());
let hop_line = std::sync::Mutex::new(None::<String>);
let sink = |event: AgentEvent| {
if let AgentEvent::Message(text) = event {
if let Ok(mut v) = turns.lock() {
v.push(text);
}
}
};
let run = agent
.run_checked(
None,
&prompt,
&AllowAll,
&sink,
&eclipse_core::cancel::Cancel::new(),
&eclipse_core::runtime::RunOptions {
output_schema: shape.as_ref().map(|s| s.schema.clone()),
title: false,
..Default::default()
},
shape.as_ref().map(|s| &*s.check),
)
.await?;
drop(hop_line);
let hops = eclipse_core::router::describe_hops(&run.hops);
let text = turns
.into_inner()
.unwrap_or_default()
.into_iter()
.filter(|t| !t.trim().is_empty())
.collect::<Vec<_>>()
.join("\n\n");
Ok((text, hops))
}
#[allow(clippy::too_many_arguments)]
pub fn add(
root: &Path,
name: &str,
schedule: &str,
prompt: &str,
deliver: Option<&str>,
route: Option<&str>,
workdir: Option<&str>,
skills: Vec<String>,
schema: Option<&str>,
style: &Style,
) -> Result<()> {
if let crate::bang::Line::Bang(_) = crate::bang::parse(prompt) {
bail!(
"{}",
crate::bang::refusal(crate::bang::Surface::Cron).expect("a job has no keyboard")
);
}
if eclipse_core::tasks::bg_prompt(prompt).is_some() {
bail!("{}", eclipse_core::tasks::bg_refusal("a cron job"));
}
if prompt.trim_start().starts_with("/yolo") {
bail!("{}", crate::yolo::refusal("a cron job"));
}
if let Some(source) = schema {
crate::read_schema(source)?;
}
let job = cron::Draft {
name: name.to_string(),
schedule: schedule.to_string(),
prompt: prompt.to_string(),
deliver: deliver.map(|s| s.to_string()),
route: route.map(|s| s.to_string()),
workdir: workdir.map(|s| s.to_string()),
skills,
schema: schema.map(|s| s.to_string()),
enabled: true,
}
.to_job()?;
cron::append_job(root, &job)?;
cron::load(root)?;
println!(
"{} {} ({}) → {}",
style.green("added"),
job.name,
job.schedule.describe(),
cron::jobs_path(root).display()
);
println!(
"{}",
style.dim("`eclipse cron install-timer` makes it run without you")
);
Ok(())
}
pub fn toggle(root: &Path, name: &str, enabled: bool, style: &Style) -> Result<()> {
match cron::set_enabled(root, name, enabled)? {
Some(job) => {
let word = if enabled { "enabled" } else { "disabled" };
println!(
"{} {} ({})",
style.green(word),
job.name,
job.schedule.describe()
);
Ok(())
}
None => bail!("no job named `{name}`; `eclipse cron list` shows the names"),
}
}
pub fn remove(root: &Path, name: &str, style: &Style) -> Result<()> {
if cron::remove_job(root, name)? {
println!("{} {}", style.green("removed"), name);
Ok(())
} else {
bail!("no job named `{name}`")
}
}
pub fn logs(root: &Path, name: &str, limit: usize, json: bool, style: &Style) -> Result<()> {
if json {
if !cron::load(root)?.iter().any(|j| j.name == name) {
bail!("no job named `{name}`");
}
let runs = cron::runs(root, name, limit);
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"job": name,
"runs_dir": cron::runs_dir(root, name).display().to_string(),
"runs": runs,
}))?
);
return Ok(());
}
println!("{}", log_text(root, name, limit, style)?);
Ok(())
}
pub fn log_text(root: &Path, name: &str, limit: usize, style: &Style) -> Result<String> {
if !cron::load(root)?.iter().any(|j| j.name == name) {
bail!("no job named `{name}`; {}", names(root)?);
}
let runs = cron::runs(root, name, limit);
if runs.is_empty() {
return Ok(style.dim("no runs yet"));
}
Ok(runs
.iter()
.map(|run| {
format!(
"{} {}\n {}",
style.dim(&run.at),
run.answer,
style.dim(&run.path)
)
})
.collect::<Vec<_>>()
.join("\n"))
}
pub fn names(root: &Path) -> Result<String> {
let jobs = cron::load(root)?;
if jobs.is_empty() {
return Ok("no jobs are scheduled".to_string());
}
let list: Vec<String> = jobs.iter().map(|j| format!("`{}`", j.name)).collect();
Ok(format!("jobs: {}", list.join(", ")))
}
const SERVICE_NAME: &str = "eclipse-cron.service";
const TIMER_NAME: &str = "eclipse-cron.timer";
fn units_dir_in(env: EnvFn) -> Option<std::path::PathBuf> {
env("HOME").map(|home| {
std::path::PathBuf::from(home)
.join(".config")
.join("systemd")
.join("user")
})
}
fn units_dir() -> Result<std::path::PathBuf> {
units_dir_in(&process_env).ok_or_else(|| anyhow::anyhow!("HOME is not set"))
}
pub fn install_timer(style: &Style) -> Result<()> {
let exe = std::env::current_exe()
.map_err(|e| anyhow::anyhow!("cannot find this program to point the unit at: {e}"))?;
let dir = units_dir()?;
std::fs::create_dir_all(&dir)?;
let service = format!(
"[Unit]\n\
Description=Eclipse scheduled prompts (one tick)\n\
Documentation=file:{}\n\
\n\
[Service]\n\
Type=oneshot\n\
ExecStart={} cron run\n\
# A tick with nothing due exits in milliseconds; the timer wakes every minute.\n\
Nice=5\n",
cron::jobs_path(&config::home_root(&process_env).unwrap_or_default()).display(),
crate::gateway_cli::systemd_word(&exe)
);
let timer = "[Unit]\n\
Description=Tick Eclipse's scheduled prompts every minute\n\
\n\
[Timer]\n\
OnBootSec=1min\n\
OnUnitActiveSec=1min\n\
AccuracySec=10s\n\
# Catch up once after the machine was off, rather than a burst per missed minute.\n\
Persistent=true\n\
\n\
[Install]\n\
WantedBy=timers.target\n";
let service_path = dir.join(SERVICE_NAME);
let timer_path = dir.join(TIMER_NAME);
std::fs::write(&service_path, service)?;
std::fs::write(&timer_path, timer)?;
println!("{} {}", style.green("wrote"), service_path.display());
println!("{} {}", style.green("wrote"), timer_path.display());
let ran = std::process::Command::new("systemctl")
.args(["--user", "daemon-reload"])
.status()
.map(|s| s.success())
.unwrap_or(false)
&& std::process::Command::new("systemctl")
.args(["--user", "enable", "--now", TIMER_NAME])
.status()
.map(|s| s.success())
.unwrap_or(false);
if ran {
println!("{} {}", style.green("enabled"), TIMER_NAME);
println!(
"{}",
style.dim(
" `systemctl --user list-timers eclipse-cron.timer` shows the next tick; \
`journalctl --user -u eclipse-cron.service` shows what ran"
)
);
println!(
"{}",
style.dim(
" to run while you are logged out: loginctl enable-linger $USER (needs root)"
)
);
} else {
println!(
"{}",
style.yellow("systemctl did not take it; enable it by hand with:")
);
println!(" systemctl --user daemon-reload");
println!(" systemctl --user enable --now {TIMER_NAME}");
bail!(
"the units are written to {} but systemctl did not enable the timer — run the two commands above",
dir.display()
);
}
Ok(())
}
pub fn remove_timer(style: &Style) -> Result<()> {
let dir = units_dir()?;
let _ = std::process::Command::new("systemctl")
.args(["--user", "disable", "--now", TIMER_NAME])
.status();
let mut removed = false;
for name in [TIMER_NAME, SERVICE_NAME] {
let path = dir.join(name);
if path.exists() {
std::fs::remove_file(&path)?;
removed = true;
println!("{} {}", style.green("removed"), path.display());
}
}
let _ = std::process::Command::new("systemctl")
.args(["--user", "daemon-reload"])
.status();
if !removed {
println!("{}", style.dim("no timer was installed"));
}
Ok(())
}
pub fn iso_local(ms: i64) -> String {
cron::iso_local(ms)
}
fn describe_when(ms: i64, now: i64) -> String {
let delta = ms - now;
format!("{} ({})", short_when(ms, now), humanize(delta))
}
fn describe_when_past(ms: i64, now: i64) -> String {
let delta = now - ms;
if delta < 5_000 {
return "just now".to_string();
}
format!("{} ago", span(delta))
}
fn short_when(ms: i64, now: i64) -> String {
let delta = ms - now;
if (0..86_400_000).contains(&delta) {
let (_, _, _, h, m) = cron::local_parts(ms);
format!("{h:02}:{m:02}")
} else {
iso_local(ms)[..10].to_string()
}
}
fn humanize(delta_ms: i64) -> String {
if delta_ms < 0 {
return format!("{} ago", span(delta_ms));
}
if delta_ms < 5_000 {
return "now".to_string();
}
format!("in {}", span(delta_ms))
}
fn span(delta_ms: i64) -> String {
let secs = delta_ms.unsigned_abs() / 1000;
if secs < 60 {
format!("{secs}s")
} else if secs < 3600 {
format!("{}m", secs / 60)
} else if secs < 86_400 {
format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
} else {
format!("{}d", secs / 86_400)
}
}
fn expand_path(text: &str) -> std::path::PathBuf {
if let Some(rest) = text.strip_prefix("~/") {
if let Some(home) = process_env("HOME") {
return std::path::PathBuf::from(home).join(rest);
}
}
std::path::PathBuf::from(text)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scheduler {
pub timer: Option<std::path::PathBuf>,
pub enabled: bool,
pub last_tick_ms: Option<i64>,
}
fn enabled_in(units: &Path) -> bool {
["timers.target.wants", "default.target.wants"]
.iter()
.any(|want| units.join(want).join(TIMER_NAME).exists())
}
pub fn scheduler(root: &Path) -> Scheduler {
scheduler_with(root, &process_env)
}
fn scheduler_with(root: &Path, env: EnvFn) -> Scheduler {
let units = units_dir_in(env);
let timer = units
.as_ref()
.map(|dir| dir.join(TIMER_NAME))
.filter(|path| path.is_file());
let enabled = units.as_deref().is_some_and(enabled_in);
let last_tick_ms = cron::load_state(root)
.map(|state| {
state
.jobs
.values()
.filter_map(|entry| entry.last_started_ms)
.max()
})
.ok()
.flatten();
Scheduler {
timer,
enabled,
last_tick_ms,
}
}
pub fn scheduler_note(sched: &Scheduler, style: &Style) -> Option<String> {
let now = now_ms() as i64;
match (&sched.timer, sched.enabled) {
(Some(_), true) => sched.last_tick_ms.map(|at| {
style.dim(&format!(
"scheduler: {} is enabled; the last tick was {}",
TIMER_NAME,
describe_when_past(at, now)
))
}),
(Some(_), false) => Some(format!(
"scheduler: {} is installed but not enabled, so nothing fires after a reboot — \
`systemctl --user enable --now {TIMER_NAME}`",
TIMER_NAME
)),
(None, _) => Some(
"scheduler: nothing is installed to run these, so a job fires only when you ask — \
`eclipse cron install-timer` installs it"
.to_string(),
),
}
}
fn eclipse_bin() -> std::path::PathBuf {
if let Some(path) = std::env::var_os("ECLIPSE_BIN") {
return std::path::PathBuf::from(path);
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
let beside = dir.join("eclipse");
if beside.is_file() {
return beside;
}
}
}
std::path::PathBuf::from("eclipse")
}
pub fn run_now(
place: Option<&eclipse_core::config::Where>,
root: &Path,
name: &str,
style: &Style,
) -> Result<String> {
if !cron::load(root)?.iter().any(|j| j.name == name) {
bail!("no job named `{name}`; {}", names(root)?);
}
let mut command = std::process::Command::new(eclipse_bin());
if let Some(config) = place.and_then(|p| p.config.as_ref()) {
command.arg("--config").arg(config);
}
if let Some(profile) = place.and_then(|p| p.profile.as_deref()) {
command.arg("--profile").arg(profile);
}
let output = command
.args(["cron", "run", name])
.output()
.map_err(|e| anyhow::anyhow!("could not start {}: {e}", eclipse_bin().display()))?;
let mut out = String::from_utf8_lossy(&output.stdout)
.trim_end()
.to_string();
let err = String::from_utf8_lossy(&output.stderr)
.trim_end()
.to_string();
if !err.is_empty() {
if !out.is_empty() {
out.push('\n');
}
out.push_str(err.trim_end());
}
let code = output.status.code().unwrap_or(-1);
if let Some(run) = cron::runs(root, name, 1).first() {
if !out.is_empty() {
out.push('\n');
}
out.push_str(&format!(
"{} {}{}",
style.dim("said:"),
run.answer,
if run.truncated || run.chars > run.answer.chars().count() {
format!(" (+{} more chars in {})", run.chars, run.path)
} else {
String::new()
}
));
}
if !out.is_empty() {
out.push('\n');
}
out.push_str(&format!(
"{} {}",
style.dim("exit code:"),
if code == 0 {
style.green("0")
} else {
style.red(&code.to_string())
}
));
Ok(out)
}
pub fn composer(
place: Option<&eclipse_core::config::Where>,
root: &Path,
arg: &str,
style: &Style,
) -> Result<String> {
let words: Vec<&str> = arg.split_whitespace().collect();
match words.as_slice() {
[] => {
let mut out = table(root, style)?;
if let Some(note) = scheduler_note(&scheduler(root), style) {
out.push('\n');
out.push('\n');
out.push_str(¬e);
}
Ok(out)
}
["run", name, ..] => run_now(place, root, name, style),
["logs", name] => log_text(root, name, DEFAULT_LOGS, style),
["logs", name, count, ..] => {
let limit = count.parse::<usize>().map_err(|_| {
anyhow::anyhow!("`{count}` is not a number of lines; `eclipse cron logs {name} -n {count}`")
})?;
log_text(root, name, limit, style)
}
["add", ..] => bail!(
"a job is a file with a schedule and a tool policy: `eclipse cron add --name ... --schedule ... --prompt ...`"
),
["remove", ..] | ["rm", ..] => {
bail!("`eclipse cron remove <name>` — removing is a file change, and the CLI is where a file changes")
}
[other, ..] => bail!(
"`/cron` shows the table, `/cron run <name>` and `/cron logs <name> [n]`; `{other}` is not one of those"
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use eclipse_core::cron::Schedule;
fn job(workdir: Option<&str>) -> Job {
Job {
name: "brief".into(),
schedule: Schedule::parse("every 1h").unwrap(),
prompt: "summarise".into(),
enabled: true,
route: None,
workdir: workdir.map(|s| s.to_string()),
skills: Vec::new(),
deliver: None,
schema: None,
}
}
#[test]
fn a_job_runs_in_the_workspace_it_was_given() {
let cfg = Config::default();
let scoped = job_config(&cfg, &job(Some("/srv/notes"))).unwrap();
assert_eq!(
scoped.tools.workspace_root,
Some(std::path::PathBuf::from("/srv/notes"))
);
}
#[test]
fn a_job_without_a_directory_keeps_the_configured_workspace() {
let mut cfg = Config::default();
cfg.tools.workspace_root = Some(std::path::PathBuf::from("/work"));
let plain = job_config(&cfg, &job(None)).unwrap();
assert_eq!(
plain.tools.workspace_root,
Some(std::path::PathBuf::from("/work"))
);
}
#[test]
fn the_composer_shows_the_table_the_command_prints() {
let home = tempfile::tempdir().unwrap();
let root = home.path();
cron::append_job(root, &job(None)).unwrap();
let style = Style::plain();
let tabled = table(root, &style).unwrap();
let composed = composer(None, root, "", &style).unwrap();
assert!(
composed.starts_with(&tabled),
"the same table, then whatever the scheduler has to say:\n{tabled}\n---\n{composed}"
);
let rest = composed.strip_prefix(&tabled).unwrap().trim();
assert!(
rest.is_empty() || rest.starts_with("scheduler:"),
"only the scheduler line may follow: {rest:?}"
);
}
#[test]
fn the_scheduler_line_names_the_thing_that_is_missing() {
let style = Style::plain();
let timer = std::path::PathBuf::from("/home/x/.config/systemd/user/eclipse-cron.timer");
let none = scheduler_note(
&Scheduler {
timer: None,
enabled: false,
last_tick_ms: None,
},
&style,
)
.unwrap();
assert!(none.contains("nothing is installed"), "{none}");
assert!(
none.contains("eclipse cron install-timer"),
"it says how to fix it: {none}"
);
let off = scheduler_note(
&Scheduler {
timer: Some(timer.clone()),
enabled: false,
last_tick_ms: None,
},
&style,
)
.unwrap();
assert!(off.contains("installed but not enabled"), "{off}");
let on = scheduler_note(
&Scheduler {
timer: Some(timer),
enabled: true,
last_tick_ms: Some(now_ms() as i64 - 90_000),
},
&style,
)
.unwrap();
assert!(on.contains("is enabled"), "{on}");
assert!(on.contains("last tick"), "{on}");
assert_eq!(
scheduler_note(
&Scheduler {
timer: Some(std::path::PathBuf::from("/u/eclipse-cron.timer")),
enabled: true,
last_tick_ms: None,
},
&style,
),
None
);
}
#[test]
fn an_unknown_job_name_lists_the_ones_that_exist() {
let home = tempfile::tempdir().unwrap();
let root = home.path();
cron::append_job(root, &job(None)).unwrap();
let style = Style::plain();
for asked in ["logs breg", "run breg"] {
let refused = composer(None, root, asked, &style).unwrap_err().to_string();
assert!(refused.contains("breg"), "{refused}");
assert!(
refused.contains("`brief`"),
"the names that exist: {refused}"
);
}
}
#[test]
fn adding_and_removing_refuse_and_name_the_cli() {
let home = tempfile::tempdir().unwrap();
let root = home.path();
let style = Style::plain();
let added = composer(None, root, "add --name x", &style)
.unwrap_err()
.to_string();
assert!(added.contains("eclipse cron add"), "{added}");
let removed = composer(None, root, "remove brief", &style)
.unwrap_err()
.to_string();
assert!(removed.contains("eclipse cron remove"), "{removed}");
let other = composer(None, root, "watch", &style)
.unwrap_err()
.to_string();
assert!(other.contains("/cron run <name>"), "{other}");
}
#[test]
fn logs_defaults_to_the_flag_default_and_honours_a_count() {
let home = tempfile::tempdir().unwrap();
let root = home.path();
cron::append_job(root, &job(None)).unwrap();
let style = Style::plain();
for minute in 0..7 {
cron::write_run(
root,
"brief",
1_700_000_000_000 + minute * 60_000,
&format!("# brief — run {minute}\n\n---\n\nanswer {minute}\n"),
)
.unwrap();
}
let bare = log_text(root, "brief", DEFAULT_LOGS, &style).unwrap();
assert_eq!(bare.matches("answer ").count(), DEFAULT_LOGS, "{bare}");
let two = log_text(root, "brief", 2, &style).unwrap();
assert_eq!(two.matches("answer ").count(), 2, "{two}");
let through = composer(None, root, "logs brief 2", &style).unwrap();
assert_eq!(through, two);
let unparsable = composer(None, root, "logs brief nine", &style)
.unwrap_err()
.to_string();
assert!(unparsable.contains("-n nine"), "{unparsable}");
}
#[test]
fn a_timer_enabled_under_timers_target_reads_as_enabled() {
let home = tempfile::tempdir().unwrap();
let units = home.path().join(".config").join("systemd").join("user");
std::fs::create_dir_all(units.join("timers.target.wants")).unwrap();
std::fs::write(units.join(TIMER_NAME), "[Timer]\n").unwrap();
std::fs::write(
units.join("timers.target.wants").join(TIMER_NAME),
"[Install]\n",
)
.unwrap();
let env = |key: &str| (key == "HOME").then(|| home.path().to_string_lossy().into_owned());
let sched = scheduler_with(home.path(), &env);
assert!(
sched.enabled,
"a timer systemd will start read as disabled, so the table warns forever"
);
}
#[test]
fn a_timer_enabled_under_default_target_also_reads_as_enabled() {
let home = tempfile::tempdir().unwrap();
let units = home.path().join(".config").join("systemd").join("user");
std::fs::create_dir_all(units.join("default.target.wants")).unwrap();
std::fs::write(units.join(TIMER_NAME), "[Timer]\n").unwrap();
std::fs::write(
units.join("default.target.wants").join(TIMER_NAME),
"[Install]\n",
)
.unwrap();
let env = |key: &str| (key == "HOME").then(|| home.path().to_string_lossy().into_owned());
assert!(scheduler_with(home.path(), &env).enabled);
}
#[test]
fn a_timer_with_no_enable_symlink_reads_as_disabled() {
let home = tempfile::tempdir().unwrap();
let units = home.path().join(".config").join("systemd").join("user");
std::fs::create_dir_all(&units).unwrap();
std::fs::write(units.join(TIMER_NAME), "[Timer]\n").unwrap();
let env = |key: &str| (key == "HOME").then(|| home.path().to_string_lossy().into_owned());
assert!(!scheduler_with(home.path(), &env).enabled);
}
#[test]
fn a_tilde_is_expanded_the_same_way_at_add_and_at_run() {
let mut cfg = Config::default();
cfg.tools.workspace_root = None;
let scoped = job_config(&cfg, &job(Some("~/notes"))).unwrap();
assert_eq!(
scoped.tools.workspace_root,
Some(expand_path("~/notes")),
"one expansion, both ends"
);
}
}