summaryrefslogtreecommitdiff
path: root/server/common/src/git.rs
blob: e396d8a9331a034135c25c7735835698461a2399 (plain)
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
#![allow(dead_code)]

use futures::future::TryFutureExt;
use pathdiff::diff_paths;
use std::collections::HashMap;
use std::fmt;
use std::io::{self, Cursor, Read};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tokio::fs;
use tokio::process::Command;
use tokio::sync::{RwLock, Semaphore};

use crate::fs_utils;

#[derive(Debug)]
pub struct Error {
    pub message: String,
}

impl Error {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

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

pub const EMPTY: &str = "0000000000000000000000000000000000000000";

struct RepoData {
    // Only one fetch at a time, and they should be in queue
    fetch_semaphore: Semaphore,
    config_cache: HashMap<String, String>,
}

pub struct Repository {
    path: PathBuf,
    bare: bool,

    remote: Option<String>,
    project_id: Option<String>,
    socket: Option<PathBuf>,
    githook: Option<PathBuf>,
    ssh_config: Option<PathBuf>,

    // Lock for any repo task, 90% of all tasks are readers but there are some writers
    // where nothing else may be done.
    lock: RwLock<RepoData>,
}

#[allow(dead_code)]
pub struct User {
    pub name: String,
    pub email: String,
    // Part before '@' in email
    pub username: String,
}

#[derive(Debug, PartialEq)]
pub enum ObjectType {
    BLOB,
    COMMIT,
    TREE,
}

#[derive(Debug, PartialEq)]
pub struct TreeEntry {
    pub object_type: ObjectType,
    pub object_name: String,
    pub path: String,
}

pub struct GitFile {
    cursor: Cursor<Vec<u8>>,
}

impl GitFile {
    pub fn new(data: Vec<u8>) -> Self {
        GitFile {
            cursor: Cursor::new(data),
        }
    }
}

impl Read for GitFile {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.cursor.read(buf)
    }
}

fn io_err(action: &str, e: std::io::Error) -> Error {
    Error::new(format!("{action}: {e}"))
}

fn parse_user(output: String) -> User {
    let mut lines = output.split_terminator('\0');
    let name = lines.next().unwrap_or("").to_string();
    let username = lines.next().unwrap_or("").to_string();
    let email = lines.next().unwrap_or("").to_string();
    User {
        name,
        email,
        username,
    }
}

fn parse_tree_entries(output: String) -> Vec<TreeEntry> {
    let mut ret = Vec::new();
    for line in output.split_terminator('\0') {
        let mut parts = line.split_terminator('\t');
        let mut parts2 = parts.next().unwrap_or("").split_terminator(' ');
        parts2.next(); // object mode
        let object_type = match parts2.next() {
            Some(value) => match value {
                "blob" => ObjectType::BLOB,
                "commit" => ObjectType::COMMIT,
                "tree" => ObjectType::TREE,
                _ => continue,
            },
            None => continue,
        };
        if let Some(object_name) = parts2.next() {
            if let Some(path) = parts.next() {
                ret.push(TreeEntry {
                    object_type,
                    object_name: object_name.to_string(),
                    path: path.to_string(),
                });
            }
        }
    }
    ret
}

fn branch_eq(a: impl AsRef<str>, b: impl AsRef<str>) -> bool {
    let a = a.as_ref();
    let b = b.as_ref();
    if a.starts_with("refs/heads/") {
        if b.starts_with("refs/heads/") {
            return a[11..] == b[11..];
        }
        return a == format!("refs/heads/{b}");
    } else {
        if b.starts_with("refs/heads/") {
            return format!("refs/heads/{a}") == b;
        }
        return a == b;
    }
}

impl RepoData {
    fn new() -> Self {
        Self {
            fetch_semaphore: Semaphore::new(1),
            config_cache: HashMap::new(),
        }
    }

    async fn fetch(&self, repo: &Repository, branch: String) -> Result<String, Error> {
        if repo.remote.is_none() {
            return Err(Error::new("No remote set"));
        }

        let _permit = self.fetch_semaphore.acquire().await;

        let mut cmd = self.git_cmd(repo);
        cmd.arg("fetch");
        // Use an atomic transaction to update local refs.
        cmd.arg("--atomic");
        // Print the output to standard output in an easy-to-parse format for scripts.
        cmd.arg("--porcelain");
        // This option disables this automatic tag following.
        cmd.arg("--no-tags");
        // Write out refs even if they didn't change
        cmd.arg("--verbose");
        cmd.arg("origin");
        // <+ force update><remote branch>:<local branch>
        cmd.arg(format!("+{branch}:{branch}"));

        let output = self.output(&mut cmd).await?;

        // git fetch porcelain format:
        // <flag> <old-object-id> <new-object-id> <local-reference>
        for line in output.lines() {
            let mut parts = line.split(' ');
            parts.next(); // flag
            parts.next(); // old-object-id
            if let Some(new_object_id) = parts.next() {
                let local_reference = parts.collect::<Vec<&str>>().join(" ");
                if branch_eq(local_reference, &branch) {
                    return Ok(new_object_id.to_string());
                }
            }
        }

        assert!(false);
        Err(Error::new("Fetch succeeded but branch not found"))
    }

    async fn init(&mut self, repo: &Repository) -> Result<(), Error> {
        fs_utils::create_dir_allow_existing(repo.path())
            .map_err(|e| Error::new(format!("{e}")))
            .await?;

        let mut cmd = self.git_cmd(repo);
        cmd.arg("init");
        if repo.is_bare() {
            cmd.arg("--bare");
        }

        self.run(&mut cmd).await?;

        Ok(())
    }

    async fn sync_config(&mut self, repo: &Repository) -> Result<(), Error> {
        self.config_fill_cache(repo).await?;

        if let Some(remote) = repo.remote() {
            self.config_set(repo, "remote.origin.url", remote).await?;
        }
        if let Some(socket) = repo.socket() {
            let relative = diff_paths(socket, repo.path()).unwrap();
            self.config_set(repo, "eyeballs.socket", relative.to_str().unwrap())
                .await?;
        }
        if let Some(ssh_config) = repo.ssh_config() {
            let relative = diff_paths(ssh_config, repo.path()).unwrap();
            self.config_set(
                repo,
                "core.sshcommand",
                format!("ssh -F {}", relative.to_str().unwrap()).as_str(),
            )
            .await?;
        }

        // Handled by pre-receive hook, allow fast forwards for reviews that expect it.
        self.config_set(repo, "receive.denyNonFastForwards", "false")
            .await?;
        // Handled by pre-receive hook, allow deletes for non-review branches
        self.config_set(repo, "receive.denyDeletes", "false")
            .await?;

        Ok(())
    }

    async fn sync_hooks(&mut self, repo: &Repository) -> Result<(), Error> {
        let hook = match repo.githook() {
            Some(path) => PathBuf::from(path),
            None => {
                let server_exe =
                    std::env::current_exe().map_err(|e| io_err("unable to get current exe", e))?;
                server_exe.parent().unwrap().join("eyeballs-githook")
            }
        };

        let hooks = if repo.is_bare() {
            repo.path().join("hooks")
        } else {
            repo.path().join(".git/hooks")
        };

        fs_utils::create_dir_allow_existing(&hooks)
            .map_err(|e| io_err("unable to create hooks", e))
            .await?;

        let pre_receive = hooks.join("pre-receive");
        let update = hooks.join("update");
        let post_receive = hooks.join("post-receive");

        fs_utils::remove_file_allow_not_found(update)
            .map_err(|e| io_err("unable to remove update hook", e))
            .await?;

        // Must be hard links, symbolic links doesn't allow the hook
        // the lookup how it's called using std::env::current_exe().
        fs_utils::remove_file_allow_not_found(&pre_receive)
            .map_err(|e| io_err("unable to remove pre-receive hook", e))
            .await?;
        fs::hard_link(hook.as_path(), pre_receive)
            .map_err(|e| io_err("unable to link pre-receive hook", e))
            .await?;
        fs_utils::remove_file_allow_not_found(&post_receive)
            .map_err(|e| io_err("unable to remove post-receive hook", e))
            .await?;
        fs::hard_link(hook.as_path(), post_receive)
            .map_err(|e| io_err("unable to link post-receive hook", e))
            .await
    }

    fn canonical_config_name(name: &str) -> String {
        let mut ret = String::with_capacity(name.len());
        let mut iter = name.splitn(3, '.');
        ret.push_str(iter.next().unwrap());
        ret.as_mut_str().make_ascii_lowercase();
        if let Some(subsection) = iter.next() {
            ret.push('.');
            let offset;
            if let Some(value) = iter.next() {
                ret.push_str(subsection);
                ret.push('.');
                offset = ret.len();
                ret.push_str(value);
            } else {
                offset = ret.len();
                ret.push_str(subsection);
            }
            ret.as_mut_str()
                .get_mut(offset..)
                .unwrap()
                .make_ascii_lowercase();
        }
        ret
    }

    async fn config_get(&self, repo: &Repository, name: &str) -> Result<String, Error> {
        let name = Self::canonical_config_name(name);
        if let Some(value) = self.config_cache.get(&name) {
            return Ok(value.clone());
        }

        // Note, want to keep this method non-mutable so we can't update the cache here, should be
        // edge case to end up here anyway.

        let mut cmd = self.git_cmd(repo);
        cmd.arg("config")
            .arg("get")
            // End value with the null character and use newline as delimiter between key and value
            .arg("--null")
            .arg("--default=")
            .arg(name);
        let data = self.output(&mut cmd).await?;
        match data.as_str().split_once('\0') {
            Some((value, _)) => Ok(value.to_string()),
            None => Err(Error::new("Invalid output from git config get")),
        }
    }

    async fn config_fill_cache(&mut self, repo: &Repository) -> Result<(), Error> {
        self.config_cache.clear();

        let mut cmd = self.git_cmd(repo);
        cmd.arg("config")
            .arg("list")
            // read only from the repository .git/config,
            .arg("--local")
            // End value with the null character and use newline as delimiter between key and value
            .arg("--null");
        let data = self.output(&mut cmd).await?;
        for key_value in data.split_terminator('\0') {
            match key_value.split_once('\n') {
                Some((key, value)) => {
                    self.config_cache.insert(key.to_string(), value.to_string());
                }
                None => return Err(Error::new("Invalid output from git config list")),
            };
        }
        Ok(())
    }

    async fn config_set(
        &mut self,
        repo: &Repository,
        name: &str,
        value: &str,
    ) -> Result<(), Error> {
        let name = Self::canonical_config_name(name);
        if let Some(cached_value) = self.config_cache.get(&name) {
            if cached_value == value {
                return Ok(());
            }
        }

        let mut cmd = self.git_cmd(repo);
        cmd.arg("config").arg("set").arg(&name).arg(value);
        self.run(&mut cmd).await?;

        self.config_cache.insert(name, value.to_string());

        Ok(())
    }

    async fn is_ancestor(
        &self,
        repo: &Repository,
        ancestor: &str,
        commit: &str,
    ) -> Result<bool, Error> {
        let mut cmd = self.git_cmd(repo);
        cmd.arg("merge-base")
            .arg("--is-ancestor")
            .arg(ancestor)
            .arg(commit);
        self.check(&mut cmd).await
    }

    async fn is_equal_content(
        &self,
        repo: &Repository,
        commit1: &str,
        commit2: &str,
    ) -> Result<bool, Error> {
        let mut cmd = self.git_cmd(repo);
        cmd.arg("diff")
            .arg("--quiet")
            .arg("--no-renames")
            .arg(commit1)
            .arg(commit2);
        self.check(&mut cmd).await
    }

    async fn get_author(&self, repo: &Repository, commit: &str) -> Result<User, Error> {
        self.get_log_format(repo, commit, "%an%x00%al%x00%ae")
            .map_ok(parse_user)
            .await
    }

    async fn get_commiter(&self, repo: &Repository, commit: &str) -> Result<User, Error> {
        self.get_log_format(repo, commit, "%cn%x00%cl%x00%ce")
            .map_ok(parse_user)
            .await
    }

    async fn delete_branch(&self, repo: &Repository, branch: &str) -> Result<(), Error> {
        let mut cmd = self.git_cmd(repo);
        cmd.arg("branch").arg("--delete").arg("--force").arg(branch);
        self.run(&mut cmd).await
    }

    async fn ls_tree(
        &self,
        repo: &Repository,
        commit: &str,
        recursive: bool,
    ) -> Result<Vec<TreeEntry>, Error> {
        let mut cmd = self.git_cmd(repo);
        cmd.arg("ls-tree").arg("-z");
        if recursive {
            cmd.arg("-r");
        }
        cmd.arg(commit);
        self.output(&mut cmd).map_ok(parse_tree_entries).await
    }

    async fn cat_file(
        &self,
        repo: &Repository,
        object_type: ObjectType,
        object_name: &str,
    ) -> Result<GitFile, Error> {
        let mut cmd = self.git_cmd(repo);
        cmd.arg("cat-file")
            .arg(match object_type {
                ObjectType::BLOB => "blob",
                ObjectType::COMMIT => "commit",
                ObjectType::TREE => "tree",
            })
            .arg(object_name);
        self.raw_output(&mut cmd).map_ok(GitFile::new).await
    }

    async fn get_log_format(
        &self,
        repo: &Repository,
        commit: &str,
        format: &str,
    ) -> Result<String, Error> {
        let mut cmd = self.git_cmd(repo);
        cmd.arg("log")
            .arg("-1")
            .arg("--no-decorate")
            .arg("--no-mailmap")
            .arg(format!("--pretty=format:{format}"))
            .arg(commit);
        self.output(&mut cmd).await
    }

    fn git_cmd(&self, repo: &Repository) -> Command {
        let mut cmd = Command::new("git");
        // Run as if git was started in <path> instead of the current working directory.
        cmd.arg("-C").arg(repo.path().to_str().unwrap());
        // Disable all advice hints from being printed.
        cmd.arg("--no-advice");
        // Do not pipe Git output into a pager.
        cmd.arg("--no-pager");
        // Do not perform optional operations that require locks.
        cmd.arg("--no-optional-locks");

        cmd
    }

    async fn run(&self, cmd: &mut Command) -> Result<(), Error> {
        cmd.stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped());

        let child = cmd
            .spawn()
            .map_err(|e| Error::new(format!("git command failed to start: {e}")))?;

        let output = child
            .wait_with_output()
            .map_err(|e| Error::new(format!("git command failed to execute: {e}")))
            .await?;

        if output.status.success() {
            Ok(())
        } else {
            Err(Error::new(format!(
                "git command failed with exitcode: {}\n{:?}\n{}",
                output.status,
                cmd.as_std().get_args(),
                std::str::from_utf8(output.stderr.as_slice()).unwrap_or(""),
            )))
        }
    }

    async fn check(&self, cmd: &mut Command) -> Result<bool, Error> {
        cmd.stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped());

        let child = cmd
            .spawn()
            .map_err(|e| Error::new(format!("git command failed to start: {e}")))?;

        let output = child
            .wait_with_output()
            .map_err(|e| Error::new(format!("git command failed to execute: {e}")))
            .await?;

        if output.status.success() {
            Ok(true)
        } else {
            match output.status.code() {
                Some(1) => Ok(false),
                _ => Err(Error::new(format!(
                    "git command failed with exitcode: {}\n{:?}\n{}",
                    output.status,
                    cmd.as_std().get_args(),
                    std::str::from_utf8(output.stderr.as_slice()).unwrap_or(""),
                ))),
            }
        }
    }

    async fn output(&self, cmd: &mut Command) -> Result<String, Error> {
        match self.raw_output(cmd).await {
            Ok(bytes) => String::from_utf8(bytes)
                .map_err(|e| Error::new(format!("git command had invalid output: {e}"))),
            Err(e) => Err(e),
        }
    }

    async fn raw_output(&self, cmd: &mut Command) -> Result<Vec<u8>, Error> {
        cmd.stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let child = cmd
            .spawn()
            .map_err(|e| Error::new(format!("git command failed to start: {e}")))?;

        let output = child
            .wait_with_output()
            .map_err(|e| Error::new(format!("git command failed to execute: {e}")))
            .await?;

        if output.status.success() {
            Ok(output.stdout)
        } else {
            Err(Error::new(format!(
                "git command failed with exitcode: {}\n{:?}\n{}",
                output.status,
                cmd.as_std().get_args(),
                std::str::from_utf8(output.stderr.as_slice()).unwrap_or(""),
            )))
        }
    }
}

#[allow(dead_code)]
impl Repository {
    pub fn new(
        path: impl Into<PathBuf>,
        bare: bool,
        remote: Option<impl Into<String>>,
        project_id: Option<impl Into<String>>,
        githook: Option<impl Into<PathBuf>>,
        ssh_config: Option<impl Into<PathBuf>>,
    ) -> Self {
        let path = path.into();
        let project_id = project_id.map(|x| x.into());
        let githook = githook.map(|x| x.into());
        let ssh_config = ssh_config.map(|x| x.into());
        let socket: Option<PathBuf>;
        if let Some(project_id) = &project_id {
            socket = Some(
                path.parent()
                    .unwrap()
                    .join(format!("{}.socket", project_id)),
            );
        } else {
            socket = None;
        }

        Self {
            remote: remote.map(|x| x.into()),
            project_id,
            path,
            socket,
            githook,
            ssh_config,
            bare,
            lock: RwLock::new(RepoData::new()),
        }
    }

    pub fn remote(&self) -> Option<&str> {
        self.remote.as_deref()
    }

    pub fn project_id(&self) -> Option<&str> {
        self.project_id.as_deref()
    }

    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

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

    fn githook(&self) -> Option<&Path> {
        self.githook.as_deref()
    }

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

    pub fn is_bare(&self) -> bool {
        self.bare
    }

    pub async fn setup(&self) -> Result<(), Error> {
        let mut data = self.lock.write().await;

        data.init(self).await?;
        data.sync_config(self).await?;
        if self.socket.is_some() {
            data.sync_hooks(self).await?;
        }

        Ok(())
    }

    pub async fn fetch(&self, branch: impl Into<String>) -> Result<String, Error> {
        let branch = branch.into();
        let data = self.lock.read().await;

        data.fetch(self, branch).await
    }

    pub async fn config_get(&self, name: impl Into<String>) -> Result<String, Error> {
        let name = name.into();
        let data = self.lock.read().await;

        data.config_get(self, name.as_str()).await
    }

    pub async fn is_ancestor(
        &self,
        ancestor: impl Into<String>,
        commit: impl Into<String>,
    ) -> Result<bool, Error> {
        let ancestor = ancestor.into();
        let commit = commit.into();

        let data = self.lock.read().await;

        data.is_ancestor(self, ancestor.as_str(), commit.as_str())
            .await
    }

    pub async fn is_equal_content(
        &self,
        commit1: impl Into<String>,
        commit2: impl Into<String>,
    ) -> Result<bool, Error> {
        let commit1 = commit1.into();
        let commit2 = commit2.into();
        let data = self.lock.read().await;

        data.is_equal_content(self, commit1.as_str(), commit2.as_str())
            .await
    }

    pub async fn get_author(&self, commit: impl Into<String>) -> Result<User, Error> {
        let commit = commit.into();
        let data = self.lock.read().await;

        data.get_author(self, commit.as_str()).await
    }

    pub async fn get_commiter(&self, commit: impl Into<String>) -> Result<User, Error> {
        let commit = commit.into();
        let data = self.lock.read().await;

        data.get_commiter(self, commit.as_str()).await
    }

    pub async fn delete_branch(&self, branch: impl Into<String>) -> Result<(), Error> {
        let branch = branch.into();
        let data = self.lock.read().await;

        data.delete_branch(self, branch.as_str()).await
    }

    pub async fn ls_tree(
        &self,
        commit: impl Into<String>,
        recursive: bool,
    ) -> Result<Vec<TreeEntry>, Error> {
        let commit = commit.into();
        let data = self.lock.read().await;

        data.ls_tree(self, commit.as_str(), recursive).await
    }

    pub async fn cat_file(
        &self,
        object_type: ObjectType,
        object_name: impl Into<String>,
    ) -> Result<GitFile, Error> {
        let object_name = object_name.into();
        let data = self.lock.read().await;

        data.cat_file(self, object_type, object_name.as_str()).await
    }
}