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

Split cargo-deadlinks and deadlinks into two binaries #87

Merged
merged 3 commits into from
Nov 18, 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
26 changes: 17 additions & 9 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@ jobs:
include:
- name: linux
os: ubuntu-latest
artifact_name: cargo-deadlinks
asset_name: deadlinks-linux
suffix: ""
asset_suffix: -linux
- name: windows
os: windows-latest
artifact_name: cargo-deadlinks.exe
asset_name: deadlinks-windows
suffix: .exe
asset_suffix: -windows
- name: macos
os: macos-latest
artifact_name: cargo-deadlinks
asset_name: deadlinks-macos
suffix: ""
asset_suffix: -macos

steps:
- uses: actions/checkout@v1
Expand All @@ -38,10 +38,18 @@ jobs:
- name: Build
run: cargo build --release

- name: Upload binaries to release
- name: Upload `deadlinks` binaries
uses: svenstaro/upload-release-action@v1-release
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: target/release/${{ matrix.artifact_name }}
asset_name: ${{ matrix.asset_name }}
file: target/release/deadlinks${{ matrix.suffix }}
asset_name: deadlinks${{ matrix.asset_suffix }}
tag: ${{ github.ref }}

- name: Upload `cargo-deadlinks` binaries
uses: svenstaro/upload-release-action@v1-release
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: target/release/cargo-deadlinks${{ matrix.suffix }}
asset_name: cargo-deadlinks${{ matrix.asset_suffix }}
tag: ${{ github.ref }}
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
#### Added

* `RUST_LOG` is now read, and controls logging. [PR#100]
* There is now a separate `deadlinks` binary which doesn't depend on cargo in any way. [PR#87]

#### Changes

* Errors are now printed to stdout, not stderr. [PR#100]
* Logging now follows the standard `env_logger` format. [PR#100]
* `--debug` and `--verbose` are deprecated in favor of `RUST_LOG`. [PR#100]

[PR#87]: https://github.com/deadlinks/cargo-deadlinks/pull/87
[PR#100]: https://github.com/deadlinks/cargo-deadlinks/pull/100

<a name="0.5.0"></a>
Expand Down
17 changes: 15 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,23 @@ edition = "2018"
repository = "https://github.com/deadlinks/cargo-deadlinks"
readme = "README.md"
license = "MIT OR Apache-2.0"
autobins = false
default-run = "deadlinks"

[[bin]]
name = "cargo-deadlinks"
required-features = ["cargo"]

[[bin]]
name = "deadlinks"

[features]
cargo = ["cargo_metadata", "serde_json"]
default = ["cargo"]

[dependencies]
cargo_metadata = "0.9"
cargo_metadata = { version = "0.9", optional = true }
serde_json = { version = "1.0.34", optional = true }
docopt = "1"
env_logger = "0.8"
lol_html = "0.2"
Expand All @@ -21,7 +35,6 @@ serde = "1.0"
serde_derive = "1.0"
url = "2"
walkdir = "2.1"
serde_json = "1.0.34"

[dev-dependencies]
assert_cmd = "1.0"
Expand Down
64 changes: 11 additions & 53 deletions src/main.rs → src/bin/cargo-deadlinks.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
use serde_derive::Deserialize;

use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::process;

use cargo_metadata::MetadataCommand;
use docopt::Docopt;
use log::LevelFilter;
use serde_derive::Deserialize;

use rayon::{prelude::*, ThreadPoolBuilder};
use cargo_deadlinks::{walk_dir, CheckContext};

use cargo_deadlinks::{unavailable_urls, CheckContext};
mod shared;

const MAIN_USAGE: &str = "
Check your package's documentation for dead links.
Expand All @@ -34,10 +32,11 @@ struct MainArgs {
flag_check_http: bool,
}

impl Into<CheckContext> for MainArgs {
fn into(self) -> CheckContext {
impl From<MainArgs> for CheckContext {
fn from(args: MainArgs) -> CheckContext {
CheckContext {
check_http: self.flag_check_http,
check_http: args.flag_check_http,
verbose: args.flag_debug,
}
}
}
Expand All @@ -50,13 +49,14 @@ fn main() {
})
.unwrap_or_else(|e| e.exit());

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

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

let ctx = CheckContext::from(args);
let mut errors = false;
for dir in dirs {
let dir = match dir.canonicalize() {
Expand All @@ -69,7 +69,7 @@ fn main() {
}
};
log::info!("checking directory {:?}", dir);
if walk_dir(&dir, &args) {
if walk_dir(&dir, ctx.clone()) {
errors = true;
}
}
Expand All @@ -78,21 +78,6 @@ fn main() {
}
}

/// Initalizes the logger according to the provided config flags.
fn init_logger(args: &MainArgs) {
let mut builder = env_logger::Builder::new();
match (args.flag_debug, args.flag_verbose) {
(true, _) => {
builder.filter(Some("cargo_deadlinks"), LevelFilter::Debug);
}
(false, true) => {
builder.filter(Some("cargo_deadlinks"), LevelFilter::Info);
}
_ => {}
}
builder.parse_default_env().init();
}

/// Returns the directory to use as root of the documentation.
///
/// If an directory has been provided as CLI argument that one is used.
Expand Down Expand Up @@ -143,33 +128,6 @@ fn has_docs(target: &cargo_metadata::Target) -> bool {
}
}

/// Traverses a given path recursively, checking all *.html files found.
///
/// Returns whether an error occurred.
fn walk_dir(dir_path: &Path, args: &MainArgs) -> bool {
let pool = ThreadPoolBuilder::new()
.num_threads(num_cpus::get())
.build()
.unwrap();

let ctx = CheckContext {
check_http: args.flag_check_http,
};
pool.install(|| {
unavailable_urls(dir_path, &ctx)
.map(|err| {
if args.flag_debug {
println!("{}", err);
} else {
println!("{}", err.print_shortened(Some(dir_path)));
}
true
})
// ||||||
.reduce(|| false, |initial, new| initial || new)
})
}

#[cfg(test)]
mod test {
use super::has_docs;
Expand Down
61 changes: 61 additions & 0 deletions src/bin/deadlinks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::path::PathBuf;
use std::process;

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

mod shared;

const MAIN_USAGE: &str = "
Check your package's documentation for dead links.
Usage:
deadlinks <directory> [options]
Options:
-h --help Print this message
--check-http Check 'http' and 'https' scheme links
--debug Use debug output
-v --verbose Use verbose output
-V --version Print version info and exit.
";

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

impl From<MainArgs> for CheckContext {
fn from(args: MainArgs) -> CheckContext {
CheckContext {
check_http: args.flag_check_http,
verbose: args.flag_debug,
}
}
}

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");

let dir = match args.arg_directory.canonicalize() {
Ok(dir) => dir,
Err(_) => {
println!("Could not find directory {:?}.", args.arg_directory);
process::exit(1);
}
};
log::info!("checking directory {:?}", dir);
if walk_dir(&dir, args.into()) {
process::exit(1);
}
}
16 changes: 16 additions & 0 deletions src/bin/shared.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use log::LevelFilter;

/// Initalizes the logger according to the provided config flags.
pub fn init_logger(debug: bool, verbose: bool, krate: &str) {
let mut builder = env_logger::Builder::new();
match (debug, verbose) {
(true, _) => {
builder.filter(Some(krate), LevelFilter::Debug);
}
(false, true) => {
builder.filter(Some(krate), LevelFilter::Info);
}
_ => {}
}
builder.parse_default_env().init();
}
9 changes: 8 additions & 1 deletion src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,14 @@ mod test {
let cwd = env::current_dir().unwrap();
let url = Url::from_file_path(cwd.join(path)).unwrap();

check_file_url(&url, &CheckContext { check_http: false }).unwrap();
check_file_url(
&url,
&CheckContext {
verbose: false,
check_http: false,
},
)
.unwrap();
}

#[test]
Expand Down
30 changes: 29 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
};

use rayon::prelude::*;
use rayon::ThreadPoolBuilder;
use walkdir::{DirEntry, WalkDir};

use check::is_available;
Expand All @@ -14,9 +15,11 @@ pub use check::{CheckError, HttpError};
mod check;
mod parse;

#[derive(Debug)]
// NOTE: this could be Copy, but we intentionally choose not to guarantee that.
#[derive(Clone, Debug)]
pub struct CheckContext {
pub check_http: bool,
pub verbose: bool,
}

#[derive(Debug)]
Expand All @@ -32,6 +35,31 @@ impl fmt::Display for FileError {
}
}

/// Traverses a given path recursively, checking all *.html files found.
///
/// For each error that occurred, print an error message.
/// Returns whether an error occurred.
pub fn walk_dir(dir_path: &Path, ctx: CheckContext) -> bool {
let pool = ThreadPoolBuilder::new()
.num_threads(num_cpus::get())
.build()
.unwrap();

pool.install(|| {
unavailable_urls(dir_path, &ctx)
.map(|err| {
if ctx.verbose {
println!("{}", err);
} else {
println!("{}", err.print_shortened(Some(dir_path)));
}
true
})
// ||||||
.reduce(|| false, |initial, new| initial || new)
})
}

impl FileError {
pub fn print_shortened(&self, prefix: Option<&Path>) -> String {
let prefix = prefix.unwrap_or_else(|| Path::new(""));
Expand Down