jj_cli/
command_error.rs

1// Copyright 2022-2024 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::error;
16use std::error::Error as _;
17use std::io;
18use std::io::Write as _;
19use std::iter;
20use std::sync::Arc;
21
22use itertools::Itertools as _;
23use jj_lib::absorb::AbsorbError;
24use jj_lib::backend::BackendError;
25use jj_lib::backend::CommitId;
26use jj_lib::bisect::BisectionError;
27use jj_lib::config::ConfigFileSaveError;
28use jj_lib::config::ConfigGetError;
29use jj_lib::config::ConfigLoadError;
30use jj_lib::config::ConfigMigrateError;
31use jj_lib::dsl_util::Diagnostics;
32use jj_lib::evolution::WalkPredecessorsError;
33use jj_lib::fileset::FilePatternParseError;
34use jj_lib::fileset::FilesetParseError;
35use jj_lib::fileset::FilesetParseErrorKind;
36use jj_lib::fix::FixError;
37use jj_lib::gitignore::GitIgnoreError;
38use jj_lib::index::IndexError;
39use jj_lib::op_heads_store::OpHeadResolutionError;
40use jj_lib::op_heads_store::OpHeadsStoreError;
41use jj_lib::op_store::OpStoreError;
42use jj_lib::op_walk::OpsetEvaluationError;
43use jj_lib::op_walk::OpsetResolutionError;
44use jj_lib::repo::CheckOutCommitError;
45use jj_lib::repo::EditCommitError;
46use jj_lib::repo::RepoLoaderError;
47use jj_lib::repo::RewriteRootCommit;
48use jj_lib::repo_path::RepoPathBuf;
49use jj_lib::repo_path::UiPathParseError;
50use jj_lib::revset;
51use jj_lib::revset::RevsetEvaluationError;
52use jj_lib::revset::RevsetParseError;
53use jj_lib::revset::RevsetParseErrorKind;
54use jj_lib::revset::RevsetResolutionError;
55use jj_lib::str_util::StringPatternParseError;
56use jj_lib::trailer::TrailerParseError;
57use jj_lib::transaction::TransactionCommitError;
58use jj_lib::view::RenameWorkspaceError;
59use jj_lib::working_copy::RecoverWorkspaceError;
60use jj_lib::working_copy::ResetError;
61use jj_lib::working_copy::SnapshotError;
62use jj_lib::working_copy::WorkingCopyStateError;
63use jj_lib::workspace::WorkspaceInitError;
64use thiserror::Error;
65
66use crate::cli_util::short_operation_hash;
67use crate::description_util::ParseBulkEditMessageError;
68use crate::description_util::TempTextEditError;
69use crate::description_util::TextEditError;
70use crate::diff_util::DiffRenderError;
71use crate::formatter::FormatRecorder;
72use crate::formatter::Formatter;
73use crate::formatter::FormatterExt as _;
74use crate::merge_tools::ConflictResolveError;
75use crate::merge_tools::DiffEditError;
76use crate::merge_tools::MergeToolConfigError;
77use crate::merge_tools::MergeToolPartialResolutionError;
78use crate::revset_util::BookmarkNameParseError;
79use crate::revset_util::TagNameParseError;
80use crate::revset_util::UserRevsetEvaluationError;
81use crate::template_parser::TemplateParseError;
82use crate::template_parser::TemplateParseErrorKind;
83use crate::ui::Ui;
84
85#[derive(Clone, Copy, Debug, Eq, PartialEq)]
86pub enum CommandErrorKind {
87    User,
88    Config,
89    /// Invalid command line. The inner error type may be `clap::Error`.
90    Cli,
91    BrokenPipe,
92    Internal,
93}
94
95#[derive(Clone, Debug)]
96pub struct CommandError {
97    pub kind: CommandErrorKind,
98    pub error: Arc<dyn error::Error + Send + Sync>,
99    pub hints: Vec<ErrorHint>,
100}
101
102impl CommandError {
103    pub fn new(
104        kind: CommandErrorKind,
105        err: impl Into<Box<dyn error::Error + Send + Sync>>,
106    ) -> Self {
107        Self {
108            kind,
109            error: Arc::from(err.into()),
110            hints: vec![],
111        }
112    }
113
114    pub fn with_message(
115        kind: CommandErrorKind,
116        message: impl Into<String>,
117        source: impl Into<Box<dyn error::Error + Send + Sync>>,
118    ) -> Self {
119        Self::new(kind, ErrorWithMessage::new(message, source))
120    }
121
122    /// Returns error with the given plain-text `hint` attached.
123    pub fn hinted(mut self, hint: impl Into<String>) -> Self {
124        self.add_hint(hint);
125        self
126    }
127
128    /// Appends plain-text `hint` to the error.
129    pub fn add_hint(&mut self, hint: impl Into<String>) {
130        self.hints.push(ErrorHint::PlainText(hint.into()));
131    }
132
133    /// Appends formatted `hint` to the error.
134    pub fn add_formatted_hint(&mut self, hint: FormatRecorder) {
135        self.hints.push(ErrorHint::Formatted(hint));
136    }
137
138    /// Constructs formatted hint and appends it to the error.
139    pub fn add_formatted_hint_with(
140        &mut self,
141        write: impl FnOnce(&mut dyn Formatter) -> io::Result<()>,
142    ) {
143        let mut formatter = FormatRecorder::new();
144        write(&mut formatter).expect("write() to FormatRecorder should never fail");
145        self.add_formatted_hint(formatter);
146    }
147
148    /// Appends 0 or more plain-text `hints` to the error.
149    pub fn extend_hints(&mut self, hints: impl IntoIterator<Item = String>) {
150        self.hints
151            .extend(hints.into_iter().map(ErrorHint::PlainText));
152    }
153}
154
155#[derive(Clone, Debug)]
156pub enum ErrorHint {
157    PlainText(String),
158    Formatted(FormatRecorder),
159}
160
161/// Wraps error with user-visible message.
162#[derive(Debug, Error)]
163#[error("{message}")]
164struct ErrorWithMessage {
165    message: String,
166    source: Box<dyn error::Error + Send + Sync>,
167}
168
169impl ErrorWithMessage {
170    fn new(
171        message: impl Into<String>,
172        source: impl Into<Box<dyn error::Error + Send + Sync>>,
173    ) -> Self {
174        Self {
175            message: message.into(),
176            source: source.into(),
177        }
178    }
179}
180
181pub fn user_error(err: impl Into<Box<dyn error::Error + Send + Sync>>) -> CommandError {
182    CommandError::new(CommandErrorKind::User, err)
183}
184
185pub fn user_error_with_hint(
186    err: impl Into<Box<dyn error::Error + Send + Sync>>,
187    hint: impl Into<String>,
188) -> CommandError {
189    user_error(err).hinted(hint)
190}
191
192pub fn user_error_with_message(
193    message: impl Into<String>,
194    source: impl Into<Box<dyn error::Error + Send + Sync>>,
195) -> CommandError {
196    CommandError::with_message(CommandErrorKind::User, message, source)
197}
198
199pub fn config_error(err: impl Into<Box<dyn error::Error + Send + Sync>>) -> CommandError {
200    CommandError::new(CommandErrorKind::Config, err)
201}
202
203pub fn config_error_with_message(
204    message: impl Into<String>,
205    source: impl Into<Box<dyn error::Error + Send + Sync>>,
206) -> CommandError {
207    CommandError::with_message(CommandErrorKind::Config, message, source)
208}
209
210pub fn cli_error(err: impl Into<Box<dyn error::Error + Send + Sync>>) -> CommandError {
211    CommandError::new(CommandErrorKind::Cli, err)
212}
213
214pub fn cli_error_with_message(
215    message: impl Into<String>,
216    source: impl Into<Box<dyn error::Error + Send + Sync>>,
217) -> CommandError {
218    CommandError::with_message(CommandErrorKind::Cli, message, source)
219}
220
221pub fn internal_error(err: impl Into<Box<dyn error::Error + Send + Sync>>) -> CommandError {
222    CommandError::new(CommandErrorKind::Internal, err)
223}
224
225pub fn internal_error_with_message(
226    message: impl Into<String>,
227    source: impl Into<Box<dyn error::Error + Send + Sync>>,
228) -> CommandError {
229    CommandError::with_message(CommandErrorKind::Internal, message, source)
230}
231
232fn format_similarity_hint<S: AsRef<str>>(candidates: &[S]) -> Option<String> {
233    match candidates {
234        [] => None,
235        names => {
236            let quoted_names = names.iter().map(|s| format!("`{}`", s.as_ref())).join(", ");
237            Some(format!("Did you mean {quoted_names}?"))
238        }
239    }
240}
241
242impl From<io::Error> for CommandError {
243    fn from(err: io::Error) -> Self {
244        let kind = match err.kind() {
245            io::ErrorKind::BrokenPipe => CommandErrorKind::BrokenPipe,
246            _ => CommandErrorKind::User,
247        };
248        Self::new(kind, err)
249    }
250}
251
252impl From<jj_lib::file_util::PathError> for CommandError {
253    fn from(err: jj_lib::file_util::PathError) -> Self {
254        user_error(err)
255    }
256}
257
258impl From<ConfigFileSaveError> for CommandError {
259    fn from(err: ConfigFileSaveError) -> Self {
260        user_error(err)
261    }
262}
263
264impl From<ConfigGetError> for CommandError {
265    fn from(err: ConfigGetError) -> Self {
266        let hint = config_get_error_hint(&err);
267        let mut cmd_err = config_error(err);
268        cmd_err.extend_hints(hint);
269        cmd_err
270    }
271}
272
273impl From<ConfigLoadError> for CommandError {
274    fn from(err: ConfigLoadError) -> Self {
275        let hint = match &err {
276            ConfigLoadError::Read(_) => None,
277            ConfigLoadError::Parse { source_path, .. } => source_path
278                .as_ref()
279                .map(|path| format!("Check the config file: {}", path.display())),
280        };
281        let mut cmd_err = config_error(err);
282        cmd_err.extend_hints(hint);
283        cmd_err
284    }
285}
286
287impl From<ConfigMigrateError> for CommandError {
288    fn from(err: ConfigMigrateError) -> Self {
289        let hint = err
290            .source_path
291            .as_ref()
292            .map(|path| format!("Check the config file: {}", path.display()));
293        let mut cmd_err = config_error(err);
294        cmd_err.extend_hints(hint);
295        cmd_err
296    }
297}
298
299impl From<RewriteRootCommit> for CommandError {
300    fn from(err: RewriteRootCommit) -> Self {
301        internal_error_with_message("Attempted to rewrite the root commit", err)
302    }
303}
304
305impl From<EditCommitError> for CommandError {
306    fn from(err: EditCommitError) -> Self {
307        internal_error_with_message("Failed to edit a commit", err)
308    }
309}
310
311impl From<CheckOutCommitError> for CommandError {
312    fn from(err: CheckOutCommitError) -> Self {
313        internal_error_with_message("Failed to check out a commit", err)
314    }
315}
316
317impl From<RenameWorkspaceError> for CommandError {
318    fn from(err: RenameWorkspaceError) -> Self {
319        user_error_with_message("Failed to rename a workspace", err)
320    }
321}
322
323impl From<BackendError> for CommandError {
324    fn from(err: BackendError) -> Self {
325        match &err {
326            BackendError::Unsupported(_) => user_error(err),
327            _ => internal_error_with_message("Unexpected error from backend", err),
328        }
329    }
330}
331
332impl From<IndexError> for CommandError {
333    fn from(err: IndexError) -> Self {
334        internal_error_with_message("Unexpected error from index", err)
335    }
336}
337
338impl From<OpHeadsStoreError> for CommandError {
339    fn from(err: OpHeadsStoreError) -> Self {
340        internal_error_with_message("Unexpected error from operation heads store", err)
341    }
342}
343
344impl From<WorkspaceInitError> for CommandError {
345    fn from(err: WorkspaceInitError) -> Self {
346        match err {
347            WorkspaceInitError::DestinationExists(_) => {
348                user_error("The target repo already exists")
349            }
350            WorkspaceInitError::EncodeRepoPath(_) => user_error(err),
351            WorkspaceInitError::CheckOutCommit(err) => {
352                internal_error_with_message("Failed to check out the initial commit", err)
353            }
354            WorkspaceInitError::Path(err) => {
355                internal_error_with_message("Failed to access the repository", err)
356            }
357            WorkspaceInitError::OpHeadsStore(err) => {
358                user_error_with_message("Failed to record initial operation", err)
359            }
360            WorkspaceInitError::Backend(err) => {
361                user_error_with_message("Failed to access the repository", err)
362            }
363            WorkspaceInitError::WorkingCopyState(err) => {
364                internal_error_with_message("Failed to access the repository", err)
365            }
366            WorkspaceInitError::SignInit(err) => user_error(err),
367            WorkspaceInitError::TransactionCommit(err) => err.into(),
368        }
369    }
370}
371
372impl From<OpHeadResolutionError> for CommandError {
373    fn from(err: OpHeadResolutionError) -> Self {
374        match err {
375            OpHeadResolutionError::NoHeads => {
376                internal_error_with_message("Corrupt repository", err)
377            }
378        }
379    }
380}
381
382impl From<OpsetEvaluationError> for CommandError {
383    fn from(err: OpsetEvaluationError) -> Self {
384        match err {
385            OpsetEvaluationError::OpsetResolution(err) => {
386                let hint = opset_resolution_error_hint(&err);
387                let mut cmd_err = user_error(err);
388                cmd_err.extend_hints(hint);
389                cmd_err
390            }
391            OpsetEvaluationError::OpHeadResolution(err) => err.into(),
392            OpsetEvaluationError::OpHeadsStore(err) => err.into(),
393            OpsetEvaluationError::OpStore(err) => err.into(),
394        }
395    }
396}
397
398impl From<SnapshotError> for CommandError {
399    fn from(err: SnapshotError) -> Self {
400        internal_error_with_message("Failed to snapshot the working copy", err)
401    }
402}
403
404impl From<OpStoreError> for CommandError {
405    fn from(err: OpStoreError) -> Self {
406        internal_error_with_message("Failed to load an operation", err)
407    }
408}
409
410impl From<RepoLoaderError> for CommandError {
411    fn from(err: RepoLoaderError) -> Self {
412        internal_error_with_message("Failed to load the repo", err)
413    }
414}
415
416impl From<ResetError> for CommandError {
417    fn from(err: ResetError) -> Self {
418        internal_error_with_message("Failed to reset the working copy", err)
419    }
420}
421
422impl From<TransactionCommitError> for CommandError {
423    fn from(err: TransactionCommitError) -> Self {
424        internal_error(err)
425    }
426}
427
428impl From<WalkPredecessorsError> for CommandError {
429    fn from(err: WalkPredecessorsError) -> Self {
430        match err {
431            WalkPredecessorsError::Backend(err) => err.into(),
432            WalkPredecessorsError::Index(err) => err.into(),
433            WalkPredecessorsError::OpStore(err) => err.into(),
434            WalkPredecessorsError::CycleDetected(_) => internal_error(err),
435        }
436    }
437}
438
439impl From<DiffEditError> for CommandError {
440    fn from(err: DiffEditError) -> Self {
441        user_error_with_message("Failed to edit diff", err)
442    }
443}
444
445impl From<DiffRenderError> for CommandError {
446    fn from(err: DiffRenderError) -> Self {
447        match err {
448            DiffRenderError::DiffGenerate(_) => user_error(err),
449            DiffRenderError::Backend(err) => err.into(),
450            DiffRenderError::AccessDenied { .. } => user_error(err),
451            DiffRenderError::InvalidRepoPath(_) => user_error(err),
452            DiffRenderError::Io(err) => err.into(),
453        }
454    }
455}
456
457impl From<ConflictResolveError> for CommandError {
458    fn from(err: ConflictResolveError) -> Self {
459        match err {
460            ConflictResolveError::Backend(err) => err.into(),
461            ConflictResolveError::Io(err) => err.into(),
462            _ => {
463                let hint = match &err {
464                    ConflictResolveError::ConflictTooComplicated { .. } => {
465                        Some("Edit the conflict markers manually to resolve this.".to_owned())
466                    }
467                    ConflictResolveError::ExecutableConflict { .. } => {
468                        Some("Use `jj file chmod` to update the executable bit.".to_owned())
469                    }
470                    _ => None,
471                };
472                let mut cmd_err = user_error_with_message("Failed to resolve conflicts", err);
473                cmd_err.extend_hints(hint);
474                cmd_err
475            }
476        }
477    }
478}
479
480impl From<MergeToolPartialResolutionError> for CommandError {
481    fn from(err: MergeToolPartialResolutionError) -> Self {
482        user_error(err)
483    }
484}
485
486impl From<MergeToolConfigError> for CommandError {
487    fn from(err: MergeToolConfigError) -> Self {
488        match &err {
489            MergeToolConfigError::MergeArgsNotConfigured { tool_name } => {
490                let tool_name = tool_name.clone();
491                user_error_with_hint(
492                    err,
493                    format!(
494                        "To use `{tool_name}` as a merge tool, the config \
495                         `merge-tools.{tool_name}.merge-args` must be defined (see docs for \
496                         details)"
497                    ),
498                )
499            }
500            _ => user_error_with_message("Failed to load tool configuration", err),
501        }
502    }
503}
504
505impl From<TextEditError> for CommandError {
506    fn from(err: TextEditError) -> Self {
507        user_error(err)
508    }
509}
510
511impl From<TempTextEditError> for CommandError {
512    fn from(err: TempTextEditError) -> Self {
513        let hint = err.path.as_ref().map(|path| {
514            let name = err.name.as_deref().unwrap_or("file");
515            format!("Edited {name} is left in {path}", path = path.display())
516        });
517        let mut cmd_err = user_error(err);
518        cmd_err.extend_hints(hint);
519        cmd_err
520    }
521}
522
523impl From<TrailerParseError> for CommandError {
524    fn from(err: TrailerParseError) -> Self {
525        user_error(err)
526    }
527}
528
529#[cfg(feature = "git")]
530mod git {
531    use jj_lib::git::GitDefaultRefspecError;
532    use jj_lib::git::GitExportError;
533    use jj_lib::git::GitFetchError;
534    use jj_lib::git::GitImportError;
535    use jj_lib::git::GitPushError;
536    use jj_lib::git::GitRefExpansionError;
537    use jj_lib::git::GitRemoteManagementError;
538    use jj_lib::git::GitResetHeadError;
539    use jj_lib::git::UnexpectedGitBackendError;
540
541    use super::*;
542
543    impl From<GitImportError> for CommandError {
544        fn from(err: GitImportError) -> Self {
545            let hint = match &err {
546                GitImportError::MissingHeadTarget { .. }
547                | GitImportError::MissingRefAncestor { .. } => Some(
548                    "\
549Is this Git repository a partial clone (cloned with the --filter argument)?
550jj currently does not support partial clones. To use jj with this repository, try re-cloning with \
551                     the full repository contents."
552                        .to_string(),
553                ),
554                GitImportError::Backend(_) => None,
555                GitImportError::Index(_) => None,
556                GitImportError::Git(_) => None,
557                GitImportError::UnexpectedBackend(_) => None,
558            };
559            let mut cmd_err =
560                user_error_with_message("Failed to import refs from underlying Git repo", err);
561            cmd_err.extend_hints(hint);
562            cmd_err
563        }
564    }
565
566    impl From<GitExportError> for CommandError {
567        fn from(err: GitExportError) -> Self {
568            user_error_with_message("Failed to export refs to underlying Git repo", err)
569        }
570    }
571
572    impl From<GitFetchError> for CommandError {
573        fn from(err: GitFetchError) -> Self {
574            match err {
575                GitFetchError::NoSuchRemote(_) => user_error(err),
576                GitFetchError::RemoteName(_) => user_error_with_hint(
577                    err,
578                    "Run `jj git remote rename` to give a different name.",
579                ),
580                GitFetchError::Subprocess(_) => user_error(err),
581            }
582        }
583    }
584
585    impl From<GitDefaultRefspecError> for CommandError {
586        fn from(err: GitDefaultRefspecError) -> Self {
587            match err {
588                GitDefaultRefspecError::NoSuchRemote(_) => user_error(err),
589                GitDefaultRefspecError::InvalidRemoteConfiguration(_, _) => user_error(err),
590            }
591        }
592    }
593
594    impl From<GitRefExpansionError> for CommandError {
595        fn from(err: GitRefExpansionError) -> Self {
596            match &err {
597                GitRefExpansionError::InvalidBranchPattern(pattern) => {
598                    if pattern.as_exact().is_some_and(|s| s.contains('*')) {
599                        user_error_with_hint(
600                            "Branch names may not include `*`.",
601                            "Prefix the pattern with `glob:` to expand `*` as a glob",
602                        )
603                    } else {
604                        user_error(err)
605                    }
606                }
607            }
608        }
609    }
610
611    impl From<GitPushError> for CommandError {
612        fn from(err: GitPushError) -> Self {
613            match err {
614                GitPushError::NoSuchRemote(_) => user_error(err),
615                GitPushError::RemoteName(_) => user_error_with_hint(
616                    err,
617                    "Run `jj git remote rename` to give a different name.",
618                ),
619                GitPushError::Subprocess(_) => user_error(err),
620                GitPushError::UnexpectedBackend(_) => user_error(err),
621            }
622        }
623    }
624
625    impl From<GitRemoteManagementError> for CommandError {
626        fn from(err: GitRemoteManagementError) -> Self {
627            user_error(err)
628        }
629    }
630
631    impl From<GitResetHeadError> for CommandError {
632        fn from(err: GitResetHeadError) -> Self {
633            user_error_with_message("Failed to reset Git HEAD state", err)
634        }
635    }
636
637    impl From<UnexpectedGitBackendError> for CommandError {
638        fn from(err: UnexpectedGitBackendError) -> Self {
639            user_error(err)
640        }
641    }
642}
643
644impl From<RevsetEvaluationError> for CommandError {
645    fn from(err: RevsetEvaluationError) -> Self {
646        user_error(err)
647    }
648}
649
650impl From<FilesetParseError> for CommandError {
651    fn from(err: FilesetParseError) -> Self {
652        let hint = fileset_parse_error_hint(&err);
653        let mut cmd_err =
654            user_error_with_message(format!("Failed to parse fileset: {}", err.kind()), err);
655        cmd_err.extend_hints(hint);
656        cmd_err
657    }
658}
659
660impl From<RecoverWorkspaceError> for CommandError {
661    fn from(err: RecoverWorkspaceError) -> Self {
662        match err {
663            RecoverWorkspaceError::Backend(err) => err.into(),
664            RecoverWorkspaceError::Reset(err) => err.into(),
665            RecoverWorkspaceError::RewriteRootCommit(err) => err.into(),
666            RecoverWorkspaceError::TransactionCommit(err) => err.into(),
667            err @ RecoverWorkspaceError::WorkspaceMissingWorkingCopy(_) => user_error(err),
668        }
669    }
670}
671
672impl From<RevsetParseError> for CommandError {
673    fn from(err: RevsetParseError) -> Self {
674        let hint = revset_parse_error_hint(&err);
675        let mut cmd_err =
676            user_error_with_message(format!("Failed to parse revset: {}", err.kind()), err);
677        cmd_err.extend_hints(hint);
678        cmd_err
679    }
680}
681
682impl From<RevsetResolutionError> for CommandError {
683    fn from(err: RevsetResolutionError) -> Self {
684        let hints = revset_resolution_error_hints(&err);
685        let mut cmd_err = user_error(err);
686        cmd_err.extend_hints(hints);
687        cmd_err
688    }
689}
690
691impl From<UserRevsetEvaluationError> for CommandError {
692    fn from(err: UserRevsetEvaluationError) -> Self {
693        match err {
694            UserRevsetEvaluationError::Resolution(err) => err.into(),
695            UserRevsetEvaluationError::Evaluation(err) => err.into(),
696        }
697    }
698}
699
700impl From<TemplateParseError> for CommandError {
701    fn from(err: TemplateParseError) -> Self {
702        let hint = template_parse_error_hint(&err);
703        let mut cmd_err =
704            user_error_with_message(format!("Failed to parse template: {}", err.kind()), err);
705        cmd_err.extend_hints(hint);
706        cmd_err
707    }
708}
709
710impl From<UiPathParseError> for CommandError {
711    fn from(err: UiPathParseError) -> Self {
712        user_error(err)
713    }
714}
715
716impl From<clap::Error> for CommandError {
717    fn from(err: clap::Error) -> Self {
718        let hint = find_source_parse_error_hint(&err);
719        let mut cmd_err = cli_error(err);
720        cmd_err.extend_hints(hint);
721        cmd_err
722    }
723}
724
725impl From<WorkingCopyStateError> for CommandError {
726    fn from(err: WorkingCopyStateError) -> Self {
727        internal_error_with_message("Failed to access working copy state", err)
728    }
729}
730
731impl From<GitIgnoreError> for CommandError {
732    fn from(err: GitIgnoreError) -> Self {
733        user_error_with_message("Failed to process .gitignore.", err)
734    }
735}
736
737impl From<ParseBulkEditMessageError> for CommandError {
738    fn from(err: ParseBulkEditMessageError) -> Self {
739        user_error(err)
740    }
741}
742
743impl From<AbsorbError> for CommandError {
744    fn from(err: AbsorbError) -> Self {
745        match err {
746            AbsorbError::Backend(err) => err.into(),
747            AbsorbError::RevsetEvaluation(err) => err.into(),
748        }
749    }
750}
751
752impl From<FixError> for CommandError {
753    fn from(err: FixError) -> Self {
754        match err {
755            FixError::Backend(err) => err.into(),
756            FixError::RevsetEvaluation(err) => err.into(),
757            FixError::IO(err) => err.into(),
758            FixError::FixContent(err) => internal_error_with_message(
759                "An error occurred while attempting to fix file content",
760                err,
761            ),
762        }
763    }
764}
765
766impl From<BisectionError> for CommandError {
767    fn from(err: BisectionError) -> Self {
768        match err {
769            BisectionError::RevsetEvaluationError(_) => user_error(err),
770        }
771    }
772}
773
774fn find_source_parse_error_hint(err: &dyn error::Error) -> Option<String> {
775    let source = err.source()?;
776    if let Some(source) = source.downcast_ref() {
777        bookmark_name_parse_error_hint(source)
778    } else if let Some(source) = source.downcast_ref() {
779        config_get_error_hint(source)
780    } else if let Some(source) = source.downcast_ref() {
781        file_pattern_parse_error_hint(source)
782    } else if let Some(source) = source.downcast_ref() {
783        fileset_parse_error_hint(source)
784    } else if let Some(source) = source.downcast_ref() {
785        revset_parse_error_hint(source)
786    } else if let Some(source) = source.downcast_ref() {
787        // TODO: propagate all hints?
788        revset_resolution_error_hints(source).into_iter().next()
789    } else if let Some(UserRevsetEvaluationError::Resolution(source)) = source.downcast_ref() {
790        // TODO: propagate all hints?
791        revset_resolution_error_hints(source).into_iter().next()
792    } else if let Some(source) = source.downcast_ref() {
793        string_pattern_parse_error_hint(source)
794    } else if let Some(source) = source.downcast_ref() {
795        tag_name_parse_error_hint(source)
796    } else if let Some(source) = source.downcast_ref() {
797        template_parse_error_hint(source)
798    } else {
799        None
800    }
801}
802
803const REVSET_SYMBOL_HINT: &str = "See https://jj-vcs.github.io/jj/latest/revsets/ or use `jj help \
804                                  -k revsets` for how to quote symbols.";
805
806fn bookmark_name_parse_error_hint(err: &BookmarkNameParseError) -> Option<String> {
807    use revset::ExpressionKind;
808    match revset::parse_program(&err.input).map(|node| node.kind) {
809        Ok(ExpressionKind::RemoteSymbol(symbol)) => Some(format!(
810            "Looks like remote bookmark. Run `jj bookmark track {symbol}` to track it."
811        )),
812        _ => Some(REVSET_SYMBOL_HINT.to_owned()),
813    }
814}
815
816fn config_get_error_hint(err: &ConfigGetError) -> Option<String> {
817    match &err {
818        ConfigGetError::NotFound { .. } => None,
819        ConfigGetError::Type { source_path, .. } => source_path
820            .as_ref()
821            .map(|path| format!("Check the config file: {}", path.display())),
822    }
823}
824
825fn file_pattern_parse_error_hint(err: &FilePatternParseError) -> Option<String> {
826    match err {
827        FilePatternParseError::InvalidKind(_) => Some(String::from(
828            "See https://jj-vcs.github.io/jj/latest/filesets/#file-patterns or `jj help -k \
829             filesets` for valid prefixes.",
830        )),
831        // Suggest root:"<path>" if input can be parsed as repo-relative path
832        FilePatternParseError::UiPath(UiPathParseError::Fs(e)) => {
833            RepoPathBuf::from_relative_path(&e.input).ok().map(|path| {
834                format!(r#"Consider using root:{path:?} to specify repo-relative path"#)
835            })
836        }
837        FilePatternParseError::RelativePath(_) => None,
838        FilePatternParseError::GlobPattern(_) => None,
839    }
840}
841
842fn fileset_parse_error_hint(err: &FilesetParseError) -> Option<String> {
843    match err.kind() {
844        FilesetParseErrorKind::SyntaxError => Some(String::from(
845            "See https://jj-vcs.github.io/jj/latest/filesets/ or use `jj help -k filesets` for \
846             filesets syntax and how to match file paths.",
847        )),
848        FilesetParseErrorKind::NoSuchFunction {
849            name: _,
850            candidates,
851        } => format_similarity_hint(candidates),
852        FilesetParseErrorKind::InvalidArguments { .. } | FilesetParseErrorKind::Expression(_) => {
853            find_source_parse_error_hint(&err)
854        }
855    }
856}
857
858fn opset_resolution_error_hint(err: &OpsetResolutionError) -> Option<String> {
859    match err {
860        OpsetResolutionError::MultipleOperations {
861            expr: _,
862            candidates,
863        } => Some(format!(
864            "Try specifying one of the operations by ID: {}",
865            candidates.iter().map(short_operation_hash).join(", ")
866        )),
867        OpsetResolutionError::EmptyOperations(_)
868        | OpsetResolutionError::InvalidIdPrefix(_)
869        | OpsetResolutionError::NoSuchOperation(_)
870        | OpsetResolutionError::AmbiguousIdPrefix(_) => None,
871    }
872}
873
874fn revset_parse_error_hint(err: &RevsetParseError) -> Option<String> {
875    // Only for the bottom error, which is usually the root cause
876    let bottom_err = iter::successors(Some(err), |e| e.origin()).last().unwrap();
877    match bottom_err.kind() {
878        RevsetParseErrorKind::SyntaxError => Some(
879            "See https://jj-vcs.github.io/jj/latest/revsets/ or use `jj help -k revsets` for \
880             revsets syntax and how to quote symbols."
881                .into(),
882        ),
883        RevsetParseErrorKind::NotPrefixOperator {
884            op: _,
885            similar_op,
886            description,
887        }
888        | RevsetParseErrorKind::NotPostfixOperator {
889            op: _,
890            similar_op,
891            description,
892        }
893        | RevsetParseErrorKind::NotInfixOperator {
894            op: _,
895            similar_op,
896            description,
897        } => Some(format!("Did you mean `{similar_op}` for {description}?")),
898        RevsetParseErrorKind::NoSuchFunction {
899            name: _,
900            candidates,
901        } => format_similarity_hint(candidates),
902        RevsetParseErrorKind::InvalidFunctionArguments { .. }
903        | RevsetParseErrorKind::Expression(_) => find_source_parse_error_hint(bottom_err),
904        _ => None,
905    }
906}
907
908fn revset_resolution_error_hints(err: &RevsetResolutionError) -> Vec<String> {
909    let multiple_targets_hint = |targets: &[CommitId]| {
910        format!(
911            "Use commit ID to select single revision from: {}",
912            targets.iter().map(|id| format!("{id:.12}")).join(", ")
913        )
914    };
915    match err {
916        RevsetResolutionError::NoSuchRevision {
917            name: _,
918            candidates,
919        } => format_similarity_hint(candidates).into_iter().collect(),
920        RevsetResolutionError::DivergentChangeId { symbol, targets } => vec![
921            multiple_targets_hint(targets),
922            format!("Use `change_id({symbol})` to select all revisions"),
923            "To abandon unneeded revisions, run `jj abandon <commit_id>`".to_owned(),
924        ],
925        RevsetResolutionError::ConflictedRef {
926            kind: "bookmark",
927            symbol,
928            targets,
929        } => vec![
930            multiple_targets_hint(targets),
931            format!("Use `bookmarks(exact:{symbol})` to select all revisions"),
932            format!(
933                "To set which revision the bookmark points to, run `jj bookmark set {symbol} -r \
934                 <REVISION>`"
935            ),
936        ],
937        RevsetResolutionError::ConflictedRef {
938            kind: _,
939            symbol: _,
940            targets,
941        } => vec![multiple_targets_hint(targets)],
942        RevsetResolutionError::EmptyString
943        | RevsetResolutionError::WorkspaceMissingWorkingCopy { .. }
944        | RevsetResolutionError::AmbiguousCommitIdPrefix(_)
945        | RevsetResolutionError::AmbiguousChangeIdPrefix(_)
946        | RevsetResolutionError::Backend(_)
947        | RevsetResolutionError::Other(_) => vec![],
948    }
949}
950
951fn string_pattern_parse_error_hint(err: &StringPatternParseError) -> Option<String> {
952    match err {
953        StringPatternParseError::InvalidKind(_) => Some(
954            "Try prefixing with one of `exact:`, `glob:`, `regex:`, `substring:`, or one of these \
955             with `-i` suffix added (e.g. `glob-i:`) for case-insensitive matching"
956                .into(),
957        ),
958        StringPatternParseError::GlobPattern(_) | StringPatternParseError::Regex(_) => None,
959    }
960}
961
962fn tag_name_parse_error_hint(_: &TagNameParseError) -> Option<String> {
963    Some(REVSET_SYMBOL_HINT.to_owned())
964}
965
966fn template_parse_error_hint(err: &TemplateParseError) -> Option<String> {
967    // Only for the bottom error, which is usually the root cause
968    let bottom_err = iter::successors(Some(err), |e| e.origin()).last().unwrap();
969    match bottom_err.kind() {
970        TemplateParseErrorKind::NoSuchKeyword { candidates, .. }
971        | TemplateParseErrorKind::NoSuchFunction { candidates, .. }
972        | TemplateParseErrorKind::NoSuchMethod { candidates, .. } => {
973            format_similarity_hint(candidates)
974        }
975        TemplateParseErrorKind::InvalidArguments { .. } | TemplateParseErrorKind::Expression(_) => {
976            find_source_parse_error_hint(bottom_err)
977        }
978        _ => None,
979    }
980}
981
982const BROKEN_PIPE_EXIT_CODE: u8 = 3;
983
984pub(crate) fn handle_command_result(ui: &mut Ui, result: Result<(), CommandError>) -> u8 {
985    try_handle_command_result(ui, result).unwrap_or(BROKEN_PIPE_EXIT_CODE)
986}
987
988fn try_handle_command_result(ui: &mut Ui, result: Result<(), CommandError>) -> io::Result<u8> {
989    let Err(cmd_err) = &result else {
990        return Ok(0);
991    };
992    let err = &cmd_err.error;
993    let hints = &cmd_err.hints;
994    match cmd_err.kind {
995        CommandErrorKind::User => {
996            print_error(ui, "Error: ", err, hints)?;
997            Ok(1)
998        }
999        CommandErrorKind::Config => {
1000            print_error(ui, "Config error: ", err, hints)?;
1001            writeln!(
1002                ui.stderr_formatter().labeled("hint"),
1003                "For help, see https://jj-vcs.github.io/jj/latest/config/ or use `jj help -k \
1004                 config`."
1005            )?;
1006            Ok(1)
1007        }
1008        CommandErrorKind::Cli => {
1009            if let Some(err) = err.downcast_ref::<clap::Error>() {
1010                handle_clap_error(ui, err, hints)
1011            } else {
1012                print_error(ui, "Error: ", err, hints)?;
1013                Ok(2)
1014            }
1015        }
1016        CommandErrorKind::BrokenPipe => {
1017            // A broken pipe is not an error, but a signal to exit gracefully.
1018            Ok(BROKEN_PIPE_EXIT_CODE)
1019        }
1020        CommandErrorKind::Internal => {
1021            print_error(ui, "Internal error: ", err, hints)?;
1022            Ok(255)
1023        }
1024    }
1025}
1026
1027fn print_error(
1028    ui: &Ui,
1029    heading: &str,
1030    err: &dyn error::Error,
1031    hints: &[ErrorHint],
1032) -> io::Result<()> {
1033    writeln!(ui.error_with_heading(heading), "{err}")?;
1034    print_error_sources(ui, err.source())?;
1035    print_error_hints(ui, hints)?;
1036    Ok(())
1037}
1038
1039/// Prints error sources one by one from the given `source` inclusive.
1040pub fn print_error_sources(ui: &Ui, source: Option<&dyn error::Error>) -> io::Result<()> {
1041    let Some(err) = source else {
1042        return Ok(());
1043    };
1044    let mut formatter = ui.stderr_formatter().into_labeled("error_source");
1045    if err.source().is_none() {
1046        write!(formatter.labeled("heading"), "Caused by: ")?;
1047        writeln!(formatter, "{err}")?;
1048    } else {
1049        writeln!(formatter.labeled("heading"), "Caused by:")?;
1050        for (i, err) in iter::successors(Some(err), |&err| err.source()).enumerate() {
1051            write!(formatter.labeled("heading"), "{}: ", i + 1)?;
1052            writeln!(formatter, "{err}")?;
1053        }
1054    }
1055    Ok(())
1056}
1057
1058fn print_error_hints(ui: &Ui, hints: &[ErrorHint]) -> io::Result<()> {
1059    let mut formatter = ui.stderr_formatter().into_labeled("hint");
1060    for hint in hints {
1061        write!(formatter.labeled("heading"), "Hint: ")?;
1062        match hint {
1063            ErrorHint::PlainText(message) => {
1064                writeln!(formatter, "{message}")?;
1065            }
1066            ErrorHint::Formatted(recorded) => {
1067                recorded.replay(formatter.as_mut())?;
1068                // Formatted hint is usually multi-line text, and it's
1069                // convenient if trailing "\n" doesn't have to be omitted.
1070                if !recorded.data().ends_with(b"\n") {
1071                    writeln!(formatter)?;
1072                }
1073            }
1074        }
1075    }
1076    Ok(())
1077}
1078
1079fn handle_clap_error(ui: &mut Ui, err: &clap::Error, hints: &[ErrorHint]) -> io::Result<u8> {
1080    let clap_str = if ui.color() {
1081        err.render().ansi().to_string()
1082    } else {
1083        err.render().to_string()
1084    };
1085
1086    match err.kind() {
1087        clap::error::ErrorKind::DisplayHelp
1088        | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand => ui.request_pager(),
1089        _ => {}
1090    };
1091    // Definitions for exit codes and streams come from
1092    // https://github.com/clap-rs/clap/blob/master/src/error/mod.rs
1093    match err.kind() {
1094        clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => {
1095            write!(ui.stdout(), "{clap_str}")?;
1096            return Ok(0);
1097        }
1098        _ => {}
1099    }
1100    write!(ui.stderr(), "{clap_str}")?;
1101    // Skip the first source error, which should be printed inline.
1102    print_error_sources(ui, err.source().and_then(|err| err.source()))?;
1103    print_error_hints(ui, hints)?;
1104    Ok(2)
1105}
1106
1107/// Prints diagnostic messages emitted during parsing.
1108pub fn print_parse_diagnostics<T: error::Error>(
1109    ui: &Ui,
1110    context_message: &str,
1111    diagnostics: &Diagnostics<T>,
1112) -> io::Result<()> {
1113    for diag in diagnostics {
1114        writeln!(ui.warning_default(), "{context_message}")?;
1115        for err in iter::successors(Some(diag as &dyn error::Error), |&err| err.source()) {
1116            writeln!(ui.stderr(), "{err}")?;
1117        }
1118        // If we add support for multiple error diagnostics, we might have to do
1119        // find_source_parse_error_hint() and print it here.
1120    }
1121    Ok(())
1122}