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

Switch to pico-args #116

Merged
merged 4 commits into from
Nov 27, 2020
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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@

## NEXT (UNRELEASED)

#### Added

* `cargo-deadlinks` now allows passing arguments to `cargo doc`, using `cargo deadlinks -- <CARGO_ARGS>`. [PR#116]
* `deadlinks` now allows specifying multiple directories to check. [PR#116]

#### Fixed

* Warnings from cargo are no longer silenced when documenting. [PR#114]
* `cargo deadlinks` no longer ignores all directories on Windows. [PR#121]

#### Changes

* Argument parsing now uses `pico-args`, not `docopt`. [PR#116]
* Running `cargo-deadlinks` (not `cargo deadlinks`) now gives a better error message. [PR#116]
* Both binaries now print the name of the binary when passed `--version`. [PR#116]

[PR#114]: https://github.com/deadlinks/cargo-deadlinks/pull/114
[PR#116]: https://github.com/deadlinks/cargo-deadlinks/pull/116
[PR#121]: https://github.com/deadlinks/cargo-deadlinks/pull/121

<a name="0.6.1"></a>
Expand Down
26 changes: 7 additions & 19 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ default = ["cargo"]
cached = { version = "0.20.0", default-features = false }
cargo_metadata = { version = "0.12", optional = true }
serde_json = { version = "1.0.34", optional = true }
docopt = "1"
pico-args = "0.3"
env_logger = "0.8"
lol_html = "0.2"
log = "0.4"
Expand Down
71 changes: 58 additions & 13 deletions src/bin/cargo-deadlinks.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::env;
use std::ffi::OsString;
use std::io::BufReader;
use std::path::PathBuf;
use std::process::{self, Command};

use cargo_metadata::{Message, MetadataCommand};
use docopt::Docopt;
use serde_derive::Deserialize;

use cargo_deadlinks::{walk_dir, CheckContext};
Expand All @@ -15,7 +15,7 @@ const MAIN_USAGE: &str = "
Check your package's documentation for dead links.

Usage:
cargo deadlinks [--dir <directory>] [options]
cargo deadlinks [--dir <directory>] [options] [-- <CARGO_ARGS>]

Options:
-h --help Print this message.
Expand All @@ -36,6 +36,7 @@ struct MainArgs {
flag_check_http: bool,
flag_no_build: bool,
flag_ignore_fragments: bool,
cargo_args: Vec<OsString>,
}

impl From<&MainArgs> for CheckContext {
Expand All @@ -48,20 +49,63 @@ impl From<&MainArgs> for CheckContext {
}
}

fn parse_args() -> Result<MainArgs, shared::PicoError> {
use pico_args::*;

let mut args: Vec<_> = std::env::args_os().collect();
args.remove(0);
if args.get(0).map_or(true, |arg| arg != "deadlinks") {
return Err(Error::ArgumentParsingFailed {
cause: "cargo-deadlinks should be run as `cargo deadlinks`".into(),
}
.into());
}
args.remove(0);

let cargo_args = if let Some(dash_dash) = args.iter().position(|arg| arg == "--") {
let c = args.drain(dash_dash + 1..).collect();
args.pop();
c
} else {
Vec::new()
};

let mut args = Arguments::from_vec(args);
if args.contains(["-V", "--version"]) {
println!(concat!("cargo-deadlinks ", env!("CARGO_PKG_VERSION")));
std::process::exit(0);
} else if args.contains(["-h", "--help"]) {
println!("{}", MAIN_USAGE);
std::process::exit(0);
}
let main_args = MainArgs {
arg_directory: args.opt_value_from_str("--dir")?,
flag_verbose: args.contains(["-v", "--verbose"]),
flag_debug: args.contains("--debug"),
flag_no_build: args.contains("--no-build"),
flag_ignore_fragments: args.contains("--ignore-fragments"),
flag_check_http: args.contains("--check-http"),
cargo_args,
};
args.finish()?;
Ok(main_args)
}

fn main() {
let args: MainArgs = Docopt::new(MAIN_USAGE)
.and_then(|d| {
d.version(Some(env!("CARGO_PKG_VERSION").to_owned()))
.deserialize()
})
.unwrap_or_else(|e| e.exit());
let args: MainArgs = match parse_args() {
Ok(args) => args,
Err(err) => {
eprintln!("error: {}", err);
std::process::exit(1)
}
};

shared::init_logger(args.flag_debug, args.flag_verbose, "cargo_deadlinks");

let dirs = args
.arg_directory
.as_ref()
.map_or_else(|| determine_dir(args.flag_no_build), |dir| vec![dir.into()]);
let dirs = args.arg_directory.as_ref().map_or_else(
|| determine_dir(args.flag_no_build, &args.cargo_args),
|dir| vec![dir.into()],
);

let ctx = CheckContext::from(&args);
let mut errors = false;
Expand Down Expand Up @@ -103,7 +147,7 @@ fn main() {
/// Otherwise, build the documentation and have cargo itself tell us where it is.
///
/// All *.html files under the root directory will be checked.
fn determine_dir(no_build: bool) -> Vec<PathBuf> {
fn determine_dir(no_build: bool, cargo_args: &[OsString]) -> Vec<PathBuf> {
if no_build {
eprintln!("warning: --no-build ignores `doc = false` and may have other bugs");
let manifest = MetadataCommand::new()
Expand Down Expand Up @@ -143,6 +187,7 @@ fn determine_dir(no_build: bool) -> Vec<PathBuf> {
"--message-format",
"json-render-diagnostics",
])
.args(cargo_args)
.stdout(process::Stdio::piped())
// spawn instead of output() allows running deadlinks and cargo in parallel;
// this is helpful when you have many dependencies that take a while to document
Expand Down
65 changes: 46 additions & 19 deletions src/bin/deadlinks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::path::PathBuf;
use std::process;

use cargo_deadlinks::{walk_dir, CheckContext};
use docopt::Docopt;
use serde_derive::Deserialize;

mod shared;
Expand All @@ -11,7 +10,7 @@ const MAIN_USAGE: &str = "
Check your package's documentation for dead links.

Usage:
deadlinks <directory> [options]
deadlinks [options] <directory>...

Options:
-h --help Print this message
Expand All @@ -24,15 +23,15 @@ Options:

#[derive(Debug, Deserialize)]
struct MainArgs {
arg_directory: PathBuf,
arg_directory: Vec<PathBuf>,
flag_verbose: bool,
flag_debug: bool,
flag_check_http: bool,
flag_ignore_fragments: bool,
}

impl From<MainArgs> for CheckContext {
fn from(args: MainArgs) -> CheckContext {
impl From<&MainArgs> for CheckContext {
fn from(args: &MainArgs) -> CheckContext {
CheckContext {
check_http: args.flag_check_http,
verbose: args.flag_debug,
Expand All @@ -41,24 +40,52 @@ impl From<MainArgs> for CheckContext {
}
}

fn main() {
let args: MainArgs = Docopt::new(MAIN_USAGE)
.and_then(|d| {
d.version(Some(env!("CARGO_PKG_VERSION").to_owned()))
.deserialize()
})
.unwrap_or_else(|e| e.exit());
shared::init_logger(args.flag_debug, args.flag_verbose, "deadlinks");
fn parse_args() -> Result<MainArgs, shared::PicoError> {
let mut args = pico_args::Arguments::from_env();
if args.contains(["-V", "--version"]) {
println!(concat!("deadlinks ", env!("CARGO_PKG_VERSION")));
std::process::exit(0);
} else if args.contains(["-h", "--help"]) {
println!("{}", MAIN_USAGE);
std::process::exit(0);
}
Ok(MainArgs {
flag_verbose: args.contains(["-v", "--verbose"]),
flag_debug: args.contains("--debug"),
flag_ignore_fragments: args.contains("--ignore-fragments"),
flag_check_http: args.contains("--check-http"),
arg_directory: args.free_os()?.into_iter().map(Into::into).collect(),
})
}

let dir = match args.arg_directory.canonicalize() {
Ok(dir) => dir,
Err(_) => {
println!("Could not find directory {:?}.", args.arg_directory);
fn main() {
let args = match parse_args() {
Ok(args) => args,
Err(err) => {
println!("error: {}", err);
process::exit(1);
}
};
log::info!("checking directory {:?}", dir);
if walk_dir(&dir, args.into()) {
if args.arg_directory.is_empty() {
eprintln!("error: missing <directory> argument");
process::exit(1);
}
shared::init_logger(args.flag_debug, args.flag_verbose, "deadlinks");

let mut errors = false;
let ctx = CheckContext::from(&args);
for relative_dir in args.arg_directory {
let dir = match relative_dir.canonicalize() {
Ok(dir) => dir,
Err(_) => {
println!("Could not find directory {:?}.", relative_dir);
process::exit(1);
}
};
log::info!("checking directory {:?}", dir);
errors |= walk_dir(&dir, ctx.clone());
}
if errors {
process::exit(1);
}
}
25 changes: 25 additions & 0 deletions src/bin/shared.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use log::LevelFilter;
use pico_args::Error;
use std::fmt::{self, Display};

/// Initalizes the logger according to the provided config flags.
pub fn init_logger(debug: bool, verbose: bool, krate: &str) {
Expand All @@ -14,3 +16,26 @@ pub fn init_logger(debug: bool, verbose: bool, krate: &str) {
}
builder.parse_default_env().init();
}

// See https://github.com/RazrFalcon/pico-args/pull/26
pub struct PicoError(pub Error);

impl Display for PicoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
Error::ArgumentParsingFailed { cause } => {
write!(f, "failed to parse arguments: {}", cause)
}
Error::Utf8ArgumentParsingFailed { value, cause } => {
write!(f, "failed to parse '{}': {}", value, cause)
}
_ => self.0.fmt(f),
}
}
}

impl From<Error> for PicoError {
fn from(err: Error) -> Self {
Self(err)
}
}
1 change: 1 addition & 0 deletions tests/broken_links/hardcoded-target/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<a href="./x.html"></a>
9 changes: 9 additions & 0 deletions tests/cli_args/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "cli_args"
version = "0.1.0"
authors = ["Joshua Nelson <jyn514@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
2 changes: 2 additions & 0 deletions tests/cli_args/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
//! Links to [Private]
struct Private;
Loading