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

Fixes #1368

Merged
merged 7 commits into from
Dec 2, 2023
Merged

Fixes #1368

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/neat-suits-invite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'lint-staged': patch
---

Update most dependencies
5 changes: 5 additions & 0 deletions .changeset/selfish-pillows-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'lint-staged': patch
---

To improve performance, only use `lilconfig` when searching for config files outside the git repo. In the regular case, _lint-staged_ finds the config files from the Git index and loads them directly.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
coverage
test/unit/__mocks__
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
test/unit/__mocks__
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const config = {
'!lib/resolveConfig.js',
],
moduleDirectories: ['node_modules'],
prettierPath: null,
setupFiles: ['./testSetup.js'],
snapshotSerializers: ['jest-snapshot-serializer-ansi'],
testEnvironment: 'node',
Expand Down
45 changes: 36 additions & 9 deletions lib/loadConfig.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
/** @typedef {import('./index').Logger} Logger */

import fs from 'node:fs/promises'
import path from 'node:path'

import debug from 'debug'
import { lilconfig } from 'lilconfig'
import YAML from 'yaml'

import { dynamicImport } from './dynamicImport.js'
Expand Down Expand Up @@ -37,8 +37,10 @@ export const searchPlaces = [
]

const jsonParse = (filePath, content) => {
const isPackageFile = PACKAGE_JSON_FILE.includes(path.basename(filePath))
try {
return JSON.parse(content)
const json = JSON.parse(content)
return isPackageFile ? json[CONFIG_NAME] : json
} catch (error) {
if (path.basename(filePath) === PACKAGE_JSON_FILE) {
debugLog('Ignoring invalid package file `%s` with content:\n%s', filePath, content)
Expand All @@ -64,6 +66,8 @@ const yamlParse = (filePath, content) => {
}
}

const NO_EXT = 'noExt'

/**
* `lilconfig` doesn't support yaml files by default,
* so we add custom loaders for those. Files without
Expand All @@ -77,10 +81,31 @@ const loaders = {
'.cjs': dynamicImport,
'.yaml': yamlParse,
'.yml': yamlParse,
noExt: yamlParse,
[NO_EXT]: yamlParse,
}

const readFile = async (filepath) => {
const absolutePath = path.resolve(filepath)
const file = await fs.readFile(absolutePath)
return await file.toString()
}

const explorer = lilconfig(CONFIG_NAME, { searchPlaces, loaders })
const loadConfigByExt = async (filepath) => {
filepath = path.resolve(filepath)
const ext = path.extname(filepath) || NO_EXT
const loader = loaders[ext]

/**
* No need to read file contents when loader only takes in the filepath argument
* and reads itself; this is for `lilconfig` compatibility
*/
const content = loader.length > 1 ? await readFile(filepath) : undefined

return {
config: await loader(filepath, content),
filepath,
}
}

/**
* @param {object} options
Expand All @@ -89,20 +114,22 @@ const explorer = lilconfig(CONFIG_NAME, { searchPlaces, loaders })
*/
export const loadConfig = async ({ configPath, cwd }, logger) => {
try {
let result

if (configPath) {
debugLog('Loading configuration from `%s`...', configPath)
result = await loadConfigByExt(resolveConfig(configPath))
} else {
debugLog('Searching for configuration from `%s`...', cwd)
const { lilconfig } = await import('lilconfig')
const explorer = lilconfig(CONFIG_NAME, { searchPlaces, loaders })
result = await explorer.search(cwd)
}

const result = await (configPath
? explorer.load(resolveConfig(configPath))
: explorer.search(cwd))

if (!result) return {}

// config is a promise when using the `dynamicImport` loader
const config = await result.config
const config = (await result.config) ?? null
const filepath = result.filepath

debugLog('Successfully loaded config from `%s`:\n%O', filepath, config)
Expand Down
4 changes: 2 additions & 2 deletions lib/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export const skippingBackup = (hasInitialCommit, diff) => {
diff !== undefined
? '`--diff` was used'
: hasInitialCommit
? '`--no-stash` was used'
: 'there’s no initial commit yet'
? '`--no-stash` was used'
: 'there’s no initial commit yet'

return chalk.yellow(`${warning} Skipping backup because ${reason}.\n`)
}
Expand Down
8 changes: 4 additions & 4 deletions lib/resolveGitRepo.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const debugLog = debug('lint-staged:resolveGitRepo')
*/
const resolveGitConfigDir = async (gitDir) => {
// Get the real path in case it's a symlink
const defaultDir = normalizePath(await fs.realpath(path.join(gitDir, '.git')))
const defaultDir = await fs.realpath(path.join(gitDir, '.git'))
const stats = await fs.lstat(defaultDir)
// If .git is a directory, use it
if (stats.isDirectory()) return defaultDir
Expand All @@ -33,10 +33,10 @@ export const determineGitDir = (cwd, relativeDir) => {
}
if (relativeDir) {
// the current working dir is inside the git top-level directory
return normalizePath(cwd.substring(0, cwd.lastIndexOf(relativeDir)))
return cwd.substring(0, cwd.lastIndexOf(relativeDir))
} else {
// the current working dir is the top-level git directory
return normalizePath(cwd)
return cwd
}
}

Expand All @@ -56,7 +56,7 @@ export const resolveGitRepo = async (cwd = process.cwd()) => {
// read the path of the current directory relative to the top-level directory
// don't read the toplevel directly, it will lead to an posix conform path on non posix systems (cygwin)
const gitRel = normalizePath(await execGit(['rev-parse', '--show-prefix'], { cwd }))
const gitDir = determineGitDir(normalizePath(cwd), gitRel)
const gitDir = normalizePath(determineGitDir(normalizePath(cwd), gitRel))
const gitConfigDir = normalizePath(await resolveGitConfigDir(gitDir))

debugLog('Resolved git directory to be `%s`', gitDir)
Expand Down