Skip to main content

verctl_git/
commit.rs

1use std::env;
2use std::fs::{self, File, Metadata};
3use std::io::Read;
4use std::path::{self, Component, Path, PathBuf};
5use std::time::Duration;
6
7use anyhow::{Context, Result};
8use gix::actor::Signature;
9use gix::date::Time;
10use gix::filter::Pipeline;
11use gix::index::State;
12use gix::objs::Commit;
13use gix::objs::tree::EntryKind;
14use gix::refs::transaction::PreviousValue;
15use verctl_core::process;
16use verctl_core::repo::Repo;
17
18use crate::discover;
19
20/// What [`commit_branch_and_push`] did: `Empty` when the tree was unchanged.
21///
22/// Not `#[non_exhaustive]`: `verctl-release` matches both outcomes
23/// exhaustively.
24#[derive(Debug, Clone, Copy, Eq, PartialEq)]
25pub enum PushOutcome {
26    /// No version files changed.
27    Empty,
28    /// Branch was updated and pushed.
29    Pushed,
30}
31
32/// Commits `paths` onto `branch` without moving HEAD, then force-pushes
33/// `branch` to `github` over HTTPS with `token`.
34///
35/// When `paths` leave the tree unchanged, nothing is pushed and the result is
36/// [`PushOutcome::Empty`].
37///
38/// # Errors
39///
40/// Returns an error when:
41///
42/// - `root` is not inside a git repository;
43/// - the repository has no workdir, or HEAD names no commit;
44/// - a path lies outside the workdir, is not UTF-8, or cannot be read or
45///   filtered;
46/// - the commit or branch ref cannot be written;
47/// - `git push` fails or runs past five minutes.
48pub fn commit_branch_and_push(
49    root: &Path,
50    branch: &str,
51    message: &str,
52    token: &str,
53    github: &Repo,
54    paths: &[PathBuf],
55) -> Result<PushOutcome> {
56    let repo = discover(root).context("open git repository")?;
57    let workdir = absolute_workdir(&repo)?;
58    let parent = repo.head_commit().context("HEAD commit")?;
59    let Some(_) = write_commit_on_branch(&repo, &workdir, &parent, branch, message, paths)? else {
60        return Ok(PushOutcome::Empty);
61    };
62    let url = format!("https://github.com/{}/{}.git", github.owner, github.name);
63    push(repo.git_dir(), &url, branch, token)?;
64    Ok(PushOutcome::Pushed)
65}
66
67/// The working tree as an absolute path. gix reports it as it was discovered,
68/// so a repository found from `.` has `.` for a workdir, and no path would
69/// strip that prefix.
70pub(crate) fn absolute_workdir(repo: &gix::Repository) -> Result<PathBuf> {
71    let workdir = repo.workdir().context("repository has no workdir")?;
72    path::absolute(workdir).with_context(|| format!("resolve the workdir {}", workdir.display()))
73}
74
75/// The token reaches `git push` through this variable, which only the push's
76/// own process sees.
77const PUSH_TOKEN: &str = "VERCTL_GIT_TOKEN";
78
79/// The credential helper `git push` runs. For `get` it supplies
80/// `x-access-token` and the token from [`PUSH_TOKEN`]. It ignores `store` and
81/// `erase`, so the token is never in argv, a URL, or a credential store.
82const PUSH_CREDENTIAL_HELPER: &str = r#"!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$VERCTL_GIT_TOKEN"; }; f"#;
83
84/// How long a push may run before it is killed.
85const PUSH_TIMEOUT: Duration = Duration::from_mins(5);
86
87/// Force-pushes `branch` to `url` with the `git` binary, because gix cannot
88/// push yet.
89///
90/// `credential.helper=` first clears every helper the user configured, so no
91/// keychain supplies a credential or stores one in its place.
92/// `GIT_TERMINAL_PROMPT=0` makes a rejected token fail instead of waiting for
93/// input.
94///
95/// The repository's own hooks do not run (`--no-verify`): the branch is
96/// generated, and libgit2, which pushed it before, never ran hooks either.
97///
98/// `--git-dir` names the repository outright, so a `GIT_DIR` a hook exported
99/// cannot redirect the push. The error, which carries git's stderr, can contain
100/// the URL but not the token, since git only ever saw the variable's name.
101pub(crate) fn push(git_dir: &Path, url: &str, branch: &str, token: &str) -> Result<()> {
102    let git_dir = git_dir
103        .canonicalize()
104        .with_context(|| format!("git directory {}", git_dir.display()))?;
105    let git_dir = format!(
106        "--git-dir={}",
107        git_dir.to_str().context("git directory is not UTF-8")?
108    );
109    let helper = format!("credential.helper={PUSH_CREDENTIAL_HELPER}");
110    let refspec = format!("+refs/heads/{branch}:refs/heads/{branch}");
111    let argv = process::argv(&[
112        "git",
113        &git_dir,
114        "-c",
115        "credential.helper=",
116        "-c",
117        &helper,
118        "push",
119        "--no-verify",
120        "--quiet",
121        url,
122        &refspec,
123    ]);
124    process::run_limited(
125        &argv,
126        &[(PUSH_TOKEN, token), ("GIT_TERMINAL_PROMPT", "0")],
127        PUSH_TIMEOUT,
128    )
129    .context("git push")?;
130    Ok(())
131}
132
133/// Writes a commit that starts from `parent`'s tree and takes `paths` from the
134/// working tree, then points `branch` at it. HEAD, the index, and the working
135/// tree are left alone, because the tree is edited in memory. `None` when the
136/// tree is unchanged.
137///
138/// A path missing from the working tree is removed from the tree. Each file
139/// passes through the `.gitattributes` clean filters first, as `git add` runs
140/// them. So `text` normalization and Large File Storage (LFS) pointers match
141/// what git would store.
142pub(crate) fn write_commit_on_branch(
143    repo: &gix::Repository,
144    workdir: &Path,
145    parent: &gix::Commit<'_>,
146    branch: &str,
147    message: &str,
148    paths: &[PathBuf],
149) -> Result<Option<gix::ObjectId>> {
150    let parent_tree = parent.tree_id().context("HEAD tree")?.detach();
151    let mut editor = repo.edit_tree(parent_tree).context("edit HEAD tree")?;
152    let (mut filters, index) = repo
153        .filter_pipeline(None)
154        .context("load the .gitattributes filters")?;
155    for path in paths {
156        let rel = workdir_rel(workdir, path)?;
157        let name = rel
158            .to_str()
159            .with_context(|| format!("path is not UTF-8: {}", rel.display()))?
160            .to_owned();
161        let abs = workdir.join(&rel);
162        if abs.exists() {
163            let (kind, data) = worktree_entry(&mut filters, &index, &abs, &rel)?;
164            let blob = repo
165                .write_blob(data)
166                .with_context(|| format!("git add {name}"))?;
167            editor
168                .upsert(&name, kind, blob)
169                .with_context(|| format!("git add {name}"))?;
170        } else {
171            editor
172                .remove(&name)
173                .with_context(|| format!("git rm {name}"))?;
174        }
175    }
176    let tree = editor.write().context("write tree")?.detach();
177    if tree == parent_tree {
178        return Ok(None);
179    }
180    let signature = signature(repo);
181    let commit = Commit {
182        tree,
183        parents: [parent.id().detach()].into_iter().collect(),
184        author: signature.clone(),
185        committer: signature,
186        encoding: None,
187        message: message.into(),
188        extra_headers: Vec::new(),
189    };
190    let id = repo.write_object(&commit).context("git commit")?.detach();
191    repo.reference(
192        format!("refs/heads/{branch}"),
193        id,
194        PreviousValue::Any,
195        "verctl: version packages",
196    )
197    .context("git commit")?;
198    Ok(Some(id))
199}
200
201/// The tree entry kind and content for the file at `abs`, which sits at `rel`
202/// in the working tree. A symbolic link stores its target. A file stores what
203/// the clean `filters` make of it and keeps its executable bit.
204fn worktree_entry(
205    filters: &mut Pipeline<'_>,
206    index: &State,
207    abs: &Path,
208    rel: &Path,
209) -> Result<(EntryKind, Vec<u8>)> {
210    let meta = fs::symlink_metadata(abs).with_context(|| abs.display().to_string())?;
211    if meta.file_type().is_symlink() {
212        let target = fs::read_link(abs).with_context(|| abs.display().to_string())?;
213        let target = target
214            .to_str()
215            .with_context(|| format!("link target is not UTF-8: {}", abs.display()))?;
216        return Ok((EntryKind::Link, target.as_bytes().to_vec()));
217    }
218    let file = File::open(abs).with_context(|| abs.display().to_string())?;
219    let mut clean = filters
220        .convert_to_git(file, rel, index)
221        .with_context(|| format!("filter {}", rel.display()))?;
222    let mut data = Vec::new();
223    Read::read_to_end(&mut clean, &mut data)
224        .with_context(|| format!("filter {}", rel.display()))?;
225    Ok((blob_entry_mode(&meta), data))
226}
227
228#[cfg(unix)]
229fn blob_entry_mode(meta: &Metadata) -> EntryKind {
230    use std::os::unix::fs::PermissionsExt;
231    if meta.permissions().mode() & 0o111 == 0 {
232        EntryKind::Blob
233    } else {
234        EntryKind::BlobExecutable
235    }
236}
237
238#[cfg(not(unix))]
239fn blob_entry_mode(_meta: &Metadata) -> EntryKind {
240    EntryKind::Blob
241}
242
243/// `path` relative to the working tree. A relative `path` is taken from the
244/// workdir. An absolute one may spell the workdir as given or canonical. The
245/// dirty-path check returns canonical paths. The plan keeps the spelling
246/// verctl was started with, and a checkout behind a symlink spells them
247/// differently.
248///
249/// Both spellings of the workdir are tried against `path` as given and against
250/// `path` with its parent canonicalized. The second try still works for a file
251/// that was deleted.
252pub(crate) fn workdir_rel(workdir: &Path, path: &Path) -> Result<PathBuf> {
253    let absolute = if path.is_absolute() {
254        path.to_path_buf()
255    } else {
256        workdir.join(path)
257    };
258    let normalized: PathBuf = absolute
259        .components()
260        .filter(|component| !matches!(component, Component::CurDir))
261        .collect();
262    let workdirs = [Some(workdir.to_path_buf()), workdir.canonicalize().ok()];
263    let through_parent = normalized
264        .parent()
265        .and_then(|parent| parent.canonicalize().ok())
266        .zip(normalized.file_name())
267        .map(|(parent, name)| parent.join(name));
268    let paths = [Some(normalized.clone()), through_parent];
269    paths
270        .iter()
271        .flatten()
272        .find_map(|path| {
273            workdirs
274                .iter()
275                .flatten()
276                .find_map(|workdir| path.strip_prefix(workdir).ok())
277        })
278        .map(Path::to_path_buf)
279        .with_context(|| format!("path outside workdir: {}", normalized.display()))
280}
281
282/// Who the Version PR commit is by: `user.name` and `user.email` when the
283/// repository's git config sets both, else the [`fallback_identity`].
284fn signature(repo: &gix::Repository) -> Signature {
285    let time = Time::now_local_or_utc();
286    let config = repo.config_snapshot();
287    if let (Some(name), Some(email)) = (config.string("user.name"), config.string("user.email")) {
288        return Signature { name, email, time };
289    }
290    let (name, email) = fallback_identity();
291    Signature {
292        name: name.into(),
293        email: email.into(),
294        time,
295    }
296}
297
298/// Fallback author identity when git config sets none (`GIT_AUTHOR_NAME` or
299/// `GITHUB_ACTOR`, else `verctl`, with `GIT_AUTHOR_EMAIL` or GitHub noreply).
300pub(crate) fn fallback_identity() -> (String, String) {
301    let name = env::var("GIT_AUTHOR_NAME")
302        .or_else(|_| env::var("GITHUB_ACTOR"))
303        .unwrap_or_else(|_| "verctl".into());
304    let email =
305        env::var("GIT_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{name}@users.noreply.github.com"));
306    (name, email)
307}