Debian Codegraph @

src/main.rs

raw symbols SCIP
1 use std::ffi::OsString;
2 use std::io::{self, Write};
3 use std::path::PathBuf;
4 use std::process::{Command, exit, Stdio};
5 use std::time::{Duration, Instant};
6
7 use anyhow::{Context, Result};
8 use clap::Parser;
9
10 use bkt::{CommandDesc, Bkt};
11
12 // Re-invokes bkt with --force and then discards the subprocess, causing the cache
13 // to be refreshed asynchronously.
14 fn force_update_async() -> Result<()> {
15 let mut args = std::env::args_os();
16 let arg0 = args.next().expect("Must always be a 0th argument");
17 let mut command = match std::env::current_exe() {
18 Ok(path) => Command::new(path),
19 Err(_) => Command::new(arg0),
20 };
21 // Discard stdout/err so the calling process doesn't wait for them to close.
22 // Intentionally drop the returned Child; after this process exits the
23 // child process will continue running in the background.
24 command.arg("--force").args(args.filter(|a| a != "--warm"))
25 .stdout(Stdio::null()).stderr(Stdio::null())
26 .spawn().context("Failed to start background process")?;
27 Ok(())
28 }
29
30 // Runs bkt after main() handles flag parsing
31 fn run(cli: Cli) -> Result<i32> {
32 let ttl: Duration = cli.ttl.into();
33 let stale: Option<Duration> = cli.stale.map(Into::into);
34
35 assert!(!ttl.is_zero(), "--ttl cannot be zero");
36 if let Some(stale) = stale {
37 assert!(!stale.is_zero(), "--stale cannot be zero");
38 assert!(stale < ttl, "--stale must be less than --ttl");
39 }
40
41 let mut bkt = match cli.cache_dir {
42 Some(cache_dir) => Bkt::create(cache_dir)?,
43 None => Bkt::in_tmp()?,
44 };
45 if let Some(scope) = cli.scope {
46 bkt = bkt.scoped(scope);
47 }
48
49 let mut command = CommandDesc::new(cli.command);
50
51 if cli.cwd {
52 command = command.with_cwd();
53 }
54
55 let envs = cli.env;
56 if !envs.is_empty() {
57 command = command.with_envs(&envs);
58 }
59
60 let files = cli.modtime;
61 if !files.is_empty() {
62 command = command.with_modtimes(&files);
63 }
64
65 if cli.discard_failures {
66 command = command.with_discard_failures(true);
67 }
68
69 if cli.warm && !cli.force {
70 force_update_async()?;
71 return Ok(0);
72 }
73
74 let invocation = if cli.force {
75 bkt.refresh(&command, ttl)?.0
76 } else {
77 let (invocation, status) = bkt.retrieve(&command, ttl)?;
78 if let Some(stale) = stale {
79 if let bkt::CacheStatus::Hit(cached_at) = status {
80 if (Instant::now() - cached_at) > stale {
81 force_update_async()?;
82 }
83 }
84 }
85 invocation
86 };
87
88 // BrokenPipe errors are uninteresting for command line applications; just stop writing to that
89 // descriptor and, if appropriate, exit. Rust doesn't have good support for this presently, see
90 // https://github.com/rust-lang/rust/issues/46016
91 fn disregard_broken_pipe(result: std::io::Result<()>) -> std::io::Result<()> {
92 use std::io::ErrorKind::*;
93 if let Err(e) = &result {
94 if let BrokenPipe = e.kind() {
95 return Ok(());
96 }
97 }
98 result
99 }
100
101 disregard_broken_pipe(io::stdout().write_all(invocation.stdout()))
102 .context("error writing to stdout")?;
103 disregard_broken_pipe(io::stderr().write_all(invocation.stderr()))
104 .context("error writing to stderr")?;
105 Ok(invocation.exit_code())
106 }
107
108 #[derive(Debug, Parser)]
109 #[command(about, version)]
110 struct Cli {
111 /// The command to run
112 #[arg(required = true, last = true)]
113 command: Vec<OsString>,
114
115 /// Duration the cached result will be valid for
116 #[arg(long, value_name = "DURATION", default_value = "60s", visible_alias = "time-to-live", env = "BKT_TTL")]
117 ttl: humantime::Duration,
118
119 /// Duration after which the result will be asynchronously refreshed
120 #[arg(long, value_name = "DURATION", conflicts_with = "warm")]
121 stale: Option<humantime::Duration>,
122
123 /// Asynchronously execute and cache the given command, even if it's already cached
124 #[arg(long)]
125 warm: bool,
126
127 /// Execute and cache the given command, even if it's already cached
128 #[arg(long, conflicts_with = "warm")]
129 force: bool,
130
131 /// Includes the current working directory in the cache key,
132 /// so that the same command run in different directories caches separately
133 #[arg(long, visible_alias = "use-working-dir")]
134 cwd: bool,
135
136 /// Includes the given environment variable in the cache key,
137 /// so that the same command run with different values for the given variables caches separately
138 #[arg(long, value_name = "NAME", visible_alias = "use-environment")]
139 env: Vec<OsString>,
140
141 /// Includes the last modification time of the given file(s) in the cache key,
142 /// so that the same command run with different modtimes for the given files caches separately
143 #[arg(long, value_name = "FILE", visible_alias = "use-file-modtime")]
144 modtime: Vec<OsString>,
145
146 /// Don't cache invocations that fail (non-zero exit code).
147 /// USE CAUTION when passing this flag, as unexpected failures can lead to a spike in invocations
148 /// which can exacerbate ongoing issues, effectively a DDoS.
149 #[arg(long)]
150 discard_failures: bool,
151
152 /// If set, all cached data will be scoped to this value,
153 /// preventing collisions with commands cached with different scopes
154 #[arg(long, value_name = "NAME", env = "BKT_SCOPE")]
155 scope: Option<String>,
156
157 /// The directory under which to persist cached invocations;
158 /// defaults to the system's temp directory.
159 /// Setting this to a directory backed by RAM or an SSD, such as a tmpfs partition,
160 /// will significantly reduce caching overhead.
161 #[arg(long, value_name = "DIR", env = "BKT_CACHE_DIR")]
162 cache_dir: Option<PathBuf>,
163 }
164
165 fn main() {
166 let cli = Cli::parse();
167
168 match run(cli) {
169 Ok(code) => exit(code),
170 Err(msg) => {
171 eprintln!("bkt: {:#}", msg);
172 exit(127);
173 }
174 }
175 }