Skip to content

Commit

Permalink
Merge #15
Browse files Browse the repository at this point in the history
15: Support multiline doc comments  r=matklad a=thomcc

Previously these didn't work, and it was kind of annoying trying to describe things in one line. The fix is pretty simple, most of the diff is from extending tests/it/help and regenerating it.

I thought about trying to either mirror the logic [structopt](https://github.com/TeXitoi/structopt/blob/d16cfd264d3173fe64a883dea67e9975dc7bbb2d/structopt-derive/src/doc_comments.rs#L1) or [rustdoc](https://github.com/rust-lang/rust/blob/6c2dd251bbff03c7a3092d43fb5b637eca0810e3/compiler/rustc_ast/src/util/comments.rs#L28) use... but it gets pretty convoluted.

I figure for terminal output this doesn't matter that much. Also it's easier just to preserve the way the user formatted it for now, and that gets 90% of there anyway, so long as people don't use multiline comments (which you can just not use here, if you're in the minority of rust users who prefer them).

This also ensures stuff like markdown lists stay formatted, which is a problem with structopt's approach.

I had to re-enable the `help` "test" (I dont think it's used to test anything, aside from somethign perhaps that the output matches? I wasn't sure how to test beyond that, but I did make sure to update it, so you can see the results here.

I also fixed a minor issue with how your xtask prints its help message. (This is entirely unrelated, admittedly)

Co-authored-by: Thom Chiovoloni <[email protected]>
  • Loading branch information
bors[bot] and thomcc authored Jun 10, 2021
2 parents cb5c2c4 + 6f36cfe commit 92814e1
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 13 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "xflags"
version = "0.2.1" # NB: update me in 3 places
version = "0.2.2" # NB: update me in 3 places
description = "Moderately simple command line arguments parser."
categories = ["command-line-interface"]
license = "MIT OR Apache-2.0"
Expand All @@ -14,4 +14,4 @@ exclude = [".github/", "bors.toml", "rustfmt.toml"]
members = ["xtask", "xflags-macros"]

[dependencies]
xflags-macros = { path = "./xflags-macros", version = "=0.2.1" }
xflags-macros = { path = "./xflags-macros", version = "=0.2.2" }
2 changes: 1 addition & 1 deletion xflags-macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "xflags-macros"
version = "0.2.1"
version = "0.2.2"
description = "Private implementation details of xflags."
license = "MIT OR Apache-2.0"
repository = "https://github.com/matklad/xflags"
Expand Down
16 changes: 13 additions & 3 deletions xflags-macros/src/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,10 +331,20 @@ fn emit_help(buf: &mut String, xflags: &ast::XFlags) {
w!(buf, "}}\n");
}

fn write_lines_indented(buf: &mut String, multiline_str: &str, indent: usize) {
for line in multiline_str.split('\n').map(str::trim_end) {
if line.is_empty() {
w!(buf, "\n")
} else {
w!(buf, "{blank:indent$}{}\n", line, indent = indent, blank = "");
}
}
}

fn help_rec(buf: &mut String, prefix: &str, cmd: &ast::Cmd) {
w!(buf, "{}{}\n", prefix, cmd.name);
if let Some(doc) = &cmd.doc {
w!(buf, " {}\n", doc)
write_lines_indented(buf, doc, 2);
}
let indent = if prefix.is_empty() { "" } else { " " };

Expand All @@ -355,7 +365,7 @@ fn help_rec(buf: &mut String, prefix: &str, cmd: &ast::Cmd) {
};
w!(buf, " {}{}{}\n", l, arg.val.name, r);
if let Some(doc) = &arg.doc {
w!(buf, " {}\n", doc)
write_lines_indented(buf, doc, 6)
}
}
}
Expand All @@ -374,7 +384,7 @@ fn help_rec(buf: &mut String, prefix: &str, cmd: &ast::Cmd) {
let value = flag.val.as_ref().map(|it| format!(" <{}>", it.name)).unwrap_or_default();
w!(buf, " {}--{}{}\n", short, flag.name, value);
if let Some(doc) = &flag.doc {
w!(buf, " {}\n", doc)
write_lines_indented(buf, doc, 6);
}
}
}
Expand Down
14 changes: 13 additions & 1 deletion xflags-macros/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ fn ty(p: &mut Parser) -> Result<ast::Ty> {
Ok(res)
}

fn opt_doc(p: &mut Parser) -> Result<Option<String>> {
fn opt_single_doc(p: &mut Parser) -> Result<Option<String>> {
if !p.eat_punct('#') {
return Ok(None);
}
Expand All @@ -170,6 +170,18 @@ fn opt_doc(p: &mut Parser) -> Result<Option<String>> {
Ok(Some(res))
}

fn opt_doc(p: &mut Parser) -> Result<Option<String>> {
let lines =
core::iter::from_fn(|| opt_single_doc(p).transpose()).collect::<Result<Vec<String>>>()?;
let lines = lines.join("\n");

if lines.is_empty() {
Ok(None)
} else {
Ok(Some(lines))
}
}

fn cmd_name(p: &mut Parser) -> Result<String> {
let name = p.expect_name()?;
if name.starts_with('-') {
Expand Down
35 changes: 31 additions & 4 deletions xflags-macros/tests/it/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use std::{ffi::OsString, path::PathBuf};

#[derive(Debug)]
pub struct Helpful {
pub src: Option<PathBut>,
pub src: Option<PathBuf>,
pub extra: Option<String>,

pub switch: (),
pub subcommand: HelpfulCmd,
Expand All @@ -15,7 +16,9 @@ pub enum HelpfulCmd {
}

#[derive(Debug)]
pub struct Sub;
pub struct Sub {
pub flag: bool,
}

impl Helpful {
pub const HELP: &'static str = Self::HELP_;
Expand Down Expand Up @@ -47,6 +50,7 @@ impl Helpful {
let mut switch = Vec::new();

let mut src = (false, Vec::new());
let mut extra = (false, Vec::new());

let mut sub_ = None;
while let Some(arg_) = p_.pop_flag() {
Expand All @@ -64,7 +68,12 @@ impl Helpful {
_ => (),
}
if let (done_ @ false, buf_) = &mut src {
buf_.push(p_.value_from_str::<PathBut>("src", arg_)?);
buf_.push(arg_.into());
*done_ = true;
continue;
}
if let (done_ @ false, buf_) = &mut extra {
buf_.push(p_.value_from_str::<String>("extra", arg_)?);
*done_ = true;
continue;
}
Expand All @@ -74,6 +83,7 @@ impl Helpful {
}
Ok(Self {
src: p_.optional("src", src.1)?,
extra: p_.optional("extra", extra.1)?,

switch: p_.required("--switch", switch)?,
subcommand: p_.subcommand(sub_)?,
Expand All @@ -83,28 +93,40 @@ impl Helpful {

impl Sub {
fn parse_(p_: &mut xflags::rt::Parser) -> xflags::Result<Self> {
let mut flag = Vec::new();

while let Some(arg_) = p_.pop_flag() {
match arg_ {
Ok(flag_) => match flag_.as_str() {
"--flag" | "-f" => flag.push(()),
_ => return Err(p_.unexpected_flag(&flag_)),
},
Err(arg_) => {
return Err(p_.unexpected_arg(arg_));
}
}
}
Ok(Self {})
Ok(Self { flag: p_.optional("--flag", flag)?.is_some() })
}
}
impl Helpful {
const HELP_: &'static str = "\
helpful
Does stuff
Helpful stuff.
ARGS:
[src]
With an arg.
[extra]
Another arg.
This time, we provide some extra info about the
arg. Maybe some caveats, or what kinds of
values are accepted.
OPTIONS:
-s, --switch
And a switch.
Expand All @@ -113,5 +135,10 @@ SUBCOMMANDS:
helpful sub
And even a subcommand!
OPTIONS:
-f, --flag
With an optional flag. This has a really long
description which spans multiple lines.
";
}
1 change: 1 addition & 0 deletions xflags-macros/tests/it/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod repeated_pos;
mod smoke;
mod subcommands;
mod help;

use std::{ffi::OsString, fmt};

Expand Down
13 changes: 12 additions & 1 deletion xflags-macros/tests/it/src/help.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
xflags! {
/// Does stuff
///
/// Helpful stuff.
cmd helpful
/// With an arg.
optional src: PathBut
optional src: PathBuf
/// Another arg.
///
/// This time, we provide some extra info about the
/// arg. Maybe some caveats, or what kinds of
/// values are accepted.
optional extra: String
{
/// And a switch.
required -s, --switch

/// And even a subcommand!
cmd sub {
/// With an optional flag. This has a really long
/// description which spans multiple lines.
optional -f, --flag
}
}
}
2 changes: 1 addition & 1 deletion xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ fn try_main() -> Result<()> {
fn print_usage() {
eprintln!(
"\
Usage: cargo run -p xtask <SUBCOMMAND>
Usage: cargo run -p xtask -- <SUBCOMMAND>
SUBCOMMANDS:
ci
Expand Down

0 comments on commit 92814e1

Please sign in to comment.