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

Support multiple pages directories for linting #25565

Merged
merged 6 commits into from
Jul 20, 2021
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
36 changes: 30 additions & 6 deletions packages/eslint-plugin-next/lib/rules/no-html-link-for-pages.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const path = require('path')
const fs = require('fs')
const {
getUrlFromPagesDirectory,
getUrlFromPagesDirectories,
normalizeURL,
execOnce,
} = require('../utils/url')
Expand All @@ -13,6 +13,10 @@ const pagesDirWarning = execOnce((pagesDirs) => {
)
})

// Cache for fs.existsSync lookup.
// Prevent multiple blocking IO requests that have already been calculated.
const fsExistsSyncCache = {}

module.exports = {
meta: {
docs: {
Expand All @@ -21,24 +25,44 @@ module.exports = {
recommended: true,
},
fixable: null, // or "code" or "whitespace"
schema: ['pagesDirectory'],
schema: [
{
oneOf: [
{
type: 'string',
},
{
type: 'array',
uniqueItems: true,
items: {
type: 'string',
},
},
],
},
],
},

create: function (context) {
const [customPagesDirectory] = context.options
const pagesDirs = customPagesDirectory
? [customPagesDirectory]
? [customPagesDirectory].flat()
: [
path.join(context.getCwd(), 'pages'),
path.join(context.getCwd(), 'src', 'pages'),
]
const pagesDir = pagesDirs.find((dir) => fs.existsSync(dir))
if (!pagesDir) {
const foundPagesDirs = pagesDirs.filter((dir) => {
if (fsExistsSyncCache[dir] === undefined) {
fsExistsSyncCache[dir] = fs.existsSync(dir)
}
return fsExistsSyncCache[dir]
})
if (foundPagesDirs.length === 0) {
pagesDirWarning(pagesDirs)
return {}
}

const urls = getUrlFromPagesDirectory('/', pagesDir)
const urls = getUrlFromPagesDirectories('/', foundPagesDirs)
return {
JSXOpeningElement(node) {
if (node.name.name !== 'a') {
Expand Down
43 changes: 32 additions & 11 deletions packages/eslint-plugin-next/lib/utils/url.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,64 @@
const fs = require('fs')
const path = require('path')

// Cache for fs.lstatSync lookup.
// Prevent multiple blocking IO requests that have already been calculated.
const fsLstatSyncCache = {}
const fsLstatSync = (source) => {
fsLstatSyncCache[source] = fsLstatSyncCache[source] || fs.lstatSync(source)
return fsLstatSyncCache[source]
}

/**
* Checks if the source is a directory.
* @param {string} source
*/
function isDirectory(source) {
return fs.lstatSync(source).isDirectory()
return fsLstatSync(source).isDirectory()
}

/**
* Checks if the source is a directory.
* @param {string} source
*/
function isSymlink(source) {
return fs.lstatSync(source).isSymbolicLink()
return fsLstatSync(source).isSymbolicLink()
}

/**
* Gets the possible URLs from a directory.
* @param {string} urlprefix
* @param {string} directory
* @param {string[]} directories
*/
function getUrlFromPagesDirectory(urlPrefix, directory) {
return parseUrlForPages(urlPrefix, directory).map(
// Since the URLs are normalized we add `^` and `$` to the RegExp to make sure they match exactly.
(url) => new RegExp(`^${normalizeURL(url)}$`)
)
function getUrlFromPagesDirectories(urlPrefix, directories) {
return Array.from(
// De-duplicate similar pages across multiple directories.
new Set(
directories
.map((directory) => parseUrlForPages(urlPrefix, directory))
.flat()
.map(
// Since the URLs are normalized we add `^` and `$` to the RegExp to make sure they match exactly.
(url) => `^${normalizeURL(url)}$`
)
)
).map((urlReg) => new RegExp(urlReg))
}

// Cache for fs.readdirSync lookup.
// Prevent multiple blocking IO requests that have already been calculated.
const fsReadDirSyncCache = {}

/**
* Recursively parse directory for page URLs.
* @param {string} urlprefix
* @param {string} directory
*/
function parseUrlForPages(urlprefix, directory) {
const files = fs.readdirSync(directory)
fsReadDirSyncCache[directory] =
fsReadDirSyncCache[directory] || fs.readdirSync(directory)
const res = []
files.forEach((fname) => {
fsReadDirSyncCache[directory].forEach((fname) => {
if (/(\.(j|t)sx?)$/.test(fname)) {
fname = fname.replace(/\[.*\]/g, '.*')
if (/^index(\.(j|t)sx?)$/.test(fname)) {
Expand Down Expand Up @@ -90,7 +111,7 @@ function execOnce(fn) {
}

module.exports = {
getUrlFromPagesDirectory,
getUrlFromPagesDirectories,
normalizeURL,
execOnce,
}
23 changes: 23 additions & 0 deletions test/eslint-plugin-next/no-html-link-for-pages.unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ const linterConfig = {
},
},
}
const linterConfigWithMultipleDirectories = {
...linterConfig,
rules: {
'no-html-link-for-pages': [
2,
[
path.join(__dirname, 'custom-pages'),
path.join(__dirname, 'custom-pages/list'),
],
],
},
}

linter.defineRules({
'no-html-link-for-pages': rule,
Expand Down Expand Up @@ -108,6 +120,17 @@ describe('no-html-link-for-pages', function () {
assert.deepEqual(report, [])
})

it('valid link element with multiple directories', function () {
const report = linter.verify(
validCode,
linterConfigWithMultipleDirectories,
{
filename: 'foo.js',
}
)
assert.deepEqual(report, [])
})

it('valid anchor element', function () {
const report = linter.verify(validAnchorCode, linterConfig, {
filename: 'foo.js',
Expand Down