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
use crate::Error;
use crate::Result;
use crate::graph::Jeans;
use crate::graph::State;
use crate::graph::ids_revset;
use crate::init::created_id;
use crate::init::done_bookmark;
use crate::init::goal_bookmark;
use crate::jj::jj_allow_failure;
use crate::message::finished_message;
use crate::message::message;

impl Jeans {
    /// Inserts a task before BEFORE (default: the goal) and after each of
    /// AFTER (default: trunk), and returns its change ID.
    pub(crate) fn add(
        &self,
        title: &str,
        body: Option<&str>,
        before: Option<&str>,
        after: &[String],
    ) -> Result<String> {
        self.locked(|| {
            if self.goal.is_none() {
                return Err(Error::msg(
                    "there's no goal to add to; run `jeans init` first",
                ));
            }
            let before = self.resolve(before.unwrap_or(&self.goal_revset))?;
            if self.done_ids()?.contains(&before) {
                return Err(Error::msg(format!(
                    "{before} is done; add follow-up work before a task that isn't"
                )));
            }
            self.guard_scope(&before, true)?;

            let after = if after.is_empty() {
                vec!["trunk()".to_owned()]
            } else {
                after
                    .iter()
                    .map(|rev| self.resolve(rev))
                    .collect::<Result<_>>()?
            };
            let message = message(title, body);
            let mut args = vec!["new", "--no-edit"];
            for parent in &after {
                args.extend(["-A", parent]);
            }
            args.extend(["-B", &before, "-m", &message]);
            let new = self.jj_in(&self.main, &args)?;
            created_id(&new.stderr, &self.main, self.snapshot)
        })
    }

    /// Replaces a task's description.
    pub(crate) fn describe(&self, rev: &str, message: &str) -> Result<()> {
        self.locked(|| {
            let id = self.resolve(rev)?;
            self.guard_scope(&id, false)?;
            self.jj(&["describe", "-r", &id, "-m", message])?;
            Ok(())
        })
    }

    /// Makes a ready task's workspace and returns its path.
    pub(crate) fn claim(&self, rev: &str) -> Result<String> {
        self.locked(|| {
            let id = self.resolve(rev)?;
            let state = self.state(&id)?;
            if state != State::Ready {
                return Err(Error::msg(format!("{id} is {}, not ready", state.name())));
            }
            let path = self.workspace_path(&id);
            self.jj(&[
                "workspace",
                "add",
                path.as_str(),
                "--name",
                &Self::workspace_name(&id),
                "-r",
                &id,
            ])?;
            Ok(path.into_string())
        })
    }

    /// Squashes a task's workspace in, puts MESSAGE above its spec, and
    /// moves it under the done node.
    pub(crate) fn done(&self, rev: &str, message: Option<&str>) -> Result<String> {
        let message = message.filter(|m| !m.trim().is_empty()).ok_or_else(|| {
            Error::msg("done needs -m MESSAGE, a commit message for the finished work")
        })?;
        self.finish(rev, |id| self.integrate_finished(id, message))
    }

    /// Squashes a task's workspace in and drops it, leaving the task undone.
    pub(crate) fn release(&self, rev: &str) -> Result<String> {
        self.finish(rev, |_| Ok(()))
    }

    fn integrate_finished(&self, id: &str, message: &str) -> Result<()> {
        let conflicted = self.tasks()?.into_iter().any(|t| t.id == id && t.conflict);
        if conflicted {
            return Err(Error::msg(format!(
                "{id} has conflicts; resolve them in its workspace first"
            )));
        }

        let goal_ids = self.log_ids(&self.goal_revset)?;
        let finishing_goal = self
            .goal
            .as_ref()
            .filter(|_| goal_ids.iter().any(|g| g == id));
        let spec = self.jj(&["log", "--no-graph", "-r", id, "-T", "description"])?;
        self.jj(&[
            "describe",
            "-r",
            id,
            "-m",
            &finished_message(message, &spec),
        ])?;

        let heads = self.log_ids(&format!(
            "heads(parents({}) ~ ::trunk() | {id})",
            self.done_node
        ))?;
        let superseded = self.superseded_resolutions(&heads, id)?;
        // -s, not -r: -r would drop the done node from the integration node above it.
        let mut rebase = vec!["rebase", "-s", &self.done_node];
        for head in heads.iter().filter(|h| !superseded.contains(h)) {
            rebase.extend(["-o", head]);
        }
        self.jj(&rebase)?;
        if !superseded.is_empty() {
            let mut abandon = vec!["abandon"];
            abandon.extend(superseded.iter().map(String::as_str));
            self.jj(&abandon)?;
        }

        let resolution = self.add_resolution_task()?;
        if let Some(resolution) = &resolution {
            eprintln!("the finished tasks conflict; added resolution task {resolution}");
        }
        if let Some(goal) = finishing_goal {
            // The goal takes the done node's place as a parent of the
            // integration node.
            let node = self.resolve(&self.done_node)?;
            self.jj(&[
                "bookmark",
                "delete",
                &goal_bookmark(goal),
                &done_bookmark(goal),
            ])?;
            self.jj(&["abandon", &node])?;
        }
        if resolution.is_none() {
            self.warn_integration_conflicts()?;
        }
        Ok(())
    }

    fn finish(&self, rev: &str, work: impl FnOnce(&str) -> Result<()>) -> Result<String> {
        self.locked(|| {
            let id = self.resolve(rev)?;
            let ws = self.workspace_path(&id);
            if !self.claimed()?.contains(&id) {
                return Err(Error::msg(format!("{id} isn't claimed")));
            }

            self.jj_in(&ws, &["workspace", "update-stale"])?;
            let wc_args = [
                "log",
                "--no-graph",
                "-r",
                "@",
                "-T",
                r#"empty ++ " " ++ conflict"#,
            ];
            let wc = self.jj_in(&ws, &wc_args)?;
            let (empty, conflict) = wc.stdout.split_once(' ').unwrap_or_default();
            if conflict == "true" {
                return Err(Error::msg(format!(
                    "the working copy in {ws} has conflicts; resolve them first"
                )));
            }
            if empty != "true" {
                self.jj_in(&ws, &["squash", "--from", "@", "--into", &id, "-u"])?;
            }

            work(&id)?;

            let name = Self::workspace_name(&id);
            let leftover = self.jj(&[
                "log",
                "--no-graph",
                "-r",
                &format!("{name}@"),
                "-T",
                "commit_id",
            ])?;
            self.jj(&["workspace", "forget", &name])?;
            let abandon = ["abandon", leftover.trim()];
            jj_allow_failure(Some(&self.main), self.snapshot, &abandon)?;
            match fs_err::remove_dir_all(&ws) {
                Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()), // cov-excl-line
                _ => {}
            }
            Ok(id)
        })
    }

    /// A claimed task's scope belongs to the developer on it, who runs jeans
    /// from inside its workspace. That developer in turn changes only its
    /// own subtree; work it finds elsewhere is the stakeholder's to add.
    fn guard_scope(&self, id: &str, own_subtree: bool) -> Result<()> {
        if let Some(current) = self.current_task()? {
            let allowed = if own_subtree {
                self.log_ids(&format!("::{current} & ({})", self.tasks_revset))?
            } else {
                vec![current.clone()]
            };
            if allowed.iter().any(|a| a == id) {
                return Ok(());
            }
            return Err(Error::msg(format!(
                "{id} is outside your task {current}; report it to the stakeholder instead"
            )));
        }
        if self.claimed()?.iter().any(|c| c == id) {
            return Err(Error::msg(format!(
                "{id} is claimed; only the developer in {} can change it",
                self.workspace_path(id)
            )));
        }
        Ok(())
    }

    /// A resolution task is redundant once another done task integrates all
    /// of its parents, and merging it with that task conflicts again even
    /// when both resolved the same way. Leave one a developer is still on
    /// until it finishes.
    fn superseded_resolutions(&self, heads: &[String], finishing: &str) -> Result<Vec<String>> {
        let resolutions =
            self.log_ids(&format!("({}) ~ ::{}", self.tasks_revset, self.goal_revset))?;
        let taken = self.claimed()?;
        let mut superseded = Vec::new();
        for head in heads {
            if !resolutions.contains(head) || (head != finishing && taken.contains(head)) {
                continue;
            }
            let others: Vec<&str> = heads
                .iter()
                .filter(|h| *h != head)
                .map(String::as_str)
                .collect();
            let uncovered =
                self.log_ids(&format!("parents({head}) ~ ::({})", ids_revset(&others)))?;
            if uncovered.is_empty() {
                superseded.push(head.clone());
            }
        }
        Ok(superseded)
    }

    /// Adds a task to resolve the done node's conflicts. A conflicted parent
    /// is an unresolved resolution task, whose own resolution will be checked
    /// again when it's done.
    fn add_resolution_task(&self) -> Result<Option<String>> {
        let conflicted =
            self.jj(&["log", "--no-graph", "-r", &self.done_node, "-T", "conflict"])?;
        if conflicted != "true" {
            return Ok(None);
        }
        let parents_revset = format!("parents({})", self.done_node);
        if !self
            .log_ids(&format!("{parents_revset} & conflicts()"))?
            .is_empty()
        {
            return Ok(None);
        }

        let parents = self.log_ids(&parents_revset)?;
        let parent_refs: Vec<&str> = parents.iter().map(String::as_str).collect();
        let titles = self.jj(&[
            "log",
            "--no-graph",
            "-r",
            &ids_revset(&parent_refs),
            "-T",
            r#"description.first_line() ++ "\n""#,
        ])?;
        let list = ["resolve", "--list", "-r", &self.done_node];
        let files = jj_allow_failure(Some(&self.main), self.snapshot, &list)?.stdout;
        let message = message(
            &format!(
                "Resolve conflicts between {}",
                titles.lines().collect::<Vec<_>>().join(", ")
            ),
            Some(&format!(
                "These finished tasks conflict when merged:\n\n{}",
                files.trim_end()
            )),
        );
        let mut args = vec!["new", "--no-edit"];
        for parent in &parent_refs {
            args.extend(["-A", parent]);
        }
        args.extend(["-B", &self.done_node, "-m", &message]);
        let new = self.jj_in(&self.main, &args)?;
        created_id(&new.stderr, &self.main, self.snapshot).map(Some)
    }

    /// The finished work merged cleanly, but conflicts with the integration
    /// node's other parents.
    fn warn_integration_conflicts(&self) -> Result<()> {
        let conflicted =
            self.jj(&["log", "--no-graph", "-r", &self.integrate, "-T", "conflict"])?;
        if conflicted == "true" {
            eprintln!(
                "{} has conflicts between the finished tasks and its other parents",
                self.integrate
            );
        }
        Ok(())
    }

    pub(crate) fn state(&self, id: &str) -> Result<State> {
        self.tasks()?
            .into_iter()
            .find(|t| t.id == id)
            .map(|t| t.state)
            .ok_or_else(|| Error::msg(format!("{id} isn't a task")))
    }

    /// Runs WORK holding the home directory's lock, so concurrent jeans
    /// commands change the graph one at a time.
    fn locked<T>(&self, work: impl FnOnce() -> Result<T>) -> Result<T> {
        let lock = fs_err::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(self.home.join("lock"))?;
        lock.file().lock()?;
        work()
    }
}