summaryrefslogtreecommitdiff
path: root/lib/libgfold/src/repository_view.rs
blob: 64cf3f3da42e0f687b358c5f65ed6177ff464703 (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
use git2::{ErrorCode, Reference, Remote, Repository, StatusOptions};
use log::{debug, error, trace};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use submodule_view::SubmoduleView;
use thiserror::Error;

use crate::status::Status;

mod submodule_view;

#[derive(Error, Debug)]
pub enum RepositoryViewError {
    #[error("received None (Option<&OsStr>) for file name: {0}")]
    FileNameNotFound(PathBuf),
    #[error("could not convert file name (&OsStr) to &str: {0}")]
    FileNameToStrConversionFailure(PathBuf),
    #[error("full shorthand for Git reference is invalid UTF-8")]
    GitReferenceShorthandInvalid,
    #[error("could not convert path (Path) to &str: {0}")]
    PathToStrConversionFailure(PathBuf),
}

/// A collection of results for a Git repository at a given path.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct RepositoryView {
    /// The directory name of the Git repository.
    pub name: String,
    /// The name of the current, open branch.
    pub branch: String,
    /// The [`Status`] of the working tree.
    pub status: Status,

    /// The parent directory of the `path` field. The value will be `None` if a parent is not found.
    pub parent: Option<String>,
    /// The remote origin URL. The value will be `None` if the URL cannot be found.
    pub url: Option<String>,

    pub email: Option<String>,
    pub submodules: Vec<SubmoduleView>,
}

impl RepositoryView {
    /// Generates a collector for a given path.
    pub fn new(
        repo_path: &Path,
        include_email: bool,
        include_submodules: bool,
    ) -> anyhow::Result<RepositoryView> {
        debug!(
            "attempting to generate collector for repository_view at path: {:?}",
            repo_path
        );

        let repo = match Repository::open(repo_path) {
            Ok(repo) => repo,
            Err(e) if e.message() == "unsupported extension name extensions.worktreeconfig" => {
                error!("skipping error ({e}) until upstream libgit2 issue is resolved: https://github.com/libgit2/libgit2/issues/6044");
                let unknown_report = RepositoryView::finalize(
                    repo_path,
                    None,
                    Status::Unknown,
                    None,
                    None,
                    Vec::with_capacity(0),
                )?;
                return Ok(unknown_report);
            }
            Err(e) => return Err(e.into()),
        };
        let (status, head, remote) = RepositoryView::find_status(&repo)?;

        let submodules = if include_submodules {
            SubmoduleView::list(&repo)?
        } else {
            Vec::with_capacity(0)
        };

        let branch = match &head {
            Some(head) => head
                .shorthand()
                .ok_or(RepositoryViewError::GitReferenceShorthandInvalid)?,
            None => "HEAD",
        };

        let url = match remote {
            Some(remote) => remote.url().map(|s| s.to_string()),
            None => None,
        };

        let email = match include_email {
            true => Self::get_email(&repo),
            false => None,
        };

        debug!(
            "finalized collector collection for repository_view at path: {:?}",
            repo_path
        );
        Ok(RepositoryView::finalize(
            repo_path,
            Some(branch.to_string()),
            status,
            url,
            email,
            submodules,
        )?)
    }

    pub fn finalize(
        path: &Path,
        branch: Option<String>,
        status: Status,
        url: Option<String>,
        email: Option<String>,
        submodules: Vec<SubmoduleView>,
    ) -> Result<Self, RepositoryViewError> {
        let name = match path.file_name() {
            Some(s) => match s.to_str() {
                Some(s) => s.to_string(),
                None => {
                    return Err(RepositoryViewError::FileNameToStrConversionFailure(
                        path.to_path_buf(),
                    ))
                }
            },
            None => return Err(RepositoryViewError::FileNameNotFound(path.to_path_buf())),
        };
        let parent = match path.parent() {
            Some(s) => match s.to_str() {
                Some(s) => Some(s.to_string()),
                None => {
                    return Err(RepositoryViewError::PathToStrConversionFailure(
                        s.to_path_buf(),
                    ))
                }
            },
            None => None,
        };
        let branch = match branch {
            Some(branch) => branch,
            None => "unknown".to_string(),
        };

        Ok(Self {
            name,
            branch,
            status,
            parent,
            url,
            email,
            submodules,
        })
    }

    /// Find the [`Status`] for a given [`Repository`](git2::Repository). The
    /// [`head`](Option<git2::Reference>) and [`remote`](Option<git2::Remote>) are also returned.
    pub fn find_status(
        repo: &Repository,
    ) -> anyhow::Result<(Status, Option<Reference>, Option<Remote>)> {
        let head = match repo.head() {
            Ok(head) => Some(head),
            Err(ref e)
                if e.code() == ErrorCode::UnbornBranch || e.code() == ErrorCode::NotFound =>
            {
                None
            }
            Err(e) => return Err(e.into()),
        };

        // Greedily chooses a remote if "origin" is not found.
        let (remote, remote_name) = match repo.find_remote("origin") {
            Ok(origin) => (Some(origin), Some("origin".to_string())),
            Err(e) if e.code() == ErrorCode::NotFound => Self::choose_remote_greedily(repo)?,
            Err(e) => return Err(e.into()),
        };

        // We'll include all untracked files and directories in the status options.
        let mut opts = StatusOptions::new();
        opts.include_untracked(true).recurse_untracked_dirs(true);

        // If "head" is "None" and statuses are empty, then the repository_view must be clean because there
        // are no commits to push.
        let status = match repo.statuses(Some(&mut opts)) {
            Ok(v) if v.is_empty() => match &head {
                Some(head) => match remote_name {
                    Some(remote_name) => {
                        match RepositoryView::is_unpushed(repo, head, &remote_name)? {
                            true => Status::Unpushed,
                            false => Status::Clean,
                        }
                    }
                    None => Status::Clean,
                },
                None => Status::Clean,
            },
            Ok(_) => Status::Unclean,
            Err(e) if e.code() == ErrorCode::BareRepo => Status::Bare,
            Err(e) => return Err(e.into()),
        };

        Ok((status, head, remote))
    }

    fn choose_remote_greedily(
        repository: &Repository,
    ) -> Result<(Option<Remote>, Option<String>), git2::Error> {
        let remotes = repository.remotes()?;
        Ok(match remotes.get(0) {
            Some(remote_name) => (
                Some(repository.find_remote(remote_name)?),
                Some(remote_name.to_string()),
            ),
            None => (None, None),
        })
    }

    /// Checks if local commit(s) on the current branch have not yet been pushed to the remote.
    fn is_unpushed(
        repo: &Repository,
        head: &Reference,
        remote_name: &str,
    ) -> Result<bool, git2::Error> {
        let local_head = head.peel_to_commit()?;
        let remote = format!(
            "{}/{}",
            remote_name,
            match head.shorthand() {
                Some(v) => v,
                None => {
                    debug!("assuming unpushed; could not determine shorthand for head");
                    return Ok(true);
                }
            }
        );
        let remote_head = match repo.resolve_reference_from_short_name(&remote) {
            Ok(reference) => reference.peel_to_commit()?,
            Err(e) => {
                debug!("assuming unpushed; could not resolve remote reference from short name (ignored error: {})", e);
                return Ok(true);
            }
        };
        Ok(
            matches!(repo.graph_ahead_behind(local_head.id(), remote_head.id()), Ok(number_unique_commits) if number_unique_commits.0 > 0),
        )
    }

    /// Find the "user.email" value in the local or global Git config. The
    /// [`Repository::config()`] method will look for a local config first and fallback to
    /// global, as needed. Absorb and log any and all errors as the email field is non-critical to
    /// the final results.
    fn get_email(repository: &Repository) -> Option<String> {
        let config = match repository.config() {
            Ok(v) => v,
            Err(e) => {
                trace!("ignored error: {}", e);
                return None;
            }
        };
        let mut entries = match config.entries(None) {
            Ok(v) => v,
            Err(e) => {
                trace!("ignored error: {}", e);
                return None;
            }
        };

        // Greedily find our "user.email" value. Return the first result found.
        while let Some(entry) = entries.next() {
            match entry {
                Ok(entry) => {
                    if let Some(name) = entry.name() {
                        if name == "user.email" {
                            if let Some(value) = entry.value() {
                                return Some(value.to_string());
                            }
                        }
                    }
                }
                Err(e) => debug!("ignored error: {}", e),
            }
        }
        None
    }
}