Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,495 changes: 0 additions & 2,495 deletions src/git.rs

This file was deleted.

97 changes: 97 additions & 0 deletions src/git/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
use anyhow::{Context, Result};
use git2::{Cred, CredentialType, Repository};

use crate::error_code::{self, ErrorCodeExt};

pub(super) fn extract_url_password(url: &str) -> Option<(String, String)> {
let after_scheme = url.split("://").nth(1)?;
let userinfo = after_scheme.split('@').next()?;
let (user, password) = userinfo.split_once(':')?;
if password.is_empty() {
return None;
}
Some((user.to_string(), password.to_string()))
}

pub(super) fn credentials_callback(
url: &str,
username_from_url: Option<&str>,
allowed_types: CredentialType,
) -> std::result::Result<Cred, git2::Error> {
if allowed_types.contains(CredentialType::SSH_KEY) {
return Cred::ssh_key_from_agent(username_from_url.unwrap_or("git"));
}
if allowed_types.contains(CredentialType::USER_PASS_PLAINTEXT) {
if let Ok(token) = std::env::var("FERRFLOW_TOKEN").or_else(|_| {
if url.contains("gitlab") {
std::env::var("GITLAB_TOKEN")
} else {
std::env::var("GITHUB_TOKEN")
}
}) {
let user = username_from_url.unwrap_or_else(|| {
if url.contains("gitlab") {
"oauth2"
} else {
"x-access-token"
}
});
return Cred::userpass_plaintext(user, &token);
}
if let Some((user, password)) = extract_url_password(url) {
return Cred::userpass_plaintext(&user, &password);
}
if let Ok(cfg) = git2::Config::open_default()
&& let Ok(cred) = Cred::credential_helper(&cfg, url, username_from_url)
{
return Ok(cred);
}
eprintln!(
"Warning: No git credentials found. Set FERRFLOW_TOKEN (or GITHUB_TOKEN/GITLAB_TOKEN) or embed credentials in the remote URL."
);
}
Cred::default()
}

pub(super) fn authenticated_remote_url(url: &str) -> Option<String> {
let token = std::env::var("FERRFLOW_TOKEN").ok()?;
let user = if url.contains("gitlab") {
"oauth2"
} else {
"x-access-token"
};
if let Some(scheme_end) = url.find("://") {
let scheme = &url[..scheme_end];
let rest = &url[scheme_end + 3..];
let host_and_path = if let Some(at) = rest.find('@') {
&rest[at + 1..]
} else {
rest
};
Some(format!("{scheme}://{user}:{token}@{host_and_path}"))
} else {
None
}
}

pub(super) fn get_authenticated_remote<'a>(
repo: &'a Repository,
remote_name: &str,
) -> Result<git2::Remote<'a>> {
let remote = repo
.find_remote(remote_name)
.with_context(|| format!("Remote '{}' not found", remote_name))
.error_code(error_code::GIT_REMOTE_NOT_FOUND)?;
if let Some(url) = remote.url()
&& let Some(authed_url) = authenticated_remote_url(url)
{
drop(remote);
return Ok(repo.remote_anonymous(&authed_url)?);
}
Ok(remote)
}

pub fn get_remote_url(repo: &Repository, remote_name: &str) -> Option<String> {
let remote = repo.find_remote(remote_name).ok()?;
Some(remote.url()?.to_string())
}
135 changes: 135 additions & 0 deletions src/git/commits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
use anyhow::Result;
use git2::{Repository, Sort};
use std::path::Path;

pub use crate::changelog::GitLog;
use crate::config::OrphanedTagStrategy;

use super::tags::{find_last_stable_tag, find_last_tag_commit};

pub fn get_commits_since_last_tag(
repo: &Repository,
tag_prefix: &str,
strategy: OrphanedTagStrategy,
) -> Result<Vec<GitLog>> {
let last_tag_oid = find_last_tag_commit(repo, tag_prefix, strategy)?;

let mut walk = repo.revwalk()?;
walk.push_head()?;
walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)?;

let mut commits = Vec::new();
for oid in walk {
let oid = oid?;
if let Some(stop) = last_tag_oid
&& oid == stop
{
break;
}
if let Ok(commit) = repo.find_commit(oid) {
let message = commit.message().unwrap_or("").to_string();
if message.contains("[skip ci]") {
continue;
}
commits.push(GitLog {
hash: oid.to_string()[..8].to_string(),
message,
});
}
}

Ok(commits)
}

pub fn get_commits_since_last_stable_tag(
repo: &Repository,
tag_prefix: &str,
strategy: OrphanedTagStrategy,
) -> Result<Vec<GitLog>> {
let last_tag_oid = find_last_stable_tag(repo, tag_prefix, strategy)?.map(|t| t.commit_oid);

let mut walk = repo.revwalk()?;
walk.push_head()?;
walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)?;

let mut commits = Vec::new();
for oid in walk {
let oid = oid?;
if let Some(stop) = last_tag_oid
&& oid == stop
{
break;
}
if let Ok(commit) = repo.find_commit(oid) {
let message = commit.message().unwrap_or("").to_string();
if message.contains("[skip ci]") {
continue;
}
commits.push(GitLog {
hash: oid.to_string()[..8].to_string(),
message,
});
}
}

Ok(commits)
}

pub(super) fn signature(repo: &Repository) -> Result<git2::Signature<'static>> {
if let Ok(sig) = repo.signature() {
return Ok(sig);
}
Ok(git2::Signature::now("FerrFlow", "contact@ferrflow.com")?)
}

pub fn create_commit(repo: &Repository, files: &[&str], message: &str) -> Result<()> {
let mut index = repo.index()?;
for file in files {
index.add_path(Path::new(file))?;
}
index.write()?;

let tree_id = index.write_tree()?;
let tree = repo.find_tree(tree_id)?;
let sig = signature(repo)?;
let parent = repo.head()?.peel_to_commit()?;

repo.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&parent])?;
Ok(())
}

pub fn create_branch_and_commit(
repo: &Repository,
branch_name: &str,
files: &[&str],
message: &str,
) -> Result<()> {
create_branch_and_commits(repo, branch_name, &[(files, message)])
}

pub fn create_branch_and_commits(
repo: &Repository,
branch_name: &str,
commits: &[(&[&str], &str)],
) -> Result<()> {
let head = repo.head()?.peel_to_commit()?;
repo.branch(branch_name, &head, false)?;

let refname = format!("refs/heads/{branch_name}");
let sig = signature(repo)?;
let mut parent = head;

for (files, message) in commits {
let mut index = repo.index()?;
for file in *files {
index.add_path(Path::new(file))?;
}
index.write()?;

let tree_id = index.write_tree()?;
let tree = repo.find_tree(tree_id)?;
let oid = repo.commit(Some(&refname), &sig, &sig, message, &tree, &[&parent])?;
parent = repo.find_commit(oid)?;
}
Ok(())
}
78 changes: 78 additions & 0 deletions src/git/diff.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use anyhow::Result;
use git2::Repository;

use crate::config::OrphanedTagStrategy;

use super::tags::find_last_tag_commit;

pub fn get_changed_files(repo: &Repository) -> Result<Vec<String>> {
let head = match repo.head() {
Ok(h) => h.peel_to_commit()?,
Err(_) => return Ok(vec![]),
};
let head_tree = head.tree()?;

let files = if let Ok(parent) = head.parent(0) {
let parent_tree = parent.tree()?;
let diff = repo.diff_tree_to_tree(Some(&parent_tree), Some(&head_tree), None)?;
let mut files = Vec::new();
diff.foreach(
&mut |delta, _| {
if let Some(path) = delta.new_file().path() {
files.push(path.to_string_lossy().to_string());
}
true
},
None,
None,
None,
)?;
files
} else {
let mut files = Vec::new();
head_tree.walk(git2::TreeWalkMode::PreOrder, |_, entry| {
if let Some(name) = entry.name() {
files.push(name.to_string());
}
git2::TreeWalkResult::Ok
})?;
files
};

Ok(files)
}

pub fn get_changed_files_since_tag(
repo: &Repository,
tag_prefix: &str,
strategy: OrphanedTagStrategy,
) -> Result<Vec<String>> {
let head = match repo.head() {
Ok(h) => h.peel_to_commit()?,
Err(_) => return Ok(vec![]),
};
let head_tree = head.tree()?;

let old_tree = if let Some(tag_oid) = find_last_tag_commit(repo, tag_prefix, strategy)? {
let tag_commit = repo.find_commit(tag_oid)?;
Some(tag_commit.tree()?)
} else {
None
};

let diff = repo.diff_tree_to_tree(old_tree.as_ref(), Some(&head_tree), None)?;
let mut files = Vec::new();
diff.foreach(
&mut |delta, _| {
if let Some(path) = delta.new_file().path() {
files.push(path.to_string_lossy().to_string());
}
true
},
None,
None,
None,
)?;

Ok(files)
}
19 changes: 19 additions & 0 deletions src/git/fetch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use anyhow::Result;
use git2::{RemoteCallbacks, Repository};

use super::auth::{credentials_callback, get_authenticated_remote};

pub(super) fn make_fetch_options() -> git2::FetchOptions<'static> {
let mut callbacks = RemoteCallbacks::new();
callbacks.credentials(credentials_callback);
let mut opts = git2::FetchOptions::new();
opts.remote_callbacks(callbacks);
opts
}

pub fn fetch_tags(repo: &Repository, remote_name: &str) -> Result<()> {
let mut remote = get_authenticated_remote(repo, remote_name)?;
let mut opts = make_fetch_options();
remote.fetch(&["refs/tags/*:refs/tags/*"], Some(&mut opts), None)?;
Ok(())
}
30 changes: 30 additions & 0 deletions src/git/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
mod auth;
mod commits;
mod diff;
mod fetch;
mod push;
mod repo;
mod retry;
mod tags;

pub use auth::get_remote_url;
#[allow(unused_imports)]
pub use commits::{
GitLog, create_branch_and_commit, create_branch_and_commits, create_commit,
get_commits_since_last_stable_tag, get_commits_since_last_tag,
};
pub use diff::{get_changed_files, get_changed_files_since_tag};
pub use fetch::fetch_tags;
#[allow(unused_imports)]
pub use push::{
force_push_tags, push, push_branch, push_tags, reset_branch_to_remote, verify_remote_branch,
};
Comment on lines +11 to +21
pub use repo::{get_repo_root, open_repo, resolve_current_branch};
pub use retry::is_push_rejected_error;
pub use tags::{
collect_all_tags, create_or_move_tag, create_tag, find_highest_semver_tag, find_last_tag_name,
get_tag_message, tag_exists,
};

#[cfg(test)]
mod tests;
Loading
Loading