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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use camino::Utf8Path;
use camino::Utf8PathBuf;
use std::collections::HashSet;
use crate::Error;
use crate::Result;
use crate::color::Paint;
use crate::color::paint;
use crate::init::bookmark_revset;
use crate::init::done_bookmark;
use crate::init::goal_bookmark;
use crate::init::goals;
use crate::jj;
use crate::message::short;
const LEGACY_GOAL: &str = "jeans-goal";
const WORKSPACE_PREFIX: &str = "jeans-";
/// A repo's jeans setup and the goal a command works on.
pub(crate) struct Jeans {
pub(crate) color: bool,
pub(crate) snapshot: bool,
pub(crate) main: Utf8PathBuf,
pub(crate) home: Utf8PathBuf,
pub(crate) integrate: String,
pub(crate) goal: Option<String>,
pub(crate) goal_revset: String,
/// A task is done once it's an ancestor of the done node. The node is a
/// parent of the integration node, so the human's checkout holds all the
/// finished work.
pub(crate) done_node: String,
/// Conflict resolution tasks hang under the done node, outside the goal.
pub(crate) tasks_revset: String,
}
/// A task commit: one between trunk and the goal or the done node.
pub(crate) struct Task {
pub(crate) id: String,
pub(crate) parents: Vec<String>,
pub(crate) conflict: bool,
pub(crate) title: String,
pub(crate) state: State,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum State {
Ready,
Claimed,
Blocked,
Done,
}
pub(crate) const STATES: [State; 4] = [State::Ready, State::Claimed, State::Blocked, State::Done];
impl State {
pub(crate) fn name(self) -> &'static str {
match self {
Self::Ready => "ready",
Self::Claimed => "claimed",
Self::Blocked => "blocked",
Self::Done => "done",
}
}
pub(crate) fn paint(self) -> Paint {
match self {
Self::Ready => Paint::Ready,
Self::Claimed => Paint::Claimed,
Self::Blocked => Paint::Blocked,
Self::Done => Paint::Done,
}
}
}
impl Jeans {
/// GOAL is the --goal flag. Without it, the goal is the one that HINT, a
/// task from the command line, feeds; else the one the current
/// workspace's task feeds; else the repo's only goal.
pub(crate) fn new(
color: bool,
snapshot: bool,
goal: Option<&str>,
hint: Option<&str>,
) -> Result<Self> {
let main = Utf8PathBuf::from(config(None, snapshot, "jeans.main")?);
let home = Utf8PathBuf::from(config(Some(&main), snapshot, "jeans.home")?);
let mut jeans = Self {
color,
snapshot,
main,
home,
integrate: String::new(),
goal: None,
goal_revset: "none()".to_owned(),
done_node: "none()".to_owned(),
tasks_revset: String::new(),
};
if jeans.legacy()? {
return Err(Error::msg(format!(
"{LEGACY_GOAL} is a goal from an older jeans; \
see \"Upgrading a goal from before named goals\" in the README"
)));
}
jeans.integrate = jeans.config("jeans.integrate")?;
jeans.goal = jeans.pick_goal(goal, hint)?;
if let Some(goal) = &jeans.goal {
jeans.goal_revset = bookmark_revset(&goal_bookmark(goal));
jeans.done_node = bookmark_revset(&done_bookmark(goal));
}
jeans.tasks_revset = format!(
"(trunk()..({} | {})) ~ {}",
jeans.goal_revset, jeans.done_node, jeans.done_node
);
Ok(jeans)
}
pub(crate) fn team_size(&self) -> Result<i64> {
let size = self.config("jeans.team-size")?;
size.parse()
.map_err(|_| Error::msg(format!("jeans.team-size is {size}, not a number")))
}
/// Every task in jj log order, each with its state.
pub(crate) fn tasks(&self) -> Result<Vec<Task>> {
let template = [
"change_id",
r#"parents.map(|p| p.change_id()).join(",")"#,
"conflict",
"description.first_line()",
]
.join(r#" ++ "\t" ++ "#)
+ r#" ++ "\n""#;
let out = self.jj(&[
"log",
"--no-graph",
"-r",
&self.tasks_revset,
"-T",
&template,
])?;
let done = self.done_ids()?;
let taken = self.claimed()?;
let mut tasks: Vec<Task> = Vec::new();
for line in out.lines() {
let mut fields = line.splitn(4, '\t');
let mut field = || fields.next().unwrap_or_default().to_owned();
let id = field();
let parents = field();
let conflict = field() == "true";
let title = field();
tasks.push(Task {
state: if done.contains(&id) {
State::Done
} else {
State::Ready
},
parents: parents
.split(',')
.filter(|p| !p.is_empty())
.map(str::to_owned)
.collect(),
id,
conflict,
title,
});
}
let unfinished: HashSet<String> = tasks
.iter()
.filter(|t| t.state != State::Done)
.map(|t| t.id.clone())
.collect();
for task in &mut tasks {
if task.state == State::Done {
continue;
}
task.state = if taken.contains(&task.id) {
State::Claimed
} else if task.parents.iter().any(|p| unfinished.contains(p)) {
State::Blocked
} else {
State::Ready
};
}
Ok(tasks)
}
/// The IDs of the claimed tasks, from their workspace names.
pub(crate) fn claimed(&self) -> Result<Vec<String>> {
let out = self.jj(&["workspace", "list", "-T", r#"name ++ "\n""#])?;
Ok(out
.lines()
.filter_map(|name| name.strip_prefix(WORKSPACE_PREFIX))
.map(str::to_owned)
.collect())
}
pub(crate) fn state_label(&self, state: State) -> String {
paint(self.color, &format!("[{}]", state.name()), state.paint())
}
pub(crate) fn paint(&self, text: &str, key: Paint) -> String {
paint(self.color, text, key)
}
pub(crate) fn resolve(&self, rev: &str) -> Result<String> {
let out = self.jj(&["log", "--no-graph", "-r", rev, "-T", r#"change_id ++ "\n""#])?;
match out.lines().collect::<Vec<_>>().as_slice() {
[id] => Ok((*id).to_owned()),
ids => Err(Error::msg(format!(
"{rev} resolves to {} commits",
ids.len()
))),
}
}
/// The task whose workspace jeans is running in, if any.
pub(crate) fn current_task(&self) -> Result<Option<String>> {
let root = jj::jj(None, self.snapshot, &["root"])?.stdout;
let here = fs_err::canonicalize(root.trim())?;
for id in self.claimed()? {
let path = self.workspace_path(&id);
if path.exists() && fs_err::canonicalize(&path)? == here {
return Ok(Some(id));
}
}
Ok(None)
}
pub(crate) fn done_ids(&self) -> Result<HashSet<String>> {
Ok(self
.log_ids(&format!(
"::{} & ({}) ~ conflicts()",
self.done_node, self.tasks_revset
))?
.into_iter()
.collect())
}
pub(crate) fn log_ids(&self, revset: &str) -> Result<Vec<String>> {
let out = self.jj(&[
"log",
"--no-graph",
"-r",
revset,
"-T",
r#"change_id ++ "\n""#,
])?;
Ok(out.lines().map(str::to_owned).collect())
}
pub(crate) fn workspace_name(id: &str) -> String {
format!("{WORKSPACE_PREFIX}{id}")
}
pub(crate) fn workspace_path(&self, id: &str) -> Utf8PathBuf {
self.home.join(id)
}
/// Runs jj in the main repo and returns its stdout.
pub(crate) fn jj(&self, args: &[&str]) -> Result<String> {
Ok(jj::jj(Some(&self.main), self.snapshot, args)?.stdout)
}
pub(crate) fn jj_in(&self, repo: &Utf8Path, args: &[&str]) -> Result<jj::Output> {
jj::jj(Some(repo), self.snapshot, args)
}
fn config(&self, key: &str) -> Result<String> {
config(Some(&self.main), self.snapshot, key)
}
/// A goal still in progress whose done node is the main workspace's
/// working copy.
fn legacy(&self) -> Result<bool> {
if self.config("jeans.workspace").is_err() {
return Ok(false);
}
Ok(!self.log_ids(&bookmark_revset(LEGACY_GOAL))?.is_empty())
}
fn pick_goal(&self, name: Option<&str>, hint: Option<&str>) -> Result<Option<String>> {
let names = goals(&self.main, self.snapshot)?;
if let Some(name) = name {
if !names.iter().any(|n| n == name) {
return Err(Error::msg(format!(
"there's no goal named {name}; the goals are {}",
list(&names)
)));
}
return Ok(Some(name.to_owned()));
}
let hint = hint.map(|rev| self.resolve(rev)).transpose()?;
let current = self.current_task()?;
for task in hint.iter().chain(current.iter()) {
let mut owners = Vec::new();
for name in &names {
if !self
.log_ids(&format!("{task} & ::{}", goal_heads(name)))?
.is_empty()
{
owners.push(name.clone());
}
}
if owners.len() > 1 {
return Err(Error::msg(format!(
"{} feeds goals {}; pick one with --goal NAME",
short(task, 8),
list(&owners)
)));
}
if let Some(owner) = owners.pop() {
return Ok(Some(owner));
}
}
if names.len() > 1 {
return Err(Error::msg(format!(
"this repo has goals {}; pick one with --goal NAME",
list(&names)
)));
}
Ok(names.into_iter().next())
}
}
pub(crate) fn ids_revset(ids: &[&str]) -> String {
if ids.is_empty() {
"none()".to_owned()
} else {
ids.join(" | ")
}
}
fn config(repo: Option<&Utf8Path>, snapshot: bool, key: &str) -> Result<String> {
match jj::jj(repo, snapshot, &["config", "get", key]) {
Ok(out) => Ok(out.stdout.trim().to_owned()),
Err(_) => Err(Error::msg(format!(
"{key} isn't set; run `jeans init` in the repository first"
))),
}
}
fn goal_heads(name: &str) -> String {
format!(
"({} | {})",
bookmark_revset(&goal_bookmark(name)),
bookmark_revset(&done_bookmark(name))
)
}
fn list(names: &[String]) -> String {
if names.is_empty() {
"none".to_owned()
} else {
names.join(", ")
}
}