Make ruff_cli binary a small wrapper around lib (#3398)

This commit is contained in:
Micha Reiser 2023-03-08 12:11:55 +01:00 committed by GitHub
parent d9dfec30eb
commit a3de791f0a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 457 additions and 453 deletions

View file

@ -1,13 +1,15 @@
//! Generate CLI help.
#![allow(clippy::print_stdout, clippy::print_stderr)]
#![allow(clippy::print_stdout)]
use std::path::PathBuf;
use std::{fs, str};
use anyhow::{bail, Result};
use anyhow::{bail, Context, Result};
use clap::CommandFactory;
use pretty_assertions::StrComparison;
use ruff_cli::args;
use crate::generate_all::REGENERATE_ALL_COMMAND;
use crate::generate_all::{Mode, REGENERATE_ALL_COMMAND};
use crate::ROOT_DIR;
const COMMAND_HELP_BEGIN_PRAGMA: &str = "<!-- Begin auto-generated command help. -->\n";
@ -18,12 +20,8 @@ const SUBCOMMAND_HELP_END_PRAGMA: &str = "<!-- End auto-generated subcommand hel
#[derive(clap::Args)]
pub struct Args {
/// Write the generated help to stdout (rather than to `docs/configuration.md`).
#[arg(long)]
pub(crate) dry_run: bool,
/// Don't write to the file, check if the file is up-to-date and error if not
#[arg(long)]
pub(crate) check: bool,
#[arg(long, default_value_t, value_enum)]
pub(crate) mode: Mode,
}
fn trim_lines(s: &str) -> String {
@ -36,59 +34,63 @@ fn replace_docs_section(
section: &str,
begin_pragma: &str,
end_pragma: &str,
) -> String {
) -> Result<String> {
// Extract the prefix.
let index = existing
.find(begin_pragma)
.expect("Unable to find begin pragma");
.with_context(|| "Unable to find begin pragma")?;
let prefix = &existing[..index + begin_pragma.len()];
// Extract the suffix.
let index = existing
.find(end_pragma)
.expect("Unable to find end pragma");
.with_context(|| "Unable to find end pragma")?;
let suffix = &existing[index..];
format!("{prefix}\n{section}{suffix}")
Ok(format!("{prefix}\n{section}{suffix}"))
}
pub fn main(args: &Args) -> Result<()> {
pub(super) fn main(args: &Args) -> Result<()> {
// Generate `ruff help`.
let command_help = trim_lines(ruff_cli::command_help().trim());
let command_help = trim_lines(&help_text());
// Generate `ruff help check`.
let subcommand_help = trim_lines(ruff_cli::subcommand_help().trim());
let subcommand_help = trim_lines(&check_help_text());
if args.dry_run {
if args.mode.is_dry_run() {
print!("{command_help}");
print!("{subcommand_help}");
} else {
// Read the existing file.
let filename = "docs/configuration.md";
let file = PathBuf::from(ROOT_DIR).join(filename);
let existing = fs::read_to_string(&file)?;
return Ok(());
}
let new = replace_docs_section(
&existing,
&format!("```text\n{command_help}\n```\n\n"),
COMMAND_HELP_BEGIN_PRAGMA,
COMMAND_HELP_END_PRAGMA,
);
let new = replace_docs_section(
&new,
&format!("```text\n{subcommand_help}\n```\n\n"),
SUBCOMMAND_HELP_BEGIN_PRAGMA,
SUBCOMMAND_HELP_END_PRAGMA,
);
// Read the existing file.
let filename = "docs/configuration.md";
let file = PathBuf::from(ROOT_DIR).join(filename);
let existing = fs::read_to_string(&file)?;
if args.check {
let new = replace_docs_section(
&existing,
&format!("```text\n{command_help}\n```\n\n"),
COMMAND_HELP_BEGIN_PRAGMA,
COMMAND_HELP_END_PRAGMA,
)?;
let new = replace_docs_section(
&new,
&format!("```text\n{subcommand_help}\n```\n\n"),
SUBCOMMAND_HELP_BEGIN_PRAGMA,
SUBCOMMAND_HELP_END_PRAGMA,
)?;
match args.mode {
Mode::Check => {
if existing == new {
println!("up-to-date: {filename}");
} else {
let comparison = StrComparison::new(&existing, &new);
bail!("{filename} changed, please run `{REGENERATE_ALL_COMMAND}`:\n{comparison}");
}
} else {
}
_ => {
fs::write(file, &new)?;
}
}
@ -96,16 +98,33 @@ pub fn main(args: &Args) -> Result<()> {
Ok(())
}
/// Returns the output of `ruff help`.
fn help_text() -> String {
args::Args::command().render_help().to_string()
}
/// Returns the output of `ruff help check`.
fn check_help_text() -> String {
let mut cmd = args::Args::command();
// The build call is necessary for the help output to contain `Usage: ruff
// check` instead of `Usage: check` see https://github.com/clap-rs/clap/issues/4685
cmd.build();
cmd.find_subcommand_mut("check")
.expect("`check` subcommand not found")
.render_help()
.to_string()
}
#[cfg(test)]
mod test {
use super::{main, Args};
use crate::generate_all::Mode;
use anyhow::Result;
#[test]
fn test_generate_json_schema() -> Result<()> {
main(&Args {
dry_run: false,
check: true,
})
main(&Args { mode: Mode::Check })
}
}