git_policy_cli/landing/
service_message.rs1use crate::commit_transaction::{CommitInvocation, TransactionStop, failed};
16use crate::service_commit_args::{FixupKind, ServiceCommitArgs, cleanup_message};
17use crate::transaction_git::{GitContext, GitRequest, run_git};
18use std::ffi::OsString;
19use std::path::Path;
20
21#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct Built {
24 pub message: String,
26 pub reused_author: Option<String>,
28}
29
30pub fn identity(context: &GitContext, cwd: &Path, variable: &str, overrides: &[(&str, String)]) -> Result<Option<String>, TransactionStop> {
33 let mut request: GitRequest = GitRequest::new(cwd, &["var", variable]);
34 request.environment = overrides.iter().map(|(name, value)| { return (OsString::from(name), OsString::from(value)); }).collect();
35 let output = run_git(context, &request).map_err(|error| { return failed(format!("reading the commit identity failed: {error:?}")); })?;
36 if output.code != Some(0) {
37 return Ok(None);
38 }
39 return Ok(Some(String::from_utf8_lossy(output.stdout.as_slice()).trim().to_string()));
40}
41
42pub fn author_overrides(parsed: &ServiceCommitArgs) -> Vec<(&'static str, String)> {
44 let mut overrides: Vec<(&'static str, String)> = Vec::new();
45 if let Some(author) = parsed.author.as_deref() {
46 let (name, rest): (&str, &str) = author.split_once('<').unwrap_or((author, ""));
47 overrides.push(("GIT_AUTHOR_NAME", name.trim().to_string()));
48 overrides.push(("GIT_AUTHOR_EMAIL", rest.trim_end().trim_end_matches('>').to_string()));
49 }
50 if let Some(date) = parsed.date.as_deref() {
51 overrides.push(("GIT_AUTHOR_DATE", date.to_string()));
52 }
53 return overrides;
54}
55
56fn query(context: &GitContext, cwd: &Path, arguments: &[&str]) -> Result<Option<Vec<u8>>, TransactionStop> {
58 let output = run_git(context, &GitRequest::new(cwd, arguments)).map_err(|error| { return failed(format!("reading the repository failed: {error:?}")); })?;
59 return Ok(if output.code == Some(0) { Some(output.stdout) } else { None });
60}
61
62fn reused_commit(context: &GitContext, cwd: &Path, revision: &str) -> Result<Option<(String, String)>, TransactionStop> {
64 if revision.starts_with('-') {
65 return Ok(None);
66 }
67 let Some(oid) = query(context, cwd, &["rev-parse", "--verify", "--quiet", format!("{revision}^{{commit}}").as_str()])? else { return Ok(None) };
68 let Some(raw) = query(context, cwd, &["cat-file", "commit", String::from_utf8_lossy(oid.as_slice()).trim()])? else { return Ok(None) };
69 let Ok(text) = String::from_utf8(raw) else { return Ok(None) };
70 let Some((header, message)) = text.split_once("\n\n") else { return Ok(None) };
71 if header.lines().any(|line| { return line.starts_with("encoding "); }) {
73 return Ok(None);
74 }
75 let Some(author) = header.lines().find_map(|line| { return line.strip_prefix("author "); }) else { return Ok(None) };
76 return Ok(Some((author.to_string(), message.to_string())));
77}
78
79fn subject_of(context: &GitContext, cwd: &Path, revision: &str) -> Result<Option<String>, TransactionStop> {
81 if revision.starts_with('-') {
82 return Ok(None);
83 }
84 let Some(bytes) = query(context, cwd, &["log", "-1", "--format=%s", revision, "--"])? else { return Ok(None) };
85 return Ok(String::from_utf8(bytes).ok().map(|text| { return text.trim_end_matches('\n').to_string(); }));
86}
87
88pub fn strip_comment_lines(text: &str) -> String {
90 return text.split('\n').filter(|line| { return !line.starts_with('#'); }).collect::<Vec<&str>>().join("\n");
91}
92
93pub fn build_message(
106 invocation: &CommitInvocation<'_>,
107 parsed: &ServiceCommitArgs,
108 committer: &str,
109 previous_message: Option<&str>,
110) -> Result<Option<Built>, TransactionStop> {
111 let context: &GitContext = invocation.context;
112 let cwd: &Path = invocation.cwd;
113 let mut reused_author: Option<String> = None;
114 let sources: Vec<String> = if let Some(file) = parsed.file.as_ref() {
115 match std::fs::read(cwd.join(file)).ok().and_then(|bytes| { return String::from_utf8(bytes).ok(); }) {
116 Some(text) => vec![text],
117 None => return Ok(None),
118 }
119 } else if let Some(revision) = parsed.reuse.as_deref() {
120 let Some((author, message)) = reused_commit(context, cwd, revision)? else { return Ok(None) };
121 reused_author = Some(author);
122 vec![message]
123 } else if let Some((kind, revision)) = parsed.fixup.as_ref() {
124 let Some(subject) = subject_of(context, cwd, revision.as_str())? else { return Ok(None) };
125 let prefix: &str = match kind {
126 FixupKind::Fixup => "fixup!",
127 };
128 vec![format!("{prefix} {subject}")]
129 } else if parsed.messages.is_empty() && let Some(previous) = previous_message.filter(|_| { return parsed.amend; }) {
130 vec![previous.to_string()]
132 } else {
133 parsed.messages.clone()
134 };
135 let texts: Vec<String> = if parsed.strip { sources.iter().map(|text| { return strip_comment_lines(text.as_str()); }).collect() } else { sources };
136 let cleaned: Option<String> = if parsed.verbatim {
137 Some(texts.iter().map(|text| { return if text.ends_with('\n') { text.clone() } else { format!("{text}\n") }; }).collect::<Vec<String>>().join("\n"))
138 } else {
139 cleanup_message(texts.as_slice())
140 };
141 let message: String = match cleaned {
142 Some(text) if !text.trim().is_empty() || parsed.verbatim => text,
143 _ if parsed.allow_empty_message => String::new(),
144 _ => return Ok(None),
145 };
146 let mut trailers: Vec<String> = Vec::new();
147 if parsed.signoff {
148 let who: &str = committer.split_once('>').map_or(committer, |(name_and_email, _)| { return &committer[..name_and_email.len() + 1]; });
149 trailers.push(format!("Signed-off-by: {who}"));
150 }
151 trailers.extend(parsed.trailers.iter().cloned());
152 if trailers.is_empty() {
153 return Ok(Some(Built { message, reused_author }));
154 }
155 let mut arguments: Vec<String> = vec![String::from("interpret-trailers")];
156 for trailer in &trailers {
157 arguments.push(String::from("--trailer"));
158 arguments.push(trailer.clone());
159 }
160 let mut request: GitRequest = GitRequest::new(cwd, arguments.as_slice());
161 request.input = Some(message.into_bytes());
162 let output = run_git(context, &request).map_err(|error| { return failed(format!("preparing the commit message failed: {error:?}")); })?;
163 if output.code != Some(0) {
164 return Ok(None);
165 }
166 return Ok(String::from_utf8(output.stdout).ok().map(|trailed| { return Built { message: trailed, reused_author }; }));
167}