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::diagnostic_log::warn;
use super::service_commit_args::{ServiceCommitArgs, opens_editor, parse_service_commit};
use super::service_native::{BuildInput, GitBuilt, build_with_git};
use super::service_amend::{AmendSource, amended_author, read_amend_source};
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>,
}
pub const REBUILD_ATTEMPTS: usize = 5;
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,
scratch: Scratch,
needs_native: bool,
inputs: NativeInputs,
}
struct NativeInputs {
capture: InvocationCapture,
arguments: Vec<OsString>,
pathspecs: Vec<String>,
mode: TransactionMode,
staged_all: bool,
commit_index: PathBuf,
}
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(_)) {
return Ok(Prepared::Decline);
}
let needs_native: bool = config_needs_native(capture.layout.config_snapshot.as_ref());
let amends: bool = invocation.region.amend;
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 && !amends {
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 && !amends {
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),
needs_native,
inputs: NativeInputs {
arguments: outcome.pass.arguments.clone(),
pathspecs: pathspecs.iter().map(|token| { return token.to_string_lossy().into_owned(); }).collect(),
mode: selection.mode,
staged_all: selection.staged_all,
commit_index: indexes.commit_index.clone(),
capture,
},
scratch,
})));
}
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.pathspec_from_file.is_some() {
return Ok(None);
}
let after: &[OsString] = invocation.arguments.get(invocation.subcommand_index + 1..).unwrap_or(&[]);
let id: String = random_uuid().map_err(|error| { return failed(format!("an identity for this commit could not be made: {error:?}")); })?;
let allow_empty: bool = region.allow_empty;
let mut provisioned: bool = false;
let editor_possible: bool = opens_editor(after);
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}");
let mut embedded: Option<Embedded> = None;
let mut decided: bool = false; for attempt in 0..REBUILD_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,
};
if !decided {
decided = true;
if !ready.needs_native
&& let Some(parsed) = parse_service_commit(after)
{
embedded = embedded_commit(invocation, parsed)?;
}
}
let native: bool = embedded.is_none();
let inputs: &NativeInputs = &ready.inputs;
let mut tree: Option<String> = None;
if let Some(source) = embedded.as_ref().and_then(|made| { return made.source.as_ref(); }) {
if source.base != ready.base {
let branch: String = ready.reference.trim_start_matches("refs/heads/").to_string();
return Err(TransactionStop::Message(render(&ClientFailure::BranchMoved { branch })));
}
let written = run_git_checked(
invocation.context,
&indexed_request(
invocation.cwd,
&["write-tree"],
Some(inputs.commit_index.as_path()),
Some(inputs.capture.layout.object_directory.as_path()),
),
)?;
let made: String = String::from_utf8_lossy(written.stdout.as_slice()).trim().to_string();
let against: &str = source.parent_tree.as_deref().unwrap_or(inputs.capture.layout.empty_tree_oid.as_str());
if source.parents.len() < 2 && !allow_empty && made == against {
return Ok(None);
}
tree = Some(made);
}
let mut typed: Option<String> = None;
let (sent, first_parent): (CommitRequest, String) = match embedded.as_ref() {
None => {
let built: GitBuilt = build_with_git(&BuildInput {
context: invocation.context,
cwd: invocation.cwd,
capture: &inputs.capture,
scratch: ready.scratch.0.as_path(),
commit_index: inputs.commit_index.as_path(),
arguments: inputs.arguments.as_slice(),
pathspecs: inputs.pathspecs.as_slice(),
mode: inputs.mode,
staged_all: inputs.staged_all,
quiet: attempt > 0,
})?;
let parent: String = built.parents.first().cloned().unwrap_or_default();
typed = Some(built.message.clone());
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: String::new(),
author: None,
committer: String::new(),
amend: invocation.region.amend,
tree: None,
commit: Some(built.commit),
};
(sent, parent)
}
Some(made) => {
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: made.message.clone(),
author: Some(made.author.clone()),
committer: made.committer.clone(),
amend: tree.is_some(),
tree: tree.clone(),
commit: None,
};
let parent: String = match made.source.as_ref() {
Some(replaced) => replaced.parents.first().cloned().unwrap_or_default(),
None => ready.base.clone(),
};
(sent, parent)
}
};
if let Some(host) = provisioning.as_ref().filter(|_| { return !provisioned; }) {
provision(host).map_err(|failure| { return TransactionStop::Message(render(&failure)); })?;
provisioned = true;
}
match submit(&config, &sent, &mut std::io::stderr()) {
Ok(Submitted::Landed { commit, .. }) => {
if let Some(made) = embedded.as_ref().filter(|made| { return !native && !made.quiet; }) {
let subject: &str = made.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}");
}
if native && attempt > 0 {
let subject: &str = typed.as_deref().and_then(|text| { return text.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: first_parent,
};
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 native || sent.amend {
let branch: String = ready.reference.trim_start_matches("refs/heads/").to_string();
return Err(TransactionStop::Message(render(&ClientFailure::BranchMoved { branch })));
}
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 })));
}
}
Ok(Submitted::Moved) => {
let branch: String = ready.reference.trim_start_matches("refs/heads/").to_string();
if native && !sent.amend && !editor_possible {
if attempt + 1 == REBUILD_ATTEMPTS {
return Err(TransactionStop::Message(render(&ClientFailure::BranchKeepsChanging { branch, times: REBUILD_ATTEMPTS })));
}
continue;
}
if native && editor_possible && let Some(text) = typed.as_deref() {
let file: PathBuf = inputs.capture.layout.git_dir.join(format!("cli-git-saved-message-{}", id.get(..8).unwrap_or(id.as_str())));
match std::fs::write(&file, text) {
Ok(()) => {
let failure: ClientFailure = ClientFailure::BranchMovedMessageSaved { branch, file: file.display().to_string(), amend: sent.amend };
return Err(TransactionStop::Message(render(&failure)));
}
Err(error) => warn("serviceCommit", format!("saving the typed message failed: {error}").as_str()),
}
let again: String = ready.reference.trim_start_matches("refs/heads/").to_string();
return Err(TransactionStop::Message(render(&ClientFailure::BranchMoved { branch: again })));
}
return Err(TransactionStop::Message(render(&ClientFailure::BranchMoved { branch })));
}
Err(failure) => return Err(TransactionStop::Message(render(&failure))),
}
}
return Ok(None);
}
struct Embedded {
message: String,
author: String,
committer: String,
source: Option<AmendSource>,
quiet: bool,
}
fn embedded_commit(invocation: &CommitInvocation<'_>, parsed: ServiceCommitArgs) -> Result<Option<Embedded>, TransactionStop> {
let Some(committer) = identity(invocation.context, invocation.cwd, "GIT_COMMITTER_IDENT", &[])? else { return Ok(None) };
let source: Option<AmendSource> = if parsed.amend {
let Some(read) = read_amend_source(invocation.context, invocation.cwd)? else { return Ok(None) };
Some(read)
} else {
None
};
let previous: Option<&str> = source.as_ref().map(|found| { return found.message.as_str(); });
let Some(built) = build_message(invocation, &parsed, committer.as_str(), previous)? else { return Ok(None) };
let author: String = match built.reused_author {
Some(reused) => reused,
None => match source.as_ref() {
Some(replaced) => {
let Some(made) = amended_author(invocation.context, invocation.cwd, replaced, &parsed)? else { return Ok(None) };
made
}
None => {
let Some(made) = identity(invocation.context, invocation.cwd, "GIT_AUTHOR_IDENT", author_overrides(&parsed).as_slice())? else {
return Ok(None);
};
made
}
},
};
return Ok(Some(Embedded { message: built.message, author, committer, source, quiet: parsed.quiet }));
}
#[cfg(test)]
#[path = "service_commit_tests.rs"]
mod tests;