Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

help: Add a keyword feature #4630

Merged
merged 1 commit into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
* New command `jj config unset` that unsets config values. For example,
`jj config unset --user user.name`.

* `jj help` now has the flag `--keyword` (shorthand `-k`), which can give help
for some keywords (e.g. `jj help -k revsets`). To see a list of the available
keywords you can do `jj help --help`.

### Fixed bugs

* Error on `trunk()` revset resolution is now handled gracefully.
Expand Down
77 changes: 76 additions & 1 deletion cli/src/commands/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::Write as _;
use std::io::Write;

use clap::builder::PossibleValue;
use clap::builder::StyledStr;
use crossterm::style::Stylize;
use itertools::Itertools;
use tracing::instrument;

use crate::cli_util::CommandHelper;
Expand All @@ -24,14 +31,33 @@ use crate::ui::Ui;
pub(crate) struct HelpArgs {
/// Print help for the subcommand(s)
pub(crate) command: Vec<String>,
/// Show help for keywords instead of commands
#[arg(
long,
short = 'k',
conflicts_with = "command",
value_parser = KEYWORDS
.iter()
.map(|k| PossibleValue::new(k.name).help(k.description))
.collect_vec()
)]
pub(crate) keyword: Option<String>,
}
Grillo-0 marked this conversation as resolved.
Show resolved Hide resolved

#[instrument(skip_all)]
pub(crate) fn cmd_help(
_ui: &mut Ui,
ui: &mut Ui,
command: &CommandHelper,
args: &HelpArgs,
) -> Result<(), CommandError> {
if let Some(name) = &args.keyword {
let keyword = find_keyword(name).expect("clap should check this with `value_parser`");
ui.request_pager();
write!(ui.stdout(), "{}", keyword.content)?;

return Ok(());
}

let mut args_to_show_help = vec![command.app().get_name()];
args_to_show_help.extend(args.command.iter().map(|s| s.as_str()));
args_to_show_help.push("--help");
Expand All @@ -47,3 +73,52 @@ pub(crate) fn cmd_help(

Err(command_error::cli_error(help_err))
}

#[derive(Clone)]
struct Keyword {
name: &'static str,
description: &'static str,
content: &'static str,
}

// TODO: Add all documentation to keywords
//
// Maybe adding some code to build.rs to find all the docs files and build the
// `KEYWORDS` at compile time.
//
// It would be cool to follow the docs hierarchy somehow.
//
// One of the problems would be `config.md`, as it has the same name as a
// subcommand.
//
// TODO: Find a way to render markdown using ANSI escape codes.
//
// Maybe we can steal some ideas from https://github.com/martinvonz/jj/pull/3130
const KEYWORDS: &[Keyword] = &[
Keyword {
name: "revsets",
description: "A functional language for selecting a set of revision",
content: include_str!("../../../docs/revsets.md"),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does anyone know if this pointer outside of the crate will work when we publish to crates.io (as I'm supposed to do on wednesday)?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. It could be worked around by a symlink (ln -s ../docs cli), but symlink has its own problem, so I have no idea.

Copy link
Collaborator

@thoughtpolice thoughtpolice Nov 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I somewhat doubt it will, I found a rather confusing thread about it.

We should probably instead use build.rs in order to get access to OUT_DIR and just copy the files there at compile time. A minor annoyance but nothing too horrid, I guess (though I'd need to figure out how to port the Buck changes, I expect it would be very minor.)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean that we should make build.rs copy the files from docs/ into e.g. cli/srcs/docs/ so we have two copies of the files?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps, what we can do with build.rs is to fall back to ../docs if ./docs doesn't exist? We'll need docs symlink or something in order to include docs/* in the release package.

},
Keyword {
name: "tutorial",
description: "Show a tutorial to get started with jj",
content: include_str!("../../../docs/tutorial.md"),
},
];

fn find_keyword(name: &str) -> Option<&Keyword> {
KEYWORDS.iter().find(|keyword| keyword.name == name)
}

pub fn show_keyword_hint_after_help() -> StyledStr {
let mut ret = StyledStr::new();
writeln!(
ret,
"{} list available keywords. Use {} to show help for one of these keywords.",
"'jj help --help'".bold(),
"'jj help -k'".bold(),
)
Grillo-0 marked this conversation as resolved.
Show resolved Hide resolved
.unwrap();
ret
}
1 change: 1 addition & 0 deletions cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ use crate::ui::Ui;

#[derive(clap::Parser, Clone, Debug)]
#[command(disable_help_subcommand = true)]
#[command(after_long_help = help::show_keyword_hint_after_help())]
enum Command {
Abandon(abandon::AbandonArgs),
Backout(backout::BackoutArgs),
Expand Down
16 changes: 15 additions & 1 deletion cli/tests/[email protected]
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ To get started, see the tutorial at https://martinvonz.github.io/jj/latest/tutor

**Usage:** `jj [OPTIONS] [COMMAND]`

'jj help --help' list available keywords. Use 'jj help -k' to show help for one of these keywords.


###### **Subcommands:**

* `abandon` — Abandon a revision
Expand Down Expand Up @@ -1215,12 +1218,23 @@ Set the URL of a Git remote

Print this message or the help of the given subcommand(s)

**Usage:** `jj help [COMMAND]...`
**Usage:** `jj help [OPTIONS] [COMMAND]...`

###### **Arguments:**

* `<COMMAND>` — Print help for the subcommand(s)

###### **Options:**

* `-k`, `--keyword <KEYWORD>` — Show help for keywords instead of commands

Possible values:
- `revsets`:
A functional language for selecting a set of revision
- `tutorial`:
Show a tutorial to get started with jj




## `jj init`
Expand Down
59 changes: 59 additions & 0 deletions cli/tests/test_help_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,62 @@ fn test_help() {
For more information, try '--help'.
"#);
}

#[test]
fn test_help_keyword() {
let test_env = TestEnvironment::default();

// It should show help for a certain keyword if the `--keyword` flag is present
let help_cmd_stdout =
test_env.jj_cmd_success(test_env.env_root(), &["help", "--keyword", "revsets"]);
// It should be equal to the docs
assert_eq!(help_cmd_stdout, include_str!("../../docs/revsets.md"));

// It should show help for a certain keyword if the `-k` flag is present
let help_cmd_stdout = test_env.jj_cmd_success(test_env.env_root(), &["help", "-k", "revsets"]);
// It should be equal to the docs
assert_eq!(help_cmd_stdout, include_str!("../../docs/revsets.md"));

// It should give hints if a similar keyword is present
let help_cmd_stderr = test_env.jj_cmd_cli_error(test_env.env_root(), &["help", "-k", "rev"]);
insta::assert_snapshot!(help_cmd_stderr, @r#"
error: invalid value 'rev' for '--keyword <KEYWORD>'
[possible values: revsets, tutorial]

tip: a similar value exists: 'revsets'

For more information, try '--help'.
"#);

// It should give error with a hint if no similar keyword is found
let help_cmd_stderr =
test_env.jj_cmd_cli_error(test_env.env_root(), &["help", "-k", "<no-similar-keyword>"]);
insta::assert_snapshot!(help_cmd_stderr, @r#"
error: invalid value '<no-similar-keyword>' for '--keyword <KEYWORD>'
[possible values: revsets, tutorial]

For more information, try '--help'.
"#);

// The keyword flag with no argument should error with a hint
let help_cmd_stderr = test_env.jj_cmd_cli_error(test_env.env_root(), &["help", "-k"]);
insta::assert_snapshot!(help_cmd_stderr, @r#"
error: a value is required for '--keyword <KEYWORD>' but none was supplied
[possible values: revsets, tutorial]

For more information, try '--help'.
"#);

// It shouldn't show help for a certain keyword if the `--keyword` is not
// present
let help_cmd_stderr = test_env.jj_cmd_cli_error(test_env.env_root(), &["help", "revsets"]);
insta::assert_snapshot!(help_cmd_stderr, @r#"
error: unrecognized subcommand 'revsets'

tip: some similar subcommands exist: 'resolve', 'prev', 'restore', 'rebase', 'revert'

Usage: jj [OPTIONS] <COMMAND>

For more information, try '--help'.
"#);
}