lazyfossil 0.7.3

Make it easy to work with Fossil from the terminal: browse files, see history, preview changes, and commit or sync without extra friction.
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
use anyhow::Result;
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Debug, Clone)]
pub struct RepoState {
    pub files: Vec<FileStatus>,
    pub timeline: Vec<TimelineEntry>,
    pub selected_file: usize,
}

#[derive(Debug, Clone)]
pub struct FileStatus {
    pub path: String,
    pub status: String,
}

#[derive(Debug, Clone)]
pub struct TimelineEntry {
    pub rid: String,
    pub user: String,
    pub message: String,
    pub date: String,
    pub tags: String,
}

#[derive(Debug)]
pub enum FossilError {
    NotRepository,
    CommandFailed(String),
}

impl std::fmt::Display for FossilError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FossilError::NotRepository => write!(f, "not a fossil repository"),
            FossilError::CommandFailed(msg) => write!(f, "{}", msg),
        }
    }
}

impl std::error::Error for FossilError {}

pub struct FossilClient {
    checkout_root: Option<PathBuf>,
    debug_enabled: bool,
}

impl FossilClient {
    pub fn new(debug_enabled: bool) -> Self {
        Self {
            checkout_root: None,
            debug_enabled,
        }
    }

    pub fn checkout_root_path(&self) -> Option<&Path> {
        self.checkout_root.as_deref()
    }

    pub fn repo_state(&mut self) -> std::result::Result<RepoState, FossilError> {
        self.ensure_repo()?;
        self.checkout_root = Some(self.checkout_root()?);
        let status = self.run(&["status"])?;
        let tracked = self.run(&["ls"])?;
        let extras = self.run(&["extras", "--dotfiles"]).unwrap_or_default();
        let timeline = self.history_timeline(None).unwrap_or_default();
        Ok(RepoState {
            files: merge_files(
                parse_tracked(&tracked),
                parse_status(&status),
                parse_extra(&extras),
            ),
            timeline,
            selected_file: 0,
        })
    }

    pub fn diff_for(&self, path: &str) -> std::result::Result<String, FossilError> {
        self.run(&["diff", "--", path])
    }

    pub fn checkin_diff(&self, rid: &str) -> std::result::Result<String, FossilError> {
        self.run(&["diff", "--checkin", rid])
    }

    pub fn checkin_file_diff(
        &self,
        rid: &str,
        path: &str,
    ) -> std::result::Result<String, FossilError> {
        self.run(&["diff", "--checkin", rid, "--", path])
    }

    pub fn sync(&self) -> std::result::Result<String, FossilError> {
        self.run(&["sync"])
    }

    pub fn history_timeline(
        &self,
        path: Option<&str>,
    ) -> std::result::Result<Vec<TimelineEntry>, FossilError> {
        let mut args: Vec<String> = vec!["timeline", "-n", "50", "-t", "ci", "-F", "%h|%a|%d|%c|%t"]
            .into_iter()
            .map(|s| s.to_string())
            .collect();
        if let Some(path) = path {
            args.push("-p".to_string());
            args.push(path.to_string());
        }
        let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let output = self.run(&arg_refs)?;
        Ok(parse_timeline(&output))
    }

    pub fn add_files(&self, paths: &[String]) -> std::result::Result<String, FossilError> {
        self.run(&build_add_args(paths))
    }

    pub fn commit_paths(
        &self,
        paths: &[String],
        message: &str,
    ) -> std::result::Result<String, FossilError> {
        self.run(&build_commit_args(paths, message))
    }

    pub fn ignore_glob(&self, pattern: &str) -> std::result::Result<String, FossilError> {
        let root = self
            .checkout_root
            .as_deref()
            .ok_or(FossilError::NotRepository)?;
        update_ignore_file(root, pattern).map_err(|e| FossilError::CommandFailed(e.to_string()))?;
        Ok(format!("ignored {}", pattern))
    }

    pub fn discard_file(&self, path: &str) -> std::result::Result<String, FossilError> {
        self.run(&["revert", "--", path])
    }

    pub fn remove_files(&self, paths: &[String]) -> std::result::Result<String, FossilError> {
        self.run(&build_rm_args(paths))
    }

    pub fn set_binary_glob(&self, pattern: &str) -> std::result::Result<String, FossilError> {
        self.run(&["settings", "binary-glob", pattern])
    }

    pub fn cat_file(&self, path: &str) -> std::result::Result<String, FossilError> {
        self.run(&["cat", path])
    }

    pub fn ensure_repo(&self) -> std::result::Result<(), FossilError> {
        self.run(&["info"]).map(|_| ())
    }

    fn checkout_root(&self) -> std::result::Result<PathBuf, FossilError> {
        let mut command = Command::new("fossil");
        command.arg("info");
        let output = command
            .output()
            .map_err(|e| FossilError::CommandFailed(e.to_string()))?;
        let info = String::from_utf8_lossy(&output.stdout);
        for line in info.lines() {
            if let Some(root) = line.strip_prefix("local-root:") {
                return Ok(Path::new(root.trim()).to_path_buf());
            }
        }
        Err(FossilError::CommandFailed(
            "unable to determine checkout root".to_string(),
        ))
    }

    fn run(&self, args: &[&str]) -> std::result::Result<String, FossilError> {
        let cmdline = format!("fossil {}", args.join(" "));
        let mut command = Command::new("fossil");
        command.args(args);
        if let Some(root) = self.checkout_root.as_deref() {
            command.current_dir(root);
        }
        let output = command
            .output()
            .map_err(|e| FossilError::CommandFailed(e.to_string()))?;

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        if self.debug_enabled {
            let _ = log_command(&cmdline, output.status.success(), &stdout, &stderr);
        }

        if output.status.success() {
            Ok(stdout)
        } else {
            let lowered = stderr.to_lowercase();
            if lowered.contains("not within an open checkout")
                || lowered.contains("not an open checkout")
                || lowered.contains("use 'fossil open'")
                || lowered.contains("repository filename")
                || lowered.contains("no such file or directory")
            {
                Err(FossilError::NotRepository)
            } else {
                Err(FossilError::CommandFailed(stderr))
            }
        }
    }
}

fn build_add_args(paths: &[String]) -> Vec<&str> {
    let mut args = vec!["add"];
    for path in paths {
        args.push(path.as_str());
    }
    args
}

fn build_commit_args<'a>(paths: &'a [String], message: &'a str) -> Vec<&'a str> {
    let mut args = vec!["commit", "-m", message];
    for path in paths {
        args.push(path.as_str());
    }
    args
}

fn build_rm_args(paths: &[String]) -> Vec<&str> {
    let mut args = vec!["rm"];
    for path in paths {
        args.push(path.as_str());
    }
    args
}

fn update_ignore_file(root: &Path, pattern: &str) -> std::io::Result<()> {
    let dir = root.join(".fossil-settings");
    let path = dir.join("ignore-glob");
    fs::create_dir_all(&dir)?;
    let mut contents = fs::read_to_string(&path).unwrap_or_default();
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return Ok(());
    }
    if !contents.lines().any(|line| line.trim() == pattern) {
        if !contents.ends_with('\n') && !contents.is_empty() {
            contents.push('\n');
        }
        contents.push_str(pattern);
        contents.push('\n');
        fs::write(path, contents)?;
    }
    Ok(())
}

fn log_command(cmd: &str, success: bool, stdout: &str, stderr: &str) -> std::io::Result<()> {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open("fossil-debug.log")?;
    writeln!(file, "=== {} ===", cmd)?;
    writeln!(file, "status: {}", if success { "ok" } else { "err" })?;
    if !stdout.trim().is_empty() {
        writeln!(file, "stdout:\n{}", stdout)?;
    }
    if !stderr.trim().is_empty() {
        writeln!(file, "stderr:\n{}", stderr)?;
    }
    writeln!(file)?;
    Ok(())
}

fn parse_status(out: &str) -> Vec<FileStatus> {
    out.lines()
        .filter_map(|line| {
            line.strip_prefix("EDITED ")
                .map(|path| FileStatus {
                    path: path.trim().to_string(),
                    status: "edited".to_string(),
                })
                .or_else(|| {
                    line.strip_prefix("ADDED   ").map(|path| FileStatus {
                        path: path.trim().to_string(),
                        status: "added".to_string(),
                    })
                })
                .or_else(|| {
                    line.strip_prefix("DELETED ").map(|path| FileStatus {
                        path: path.trim().to_string(),
                        status: "deleted".to_string(),
                    })
                })
                .or_else(|| {
                    line.strip_prefix("MISSING ").map(|path| FileStatus {
                        path: path.trim().to_string(),
                        status: "missing".to_string(),
                    })
                })
                .or_else(|| {
                    line.strip_prefix("CHECKED-OUT ").map(|path| FileStatus {
                        path: path.trim().to_string(),
                        status: "checked-out".to_string(),
                    })
                })
                .or_else(|| {
                    line.strip_prefix("CONFLICT ").map(|path| FileStatus {
                        path: path.trim().to_string(),
                        status: "conflict".to_string(),
                    })
                })
                .or_else(|| {
                    line.strip_prefix("MERGE-CONFLICT ").map(|path| FileStatus {
                        path: path.trim().to_string(),
                        status: "conflict".to_string(),
                    })
                })
        })
        .collect()
}

fn parse_extra(out: &str) -> Vec<FileStatus> {
    out.lines()
        .filter_map(|line| {
            let path = line.trim();
            (!path.is_empty()).then(|| FileStatus {
                path: path.to_string(),
                status: "extra".to_string(),
            })
        })
        .collect()
}

fn parse_tracked(out: &str) -> Vec<FileStatus> {
    out.lines()
        .filter_map(|line| {
            let path = line.trim();
            (!path.is_empty()).then(|| FileStatus {
                path: path.to_string(),
                status: "checked-out".to_string(),
            })
        })
        .collect()
}

fn merge_files(
    mut tracked: Vec<FileStatus>,
    status: Vec<FileStatus>,
    extras: Vec<FileStatus>,
) -> Vec<FileStatus> {
    for file in status.into_iter().chain(extras) {
        if let Some(existing) = tracked.iter_mut().find(|entry| entry.path == file.path) {
            existing.status = file.status;
        } else {
            tracked.push(file);
        }
    }
    tracked.sort_by(
        |a, b| match (a.path.starts_with('.'), b.path.starts_with('.')) {
            (false, true) => std::cmp::Ordering::Less,
            (true, false) => std::cmp::Ordering::Greater,
            _ => a.path.cmp(&b.path),
        },
    );
    tracked
}

fn parse_timeline(out: &str) -> Vec<TimelineEntry> {
    out.lines()
        .filter_map(|line| {
            let parts: Vec<_> = line.splitn(5, '|').collect();
            if parts.len() == 5 {
                Some(TimelineEntry {
                    rid: parts[0].trim().to_string(),
                    user: parts[1].trim().to_string(),
                    date: parts[2].trim().to_string(),
                    message: parts[3].trim().to_string(),
                    tags: parts[4].trim().to_string(),
                })
            } else {
                None
            }
        })
        .collect()
}

pub fn _dummy_result() -> Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_status_and_extras_and_merges() {
        let tracked = parse_tracked("src/lib.rs\nREADME.md\nold.txt\ntracked.txt\n");
        let status = parse_status("EDITED src/lib.rs\nADDED   README.md\nDELETED old.txt\nMISSING gone.txt\nCHECKED-OUT tracked.txt\nIGNORED nope\n");
        let extras = parse_extra("tmp.log\n  \nnotes.txt\n.hidden\n");
        let merged = merge_files(tracked, status, extras);

        assert_eq!(merged.len(), 8);
        assert_eq!(merged.first().map(|f| f.path.as_str()), Some("README.md"));
        assert_eq!(merged.last().map(|f| f.path.as_str()), Some(".hidden"));
        assert!(merged
            .iter()
            .any(|f| f.path == "src/lib.rs" && f.status == "edited"));
        assert!(merged
            .iter()
            .any(|f| f.path == "README.md" && f.status == "added"));
        assert!(merged
            .iter()
            .any(|f| f.path == "old.txt" && f.status == "deleted"));
        assert!(merged
            .iter()
            .any(|f| f.path == "gone.txt" && f.status == "missing"));
        assert!(merged
            .iter()
            .any(|f| f.path == "tracked.txt" && f.status == "checked-out"));
        assert!(merged
            .iter()
            .any(|f| f.path == "tmp.log" && f.status == "extra"));
        assert!(merged
            .iter()
            .any(|f| f.path == "notes.txt" && f.status == "extra"));
    }

    #[test]
    fn parses_timeline_format() {
        let entries = parse_timeline(
            "abc123|Alice|2026-06-04 10:00|Fix bug|sym-v0.7.1\nzzz999|Bob|2026-06-04 11:00|Refactor|trunk\n",
        );
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].rid, "abc123");
        assert_eq!(entries[0].user, "Alice");
        assert_eq!(entries[0].date, "2026-06-04 10:00");
        assert_eq!(entries[0].message, "Fix bug");
        assert_eq!(entries[0].tags, "sym-v0.7.1");
    }

    #[test]
    fn builds_commit_arguments_for_selected_paths() {
        let paths = vec!["a.txt".to_string(), "b.txt".to_string()];
        let args = build_commit_args(&paths, "hello");
        assert_eq!(args, vec!["commit", "-m", "hello", "a.txt", "b.txt"]);
    }

    #[test]
    fn builds_add_arguments_for_selected_paths() {
        let paths = vec!["extra.txt".to_string()];
        let args = build_add_args(&paths);
        assert_eq!(args, vec!["add", "extra.txt"]);
    }

    #[test]
    fn builds_rm_arguments_for_missing_paths() {
        let paths = vec!["missing.txt".to_string()];
        let args = build_rm_args(&paths);
        assert_eq!(args, vec!["rm", "missing.txt"]);
    }

    #[test]
    fn parses_conflict_status_entries() {
        let status = parse_status("CONFLICT file.txt\nMERGE-CONFLICT other.txt\n");
        assert_eq!(status.len(), 2);
        assert!(status.iter().all(|f| f.status == "conflict"));
    }

    #[test]
    fn updates_ignore_file_contents() {
        let dir = std::env::temp_dir().join(format!("lazyfossil-test-{}", std::process::id()));
        let settings = dir.join(".fossil-settings");
        std::fs::create_dir_all(&settings).unwrap();
        let ignore = settings.join("ignore-glob");
        std::fs::write(&ignore, "*.swp\n").unwrap();

        let old = std::env::current_dir().unwrap();
        std::env::set_current_dir(&dir).unwrap();
        update_ignore_file(&dir, "notes.txt").unwrap();
        std::env::set_current_dir(old).unwrap();

        let contents = std::fs::read_to_string(ignore).unwrap();
        assert!(contents.contains("*.swp"));
        assert!(contents.contains("notes.txt"));
    }
}