UNPKG

2.36 kBJavaScriptView Raw
1/** @typedef {import('./index').Logger} Logger */
2
3import { basename, join } from 'path'
4
5import normalize from 'normalize-path'
6
7import { execGit } from './execGit.js'
8import { loadConfig, searchPlaces } from './loadConfig.js'
9import { parseGitZOutput } from './parseGitZOutput.js'
10import { validateConfig } from './validateConfig.js'
11
12const EXEC_GIT = ['ls-files', '-z', '--full-name']
13
14const filterPossibleConfigFiles = (file) => searchPlaces.includes(basename(file))
15
16const numberOfLevels = (file) => file.split('/').length
17
18const sortDeepestParth = (a, b) => (numberOfLevels(a) > numberOfLevels(b) ? -1 : 1)
19
20/**
21 * Search all config files from the git repository
22 *
23 * @param {string} gitDir
24 * @param {Logger} logger
25 * @returns {Promise<{ [key: string]: * }>} found configs with filepath as key, and config as value
26 */
27export const searchConfigs = async (gitDir = process.cwd(), logger) => {
28 /** Get all possible config files known to git */
29 const cachedFiles = parseGitZOutput(await execGit(EXEC_GIT, { cwd: gitDir })).filter(
30 filterPossibleConfigFiles
31 )
32
33 /** Get all possible config files from uncommitted files */
34 const otherFiles = parseGitZOutput(
35 await execGit([...EXEC_GIT, '--others', '--exclude-standard'], { cwd: gitDir })
36 ).filter(filterPossibleConfigFiles)
37
38 /** Sort possible config files so that deepest is first */
39 const possibleConfigFiles = [...cachedFiles, ...otherFiles]
40 .map((file) => join(gitDir, file))
41 .map((file) => normalize(file))
42 .sort(sortDeepestParth)
43
44 /** Create object with key as config file, and value as null */
45 const configs = possibleConfigFiles.reduce(
46 (acc, configPath) => Object.assign(acc, { [configPath]: null }),
47 {}
48 )
49
50 /** Load and validate all configs to the above object */
51 await Promise.all(
52 possibleConfigFiles
53 .map((configPath) => loadConfig({ configPath }, logger))
54 .map((promise) =>
55 promise.then(({ config, filepath }) => {
56 if (config) {
57 configs[filepath] = validateConfig(config, filepath, logger)
58 }
59 })
60 )
61 )
62
63 /** Get validated configs from the above object, without any `null` values (not found) */
64 const foundConfigs = Object.entries(configs)
65 .filter(([, value]) => !!value)
66 .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {})
67
68 return foundConfigs
69}