From b6b092dc1fc416d0abb0060636e2d56a6a60b2b2 Mon Sep 17 00:00:00 2001 From: Divlo Date: Fri, 6 Jan 2023 18:37:40 +0100 Subject: [PATCH] fix: only detect `file:` protocol links fixes #1 --- README.md | 27 +++++++++++++++++++++++++-- src/index.js | 15 ++------------- test/fixtures/Valid.md | 6 ++++++ 3 files changed, 33 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index d9d7c47..8e0ba35 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,32 @@ **markdownlint-rule-relative-links** is a [markdownlint](https://github.com/DavidAnson/markdownlint) custom rule to validate relative links. -It ensures that relative links that start with `./` or `../` (or not starting with external protocols like `http://` or `https://`) are working and not "dead" which means that it exists in the file system of the project that uses `markdownlint`. +It ensures that relative links (using `file:` protocol) are working and not "dead" which means that it exists in the file system of the project that uses `markdownlint`. -Related links: +### Example + +File structure: + +```txt +├── abc.txt +└── awesome.md +``` + +With `awesome.md` content: + +```md +[abc](./abc.txt) + +[Dead link](./dead.txt) +``` + +Running `markdownlint-cli2` with `markdownlint-rule-relative-links` will output: + +```sh +awesome.md:3 relative-links Relative links should be valid [Link "./dead.txt" is dead] +``` + +### Related links - [DavidAnson/markdownlint#253](https://github.com/DavidAnson/markdownlint/issues/253) - [DavidAnson/markdownlint#121](https://github.com/DavidAnson/markdownlint/issues/121) diff --git a/src/index.js b/src/index.js index c417e33..99b09be 100644 --- a/src/index.js +++ b/src/index.js @@ -40,14 +40,6 @@ const addError = (onError, lineNumber, detail, context, range, fixInfo) => { }) } -const EXTERNAL_PROTOCOLS = new Set([ - 'http:', - 'https:', - 'mailto:', - 'tel:', - 'ftp:' -]) - const customRule = { names: ['relative-links'], description: 'Relative links should be valid', @@ -79,11 +71,8 @@ const customRule = { if (hrefSrc != null) { const url = new URL(hrefSrc, pathToFileURL(params.name)) url.hash = '' - const isRelative = - hrefSrc.startsWith('./') || - hrefSrc.startsWith('../') || - !EXTERNAL_PROTOCOLS.has(url.protocol) - if (isRelative && !fs.existsSync(url.pathname)) { + const isRelative = url.protocol === 'file:' + if (isRelative && !fs.existsSync(url)) { const detail = `Link "${hrefSrc}" is dead` addError(onError, lineNumber, detail) } diff --git a/test/fixtures/Valid.md b/test/fixtures/Valid.md index 928b357..35fa567 100644 --- a/test/fixtures/Valid.md +++ b/test/fixtures/Valid.md @@ -3,3 +3,9 @@ [basic.js](../basic.test.js) ![Image](./image.png) + +[External https link](https://example.com/) + +[External https link 2](https:./external.https) + +[External ftp link](ftp:./external.ftp)