Skip to main content

git_policy_cli/
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 commands that show whether the commit was made.
24pub const CHECK_COMMANDS: [&str; 2] = ["git log -1", "git status"];
25
26/// Printed once when the service takes longer than the grace to answer.
27pub const STARTING_NOTICE: &str = "Starting the commit service...";
28
29/// Printed once when the service is being replaced by a newer one.
30pub const UPDATING_NOTICE: &str = "Updating the commit service...";
31
32/// What:
33///  Where the client cannot get a service from the operating system.
34/// Why:
35///   Each platform has its own remedy, and none has a second way to commit.
36///
37/// In TS you'd write (pseudocode):
38/// ```ts
39/// type Platform = 'windows' | 'bsd' | 'linux-without-user-services' | 'other';
40/// ```
41#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42pub enum Platform {
43    /// Windows, where activation is designed but not built.
44    Windows,
45    /// A BSD system.
46    Bsd,
47    /// Linux with no user service manager (minimal containers, WSL 1, other init systems).
48    LinuxWithoutUserServices,
49    /// Any other system.
50    Other,
51}
52
53/// What:
54///  Every failure that reaches the user, with the facts its text names.
55/// Why:
56///   The set is closed, so a test renders all of them.
57///
58/// In TS you'd write (pseudocode):
59/// ```ts
60/// type ClientFailure = { kind: 'not-installed' } | { kind: 'did-not-start' } | ...;
61/// ```
62#[derive(Clone, Debug, Eq, PartialEq)]
63pub enum ClientFailure {
64    /// The service was started and did not come up.
65    DidNotStart,
66    /// The platform cannot start the service on demand.
67    NoActivation(Platform),
68    /// The service on the socket belongs to another account.
69    OtherAccount,
70    /// The service stopped before it confirmed the commit.
71    MayNotHaveLanded,
72    /// The installed service speaks no protocol this wrapper speaks, after a replacement attempt.
73    NoCommonVersion,
74    /// The repository has no room left.
75    RepositoryFull(String),
76    /// The repository cannot be written.
77    RepositoryReadOnly(String),
78    /// The branch changed while the commit was prepared, `times` times.
79    BranchKeepsChanging { branch: String, times: usize },
80    /// The branch was no longer where the amended commit was prepared, so the amend was not made.
81    BranchMoved { branch: String },
82    /// The branch moved while the person wrote a message; the message is saved in `file` for them to reuse.
83    BranchMovedMessageSaved { branch: String, file: String, amend: bool },
84    /// The commit waited `minutes` minutes behind others.
85    WaitedTooLong { minutes: u64 },
86    /// The request was refused as malformed or unsafe.
87    Refused,
88    /// Another program holds the repository's index.
89    IndexInUse(String),
90    /// The service failed in a way it could not resolve.
91    Unavailable,
92    /// The service program is not next to the wrapper.
93    ProgramMissing(String),
94    /// Setting up the service failed for a reason the person can act on.
95    CouldNotStart(String),
96    /// A unit file of the same name that something else wrote stands in the way.
97    UnitInTheWay(String),
98    /// The commit is saved but the backup push and upkeep could not be handed over.
99    WorkNotHandedOver(String),
100}
101
102/// The sentence every failure ends with when nothing was changed.
103const NOTHING_CHANGED: &str = "Nothing in the repository changed.";
104
105/// What:
106///  The text for a failure.
107/// Why:
108///   Plain words, the input named, every remedy; nothing about how the service works.
109///
110/// In TS you'd write (pseudocode):
111/// ```ts
112/// render(failure): string
113/// ```
114pub fn render(failure: &ClientFailure) -> String {
115    return match failure {
116        ClientFailure::DidNotStart => format!(
117            "The commit service did not start, so this commit was not made. Its log shows why: `{LOG_COMMAND}`. \
118             Run the commit again after fixing that. {NOTHING_CHANGED}"
119        ),
120        ClientFailure::NoActivation(platform) => format!(
121            "This computer cannot start the commit service on demand, so this commit was not made. {} {NOTHING_CHANGED}",
122            platform_remedy(*platform)
123        ),
124        ClientFailure::OtherAccount => format!(
125            "Another account runs the commit service here, so this commit was not made. Use your own account, or ask \
126             the other account to stop its service, then run the commit again. {NOTHING_CHANGED}"
127        ),
128        ClientFailure::MayNotHaveLanded => format!(
129            "The commit service stopped before it confirmed this commit. Run `{}` to see whether it was made, and `{}` \
130             to see what is still staged. If it was not made, run the commit again.",
131            CHECK_COMMANDS[0], CHECK_COMMANDS[1]
132        ),
133        ClientFailure::NoCommonVersion => format!(
134            "This git is older than the installed commit service and cannot work with it, so this commit was not made. \
135             Update the git wrapper with the tool that installed it, and run the commit again. {NOTHING_CHANGED}"
136        ),
137        ClientFailure::RepositoryFull(path) => format!(
138            "There is no space left for {path}, so this commit was not made. Free some space and run the commit again. \
139             {NOTHING_CHANGED}"
140        ),
141        ClientFailure::RepositoryReadOnly(path) => format!(
142            "{path} cannot be written to, so this commit was not made. Make the repository writable (check its \
143             permissions and whether the disk is mounted read-only) and run the commit again. {NOTHING_CHANGED}"
144        ),
145        ClientFailure::BranchKeepsChanging { branch, times } => format!(
146            "The branch {branch} changed {times} times while this commit was being prepared, so it was not made. Run \
147             the commit again; if other people commit to the same branch at the same moment, it will succeed once they \
148             pause. {NOTHING_CHANGED}"
149        ),
150        ClientFailure::BranchMoved { branch } => format!(
151            "The branch {branch} moved while this commit was being prepared, and a commit that replaces the last one, or one \
152             that was written or signed by hand, cannot be moved onto a different last commit, so it was not made. Run the \
153             commit again to make it on the branch as it is now. {NOTHING_CHANGED}"
154        ),
155        ClientFailure::BranchMovedMessageSaved { branch, file, amend } => format!(
156            "The branch {branch} moved while this commit was being prepared, so it was not made. The message you wrote is saved \
157             in {file}. Run `git commit {}-F {file}` to make the commit on the branch as it is now. {NOTHING_CHANGED}",
158            if *amend { "--amend " } else { "" }
159        ),
160        ClientFailure::WaitedTooLong { minutes } => format!(
161            "This commit waited {minutes} minutes behind other commits and was not made. Run it again later, or raise \
162             the waiting limit in the settings for the wrapper. {NOTHING_CHANGED}"
163        ),
164        ClientFailure::Refused => format!(
165            "The commit service refused this commit because it names a path or a value that cannot be committed, so it \
166             was not made. Check the paths you passed to the commit. {NOTHING_CHANGED}"
167        ),
168        ClientFailure::IndexInUse(holder) => format!(
169            "{holder} is using this repository's index, so this commit was not made. Wait for it to finish, or close \
170             it, and run the commit again. {NOTHING_CHANGED}"
171        ),
172        ClientFailure::ProgramMissing(path) => format!(
173            "The commit service program was not found at {path}, so this commit was not made. Reinstall the git wrapper \
174             with the tool that installed it, so that the program sits next to it, then run the commit again. \
175             {NOTHING_CHANGED}"
176        ),
177        ClientFailure::UnitInTheWay(path) => format!(
178            "The file `{path}` has the name of a settings file of the commit service but was not written by the git wrapper, \
179             so the commit service could not be set up and this commit was not made. Move or delete that file, then run the \
180             commit again. {NOTHING_CHANGED}"
181        ),
182        ClientFailure::WorkNotHandedOver(reason) => format!(
183            "Your commit is saved. Its backup push and upkeep could not be handed to the commit service: {reason}. \
184             Run `git push` when ready."
185        ),
186        ClientFailure::CouldNotStart(reason) => format!(
187            "The commit service could not be set up, so this commit was not made: {reason}. Fix that and run the commit \
188             again. {NOTHING_CHANGED}"
189        ),
190        ClientFailure::Unavailable => format!(
191            "The commit service could not finish this commit, so it was not made. Run the commit again; if it fails \
192             again, look at the service's log with `{LOG_COMMAND}`. {NOTHING_CHANGED}"
193        ),
194    };
195}
196
197/// What:
198///  The remedy sentence for a platform.
199/// Why:
200///   Windows and the BSD systems have no activation yet; Linux without user services can turn them on.
201///
202/// In TS you'd write (pseudocode):
203/// ```ts
204/// platformRemedy(platform)
205/// ```
206pub fn platform_remedy(platform: Platform) -> String {
207    return match platform {
208        Platform::Windows => String::from(
209            "Committing through this wrapper is not supported on Windows yet. Use the Linux or macOS machine for commits \
210             to this repository.",
211        ),
212        Platform::Bsd => String::from(
213            "Committing through this wrapper is not supported on this system yet. Use a Linux or macOS machine for \
214             commits to this repository.",
215        ),
216        Platform::LinuxWithoutUserServices => format!(
217            "This account has no user service manager. Turn it on with `{LINGER_COMMAND}` (the system must run \
218             systemd), or commit from a system that does."
219        ),
220        Platform::Other => String::from(
221            "Committing through this wrapper is not supported on this system. Use a Linux or macOS machine for \
222             commits to this repository.",
223        ),
224    };
225}
226
227/// What:
228///  The notice for a commit that waits behind others.
229/// Why:
230///   The position is the one fact the person needs: how many commits go first.
231///
232/// In TS you'd write (pseudocode):
233/// ```ts
234/// positionNotice(number, of)
235/// ```
236pub fn position_notice(number: usize, of: usize) -> String {
237    let ahead: usize = number.saturating_sub(1);
238    let _ = of;
239    return match ahead {
240        0 => String::from("This commit is next."),
241        1 => String::from("Waiting for 1 earlier commit."),
242        many => format!("Waiting for {many} earlier commits."),
243    };
244}
245
246/// What:
247///  The notice for a backup push that failed after its commit was saved.
248/// Why:
249///   The push runs after the commit returned, so the person learns of a failure at their next commit. The service has
250///  its own environment, which is the first thing to check when a push that works in a terminal fails here.
251///
252/// In TS you'd write (pseudocode):
253/// ```ts
254/// pushFailedNotice(commit, said)
255/// ```
256pub fn push_failed_notice(commit: &str, said: &str) -> String {
257    let short: &str = commit.get(..7).unwrap_or(commit);
258    let detail: String = if said.is_empty() { String::from("Git gave no reason.") } else { format!("Git said: {said}") };
259    return format!(
260        "The backup push of your commit {short} failed, so it exists only on this computer for now. {detail} The commit \
261         service runs with its own settings, not your terminal's, so a push that works in your terminal can fail here \
262         when it needs a variable your terminal has. Run `git push` when ready."
263    );
264}
265
266/// The texts that must never reach a user: implementation terms the system should have resolved itself.
267///  Matched case-insensitively against whole words after the quoted commands are removed.
268pub const DENYLIST: [&str; 22] = [
269    "protocol", "journal", "request id", "daemon", "socket", "errno", "epipe", "econnrefused", "eagain", "flock",
270    "lock file", "peer", "frame", "handshake", "batch", "oid", "fast-import", "unix domain", "abstract", "pid",
271    "uid", "os error",
272];
273
274/// The repository path a failure names, as text.
275pub fn path_text(path: &Path) -> String {
276    return path.display().to_string();
277}
278
279/// Message controls stay out of the release executable.
280#[cfg(test)]
281#[path = "service_messages_tests.rs"]
282mod tests;