Skip to main content

git_policy_cli/
push_failure_notice.rs

1//! What:
2//!  The record of a backup push that failed after its commit was saved, and the rule for when the wrapper shows it:
3//!  the resident service writes one record per failed push under the Git directory of the worktree whose commit it was, a
4//!  later wrapper command in that worktree shows each record once on standard error, and a later push of the same branch
5//!  that succeeds removes the records of that branch.
6//! Why:
7//!  The push runs in the service after the commit command returned, so nothing is attached to the command that could
8//!  print its failure; without a record the person would never learn that their backup push was refused
9//!  (`doc/planning/cli-git-resident-service.md`, "After-commit work"). Records are plain files in the worktree's
10//!  own Git directory so the check on every command is one directory read that finds nothing when nothing failed. A record holds
11//!  the branch, the whole commit name and Git's words with credentials already masked; the wrapper words the notice when it
12//!  shows it, so the commit name is abbreviated the way Git abbreviates it in the repository as it is then. Records are
13//!  shown on standard error only, and not at all to a command whose output a program reads (`--porcelain`, `-z`,
14//!  plumbing), so that program neither sees the text in its output nor consumes the record before a person can read it.
15//!
16//! In TS you'd write (pseudocode):
17//! ```ts
18//! await recordPushFailure(gitDir, { branchRef, oid, reason }); stderr.write(await takePushFailures(gitDir));
19//! ```
20
21use super::auto_push::PUSH_FAILED_NOTE;
22use super::auto_push_branch_key::encode_branch_key;
23use super::lfs_output_mask::mask_userinfo_text;
24use super::private_storage::{create_private_directory_all, write_private_file_unsynced};
25use super::service_messages::RESTART_COMMAND;
26use std::ffi::OsString;
27use std::path::{Path, PathBuf};
28
29/// Directory under the worktree's own Git directory that holds the records for the person.
30pub const NOTICE_DIRECTORY: &str = "cli-git/notices";
31
32/// Directory under the repository's common Git directory that holds the records of removed worktrees, which any worktree's
33///  command shows because the worktree they were made for is gone.
34pub const ORPHAN_NOTICE_DIRECTORY: &str = "cli-git/orphaned-notices";
35
36/// First line of a record of a push that was lost with its worktree; its fields are those of a failure record, without words.
37const LOST_MAGIC: &str = "cli-git push lost 1";
38
39/// Separates the parts of a record's name; it is not a character a branch key can contain.
40const NAME_SEPARATOR: char = '+';
41
42/// The longest branch key a record name carries whole; a longer key is cut and tagged with a hash of the whole key, so the
43///  name stays a valid file name and two long branch names do not share records.
44const LONGEST_KEY: usize = 100;
45
46/// The most bytes of Git's own words a record keeps.
47const LONGEST_REASON: usize = 4000;
48
49/// First line of a record that holds its parts as fields; a file without it is the finished text an earlier release wrote.
50const RECORD_MAGIC: &str = "cli-git push notice 1";
51
52/// First line of a record of a push the service did not make because the branch has no destination it can name; its fields are
53///  those of a failure record, and its reason is the service's own words.
54const SKIPPED_MAGIC: &str = "cli-git push skipped 1";
55
56/// The field names of a record's header lines.
57const BRANCH_FIELD: &str = "branch: ";
58const COMMIT_FIELD: &str = "commit: ";
59
60/// Said when Git gave no words at all.
61const NO_REASON: &str = "Git gave no reason.";
62
63/// The directory that holds the records of a repository.
64pub fn notice_directory(git_dir: &Path) -> PathBuf {
65    return git_dir.join(NOTICE_DIRECTORY);
66}
67
68/// A 64-bit FNV-1a hash of the text, in hexadecimal.
69fn fnv_hex(text: &str) -> String {
70    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
71    for byte in text.bytes() {
72        hash ^= u64::from(byte);
73        hash = hash.wrapping_mul(0x0100_0000_01b3);
74    }
75    return format!("{hash:016x}");
76}
77
78/// The part of every record name that belongs to one branch.
79fn branch_prefix(branch_ref: &str) -> String {
80    let key: String = encode_branch_key(branch_ref);
81    let shown: String = if key.len() > LONGEST_KEY { format!("{}~{}", &key[..LONGEST_KEY], fnv_hex(key.as_str())) } else { key };
82    return format!("push{NAME_SEPARATOR}{shown}{NAME_SEPARATOR}");
83}
84
85/// The file name of the record of one failed push.
86pub fn record_name(branch_ref: &str, commit: &str) -> String {
87    return format!("{}{commit}.txt", branch_prefix(branch_ref));
88}
89
90/// What:
91///  Git's words for the person: the user name and password of every URL masked, control characters dropped, and the
92///  length bounded.
93/// Why:
94///   The text came from a remote and from Git, and is printed on a terminal; a URL with a user name and password, or an
95///  escape sequence, must not reach the screen or a log of it. Only the credentials are masked, never the line around them,
96///  because the line often says why the push failed (the wrapper's own Git LFS failure line names the endpoint setting and
97///  carries the exit status).
98///
99/// In TS you'd write (pseudocode):
100/// ```ts
101/// cleanReason(said)
102/// ```
103pub fn clean_reason(said: &str) -> String {
104    let masked: String = mask_userinfo_text(said);
105    let mut kept: Vec<String> = Vec::new();
106    for line in masked.lines() {
107        let plain: String = line.chars().filter(|character| { return *character == '\t' || !character.is_control(); }).collect();
108        let trimmed: &str = plain.trim_end();
109        if !trimmed.is_empty() {
110            kept.push(trimmed.to_string());
111        }
112    }
113    let mut text: String = kept.join("\n");
114    if text.len() > LONGEST_REASON {
115        let mut cut: usize = LONGEST_REASON;
116        while !text.is_char_boundary(cut) {
117            cut -= 1;
118        }
119        text.truncate(cut);
120        text.push_str("\n(Git's output is cut here.)");
121    }
122    return text;
123}
124
125/// What:
126///  The text shown for a failed backup push, with the commit named as given and Git's words already cleaned.
127/// Why:
128///   It names the branch and the commit, gives Git's own reason, says the commit is safe on this computer, and says what to
129///  do; the service runs with its own settings, which is the first thing to check when a push that works in a terminal
130///  fails here. The command that shows it may be anyone's, so it never calls the commit the reader's own.
131///
132/// In TS you'd write (pseudocode):
133/// ```ts
134/// worded({ branchRef, shown, reason })
135/// ```
136fn worded(branch_ref: &str, shown: &str, reason: &str) -> String {
137    let branch: &str = branch_ref.strip_prefix("refs/heads/").unwrap_or(branch_ref);
138    let detail: String = if reason.is_empty() {
139        NO_REASON.to_string()
140    } else {
141        format!("Git said:\n{}", reason.lines().map(|line| { return format!("    {line}"); }).collect::<Vec<String>>().join("\n"))
142    };
143    return format!(
144        "The backup push of branch {branch} failed for commit {shown}, so that commit exists only on this computer for now. \
145         It is saved in this repository and nothing was lost.\n{detail}\n\
146         Fix what Git names, then run `git push`. If it says the remote has commits you do not have, run `git pull` first. \
147         The commit service runs with its own settings, not your terminal's, so a push that works in your terminal can \
148         fail here when it needs a variable only your terminal has; give the service such a variable with \
149         `systemctl --user set-environment NAME=value` and then `{RESTART_COMMAND}`.\n{PUSH_FAILED_NOTE}"
150    );
151}
152
153/// What:
154///  The text shown for a failed backup push, from Git's raw words.
155/// Why:
156///   The commit is named as the caller gives it, so a caller that has the repository passes Git's own abbreviation.
157///
158/// In TS you'd write (pseudocode):
159/// ```ts
160/// pushFailureText({ branchRef, commit, said })
161/// ```
162pub fn push_failure_text(branch_ref: &str, commit: &str, said: &str) -> String {
163    return worded(branch_ref, commit, clean_reason(said).as_str());
164}
165
166/// What:
167///  The text shown for a push the service did not make, with the commit named as given and the service's words already cleaned.
168/// Why:
169///   Nothing failed and nothing was sent, so the text says that and not that the push was refused; it names the branch and the
170///  commit, gives the service's reason, says the commit is saved here, and names both ways out: a destination the service can
171///  name, or a push by hand. The command that shows it may be anyone's, so it never calls the commit the reader's own.
172///
173/// In TS you'd write (pseudocode):
174/// ```ts
175/// wordedSkipped({ branchRef, shown, reason })
176/// ```
177fn worded_skipped(branch_ref: &str, shown: &str, reason: &str) -> String {
178    let branch: &str = branch_ref.strip_prefix("refs/heads/").unwrap_or(branch_ref);
179    let detail: String = if reason.is_empty() {
180        String::from("The commit service gave no reason.")
181    } else {
182        format!("The commit service said:\n{}", reason.lines().map(|line| { return format!("    {line}"); }).collect::<Vec<String>>().join("\n"))
183    };
184    return format!(
185        "The backup push of branch {branch} for commit {shown} was not made, so that commit exists only on this computer for now. \
186         It is saved in this repository and nothing was lost.\n{detail}\n\
187         Either give the branch a destination the commit service can name (the `push.default` setting of `git help config` says \
188         which values do), or push it yourself with `git push <remote> {branch}`."
189    );
190}
191
192/// What:
193///  Leaves the record of one push the service did not make, replacing an earlier record of the same commit on the same branch.
194/// Why:
195///   The service settles such a push as done because nothing is left for it to retry, and the person would otherwise never
196///  learn that the backup does not exist. The name is the failure record's, so a later successful push of the branch removes
197///  it with the failures.
198///
199/// In TS you'd write (pseudocode):
200/// ```ts
201/// await recordPushSkip(gitDir, { branchRef, commit, said })
202/// ```
203pub fn record_push_skip(git_dir: &Path, branch_ref: &str, commit: &str, said: &str) -> Result<(), String> {
204    let directory: PathBuf = notice_directory(git_dir);
205    create_private_directory_all(directory.as_path()).map_err(|error| { return format!("creating the notice directory failed: {error}"); })?;
206    let path: PathBuf = directory.join(record_name(branch_ref, commit));
207    let _removed = std::fs::remove_file(path.as_path());
208    let text: String = format!("{SKIPPED_MAGIC}\n{BRANCH_FIELD}{branch_ref}\n{COMMIT_FIELD}{commit}\n\n{}", clean_reason(said));
209    return write_private_file_unsynced(path.as_path(), text.as_bytes()).map_err(|error| { return format!("writing the notice failed: {error}"); });
210}
211
212/// What:
213///  Leaves the record of one failed push, replacing an earlier record of the same commit on the same branch.
214/// Why:
215///   The name is derived from the branch and the commit, so a push that is tried again and fails again leaves one record.
216///  The reason is cleaned before it is written, so no credential reaches the disk.
217///
218/// In TS you'd write (pseudocode):
219/// ```ts
220/// await recordPushFailure(gitDir, { branchRef, commit, said })
221/// ```
222pub fn record_push_failure(git_dir: &Path, branch_ref: &str, commit: &str, said: &str) -> Result<(), String> {
223    let directory: PathBuf = notice_directory(git_dir);
224    create_private_directory_all(directory.as_path()).map_err(|error| { return format!("creating the notice directory failed: {error}"); })?;
225    let path: PathBuf = directory.join(record_name(branch_ref, commit));
226    // A repeat of the same failure replaces its record.
227    let _removed = std::fs::remove_file(path.as_path());
228    let text: String = format!("{RECORD_MAGIC}\n{BRANCH_FIELD}{branch_ref}\n{COMMIT_FIELD}{commit}\n\n{}", clean_reason(said));
229    return write_private_file_unsynced(path.as_path(), text.as_bytes()).map_err(|error| { return format!("writing the notice failed: {error}"); });
230}
231
232/// What:
233///  The text shown for a push that had not finished when the worktree that made the commit was removed.
234/// Why:
235///   Nothing says whether the push ran, failed or never started, so the text says only what is known: the commit is saved here
236///  and the branch may not be on the remote.
237fn worded_lost(branch_ref: &str, shown: &str) -> String {
238    let branch: &str = branch_ref.strip_prefix("refs/heads/").unwrap_or(branch_ref);
239    return format!(
240        "The backup push of branch {branch} for commit {shown} had not finished when the worktree that made the commit was \
241         removed, so that commit may exist only on this computer for now. It is saved in this repository and nothing was lost. \
242         Run `git push` in a worktree that has branch {branch} checked out, or `git push <remote> {branch}` from any worktree."
243    );
244}
245
246/// What:
247///  Leaves the record of a push that was lost with its worktree, unless a record of that commit on that branch is already
248///  there.
249/// Why:
250///   An existing record holds Git's own words about a failed push, which say more than this one does.
251///
252/// In TS you'd write (pseudocode):
253/// ```ts
254/// await recordLostPush(commonDir, { branchRef, commit })
255/// ```
256pub fn record_lost_push(common_dir: &Path, branch_ref: &str, commit: &str) -> Result<(), String> {
257    let directory: PathBuf = common_dir.join(ORPHAN_NOTICE_DIRECTORY);
258    create_private_directory_all(directory.as_path()).map_err(|error| { return format!("creating the notice directory failed: {error}"); })?;
259    let path: PathBuf = directory.join(record_name(branch_ref, commit));
260    if path.exists() {
261        return Ok(());
262    }
263    let text: String = format!("{LOST_MAGIC}\n{BRANCH_FIELD}{branch_ref}\n{COMMIT_FIELD}{commit}\n\n");
264    return match write_private_file_unsynced(path.as_path(), text.as_bytes()) {
265        Err(error) if error.kind() != std::io::ErrorKind::AlreadyExists => Err(format!("writing the notice failed: {error}")),
266        Ok(()) | Err(_) => Ok(()),
267    };
268}
269
270/// What a record says besides its branch and commit.
271enum RecordKind<'a> {
272    /// A failed push, with Git's cleaned words.
273    Failed(&'a str),
274    /// A push the service did not make, with its cleaned words.
275    Skipped(&'a str),
276    /// A push lost with its worktree.
277    Lost,
278}
279
280/// The branch, the commit and the kind of a record written by this release.
281fn parse_record(text: &str) -> Option<(&str, &str, RecordKind<'_>)> {
282    let mut lines = text.splitn(5, '\n');
283    let magic: &str = lines.next()?;
284    if ![RECORD_MAGIC, SKIPPED_MAGIC, LOST_MAGIC].contains(&magic) {
285        return None;
286    }
287    let branch: &str = lines.next()?.strip_prefix(BRANCH_FIELD)?;
288    let commit: &str = lines.next()?.strip_prefix(COMMIT_FIELD)?;
289    if !lines.next()?.is_empty() {
290        return None;
291    }
292    let reason: &str = lines.next().unwrap_or("");
293    return Some((branch, commit, match magic {
294        LOST_MAGIC => RecordKind::Lost,
295        SKIPPED_MAGIC => RecordKind::Skipped(reason),
296        _ => RecordKind::Failed(reason),
297    }));
298}
299
300/// What:
301///  Removes the records of one branch, after a push of that branch succeeded.
302/// Why:
303///   A successful push of the branch carries every earlier commit of it, so an earlier failure is no longer true.
304///
305/// In TS you'd write (pseudocode):
306/// ```ts
307/// await clearPushFailures(gitDir, branchRef)
308/// ```
309pub fn clear_push_failures(git_dir: &Path, branch_ref: &str) {
310    clear_push_failures_before(git_dir, branch_ref, std::time::SystemTime::now());
311}
312
313/// What:
314///  Removes the records of one branch that were written no later than `cutoff`, after a push of that branch succeeded.
315/// Why:
316///   A push carries the commits that existed when it began. A record written after that moment is about a newer commit, which
317///  another instance of the service may have pushed and failed to push while this push's result was still being handled; the
318///  older push says nothing about it, so it stays.
319///
320/// In TS you'd write (pseudocode):
321/// ```ts
322/// await clearPushFailuresBefore(gitDir, branchRef, pushBegan)
323/// ```
324pub fn clear_push_failures_before(git_dir: &Path, branch_ref: &str, cutoff: std::time::SystemTime) {
325    let Ok(listing) = std::fs::read_dir(notice_directory(git_dir)) else { return };
326    let prefix: String = branch_prefix(branch_ref);
327    for entry in listing.flatten() {
328        let older: bool = entry.metadata().and_then(|meta| { return meta.modified(); }).is_ok_and(|written| { return written <= cutoff; });
329        if older && entry.file_name().to_string_lossy().starts_with(prefix.as_str()) {
330            let _removed = std::fs::remove_file(entry.path());
331        }
332    }
333}
334
335/// Where the worktrees of a repository stand: the branch the asking worktree has checked out and every branch any
336///  worktree has checked out.
337#[derive(Clone, Debug, Default, Eq, PartialEq)]
338pub struct Worktrees {
339    /// The branch reference the command's worktree has checked out; nothing for a detached head or an unknown worktree.
340    pub here: Option<String>,
341    /// The branch references checked out in every worktree of the repository.
342    pub all: Vec<String>,
343}
344
345/// What:
346///  The branch reference a `HEAD` file names, or nothing for a detached head or an unreadable file.
347/// Why:
348///   Only the plain `ref: refs/heads/<name>` form names a branch.
349///
350/// In TS you'd write (pseudocode):
351/// ```ts
352/// branchOfHead(gitDir)
353/// ```
354pub fn branch_of_head(git_dir: &Path) -> Option<String> {
355    let text: String = std::fs::read_to_string(git_dir.join("HEAD")).ok()?;
356    let target: &str = text.lines().next()?.strip_prefix("ref: ")?.trim();
357    return target.starts_with("refs/heads/").then(|| { return target.to_string(); });
358}
359
360/// What:
361///  The branches checked out in the repository's worktrees: the main one and each linked one.
362/// Why:
363///   A linked worktree keeps its own `HEAD` under `worktrees/<name>`; the main worktree's is the common directory's.
364///
365/// In TS you'd write (pseudocode):
366/// ```ts
367/// checkedOutBranches(commonDir)
368/// ```
369pub fn checked_out_branches(common_dir: &Path) -> Vec<String> {
370    let mut branches: Vec<String> = branch_of_head(common_dir).into_iter().collect();
371    if let Ok(listing) = std::fs::read_dir(common_dir.join("worktrees")) {
372        for entry in listing.flatten() {
373            branches.extend(branch_of_head(entry.path().as_path()));
374        }
375    }
376    return branches;
377}
378
379/// Whether a record of `branch_ref` is for the asking worktree: it has the branch checked out, or no worktree has.
380fn is_for(worktrees: &Worktrees, branch_ref: &str) -> bool {
381    return worktrees.here.as_deref() == Some(branch_ref) || !worktrees.all.iter().any(|held| { return held == branch_ref; });
382}
383
384/// What:
385///  Reads and removes the records that are for the asking worktree (all of them when no worktree is given), oldest name
386///  first, worded with the commit named by `abbreviate`.
387/// Why:
388///   A record is shown once, to the worktree whose commit it is about; another worktree's command leaves it where it is.
389///  When nothing failed the notice directory does not exist, and this is one directory read.
390///
391/// In TS you'd write (pseudocode):
392/// ```ts
393/// const texts = await takePushFailuresFor(gitDir, worktrees, abbreviate)
394/// ```
395pub fn take_push_failures_for(git_dir: &Path, worktrees: Option<&Worktrees>, abbreviate: &dyn Fn(&str) -> String) -> Vec<String> {
396    return take_records_from(notice_directory(git_dir).as_path(), worktrees, abbreviate);
397}
398
399/// What:
400///  Reads and removes the records of removed worktrees, which belong to no worktree and so are shown to the first command
401///  that asks.
402/// Why:
403///   The worktree a record was made for is gone, so nobody else could ever be shown it; one directory read when none exist.
404///
405/// In TS you'd write (pseudocode):
406/// ```ts
407/// const texts = await takeOrphanedFailures(commonDir, abbreviate)
408/// ```
409pub fn take_orphaned_failures(common_dir: &Path, abbreviate: &dyn Fn(&str) -> String) -> Vec<String> {
410    return take_records_from(common_dir.join(ORPHAN_NOTICE_DIRECTORY).as_path(), None, abbreviate);
411}
412
413/// Reads and removes the records in one directory that are for the asking worktree, oldest name first.
414fn take_records_from(directory: &Path, worktrees: Option<&Worktrees>, abbreviate: &dyn Fn(&str) -> String) -> Vec<String> {
415    let Ok(listing) = std::fs::read_dir(directory) else { return Vec::new() };
416    let mut paths: Vec<PathBuf> = listing.flatten().map(|entry| { return entry.path(); }).collect();
417    paths.sort();
418    let mut texts: Vec<String> = Vec::new();
419    for path in paths {
420        let Ok(text) = std::fs::read_to_string(path.as_path()) else { continue };
421        let parsed: Option<(&str, &str, RecordKind<'_>)> = parse_record(text.as_str());
422        if let (Some((branch, _, _)), Some(asking)) = (&parsed, worktrees)
423            && !is_for(asking, branch)
424        {
425            continue;
426        }
427        // The record is removed before its text is used, so two commands that start together cannot both show it.
428        if std::fs::remove_file(path.as_path()).is_err() {
429            continue;
430        }
431        texts.push(match parsed {
432            Some((branch, commit, RecordKind::Failed(reason))) => worded(branch, abbreviate(commit).as_str(), reason),
433            Some((branch, commit, RecordKind::Skipped(reason))) => worded_skipped(branch, abbreviate(commit).as_str(), reason),
434            Some((branch, commit, RecordKind::Lost)) => worded_lost(branch, abbreviate(commit).as_str()),
435            // The finished text an earlier release wrote.
436            None => text,
437        });
438    }
439    return texts;
440}
441
442/// What:
443///  Reads and removes every record, with each commit named in full.
444/// Why:
445///   The service's own controls and a repository with no worktree to ask need all of them.
446///
447/// In TS you'd write (pseudocode):
448/// ```ts
449/// const texts = await takePushFailures(gitDir)
450/// ```
451pub fn take_push_failures(git_dir: &Path) -> Vec<String> {
452    return take_push_failures_for(git_dir, None, &|commit| { return commit.to_string(); });
453}
454
455/// Commands that a program reads the output of, or that carry a protocol on their streams.
456const MACHINE_COMMANDS: &[&[u8]] = &[
457    b"cat-file", b"check-attr", b"check-ignore", b"check-ref-format", b"commit-tree", b"config", b"credential", b"diff-files",
458    b"diff-index", b"diff-tree", b"fast-export", b"fast-import", b"for-each-ref", b"hash-object", b"index-pack", b"ls-files",
459    b"ls-tree", b"merge-base", b"mktree", b"name-rev", b"pack-objects", b"read-tree", b"receive-pack", b"rev-list",
460    b"rev-parse", b"show-ref", b"symbolic-ref", b"unpack-objects", b"update-ref", b"upload-archive", b"upload-pack",
461    b"var", b"write-tree", b"update-index", b"verify-pack",
462];
463
464/// Option spellings that ask a command for output made to be read by a program.
465fn asks_for_machine_output(option: &[u8]) -> bool {
466    return option == b"-z"
467        || option == b"--null"
468        || option.starts_with(b"--porcelain")
469        || option.starts_with(b"--format")
470        || option.starts_with(b"--pretty");
471}
472
473/// What:
474///  Whether a command's output is read by a program, so that no record may be shown to it or taken from it.
475/// Why:
476///   A prompt, an editor or a script runs `git status --porcelain` or `git rev-parse` often and reads every byte; the
477///  record is meant for the person, and the first such call would otherwise take it.
478///
479/// In TS you'd write (pseudocode):
480/// ```ts
481/// isMachineRead(commandWord, region)
482/// ```
483pub fn is_machine_read(command: &[u8], region: &[OsString]) -> bool {
484    if MACHINE_COMMANDS.contains(&command) {
485        return true;
486    }
487    for argument in region {
488        let bytes: &[u8] = argument.as_encoded_bytes();
489        // Everything after the separator is a name, not an option.
490        if bytes == b"--" {
491            break;
492        }
493        if asks_for_machine_output(bytes) {
494            return true;
495        }
496    }
497    return false;
498}
499
500/// Record controls stay out of the release executable.
501#[cfg(test)]
502#[path = "push_failure_notice_tests.rs"]
503mod tests;