rs-hop 0.2.0

Fuzzy-finder TUI to jump between git repositories and folders
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Business rules over the managed entries: CRUD, favourite/archive toggles,
//! slug assignment, path repair, usage tracking and one-level undo.
//!
//! The service owns the working entry list (with runtime git info and usage
//! hydrated onto it) and persists stored fields through the injected
//! [`RepoRepository`]. Every config-mutating method records the pre-change list
//! as a single undo frame and rolls back if the write fails.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::domain::error::{Error, Result};
use crate::domain::repo::{GitInfo, Repo};
use crate::domain::sections;
use crate::domain::slug;
use crate::storage::repository::RepoRepository;
use crate::storage::usage_state;

/// A captured entry list plus a human label, for one level of undo.
struct UndoSnapshot {
    repos: Vec<Repo>,
    label: String,
}

/// Coordinates reads and writes of the managed entries.
pub struct RepoService {
    repository: Box<dyn RepoRepository>,
    repos: Vec<Repo>,
    sections: Vec<String>,
    usage_path: PathBuf,
    selected_repo_path: PathBuf,
    undo: Option<UndoSnapshot>,
}

impl RepoService {
    /// Loads entries through `repository` and hydrates usage from `usage_path`.
    ///
    /// # Errors
    /// Returns an error if the entries cannot be read.
    pub fn new(
        repository: Box<dyn RepoRepository>,
        usage_path: PathBuf,
        selected_repo_path: PathBuf,
    ) -> Result<Self> {
        let mut service = RepoService {
            repos: repository.find_all()?,
            sections: repository.find_sections()?,
            repository,
            usage_path,
            selected_repo_path,
            undo: None,
        };
        service.hydrate_usage();
        Ok(service)
    }

    /// All entries in stored order (the view applies its own sort and filter).
    pub fn repos(&self) -> &[Repo] {
        &self.repos
    }

    /// The entry at `index`, if any.
    pub fn get(&self, index: usize) -> Option<&Repo> {
        self.repos.get(index)
    }

    /// The index of the entry with the given slug, if any.
    pub fn index_by_slug(&self, slug: &str) -> Option<usize> {
        self.repos
            .iter()
            .position(|repo| repo.slug.as_deref() == Some(slug))
    }

    /// Adds `repo`, validating its slug when present.
    ///
    /// # Errors
    /// Returns [`Error::Slug`] for an invalid or duplicate slug, or a write
    /// error if persistence fails.
    pub fn add(&mut self, repo: Repo) -> Result<()> {
        if let Some(slug) = repo.slug.clone() {
            self.check_slug(&slug, None)?;
        }
        self.mutate("add entry", |repos| {
            repos.push(repo);
            Ok(())
        })
    }

    /// Adds several entries as one undo-able action (used by `hop scan`).
    /// A no-op for an empty list.
    ///
    /// # Errors
    /// Returns [`Error::Slug`] for an invalid or duplicate slug, or a write
    /// error if persistence fails.
    pub fn add_many(&mut self, repos: Vec<Repo>) -> Result<()> {
        if repos.is_empty() {
            return Ok(());
        }
        for repo in &repos {
            if let Some(slug) = &repo.slug {
                self.check_slug(slug, None)?;
            }
        }
        self.mutate("add entries", |existing| {
            existing.extend(repos);
            Ok(())
        })
    }

    /// Replaces the entry at `index` with `repo`, validating its slug.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, [`Error::Slug`] for an
    /// invalid or duplicate slug, or a write error.
    pub fn update(&mut self, index: usize, repo: Repo) -> Result<()> {
        self.ensure_index(index)?;
        if let Some(slug) = repo.slug.clone() {
            self.check_slug(&slug, Some(index))?;
        }
        self.mutate("edit entry", |repos| {
            repos[index] = repo;
            Ok(())
        })
    }

    /// Removes the entry at `index`.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn delete(&mut self, index: usize) -> Result<()> {
        self.ensure_index(index)?;
        self.mutate("delete entry", |repos| {
            repos.remove(index);
            Ok(())
        })
    }

    /// Toggles the favourite flag of the entry at `index`.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn toggle_fav(&mut self, index: usize) -> Result<()> {
        self.ensure_index(index)?;
        self.mutate("toggle favourite", |repos| {
            repos[index].fav = !repos[index].fav;
            Ok(())
        })
    }

    /// Sets the archived flag of the entry at `index`.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn set_archived(&mut self, index: usize, archived: bool) -> Result<()> {
        self.ensure_index(index)?;
        let label = if archived {
            "archive entry"
        } else {
            "restore entry"
        };
        self.mutate(label, |repos| {
            repos[index].archived = archived;
            Ok(())
        })
    }

    /// Sets or clears the slug of the entry at `index`.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, [`Error::Slug`] for an
    /// invalid or duplicate slug, or a write error.
    pub fn set_slug(
        &mut self,
        index: usize,
        new_slug: Option<String>,
    ) -> Result<()> {
        self.ensure_index(index)?;
        if let Some(slug) = &new_slug {
            self.check_slug(slug, Some(index))?;
        }
        self.mutate("set slug", |repos| {
            repos[index].slug = new_slug;
            Ok(())
        })
    }

    /// Deletes every entry in `indices` as one undo-able action.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn delete_many(&mut self, indices: &[usize]) -> Result<()> {
        for &index in indices {
            self.ensure_index(index)?;
        }
        let mut sorted = indices.to_vec();
        sorted.sort_unstable();
        sorted.dedup();
        self.mutate("delete entries", |repos| {
            // Remove from the back so earlier indices stay valid.
            for &index in sorted.iter().rev() {
                repos.remove(index);
            }
            Ok(())
        })
    }

    /// Sets the archived flag for every entry in `indices` as one action.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn set_archived_many(
        &mut self,
        indices: &[usize],
        archived: bool,
    ) -> Result<()> {
        for &index in indices {
            self.ensure_index(index)?;
        }
        let label = if archived {
            "archive entries"
        } else {
            "restore entries"
        };
        let indices = indices.to_vec();
        self.mutate(label, |repos| {
            for &index in &indices {
                repos[index].archived = archived;
            }
            Ok(())
        })
    }

    /// Sets the favourite flag for every entry in `indices` as one action.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn set_fav_many(&mut self, indices: &[usize], fav: bool) -> Result<()> {
        for &index in indices {
            self.ensure_index(index)?;
        }
        let indices = indices.to_vec();
        self.mutate("set favourite", |repos| {
            for &index in &indices {
                repos[index].fav = fav;
            }
            Ok(())
        })
    }

    /// Swaps two entries' positions (the stored custom order), as one action.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn swap_entries(&mut self, a: usize, b: usize) -> Result<()> {
        self.ensure_index(a)?;
        self.ensure_index(b)?;
        self.mutate("reorder entry", |repos| {
            repos.swap(a, b);
            Ok(())
        })
    }

    /// Repoints the entry at `index` to `path` (used by the path-repair picker).
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn set_path(&mut self, index: usize, path: PathBuf) -> Result<()> {
        self.ensure_index(index)?;
        self.mutate("repair path", |repos| {
            repos[index].path = path;
            Ok(())
        })
    }

    /// The ordered list of user section names (Files tab grouping).
    pub fn sections(&self) -> &[String] {
        &self.sections
    }

    /// Appends a new section, validating its name.
    ///
    /// # Errors
    /// Returns [`Error::Invalid`] for an empty, reserved or duplicate name, or a
    /// write error.
    pub fn add_section(&mut self, name: &str) -> Result<()> {
        let name = name.trim();
        self.validate_section_name(name, None)?;
        let mut next = self.sections.clone();
        next.push(name.to_string());
        self.persist_sections(next)
    }

    /// Registers `name` as a section if it is non-empty and not already known
    /// (case-insensitive), used when an entry is saved with a new section.
    ///
    /// # Errors
    /// Returns a write error if persistence fails.
    pub fn ensure_section(&mut self, name: &str) -> Result<()> {
        let name = name.trim();
        if name.is_empty() || self.section_index(name).is_some() {
            return Ok(());
        }
        let mut next = self.sections.clone();
        next.push(name.to_string());
        self.persist_sections(next)
    }

    /// Renames the section `old` to `new`, updating every entry that referenced
    /// it (one undo frame for the entries).
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] when `old` is unknown, [`Error::Invalid`] for
    /// a bad `new` name, or a write error.
    pub fn rename_section(&mut self, old: &str, new: &str) -> Result<()> {
        let new = new.trim();
        let pos = self
            .section_index(old)
            .ok_or_else(|| Error::NotFound(format!("section '{old}'")))?;
        self.validate_section_name(new, Some(pos))?;
        let old_name = self.sections[pos].clone();
        let new_name = new.to_string();
        self.mutate("rename section", |repos| {
            for repo in repos.iter_mut() {
                if repo.section.as_deref() == Some(old_name.as_str()) {
                    repo.section = Some(new_name.clone());
                }
            }
            Ok(())
        })?;
        let mut next = self.sections.clone();
        next[pos] = new.to_string();
        self.persist_sections(next)
    }

    /// Deletes the section `name`, moving its entries to Ungrouped (one undo
    /// frame for the entries).
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] when `name` is unknown, or a write error.
    pub fn delete_section(&mut self, name: &str) -> Result<()> {
        let pos = self
            .section_index(name)
            .ok_or_else(|| Error::NotFound(format!("section '{name}'")))?;
        let removed = self.sections[pos].clone();
        self.mutate("delete section", |repos| {
            for repo in repos.iter_mut() {
                if repo.section.as_deref() == Some(removed.as_str()) {
                    repo.section = None;
                }
            }
            Ok(())
        })?;
        let mut next = self.sections.clone();
        next.remove(pos);
        self.persist_sections(next)
    }

    /// Moves the section at `from` to position `to` in the order.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for an out-of-range index, or a write error.
    pub fn move_section(&mut self, from: usize, to: usize) -> Result<()> {
        let len = self.sections.len();
        if from >= len || to >= len {
            return Err(Error::NotFound(format!("section index {from}/{to}")));
        }
        let mut next = self.sections.clone();
        let name = next.remove(from);
        next.insert(to, name);
        self.persist_sections(next)
    }

    /// The index of the section named `name` (case-insensitive), if present.
    fn section_index(&self, name: &str) -> Option<usize> {
        let name = name.trim();
        self.sections
            .iter()
            .position(|section| section.eq_ignore_ascii_case(name))
    }

    /// Validates a section name: non-empty, not the reserved Ungrouped label,
    /// and not a duplicate of another section (case-insensitive).
    fn validate_section_name(
        &self,
        name: &str,
        except: Option<usize>,
    ) -> Result<()> {
        if name.is_empty() {
            return Err(Error::invalid("section name must not be empty"));
        }
        if name.eq_ignore_ascii_case(sections::UNGROUPED) {
            return Err(Error::invalid("'Ungrouped' is a reserved name"));
        }
        let clash = self.sections.iter().enumerate().any(|(index, section)| {
            Some(index) != except && section.eq_ignore_ascii_case(name)
        });
        if clash {
            return Err(Error::invalid(format!(
                "section '{name}' already exists"
            )));
        }
        Ok(())
    }

    /// Replaces the section list and persists it, rolling back on write failure.
    fn persist_sections(&mut self, next: Vec<String>) -> Result<()> {
        let previous = std::mem::replace(&mut self.sections, next);
        if let Err(error) = self.repository.save_sections(&self.sections) {
            self.sections = previous;
            return Err(error);
        }
        Ok(())
    }

    /// Reverts the last config mutation, returning its label.
    ///
    /// # Errors
    /// Returns a write error if persisting the reverted list fails.
    pub fn undo(&mut self) -> Result<Option<String>> {
        let Some(snapshot) = self.undo.take() else {
            return Ok(None);
        };
        self.repository.save_all(&snapshot.repos)?;
        self.repos = snapshot.repos;
        self.hydrate_usage();
        Ok(Some(snapshot.label))
    }

    /// Records an open of the entry at `index`: bumps its usage counters.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] for a bad index, or a write error.
    pub fn mark_used(&mut self, index: usize) -> Result<()> {
        let repo = self
            .repos
            .get(index)
            .ok_or_else(|| Error::NotFound(format!("index {index}")))?;
        let path = repo.path.clone();
        usage_state::record(&self.usage_path, &path)?;
        if let Some(usage) =
            usage_state::load(&self.usage_path).get(&path).copied()
        {
            let repo = &mut self.repos[index];
            repo.last_used = usage.last_used;
            repo.open_count = usage.open_count;
        }
        Ok(())
    }

    /// Writes `repo_path` to the selected-repo handoff file the shell reads.
    ///
    /// # Errors
    /// Returns a write error if the file cannot be written.
    pub fn write_selected(&self, repo_path: &Path) -> Result<()> {
        usage_state::write_selected_repo(&self.selected_repo_path, repo_path)
    }

    /// Applies gathered git info onto the matching entries (by path).
    pub fn apply_git_infos(&mut self, infos: &HashMap<PathBuf, GitInfo>) {
        for repo in &mut self.repos {
            if let Some(info) = infos.get(&repo.path) {
                repo.git_info = Some(info.clone());
            }
        }
    }

    /// Sets the live git info for the entry whose path matches `path`.
    pub fn set_git_info(&mut self, path: &Path, info: GitInfo) {
        for repo in &mut self.repos {
            if repo.path == path {
                repo.git_info = Some(info.clone());
            }
        }
    }

    /// Loads usage counters and copies them onto the in-memory entries.
    fn hydrate_usage(&mut self) {
        let usage = usage_state::load(&self.usage_path);
        for repo in &mut self.repos {
            if let Some(entry) = usage.get(&repo.path) {
                repo.last_used = entry.last_used;
                repo.open_count = entry.open_count;
            }
        }
    }

    /// Validates a slug's format and that no other entry already uses it.
    fn check_slug(&self, slug: &str, except: Option<usize>) -> Result<()> {
        slug::validate_format(slug)?;
        let clash = self.repos.iter().enumerate().any(|(index, repo)| {
            Some(index) != except && repo.slug.as_deref() == Some(slug)
        });
        if clash {
            return Err(Error::Slug(format!(
                "slug '{slug}' is already in use"
            )));
        }
        Ok(())
    }

    /// Confirms `index` is in range.
    fn ensure_index(&self, index: usize) -> Result<()> {
        if index >= self.repos.len() {
            return Err(Error::NotFound(format!("index {index}")));
        }
        Ok(())
    }

    /// Applies `f` to the entry list, persists it, and records one undo frame.
    /// Rolls back the in-memory list if `f` or the write fails.
    fn mutate<F>(&mut self, label: &str, f: F) -> Result<()>
    where
        F: FnOnce(&mut Vec<Repo>) -> Result<()>,
    {
        let snapshot = self.repos.clone();
        if let Err(error) = f(&mut self.repos) {
            self.repos = snapshot;
            return Err(error);
        }
        if let Err(error) = self.repository.save_all(&self.repos) {
            self.repos = snapshot;
            return Err(error);
        }
        self.undo = Some(UndoSnapshot {
            repos: snapshot,
            label: label.to_string(),
        });
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::repo::RepoKind;
    use crate::storage::in_memory_repository::InMemoryRepoRepository;

    fn service(initial: Vec<Repo>) -> RepoService {
        let dir = std::env::temp_dir().join(format!(
            "hop-svc-{}-{}",
            std::process::id(),
            initial.len()
        ));
        RepoService::new(
            Box::new(InMemoryRepoRepository::new(initial)),
            dir.join("usage.toml"),
            dir.join("selected.txt"),
        )
        .unwrap()
    }

    fn repo(name: &str) -> Repo {
        let mut repo = Repo::new(PathBuf::from(format!("/code/{name}")));
        repo.name = Some(name.to_string());
        repo
    }

    #[test]
    fn add_rejects_duplicate_slug() {
        let mut a = repo("a");
        a.slug = Some("x".to_string());
        let mut svc = service(vec![a]);
        let mut b = repo("b");
        b.slug = Some("x".to_string());
        assert!(matches!(svc.add(b), Err(Error::Slug(_))));
        assert_eq!(svc.repos().len(), 1);
    }

    #[test]
    fn delete_many_removes_all_and_undoes_as_one() {
        let mut svc = service(vec![repo("a"), repo("b"), repo("c")]);
        svc.delete_many(&[0, 2]).unwrap();
        let names: Vec<_> =
            svc.repos().iter().map(Repo::display_name).collect();
        assert_eq!(names, vec!["b"]);
        svc.undo().unwrap();
        assert_eq!(svc.repos().len(), 3);
    }

    #[test]
    fn set_archived_and_fav_many() {
        let mut svc = service(vec![repo("a"), repo("b"), repo("c")]);
        svc.set_archived_many(&[0, 1], true).unwrap();
        assert!(svc.get(0).unwrap().archived);
        assert!(svc.get(1).unwrap().archived);
        assert!(!svc.get(2).unwrap().archived);
        svc.set_fav_many(&[1, 2], true).unwrap();
        assert!(svc.get(1).unwrap().fav);
        assert!(svc.get(2).unwrap().fav);
    }

    #[test]
    fn swap_entries_reorders() {
        let mut svc = service(vec![repo("a"), repo("b"), repo("c")]);
        svc.swap_entries(0, 2).unwrap();
        let names: Vec<_> =
            svc.repos().iter().map(Repo::display_name).collect();
        assert_eq!(names, vec!["c", "b", "a"]);
    }

    #[test]
    fn add_rejects_reserved_slug() {
        let mut svc = service(vec![]);
        let mut a = repo("a");
        a.slug = Some("list".to_string());
        assert!(matches!(svc.add(a), Err(Error::Slug(_))));
    }

    #[test]
    fn archive_and_restore_round_trip() {
        let mut svc = service(vec![repo("a")]);
        svc.set_archived(0, true).unwrap();
        assert!(svc.get(0).unwrap().archived);
        svc.set_archived(0, false).unwrap();
        assert!(!svc.get(0).unwrap().archived);
    }

    #[test]
    fn toggle_fav_flips_flag() {
        let mut svc = service(vec![repo("a")]);
        svc.toggle_fav(0).unwrap();
        assert!(svc.get(0).unwrap().fav);
    }

    #[test]
    fn set_slug_then_lookup_by_slug() {
        let mut svc = service(vec![repo("a"), repo("b")]);
        svc.set_slug(1, Some("bee".to_string())).unwrap();
        assert_eq!(svc.index_by_slug("bee"), Some(1));
    }

    #[test]
    fn undo_reverts_last_change() {
        let mut svc = service(vec![repo("a")]);
        svc.add(repo("b")).unwrap();
        assert_eq!(svc.repos().len(), 2);
        let label = svc.undo().unwrap();
        assert_eq!(label.as_deref(), Some("add entry"));
        assert_eq!(svc.repos().len(), 1);
    }

    fn sectioned(name: &str, section: Option<&str>) -> Repo {
        let mut repo = repo(name);
        repo.section = section.map(str::to_string);
        repo
    }

    #[test]
    fn add_section_rejects_empty_reserved_and_duplicate() {
        let mut svc = service(vec![]);
        svc.add_section("Work").unwrap();
        assert_eq!(svc.sections(), ["Work"]);
        assert!(matches!(svc.add_section("  "), Err(Error::Invalid(_))));
        assert!(matches!(
            svc.add_section("Ungrouped"),
            Err(Error::Invalid(_))
        ));
        // Duplicate is case-insensitive.
        assert!(matches!(svc.add_section("work"), Err(Error::Invalid(_))));
    }

    #[test]
    fn ensure_section_is_idempotent() {
        let mut svc = service(vec![]);
        svc.ensure_section("Work").unwrap();
        svc.ensure_section("work").unwrap();
        svc.ensure_section("  ").unwrap();
        assert_eq!(svc.sections(), ["Work"]);
    }

    #[test]
    fn rename_section_updates_entries() {
        let mut svc =
            service(vec![sectioned("a", Some("Work")), sectioned("b", None)]);
        svc.add_section("Work").unwrap();
        svc.rename_section("Work", "Job").unwrap();
        assert_eq!(svc.sections(), ["Job"]);
        assert_eq!(svc.get(0).unwrap().section.as_deref(), Some("Job"));
        assert_eq!(svc.get(1).unwrap().section, None);
    }

    #[test]
    fn delete_section_ungroups_entries() {
        let mut svc = service(vec![sectioned("a", Some("Work"))]);
        svc.add_section("Work").unwrap();
        svc.delete_section("Work").unwrap();
        assert!(svc.sections().is_empty());
        assert_eq!(svc.get(0).unwrap().section, None);
    }

    #[test]
    fn move_section_reorders() {
        let mut svc = service(vec![]);
        svc.add_section("Work").unwrap();
        svc.add_section("Personal").unwrap();
        svc.add_section("Misc").unwrap();
        svc.move_section(2, 0).unwrap();
        assert_eq!(svc.sections(), ["Misc", "Work", "Personal"]);
    }

    #[test]
    fn delete_removes_entry() {
        let mut svc = service(vec![repo("a"), repo("b")]);
        svc.delete(0).unwrap();
        assert_eq!(svc.repos().len(), 1);
        assert_eq!(svc.get(0).unwrap().display_name(), "b");
    }

    #[test]
    fn add_many_appends_all_in_one_action() {
        let mut svc = service(vec![repo("a")]);
        svc.add_many(vec![repo("b"), repo("c")]).unwrap();
        let names: Vec<_> =
            svc.repos().iter().map(Repo::display_name).collect();
        assert_eq!(names, vec!["a", "b", "c"]);
        // One undo frame reverts the whole batch.
        svc.undo().unwrap();
        assert_eq!(svc.repos().len(), 1);
        // An empty batch is a no-op.
        svc.add_many(vec![]).unwrap();
        assert_eq!(svc.repos().len(), 1);
    }

    #[test]
    fn update_changes_kind() {
        let mut svc = service(vec![repo("a")]);
        let mut edited = repo("a");
        edited.kind = RepoKind::Path;
        svc.update(0, edited).unwrap();
        assert_eq!(svc.get(0).unwrap().kind, RepoKind::Path);
    }
}