eugene 0.8.3

Careful with That Lock, Eugene
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
use log::trace;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::error::{ContextualError, ContextualResult, InnerError};

#[derive(Debug, Eq, PartialEq, Clone)]
pub enum GitMode {
    DiffWith(String),
    Disabled,
}

impl From<Option<String>> for GitMode {
    fn from(value: Option<String>) -> Self {
        match value {
            Some(v) => GitMode::DiffWith(v),
            None => GitMode::Disabled,
        }
    }
}

fn git_is_on_path() -> crate::Result<()> {
    Command::new("git")
        .arg("--version")
        .output()
        .map_err(|e| {
            InnerError::NoGitExecutableError
                .with_context(format!("Failed to execute `git --version`: {e}"))
        })
        .map(|_| ())
}

fn git_ref_exists<P: AsRef<Path>>(gitref: &str, cwd: P) -> crate::Result<()> {
    Command::new("git")
        .arg("rev-parse")
        .arg("--verify")
        .arg(gitref)
        .current_dir(cwd.as_ref())
        .output()
        .map_err(|e| {
            InnerError::GitError.with_context(format!(
                "Failed to execute `git rev-parse --abbrev-ref {gitref}`: {e}"
            ))
        })
        .and_then(|o| {
            if o.status.success() {
                Ok(())
            } else {
                Err(InnerError::GitError.with_context(format!("Git ref {gitref} not found")))
            }
        })
}

/// Find the nearest directory containing the given path, useful for setting cwd for git
fn nearest_directory<P: AsRef<Path>>(path: P) -> crate::Result<PathBuf> {
    let path = path.as_ref();
    let p = Path::new(path);
    if p.is_file() {
        // p must have a parent, so we can unwrap it
        Ok(p.parent().unwrap().into())
    } else if p.is_dir() {
        Ok(p.into())
    } else if p.is_symlink() {
        // For now, symlink is not supported
        Err(InnerError::NotFound.with_context(format!(
            "{path:?} is a symlink which is unsupported by eugene::git"
        )))
    } else {
        Err(InnerError::NotFound.with_context(format!("{path:?} does not exist")))
    }
}

fn git_status<P: AsRef<Path>>(cwd: P) -> crate::Result<String> {
    let cwd = cwd.as_ref();
    Command::new("git")
        .arg("status")
        .arg("--porcelain")
        .current_dir(cwd)
        .output()
        .map_err(|e| {
            InnerError::GitError.with_context(format!(
                "Failed to execute `git status --porcelain` in {cwd:?}: {e}"
            ))
        })
        .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
}

/// Discover unstaged files in the path, which may be either a file or directory
///
/// Fails if the path does not exist, or isn't in a git repository
fn unstaged_children<P: AsRef<Path>>(path: P) -> crate::Result<Vec<String>> {
    let path = path.as_ref();
    trace!("Checking if {path:?} has unstaged");
    let cwd = nearest_directory(path)?;
    // p exists
    if path.is_file() {
        // cwd is the parent and if `git status --porcelain` inside cwd contains `?? p`
        // it is unstaged and will be the only output. We can unwrap here because `p` is a file
        let file_name = path.file_name().unwrap().to_str().ok_or_else(|| {
            InnerError::InvalidPath.with_context(format!("{path:?} contains non utf-8 characters"))
        })?;
        let status = git_status(&cwd).with_context(format!("Check if {path:?} is unstaged"))?;
        trace!("git status --porcelain in {cwd:?} is {status}");
        let look_for = format!("?? {file_name}");
        if status.lines().any(|l| l.starts_with(&look_for)) {
            let as_string = path.to_str().ok_or_else(|| {
                InnerError::InvalidPath
                    .with_context(format!("{path:?} contains non utf-8 characters"))
            })?;
            Ok(vec![as_string.to_string()])
        } else {
            Ok(vec![])
        }
    } else {
        // cwd is the directory itself. We will use it as the working dir and join all the
        // paths in the output to cwd to produce results, using only the lines that start with `??`
        let status =
            git_status(&cwd).with_context(format!("Check if {path:?} contains unstaged"))?;
        trace!("git status --porcelain in {cwd:?} is {status}");
        Ok(status
            .lines()
            .filter(|l| l.starts_with("??"))
            .map(|l| {
                let file_name = l.trim_start_matches("?? ").trim();
                cwd.join(file_name).to_str().unwrap().to_string()
            })
            .collect())
    }
}

fn git_diff_name_only(cwd: &Path, gitref: &str) -> Command {
    let mut cmd = Command::new("git");
    cmd.arg("diff")
        .arg("--name-only")
        .arg("--relative")
        .arg(gitref)
        .current_dir(cwd);
    cmd
}

fn diff_files_since_ref<P: AsRef<Path> + Debug>(
    path: P,
    gitref: &str,
) -> crate::Result<Vec<String>> {
    let path = path.as_ref();
    let cwd = nearest_directory(path)?;
    git_ref_exists(gitref, &cwd)?;
    let mut cmd = git_diff_name_only(&cwd, gitref);
    if path.is_file() {
        // cwd is above; if `git diff --name-only` in cwd name of `path`, it changed
        let output = cmd.output().with_context(format!(
            "Failed to execute `git diff --name-only {gitref}` in {cwd:?}"
        ))?;
        let string_ouput = String::from_utf8_lossy(&output.stdout);
        trace!("git diff --name-only {gitref} in {cwd:?} is {string_ouput}");
        // We can unwrap file_name here because `p` is a file
        let file_name = path.file_name().unwrap().to_str().ok_or_else(|| {
            InnerError::InvalidPath.with_context(format!("{path:?} contains non utf-8 characters"))
        })?;
        let as_string = path.to_str().ok_or_else(|| {
            InnerError::InvalidPath.with_context(format!("{path:?} contains non utf-8 characters"))
        })?;
        if string_ouput.lines().any(|l| l == file_name) {
            Ok(vec![as_string.to_string()])
        } else {
            Ok(vec![])
        }
    } else {
        // cwd is the directory itself. We will use it as the working dir and join all the
        // paths in the output to cwd to produce results
        let output = cmd.output().with_context(format!(
            "Failed to execute `git diff --name-only {gitref}` in {cwd:?}"
        ))?;
        let string_output = String::from_utf8_lossy(&output.stdout);
        trace!("git diff --name-only {gitref} in {cwd:?} is {string_output}");
        let r: crate::Result<Vec<_>> = string_output
            .lines()
            .map(|l| {
                let file_name = l.trim();
                Ok(cwd
                    .join(file_name)
                    .to_str()
                    .ok_or_else(|| {
                        InnerError::InvalidPath
                            .with_context(format!("{path:?} contains invalid utf-8 characters"))
                    })?
                    .to_string())
            })
            .collect();
        Ok(r?)
    }
}

#[derive(Debug)]
pub struct AllowList {
    paths: Vec<String>,
}

#[derive(Debug)]
pub enum GitFilter {
    Ignore,
    OneOf(AllowList),
}

impl GitFilter {
    pub fn new<P: AsRef<Path> + Debug>(path: P, mode: GitMode) -> crate::Result<GitFilter> {
        match mode {
            GitMode::Disabled => Ok(GitFilter::Ignore),
            GitMode::DiffWith(refname) => {
                git_is_on_path()?;
                let path = path.as_ref();
                let mut diff = diff_files_since_ref(path, &refname)?;
                diff.extend(unstaged_children(path)?);
                Ok(GitFilter::OneOf(AllowList { paths: diff }))
            }
        }
    }

    pub fn empty(mode: GitMode) -> GitFilter {
        match mode {
            GitMode::Disabled => GitFilter::Ignore,
            GitMode::DiffWith(_) => GitFilter::OneOf(AllowList { paths: vec![] }),
        }
    }

    pub fn allows<S: AsRef<str>>(&self, path: S) -> bool {
        let path = path.as_ref();
        match self {
            GitFilter::Ignore => true,
            GitFilter::OneOf(allow_list) => allow_list.paths.iter().any(|p| p == path),
        }
    }

    pub fn extend(&mut self, other: GitFilter) {
        if let (GitFilter::OneOf(mine), GitFilter::OneOf(theirs)) = (self, other) {
            mine.paths.extend(theirs.paths);
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::utils::FsyncDir;
    use pretty_assertions::assert_eq;
    use std::fs;
    use std::thread::sleep;
    use std::time::Duration;
    use tempfile::{Builder, TempDir};

    use super::*;

    struct RestoreContext {
        restore: Option<Box<dyn FnOnce()>>,
    }

    impl RestoreContext {
        fn new<F: FnOnce() + 'static>(restore: F) -> Self {
            Self {
                restore: Some(Box::new(restore)),
            }
        }
    }

    impl Drop for RestoreContext {
        fn drop(&mut self) {
            let inner = self.restore.take();
            if let Some(restore) = inner {
                restore();
            }
        }
    }

    fn set_path(new: &str) -> RestoreContext {
        let old = std::env::var("PATH").unwrap();
        std::env::set_var("PATH", new);
        RestoreContext::new(move || std::env::set_var("PATH", old))
    }

    fn configure_git(path: &Path) {
        fn inner(path: &Path) -> std::io::Result<()> {
            Command::new("git")
                .arg("init")
                .arg("-b")
                .arg("main")
                .current_dir(path)
                .output()?;
            Command::new("git")
                .arg("config")
                .arg("user.email")
                .arg("ci@example.com")
                .current_dir(path)
                .output()?;
            Command::new("git")
                .arg("config")
                .arg("user.name")
                .arg("ci@example.com")
                .current_dir(path)
                .output()?;
            path.fsync()?;
            Ok(())
        }
        let mut attempt = 0;
        loop {
            match inner(path) {
                Ok(_) => break,
                Err(e) => {
                    attempt += 1;
                    sleep(Duration::from_millis(100));
                    if attempt > 5 {
                        panic!("Failed to configure git in {path:?} after 3 attempts: {e}");
                    }
                }
            }
        }
    }

    #[test]
    fn test_nearest_dir() {
        let tmp = TempDir::new().unwrap();
        let fp = tmp.path().join("foo");
        fs::write(&fp, "").unwrap();
        assert_eq!(nearest_directory(fp).unwrap(), tmp.path());
        assert_eq!(nearest_directory(tmp.path()).unwrap(), tmp.path());
        let subdir = tmp.path().join("subdir");
        std::fs::create_dir(&subdir).unwrap();
        assert_eq!(&nearest_directory(&subdir).unwrap(), &subdir);
        let notexists = tmp.path().join("notexists");
        assert!(nearest_directory(notexists).is_err());
    }

    #[test]
    fn test_is_git_in_path() {
        assert!(git_is_on_path().is_ok());
        let _tmp = set_path("");
        assert!(git_is_on_path().is_err());
    }

    #[test]
    fn test_unstaged() {
        let tmp = Builder::new()
            .prefix("eugene-test-unstaged")
            .tempdir()
            .unwrap();
        tmp.fsync().unwrap();
        let p = tmp.path();
        configure_git(p);
        assert!(unstaged_children(p.to_str().unwrap()).unwrap().is_empty());
        assert!(unstaged_children(p.join("foo").to_str().unwrap()).is_err());
        let fp = p.join("foo");
        fs::write(&fp, "hei").unwrap();
        assert_eq!(
            unstaged_children(fp.to_str().unwrap()).unwrap(),
            vec![fp.to_str().unwrap()]
        );
    }

    #[test]
    fn test_gitref_exists() {
        let tmp = Builder::new()
            .prefix("eugene-test-gitref-exists")
            .tempdir()
            .unwrap();
        tmp.fsync().unwrap();
        let p = tmp.path();

        configure_git(p);
        assert!(git_ref_exists("main", p).is_err());
        let fp = p.join("foo");
        std::fs::write(fp, "hei").unwrap();
        let o = Command::new("git")
            .arg("add")
            .arg("foo")
            .current_dir(p)
            .output()
            .unwrap();
        eprintln!("{o:?}");
        let o = Command::new("git")
            .arg("commit")
            .arg("-m")
            .arg("initial")
            .current_dir(p)
            .output()
            .unwrap();
        eprintln!("{o:?}");
        assert!(git_ref_exists("main", p).is_ok());
        assert!(git_ref_exists("nonono", p).is_err());
    }

    #[test]
    fn test_diff() {
        let tmp = Builder::new().prefix("eugene-test-diff").tempdir().unwrap();
        tmp.fsync().unwrap();
        let p = tmp.path();
        configure_git(p);
        let fp = p.join("foo");
        fs::write(&fp, "hei").unwrap();
        Command::new("git")
            .arg("add")
            .arg("foo")
            .current_dir(p)
            .output()
            .unwrap();
        Command::new("git")
            .arg("commit")
            .arg("-m")
            .arg("initial")
            .current_dir(p)
            .output()
            .unwrap();
        assert!(diff_files_since_ref(&fp, "main").unwrap().is_empty(),);
        Command::new("git")
            .arg("checkout")
            .arg("-b")
            .arg("newbranch")
            .current_dir(p)
            .output()
            .unwrap();
        let fp2 = p.join("bar");
        std::fs::write(&fp2, "hei").unwrap();
        Command::new("git")
            .arg("add")
            .arg("bar")
            .current_dir(p)
            .output()
            .unwrap();
        Command::new("git")
            .arg("commit")
            .arg("-m")
            .arg("new file")
            .current_dir(p)
            .output()
            .unwrap();
        // The new file is contained in the diff with main
        assert_eq!(
            diff_files_since_ref(&fp2, "main").unwrap(),
            vec![fp2.to_str().unwrap()]
        );
        assert_eq!(
            diff_files_since_ref(p, "main").unwrap(),
            vec![fp2.to_str().unwrap()]
        );

        // Change fp
    }
}