Skip to content

Commit

Permalink
feat(projects): git-commit support Chinese mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Azir-11 committed Aug 21, 2024
1 parent b0c5db9 commit 9e097e3
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 52 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"build-pkg": "pnpm -r --filter='./packages/*' run build",
"cleanup": "soy cleanup",
"commit": "soy git-commit",
"commit:zh": "soy git-commit -l=zh-cn",
"lint": "eslint . --fix",
"prepare": "simple-git-hooks",
"publish-pkg": "pnpm -r publish --access public",
Expand Down
32 changes: 15 additions & 17 deletions src/command/git-commit.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import path from 'node:path';
import { readFileSync } from 'node:fs';
import { prompt } from 'enquirer';
import { bgRed, green, red, yellow } from 'kolorist';
import { execCommand } from '../shared';
import type { CliOption } from '../types';
import { locales } from '../locales';
import type { Lang } from '../locales';

interface PromptObject {
types: string;
Expand All @@ -14,13 +14,11 @@ interface PromptObject {
/**
* Git commit with Conventional Commits standard
*
* @param gitCommitTypes
* @param gitCommitScopes
* @param lang
*/
export async function gitCommit(
gitCommitTypes: CliOption['gitCommitTypes'],
gitCommitScopes: CliOption['gitCommitScopes']
) {
export async function gitCommit(lang: Lang = 'en-us') {
const { gitCommitMessages, gitCommitTypes, gitCommitScopes } = locales[lang];

const typesChoices = gitCommitTypes.map(([value, msg]) => {
const nameWithSuffix = `${value}:`;

Expand All @@ -41,19 +39,19 @@ export async function gitCommit(
{
name: 'types',
type: 'select',
message: 'Please select a type',
message: gitCommitMessages.types,
choices: typesChoices
},
{
name: 'scopes',
type: 'select',
message: 'Please select a scope',
message: gitCommitMessages.scopes,
choices: scopesChoices
},
{
name: 'description',
type: 'text',
message: `Please enter a description (add prefix ${yellow('!')} to indicate breaking change)`
message: gitCommitMessages.description
}
]);

Expand All @@ -67,20 +65,20 @@ export async function gitCommit(
}

/** Git commit message verify */
export async function gitCommitVerify() {
export async function gitCommitVerify(lang: Lang = 'en-us', ignores: RegExp[] = []) {
const gitPath = await execCommand('git', ['rev-parse', '--show-toplevel']);

const gitMsgPath = path.join(gitPath, '.git', 'COMMIT_EDITMSG');

const commitMsg = readFileSync(gitMsgPath, 'utf8').trim();

if (ignores.some(regExp => regExp.test(commitMsg))) return;

const REG_EXP = /(?<type>[a-z]+)(?:\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i;

if (!REG_EXP.test(commitMsg)) {
throw new Error(
`${bgRed(' ERROR ')} ${red('git commit message must match the Conventional Commits standard!')}\n\n${green(
'Recommended to use the command `pnpm commit` to generate Conventional Commits compliant commit information.\nGet more info about Conventional Commits, follow this link: https://conventionalcommits.org'
)}`
);
const errorMsg = locales[lang].gitCommitVerify;

throw new Error(errorMsg);
}
}
38 changes: 11 additions & 27 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,18 @@ const defaultOptions: CliOption = {
'**/node_modules',
'!node_modules/**'
],
gitCommitTypes: [
['feat', 'A new feature'],
['fix', 'A bug fix'],
['docs', 'Documentation only changes'],
['style', 'Changes that do not affect the meaning of the code'],
['refactor', 'A code change that neither fixes a bug nor adds a feature'],
['perf', 'A code change that improves performance'],
['optimize', 'A code change that optimizes code quality'],
['test', 'Adding missing tests or correcting existing tests'],
['build', 'Changes that affect the build system or external dependencies'],
['ci', 'Changes to our CI configuration files and scripts'],
['chore', "Other changes that don't modify src or test files"],
['revert', 'Reverts a previous commit']
],
gitCommitScopes: [
['projects', 'project'],
['packages', 'packages'],
['components', 'components'],
['hooks', 'hook functions'],
['utils', 'utils functions'],
['types', 'TS declaration'],
['styles', 'style'],
['deps', 'project dependencies'],
['release', 'release project'],
['other', 'other changes']
],
ncuCommandArgs: ['--deep', '-u'],
changelogOptions: {}
changelogOptions: {},
gitCommitVerifyIgnores: [
/^((Merge pull request)|(Merge (.*?) into (.*?)|(Merge branch (.*?)))(?:\r?\n)*$)/m,
/^(Merge tag (.*?))(?:\r?\n)*$/m,
/^(R|r)evert (.*)/,
/^(amend|fixup|squash)!/,
/^(Merged (.*?)(in|into) (.*)|Merged PR (.*): (.*))/,
/^Merge remote-tracking branch(\s*)(.*)/,
/^Automatic merge(.*)/,
/^Auto-merged (.*?) into (.*)/
]
};

export async function loadCliOptions(overrides?: Partial<CliOption>, cwd = process.cwd()) {
Expand Down
16 changes: 12 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { version } from '../package.json';
import { cleanup, genChangelog, gitCommit, gitCommitVerify, ncu, release } from './command';
import { loadCliOptions } from './config';
import type { CliOption } from './types';
import type { Lang } from './locales';

type Command = 'cleanup' | 'ncu' | 'update-pkg' | 'git-commit' | 'git-commit-verify' | 'changelog' | 'release';

Expand All @@ -26,6 +27,12 @@ interface CommandArg {
* Multiple values use "," to separate them
*/
cleanupDir?: string;
/**
* display lang of cli
*
* @default 'en-us'
*/
lang?: Lang;
}

async function setupCli() {
Expand All @@ -45,6 +52,7 @@ async function setupCli() {
'-c, --cleanupDir <dir>',
'The glob pattern of dirs to cleanup, If not set, it will use the default value, Multiple values use "," to separate them'
)
.option('-l, --lang <lang>', 'display lang of cli', { default: 'en-us', type: [String] })
.help();

const commands: CommandWithAction<CommandArg> = {
Expand Down Expand Up @@ -75,14 +83,14 @@ async function setupCli() {
},
'git-commit': {
desc: 'git commit, generate commit message which match Conventional Commits standard',
action: async () => {
await gitCommit(cliOptions.gitCommitTypes, cliOptions.gitCommitScopes);
action: async args => {
await gitCommit(args?.lang);
}
},
'git-commit-verify': {
desc: 'verify git commit message, make sure it match Conventional Commits standard',
action: async () => {
await gitCommitVerify();
action: async args => {
await gitCommitVerify(args?.lang, cliOptions.gitCommitVerifyIgnores);
}
},
changelog: {
Expand Down
78 changes: 78 additions & 0 deletions src/locales/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { bgRed, green, red, yellow } from 'kolorist';

export type Lang = 'zh-cn' | 'en-us';

export const locales = {
'zh-cn': {
gitCommitMessages: {
types: '请选择提交类型',
scopes: '请选择提交范围',
description: `请输入描述信息(${yellow('!')}开头表示破坏性改动`
},
gitCommitTypes: [
['feat', '新功能'],
['fix', '修复Bug'],
['docs', '只涉及文档更新'],
['style', '修改代码风格,不影响代码含义的变更'],
['refactor', '代码重构,既不修复 bug 也不添加功能的代码变更'],
['perf', '可提高性能的代码更改'],
['optimize', '优化代码质量的代码更改'],
['test', '添加缺失的测试或更正现有测试'],
['build', '影响构建系统或外部依赖项的更改'],
['ci', '对 CI 配置文件和脚本的更改'],
['chore', '没有修改src或测试文件的其他变更'],
['revert', '还原先前的提交']
] as [string, string][],
gitCommitScopes: [
['projects', '项目'],
['packages', '包'],
['components', '组件'],
['hooks', '钩子函数'],
['utils', '工具函数'],
['types', 'TS类型声明'],
['styles', '代码风格'],
['deps', '项目依赖'],
['release', '发布项目新版本'],
['other', '其他的变更']
] as [string, string][],
gitCommitVerify: `${bgRed(' 错误 ')} ${red('git 提交信息必须符合 Conventional Commits 标准!')}\n\n${green(
'推荐使用命令 `pnpm commit` 生成符合 Conventional Commits 标准的提交信息。\n获取有关 Conventional Commits 的更多信息,请访问此链接: https://conventionalcommits.org'
)}`
},
'en-us': {
gitCommitMessages: {
types: 'Please select a type',
scopes: 'Please select a scope',
description: `Please enter a description (add prefix ${yellow('!')} to indicate breaking change)`
},
gitCommitTypes: [
['feat', 'A new feature'],
['fix', 'A bug fix'],
['docs', 'Documentation only changes'],
['style', 'Changes that do not affect the meaning of the code'],
['refactor', 'A code change that neither fixes a bug nor adds a feature'],
['perf', 'A code change that improves performance'],
['optimize', 'A code change that optimizes code quality'],
['test', 'Adding missing tests or correcting existing tests'],
['build', 'Changes that affect the build system or external dependencies'],
['ci', 'Changes to our CI configuration files and scripts'],
['chore', "Other changes that don't modify src or test files"],
['revert', 'Reverts a previous commit']
] as [string, string][],
gitCommitScopes: [
['projects', 'project'],
['packages', 'packages'],
['components', 'components'],
['hooks', 'hook functions'],
['utils', 'utils functions'],
['types', 'TS declaration'],
['styles', 'style'],
['deps', 'project dependencies'],
['release', 'release project'],
['other', 'other changes']
] as [string, string][],
gitCommitVerify: `${bgRed(' ERROR ')} ${red('git commit message must match the Conventional Commits standard!')}\n\n${green(
'Recommended to use the command `pnpm commit` to generate Conventional Commits compliant commit information.\nGet more info about Conventional Commits, follow this link: https://conventionalcommits.org'
)}`
}
} satisfies Record<Lang, Record<string, unknown>>;
6 changes: 2 additions & 4 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ export interface CliOption {
* ```
*/
cleanupDirs: string[];
/** Git commit types */
gitCommitTypes: [string, string][];
/** Git commit scopes */
gitCommitScopes: [string, string][];
/**
* Npm-check-updates command args
*
Expand All @@ -30,4 +26,6 @@ export interface CliOption {
* @link https://github.com/soybeanjs/changelog
*/
changelogOptions: Partial<ChangelogOption>;
/** The ignore pattern list of git commit verify */
gitCommitVerifyIgnores: RegExp[];
}

0 comments on commit 9e097e3

Please sign in to comment.