use std::env;
use std::fs::{self, File, Metadata};
use std::io::Read;
use std::path::{self, Component, Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result};
use gix::actor::Signature;
use gix::date::Time;
use gix::filter::Pipeline;
use gix::index::State;
use gix::objs::Commit;
use gix::objs::tree::EntryKind;
use gix::refs::transaction::PreviousValue;
use verctl_core::process;
use verctl_core::repo::Repo;
use crate::discover;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PushOutcome {
Empty,
Pushed,
}
pub fn commit_branch_and_push(
root: &Path,
branch: &str,
message: &str,
token: &str,
github: &Repo,
paths: &[PathBuf],
) -> Result<PushOutcome> {
let repo = discover(root).context("open git repository")?;
let workdir = absolute_workdir(&repo)?;
let parent = repo.head_commit().context("HEAD commit")?;
let Some(_) = write_commit_on_branch(&repo, &workdir, &parent, branch, message, paths)? else {
return Ok(PushOutcome::Empty);
};
let url = format!("https://github.com/{}/{}.git", github.owner, github.name);
push(repo.git_dir(), &url, branch, token)?;
Ok(PushOutcome::Pushed)
}
pub(crate) fn absolute_workdir(repo: &gix::Repository) -> Result<PathBuf> {
let workdir = repo.workdir().context("repository has no workdir")?;
path::absolute(workdir).with_context(|| format!("resolve the workdir {}", workdir.display()))
}
const PUSH_TOKEN: &str = "VERCTL_GIT_TOKEN";
const PUSH_CREDENTIAL_HELPER: &str = r#"!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$VERCTL_GIT_TOKEN"; }; f"#;
const PUSH_TIMEOUT: Duration = Duration::from_mins(5);
pub(crate) fn push(git_dir: &Path, url: &str, branch: &str, token: &str) -> Result<()> {
let git_dir = git_dir
.canonicalize()
.with_context(|| format!("git directory {}", git_dir.display()))?;
let git_dir = format!(
"--git-dir={}",
git_dir.to_str().context("git directory is not UTF-8")?
);
let helper = format!("credential.helper={PUSH_CREDENTIAL_HELPER}");
let refspec = format!("+refs/heads/{branch}:refs/heads/{branch}");
let argv = process::argv(&[
"git",
&git_dir,
"-c",
"credential.helper=",
"-c",
&helper,
"push",
"--no-verify",
"--quiet",
url,
&refspec,
]);
process::run_limited(
&argv,
&[(PUSH_TOKEN, token), ("GIT_TERMINAL_PROMPT", "0")],
PUSH_TIMEOUT,
)
.context("git push")?;
Ok(())
}
pub(crate) fn write_commit_on_branch(
repo: &gix::Repository,
workdir: &Path,
parent: &gix::Commit<'_>,
branch: &str,
message: &str,
paths: &[PathBuf],
) -> Result<Option<gix::ObjectId>> {
let parent_tree = parent.tree_id().context("HEAD tree")?.detach();
let mut editor = repo.edit_tree(parent_tree).context("edit HEAD tree")?;
let (mut filters, index) = repo
.filter_pipeline(None)
.context("load the .gitattributes filters")?;
for path in paths {
let rel = workdir_rel(workdir, path)?;
let name = rel
.to_str()
.with_context(|| format!("path is not UTF-8: {}", rel.display()))?
.to_owned();
let abs = workdir.join(&rel);
if abs.exists() {
let (kind, data) = worktree_entry(&mut filters, &index, &abs, &rel)?;
let blob = repo
.write_blob(data)
.with_context(|| format!("git add {name}"))?;
editor
.upsert(&name, kind, blob)
.with_context(|| format!("git add {name}"))?;
} else {
editor
.remove(&name)
.with_context(|| format!("git rm {name}"))?;
}
}
let tree = editor.write().context("write tree")?.detach();
if tree == parent_tree {
return Ok(None);
}
let signature = signature(repo);
let commit = Commit {
tree,
parents: [parent.id().detach()].into_iter().collect(),
author: signature.clone(),
committer: signature,
encoding: None,
message: message.into(),
extra_headers: Vec::new(),
};
let id = repo.write_object(&commit).context("git commit")?.detach();
repo.reference(
format!("refs/heads/{branch}"),
id,
PreviousValue::Any,
"verctl: version packages",
)
.context("git commit")?;
Ok(Some(id))
}
fn worktree_entry(
filters: &mut Pipeline<'_>,
index: &State,
abs: &Path,
rel: &Path,
) -> Result<(EntryKind, Vec<u8>)> {
let meta = fs::symlink_metadata(abs).with_context(|| abs.display().to_string())?;
if meta.file_type().is_symlink() {
let target = fs::read_link(abs).with_context(|| abs.display().to_string())?;
let target = target
.to_str()
.with_context(|| format!("link target is not UTF-8: {}", abs.display()))?;
return Ok((EntryKind::Link, target.as_bytes().to_vec()));
}
let file = File::open(abs).with_context(|| abs.display().to_string())?;
let mut clean = filters
.convert_to_git(file, rel, index)
.with_context(|| format!("filter {}", rel.display()))?;
let mut data = Vec::new();
Read::read_to_end(&mut clean, &mut data)
.with_context(|| format!("filter {}", rel.display()))?;
Ok((blob_entry_mode(&meta), data))
}
#[cfg(unix)]
fn blob_entry_mode(meta: &Metadata) -> EntryKind {
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o111 == 0 {
EntryKind::Blob
} else {
EntryKind::BlobExecutable
}
}
#[cfg(not(unix))]
fn blob_entry_mode(_meta: &Metadata) -> EntryKind {
EntryKind::Blob
}
pub(crate) fn workdir_rel(workdir: &Path, path: &Path) -> Result<PathBuf> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
workdir.join(path)
};
let normalized: PathBuf = absolute
.components()
.filter(|component| !matches!(component, Component::CurDir))
.collect();
let workdirs = [Some(workdir.to_path_buf()), workdir.canonicalize().ok()];
let through_parent = normalized
.parent()
.and_then(|parent| parent.canonicalize().ok())
.zip(normalized.file_name())
.map(|(parent, name)| parent.join(name));
let paths = [Some(normalized.clone()), through_parent];
paths
.iter()
.flatten()
.find_map(|path| {
workdirs
.iter()
.flatten()
.find_map(|workdir| path.strip_prefix(workdir).ok())
})
.map(Path::to_path_buf)
.with_context(|| format!("path outside workdir: {}", normalized.display()))
}
fn signature(repo: &gix::Repository) -> Signature {
let time = Time::now_local_or_utc();
let config = repo.config_snapshot();
if let (Some(name), Some(email)) = (config.string("user.name"), config.string("user.email")) {
return Signature { name, email, time };
}
let (name, email) = fallback_identity();
Signature {
name: name.into(),
email: email.into(),
time,
}
}
pub(crate) fn fallback_identity() -> (String, String) {
let name = env::var("GIT_AUTHOR_NAME")
.or_else(|_| env::var("GITHUB_ACTOR"))
.unwrap_or_else(|_| "verctl".into());
let email =
env::var("GIT_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{name}@users.noreply.github.com"));
(name, email)
}