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
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;

use crate::Error;
use crate::Result;
use crate::color::Paint;
use crate::graph::Jeans;
use crate::graph::STATES;
use crate::graph::State;
use crate::graph::Task;
use crate::graph::ids_revset;
use crate::message::short;

const LOG_TEMPLATE: &str = r#"change_id.short(12) ++ " " ++ description.first_line() ++ "\n""#;

impl Jeans {
    pub(crate) fn ready(&self) -> Result<Vec<String>> {
        Ok(self
            .tasks()?
            .into_iter()
            .filter(|t| t.state == State::Ready)
            .map(|t| t.id)
            .collect())
    }

    /// `jj log` of the tasks in VIEW, each ID followed by its state.
    pub(crate) fn log(&self, view: Option<&str>, task: Option<&str>) -> Result<String> {
        let tasks = self.tasks()?;
        let ids_in = |keep: &dyn Fn(State) -> bool| {
            let ids: Vec<&str> = tasks
                .iter()
                .filter(|t| keep(t.state))
                .map(|t| t.id.as_str())
                .collect();
            ids_revset(&ids)
        };
        let revset = match view {
            None => format!("{} | trunk()", self.tasks_revset),
            Some("open") => ids_in(&|s| s != State::Done),
            Some("under") => format!(
                "::{} & ({})",
                self.resolve_view_task(task)?,
                self.tasks_revset
            ),
            Some("path") => format!("{}::{}", self.resolve_view_task(task)?, self.goal_revset),
            Some(view) => match STATES.into_iter().find(|s| s.name() == view) {
                Some(state) => ids_in(&|s| s == state),
                None => format!("({view}) & ({})", self.tasks_revset),
            },
        };
        let out = self.jj(&["log", "-r", &revset, "-T", LOG_TEMPLATE])?;
        Ok(self.label_ids(&out, &tasks))
    }

    /// An outline with the goal at the root, followed by any resolution
    /// tasks under the done node. Each task sits under the tasks it feeds. A
    /// task feeding more than one other task is printed once and referenced
    /// after. Everything feeding a done task is done too, so its subtree
    /// collapses to a count.
    pub(crate) fn tree(&self, root: Option<&str>, depth: Option<usize>) -> Result<String> {
        let tasks = self.tasks()?;
        let roots = match root {
            Some(root) => vec![self.resolve(root)?],
            None => {
                let mut roots = self.log_ids(&self.goal_revset)?;
                roots.extend(self.log_ids(&format!(
                    "heads(({}) ~ ::{})",
                    self.tasks_revset, self.goal_revset
                ))?);
                roots
            }
        };
        let mut tree = Tree {
            jeans: self,
            by_id: tasks.iter().map(|t| (t.id.as_str(), t)).collect(),
            depth,
            lines: Vec::new(),
            seen: HashSet::new(),
        };
        for id in &roots {
            tree.visit(id, "", "", 0)?;
        }
        Ok(tree.lines.join("\n"))
    }

    /// One section per state, for ROOT and what feeds it.
    pub(crate) fn board(&self, root: Option<&str>) -> Result<String> {
        let tasks = self.tasks()?;
        let by_id: HashMap<&str, &Task> = tasks.iter().map(|t| (t.id.as_str(), t)).collect();
        let scope = match root {
            Some(root) => {
                let under = format!("::{} & ({})", self.resolve(root)?, self.tasks_revset);
                self.log_ids(&under)?
            }
            None => tasks.iter().map(|t| t.id.clone()).collect(),
        };
        let mut sections = Vec::new();
        for state in STATES {
            let mut section = Vec::new();
            for task in scope.iter().filter_map(|id| by_id.get(id.as_str())) {
                if task.state == state {
                    section.push(format!(
                        "  {} {}",
                        self.paint(short(&task.id, 8), Paint::Id),
                        task.title
                    ));
                }
            }
            let heading = format!("{} ({})", state.name().to_uppercase(), section.len());
            section.insert(0, self.paint(&heading, state.paint()));
            sections.push(section.join("\n"));
        }
        Ok(sections.join("\n\n"))
    }

    /// Redraws VIEW whenever jj records an operation, until `stop` is set.
    pub(crate) fn watch(
        &self,
        view: &str,
        task: Option<&str>,
        depth: Option<usize>,
        stop: &Arc<AtomicBool>,
        out: &mut impl std::io::Write,
    ) -> Result<()> {
        if view != "tree" && view != "board" {
            return Err(Error::msg(format!("watch shows tree or board, not {view}")));
        }
        let interval = Duration::from_secs(1);
        let mut last = None;
        while !stop.load(Ordering::Relaxed) {
            // A terminal's ^C also kills the jj child mid-call, which is no error.
            if let Err(e) = self.redraw(view, task, depth, &mut last, out)
                && !stop.load(Ordering::Relaxed)
            {
                return Err(e);
            }
            let deadline = Instant::now()
                .checked_add(interval)
                .unwrap_or_else(Instant::now);
            while !stop.load(Ordering::Relaxed) && Instant::now() < deadline {
                std::thread::sleep(Duration::from_millis(50));
            }
        }
        Ok(())
    }

    /// Draws VIEW unless jj's latest operation is still LAST.
    fn redraw(
        &self,
        view: &str,
        task: Option<&str>,
        depth: Option<usize>,
        last: &mut Option<String>,
        out: &mut impl std::io::Write,
    ) -> Result<()> {
        let op = self.jj(&["op", "log", "-n1", "--no-graph", "-T", "id"])?;
        if last.as_ref() != Some(&op) {
            let frame = if view == "board" {
                self.board(task)?
            } else {
                self.tree(task, depth)?
            };
            writeln!(out, "\x1b[H\x1b[2J{frame}")?;
            out.flush()?;
            *last = Some(op);
        }
        Ok(())
    }

    /// A task's state, workspace, and description.
    pub(crate) fn show(&self, rev: &str) -> Result<String> {
        let id = self.resolve(rev)?;
        let state = self.state(&id)?;
        let description = self.jj(&["log", "--no-graph", "-r", &id, "-T", "description"])?;
        Ok(format!(
            "{}\n{}\n{description}",
            self.paint(state.name(), state.paint()),
            self.workspace_path(&id)
        ))
    }

    fn resolve_view_task(&self, task: Option<&str>) -> Result<String> {
        self.resolve(task.ok_or_else(|| Error::msg("log under and log path need TASK"))?)
    }

    /// Follows each task ID in jj's log output with the task's state.
    fn label_ids(&self, out: &str, tasks: &[Task]) -> String {
        let is_word = |c: char| c.is_alphanumeric() || c == '_';
        let mut labeled = String::with_capacity(out.len());
        let mut rest = out;
        while let Some(start) = rest.find(is_word) {
            let (before, from_word) = rest.split_at(start);
            let end = from_word.find(|c| !is_word(c)).unwrap_or(from_word.len());
            let (word, after) = from_word.split_at(end);
            labeled.push_str(before);
            if word.len() == 12 && word.bytes().all(|b| (b'k'..=b'z').contains(&b)) {
                labeled.push_str(&self.paint(word, Paint::Id));
                if let Some(task) = tasks.iter().find(|t| t.id.starts_with(word)) {
                    labeled.push(' ');
                    labeled.push_str(&self.state_label(task.state));
                }
            } else {
                labeled.push_str(word);
            }
            rest = after;
        }
        labeled.push_str(rest);
        labeled
    }
}

struct Tree<'a> {
    jeans: &'a Jeans,
    by_id: HashMap<&'a str, &'a Task>,
    depth: Option<usize>,
    lines: Vec<String>,
    seen: HashSet<String>,
}

impl<'a> Tree<'a> {
    fn visit(&mut self, id: &str, lead: &str, branch: &str, level: usize) -> Result<()> {
        let task = self.task(id)?;
        let label = format!(
            "{lead}{branch}{} {} {}",
            self.jeans.paint(short(id, 8), Paint::Id),
            task.title,
            self.jeans.state_label(task.state)
        );
        let children = self.subtasks(task);
        if self.seen.contains(id) {
            self.lines.push(format!("{label} (see above)"));
        } else if !children.is_empty() && (task.state == State::Done || Some(level) == self.depth) {
            let mut below = HashSet::new();
            self.count(task, &mut below);
            let kind = if task.state == State::Done {
                "done"
            } else {
                "more"
            };
            self.lines
                .push(format!("{label} (+{} {kind})", below.len()));
        } else {
            self.lines.push(label);
            self.seen.insert(id.to_owned());
            let child_lead = match branch {
                "├── " => format!("{lead}│   "),
                "└── " => format!("{lead}    "),
                _ => lead.to_owned(),
            };
            let last = children.len().saturating_sub(1);
            for (i, child) in children.iter().enumerate() {
                let branch = if i == last {
                    "└── "
                } else {
                    "├── "
                };
                self.visit(child, &child_lead, branch, level.saturating_add(1))?;
            }
        }
        Ok(())
    }

    fn task(&self, id: &str) -> Result<&'a Task> {
        self.by_id
            .get(id)
            .copied()
            .ok_or_else(|| Error::msg(format!("{id} isn't a task")))
    }

    fn subtasks(&self, task: &Task) -> Vec<String> {
        task.parents
            .iter()
            .filter(|p| self.by_id.contains_key(p.as_str()))
            .cloned()
            .collect()
    }

    fn count(&self, task: &Task, below: &mut HashSet<String>) {
        for child in self.subtasks(task) {
            if let Some(child_task) = self.by_id.get(child.as_str()).copied() {
                self.count(child_task, below);
            }
            below.insert(child);
        }
    }
}