-
Notifications
You must be signed in to change notification settings - Fork 13.5k
Add --link-targets-dir
argument to linkchecker
#143883
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
Open
pietroalbini
wants to merge
4
commits into
rust-lang:master
Choose a base branch
from
pietroalbini:pa-linkchecker-extra-target
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+86
−9
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,7 @@ | ||
[package] | ||
name = "linkchecker" | ||
version = "0.1.0" | ||
edition = "2021" | ||
edition = "2024" | ||
|
||
[[bin]] | ||
name = "linkchecker" | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,12 +17,14 @@ | |
//! should catch the majority of "broken link" cases. | ||
|
||
use std::cell::{Cell, RefCell}; | ||
use std::collections::hash_map::Entry; | ||
use std::collections::{HashMap, HashSet}; | ||
use std::fs; | ||
use std::io::ErrorKind; | ||
use std::iter::once; | ||
use std::path::{Component, Path, PathBuf}; | ||
use std::rc::Rc; | ||
use std::time::Instant; | ||
use std::{env, fs}; | ||
|
||
use html5ever::tendril::ByteTendril; | ||
use html5ever::tokenizer::{ | ||
|
@@ -110,10 +112,25 @@ macro_rules! t { | |
}; | ||
} | ||
|
||
struct Cli { | ||
docs: PathBuf, | ||
link_targets_dirs: Vec<PathBuf>, | ||
} | ||
|
||
fn main() { | ||
let docs = env::args_os().nth(1).expect("doc path should be first argument"); | ||
let docs = env::current_dir().unwrap().join(docs); | ||
let mut checker = Checker { root: docs.clone(), cache: HashMap::new() }; | ||
let cli = match parse_cli() { | ||
Ok(cli) => cli, | ||
Err(err) => { | ||
eprintln!("error: {err}"); | ||
usage_and_exit(1); | ||
} | ||
}; | ||
|
||
let mut checker = Checker { | ||
root: cli.docs.clone(), | ||
link_targets_dirs: cli.link_targets_dirs, | ||
cache: HashMap::new(), | ||
}; | ||
let mut report = Report { | ||
errors: 0, | ||
start: Instant::now(), | ||
|
@@ -125,16 +142,58 @@ fn main() { | |
intra_doc_exceptions: 0, | ||
has_broken_urls: false, | ||
}; | ||
checker.walk(&docs, &mut report); | ||
checker.walk(&cli.docs, &mut report); | ||
report.report(); | ||
if report.errors != 0 { | ||
println!("found some broken links"); | ||
std::process::exit(1); | ||
} | ||
} | ||
|
||
fn parse_cli() -> Result<Cli, String> { | ||
fn to_canonical_path(arg: &str) -> Result<PathBuf, String> { | ||
PathBuf::from(arg).canonicalize().map_err(|e| format!("could not canonicalize {arg}: {e}")) | ||
} | ||
|
||
let mut verbatim = false; | ||
let mut docs = None; | ||
let mut link_targets_dirs = Vec::new(); | ||
|
||
let mut args = std::env::args().skip(1); | ||
while let Some(arg) = args.next() { | ||
if !verbatim && arg == "--" { | ||
verbatim = true; | ||
} else if !verbatim && (arg == "-h" || arg == "--help") { | ||
usage_and_exit(0) | ||
} else if !verbatim && arg == "--link-targets-dir" { | ||
link_targets_dirs.push(to_canonical_path( | ||
&args.next().ok_or("missing value for --link-targets-dir")?, | ||
)?); | ||
} else if !verbatim && let Some(value) = arg.strip_prefix("--link-targets-dir=") { | ||
link_targets_dirs.push(to_canonical_path(value)?); | ||
} else if !verbatim && arg.starts_with('-') { | ||
return Err(format!("unknown flag: {arg}")); | ||
} else if docs.is_none() { | ||
docs = Some(arg); | ||
} else { | ||
return Err("too many positional arguments".into()); | ||
} | ||
} | ||
|
||
Ok(Cli { | ||
docs: to_canonical_path(&docs.ok_or("missing first positional argument")?)?, | ||
link_targets_dirs, | ||
}) | ||
} | ||
|
||
fn usage_and_exit(code: i32) -> ! { | ||
eprintln!("usage: linkchecker PATH [--link-targets-dir=PATH ...]"); | ||
std::process::exit(code) | ||
} | ||
|
||
struct Checker { | ||
root: PathBuf, | ||
link_targets_dirs: Vec<PathBuf>, | ||
cache: Cache, | ||
} | ||
|
||
|
@@ -427,15 +486,23 @@ impl Checker { | |
let pretty_path = | ||
file.strip_prefix(&self.root).unwrap_or(file).to_str().unwrap().to_string(); | ||
|
||
let entry = | ||
self.cache.entry(pretty_path.clone()).or_insert_with(|| match fs::metadata(file) { | ||
for base in once(&self.root).chain(self.link_targets_dirs.iter()) { | ||
Comment on lines
-430
to
+489
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changing this from a closure to a loop breaks on windows, because the --- a/src/tools/linkchecker/main.rs
+++ b/src/tools/linkchecker/main.rs
@@ -439,15 +439,18 @@ fn load_file(&mut self, file: &Path, report: &mut Report) -> (String, &FileEntry
}
}
Err(e) if e.kind() == ErrorKind::NotFound => FileEntry::Missing,
- Err(e) => {
- // If a broken intra-doc link contains `::`, on windows, it will cause `ERROR_INVALID_NAME` rather than `NotFound`.
- // Explicitly check for that so that the broken link can be allowed in `LINKCHECK_EXCEPTIONS`.
- #[cfg(windows)]
+ // If a broken intra-doc link contains `::`, on windows, it
+ // will cause `ERROR_INVALID_NAME` rather than `NotFound`.
+ // Explicitly check for that so that the broken link can be
+ // allowed in `LINKCHECK_EXCEPTIONS`.
+ #[cfg(windows)]
+ Err(e)
if e.raw_os_error() == Some(ERROR_INVALID_NAME)
- && file.as_os_str().to_str().map_or(false, |s| s.contains("::"))
- {
- return FileEntry::Missing;
- }
+ && file.as_os_str().to_str().map_or(false, |s| s.contains("::")) =>
+ {
+ FileEntry::Missing
+ }
+ Err(e) => {
panic!("unexpected read error for {}: {}", file.display(), e);
}
}); |
||
let entry = self.cache.entry(pretty_path.clone()); | ||
if let Entry::Occupied(e) = &entry | ||
&& !matches!(e.get(), FileEntry::Missing) | ||
{ | ||
break; | ||
} | ||
|
||
let file = base.join(&pretty_path); | ||
entry.insert_entry(match fs::metadata(&file) { | ||
Ok(metadata) if metadata.is_dir() => FileEntry::Dir, | ||
Ok(_) => { | ||
if file.extension().and_then(|s| s.to_str()) != Some("html") { | ||
FileEntry::OtherFile | ||
} else { | ||
report.html_files += 1; | ||
load_html_file(file, report) | ||
load_html_file(&file, report) | ||
} | ||
} | ||
Err(e) if e.kind() == ErrorKind::NotFound => FileEntry::Missing, | ||
|
@@ -451,6 +518,9 @@ impl Checker { | |
panic!("unexpected read error for {}: {}", file.display(), e); | ||
} | ||
}); | ||
} | ||
|
||
let entry = self.cache.get(&pretty_path).unwrap(); | ||
(pretty_path, entry) | ||
} | ||
} | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For the record, I'm always slightly uneasy with ever using
canonicalize
. I don't think there is anything to change here since it seems to be working. I just wanted to note the risk here.