# @branchwright/cli 中文文档

规范地址：https://npmcn.com/package/%40branchwright/cli/

版本：1\.0\.1
npm 元数据更新时间：2025-11-23T21:32:15.725Z
中文译文更新时间：2026-11-08T13:54:21.829Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40branchwright/cli
原文对照：https://npmcn.com/package/%40branchwright/cli/?lang=original
项目主页：https://branchwright.github.io/branchwright
源码仓库：https://github.com/branchwright/branchwright

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：433 kB，40 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.12\.0
- 运行依赖：7 个
- 首次发布：2025-11-08T20:19:02.913Z
- 最新版本发布：2025-11-23T21:32:15.264Z
- 近 30 天下载量：12062（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：4（近 12 个月 4 个）

## 中文简介

Git 分支名称林入和交互式分支创建工具

## 安装

```sh
npm install @branchwright/cli
```

也可以使用：`pnpm add @branchwright/cli`、`yarn add @branchwright/cli`、`bun add @branchwright/cli`

## README

![Branchwright](https://npmcn.com/package/%40branchwright/cli/assets/logo.svg)

# 分支作家

> Git 分支名称 林入和交互式分支创建 - 树枝的约定/承诺

[![npm](https://img.shields.io/npm/v/%40branchwright%2Fcli)](https://www.npmjs.com/package/@branchwright/cli) [![npm downloads](https://img.shields.io/npm/dm/%40branchwright%2Fcli)](https://www.npmjs.com/package/@branchwright/cli) [![Release](https://github.com/branchwright/branchwright/actions/workflows/release.yml/badge.svg?branch=main)](https://github.com/branchwright/branchwright/actions/workflows/release.yml) [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6)](https://www.typescriptlang.org/)

**分支作家** 帮助团队以精简、互动的工作流程保持吉特分支命名惯例的一致性:

-   ✨ **无光滑分支创建** - 智能默认,最小提示
-   🔍 **分支名称验证** - 违反你的规矩把现有的分行放下
-   🎯 **广泛的规则制度** - 内建规则外加自定义规则插件
-   ⚙️ **基于模板的命名** - 说吧 `{{type}}/{{ticket}}-{{desc}}` 或任何需要的格式
-   🚀 **CLI 和 API 软件** - 单独使用或按方案整合
-   📦 **类型脚本第一** - 包括全部类型定义

## 安装

```bash
# Global installation (recommended)
npm install -g @branchwright/cli

# Project-local installation
npm install --save-dev @branchwright/cli

# Or use without installing
npx @branchwright/cli create
```

## 快速启动

### 互动分支创建

```bash
# If installed globally or locally
brw create

# Without installing (using npx)
npx @branchwright/cli create
```

就这样! Branchwright将引导你通过:

1.  选择分支类型( feat, fix, chore等)
2.  可选输入出票证
3.  描述您的分支
4.  创建和切换到新分支

该工具使用 **智能默认** 尽量减少摩擦:

-   基地分行:现分行
-   自动退出:是
-   推向远程 : no( 可选)

### 验证分支名称

```bash
# Validate current branch
brw lint

# Validate specific branch
brw lint feature/user-auth

# Validate all branches
brw lint --all
```

## 配置

创建 `branchwright.config.ts` 在您的工程根中 :

```typescript
import { defineConfig } from '@branchwright/cli';

export default defineConfig({
  // Define your branch types
  branchTypes: [
    { name: 'feat', label: 'Feature' },
    { name: 'fix', label: 'Bug Fix' },
    { name: 'chore', label: 'Chore' },
  ],
  
  // Customize branch name template
  template: '{{type}}/{{ticket}}-{{desc}}',
  
  // Configure rules
  rules: {
    ticketId: ['optional', { prefix: 'PROJ-' }],
  },
  
  // Control optional questions (all default to false)
  extraQuestions: {
    baseBranch: false,    // Ask which branch to base from
    checkout: false,      // Ask whether to switch to new branch
    pushToRemote: false,  // Ask whether to push to remote
  },
  
  // Customize prompts (optional)
  questions: {
    branchType: 'What type of branch?',
    description: 'Describe your change:',
    pushToRemote: 'Push to origin?',
  },
});
```

### 配置选项

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `branchTypes` | `BranchTypeOption[]` | `[feat, fix, chore]` | 可供选择的分支类型 |
| `template` | `string` | `'{{type}}/{{desc}}'` | 带有占位符的分支名称模板 |
| `maxDescriptionLength` | `number` | `24` | 最大描述长度 |
| `descriptionStyle` | `string` | `'kebab-case'` | 强制大小写样式 : `kebab-case`, (中文(简体) ), `snake_case`, (中文(简体) ), `PascalCase`, (中文(简体) ), `camelCase` |
| `ignoredBranches` | `string[]` | `['main', 'master', 'next', 'dev']` | 校验时要跳过的分支 |
| `rules` | `Rules` | `{}` | 规则配置(见规则一节) |
| `extraQuestions` | `InteractiveQuestions` | 全体 `false` | 启用可选的提示 |
| `questions` | `QuestionConfig` | `{}` | 自定义快速文本 |

### 模板系统

在分支名称模板中使用占位符 :

-   `{{type}}` - 分支类型(feat、fix等)
-   `{{ticket}}` - 车票号码(如果提供)
-   `{{desc}}` - 说明

**实例:**

```typescript
// Simple format
template: '{{type}}/{{desc}}'
// Output: feat/user-authentication

// With ticket
template: '{{type}}/{{ticket}}-{{desc}}'
// Output: feat/PROJ-123-user-authentication

// Custom format
template: '{{ticket}}/{{type}}-{{desc}}'
// Output: PROJ-123/feat-user-authentication
```

### 交互式问题

控制在其中显示的可选问题 `brw create`数字 :

```typescript
extraQuestions: {
  baseBranch: true,    // Ask "Base branch?" (default: uses current branch)
  checkout: true,      // Ask "Switch to new branch?" (default: yes)
  pushToRemote: true,  // Ask "Push to remote?" (default: no)
}
```

默认情况下,所有 `false` 简洁的经验。 该工具:

-   使用您的当前分支作为基础
-   自动切换到新分支
-   不推向远程

只有在需要灵活性时才启用问题.

### 自定义提示

覆盖默认的提示文本 :

```typescript
questions: {
  branchType: 'Select the type of work:',
  ticketId: 'Ticket/issue number (optional):',
  ticketIdRequired: 'Ticket/issue number:',
  description: 'Brief description:',
  descriptionWithTicket: 'Describe your changes:',
  baseBranch: 'Create from which branch?',
  checkout: 'Switch to this branch now?',
  proceed: 'Create this branch?',
  pushToRemote: 'Push to origin now?',
}
```

## 规则系统

Branchwright包括一个强大的,可扩展的规则引擎用于验证.

### 内部规则

**`ticketId`** - 验证车票识别格式和要求

```typescript
rules: {
  // Off: No ticket ID validation
  ticketId: 'off',
  
  // Optional: Allow but don't require ticket IDs
  ticketId: 'optional',
  
  // Required: Ticket ID must be present
  ticketId: 'required',
  
  // With prefix validation
  ticketId: ['optional', { prefix: 'PROJ-' }],
  ticketId: ['required', { prefix: 'TEAM-' }],
}
```

### 规则配置

规则接受三个严重程度:

-   `'off'` - 规则被禁用
-   `'optional'` - 规则运行,但不阻断
-   `'required'` - 规则必须通过

配置格式 :

```typescript
rules: {
  myRule: true,                           // Boolean (true = required, false = off)
  myRule: 'optional',                     // String severity
  myRule: ['required', { option: 'val' }], // Tuple with options
}
```

### 自定义规则

定义自己的验证规则 :

```typescript
import { defineRule, coreRuleRegistry, createRegistry } from '@branchwright/cli';

const noWipRule = defineRule(
  {
    id: 'no-wip',
    meta: {
      title: 'Disallow WIP branches',
      description: 'Prevents work-in-progress markers from shipping.',
    },
    defaultSeverity: 'required',
  },
  (context) => {
    if (context.branchName.includes('wip')) {
      return { 
        message: 'Remove "wip" from the branch name.',
        suggestions: [context.branchName.replace('wip', '')],
      };
    }
    return null; // Valid
  },
);

// Use with evaluateRules
const registry = createRegistry(...coreRuleRegistry.entries(), noWipRule);
```

### 规则插件

从外部模块装入自定义规则 :

```typescript
// branchwright.config.ts
export default defineConfig({
  plugins: [
    './config/rules/company-rules.ts',  // Local file
    '@acme/branchwright-rules',         // NPM package
  ],
  rules: {
    'no-wip': 'required',
    'acme/ticket-format': ['required', { pattern: /^[A-Z]+-\d+$/ }],
  },
});
```

**插件格式 :**

```typescript
// company-rules.ts
import { defineRule } from '@branchwright/cli';

export default [
  defineRule(/* ... */),
  defineRule(/* ... */),
];
```

### 规则预设

组合多个规则配置 :

```typescript
export default defineConfig({
  presets: [
    'recommended',              // Built-in preset
    '@acme/strict-preset',      // Package preset
  ],
  rules: {
    // Override preset defaults
    ticketId: 'required',
  },
});
```

预设按顺序合并,并明确 `rules` 拥有最后的优先权.

## CLI 参考

### `brw create`

以交互或预指定值创建新分支 .

**旗帜 :**

-   `-t, --type <type>` - 预先指明分支类型(例如:成就、固定、弦乐)
-   `--ticket <id>` - 预先注明票证(例如JIRA-123)
-   `-d, --desc <description>` - 预先说明分支说明
-   `-y, --yes` - 跳过确认提示
-   `--push` - 创建后将分支推向远程
-   `--base <branch>` - 指定基础分支(覆盖配置)
-   `--dry-run` - 在不创建分支的情况下进行预览

**实例:**

```bash
# Standard interactive creation
brw create

# Fully non-interactive - provide all values
brw create -t feat --ticket PROJ-123 -d "add-user-auth" -y

# Partial - skip some prompts
brw create -t fix -d "resolve-login-bug"

# Quick feature branch
brw create -t feat -d "new-dashboard" --push

# Create from specific base
brw create --base main

# Preview what would be created
brw create --dry-run
```

#### 非交互式使用

使用旗帜跳过交互式提示 - 完全适合脚本和CI/CD :

**快速分支创建 :**

```bash
# Minimal - just type and description
brw create -t feat -d "add-oauth"

# With ticket ID
brw create -t fix --ticket BUG-456 -d "memory-leak"

# Skip confirmation
brw create -t chore -d "update-deps" -y
```

**自动化脚本( S) :**

```bash
# CI/CD workflow
brw create -t release -d "v2.0.0" -y --push

# Batch creation script
for feature in auth payments dashboard; do
  brw create -t feat -d "$feature" -y
done

# Integration with ticket systems
TICKET=$(gh issue view 123 --json number -q .number)
brw create -t feat --ticket "GH-$TICKET" -d "implement-feature" --push
```

**验证 :**

旗帜像交互式输入一样被验证 :

-   `--type` 必须匹配已配置的分支类型
-   `--ticket` 必须匹配所配置的前缀(如果规则)。 票证已经设定)
-   `--desc` 必须遵守描述Style和 maxDescriptionLength 规则

**禁用提示 :**

在全球隐藏 CLI 提示消息( 例如, 为有经验的用户) :

```typescript
export default defineConfig({
  showCliTips: false,  // Disable "you can use flags" tip
  // ... rest of config
});
```

### `brw lint [branches...]`

根据您的规则验证分支名称 .

**旗帜 :**

-   `--all` - 检查所有地方分支

**实例:**

```bash
# Validate current branch
brw lint

# Validate specific branches
brw lint feature/auth fix/login-bug

# Check all branches
brw lint --all
```

### `brw init`

生成默认值 `branchwright.config.ts` 文档.

### `brw config`

显示您的当前配置 .

## 程序化 API

在您的节点代码中使用 Branchwright :

```typescript
import { Branchwright } from '@branchwright/cli';

const branchwright = new Branchwright();

// Validate a branch name
const result = await branchwright.validate('feat/user-auth');
console.log(result.valid ? '✓ Valid' : `✗ ${result.message}`);

// Create a branch interactively
const branchName = await branchwright.create();

// Access underlying components
const validator = branchwright.getValidator();
const creator = branchwright.getCreator();
```

### 高级:规则评价

```typescript
import { evaluateRules, coreRuleRegistry } from '@branchwright/cli';

const config = { /* your config */ };
const violations = await evaluateRules('feat/my-branch', config, coreRuleRegistry);

violations.forEach(v => console.error(v.message));
```

## 一体化

### 基特·胡克斯(胡斯基)

驱动前验证分支名称 :

```bash
npm install --save-dev husky
npx husky init
```

**.husky/前推:**

```bash
#!/bin/sh
npx brw lint || exit 1
```

### CI/CD (GitHub 动作)

```yaml
name: Branch Lint
on: [pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npm install -g @branchwright/cli
      - run: brw lint ${{ github.head_ref }}
```

### 国家预防机制文稿

```json
{
  "scripts": {
    "branch": "brw create",
    "branch:lint": "brw lint"
  }
}
```

## 常见模式

### 常规提交样式

```typescript
export default defineConfig({
  branchTypes: [
    { name: 'feat', label: 'feat: New feature' },
    { name: 'fix', label: 'fix: Bug fix' },
    { name: 'docs', label: 'docs: Documentation' },
    { name: 'refactor', label: 'refactor: Code refactoring' },
    { name: 'test', label: 'test: Testing' },
    { name: 'chore', label: 'chore: Maintenance' },
  ],
  template: '{{type}}/{{desc}}',
});
```

### 车票所需工作流量

```typescript
export default defineConfig({
  template: '{{type}}/{{ticket}}-{{desc}}',
  rules: {
    ticketId: ['required', { prefix: 'PROJ-' }],
  },
});
```

### 带可选外加的团队

```typescript
export default defineConfig({
  template: '{{type}}/{{ticket}}-{{desc}}',
  rules: {
    ticketId: ['optional', { prefix: 'TEAM-' }],
  },
  extraQuestions: {
    pushToRemote: true,  // Ask about pushing
  },
});
```

## 解决问题

### "不在一个git仓库"

确保您正在 Git 仓库内运行命令 :

```bash
git init  # If needed
```

### 分支名称验证失败

检查您的配置 :

```bash
brw config
```

验证您的分支名称符合模板和规则 .

### 自定义规则不加载

确保插件路径正确且导出符合预期格式 :

```typescript
// my-rules.ts
export default [defineRule(/* ... */)];
```

## 许可证

麻省理工学院 [分公司撰稿人](https://npmcn.com/package/%40branchwright/cli/LICENSE)

* * *

**由诺尔达鲁开发和维护.**

## 常见问题

### @branchwright/cli 是什么？

Git 分支名称林入和交互式分支创建工具

### 如何安装 @branchwright/cli？

在项目目录运行 npm install @branchwright/cli，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 brw、branchwright，可以用 npx brw 直接运行。

### @branchwright/cli 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @branchwright/cli 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @branchwright/cli 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20\.12\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @branchwright/cli 可以商用吗？

@branchwright/cli 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @branchwright/cli 的下载量有多少？

根据 npm 官方下载统计，@branchwright/cli 在 2026/10/09 – 2026/11/07 这 30 天内被下载 12,062 次，日均约 402 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @branchwright/cli 还在维护吗？

最新版本 1\.0\.1 发布于 2025/11/24（11 个月前）；至今共发布 4 个版本，其中过去 12 个月发布了 4 个；首次发布于 2025/11/09。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

