Skip to main content

git_policy_cli/landing/
service_messages.rs

1//! What:
2//!  Everything the wrapper tells the user when it cannot get a commit landed by the resident service, and the notices
3//!  it prints while it waits.
4//! Why:
5//!  A failure the system can resolve is resolved without the user; the rest ends the command with plain words, the
6//!  affected input named, every remedy given, and no implementation term (`doc/planning/cli-git-resident-service.md`,
7//!  "Failures the client can meet"). The texts live here as constants so a test can check each against a list of terms
8//!  that must never reach a user, and so the text a client prints cannot drift from the text the tests read.
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! stderr.write(render({ kind: 'not-installed' }));
13//! ```
14
15use std::path::Path;
16
17/// The command that shows why the service did not start (Linux with systemd).
18pub const LOG_COMMAND: &str = "journalctl --user --unit 'cli-git@*.service'";
19
20/// The command that turns on user services for an account that is not logged in (Linux with systemd).
21pub const LINGER_COMMAND: &str = "loginctl enable-linger";
22
23/// The command that restarts the commit service, so the manager starts the one the installed units name (Linux with systemd).
24pub const RESTART_COMMAND: &str = "systemctl --user restart 'cli-git@*.service'";
25
26/// The commands that show whether the commit was made.
27pub const CHECK_COMMANDS: [&str; 2] = ["git log -1", "git status"];
28
29/// Printed once when the service takes longer than the grace to answer.
30pub const STARTING_NOTICE: &str = "Starting the commit service...";
31
32/// Printed each time the service goes silent while a commit waits, before the same request is sent to it again.
33pub const SILENT_NOTICE: &str = "The commit service stopped answering; asking it again with the same commit, which cannot land twice.";
34
35/// Printed once when the service is being replaced by a newer one.
36pub const UPDATING_NOTICE: &str = "Updating the commit service...";
37
38/// What:
39///  Where the client cannot get a service from the operating system.
40/// Why:
41///   Each platform has its own remedy, and none has a second way to commit.
42///
43/// In TS you'd write (pseudocode):
44/// ```ts
45/// type Platform = 'windows' | 'bsd' | 'linux-without-user-services' | 'other';
46/// ```
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub enum Platform {
49    /// Windows, where activation is designed but not built.
50    Windows,
51    /// A BSD system.
52    Bsd,
53    /// Linux with no user service manager (minimal containers, WSL 1, other init systems).
54    LinuxWithoutUserServices,
55    /// Any other system.
56    Other,
57}
58
59/// What:
60///  Every failure that reaches the user, with the facts its text names.
61/// Why:
62///   The set is closed, so a test renders all of them.
63///
64/// In TS you'd write (pseudocode):
65/// ```ts
66/// type ClientFailure = { kind: 'not-installed' } | { kind: 'did-not-start' } | ...;
67/// ```
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub enum ClientFailure {
70    /// The service was started and did not come up.
71    DidNotStart,
72    /// The platform cannot start the service on demand.
73    NoActivation(Platform),
74    /// The service on the socket belongs to another account.
75    OtherAccount,
76    /// The service stopped before it confirmed the commit.
77    MayNotHaveLanded,
78    /// The installed service speaks no protocol this wrapper speaks, after a replacement attempt.
79    NoCommonVersion,
80    /// A service started from another release of the wrapper is still running after it was asked to exit.
81    OtherRelease,
82    /// The repository has no room left.
83    RepositoryFull(String),
84    /// The repository cannot be written.
85    RepositoryReadOnly(String),
86    /// The branch changed while the commit was prepared, `times` times.
87    BranchKeepsChanging { branch: String, times: usize },
88    /// The branch was no longer where the amended commit was prepared, so the amend was not made.
89    BranchMoved { branch: String },
90    /// The branch moved while the person wrote a message; the message is saved in `file` for them to reuse.
91    BranchMovedMessageSaved { branch: String, file: String, amend: bool },
92    /// The worktree switched from `branch` to `now` while the commit was prepared; the message the person wrote, if any, is
93    ///  saved in `file`.
94    BranchSwitched { branch: String, now: String, file: Option<String> },
95    /// The service sent nothing for longer than it ever stays silent while it works, on every try to ask it again.
96    ServiceSilent,
97    /// The service kept the request for `minutes` minutes without answering, and the client withdrew it: it will not land.
98    StillWithService { minutes: u64, blocker: Option<String> },
99    /// The client stopped waiting and could not confirm the service withdrew the request.
100    WithdrawalUnconfirmed,
101    /// A Git step of the landing ran longer than the wrapper allows and was ended; the commit was withdrawn and kept.
102    StepTooSlow,
103    /// The request was refused as malformed or unsafe.
104    Refused,
105    /// Another program holds the repository's index.
106    IndexInUse(String),
107    /// The service failed in a way it could not resolve.
108    Unavailable,
109    /// The service program is not next to the wrapper.
110    ProgramMissing(String),
111    /// Setting up the service failed for a reason the person can act on.
112    CouldNotStart(String),
113    /// A unit file of the same name that something else wrote stands in the way.
114    UnitInTheWay(String),
115    /// The commit is saved but the backup push and upkeep could not be handed over.
116    WorkNotHandedOver(String),
117    /// The content prepared for the commit was removed from the repository before the commit landed, twice.
118    ContentPruned,
119}
120
121/// The sentence every failure ends with when nothing was changed.
122pub const NOTHING_CHANGED: &str = "Nothing in the repository changed.";
123
124/// What:
125///  The text for a failure.
126/// Why:
127///   Plain words, the input named, every remedy; nothing about how the service works.
128///
129/// In TS you'd write (pseudocode):
130/// ```ts
131/// render(failure): string
132/// ```
133pub fn render(failure: &ClientFailure) -> String {
134    return match failure {
135        ClientFailure::DidNotStart => format!(
136            "The commit service did not start, so this commit was not made. Its log shows why: `{LOG_COMMAND}`. \
137             Run the commit again after fixing that. {NOTHING_CHANGED}"
138        ),
139        ClientFailure::NoActivation(platform) => format!(
140            "This computer cannot start the commit service on demand, so this commit was not made. {} {NOTHING_CHANGED}",
141            platform_remedy(*platform)
142        ),
143        ClientFailure::OtherAccount => format!(
144            "Another account runs the commit service here, so this commit was not made. Use your own account, or ask \
145             the other account to stop its service, then run the commit again. {NOTHING_CHANGED}"
146        ),
147        ClientFailure::MayNotHaveLanded => format!(
148            "The commit service stopped before it confirmed this commit. Run `{}` to see whether it was made, and `{}` \
149             to see what is still staged. If it was not made, run the commit again.",
150            CHECK_COMMANDS[0], CHECK_COMMANDS[1]
151        ),
152        ClientFailure::NoCommonVersion => format!(
153            "This git is older than the installed commit service and cannot work with it, so this commit was not made. \
154             Update the git wrapper with the tool that installed it, and run the commit again. {NOTHING_CHANGED}"
155        ),
156        ClientFailure::OtherRelease => format!(
157            "The commit service that is running was started from another release of this git wrapper and did not stop when \
158             asked, so this commit was not made. Restart it with `{RESTART_COMMAND}`, and run the commit again. {NOTHING_CHANGED}"
159        ),
160        ClientFailure::RepositoryFull(path) => format!(
161            "There is no space left for {path}, so this commit was not made. Free some space and run the commit again. \
162             {NOTHING_CHANGED}"
163        ),
164        ClientFailure::RepositoryReadOnly(path) => format!(
165            "{path} cannot be written to, so this commit was not made. Make the repository writable (check its \
166             permissions and whether the disk is mounted read-only) and run the commit again. {NOTHING_CHANGED}"
167        ),
168        ClientFailure::BranchKeepsChanging { branch, times } => format!(
169            "The branch {branch} changed {times} times while this commit was being prepared, so it was not made. Run \
170             the commit again; if other people commit to the same branch at the same moment, it will succeed once they \
171             pause. {NOTHING_CHANGED}"
172        ),
173        ClientFailure::BranchMoved { branch } => format!(
174            "The branch {branch} moved while this commit was being prepared, and a commit that replaces the last one, or one \
175             that was written or signed by hand, cannot be moved onto a different last commit, so it was not made. Run the \
176             commit again to make it on the branch as it is now. {NOTHING_CHANGED}"
177        ),
178        ClientFailure::BranchMovedMessageSaved { branch, file, amend } => format!(
179            "The branch {branch} moved while this commit was being prepared, so it was not made. The message you wrote is saved \
180             in {file}. Run `git commit {}-F {file}` to make the commit on the branch as it is now. {NOTHING_CHANGED}",
181            if *amend { "--amend " } else { "" }
182        ),
183        ClientFailure::BranchSwitched { branch, now, file } => format!(
184            "The worktree switched from {branch} to {now} while this commit was being prepared, so it was not made. {} Switch back \
185             to {branch} and run the commit again, or run it here to commit on {now}. {NOTHING_CHANGED}",
186            match file {
187                Some(saved) => format!("The message you wrote is saved in {saved}; `git commit -F {saved}` uses it."),
188                None => String::new(),
189            }
190        ),
191        ClientFailure::ServiceSilent => format!(
192            "The commit service stopped answering while this commit waited, and it did not answer when asked again, so it is \
193             not known whether the commit was made. Run `{}` to see whether it was made, and `{}` to see what is still \
194             staged. If it was not made, look at why the service is stuck with `{LOG_COMMAND}`, restart it with \
195             `{RESTART_COMMAND}`, and run the commit again.",
196            CHECK_COMMANDS[0], CHECK_COMMANDS[1]
197        ),
198        ClientFailure::StillWithService { minutes, blocker } => format!(
199            "This commit waited {minutes} minutes for the commit service and was withdrawn, so it will not land later by itself.{} \
200             Your staged changes and your worktree are as they were. Run the commit again; if the service is stuck, look at why with \
201             `{LOG_COMMAND}` and restart it with `{RESTART_COMMAND}`. {NOTHING_CHANGED}",
202            blocker.as_ref().map_or_else(String::new, |text| { return format!(" It was waiting for: {text}."); })
203        ),
204        ClientFailure::WithdrawalUnconfirmed => format!(
205            "This commit waited for the commit service until the longest wait the wrapper allows, and the service did not confirm \
206             that it withdrew it, so it is not known whether the commit was made. Run `{}` to see whether it was made, and `{}` to \
207             see what is still staged. If it was not made, run the commit again; if the service is stuck, look at why with \
208             `{LOG_COMMAND}` and restart it with `{RESTART_COMMAND}`.",
209            CHECK_COMMANDS[0], CHECK_COMMANDS[1]
210        ),
211        ClientFailure::StepTooSlow => format!(
212            "A Git step of this commit ran longer than the commit service allows and was ended, so this commit was not made and will not \
213             land later by itself. The step is named above, and the commit built for you is kept on the side ref named there when one \
214             is. Run the commit again; if it happens again, look at why with `{LOG_COMMAND}`. {NOTHING_CHANGED}"
215        ),
216        ClientFailure::Refused => format!(
217            "The commit service refused this commit because it names a path or a value that cannot be committed, so it \
218             was not made. Check the paths you passed to the commit. {NOTHING_CHANGED}"
219        ),
220        ClientFailure::IndexInUse(holder) => format!(
221            "{holder} is using this repository's index, so this commit was not made. Wait for it to finish, or close \
222             it, and run the commit again. {NOTHING_CHANGED}"
223        ),
224        ClientFailure::ProgramMissing(path) => format!(
225            "The commit service program was not found at {path}, so this commit was not made. Reinstall the git wrapper \
226             with the tool that installed it, so that the program sits next to it, then run the commit again. \
227             {NOTHING_CHANGED}"
228        ),
229        ClientFailure::UnitInTheWay(path) => format!(
230            "The file `{path}` has the name of a settings file of the commit service but was not written by the git wrapper, \
231             so the commit service could not be set up and this commit was not made. Move or delete that file, then run the \
232             commit again. {NOTHING_CHANGED}"
233        ),
234        ClientFailure::WorkNotHandedOver(reason) => format!(
235            "Your commit is saved. Its backup push and upkeep could not be handed to the commit service: {reason}. \
236             Run `git push` when ready."
237        ),
238        ClientFailure::ContentPruned => format!(
239            "The files of this commit were removed from the repository while the commit was being made, so it was not made. \
240             Git removes content that no branch or index refers to yet when `git gc --prune=now` or `git prune` runs in the \
241             same repository, and Git's documentation says that `--prune=now` risks failures and corruption when another \
242             process writes to the repository at the same moment. Run the commit again once the cleanup has finished, and avoid `--prune=now` while commits are \
243             being made (the default `git gc` keeps new content for two weeks). If nothing like that was running, run \
244             `git fsck` to check the repository. {NOTHING_CHANGED}"
245        ),
246        ClientFailure::CouldNotStart(reason) => format!(
247            "The commit service could not be set up, so this commit was not made: {reason}. Fix that and run the commit \
248             again. {NOTHING_CHANGED}"
249        ),
250        ClientFailure::Unavailable => format!(
251            "The commit service could not finish this commit, so it was not made. Run the commit again; if it fails \
252             again, look at the service's log with `{LOG_COMMAND}`. {NOTHING_CHANGED}"
253        ),
254    };
255}
256
257/// What:
258///  The remedy sentence for a platform.
259/// Why:
260///   Windows and the BSD systems have no activation yet; Linux without user services can turn them on.
261///
262/// In TS you'd write (pseudocode):
263/// ```ts
264/// platformRemedy(platform)
265/// ```
266pub fn platform_remedy(platform: Platform) -> String {
267    return match platform {
268        Platform::Windows => String::from(
269            "Committing through this wrapper is not supported on Windows yet. Use the Linux or macOS machine for commits \
270             to this repository.",
271        ),
272        Platform::Bsd => String::from(
273            "Committing through this wrapper is not supported on this system yet. Use a Linux or macOS machine for \
274             commits to this repository.",
275        ),
276        Platform::LinuxWithoutUserServices => format!(
277            "This account has no user service manager. Turn it on with `{LINGER_COMMAND}` (the system must run \
278             systemd), or commit from a system that does."
279        ),
280        Platform::Other => String::from(
281            "Committing through this wrapper is not supported on this system. Use a Linux or macOS machine for \
282             commits to this repository.",
283        ),
284    };
285}
286
287/// What:
288///  The notice for a commit that waits behind others.
289/// Why:
290///   The position is the one fact the person needs: how many commits go first.
291///
292/// In TS you'd write (pseudocode):
293/// ```ts
294/// positionNotice(number, of)
295/// ```
296pub fn position_notice(number: usize, of: usize) -> String {
297    let ahead: usize = number.saturating_sub(1);
298    let _ = of;
299    return match ahead {
300        0 => String::from("This commit is next."),
301        1 => String::from("Waiting for 1 earlier commit."),
302        many => format!("Waiting for {many} earlier commits."),
303    };
304}
305
306/// The texts that must never reach a user: implementation terms the system should have resolved itself.
307///  Matched case-insensitively against whole words after the quoted commands are removed.
308pub const DENYLIST: [&str; 22] = [
309    "protocol", "journal", "request id", "daemon", "socket", "errno", "epipe", "econnrefused", "eagain", "flock",
310    "lock file", "peer", "frame", "handshake", "batch", "oid", "fast-import", "unix domain", "abstract", "pid",
311    "uid", "os error",
312];
313
314/// The repository path a failure names, as text.
315pub fn path_text(path: &Path) -> String {
316    return path.display().to_string();
317}
318
319/// Message controls stay out of the release executable.
320#[cfg(test)]
321#[path = "service_messages_tests.rs"]
322mod tests;