Skip to content

Commit

Permalink
feat: support absolute path
Browse files Browse the repository at this point in the history
The github repo support relative path and the links starting with `/` will be
relative to the repository root. It's easy to link to files, such as
MAINTAINERS, LICENSE and so on.

This patch is to introduce `allow-absolute-patch` flag to allow absolute
path to join with `--root` and evaluate the file link.

REF:

* https://github.blog/2013-01-31-relative-links-in-markup-files/
* https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#relative-links

Signed-off-by: Wei Fu <[email protected]>
  • Loading branch information
fuweid authored and crawford committed Oct 11, 2023
1 parent 784bd90 commit 67d8764
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ struct Options {
/// Path(s) to exclude, relative to the root
#[structopt(short, long)]
exclude: Vec<PathBuf>,

/// Allow absolute path to join with root and evaluate
#[structopt(short, long)]
allow_absolute_paths: bool,
}

fn main() {
Expand Down Expand Up @@ -160,7 +164,12 @@ fn main() {
urls.entry(url).or_insert_with(Vec::new).push(link)
}
Err(ParseError::RelativeUrlWithoutBase) => {
if let Err(error) = check_path(&link.target, &link.file) {
if let Err(error) = check_path(
&options.root,
&link.target,
&link.file,
options.allow_absolute_paths,
) {
printerror!(link.new_error(error), found_error)
}
}
Expand Down Expand Up @@ -214,11 +223,30 @@ fn check_url(url: &Url) -> Result<(), LinkError> {
}
}

fn check_path(target: &str, file: &Path) -> Result<(), LinkError> {
fn check_path(
root: &PathBuf,
target: &str,
file: &Path,
allow_absolute_paths: bool,
) -> Result<(), LinkError> {
let path = Path::new(OsStr::new(target.split('#').next().expect("string")));

if path.is_absolute() {
Err(LinkError::PathAbsolute)
} else if !file
if !allow_absolute_paths {
return Err(LinkError::PathAbsolute);
}

let mut path_comps = path.components();
path_comps.next();

if root.join(path_comps.as_path()).exists() {
return Ok(());
} else {
return Err(LinkError::PathNonExistant);
}
}

if !file
.parent()
.expect("non-root file path")
.join(path)
Expand Down

0 comments on commit 67d8764

Please sign in to comment.