brain: Make file acceptance undoable

a20f7fd28fe04dec72286509a242e84d0dbb5a0b
Record each newly accepted file hunk in document order so the existing
undo action can reject the most recent acceptance.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 7bf70d2d
crates/brain/src/session.rs +223 -5
10 10
    FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress, ViewChange,
11 11
    spawn_highlighter,
12 12
};
13 13
use rustik_repo::DiffStat;
14 14
use rustik_tui::{
15 -
    Constraint, Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, ScrollView,
16 -
    Style, Table, TableOptions, Terminal,
15 +
    Backend as TuiBackend, Constraint, Control, Event, Key, Line, List, ListState, Mouse,
16 +
    MouseButton, Rect, ScrollView, Style, Table, TableOptions, Terminal,
17 17
};
18 18
use rustik_tui_termion as tui_termion;
19 19
20 20
use crate::backend::{Backend, Brain, Commit, CommitHunks, FilePatches, HistoryStatus};
21 21
use crate::comments::ReviewComments;
222 222
    }
223 223
    Ok(())
224 224
}
225 225
226 226
/// Interactive terminal session state.
227 -
struct Session<'a> {
227 +
struct Session<'a, T: TuiBackend<Error = io::Error>> {
228 228
    /// Terminal frame target.
229 -
    terminal: &'a mut BrainTerminal,
229 +
    terminal: &'a mut Terminal<T>,
230 230
    /// Per-commit review slots, newest first.
231 231
    commits: Vec<CommitSlot>,
232 232
    /// User-facing revision range under review.
233 233
    range: String,
234 234
    /// Lazily cached global progress and remaining statistics for history.
263 263
    context_fetch: ContextFetch,
264 264
    /// Most recent recoverable session error shown in the status bar.
265 265
    error: Option<String>,
266 266
}
267 267
268 -
impl Session<'_> {
268 +
impl<T: TuiBackend<Error = io::Error>> Session<'_, T> {
269 269
    /// Returns the current commit's diff state, decoding it on first access.
270 270
    fn current(&mut self) -> Result<&mut CommitReview, Error> {
271 271
        self.load(self.current)
272 272
    }
273 273
523 523
        Ok(())
524 524
    }
525 525
526 526
    /// Persists acceptance or rejection of every hunk in the focused file.
527 527
    fn toggle_focused_file(&mut self, area: Rect) -> Result<(), Error> {
528 +
        let current = self.current;
528 529
        let loaded = self.current()?;
529 530
        let Some(file) = loaded.viewer.focused_file() else {
530 531
            loaded.viewer.apply(DiffAction::NextHunk, area);
531 532
            return Ok(());
532 533
        };
538 539
        else {
539 540
            return Ok(());
540 541
        };
541 542
        let hunk_ids = file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>();
542 543
        let accepted = loaded.review.accepts_all(hunk_ids.iter().copied());
544 +
        let mut newly_accepted = Vec::new();
543 545
        let hunks = hunk_ids
544 546
            .iter()
545 547
            .copied()
546 548
            .filter(|hunk| loaded.review.is_accepted(*hunk) == accepted)
547 549
            .filter_map(|hunk| {
548 550
                let identity = loaded.identities.get(&hunk)?.clone();
549 551
                let patch = loaded.hunk_patches.get(&hunk)?.clone();
552 +
                if !accepted {
553 +
                    newly_accepted.push((current, hunk));
554 +
                }
550 555
                Some((identity, patch))
551 556
            })
552 557
            .collect::<Vec<_>>();
553 558
        if accepted {
554 559
            let rejected = hunk_ids
558 563
            self.reject_hunks(rejected.clone())?;
559 564
            self.accepted_hunks
560 565
                .retain(|accepted| !rejected.contains(accepted));
561 566
        } else {
562 567
            self.brain.accept(hunks)?;
568 +
            self.accepted_hunks.extend(newly_accepted);
563 569
        }
564 570
        self.reconcile_reviews()?;
565 571
        Ok(())
566 572
    }
567 573
1268 1274
            Mode::Hunk(view) if view.is_editing() => ActionContext::HunkEdit,
1269 1275
            Mode::Hunk(_) => ActionContext::HunkBrowse,
1270 1276
        }
1271 1277
    }
1272 1278
}
1279 +
1280 +
#[cfg(test)]
1281 +
mod tests {
1282 +
    use std::fs;
1283 +
    use std::path::{Path, PathBuf};
1284 +
    use std::process::Command;
1285 +
    use std::time::{SystemTime, UNIX_EPOCH};
1286 +
1287 +
    use rustik_repo::Rev;
1288 +
    use rustik_tui::{Point, Size};
1289 +
1290 +
    use super::*;
1291 +
1292 +
    /// In-memory terminal backend with the production backend's error type.
1293 +
    struct IoTestBackend {
1294 +
        /// Fixed terminal size.
1295 +
        size: Size,
1296 +
    }
1297 +
1298 +
    impl TuiBackend for IoTestBackend {
1299 +
        type Error = io::Error;
1300 +
1301 +
        fn size(&mut self) -> io::Result<Size> {
1302 +
            Ok(self.size)
1303 +
        }
1304 +
1305 +
        fn draw(&mut self, _: &[rustik_tui::buffer::DirtyRun<'_>]) -> io::Result<()> {
1306 +
            Ok(())
1307 +
        }
1308 +
1309 +
        fn clear(&mut self) -> io::Result<()> {
1310 +
            Ok(())
1311 +
        }
1312 +
1313 +
        fn flush(&mut self) -> io::Result<()> {
1314 +
            Ok(())
1315 +
        }
1316 +
1317 +
        fn set_cursor_position(&mut self, _: Point) -> io::Result<()> {
1318 +
            Ok(())
1319 +
        }
1320 +
1321 +
        fn set_cursor_visible(&mut self, _: bool) -> io::Result<()> {
1322 +
            Ok(())
1323 +
        }
1324 +
    }
1325 +
1326 +
    /// Temporary Git repository containing one commit with two hunks.
1327 +
    struct RepositoryFixture {
1328 +
        /// Repository working tree.
1329 +
        path: PathBuf,
1330 +
    }
1331 +
1332 +
    impl RepositoryFixture {
1333 +
        /// Creates a repository whose tip changes two distant lines.
1334 +
        fn new() -> Self {
1335 +
            let nonce = SystemTime::now()
1336 +
                .duration_since(UNIX_EPOCH)
1337 +
                .unwrap()
1338 +
                .as_nanos();
1339 +
            let path = std::env::temp_dir().join(format!(
1340 +
                "rustik-brain-session-{}-{nonce}",
1341 +
                std::process::id()
1342 +
            ));
1343 +
            fs::create_dir(&path).unwrap();
1344 +
            Self::git(&path, &["init", "-q", "-b", "main", "."]);
1345 +
            fs::write(
1346 +
                path.join("review.txt"),
1347 +
                "\
1348 +
first
1349 +
unchanged 01
1350 +
unchanged 02
1351 +
unchanged 03
1352 +
unchanged 04
1353 +
unchanged 05
1354 +
unchanged 06
1355 +
unchanged 07
1356 +
unchanged 08
1357 +
unchanged 09
1358 +
unchanged 10
1359 +
unchanged 11
1360 +
unchanged 12
1361 +
unchanged 13
1362 +
last
1363 +
",
1364 +
            )
1365 +
            .unwrap();
1366 +
            Self::git(&path, &["add", "review.txt"]);
1367 +
            Self::git(&path, &["commit", "-q", "-m", "base"]);
1368 +
            fs::write(
1369 +
                path.join("review.txt"),
1370 +
                "\
1371 +
changed first
1372 +
unchanged 01
1373 +
unchanged 02
1374 +
unchanged 03
1375 +
unchanged 04
1376 +
unchanged 05
1377 +
unchanged 06
1378 +
unchanged 07
1379 +
unchanged 08
1380 +
unchanged 09
1381 +
unchanged 10
1382 +
unchanged 11
1383 +
unchanged 12
1384 +
unchanged 13
1385 +
changed last
1386 +
",
1387 +
            )
1388 +
            .unwrap();
1389 +
            Self::git(&path, &["add", "review.txt"]);
1390 +
            Self::git(&path, &["commit", "-q", "-m", "change"]);
1391 +
1392 +
            Self { path }
1393 +
        }
1394 +
1395 +
        /// Runs a Git command in the fixture repository.
1396 +
        fn git(path: &Path, args: &[&str]) {
1397 +
            let status = Command::new("git")
1398 +
                .args(["-c", "commit.gpgsign=false"])
1399 +
                .args(args)
1400 +
                .current_dir(path)
1401 +
                .env("GIT_AUTHOR_NAME", "Rustik Test")
1402 +
                .env("GIT_AUTHOR_EMAIL", "rustik@example.com")
1403 +
                .env("GIT_COMMITTER_NAME", "Rustik Test")
1404 +
                .env("GIT_COMMITTER_EMAIL", "rustik@example.com")
1405 +
                .status()
1406 +
                .unwrap();
1407 +
            assert!(status.success());
1408 +
        }
1409 +
    }
1410 +
1411 +
    impl Drop for RepositoryFixture {
1412 +
        fn drop(&mut self) {
1413 +
            fs::remove_dir_all(&self.path).unwrap();
1414 +
        }
1415 +
    }
1416 +
1417 +
    #[test]
1418 +
    fn undo_rejects_last_hunk_accepted_with_focused_file() {
1419 +
        let repository = RepositoryFixture::new();
1420 +
        let base = Rev::try_from("HEAD^").unwrap();
1421 +
        let target = Rev::try_from("HEAD").unwrap();
1422 +
        let backend = <dyn Backend>::from_path(&repository.path, base, target).unwrap();
1423 +
        let brain = backend.brain().unwrap();
1424 +
        let commit = backend.commits().unwrap().pop().unwrap();
1425 +
        let remaining_stats = commit.stats;
1426 +
        let slot = CommitSlot {
1427 +
            commit,
1428 +
            progress: ReviewProgress::default(),
1429 +
            remaining_stats,
1430 +
            document: None,
1431 +
            identities: None,
1432 +
            loaded: None,
1433 +
        };
1434 +
        let mut terminal = Terminal::new(IoTestBackend {
1435 +
            size: Size::new(80, 24),
1436 +
        })
1437 +
        .unwrap();
1438 +
        let (events_tx, _events_rx) = mpsc::channel();
1439 +
        let mut session = Session {
1440 +
            terminal: &mut terminal,
1441 +
            commits: vec![slot],
1442 +
            range: "HEAD^..HEAD".to_owned(),
1443 +
            history_status: None,
1444 +
            accepted_hunks: Vec::new(),
1445 +
            current: 0,
1446 +
            visibility: Visibility::default(),
1447 +
            mode: Mode::Diff,
1448 +
            parked: None,
1449 +
            list: ListState::new(),
1450 +
            options: DiffOptions::default(),
1451 +
            backend,
1452 +
            brain,
1453 +
            comments: ReviewComments::parse("").unwrap(),
1454 +
            events_tx,
1455 +
            generation: 0,
1456 +
            highlighter: None,
1457 +
            context_fetch: ContextFetch::default(),
1458 +
            error: None,
1459 +
        };
1460 +
        let area = Rect::new(0, 0, 80, 23);
1461 +
        let hunk_ids = {
1462 +
            let loaded = session.current().unwrap();
1463 +
            loaded.viewer.apply(DiffAction::NextHunk, area);
1464 +
            loaded.document.files[0]
1465 +
                .hunks
1466 +
                .iter()
1467 +
                .map(|hunk| hunk.id)
1468 +
                .collect::<Vec<_>>()
1469 +
        };
1470 +
        assert_eq!(hunk_ids.len(), 2);
1471 +
1472 +
        session.toggle_focused_file(area).unwrap();
1473 +
        assert_eq!(
1474 +
            session.current().unwrap().review.accepted(),
1475 +
            &BTreeSet::from([hunk_ids[0], hunk_ids[1]])
1476 +
        );
1477 +
1478 +
        session.undo_last_hunk_accept().unwrap();
1479 +
        let loaded = session.current().unwrap();
1480 +
        assert_eq!(loaded.review.accepted(), &BTreeSet::from([hunk_ids[0]]));
1481 +
        assert_eq!(
1482 +
            loaded.viewer.document().files[0]
1483 +
                .hunks
1484 +
                .iter()
1485 +
                .map(|hunk| hunk.id)
1486 +
                .collect::<Vec<_>>(),
1487 +
            vec![hunk_ids[1]]
1488 +
        );
1489 +
    }
1490 +
}