Skip to main content

jj_cli/
complete.rs

1// Copyright 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::collections::HashSet;
16use std::io::BufRead as _;
17use std::path::Path;
18
19use clap::FromArgMatches as _;
20use clap::builder::StyledStr;
21use clap_complete::CompletionCandidate;
22use indoc::indoc;
23use itertools::Itertools as _;
24use jj_lib::config::ConfigNamePathBuf;
25use jj_lib::file_util::normalize_path;
26use jj_lib::file_util::slash_path;
27use jj_lib::settings::UserSettings;
28use jj_lib::workspace::DefaultWorkspaceLoaderFactory;
29use jj_lib::workspace::WorkspaceLoaderFactory as _;
30
31use crate::cli_util::GlobalArgs;
32use crate::cli_util::expand_args;
33use crate::cli_util::find_workspace_dir;
34use crate::cli_util::load_revset_aliases;
35use crate::cli_util::load_template_aliases;
36use crate::command_error::CommandError;
37use crate::command_error::user_error;
38use crate::config::CONFIG_SCHEMA;
39use crate::config::ConfigArgKind;
40use crate::config::ConfigEnv;
41use crate::config::config_from_environment;
42use crate::config::default_config_layers;
43use crate::merge_tools::ExternalMergeTool;
44use crate::merge_tools::configured_merge_tools;
45use crate::merge_tools::get_external_tool_config;
46use crate::ui::Ui;
47
48const BOOKMARK_HELP_TEMPLATE: &str = r#"template-aliases.'bookmark_help()'='''
49" " ++
50coalesce(
51    if(!present, "(deleted bookmark)"),
52    if(!normal_target, "(conflicted bookmark)"),
53    if(!normal_target.description(), "(no description set)"),
54    normal_target.description().first_line(),
55)
56'''"#;
57const TAG_HELP_TEMPLATE: &str = r#"template-aliases.'tag_help()'='''
58" " ++
59coalesce(
60    if(!present, "(deleted tag)"),
61    if(!normal_target, "(conflicted tag)"),
62    if(!normal_target.description(), "(no description set)"),
63    normal_target.description().first_line(),
64)
65'''"#;
66
67/// A helper function for various completer functions. It returns
68/// (candidate, help) assuming they are separated by a space.
69fn split_help_text(line: &str) -> (&str, Option<StyledStr>) {
70    match line.split_once(' ') {
71        Some((name, help)) => (name, Some(help.to_string().into())),
72        None => (line, None),
73    }
74}
75
76pub fn local_bookmarks() -> Vec<CompletionCandidate> {
77    with_jj(|jj, _| {
78        let output = jj
79            .build()
80            .arg("bookmark")
81            .arg("list")
82            .arg("--config")
83            .arg(BOOKMARK_HELP_TEMPLATE)
84            .arg("--template")
85            .arg(r#"if(!remote, name ++ bookmark_help()) ++ "\n""#)
86            .output()
87            .map_err(user_error)?;
88
89        Ok(String::from_utf8_lossy(&output.stdout)
90            .lines()
91            .map(split_help_text)
92            .map(|(name, help)| CompletionCandidate::new(name).help(help))
93            .collect())
94    })
95}
96
97pub fn tracked_bookmarks() -> Vec<CompletionCandidate> {
98    with_jj(|jj, _| {
99        let output = jj
100            .build()
101            .arg("bookmark")
102            .arg("list")
103            .arg("--tracked")
104            .arg("--config")
105            .arg(BOOKMARK_HELP_TEMPLATE)
106            .arg("--template")
107            .arg(r#"if(remote, name ++ '@' ++ remote ++ bookmark_help() ++ "\n")"#)
108            .output()
109            .map_err(user_error)?;
110
111        Ok(String::from_utf8_lossy(&output.stdout)
112            .lines()
113            .map(split_help_text)
114            .filter_map(|(symbol, help)| Some((symbol.split_once('@')?, help)))
115            // There may be multiple remote bookmarks to untrack. Just pick the
116            // first one for help text.
117            .dedup_by(|((name1, _), _), ((name2, _), _)| name1 == name2)
118            .map(|((name, _remote), help)| CompletionCandidate::new(name).help(help))
119            .collect())
120    })
121}
122
123pub fn untracked_bookmarks() -> Vec<CompletionCandidate> {
124    with_jj(|jj, _settings| {
125        let remotes = jj
126            .build()
127            .arg("git")
128            .arg("remote")
129            .arg("list")
130            .output()
131            .map_err(user_error)?;
132        let remotes = String::from_utf8_lossy(&remotes.stdout);
133        let remotes = remotes
134            .lines()
135            .filter_map(|l| l.split_whitespace().next())
136            .collect_vec();
137
138        let bookmark_table = jj
139            .build()
140            .arg("bookmark")
141            .arg("list")
142            .arg("--all-remotes")
143            .arg("--config")
144            .arg(BOOKMARK_HELP_TEMPLATE)
145            .arg("--template")
146            .arg(
147                r#"
148                if(remote != "git",
149                    if(!remote, name) ++ "\t" ++
150                    if(remote, name ++ "@" ++ remote) ++ "\t" ++
151                    if(tracked, "tracked") ++ "\t" ++
152                    bookmark_help() ++ "\n"
153                )"#,
154            )
155            .output()
156            .map_err(user_error)?;
157        let bookmark_table = String::from_utf8_lossy(&bookmark_table.stdout);
158
159        let mut possible_bookmarks_to_track = Vec::new();
160        let mut already_tracked_bookmarks = HashSet::new();
161
162        for line in bookmark_table.lines() {
163            let [local, remote, tracked, help] =
164                line.split('\t').collect_array().unwrap_or_default();
165
166            if !local.is_empty() {
167                possible_bookmarks_to_track.extend(
168                    remotes
169                        .iter()
170                        .map(|remote| (format!("{local}@{remote}"), help)),
171                );
172            } else if tracked.is_empty() {
173                possible_bookmarks_to_track.push((remote.to_owned(), help));
174            } else {
175                already_tracked_bookmarks.insert(remote);
176            }
177        }
178        possible_bookmarks_to_track
179            .retain(|(bookmark, _help)| !already_tracked_bookmarks.contains(&bookmark.as_str()));
180
181        Ok(possible_bookmarks_to_track
182            .iter()
183            .filter_map(|(symbol, help)| Some((symbol.split_once('@')?, help)))
184            // There may be multiple remote bookmarks to track. Just pick the
185            // first one for help text.
186            .dedup_by(|((name1, _), _), ((name2, _), _)| name1 == name2)
187            .map(|((name, _remote), help)| {
188                CompletionCandidate::new(name).help(Some(help.to_string().into()))
189            })
190            .collect())
191    })
192}
193
194pub fn bookmarks() -> Vec<CompletionCandidate> {
195    with_jj(|jj, _settings| {
196        let output = jj
197            .build()
198            .arg("bookmark")
199            .arg("list")
200            .arg("--all-remotes")
201            .arg("--config")
202            .arg(BOOKMARK_HELP_TEMPLATE)
203            .arg("--template")
204            .arg(
205                // only provide help for local refs, remote could be ambiguous
206                r#"name ++ if(remote, "@" ++ remote, bookmark_help()) ++ "\n""#,
207            )
208            .output()
209            .map_err(user_error)?;
210        let stdout = String::from_utf8_lossy(&output.stdout);
211
212        Ok((&stdout
213            .lines()
214            .map(split_help_text)
215            .chunk_by(|(name, _)| name.split_once('@').map(|t| t.0).unwrap_or(name)))
216            .into_iter()
217            .map(|(bookmark, mut refs)| {
218                let help = refs.find_map(|(_, help)| help);
219                let local = help.is_some();
220                let display_order = match local {
221                    true => 0,
222                    false => 1,
223                };
224                CompletionCandidate::new(bookmark)
225                    .help(help)
226                    .display_order(Some(display_order))
227            })
228            .collect())
229    })
230}
231
232pub fn local_tags() -> Vec<CompletionCandidate> {
233    with_jj(|jj, _| {
234        let output = jj
235            .build()
236            .arg("tag")
237            .arg("list")
238            .arg("--config")
239            .arg(TAG_HELP_TEMPLATE)
240            .arg("--template")
241            .arg(r#"if(!remote, name ++ tag_help()) ++ "\n""#)
242            .output()
243            .map_err(user_error)?;
244
245        Ok(String::from_utf8_lossy(&output.stdout)
246            .lines()
247            .map(split_help_text)
248            .map(|(name, help)| CompletionCandidate::new(name).help(help))
249            .collect())
250    })
251}
252
253pub fn git_remotes() -> Vec<CompletionCandidate> {
254    with_jj(|jj, _| {
255        let output = jj
256            .build()
257            .arg("git")
258            .arg("remote")
259            .arg("list")
260            .output()
261            .map_err(user_error)?;
262
263        let stdout = String::from_utf8_lossy(&output.stdout);
264
265        Ok(stdout
266            .lines()
267            .filter_map(|line| line.split_once(' ').map(|(name, _url)| name))
268            .map(CompletionCandidate::new)
269            .collect())
270    })
271}
272
273pub fn template_aliases() -> Vec<CompletionCandidate> {
274    with_jj(|_, settings| {
275        let Ok(template_aliases) = load_template_aliases(&Ui::null(), settings.config()) else {
276            return Ok(Vec::new());
277        };
278        Ok(template_aliases
279            .symbol_names()
280            .map(|name| {
281                let doc = template_aliases.get_symbol(name).unwrap().2;
282                CompletionCandidate::new(name).help(doc.map(|doc| doc.to_owned().into()))
283            })
284            .sorted()
285            .collect())
286    })
287}
288
289pub fn aliases() -> Vec<CompletionCandidate> {
290    with_jj(|_, settings| {
291        Ok(settings
292            .table_keys("aliases")
293            // This is opinionated, but many people probably have several
294            // single- or two-letter aliases they use all the time. These
295            // aliases don't need to be completed and they would only clutter
296            // the output of `jj <TAB>`.
297            .filter(|alias| alias.len() > 2)
298            .map(|alias| {
299                CompletionCandidate::new(alias).help(
300                    settings
301                        .get_string(["aliases", alias, "doc"])
302                        .ok()
303                        .map(|doc| doc.into()),
304                )
305            })
306            .collect())
307    })
308}
309
310fn revisions(match_prefix: &str, revset_filter: Option<&str>) -> Vec<CompletionCandidate> {
311    with_jj(|jj, settings| {
312        // display order
313        const LOCAL_BOOKMARK: usize = 0;
314        const TAG: usize = 1;
315        const CHANGE_ID: usize = 2;
316        const WORKSPACE: usize = 3;
317        const REMOTE_BOOKMARK: usize = 4;
318        const REVSET_ALIAS: usize = 5;
319
320        let mut candidates = Vec::new();
321
322        // bookmarks
323
324        let mut cmd = jj.build();
325        cmd.arg("bookmark")
326            .arg("list")
327            .arg("--all-remotes")
328            .arg("--config")
329            .arg(BOOKMARK_HELP_TEMPLATE)
330            .arg("--template")
331            .arg(
332                r#"if(remote != "git", name ++ if(remote, "@" ++ remote) ++ bookmark_help() ++ "\n")"#,
333            );
334        if let Some(revs) = revset_filter {
335            cmd.arg("--revisions").arg(revs);
336        }
337        let output = cmd.output().map_err(user_error)?;
338        let stdout = String::from_utf8_lossy(&output.stdout);
339
340        candidates.extend(
341            stdout
342                .lines()
343                .map(split_help_text)
344                .filter(|(bookmark, _)| bookmark.starts_with(match_prefix))
345                .map(|(bookmark, help)| {
346                    let local = !bookmark.contains('@');
347                    let display_order = match local {
348                        true => LOCAL_BOOKMARK,
349                        false => REMOTE_BOOKMARK,
350                    };
351                    CompletionCandidate::new(bookmark)
352                        .help(help)
353                        .display_order(Some(display_order))
354                }),
355        );
356
357        // tags
358
359        // Tags cannot be filtered by revisions. In order to avoid suggesting
360        // immutable tags for mutable revision args, we skip tags entirely if
361        // revset_filter is set. This is not a big loss, since tags usually point
362        // to immutable revisions anyway.
363        if revset_filter.is_none() {
364            let output = jj
365                .build()
366                .arg("tag")
367                .arg("list")
368                .arg("--config")
369                .arg(BOOKMARK_HELP_TEMPLATE)
370                .arg("--template")
371                .arg(r#"name ++ bookmark_help() ++ "\n""#)
372                .arg(format!("glob:{}*", globset::escape(match_prefix)))
373                .output()
374                .map_err(user_error)?;
375            let stdout = String::from_utf8_lossy(&output.stdout);
376
377            candidates.extend(stdout.lines().map(|line| {
378                let (name, desc) = split_help_text(line);
379                CompletionCandidate::new(name)
380                    .help(desc)
381                    .display_order(Some(TAG))
382            }));
383        }
384
385        // workspace names
386
387        let output = jj
388            .build()
389            .arg("workspace")
390            .arg("list")
391            .arg("--template")
392            .arg(r#"name ++ "\n""#)
393            .output()
394            .map_err(user_error)?;
395        let stdout = String::from_utf8_lossy(&output.stdout);
396
397        // If there's only one workspace, the user can just use `@`, and they may even
398        // be confused if they see `default@` as an option.
399        if stdout.lines().count() > 1 {
400            candidates.extend(stdout.lines().filter_map(|name| {
401                let symbol = format!("{name}@");
402                if symbol.starts_with(match_prefix) {
403                    Some(
404                        CompletionCandidate::new(symbol)
405                            .help(Some(
406                                format!("The working copy for workspace `{name}`").into(),
407                            ))
408                            .display_order(Some(WORKSPACE)),
409                    )
410                } else {
411                    None
412                }
413            }));
414        }
415
416        // change IDs
417
418        let revisions = revset_filter
419            .map(String::from)
420            .or_else(|| settings.get_string("revsets.short-prefixes").ok())
421            .or_else(|| settings.get_string("revsets.log").ok())
422            .unwrap_or_default();
423
424        let output = jj
425            .build()
426            .arg("log")
427            .arg("--no-graph")
428            .arg("--limit")
429            .arg("100")
430            .arg("--revisions")
431            .arg(revisions)
432            .arg("--template")
433            .arg(
434                r#"
435                join(" ",
436                    separate("/",
437                        change_id.shortest(),
438                        if(hidden || divergent, change_offset),
439                    ),
440                    if(description, description.first_line(), "(no description set)"),
441                ) ++ "\n""#,
442            )
443            .output()
444            .map_err(user_error)?;
445        let stdout = String::from_utf8_lossy(&output.stdout);
446
447        candidates.extend(
448            stdout
449                .lines()
450                .map(split_help_text)
451                .filter(|(id, _)| id.starts_with(match_prefix))
452                .map(|(id, desc)| {
453                    CompletionCandidate::new(id)
454                        .help(desc)
455                        .display_order(Some(CHANGE_ID))
456                }),
457        );
458
459        // revset aliases
460
461        let revset_aliases = load_revset_aliases(&Ui::null(), settings.config())?;
462        let symbol_names = revset_aliases
463            .symbol_names()
464            .sorted_unstable()
465            .collect_vec();
466        candidates.extend(
467            symbol_names
468                .into_iter()
469                .filter(|symbol| symbol.starts_with(match_prefix))
470                .map(|symbol| {
471                    let (_, defn, doc) = revset_aliases.get_symbol(symbol).unwrap();
472                    // Prefer TOML `.doc` over definition text
473                    let help: String = doc.map(|s| s.to_owned()).unwrap_or_else(|| defn.clone());
474                    CompletionCandidate::new(symbol)
475                        .help(Some(help.into()))
476                        .display_order(Some(REVSET_ALIAS))
477                }),
478        );
479
480        Ok(candidates)
481    })
482}
483
484fn revset_expression(
485    current: &std::ffi::OsStr,
486    revset_filter: Option<&str>,
487) -> Vec<CompletionCandidate> {
488    let Some(current) = current.to_str() else {
489        return Vec::new();
490    };
491    let (prepend, match_prefix) = split_revset_trailing_name(current).unwrap_or(("", current));
492    let candidates = revisions(match_prefix, revset_filter);
493    if prepend.is_empty() {
494        candidates
495    } else {
496        candidates
497            .into_iter()
498            .map(|candidate| candidate.add_prefix(prepend))
499            .collect()
500    }
501}
502
503pub fn revset_expression_all(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
504    revset_expression(current, None)
505}
506
507pub fn revset_expression_mutable(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
508    revset_expression(current, Some("mutable()"))
509}
510
511pub fn revset_expression_mutable_conflicts(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
512    revset_expression(current, Some("mutable() & conflicts()"))
513}
514
515/// Identifies if an incomplete expression ends with a name, or may be continued
516/// with a name.
517///
518/// If the expression ends with an name or a partial name, returns a tuple that
519/// splits the string at the point the name starts.
520/// If the expression is empty or ends with a prefix or infix operator that
521/// could plausibly be followed by a name, returns a tuple where the first
522/// item is the entire input string, and the second item is empty.
523/// Otherwise, returns `None`.
524///
525/// The input expression may be incomplete (e.g. missing closing parentheses),
526/// and the ability to reject invalid expressions is limited.
527fn split_revset_trailing_name(incomplete_revset_str: &str) -> Option<(&str, &str)> {
528    let final_part = incomplete_revset_str
529        .rsplit_once([':', '~', '|', '&', '(', ','])
530        .map(|(_, rest)| rest)
531        .unwrap_or(incomplete_revset_str);
532    let final_part = final_part
533        .rsplit_once("..")
534        .map(|(_, rest)| rest)
535        .unwrap_or(final_part)
536        .trim_ascii_start();
537
538    let re = regex::Regex::new(r"^(?:[\p{XID_CONTINUE}_/]+[@.+-])*[\p{XID_CONTINUE}_/]*$").unwrap();
539    re.is_match(final_part)
540        .then(|| incomplete_revset_str.split_at(incomplete_revset_str.len() - final_part.len()))
541}
542
543pub fn operations() -> Vec<CompletionCandidate> {
544    with_jj(|jj, _| {
545        let output = jj
546            .build()
547            .arg("operation")
548            .arg("log")
549            .arg("--no-graph")
550            .arg("--limit")
551            .arg("100")
552            .arg("--template")
553            .arg(
554                r#"
555                separate(" ",
556                    id.short(),
557                    "(" ++ format_timestamp(time.end()) ++ ")",
558                    description.first_line(),
559                ) ++ "\n""#,
560            )
561            .output()
562            .map_err(user_error)?;
563
564        Ok(String::from_utf8_lossy(&output.stdout)
565            .lines()
566            .map(|line| {
567                let (id, help) = split_help_text(line);
568                CompletionCandidate::new(id).help(help)
569            })
570            .collect())
571    })
572}
573
574pub fn workspaces() -> Vec<CompletionCandidate> {
575    let template = indoc! {r#"
576        name ++ "\t" ++ if(
577            target.description(),
578            target.description().first_line(),
579            "(no description set)"
580        ) ++ "\n"
581    "#};
582    with_jj(|jj, _| {
583        let output = jj
584            .build()
585            .arg("workspace")
586            .arg("list")
587            .arg("--template")
588            .arg(template)
589            .output()
590            .map_err(user_error)?;
591        let stdout = String::from_utf8_lossy(&output.stdout);
592
593        Ok(stdout
594            .lines()
595            .filter_map(|line| {
596                let res = line.split_once('\t').map(|(name, desc)| {
597                    CompletionCandidate::new(name).help(Some(desc.to_string().into()))
598                });
599                if res.is_none() {
600                    eprintln!("Error parsing line {line}");
601                }
602                res
603            })
604            .collect())
605    })
606}
607
608fn merge_tools_filtered_by(
609    settings: &UserSettings,
610    condition: impl Fn(ExternalMergeTool) -> bool,
611) -> impl Iterator<Item = &str> {
612    configured_merge_tools(settings).filter(move |name| {
613        let Ok(Some(tool)) = get_external_tool_config(settings, name) else {
614            return false;
615        };
616        condition(tool)
617    })
618}
619
620pub fn merge_editors() -> Vec<CompletionCandidate> {
621    with_jj(|_, settings| {
622        Ok([":builtin", ":ours", ":theirs"]
623            .into_iter()
624            .chain(merge_tools_filtered_by(settings, |tool| {
625                !tool.merge_args.is_empty()
626            }))
627            .map(CompletionCandidate::new)
628            .collect())
629    })
630}
631
632/// Approximate list of known diff editors
633pub fn diff_editors() -> Vec<CompletionCandidate> {
634    with_jj(|_, settings| {
635        Ok(std::iter::once(":builtin")
636            .chain(merge_tools_filtered_by(
637                settings,
638                // The args are empty only if `edit-args` are explicitly set to
639                // `[]` in TOML. If they are not specified, the default
640                // `["$left", "$right"]` value would be used.
641                |tool| !tool.edit_args.is_empty(),
642            ))
643            .map(CompletionCandidate::new)
644            .collect())
645    })
646}
647
648/// Approximate list of known diff tools
649pub fn diff_formatters() -> Vec<CompletionCandidate> {
650    let builtin_format_kinds = crate::diff_util::all_builtin_diff_format_names();
651    with_jj(|_, settings| {
652        Ok(builtin_format_kinds
653            .iter()
654            .map(|s| s.as_str())
655            .chain(merge_tools_filtered_by(
656                settings,
657                // The args are empty only if `diff-args` are explicitly set to
658                // `[]` in TOML. If they are not specified, the default
659                // `["$left", "$right"]` value would be used.
660                |tool| !tool.diff_args.is_empty(),
661            ))
662            .map(CompletionCandidate::new)
663            .collect())
664    })
665}
666
667fn config_keys_rec(
668    prefix: ConfigNamePathBuf,
669    properties: &serde_json::Map<String, serde_json::Value>,
670    acc: &mut Vec<CompletionCandidate>,
671    only_leaves: bool,
672    suffix: &str,
673) {
674    for (key, value) in properties {
675        let mut prefix = prefix.clone();
676        prefix.push(key);
677
678        let value = value.as_object().unwrap();
679        match value.get("type").and_then(|v| v.as_str()) {
680            Some("object") => {
681                if !only_leaves {
682                    let help = value
683                        .get("description")
684                        .map(|desc| desc.as_str().unwrap().to_string().into());
685                    let escaped_key = prefix.to_string();
686                    acc.push(CompletionCandidate::new(escaped_key).help(help));
687                }
688                let Some(properties) = value.get("properties") else {
689                    continue;
690                };
691                let properties = properties.as_object().unwrap();
692                config_keys_rec(prefix, properties, acc, only_leaves, suffix);
693            }
694            _ => {
695                let help = value
696                    .get("description")
697                    .map(|desc| desc.as_str().unwrap().to_string().into());
698                let escaped_key = format!("{prefix}{suffix}");
699                acc.push(CompletionCandidate::new(escaped_key).help(help));
700            }
701        }
702    }
703}
704
705fn json_keypath<'a>(
706    schema: &'a serde_json::Value,
707    keypath: &str,
708    separator: &str,
709) -> Option<&'a serde_json::Value> {
710    keypath
711        .split(separator)
712        .try_fold(schema, |value, step| value.get(step))
713}
714fn jsonschema_keypath<'a>(
715    schema: &'a serde_json::Value,
716    keypath: &ConfigNamePathBuf,
717) -> Option<&'a serde_json::Value> {
718    keypath.components().try_fold(schema, |value, step| {
719        let value = value.as_object()?;
720        if value.get("type")?.as_str()? != "object" {
721            return None;
722        }
723        let properties = value.get("properties")?.as_object()?;
724        properties.get(step.get())
725    })
726}
727
728fn config_values(path: &ConfigNamePathBuf) -> Option<Vec<String>> {
729    let schema: serde_json::Value = serde_json::from_str(CONFIG_SCHEMA).unwrap();
730
731    let mut config_entry = jsonschema_keypath(&schema, path)?;
732    if let Some(reference) = config_entry.get("$ref") {
733        let reference = reference.as_str()?.strip_prefix("#/")?;
734        config_entry = json_keypath(&schema, reference, "/")?;
735    }
736
737    if let Some(possible_values) = config_entry.get("enum") {
738        return Some(
739            possible_values
740                .as_array()?
741                .iter()
742                .filter_map(|val| val.as_str())
743                .map(ToOwned::to_owned)
744                .collect(),
745        );
746    }
747
748    Some(match config_entry.get("type")?.as_str()? {
749        "boolean" => vec!["false".into(), "true".into()],
750        _ => vec![],
751    })
752}
753
754fn config_keys_impl(only_leaves: bool, suffix: &str) -> Vec<CompletionCandidate> {
755    let schema: serde_json::Value = serde_json::from_str(CONFIG_SCHEMA).unwrap();
756    let schema = schema.as_object().unwrap();
757    let properties = schema["properties"].as_object().unwrap();
758
759    let mut candidates = Vec::new();
760    config_keys_rec(
761        ConfigNamePathBuf::root(),
762        properties,
763        &mut candidates,
764        only_leaves,
765        suffix,
766    );
767    candidates
768}
769
770pub fn config_keys() -> Vec<CompletionCandidate> {
771    config_keys_impl(false, "")
772}
773
774pub fn leaf_config_keys() -> Vec<CompletionCandidate> {
775    config_keys_impl(true, "")
776}
777
778pub fn leaf_config_key_value(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
779    let Some(current) = current.to_str() else {
780        return Vec::new();
781    };
782
783    if let Some((key, current_val)) = current.split_once('=') {
784        let Ok(key) = key.parse() else {
785            return Vec::new();
786        };
787        let possible_values = config_values(&key).unwrap_or_default();
788
789        possible_values
790            .into_iter()
791            .filter(|x| x.starts_with(current_val))
792            .map(|x| CompletionCandidate::new(format!("{key}={x}")))
793            .collect()
794    } else {
795        config_keys_impl(true, "=")
796            .into_iter()
797            .filter(|candidate| candidate.get_value().to_str().unwrap().starts_with(current))
798            .collect()
799    }
800}
801
802pub fn config_keys_to_unset() -> Vec<CompletionCandidate> {
803    let Ok(config_level_flag) = std::env::args()
804        .filter(|arg| matches!(arg.as_str(), "--user" | "--repo" | "--workspace"))
805        .at_most_one()
806    else {
807        return Vec::new();
808    };
809
810    with_jj(|jj, _| {
811        const TEMPLATE: &str = r#"name ++ "\t" ++ source ++ "\t" ++ stringify(value).replace(regex:'\n\s*', " ") ++ "\n""#;
812        let list_output = jj
813            .build()
814            .args(["config", "list"])
815            // Only suggest unsetting overridden config options if the corresponding level is
816            // already specified.
817            .args(
818                config_level_flag
819                    .is_some()
820                    .then_some("--include-overridden"),
821            )
822            .args(config_level_flag)
823            .args(["--template", TEMPLATE])
824            .output()
825            .map_err(user_error)?;
826        Ok(String::from_utf8_lossy(&list_output.stdout)
827            .lines()
828            .filter_map(|line| line.split('\t').collect_tuple())
829            .filter(|(_, source, _)| matches!(*source, "user" | "repo" | "workspace"))
830            .map(|(name, source, value)| {
831                CompletionCandidate::new(name)
832                    .tag(Some(source.to_string().into()))
833                    .help(Some(format!("{source}: {value}").into()))
834            })
835            .collect())
836    })
837}
838
839pub fn branch_name_equals_any_revision(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
840    let Some(current) = current.to_str() else {
841        return Vec::new();
842    };
843
844    let Some((branch_name, revision)) = current.split_once('=') else {
845        // Don't complete branch names since we want to create a new branch
846        return Vec::new();
847    };
848    revset_expression(revision.as_ref(), None)
849        .into_iter()
850        .map(|rev| rev.add_prefix(format!("{branch_name}=")))
851        .collect()
852}
853
854fn path_completion_candidate_from(
855    current_prefix: &str,
856    normalized_prefix_path: &Path,
857    path: &Path,
858    mode: Option<clap::builder::StyledStr>,
859) -> Option<CompletionCandidate> {
860    let normalized_prefix = match normalized_prefix_path.to_str()? {
861        "." => "", // `.` cannot be normalized further, but doesn't prefix `path`.
862        normalized_prefix => normalized_prefix,
863    };
864
865    let path = slash_path(path);
866    let mut remainder = path.to_str()?.strip_prefix(normalized_prefix)?;
867
868    // Trailing slash might have been normalized away in which case we need to strip
869    // the leading slash in the remainder away, or else the slash would appear
870    // twice.
871    if current_prefix.ends_with(std::path::is_separator) {
872        remainder = remainder.strip_prefix('/').unwrap_or(remainder);
873    }
874
875    match remainder.split_inclusive('/').at_most_one() {
876        // Completed component is the final component in `path`, so we're completing the file to
877        // which `mode` refers.
878        Ok(file_completion) => Some(
879            CompletionCandidate::new(format!(
880                "{current_prefix}{}",
881                file_completion.unwrap_or_default()
882            ))
883            .help(mode),
884        ),
885
886        // Omit `mode` when completing only up to the next directory.
887        Err(mut components) => Some(CompletionCandidate::new(format!(
888            "{current_prefix}{}",
889            components.next().unwrap()
890        ))),
891    }
892}
893
894fn current_prefix_to_fileset(current: &str) -> String {
895    let cur_esc = globset::escape(current);
896    let dir_pat = format!("{cur_esc}*/**");
897    let path_pat = format!("{cur_esc}*");
898    format!("glob:{dir_pat:?} | glob:{path_pat:?}")
899}
900
901fn all_files_from_rev(rev: String, current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
902    let Some(current) = current.to_str() else {
903        return Vec::new();
904    };
905
906    let normalized_prefix = normalize_path(Path::new(current));
907    let normalized_prefix = slash_path(&normalized_prefix);
908
909    with_jj(|jj, _| {
910        let mut child = jj
911            .build()
912            .arg("file")
913            .arg("list")
914            .arg("--revision")
915            .arg(rev)
916            .arg("--template")
917            .arg(r#"path.display() ++ "\n""#)
918            .arg(current_prefix_to_fileset(current))
919            .stdout(std::process::Stdio::piped())
920            .stderr(std::process::Stdio::null())
921            .spawn()
922            .map_err(user_error)?;
923        let stdout = child.stdout.take().unwrap();
924
925        Ok(std::io::BufReader::new(stdout)
926            .lines()
927            .take(1_000)
928            .map_while(Result::ok)
929            .filter_map(|path| {
930                path_completion_candidate_from(current, &normalized_prefix, Path::new(&path), None)
931            })
932            .dedup() // directories may occur multiple times
933            .collect())
934    })
935}
936
937fn modified_files_from_rev_with_jj_cmd(
938    rev: (String, Option<String>),
939    mut cmd: std::process::Command,
940    current: &std::ffi::OsStr,
941) -> Result<Vec<CompletionCandidate>, CommandError> {
942    let Some(current) = current.to_str() else {
943        return Ok(Vec::new());
944    };
945
946    let normalized_prefix = normalize_path(Path::new(current));
947    let normalized_prefix = slash_path(&normalized_prefix);
948
949    // In case of a rename, one entry of `diff` results in two suggestions.
950    let template = indoc! {r#"
951        concat(
952          status ++ ' ' ++ path.display() ++ "\n",
953          if(status == 'renamed', 'renamed.source ' ++ source.path().display() ++ "\n"),
954        )
955    "#};
956    cmd.arg("diff")
957        .args(["--template", template])
958        .arg(current_prefix_to_fileset(current));
959    match rev {
960        (rev, None) => cmd.arg("--revisions").arg(rev),
961        (from, Some(to)) => cmd.arg("--from").arg(from).arg("--to").arg(to),
962    };
963    let output = cmd.output().map_err(user_error)?;
964    let stdout = String::from_utf8_lossy(&output.stdout);
965
966    let mut include_renames = false;
967    let mut candidates: Vec<_> = stdout
968        .lines()
969        .filter_map(|line| line.split_once(' '))
970        .filter_map(|(mode, path)| {
971            let mode = match mode {
972                "modified" => "Modified".into(),
973                "removed" => "Deleted".into(),
974                "added" => "Added".into(),
975                "renamed" => "Renamed".into(),
976                "renamed.source" => {
977                    include_renames = true;
978                    "Renamed".into()
979                }
980                "copied" => "Copied".into(),
981                _ => format!("unknown mode: '{mode}'").into(),
982            };
983            path_completion_candidate_from(current, &normalized_prefix, Path::new(path), Some(mode))
984        })
985        .collect();
986
987    if include_renames {
988        candidates.sort_unstable_by(|a, b| Path::new(a.get_value()).cmp(Path::new(b.get_value())));
989    }
990    candidates.dedup();
991
992    Ok(candidates)
993}
994
995fn modified_files_from_rev(
996    rev: (String, Option<String>),
997    current: &std::ffi::OsStr,
998) -> Vec<CompletionCandidate> {
999    with_jj(|jj, _| modified_files_from_rev_with_jj_cmd(rev, jj.build(), current))
1000}
1001
1002fn conflicted_files_from_rev(rev: &str, current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1003    let Some(current) = current.to_str() else {
1004        return Vec::new();
1005    };
1006
1007    let normalized_prefix = normalize_path(Path::new(current));
1008    let normalized_prefix = slash_path(&normalized_prefix);
1009
1010    with_jj(|jj, _| {
1011        let output = jj
1012            .build()
1013            .arg("resolve")
1014            .arg("--list")
1015            .arg("--revision")
1016            .arg(rev)
1017            .arg(current_prefix_to_fileset(current))
1018            .output()
1019            .map_err(user_error)?;
1020        let stdout = String::from_utf8_lossy(&output.stdout);
1021
1022        Ok(stdout
1023            .lines()
1024            .filter_map(|line| {
1025                let path = line
1026                    .split_whitespace()
1027                    .next()
1028                    .expect("resolve --list should contain whitespace after path");
1029
1030                path_completion_candidate_from(current, &normalized_prefix, Path::new(path), None)
1031            })
1032            .dedup() // directories may occur multiple times
1033            .collect())
1034    })
1035}
1036
1037pub fn modified_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1038    modified_files_from_rev(("@".into(), None), current)
1039}
1040
1041pub fn all_revision_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1042    all_files_from_rev(parse::revision_or_wc(), current)
1043}
1044
1045pub fn modified_revision_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1046    modified_files_from_rev((parse::revision_or_wc(), None), current)
1047}
1048
1049pub fn modified_range_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1050    match parse::range() {
1051        Some((from, to)) => modified_files_from_rev((from, Some(to)), current),
1052        None => modified_files_from_rev(("@".into(), None), current),
1053    }
1054}
1055
1056/// Completes files in `@` *or* the `--from` revision (not the diff between
1057/// `--from` and `@`)
1058pub fn modified_from_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1059    modified_files_from_rev((parse::from_or_wc(), None), current)
1060}
1061
1062pub fn modified_revision_or_range_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1063    if let Some(rev) = parse::revision() {
1064        return modified_files_from_rev((rev, None), current);
1065    }
1066    modified_range_files(current)
1067}
1068
1069pub fn modified_changes_in_or_range_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1070    if let Some(rev) = parse::changes_in() {
1071        return modified_files_from_rev((rev, None), current);
1072    }
1073    modified_range_files(current)
1074}
1075
1076pub fn revision_conflicted_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1077    conflicted_files_from_rev(&parse::revision_or_wc(), current)
1078}
1079
1080/// Specific function for completing file paths for `jj squash`
1081pub fn squash_revision_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1082    let rev = parse::squash_revision().unwrap_or_else(|| "@".into());
1083    modified_files_from_rev((rev, None), current)
1084}
1085
1086/// Specific function for completing file paths for `jj interdiff`
1087pub fn interdiff_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1088    let Some((from, to)) = parse::range() else {
1089        return Vec::new();
1090    };
1091    // Complete all modified files in "from" and "to". This will also suggest
1092    // files that are the same in both, which is a false positive. This approach
1093    // is more lightweight than actually doing a temporary rebase here.
1094    with_jj(|jj, _| {
1095        let mut res = modified_files_from_rev_with_jj_cmd((from, None), jj.build(), current)?;
1096        res.extend(modified_files_from_rev_with_jj_cmd(
1097            (to, None),
1098            jj.build(),
1099            current,
1100        )?);
1101        Ok(res)
1102    })
1103}
1104
1105/// Specific function for completing file paths for `jj log`
1106pub fn log_files(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> {
1107    let mut rev = parse::log_revisions().join(")|(");
1108    if rev.is_empty() {
1109        rev = "@".into();
1110    } else {
1111        rev = format!("latest(heads(({rev})))"); // limit to one
1112    }
1113    all_files_from_rev(rev, current)
1114}
1115
1116/// Shell out to jj during dynamic completion generation
1117///
1118/// In case of errors, print them and early return an empty vector.
1119fn with_jj<F>(completion_fn: F) -> Vec<CompletionCandidate>
1120where
1121    F: FnOnce(JjBuilder, &UserSettings) -> Result<Vec<CompletionCandidate>, CommandError>,
1122{
1123    get_jj_command()
1124        .and_then(|(jj, settings)| completion_fn(jj, &settings))
1125        .unwrap_or_else(|e| {
1126            eprintln!("{}", e.error);
1127            Vec::new()
1128        })
1129}
1130
1131/// Shell out to jj during dynamic completion generation
1132///
1133/// This is necessary because dynamic completion code needs to be aware of
1134/// global configuration like custom storage backends. Dynamic completion
1135/// code via clap_complete doesn't accept arguments, so they cannot be passed
1136/// that way. Another solution would've been to use global mutable state, to
1137/// give completion code access to custom backends. Shelling out was chosen as
1138/// the preferred method, because it's more maintainable and the performance
1139/// requirements of completions aren't very high.
1140fn get_jj_command() -> Result<(JjBuilder, UserSettings), CommandError> {
1141    let current_exe = std::env::current_exe().map_err(user_error)?;
1142    let mut cmd_args = Vec::<String>::new();
1143
1144    // Snapshotting could make completions much slower in some situations
1145    // and be undesired by the user.
1146    cmd_args.push("--ignore-working-copy".into());
1147    cmd_args.push("--color=never".into());
1148    cmd_args.push("--no-pager".into());
1149
1150    // Parse some of the global args we care about for passing along to the
1151    // child process. This shouldn't fail, since none of the global args are
1152    // required.
1153    let app = crate::commands::default_app();
1154    let mut raw_config = config_from_environment(default_config_layers());
1155    let ui = Ui::null();
1156    let cwd = std::env::current_dir()
1157        .and_then(dunce::canonicalize)
1158        .map_err(user_error)?;
1159    // No config migration for completion. Simply ignore deprecated variables.
1160    let mut config_env = ConfigEnv::from_environment();
1161    let maybe_cwd_workspace_loader = DefaultWorkspaceLoaderFactory.create(find_workspace_dir(&cwd));
1162    config_env.reload_system_config(&mut raw_config).ok();
1163    config_env.reload_user_config(&mut raw_config).ok();
1164    if let Ok(loader) = &maybe_cwd_workspace_loader {
1165        config_env.reset_repo_path(loader.repo_path());
1166        config_env.reload_repo_config(&ui, &mut raw_config).ok();
1167        config_env.reset_workspace_path(loader.workspace_root());
1168        config_env
1169            .reload_workspace_config(&ui, &mut raw_config)
1170            .ok();
1171    }
1172    let mut config = config_env.resolve_config(&raw_config)?;
1173    // skip 2 because of the clap_complete prelude: jj -- jj <actual args...>
1174    let args = std::env::args_os().skip(2);
1175    let args = expand_args(&ui, &app, args, &config)?;
1176    let arg_matches = app
1177        .clone()
1178        .disable_version_flag(true)
1179        .disable_help_flag(true)
1180        .ignore_errors(true)
1181        .try_get_matches_from(args)?;
1182    let args: GlobalArgs = GlobalArgs::from_arg_matches(&arg_matches)?;
1183
1184    if let Some(repository) = args.repository {
1185        // Try to update repo-specific config on a best-effort basis.
1186        if let Ok(loader) = DefaultWorkspaceLoaderFactory.create(&cwd.join(&repository)) {
1187            config_env.reset_repo_path(loader.repo_path());
1188            config_env.reload_repo_config(&ui, &mut raw_config).ok();
1189            config_env.reset_workspace_path(loader.workspace_root());
1190            config_env
1191                .reload_workspace_config(&ui, &mut raw_config)
1192                .ok();
1193            if let Ok(new_config) = config_env.resolve_config(&raw_config) {
1194                config = new_config;
1195            }
1196        }
1197        cmd_args.push("--repository".into());
1198        cmd_args.push(repository);
1199    }
1200    if let Some(at_operation) = args.at_operation {
1201        // We cannot assume that the value of at_operation is valid, because
1202        // the user may be requesting completions precisely for this invalid
1203        // operation ID. Additionally, the user may have mistyped the ID,
1204        // in which case adding the argument blindly would break all other
1205        // completions, even unrelated ones.
1206        //
1207        // To avoid this, we shell out to ourselves once with the argument
1208        // and check the exit code. There is some performance overhead to this,
1209        // but this code path is probably only executed in exceptional
1210        // situations.
1211        let mut canary_cmd = std::process::Command::new(&current_exe);
1212        canary_cmd.args(&cmd_args);
1213        canary_cmd.arg("--at-operation");
1214        canary_cmd.arg(&at_operation);
1215        canary_cmd.arg("debug");
1216        canary_cmd.arg("snapshot");
1217
1218        match canary_cmd.output() {
1219            Ok(output) if output.status.success() => {
1220                // Operation ID is valid, add it to the completion command.
1221                cmd_args.push("--at-operation".into());
1222                cmd_args.push(at_operation);
1223            }
1224            _ => {} // Invalid operation ID, ignore.
1225        }
1226    }
1227    for (kind, value) in args.early_args.merged_config_args(&arg_matches) {
1228        let arg = match kind {
1229            ConfigArgKind::Item => format!("--config={value}"),
1230            ConfigArgKind::File => format!("--config-file={value}"),
1231        };
1232        cmd_args.push(arg);
1233    }
1234
1235    let builder = JjBuilder {
1236        cmd: current_exe,
1237        args: cmd_args,
1238    };
1239    let settings = UserSettings::from_config(config)?;
1240
1241    Ok((builder, settings))
1242}
1243
1244/// A helper struct to allow completion functions to call jj multiple times with
1245/// different arguments.
1246struct JjBuilder {
1247    cmd: std::path::PathBuf,
1248    args: Vec<String>,
1249}
1250
1251impl JjBuilder {
1252    fn build(&self) -> std::process::Command {
1253        let mut cmd = std::process::Command::new(&self.cmd);
1254        cmd.args(&self.args);
1255        cmd
1256    }
1257}
1258
1259/// Functions for parsing revisions and revision ranges from the command line.
1260/// Parsing is done on a best-effort basis and relies on the heuristic that
1261/// most command line flags are consistent across different subcommands.
1262///
1263/// In some cases, this parsing will be incorrect, but it's not worth the effort
1264/// to fix that. For example, if the user specifies any of the relevant flags
1265/// multiple times, the parsing will pick any of the available ones, while the
1266/// actual execution of the command would fail.
1267mod parse {
1268    pub(super) fn parse_flag(
1269        candidates: &[&str],
1270        mut args: impl Iterator<Item = String>,
1271    ) -> impl Iterator<Item = String> {
1272        std::iter::from_fn(move || {
1273            for arg in args.by_ref() {
1274                // -r REV syntax
1275                if candidates.contains(&arg.as_ref()) {
1276                    match args.next() {
1277                        Some(val) if !val.starts_with('-') => {
1278                            return Some(strip_shell_quotes(&val).into());
1279                        }
1280                        _ => return None,
1281                    }
1282                }
1283
1284                // -r=REV syntax
1285                if let Some(value) = candidates.iter().find_map(|candidate| {
1286                    let rest = arg.strip_prefix(candidate)?;
1287                    match rest.strip_prefix('=') {
1288                        Some(value) => Some(value),
1289
1290                        // -rREV syntax
1291                        None if candidate.len() == 2 => Some(rest),
1292
1293                        None => None,
1294                    }
1295                }) {
1296                    return Some(strip_shell_quotes(value).into());
1297                }
1298            }
1299            None
1300        })
1301    }
1302
1303    pub fn parse_revision_impl(args: impl Iterator<Item = String>) -> Option<String> {
1304        parse_flag(&["-r", "--revision"], args).next()
1305    }
1306
1307    pub fn revision() -> Option<String> {
1308        parse_revision_impl(std::env::args())
1309    }
1310
1311    pub fn parse_changes_in_impl(args: impl Iterator<Item = String>) -> Option<String> {
1312        parse_flag(&["-c", "--changes-in"], args).next()
1313    }
1314
1315    pub fn changes_in() -> Option<String> {
1316        parse_changes_in_impl(std::env::args())
1317    }
1318
1319    pub fn revision_or_wc() -> String {
1320        revision().unwrap_or_else(|| "@".into())
1321    }
1322
1323    pub fn from_or_wc() -> String {
1324        parse_flag(&["-f", "--from"], std::env::args())
1325            .next()
1326            .unwrap_or_else(|| "@".into())
1327    }
1328
1329    pub fn parse_range_impl<T>(args: impl Fn() -> T) -> Option<(String, String)>
1330    where
1331        T: Iterator<Item = String>,
1332    {
1333        let from = parse_flag(&["-f", "--from"], args()).next()?;
1334        let to = parse_flag(&["-t", "--to"], args())
1335            .next()
1336            .unwrap_or_else(|| "@".into());
1337
1338        Some((from, to))
1339    }
1340
1341    pub fn range() -> Option<(String, String)> {
1342        parse_range_impl(std::env::args)
1343    }
1344
1345    // Special parse function only for `jj squash`. While squash has --from and
1346    // --to arguments, only files within --from should be completed, because
1347    // the files changed only in some other revision in the range between
1348    // --from and --to cannot be squashed into --to like that.
1349    pub fn squash_revision() -> Option<String> {
1350        if let Some(rev) = parse_flag(&["-r", "--revision"], std::env::args()).next() {
1351            return Some(rev);
1352        }
1353        parse_flag(&["-f", "--from"], std::env::args()).next()
1354    }
1355
1356    // Special parse function only for `jj log`. It has a --revisions flag,
1357    // instead of the usual --revision, and it can be supplied multiple times.
1358    pub fn log_revisions() -> Vec<String> {
1359        let candidates = &["-r", "--revisions"];
1360        parse_flag(candidates, std::env::args()).collect()
1361    }
1362
1363    fn strip_shell_quotes(s: &str) -> &str {
1364        if s.len() >= 2
1365            && (s.starts_with('"') && s.ends_with('"') || s.starts_with('\'') && s.ends_with('\''))
1366        {
1367            &s[1..s.len() - 1]
1368        } else {
1369            s
1370        }
1371    }
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376    use super::*;
1377
1378    #[test]
1379    fn test_split_revset_trailing_name() {
1380        assert_eq!(split_revset_trailing_name(""), Some(("", "")));
1381        assert_eq!(split_revset_trailing_name(" "), Some((" ", "")));
1382        assert_eq!(split_revset_trailing_name("foo"), Some(("", "foo")));
1383        assert_eq!(split_revset_trailing_name(" foo"), Some((" ", "foo")));
1384        assert_eq!(split_revset_trailing_name("foo "), None);
1385        assert_eq!(split_revset_trailing_name("foo_"), Some(("", "foo_")));
1386        assert_eq!(split_revset_trailing_name("foo/"), Some(("", "foo/")));
1387        assert_eq!(split_revset_trailing_name("foo/b"), Some(("", "foo/b")));
1388
1389        assert_eq!(split_revset_trailing_name("foo-"), Some(("", "foo-")));
1390        assert_eq!(split_revset_trailing_name("foo+"), Some(("", "foo+")));
1391        assert_eq!(
1392            split_revset_trailing_name("foo-bar-"),
1393            Some(("", "foo-bar-"))
1394        );
1395        assert_eq!(
1396            split_revset_trailing_name("foo-bar-b"),
1397            Some(("", "foo-bar-b"))
1398        );
1399
1400        assert_eq!(split_revset_trailing_name("foo."), Some(("", "foo.")));
1401        assert_eq!(split_revset_trailing_name("foo..b"), Some(("foo..", "b")));
1402        assert_eq!(split_revset_trailing_name("..foo"), Some(("..", "foo")));
1403
1404        assert_eq!(split_revset_trailing_name("foo(bar"), Some(("foo(", "bar")));
1405        assert_eq!(split_revset_trailing_name("foo(bar)"), None);
1406        assert_eq!(split_revset_trailing_name("(f"), Some(("(", "f")));
1407
1408        assert_eq!(split_revset_trailing_name("foo@"), Some(("", "foo@")));
1409        assert_eq!(split_revset_trailing_name("foo@b"), Some(("", "foo@b")));
1410        assert_eq!(split_revset_trailing_name("..foo@"), Some(("..", "foo@")));
1411        assert_eq!(
1412            split_revset_trailing_name("::F(foo@origin.1..bar@origin."),
1413            Some(("::F(foo@origin.1..", "bar@origin."))
1414        );
1415    }
1416
1417    #[test]
1418    fn test_split_revset_trailing_name_with_trailing_operator() {
1419        assert_eq!(split_revset_trailing_name("foo|"), Some(("foo|", "")));
1420        assert_eq!(split_revset_trailing_name("foo | "), Some(("foo | ", "")));
1421        assert_eq!(split_revset_trailing_name("foo&"), Some(("foo&", "")));
1422        assert_eq!(split_revset_trailing_name("foo~"), Some(("foo~", "")));
1423
1424        assert_eq!(split_revset_trailing_name(".."), Some(("..", "")));
1425        assert_eq!(split_revset_trailing_name("foo.."), Some(("foo..", "")));
1426        assert_eq!(split_revset_trailing_name("::"), Some(("::", "")));
1427        assert_eq!(split_revset_trailing_name("foo::"), Some(("foo::", "")));
1428
1429        assert_eq!(split_revset_trailing_name("("), Some(("(", "")));
1430        assert_eq!(split_revset_trailing_name("foo("), Some(("foo(", "")));
1431        assert_eq!(split_revset_trailing_name("foo()"), None);
1432        assert_eq!(split_revset_trailing_name("foo(bar)"), None);
1433    }
1434
1435    #[test]
1436    fn test_config_keys() {
1437        // Just make sure the schema is parsed without failure.
1438        config_keys();
1439    }
1440
1441    #[test]
1442    fn test_parse_revision_impl() {
1443        let good_cases: &[&[&str]] = &[
1444            &["-r", "foo"],
1445            &["-r", "'foo'"],
1446            &["-r", "\"foo\""],
1447            &["-rfoo"],
1448            &["-r'foo'"],
1449            &["-r\"foo\""],
1450            &["--revision", "foo"],
1451            &["-r=foo"],
1452            &["-r='foo'"],
1453            &["-r=\"foo\""],
1454            &["--revision=foo"],
1455            &["--revision='foo'"],
1456            &["--revision=\"foo\""],
1457            &["preceding_arg", "-r", "foo"],
1458            &["-r", "foo", "following_arg"],
1459        ];
1460        for case in good_cases {
1461            let args = case.iter().map(|s| s.to_string());
1462            assert_eq!(
1463                parse::parse_revision_impl(args),
1464                Some("foo".into()),
1465                "case: {case:?}",
1466            );
1467        }
1468        let bad_cases: &[&[&str]] = &[&[], &["-r"], &["foo"], &["-R", "foo"], &["-R=foo"]];
1469        for case in bad_cases {
1470            let args = case.iter().map(|s| s.to_string());
1471            assert_eq!(parse::parse_revision_impl(args), None, "case: {case:?}");
1472        }
1473    }
1474
1475    #[test]
1476    fn test_parse_changes_in_impl() {
1477        let good_cases: &[&[&str]] = &[
1478            &["-c", "foo"],
1479            &["--changes-in", "foo"],
1480            &["-cfoo"],
1481            &["--changes-in=foo"],
1482        ];
1483        for case in good_cases {
1484            let args = case.iter().map(|s| s.to_string());
1485            assert_eq!(
1486                parse::parse_changes_in_impl(args),
1487                Some("foo".into()),
1488                "case: {case:?}",
1489            );
1490        }
1491        let bad_cases: &[&[&str]] = &[&[], &["-c"], &["-r"], &["foo"]];
1492        for case in bad_cases {
1493            let args = case.iter().map(|s| s.to_string());
1494            assert_eq!(parse::parse_revision_impl(args), None, "case: {case:?}");
1495        }
1496    }
1497
1498    #[test]
1499    fn test_parse_range_impl() {
1500        let wc_cases: &[&[&str]] = &[
1501            &["-f", "foo"],
1502            &["--from", "foo"],
1503            &["-f=foo"],
1504            &["preceding_arg", "-f", "foo"],
1505            &["-f", "foo", "following_arg"],
1506        ];
1507        for case in wc_cases {
1508            let args = case.iter().map(|s| s.to_string());
1509            assert_eq!(
1510                parse::parse_range_impl(|| args.clone()),
1511                Some(("foo".into(), "@".into())),
1512                "case: {case:?}",
1513            );
1514        }
1515        let to_cases: &[&[&str]] = &[
1516            &["-f", "foo", "-t", "bar"],
1517            &["-f", "foo", "--to", "bar"],
1518            &["-f=foo", "-t=bar"],
1519            &["-t=bar", "-f=foo"],
1520        ];
1521        for case in to_cases {
1522            let args = case.iter().map(|s| s.to_string());
1523            assert_eq!(
1524                parse::parse_range_impl(|| args.clone()),
1525                Some(("foo".into(), "bar".into())),
1526                "case: {case:?}",
1527            );
1528        }
1529        let bad_cases: &[&[&str]] = &[&[], &["-f"], &["foo"], &["-R", "foo"], &["-R=foo"]];
1530        for case in bad_cases {
1531            let args = case.iter().map(|s| s.to_string());
1532            assert_eq!(
1533                parse::parse_range_impl(|| args.clone()),
1534                None,
1535                "case: {case:?}"
1536            );
1537        }
1538    }
1539
1540    #[test]
1541    fn test_parse_multiple_flags() {
1542        let candidates = &["-r", "--revisions"];
1543        let args = &[
1544            "unrelated_arg_at_the_beginning",
1545            "-r",
1546            "1",
1547            "--revisions",
1548            "2",
1549            "-r=3",
1550            "--revisions=4",
1551            "unrelated_arg_in_the_middle",
1552            "-r5",
1553            "unrelated_arg_at_the_end",
1554        ];
1555        let flags: Vec<_> =
1556            parse::parse_flag(candidates, args.iter().map(|a| a.to_string())).collect();
1557        let expected = ["1", "2", "3", "4", "5"];
1558        assert_eq!(flags, expected);
1559    }
1560}