thirdshift 0.16.3

Turn a GitHub issue into a ready-for-review pull request, unattended
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Dismiss an Inbox row from the CLI or Console, or take a dismissal back, keeping
//! each dismissal beside its Command record as a Stop request is kept.

use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

use super::reading::{Group, InboxItem, Observation, Snapshot};
use crate::config::UserConfig;

/// The stored kind of a dismissed Ready for review row.
pub(crate) const READY_KIND: &str = "Ready";

/// One Inbox row a dismissal covers, within its Command record. A dispatched
/// Spec run or Ticket run shares its outer Command's record, so the selector
/// says which of the record's rows this entry covers.
#[derive(Clone, Deserialize, Serialize)]
pub(crate) struct DismissedRow {
    pub selector: String,
    /// Last kind dismissed; retained for single-kind files and readers.
    pub kind: String,
    #[serde(default)]
    pub kinds: Vec<String>,
    pub who: String,
    pub at: String,
    #[serde(default)]
    pub from_console: bool,
}

impl DismissedRow {
    pub(crate) fn covers(&self, kind: &str) -> bool {
        self.kinds.iter().any(|covered| covered == kind)
    }

    fn source(&self) -> &'static str {
        if self.from_console { "Console" } else { "CLI" }
    }

    pub(crate) fn view(&self, current_kind: Option<&str>) -> DismissalView {
        DismissalView {
            who: self.who.clone(),
            dismissed_at: self.at.clone(),
            source: self.source(),
            kind: current_kind.unwrap_or(&self.kind).to_owned(),
            kinds: self.kinds.clone(),
        }
    }
}

/// A row's dismissal as `status --json` reports it: who, when, from where
/// and every kind it covers. `kind` is the current kind, or the last one
/// dismissed while a live row has no problem.
#[derive(Serialize)]
pub(crate) struct DismissalView {
    pub who: String,
    pub dismissed_at: String,
    pub source: &'static str,
    pub kind: String,
    pub kinds: Vec<String>,
}

impl DismissalView {
    pub(crate) fn line(&self) -> String {
        format!(
            "dismissed by {} from the {} at {}",
            self.who, self.source, self.dismissed_at
        )
    }
}

/// Every dismissal kept beside one Command record.
#[derive(Default, Deserialize, Serialize)]
struct DismissalFile {
    #[serde(default)]
    rows: Vec<DismissedRow>,
}

fn dismissal_path(record: &Path) -> PathBuf {
    record.with_extension("dismiss.json")
}

fn read(record: &Path) -> DismissalFile {
    std::fs::read(dismissal_path(record))
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default()
}

/// The dismissal covering this record's row, if one names its selector.
pub(crate) fn covering(record: &Path, selector: &str) -> Option<DismissedRow> {
    Captured::read(record).covering(selector).cloned()
}

/// One read of a Command record's dismissals, shared by all of its Inbox rows.
pub(super) struct Captured {
    rows: Vec<DismissedRow>,
}

impl Captured {
    pub(super) fn read(record: &Path) -> Self {
        let mut rows = read(record).rows;
        for row in &mut rows {
            // Dismissals written before kinds accumulated covered one kind.
            if !row.covers(&row.kind) {
                row.kinds.push(row.kind.clone());
            }
        }
        Self { rows }
    }

    pub(super) fn covering(&self, selector: &str) -> Option<&DismissedRow> {
        self.rows.iter().find(|row| row.selector == selector)
    }
}

fn write(record: &Path, file: &DismissalFile) -> Result<()> {
    let path = dismissal_path(record);
    if file.rows.is_empty() {
        return match std::fs::remove_file(&path) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(error).with_context(|| {
                format!("could not remove the dismissal beside {}", record.display())
            }),
        };
    }
    let parent = path.parent().context("Command record has no directory")?;
    let mut staged = tempfile::NamedTempFile::new_in(parent)?;
    staged.write_all(&serde_json::to_vec(&file)?)?;
    staged
        .persist(&path)
        .map(|_| ())
        .with_context(|| format!("could not keep the dismissal beside {}", record.display()))
}

/// One Inbox row holding the named Command: where to record and report the
/// dismissal, the kind a dismissal would cover, and every record-backed row
/// it stands for. A row read from history stands for no record.
struct DismissalTarget {
    repository: String,
    name: String,
    subject: String,
    group: Group,
    kind: String,
    members: Vec<(PathBuf, String)>,
    dismissed: bool,
}

fn row_for(
    snapshot: &Snapshot,
    github: &super::github::Kept,
    input: &str,
    days: i64,
    undo: bool,
) -> Result<DismissalTarget> {
    let selected = snapshot.resolve(input)?;
    let record = match selected.observation {
        Observation::Record(command) => &command.record,
        Observation::History(_) => {
            bail!("cannot dismiss {input}: row has no Command record");
        }
    };
    let name = record.name.clone();
    let mut target = DismissalTarget {
        repository: record.repository.clone(),
        subject: match &record.issue {
            Some(issue) => format!("{} #{}", record.kind, issue.number),
            None => name.clone(),
        },
        name,
        group: Group::History,
        kind: String::new(),
        members: Vec::new(),
        dismissed: false,
    };
    let selector = selected
        .observation
        .selector()
        .with_context(|| format!("cannot dismiss {input}: row has no Command record"))?;
    let found = snapshot
        .evaluate_inbox(days, github)
        .into_target(&selector)
        .with_context(|| {
            format!("cannot dismiss {input}: row is not in Needs you or Ready for review")
        })?;
    for item in std::iter::once(&found).chain(found.collapsed.iter()) {
        let Observation::Record(command) = item.command else {
            bail!("cannot dismiss {input}: row has no Command record");
        };
        let selector = item
            .command
            .selector()
            .with_context(|| format!("cannot dismiss {input}: row has no Command record"))?;
        target.members.push((command.record_path.clone(), selector));
    }
    // Taking a dismissal back works wherever the row now is, so only a
    // dismissal names a kind.
    let kind = match found.group {
        Group::NeedsYou => Some(
            found
                .needs_you_kind
                .map(|kind| kind.title().to_owned())
                .with_context(|| format!("cannot dismiss {input}: row has no Needs you kind"))?,
        ),
        Group::ReadyForReview => Some(READY_KIND.to_owned()),
        _ => None,
    };
    target.kind = match kind {
        Some(kind) => kind,
        None if undo => String::new(),
        None => {
            bail!(
                "cannot dismiss {input}: row is in {}, not Needs you or Ready for review",
                found.group.title()
            );
        }
    };
    target.group = found.group;
    target.dismissed = found.dismissal.is_some();
    Ok(target)
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Action {
    Dismiss,
    Undo,
}

impl Action {
    /// Availability for an evaluated row, including every collapsed member.
    pub(super) fn for_row(row: &InboxItem<'_>) -> Option<Self> {
        if !std::iter::once(row).chain(&row.collapsed).all(|item| {
            matches!(item.command, Observation::Record(_)) && item.command.selector().is_some()
        }) {
            return None;
        }
        if matches!(row.group, Group::NeedsYou | Group::ReadyForReview) {
            Some(Self::Dismiss)
        } else if row.dismissal.is_some() {
            Some(Self::Undo)
        } else {
            None
        }
    }
}

/// Command details uses the same row and collapse selection as a request.
pub(super) fn action(
    snapshot: &Snapshot,
    github: &super::github::Kept,
    input: &str,
    days: i64,
) -> Option<Action> {
    let selected = snapshot.resolve(input).ok()?;
    if !matches!(selected.observation, Observation::Record(_)) {
        return None;
    }
    let selector = selected.observation.selector()?;
    let row = snapshot
        .evaluate_inbox(days, github)
        .into_target(&selector)?;
    Action::for_row(&row)
}

pub(crate) struct Request {
    pub who: String,
    pub undo: bool,
    pub from_console: bool,
}

pub(crate) struct Change {
    name: String,
    group: Group,
    dismissal: Option<DismissalView>,
}

fn activity_write(config: &UserConfig, repository: &str, line: &str) -> Result<()> {
    let path = config.logs_dir.join(repository).join(super::activity::FILE);
    let mut file = super::activity::open(&path)?;
    writeln!(
        file,
        "{} {line}",
        chrono::Local::now().format(super::activity::TIME_FORMAT)
    )
    .with_context(|| format!("could not keep {}", path.display()))
}

pub fn dismiss(input: &str, undo: bool, json: bool) -> Result<()> {
    let who = super::unix_user("dismissal")?;
    let change = request(
        input,
        Request {
            who,
            undo,
            from_console: false,
        },
    )?;
    if let Some(dismissal) = change.dismissal {
        if json {
            println!(
                "{}",
                serde_json::json!({
                    "version": 1, "name": change.name, "group": change.group,
                    "dismissal": dismissal,
                })
            );
        } else {
            println!("dismissed {} from {}", change.name, change.group.title());
        }
    } else if json {
        println!(
            "{}",
            serde_json::json!({"version": 1, "name": change.name, "undone": true})
        );
    } else {
        println!("took back the dismissal of {}", change.name);
    }
    Ok(())
}

/// Shared mutation: Console callers supply their authenticated account; the CLI
/// supplies its Unix user. Neither caller changes GitHub or the live Command.
pub(crate) fn request(input: &str, request: Request) -> Result<Change> {
    let Request {
        who,
        undo,
        from_console,
    } = request;
    let source = if from_console { "Console" } else { "CLI" };
    let at = chrono::Local::now().to_rfc3339();
    let config = UserConfig::load()?;
    let snapshot = Snapshot::load_with_silence(
        &config.logs_dir,
        chrono::Local::now(),
        config.silent_interval,
    )?;
    let github = super::github::load(&config.logs_dir);
    let target = row_for(&snapshot, &github, input, config.inbox_days, undo)?;
    if target.members.is_empty() {
        bail!("cannot dismiss {input}: row has no Command record");
    }
    if undo {
        let mut taken_back = false;
        for (record, selector) in &target.members {
            let mut file = read(record);
            let kept = file.rows.len();
            file.rows.retain(|row| row.selector != *selector);
            if file.rows.len() != kept {
                taken_back = true;
                write(record, &file)?;
            }
        }
        if !taken_back {
            bail!("cannot take back the dismissal of {input}: row is not dismissed");
        }
        activity_write(
            &config,
            &target.repository,
            &format!(
                "{} dismissal taken back from the {source} by {who}",
                target.subject
            ),
        )?;
        return Ok(Change {
            name: target.name,
            group: target.group,
            dismissal: None,
        });
    }
    let mut dismissal = None;
    for (record, selector) in &target.members {
        let mut file = read(record);
        let mut kinds = covering(record, selector)
            .map(|row| row.kinds)
            .unwrap_or_default();
        if !kinds.contains(&target.kind) {
            kinds.push(target.kind.clone());
        }
        file.rows.retain(|row| row.selector != *selector);
        let row = DismissedRow {
            selector: selector.clone(),
            kind: target.kind.clone(),
            kinds,
            who: who.clone(),
            at: at.clone(),
            from_console,
        };
        dismissal.get_or_insert_with(|| row.view(None));
        file.rows.push(row);
        write(record, &file)?;
    }
    activity_write(
        &config,
        &target.repository,
        &format!("{} dismissed from the {source} by {who}", target.subject),
    )?;
    Ok(Change {
        name: target.name,
        group: target.group,
        dismissal,
    })
}