clap/examples/git-derive.rs

166 lines
4.2 KiB
Rust
Raw Permalink Normal View History

use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand, ValueEnum};
/// A fictional versioning CLI
docs: Move everything to docs.rs A couple of things happened when preparing to release 3.0 - We needed derive documentation - I had liked how serde handled theres - I had bad experiences finding things in structopt's documentation - The examples were broken and we needed tests - The examples seemed to follow a pattern of having tutorial content and cookbook content - We had been getting bug reports from people looking at master and thinking they were looking at what is currently released - We had gotten feedback to keep down the number of places that documentation was located From this, we went with a mix of docs.rs and github - We kept the number of content locations at 2 rather than 3 by not having an external site like serde - We rewrote the examples into explicit tutorials and cookbooks to align with the 4 styles of documentation - We could test our examples by running `console` code blocks with trycmd - Documentation was versioned and the README pointed to the last release This had downsides - The tutorials didn't have the code inlined - Users still had a hard time finding and navigating between the different forms of documentation - In practice, we were less likely to cross-link between the different types of documentation Moving to docs.rs would offer a lot of benefits, even if it is only designed for Rust-reference documentation and isn't good for Rust derive reference documentation, tutorials, cookbooks, etc. The big problem was keeping the examples tested to keep maintenance costs down. Maybe its just me but its easy to overlook - You can pull documentation from a file using `#[doc = "path"]` - Repeated doc attributes get concatenated rather than first or last writer winning Remember these when specifically thinking about Rust documentation made me realize that we could get everything into docs.rs. When doing this - Tutorial code got brought in as was one of the aims - We needed to split the lib documentation and the README to have all of the linking work. This allowed us to specialize them according to their rule (user vs contributor) - We needed to avoid users getting caught up in making a decision between Derive and Builder APIs so we put the focus on the derive API with links to the FAQ to help users decide when to use one or the other. - Improved cross-referencing between different parts of the documentation - Limited inline comments were added to example code - Introductory example code intentionally does not have teaching comments in it as its meant to give a flavor or sense of things and not meant to teach on its own. This is a first attempt. There will be a lot of room for further improvement. Current know downsides: - Content source is more split up for the tutorials This hopefully addresses #3189
2022-07-19 18:29:31 +00:00
#[derive(Debug, Parser)] // requires `derive` feature
#[command(name = "git")]
#[command(about = "A fictional versioning CLI", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
/// Clones repos
#[command(arg_required_else_help = true)]
Clone {
/// The remote to clone
remote: String,
},
/// Compare two commits
Diff {
#[arg(value_name = "COMMIT")]
base: Option<OsString>,
#[arg(value_name = "COMMIT")]
head: Option<OsString>,
#[arg(last = true)]
path: Option<OsString>,
#[arg(
long,
require_equals = true,
value_name = "WHEN",
num_args = 0..=1,
default_value_t = ColorWhen::Auto,
default_missing_value = "always",
value_enum
)]
color: ColorWhen,
},
/// pushes things
#[command(arg_required_else_help = true)]
Push {
/// The remote to target
remote: String,
},
/// adds things
#[command(arg_required_else_help = true)]
Add {
/// Stuff to add
#[arg(required = true)]
path: Vec<PathBuf>,
},
Stash(StashArgs),
#[command(external_subcommand)]
External(Vec<OsString>),
}
#[derive(ValueEnum, Copy, Clone, Debug, PartialEq, Eq)]
enum ColorWhen {
Always,
Auto,
Never,
}
impl std::fmt::Display for ColorWhen {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value()
.expect("no values are skipped")
.get_name()
.fmt(f)
}
}
#[derive(Debug, Args)]
#[command(args_conflicts_with_subcommands = true)]
#[command(flatten_help = true)]
struct StashArgs {
#[command(subcommand)]
command: Option<StashCommands>,
#[command(flatten)]
push: StashPushArgs,
}
#[derive(Debug, Subcommand)]
enum StashCommands {
Push(StashPushArgs),
Pop { stash: Option<String> },
Apply { stash: Option<String> },
}
#[derive(Debug, Args)]
struct StashPushArgs {
#[arg(short, long)]
message: Option<String>,
}
fn main() {
let args = Cli::parse();
match args.command {
Commands::Clone { remote } => {
println!("Cloning {remote}");
}
Commands::Diff {
mut base,
mut head,
mut path,
color,
} => {
if path.is_none() {
path = head;
head = None;
if path.is_none() {
path = base;
base = None;
}
}
let base = base
.as_deref()
.map(|s| s.to_str().unwrap())
.unwrap_or("stage");
let head = head
.as_deref()
.map(|s| s.to_str().unwrap())
.unwrap_or("worktree");
let path = path.as_deref().unwrap_or_else(|| OsStr::new(""));
println!(
"Diffing {}..{} {} (color={})",
base,
head,
path.to_string_lossy(),
color
);
}
Commands::Push { remote } => {
println!("Pushing to {remote}");
}
Commands::Add { path } => {
println!("Adding {path:?}");
}
Commands::Stash(stash) => {
let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push));
match stash_cmd {
StashCommands::Push(push) => {
println!("Pushing {push:?}");
}
StashCommands::Pop { stash } => {
println!("Popping {stash:?}");
}
StashCommands::Apply { stash } => {
println!("Applying {stash:?}");
}
}
}
Commands::External(args) => {
println!("Calling out to {:?} with {:?}", &args[0], &args[1..]);
}
}
// Continued program logic goes here...
}