Skip to content

Commit

Permalink
feat(plugin-loader): support esm and ts configure loader
Browse files Browse the repository at this point in the history
link #192
  • Loading branch information
Zhengqbbb committed Nov 1, 2024
1 parent c6589de commit 0abf98f
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 21 deletions.
17 changes: 9 additions & 8 deletions .commitlintrc.cjs → .commitlintrc.mjs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
const { execSync } = require('node:child_process')
const fg = require('fast-glob')
import { execSync } from 'node:child_process'
import { defineConfig } from 'cz-git'
import fg from 'fast-glob'

// git branch name = feature/cli_33 => auto get defaultIssues = #33
/** Get git branch issue number. e.g feature/cli_33 => #33 */
const issue = execSync('git rev-parse --abbrev-ref HEAD')
.toString()
.trim()
.split('_')[1]

// dynamic get monorepo packages name
const packages = fg.sync('*', { cwd: 'packages/@cz-git', onlyDirectories: true })
/** Get monorepo packages name */
const packages = fg
.sync('*', { cwd: 'packages/@cz-git', onlyDirectories: true })

/** @type {import('cz-git').UserConfig} */
module.exports = {
export default defineConfig({
extends: ['@commitlint/config-conventional'],
rules: {
'scope-enum': [2, 'always', ['cz-git', 'site', 'cli', ...packages]],
Expand All @@ -37,4 +38,4 @@ module.exports = {
customIssuePrefixAlign: !issue ? 'top' : 'bottom',
defaultIssues: !issue ? '' : `#${issue}`,
},
}
})
1 change: 1 addition & 0 deletions packages/@cz-git/plugin-loader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"devDependencies": {
"@commitlint/resolve-extends": "catalog:commitlint",
"@commitlint/types": "catalog:commitlint",
"@cz-git/inquirer": "workspace:*",
"@types/tmp": "^0.2.3",
"cosmiconfig": "catalog:",
"pkg-dir": "5.0.0",
Expand Down
43 changes: 43 additions & 0 deletions packages/@cz-git/plugin-loader/src/esm-ts-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import process from 'node:process'
import { style } from '@cz-git/inquirer'
import type { Loader } from 'cosmiconfig'

type LoaderError = Error & {
code?: string
}

// export NODE_OPTIONS="--experimental-transform-types --disable-warning ExperimentalWarning"
export function esmTsLoader(): Loader {
return async (cfgPath: string, _: string) => {
try {
const result = await import(cfgPath) as { default?: any }
return result.default || result
}
catch (e: any) {
// TODO: bun - The Current native bun will cause the TUI unnormal
// @ts-ignore // Usage: `deno task cz`
const isDeno = typeof Deno !== 'undefined' && Deno?.version?.deno
if (isDeno)
throw e

const error = e as LoaderError
const isNodeLTSInRange = (() => {
if (!process.version.startsWith('v'))
return false
const major = process.version.split('.')[0].slice(1)
const minor = process.version.split('.')[1]
return Number(major) >= 22 && Number(minor) >= 10
})()
if (error?.code === 'ERR_UNKNOWN_FILE_EXTENSION') {
if (isNodeLTSInRange)
console.log(style.gray(`Loading file: ${cfgPath}\nRequires injecting experimental NODE_OPTIONS env: --experimental-transform-types\nSee: ${style.underline('https://cz-git.qbb.sh/config/#typescript-template')}`))
else
console.log(style.gray(`Loading file: ${cfgPath}\n1. Requires Node.js version >= v22.10.0\n2. Inject experimental NODE_OPTIONS env: --experimental-transform-types\nSee: ${style.underline('https://cz-git.qbb.sh/config/#typescript-template')}`))
return {}
}
else {
throw error
}
}
}
}
42 changes: 29 additions & 13 deletions packages/@cz-git/plugin-loader/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import process from 'node:process'
import resolveExtends from '@commitlint/resolve-extends'
import { cosmiconfig } from 'cosmiconfig'
import type { RulesConfig } from '@commitlint/types'
import { esmTsLoader } from './esm-ts-loader'

type ExectableConfig<T> = (() => T) | (() => Promise<T>)
type Config<T> = T | Promise<T> | ExectableConfig<T>
Expand All @@ -23,14 +24,24 @@ export interface LoaderOptions {
packageProp?: string[]
}

const commonCosmiconfigOptions = {
ignoreEmptySearchPlaces: true,
cache: true,
loaders: {
'.ts': esmTsLoader(),
'.cts': esmTsLoader(),
'.mjs': esmTsLoader(),
'.mts': esmTsLoader(),
},
}

export async function loader(options: LoaderOptions) {
const cwd = options.cwd || process.cwd()
const cosmiconfigFn = cosmiconfig(options.moduleName, {
searchPlaces: options.searchPlaces || [],
packageProp: options.packageProp || options.moduleName,
stopDir: options.stopDir,
ignoreEmptySearchPlaces: true,
cache: true,
...commonCosmiconfigOptions,
})

const resultPath = options.explicitPath ? path.resolve(cwd, options.explicitPath) : undefined
Expand Down Expand Up @@ -80,8 +91,16 @@ export async function clLoader(cwd?: string): Promise<CommitlintOptions> {
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`.${moduleName}rc.cjs`,
`.${moduleName}rc.mjs`,
`.${moduleName}rc.ts`,
`.${moduleName}rc.cts`,
`.${moduleName}rc.mts`,
`${moduleName}.config.js`,
`${moduleName}.config.cjs`,
`${moduleName}.config.mjs`,
`${moduleName}.config.ts`,
`${moduleName}.config.cts`,
`${moduleName}.config.mts`,
],
cwd,
}
Expand Down Expand Up @@ -115,6 +134,10 @@ export async function czLoader(cwd?: string) {
`.${moduleName}rc`,
`${moduleName}.config.js`,
`${moduleName}.config.cjs`,
`${moduleName}.config.mjs`,
`${moduleName}.config.ts`,
`${moduleName}.config.cts`,
`${moduleName}.config.mts`,
'package.json',
],
packageProp: ['config', 'commitizen'],
Expand All @@ -125,10 +148,8 @@ export async function czLoader(cwd?: string) {
return {}
if (typeof data.config.czConfig === 'string') {
const base = (data && data.filepath) ? path.dirname(data.filepath) : process.cwd()
data = await cosmiconfig('commitizen', {
ignoreEmptySearchPlaces: true,
cache: true,
}).load(path.resolve(base, data.config.czConfig))
data = await cosmiconfig('commitizen', commonCosmiconfigOptions)
.load(path.resolve(base, data.config.czConfig))
}
return await execute(data?.config || data || {}, true)
}
Expand Down Expand Up @@ -166,13 +187,8 @@ export interface UserOptions {
export async function configLoader(options?: UserOptions) {
// provide cli config loader
if (typeof options?.configPath === 'string') {
const czData = await cosmiconfig(
'commitizen',
{
ignoreEmptySearchPlaces: true,
cache: true,
},
).load(path.resolve(options.cwd || process.cwd(), options.configPath))
const czData = await cosmiconfig('commitizen', commonCosmiconfigOptions)
.load(path.resolve(options.cwd || process.cwd(), options.configPath))

return { prompt: await execute(czData?.config || czData || {}, true) }
}
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0abf98f

Please sign in to comment.