use super::capture_invocation::{InvocationCapture, base_revision, capture_invocation_base, capture_invocation_layout};
use super::capture_order::{CaptureIndexes, indexed_request};
use super::commit_convergence::{CommitConvergenceInput, converge_commit_policies};
use super::commit_facts::PrivateIndexFacts;
use super::commit_index::{IndexSelection, initialize_commit_index, list_changed_index_paths, list_unmerged_index_paths};
use super::commit_transaction::{CommitInvocation, TransactionResult, TransactionStop, base_object, decide_selection, failed, private_checks, staged_at_base};
use super::lfs_pre_push::uses_lfs;
use super::policy_checks::ShippedChecks;
use super::policy_engine::{StageRequest, pass_exit_code};
use super::policy_events::PolicyEvent;
use super::private_index_stage::PrivateStage;
use super::private_storage::{create_private_directory, remove_tree};
use super::random_id::random_uuid;
use super::repository_facts::RepositoryFacts;
use super::service_client::{Activation, COMMIT_WAIT, ClientConfig, START_WAIT, Submitted, submit};
use super::service_commit_args::parse_service_commit;
use super::service_message::{author_overrides, build_message, identity};
use super::service_land::LANDING_ATTEMPTS;
use super::service_messages::{ClientFailure, render};
use super::service_protocol::{ALLOWED_MODES, Change, CommitRequest, MAX_CHANGES, is_object_name, is_plain_path};
use super::service_handoff::ServiceHandoff;
use super::service_provision::provision;
use super::service_route::{Route, RouteInputs, choose_route, remembered_own_executable};
use super::config_snapshot::ConfigSnapshot;
use super::transaction_git::{GitContext, run_git_checked};
use super::transaction_journal::{Base, Conclusion, SymbolicHead, TransactionMode};
use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};
pub struct ServiceCommit {
pub result: TransactionResult,
pub handoff: Option<ServiceHandoff>,
}
struct Scratch(PathBuf);
impl Drop for Scratch {
fn drop(&mut self) {
let _removed = remove_tree(self.0.as_path());
}
}
enum Prepared {
Decline,
Blocked(TransactionResult),
Ready(Box<Ready>),
}
struct Ready {
repository: PathBuf,
common_dir: PathBuf,
reference: String,
base: String,
changes: Vec<Change>,
events: Vec<PolicyEvent>,
uses_lfs: bool,
}
fn changes_of(context: &GitContext, cwd: &Path, indexes: &CaptureIndexes, base: &str) -> Result<Option<Vec<Change>>, TransactionStop> {
let arguments: Vec<String> = ["diff-index", "--cached", "-r", "--raw", "-z", "--no-renames", "--no-abbrev", base].map(String::from).to_vec();
let output = run_git_checked(
context,
&indexed_request(cwd, &arguments, Some(indexes.commit_index.as_path()), Some(indexes.object_directory.as_path())),
)?;
let text: String = match String::from_utf8(output.stdout) {
Ok(text) => text,
Err(_) => return Ok(None),
};
let mut fields = text.split('\0').filter(|field| { return !field.is_empty(); });
let mut changes: Vec<Change> = Vec::new();
while let Some(header) = fields.next() {
let Some(path) = fields.next() else { return Ok(None) };
let parts: Vec<&str> = header.trim_start_matches(':').split(' ').collect();
let [_, new_mode, _, new_name, status] = parts.as_slice() else { return Ok(None) };
let deletion: bool = status.starts_with('D');
let mode: u32 = if deletion { ALLOWED_MODES[0] } else { u32::from_str_radix(new_mode, 8).unwrap_or(0) };
if !is_plain_path(path) || !ALLOWED_MODES.contains(&mode) || (!deletion && !is_object_name(new_name)) {
return Ok(None);
}
changes.push(Change { path: path.to_string(), mode, blob: if deletion { None } else { Some((*new_name).to_string()) } });
}
return Ok(if changes.len() > MAX_CHANGES { None } else { Some(changes) });
}
fn prepare<F: RepositoryFacts>(
invocation: &CommitInvocation<'_>,
checks: &mut ShippedChecks<F>,
request: &StageRequest,
scratch_name: &str,
allow_empty: bool,
) -> Result<Prepared, TransactionStop> {
let context: &GitContext = invocation.context;
let cwd: &Path = invocation.cwd;
let layout = capture_invocation_layout(context, cwd, false)?;
if layout.conclusion != Conclusion::None {
return Ok(Prepared::Decline);
}
let selection = decide_selection(invocation.region, layout.conclusion);
let SymbolicHead::Branch(reference) = layout.symbolic_head.clone() else { return Ok(Prepared::Decline) };
let named: bool = selection.mode == TransactionMode::ExplicitPath;
if selection.read_only || (selection.mode == TransactionMode::Index && selection.selects_paths) {
return Ok(Prepared::Decline);
}
let capture: InvocationCapture = capture_invocation_base(context, cwd, layout)?;
if !matches!(capture.base, Base::Commit(_)) || config_needs_native(capture.layout.config_snapshot.as_ref()) {
return Ok(Prepared::Decline);
}
let base: String = base_revision(&capture);
let scratch: Scratch = Scratch(capture.layout.git_dir.join(scratch_name));
create_private_directory(scratch.0.as_path()).map_err(|error| { return failed(format!("preparing the commit failed: {error}")); })?;
let indexes: CaptureIndexes = CaptureIndexes {
captured_index: scratch.0.join("captured.index"),
commit_index: scratch.0.join("commit.index"),
object_directory: capture.layout.object_directory.clone(),
};
let region_arguments: &[OsString] = &invocation.arguments[invocation.subcommand_index + 1..];
let pathspecs: Vec<OsString> = invocation.region.pathspecs.iter().map(|at| { return region_arguments[*at].clone(); }).collect();
let index_selection: IndexSelection<'_> = IndexSelection {
mode: selection.mode,
pathspecs: if named { pathspecs.as_slice() } else { &[] },
pathspec_file: None,
pathspec_file_nul: false,
stage_into_index: false,
stage_tracked_changes: selection.staged_all,
base_revision: base.as_str(),
};
initialize_commit_index(context, cwd, capture.layout.real_index_path.as_path(), &indexes, &index_selection)
.map_err(|error| { return failed(error.0); })?;
if !list_unmerged_index_paths(context, cwd, indexes.commit_index.as_path())?.is_empty() {
return Ok(Prepared::Decline);
}
let candidate_paths: Vec<Vec<u8>> =
list_changed_index_paths(context, cwd, indexes.commit_index.as_path(), base.as_str(), indexes.object_directory.as_path())?;
if candidate_paths.is_empty() && !allow_empty {
return Ok(Prepared::Decline);
}
let mut private: ShippedChecks<PrivateIndexFacts<&mut F>> = private_checks(
checks,
indexes.commit_index.as_path(),
indexes.object_directory.as_path(),
staged_at_base(base_object(&capture)?, candidate_paths.as_slice()),
);
let outcome = converge_commit_policies(CommitConvergenceInput {
request,
checks: &mut private,
stage: PrivateStage {
context,
cwd,
index: indexes.commit_index.as_path(),
object_directory: Some(indexes.object_directory.as_path()),
},
});
let code: i32 = pass_exit_code(outcome.pass.events.as_slice(), outcome.pass.end);
if code != 0 {
return Ok(Prepared::Blocked(TransactionResult { events: outcome.pass.events, exit_code: code, landed_oid: None, uses_lfs: false }));
}
if !outcome.changed_paths.is_empty() {
return Ok(Prepared::Decline);
}
let Some(changes) = changes_of(context, cwd, &indexes, base.as_str())? else { return Ok(Prepared::Decline) };
if changes.is_empty() && !allow_empty {
return Ok(Prepared::Decline);
}
return Ok(Prepared::Ready(Box::new(Ready {
repository: capture.layout.repository_root.clone(),
common_dir: capture.layout.common_dir.clone(),
reference,
base,
changes,
events: outcome.pass.events,
uses_lfs: capture.layout.config_snapshot.as_ref().is_none_or(uses_lfs),
})));
}
fn config_needs_native(snapshot: Option<&ConfigSnapshot>) -> bool {
const KEYS: [&str; 7] = ["commit.template", "commit.cleanup", "i18n.commitencoding", "core.commentchar", "core.commentstring", "commit.signoff", "commit.verbose"];
let Some(found) = snapshot else { return true };
return found.entries().iter().any(|entry| {
let value: String = entry.value.as_deref().map(|bytes| { return String::from_utf8_lossy(bytes).to_lowercase(); }).unwrap_or_default();
let signs: bool = entry.key == "commit.gpgsign" && !["false", "no", "off", "0"].contains(&value.as_str());
return signs || KEYS.contains(&entry.key.as_str()) || entry.key.starts_with("trailer.");
});
}
pub fn try_service_commit<F: RepositoryFacts>(
invocation: &CommitInvocation<'_>,
checks: &mut ShippedChecks<F>,
request: &StageRequest,
) -> Result<Option<ServiceCommit>, TransactionStop> {
let path_variable = |name: &str| -> Option<PathBuf> { return std::env::var_os(name).filter(|value| { return !value.is_empty(); }).map(PathBuf::from); };
let runtime: Option<PathBuf> = path_variable("XDG_RUNTIME_DIR");
let config_home: Option<PathBuf> = path_variable("XDG_CONFIG_HOME");
let home: Option<PathBuf> = path_variable("HOME");
let bus_address: Option<String> = std::env::var("DBUS_SESSION_BUS_ADDRESS").ok();
let route: Route = choose_route(&RouteInputs {
runtime_dir: runtime.as_deref(),
bus_address: bus_address.as_deref(),
config_home: config_home.as_deref(),
home: home.as_deref(),
own_executable: remembered_own_executable(),
real_git: invocation.context.real_git.as_path(),
});
let Route::Service { address, provision: provisioning } = route else { return Ok(None) };
let region = invocation.region;
if region.include || region.interactive || region.patch || region.dry_run || region.amend || region.pathspec_from_file.is_some() {
return Ok(None);
}
let after: &[OsString] = invocation.arguments.get(invocation.subcommand_index + 1..).unwrap_or(&[]);
let Some(parsed) = parse_service_commit(after) else { return Ok(None) };
let quiet: bool = parsed.quiet;
let Some(committer) = identity(invocation.context, invocation.cwd, "GIT_COMMITTER_IDENT", &[])? else { return Ok(None) };
let Some(built) = build_message(invocation, &parsed, committer.as_str())? else { return Ok(None) };
let message: String = built.message;
let id: String = random_uuid().map_err(|error| { return failed(format!("an identity for this commit could not be made: {error:?}")); })?;
let author: String = match built.reused_author {
Some(reused) => reused,
None => {
let Some(made) = identity(invocation.context, invocation.cwd, "GIT_AUTHOR_IDENT", author_overrides(&parsed).as_slice())? else {
return Ok(None);
};
made
}
};
let allow_empty: bool = region.allow_empty;
if let Some(host) = provisioning.as_ref() {
provision(host).map_err(|failure| { return TransactionStop::Message(render(&failure)); })?;
}
let config: ClientConfig = ClientConfig { address, activation: Activation::Managed, start_wait: START_WAIT, commit_wait: COMMIT_WAIT };
let scratch_name: String = format!("cli-git-service-{id}");
for attempt in 0..LANDING_ATTEMPTS {
let ready: Box<Ready> = match prepare(invocation, checks, request, scratch_name.as_str(), allow_empty)? {
Prepared::Decline => return Ok(None),
Prepared::Blocked(result) => return Ok(Some(ServiceCommit { result, handoff: None })),
Prepared::Ready(ready) => ready,
};
let sent: CommitRequest = CommitRequest {
id: id.clone(),
repository: ready.repository.clone(),
common_dir: ready.common_dir.clone(),
reference: ready.reference.clone(),
base: ready.base.clone(),
changes: ready.changes.clone(),
message: message.clone(),
author: Some(author.clone()),
committer: committer.clone(),
};
match submit(&config, &sent, &mut std::io::stderr()) {
Ok(Submitted::Landed { commit, .. }) => {
if !quiet {
let subject: &str = message.lines().next().unwrap_or("");
let short: &str = commit.get(..7).unwrap_or(commit.as_str());
let branch: &str = ready.reference.trim_start_matches("refs/heads/");
let _printed = writeln!(std::io::stdout(), "[{branch} {short}] {subject}");
}
let handoff: ServiceHandoff = ServiceHandoff {
config: config.clone(),
repository: ready.repository.clone(),
common_dir: ready.common_dir.clone(),
reference: ready.reference.clone(),
parent: ready.base.clone(),
};
let result: TransactionResult = TransactionResult { events: ready.events, exit_code: 0, landed_oid: Some(commit), uses_lfs: ready.uses_lfs };
return Ok(Some(ServiceCommit { result, handoff: Some(handoff) }));
}
Ok(Submitted::PrepareAgain { .. }) => {
if attempt + 1 == LANDING_ATTEMPTS {
let branch: String = ready.reference.trim_start_matches("refs/heads/").to_string();
return Err(TransactionStop::Message(render(&ClientFailure::BranchKeepsChanging { branch, times: LANDING_ATTEMPTS })));
}
}
Err(failure) => return Err(TransactionStop::Message(render(&failure))),
}
}
return Ok(None);
}
#[cfg(test)]
#[path = "service_commit_tests.rs"]
mod tests;