1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::ffi::OsString;
use std::io::IsTerminal as _;
use std::io::Write;
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use crate::Error;
use crate::Result;
use crate::USAGE;
use crate::color_enabled;
use crate::graph::Jeans;
use crate::init::Init;
use crate::init::init;
/// Runs the jeans command in ARGS (without the program name), printing its
/// output, and returns the exit status.
pub fn run(args: Vec<OsString>) -> ExitCode {
let stdout = std::io::stdout();
match dispatch(args, &mut stdout.lock()) {
Ok(Exit::Success) => ExitCode::SUCCESS,
Ok(Exit::Usage) => {
eprint!("{USAGE}");
ExitCode::FAILURE
}
Err(e) => {
eprintln!("jeans: {e}");
ExitCode::FAILURE
}
}
}
enum Exit {
Success,
Usage,
}
/// The flags every command accepts, wherever they sit among its arguments.
#[derive(Default)]
struct Opts {
body: Option<String>,
team: Option<i64>,
home: Option<String>,
before: Option<String>,
after: Vec<String>,
depth: Option<i64>,
color: Option<String>,
goal: Option<String>,
}
fn dispatch(args: Vec<OsString>, out: &mut impl Write) -> Result<Exit> {
let mut args = args
.into_iter()
.map(|arg| {
arg.into_string()
.map_err(|arg| Error::msg(format!("{} isn't UTF-8", arg.display())))
})
.collect::<Result<Vec<_>>>()?
.into_iter();
let command = args.next().unwrap_or_default();
let (opts, args) = parse(args)?;
let color = color_enabled(
opts.color.as_deref().unwrap_or("auto"),
std::io::stdout().is_terminal(),
std::env::var_os("NO_COLOR").as_deref(),
);
let goal = opts.goal.as_deref();
let jeans = |hint: Option<&str>| Jeans::new(color, true, goal, hint);
let arg = |i: usize| args.get(i).map(String::as_str);
let required = |what: &str| arg(0).ok_or_else(|| Error::msg(format!("{command} needs {what}")));
// Past the end of --depth's range, nothing is deep enough to collapse.
let depth = opts.depth.and_then(|d| usize::try_from(d).ok());
match command.as_str() {
"init" => {
let id = init(&Init {
title: required("TITLE")?,
goal,
body: opts.body.as_deref(),
team_size: opts.team.unwrap_or(3),
home: opts.home.as_deref(),
})?;
puts(out, &id)?;
}
"add" => {
let before = opts.before.as_deref();
let id = jeans(before)?.add(
required("TITLE")?,
opts.body.as_deref(),
before,
&opts.after,
)?;
puts(out, &id)?;
}
"ready" => puts_lines(out, &jeans(None)?.ready()?)?,
"log" => puts(out, &jeans(arg(1))?.log(arg(0), arg(1))?)?,
"status" => puts(out, &jeans(None)?.log(None, None)?)?,
"tree" => puts(out, &jeans(arg(0))?.tree(arg(0), depth)?)?,
"board" => puts(out, &jeans(arg(0))?.board(arg(0))?)?,
"watch" => {
let stop = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::consts::SIGINT, Arc::clone(&stop))?;
let jeans = Jeans::new(color, false, goal, arg(1))?;
jeans.watch(arg(0).unwrap_or("tree"), arg(1), depth, &stop, out)?;
}
"show" => {
let task = required("TASK")?;
puts(out, &jeans(Some(task))?.show(task)?)?;
}
"describe" => {
let task = required("TASK")?;
let message = opts
.body
.as_deref()
.ok_or_else(|| Error::msg("describe needs -m MESSAGE"))?;
jeans(Some(task))?.describe(task, message)?;
}
"claim" => {
let task = required("TASK")?;
puts(out, &jeans(Some(task))?.claim(task)?)?;
}
"done" => {
let task = required("TASK")?;
puts(out, &jeans(Some(task))?.done(task, opts.body.as_deref())?)?;
}
"release" => {
let task = required("TASK")?;
puts(out, &jeans(Some(task))?.release(task)?)?;
}
"team-size" => puts(out, &jeans(None)?.team_size()?.to_string())?,
"guide" => {
let text = arg(0)
.and_then(crate::guide)
.ok_or_else(|| Error::msg("guide needs stakeholder or developer"))?;
write!(out, "{text}")?;
}
_ => return Ok(Exit::Usage),
}
Ok(Exit::Success)
}
/// Splits ARGS into flags and positional arguments the way Ruby's
/// OptionParser does: flags anywhere, values attached or as the next
/// argument, and everything after `--` positional.
fn parse(mut args: impl Iterator<Item = String>) -> Result<(Opts, Vec<String>)> {
let mut opts = Opts::default();
let mut positional = Vec::new();
while let Some(arg) = args.next() {
let (flag, attached) = if arg == "--" {
positional.extend(args.by_ref());
break;
} else if let Some(long) = arg.strip_prefix("--") {
match long.split_once('=') {
Some((name, value)) => (format!("--{name}"), Some(value.to_owned())),
None => (arg.clone(), None),
}
} else if let Some(value) = arg.strip_prefix("-m") {
(
"-m".to_owned(),
Some(value).filter(|v| !v.is_empty()).map(str::to_owned),
)
} else if arg.starts_with('-') && arg != "-" {
return Err(Error::msg(format!("invalid option: {arg}")));
} else {
positional.push(arg);
continue;
};
let known = [
"-m", "--team", "--home", "--before", "--after", "--depth", "--color", "--goal",
];
if !known.contains(&flag.as_str()) {
return Err(Error::msg(format!("invalid option: {flag}")));
}
let value = attached
.or_else(|| args.next())
.ok_or_else(|| Error::msg(format!("missing argument: {flag}")))?;
let invalid = || Error::msg(format!("invalid argument: {flag} {value}"));
match flag.as_str() {
"-m" => opts.body = Some(value),
"--team" => opts.team = Some(value.parse().map_err(|_| invalid())?),
"--home" => opts.home = Some(value),
"--before" => opts.before = Some(value),
"--after" => opts.after.push(value),
"--depth" => opts.depth = Some(value.parse().map_err(|_| invalid())?),
"--color" if ["always", "never", "auto"].contains(&value.as_str()) => {
opts.color = Some(value);
}
"--color" => return Err(invalid()),
_ => opts.goal = Some(value),
}
}
Ok((opts, positional))
}
/// Prints TEXT and a newline, unless TEXT already ends with one.
fn puts(out: &mut impl Write, text: &str) -> Result<()> {
if text.ends_with('\n') {
write!(out, "{text}")?;
} else {
writeln!(out, "{text}")?;
}
Ok(())
}
/// Prints each line, or a blank line for none, like Ruby's `puts []`.
fn puts_lines(out: &mut impl Write, lines: &[String]) -> Result<()> {
if lines.is_empty() {
writeln!(out)?;
}
for line in lines {
puts(out, line)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn parsed(args: &[&str]) -> Result<(Opts, Vec<String>)> {
parse(args.iter().map(|a| (*a).to_owned()))
}
fn error(args: &[&str]) -> String {
parsed(args).err().unwrap().to_string()
}
#[test]
fn flags_go_anywhere() {
let (opts, args) = parsed(&[
"a",
"--depth",
"2",
"-m",
"- one",
"--after=x",
"--after",
"y",
"b",
"--",
"--c",
])
.unwrap();
assert_eq!(args, ["a", "b", "--c"]);
assert_eq!(opts.depth, Some(2));
assert_eq!(opts.body.as_deref(), Some("- one"));
assert_eq!(opts.after, ["x", "y"]);
}
#[test]
fn every_flag_sets_its_option() {
let (opts, args) = parsed(&[
"-mbody", "--team", "4", "--home", "h", "--before", "t", "--color", "never", "--goal",
"g", "-",
])
.unwrap();
assert_eq!(args, ["-"]);
assert_eq!(opts.body.as_deref(), Some("body"));
assert_eq!(opts.team, Some(4));
assert_eq!(opts.home.as_deref(), Some("h"));
assert_eq!(opts.before.as_deref(), Some("t"));
assert_eq!(opts.color.as_deref(), Some("never"));
assert_eq!(opts.goal.as_deref(), Some("g"));
}
#[test]
fn bad_flags_are_errors() {
assert_eq!(error(&["-x"]), "invalid option: -x");
assert_eq!(error(&["--nope"]), "invalid option: --nope");
assert_eq!(error(&["--team"]), "missing argument: --team");
assert_eq!(error(&["--team", "x"]), "invalid argument: --team x");
assert_eq!(error(&["--depth=x"]), "invalid argument: --depth x");
assert_eq!(
error(&["--color", "sometimes"]),
"invalid argument: --color sometimes"
);
}
#[test]
fn puts_adds_a_missing_newline() {
let mut out = Vec::new();
puts(&mut out, "a").unwrap();
puts(&mut out, "b\n").unwrap();
puts_lines(&mut out, &[]).unwrap();
puts_lines(&mut out, &["c".to_owned()]).unwrap();
assert_eq!(String::from_utf8(out).unwrap(), "a\nb\n\nc\n");
}
}