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#[derive(Debug, Clone, Copy, Eq, PartialEq)]
25pub enum PushOutcome {
26 Empty,
28 Pushed,
30}
31
32pub 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
67pub(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
75const PUSH_TOKEN: &str = "VERCTL_GIT_TOKEN";
78
79const PUSH_CREDENTIAL_HELPER: &str = r#"!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$VERCTL_GIT_TOKEN"; }; f"#;
83
84const PUSH_TIMEOUT: Duration = Duration::from_mins(5);
86
87pub(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
133pub(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
201fn 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
243pub(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
282fn 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
298pub(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}