@ts-org/jenkins-cli 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -175
- package/dist/cli.js +20 -20
- package/docs/images/demo.png +0 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,47 +1,66 @@
|
|
|
1
|
-
##
|
|
1
|
+
## Jenkins CLI
|
|
2
2
|
|
|
3
|
-
一个轻量的 Jenkins
|
|
3
|
+
一个轻量的 Jenkins 部署工具,让你在命令行中通过交互式或非交互式的方式,轻松触发 Jenkins 参数化构建。
|
|
4
4
|
|
|
5
|
-
###
|
|
5
|
+
### ✨ 特性
|
|
6
|
+
|
|
7
|
+
- 交互式 CLI,引导你选择分支和部署环境。
|
|
8
|
+
- 智能触发,自动停止进行中的构建,并复用队列中相同的任务。
|
|
9
|
+
- 灵活的参数化构建,支持在运行时传入额外参数。
|
|
10
|
+
- 丰富的命令集,覆盖 Job、Builds、Queue 等常用操作。
|
|
11
|
+
- 支持 `jenkins-cli.yaml` 或 `package.json` 进行项目级配置。
|
|
12
|
+
|
|
13
|
+
### 📦 安装
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
# Node.js >= 16
|
|
17
|
+
npm install -g @ts-org/jenkins-cli
|
|
18
|
+
|
|
19
|
+
# Node.js >= 18,推荐使用pnpm
|
|
20
|
+
pnpm install -g @ts-org/jenkins-cli
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### 🚀 使用
|
|
24
|
+
|
|
25
|
+
在你的项目根目录下执行:
|
|
6
26
|
|
|
7
27
|
```bash
|
|
8
|
-
|
|
9
|
-
# or
|
|
10
|
-
npm add -D @ts-org/jenkins-cli
|
|
28
|
+
jenkins-cli
|
|
11
29
|
```
|
|
12
30
|
|
|
13
|
-
|
|
31
|
+
CLI 会自动加载配置,列出 Git 分支和部署环境供你选择。
|
|
14
32
|
|
|
15
|
-
|
|
33
|
+

|
|
16
34
|
|
|
17
|
-
|
|
35
|
+
### ⚙️ 配置
|
|
36
|
+
|
|
37
|
+
在项目根目录创建 `jenkins-cli.yaml`:
|
|
18
38
|
|
|
19
39
|
```yaml
|
|
20
|
-
# Jenkins API
|
|
21
|
-
apiToken: http://
|
|
40
|
+
# Jenkins API 地址,格式: http(s)://username:token@host:port
|
|
41
|
+
apiToken: http://user:token@jenkins.example.com
|
|
22
42
|
|
|
23
|
-
# Jenkins Job 名称
|
|
24
|
-
job: your-job
|
|
43
|
+
# Jenkins Job 名称 (可被 -j 参数覆盖)
|
|
44
|
+
job: your-project-job
|
|
25
45
|
|
|
26
|
-
#
|
|
46
|
+
# 部署环境列表 (将作为参数 `mode` 传入 Jenkins)
|
|
27
47
|
modes:
|
|
28
48
|
- dev
|
|
29
49
|
- sit
|
|
30
50
|
- uat
|
|
31
51
|
```
|
|
32
52
|
|
|
33
|
-
####
|
|
53
|
+
#### 扩展交互参数
|
|
34
54
|
|
|
35
|
-
|
|
55
|
+
通过 `configs` 字段,你可以添加自定义的交互式提问,其结果将作为参数传递给 Jenkins。
|
|
36
56
|
|
|
37
|
-
- `type
|
|
38
|
-
- `choices
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
- `name` 不能使用保留字段:`branch` / `modes` / `mode`
|
|
57
|
+
- `type`: 支持 `input`, `list`, `confirm` 等 [Inquirer.js](https://github.com/SBoudrias/Inquirer.js/) 类型。
|
|
58
|
+
- `choices`, `default`, `validate`: 支持从本地 TS/JS 文件动态加载。
|
|
59
|
+
- `path:Fun:funcName`:调用 `funcName()` 函数获取值 (支持 async)。
|
|
60
|
+
- `path:Var:varName`:获取 `varName` 变量的值 (支持 Promise)。
|
|
61
|
+
- `name`: 参数名,注意不要使用 `branch`, `mode`, `modes` 等保留字。
|
|
43
62
|
|
|
44
|
-
|
|
63
|
+
**示例:**
|
|
45
64
|
|
|
46
65
|
```yaml
|
|
47
66
|
configs:
|
|
@@ -49,223 +68,132 @@ configs:
|
|
|
49
68
|
name: version
|
|
50
69
|
message: '请输入版本号:'
|
|
51
70
|
default: '1.0.0'
|
|
52
|
-
|
|
53
71
|
- type: list
|
|
54
72
|
name: service
|
|
55
73
|
message: '请选择服务:'
|
|
56
|
-
choices: src/
|
|
57
|
-
|
|
74
|
+
choices: src/config.ts:Fun:getServices
|
|
58
75
|
- type: input
|
|
59
76
|
name: ticket
|
|
60
|
-
message: '
|
|
61
|
-
validate: src/
|
|
77
|
+
message: '请输入关联的工单号:'
|
|
78
|
+
validate: src/config.ts:Fun:validateTicket
|
|
62
79
|
```
|
|
63
80
|
|
|
64
|
-
`src/
|
|
65
|
-
|
|
81
|
+
对应的 `src/config.ts`:
|
|
66
82
|
```ts
|
|
67
|
-
export async function
|
|
68
|
-
return ['
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export function validateTicket(input: unknown) {
|
|
72
|
-
const s = String(input ?? '').trim()
|
|
73
|
-
if (!s) return 'ticket required'
|
|
74
|
-
return true
|
|
83
|
+
export async function getServices() {
|
|
84
|
+
return ['user-center', 'order-service'];
|
|
75
85
|
}
|
|
76
|
-
```
|
|
77
|
-
|
|
78
|
-
也可以写到 `package.json` 里(适合不想额外放 YAML 的项目):
|
|
79
|
-
|
|
80
|
-
```json
|
|
81
|
-
{
|
|
82
|
-
"jenkins-cli": {
|
|
83
|
-
"apiToken": "http://username:token@jenkins.example.com:8080",
|
|
84
|
-
"job": "your-job-name",
|
|
85
|
-
"modes": ["dev", "sit", "uat"]
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
### 配置查找优先级
|
|
91
|
-
|
|
92
|
-
从高到低:
|
|
93
|
-
|
|
94
|
-
1. 项目根目录的 `jenkins-cli.yaml`
|
|
95
|
-
2. 项目根目录 `package.json` 里的 `jenkins-cli` 字段
|
|
96
|
-
3. 从项目根的父目录开始向上查找到的 `jenkins-cli.yaml`
|
|
97
|
-
|
|
98
|
-
高优先级会覆盖低优先级的同名字段。
|
|
99
|
-
|
|
100
|
-
### 使用
|
|
101
|
-
|
|
102
|
-
在项目目录执行:
|
|
103
|
-
|
|
104
|
-
```bash
|
|
105
|
-
jenkins-cli
|
|
106
|
-
```
|
|
107
86
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
```json
|
|
111
|
-
{
|
|
112
|
-
"scripts": {
|
|
113
|
-
"ship": "jenkins-cli"
|
|
114
|
-
}
|
|
87
|
+
export function validateTicket(input: string) {
|
|
88
|
+
return /^(feat|fix|refactor)-[a-zA-Z0-9]+$/.test(input) || '工单号格式不正确';
|
|
115
89
|
}
|
|
116
90
|
```
|
|
117
91
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
🚀 Jenkins CLI - Jenkins Deployment CLI
|
|
122
|
-
|
|
123
|
-
✔ Configuration loaded
|
|
124
|
-
✔ Found 3 branches
|
|
125
|
-
? 请选择要打包的分支: origin/develop
|
|
126
|
-
? 请选择要打包的环境: dev, sit, uat
|
|
127
|
-
|
|
128
|
-
✔ dev - Build triggered successfully
|
|
129
|
-
✔ sit - Build triggered successfully
|
|
130
|
-
✔ uat - Build triggered successfully
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
触发规则补充:
|
|
92
|
+
> **提示**: 配置也支持写在 `package.json` 的 `jenkins-cli` 字段里。
|
|
93
|
+
>
|
|
94
|
+
> **查找顺序**: `jenkins-cli.yaml` > `package.json` > 父目录的 `jenkins-cli.yaml`。
|
|
134
95
|
|
|
135
|
-
|
|
136
|
-
- 如果队列里已经有完全一致的任务(`branch` + `mode` 都相同),会直接复用队列项,不重复触发
|
|
96
|
+
### 🤖 命令参考
|
|
137
97
|
|
|
138
|
-
|
|
98
|
+
#### `trigger` (非交互式触发)
|
|
139
99
|
|
|
140
|
-
|
|
100
|
+
适用于 CI 或其他脚本化场景。
|
|
141
101
|
|
|
142
102
|
```bash
|
|
103
|
+
# 触发 dev 环境构建
|
|
143
104
|
jenkins-cli trigger -b origin/develop -m dev
|
|
144
|
-
jenkins-cli trigger -b origin/develop -m dev -m uat
|
|
145
|
-
jenkins-cli trigger -b origin/develop -m dev,uat
|
|
146
|
-
```
|
|
147
105
|
|
|
148
|
-
|
|
106
|
+
# 同时触发多个环境
|
|
107
|
+
jenkins-cli trigger -b origin/develop -m dev,sit
|
|
149
108
|
|
|
150
|
-
|
|
151
|
-
jenkins-cli trigger -b origin/develop -m dev --param
|
|
109
|
+
# 传入额外参数
|
|
110
|
+
jenkins-cli trigger -b origin/develop -m dev --param version=1.2.3 --param force=true
|
|
152
111
|
```
|
|
153
112
|
|
|
154
|
-
|
|
113
|
+
---
|
|
155
114
|
|
|
156
|
-
#### builds
|
|
115
|
+
#### `builds` - 构建管理
|
|
157
116
|
|
|
158
117
|
```bash
|
|
159
|
-
#
|
|
160
|
-
jenkins-cli builds list
|
|
161
|
-
jenkins-cli builds list -j your-job -n 50
|
|
118
|
+
# 查看最近 20 次构建
|
|
119
|
+
jenkins-cli builds list
|
|
162
120
|
|
|
163
|
-
#
|
|
121
|
+
# 查看运行中的构建
|
|
164
122
|
jenkins-cli builds running
|
|
165
|
-
jenkins-cli builds running -j your-job
|
|
166
123
|
|
|
167
|
-
# Jenkins
|
|
124
|
+
# 查看 Jenkins 上所有运行中的构建
|
|
168
125
|
jenkins-cli builds running -a
|
|
169
|
-
|
|
170
|
-
# 停止指定构建
|
|
171
|
-
jenkins-cli builds stop 123
|
|
172
|
-
|
|
173
|
-
# 先清理该 job 的队列,再停止所有 running
|
|
174
|
-
jenkins-cli builds stop --all
|
|
175
|
-
jenkins-cli builds stop --all -j your-job
|
|
176
126
|
```
|
|
177
127
|
|
|
178
|
-
####
|
|
128
|
+
#### `job` - Job 管理
|
|
179
129
|
|
|
180
130
|
```bash
|
|
181
|
-
#
|
|
182
|
-
jenkins-cli
|
|
183
|
-
|
|
184
|
-
# 指定 job + 输出 json
|
|
185
|
-
jenkins-cli config read -j your-job -f xml
|
|
186
|
-
jenkins-cli config read -j your-job -f json
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
#### job
|
|
131
|
+
# 列出所有 Job (支持 glob 过滤)
|
|
132
|
+
jenkins-cli job list --search 'project-*'
|
|
190
133
|
|
|
191
|
-
|
|
192
|
-
# 列出所有 job(可按名称过滤)
|
|
193
|
-
jenkins-cli job list
|
|
194
|
-
jenkins-cli job list --search keyword
|
|
195
|
-
# 支持 glob
|
|
196
|
-
jenkins-cli job list --search 'remote*'
|
|
197
|
-
jenkins-cli job list --search remote\\*
|
|
198
|
-
|
|
199
|
-
# 查看 job 信息(可输出原始 JSON)
|
|
134
|
+
# 查看当前 Job 信息
|
|
200
135
|
jenkins-cli job info
|
|
201
|
-
jenkins-cli job info -j your-job
|
|
202
|
-
jenkins-cli job info -j your-job --json
|
|
203
136
|
```
|
|
204
137
|
|
|
205
|
-
#### log
|
|
138
|
+
#### `log` - 查看日志
|
|
206
139
|
|
|
207
140
|
```bash
|
|
208
|
-
#
|
|
209
|
-
jenkins-cli log
|
|
210
|
-
jenkins-cli log 123 -j your-job
|
|
211
|
-
|
|
212
|
-
# 只看最后 N 行
|
|
213
|
-
jenkins-cli log 123 --tail 200
|
|
141
|
+
# 查看指定构建号的日志
|
|
142
|
+
jenkins-cli log 1234
|
|
214
143
|
|
|
215
|
-
#
|
|
216
|
-
jenkins-cli log
|
|
144
|
+
# 实时跟踪日志
|
|
145
|
+
jenkins-cli log 1234 -f
|
|
217
146
|
```
|
|
218
147
|
|
|
219
|
-
####
|
|
148
|
+
#### `stop` - 停止构建
|
|
220
149
|
|
|
221
150
|
```bash
|
|
222
|
-
#
|
|
223
|
-
jenkins-cli
|
|
224
|
-
|
|
151
|
+
# 停止一个构建
|
|
152
|
+
jenkins-cli stop 1234
|
|
153
|
+
|
|
154
|
+
# 清理当前 Job 的队列和所有运行中的构建
|
|
155
|
+
jenkins-cli stop -a
|
|
156
|
+
|
|
157
|
+
# 停止 Jenkins 上所有的构建和队列项 (慎用)
|
|
158
|
+
jenkins-cli stop -A
|
|
225
159
|
```
|
|
226
160
|
|
|
227
|
-
#### queue
|
|
161
|
+
#### `queue` - 等待构建队列管理
|
|
228
162
|
|
|
229
163
|
```bash
|
|
230
|
-
#
|
|
164
|
+
# 查看等待构建的队列
|
|
231
165
|
jenkins-cli queue list
|
|
232
|
-
jenkins-cli queue list -j your-job
|
|
233
166
|
|
|
234
|
-
#
|
|
235
|
-
jenkins-cli queue cancel
|
|
167
|
+
# 取消一个等待构建队列项
|
|
168
|
+
jenkins-cli queue cancel 5678
|
|
236
169
|
```
|
|
237
170
|
|
|
238
|
-
####
|
|
171
|
+
#### `params` - Job 参数
|
|
239
172
|
|
|
240
173
|
```bash
|
|
241
|
-
#
|
|
242
|
-
jenkins-cli
|
|
243
|
-
jenkins-cli stop 123 -j your-job
|
|
244
|
-
|
|
245
|
-
# 清理该 job 的队列 + 停止该 job 下所有 running
|
|
246
|
-
jenkins-cli stop -a
|
|
247
|
-
jenkins-cli stop -a -j your-job
|
|
174
|
+
# 查看当前 Job 的参数定义
|
|
175
|
+
jenkins-cli params
|
|
248
176
|
```
|
|
249
177
|
|
|
250
|
-
####
|
|
178
|
+
#### `config` - Job 配置
|
|
251
179
|
|
|
252
180
|
```bash
|
|
253
|
-
#
|
|
254
|
-
jenkins-cli
|
|
255
|
-
jenkins-cli trigger -b origin/develop -m dev,uat
|
|
181
|
+
# 读取当前 Job 的 XML 配置
|
|
182
|
+
jenkins-cli config read
|
|
256
183
|
|
|
257
|
-
#
|
|
258
|
-
jenkins-cli
|
|
259
|
-
jenkins-cli trigger -b origin/develop -m dev -j your-job
|
|
184
|
+
# 以 JSON 格式输出
|
|
185
|
+
jenkins-cli config read -f json
|
|
260
186
|
```
|
|
261
187
|
|
|
262
|
-
#### whoami
|
|
188
|
+
#### `whoami` - 用户信息
|
|
263
189
|
|
|
264
190
|
```bash
|
|
265
|
-
#
|
|
191
|
+
# 验证 API Token 并查看当前用户
|
|
266
192
|
jenkins-cli whoami
|
|
267
193
|
```
|
|
268
194
|
|
|
269
|
-
###
|
|
195
|
+
### ❓ FAQ
|
|
196
|
+
|
|
197
|
+
**Q: `stop` 或 `queue cancel` 命令返回 403 Forbidden?**
|
|
270
198
|
|
|
271
|
-
|
|
199
|
+
A: 通常是 Jenkins 用户权限不足 (需要 `Job > Cancel` 权限)。请确保你使用的是 API Token 而非密码,并检查 Jenkins 的 CSRF 设置。工具会自动处理 CSRF,但权限问题需要手动排查。
|
package/dist/cli.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { program } from 'commander';
|
|
3
|
-
import
|
|
3
|
+
import He from 'inquirer';
|
|
4
4
|
import f from 'chalk';
|
|
5
|
-
import
|
|
5
|
+
import Me from 'ora';
|
|
6
6
|
import { exec } from 'child_process';
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import
|
|
7
|
+
import Ye, { promisify } from 'util';
|
|
8
|
+
import C from 'fs-extra';
|
|
9
|
+
import Re from 'js-yaml';
|
|
10
|
+
import S from 'path';
|
|
11
|
+
import Te from 'axios';
|
|
12
|
+
import We from 'jiti';
|
|
13
13
|
import { fileURLToPath } from 'url';
|
|
14
14
|
import { XMLParser } from 'fast-xml-parser';
|
|
15
15
|
|
|
16
|
-
var
|
|
17
|
-
`).filter(e=>e.includes("/")&&!e.includes("HEAD"))}catch{throw new Error("Failed to list branches. Are you in a git repository?")}}var
|
|
18
|
-
{PACKAGE_JSON}, and walking up from cwd. Required: apiToken, job, modes (non-empty array)`);return {...r,projectRoot:e}}var
|
|
16
|
+
var Q="3.0.1",_="Jenkins deployment CLI";var G=promisify(exec);async function H(){try{let{stdout:n}=await G("git branch --show-current"),e=n.trim();if(!e)throw new Error("Not on any branch (detached HEAD state)");return e}catch{throw new Error("Failed to get current branch. Are you in a git repository?")}}async function V(){try{let{stdout:n}=await G('git branch -r --format="%(refname:short)"');return n.split(`
|
|
17
|
+
`).filter(e=>e.includes("/")&&!e.includes("HEAD"))}catch{throw new Error("Failed to list branches. Are you in a git repository?")}}var P="jenkins-cli.yaml",q="package.json",F="jenkins-cli",Ee="jenkinsCli";function z(n,e=process.cwd()){let t=e;for(;;){let r=S.join(t,n);if(C.existsSync(r))return r;let o=S.dirname(t);if(o===t)return null;t=o;}}function Pe(n=process.cwd()){return z(P,n)}function Be(n=process.cwd()){let e=z(q,n);return e?S.dirname(e):null}function Le(n){return !!(n.apiToken&&n.job&&Array.isArray(n.modes)&&n.modes.length>0)}async function Y(n){let e=await C.readFile(n,"utf-8"),t=Re.load(e);if(!t||typeof t!="object")throw new Error(`Invalid config in ${P}: expected a YAML object`);return t}async function Ie(n){let e=S.join(n,q);if(!await C.pathExists(e))return {};let t=await C.readFile(e,"utf-8"),r=JSON.parse(t),o=r[F]??r[Ee];if(o==null)return {};if(typeof o!="object"||Array.isArray(o))throw new Error(`Invalid ${q} config: "${F}" must be an object`);return o}async function X(){let n=process.cwd(),e=Be(n)??n,t=S.join(e,P),r={},o=S.dirname(e),s=Pe(o);s&&await C.pathExists(s)&&(r=await Y(s));let i=await Ie(e);r={...r,...i};let a=await C.pathExists(t)?await Y(t):{};if(r={...r,...a},!Le(r))throw new Error(`Config incomplete or not found: tried ${P} in project root, "${F}" in $
|
|
18
|
+
{PACKAGE_JSON}, and walking up from cwd. Required: apiToken, job, modes (non-empty array)`);return {...r,projectRoot:e}}var U={maxRedirects:0,validateStatus:n=>n>=200&&n<400};function h(n){return `job/${n.split("/").map(t=>t.trim()).filter(Boolean).map(encodeURIComponent).join("/job/")}`}function O(n){let e=Array.isArray(n)?n.find(o=>o?.parameters):void 0,t=Array.isArray(e?.parameters)?e.parameters:[],r={};for(let o of t)o?.name&&(r[String(o.name)]=o?.value);return r}function qe(n){try{let t=new URL(n).pathname.split("/").filter(Boolean),r=[];for(let o=0;o<t.length-1;o++)t[o]==="job"&&t[o+1]&&r.push(decodeURIComponent(t[o+1]));return r.join("/")}catch{return ""}}async function Fe(n,e){let r=(await n.axios.get(new URL("api/json?tree=number,url,building,result,timestamp,duration,estimatedDuration,fullDisplayName,displayName,actions[parameters[name,value]]",e).toString())).data??{};return {...r,parameters:O(r.actions)}}function Ue(n,e=400){try{let r=(typeof n=="string"?n:JSON.stringify(n??"",null,2)).trim();return r?r.length>e?`${r.slice(0,e)}...`:r:""}catch{return ""}}function ee(n){let e=n.match(/^(https?):\/\/([^:]+):([^@]+)@(.+)$/);if(!e)throw new Error("Invalid apiToken format. Expected: http(s)://username:token@host:port");let[,t,r,o,s]=e,i=`${t}://${s.replace(/\/$/,"")}/`,a=Te.create({baseURL:i,auth:{username:r,password:o},proxy:!1,timeout:3e4});return {baseURL:i,auth:{username:r,password:o},axios:a,crumbForm:void 0}}async function te(n){try{let e=await n.axios.get("crumbIssuer/api/json"),{data:t}=e;t?.crumbRequestField&&t?.crumb&&(n.axios.defaults.headers.common[t.crumbRequestField]=t.crumb,n.crumbForm={field:t.crumbRequestField,value:t.crumb});let r=e.headers["set-cookie"];if(r){let o=Array.isArray(r)?r.map(s=>s.split(";")[0].trim()):[String(r).split(";")[0].trim()];n.axios.defaults.headers.common.Cookie=o.join("; ");}}catch{}}async function J(n,e){let r=(await n.axios.get("queue/api/json?tree=items[id,task[name],actions[parameters[name,value]],why]")).data.items;if(e){let o=e.trim(),s=o.split("/").filter(Boolean).pop();return r.filter(i=>{let a=i.task?.name;return a===o||(s?a===s:!1)})}return r}async function N(n,e){let t=await n.axios.get(`${h(e)}/api/json?tree=builds[number,url,building,result,timestamp,duration,estimatedDuration,actions[parameters[name,value]]]`);return (Array.isArray(t.data?.builds)?t.data.builds:[]).filter(o=>o?.building).map(o=>({...o,parameters:O(o.actions)}))}async function B(n){let e=await n.axios.get("computer/api/json?tree=computer[displayName,executors[currentExecutable[number,url]],oneOffExecutors[currentExecutable[number,url]]]"),t=Array.isArray(e.data?.computer)?e.data.computer:[],r=[];for(let i of t){let a=Array.isArray(i?.executors)?i.executors:[],l=Array.isArray(i?.oneOffExecutors)?i.oneOffExecutors:[];for(let u of [...a,...l]){let c=u?.currentExecutable;c?.url&&r.push({number:Number(c.number),url:String(c.url)});}}let o=new Map;for(let i of r)i.url&&o.set(i.url,i);return (await Promise.all([...o.values()].map(async i=>{let a=await Fe(n,i.url),l=qe(String(a?.url??i.url));return {...a,job:l}}))).filter(i=>i?.building)}async function A(n,e){return await n.axios.post("queue/cancelItem",new URLSearchParams({id:e.toString()}),U),!0}async function R(n,e,t){try{await n.axios.post(`${h(e)}/${t}/stop/`,new URLSearchParams({}),U);}catch(r){let o=r.response?.status;if(o===403){let s=typeof r.response?.data=="string"?r.response.data.slice(0,200):JSON.stringify(r.response?.data??"").slice(0,200),i=/crumb|csrf/i.test(s);console.log(f.red("[Error] 403 Forbidden: Jenkins \u62D2\u7EDD\u505C\u6B62\u6784\u5EFA\u8BF7\u6C42\uFF08\u53EF\u80FD\u662F\u6743\u9650\u6216 CSRF\uFF09\u3002")),console.log(f.yellow('[Hint] \u8BF7\u786E\u8BA4\u5F53\u524D\u7528\u6237\u5BF9\u8BE5 Job \u62E5\u6709 "Job" -> "Cancel" \u6743\u9650\u3002')),console.log(i?"[Hint] Jenkins returned a crumb/CSRF error. Ensure crumb + session cookie are sent, or use API token (not password).":s?`[Hint] Jenkins response: ${s}`:'[Hint] If "Job/Cancel" is already granted, also try granting "Run" -> "Update" (some versions use it for stop).');return}if(o===404||o===400||o===500){console.log(`[Info] Build #${t} could not be stopped (HTTP ${o}). Assuming it finished.`);return}throw r}}async function L(n,e,t){let r="branch",o="mode",s=t[o];s&&console.log(`Checking for conflicting builds for mode: ${s}...`);let[i,a]=await Promise.all([J(n,e),N(n,e)]),l=(m,p)=>{let y=m.actions?.find(v=>v.parameters);return y?y.parameters.find(v=>v.name===p)?.value:void 0},u=t[r];if(s&&u){let m=i.find(p=>l(p,o)===s&&l(p,r)===u);if(m)return console.log(`Build already in queue (ID: ${m.id}). Skipping trigger.`),new URL(`queue/item/${m.id}/`,n.baseURL).toString()}let c=!1;if(s)for(let m of a)l(m,o)===s&&(console.log(`Stopping running build #${m.number} (mode=${s})...`),await R(n,e,m.number),c=!0);c&&await new Promise(m=>setTimeout(m,1e3)),s&&console.log(`Triggering new build for mode=${s}...`);try{return (await n.axios.post(`${h(e)}/buildWithParameters/`,new URLSearchParams({...t}),U)).headers.location||""}catch(m){let p=m?.response?.status,y=Ue(m?.response?.data);if(p===400){let w=[];w.push("Hint: Jenkins returned 400. Common causes: job is not parameterized, parameter names do not match, or the job endpoint differs (e.g. multibranch jobs)."),w.push(`Hint: This CLI sends parameters "${r}" and "${o}". Ensure your Jenkins Job has matching parameter names.`);let v=y?`
|
|
19
19
|
Jenkins response (snippet):
|
|
20
|
-
${y}`:"";throw new Error(`Request failed with status code 400.${
|
|
21
|
-
${
|
|
22
|
-
`)}`)}if(p){let
|
|
20
|
+
${y}`:"";throw new Error(`Request failed with status code 400.${v}
|
|
21
|
+
${w.join(`
|
|
22
|
+
`)}`)}if(p){let w=y?`
|
|
23
23
|
Jenkins response (snippet):
|
|
24
|
-
${y}`:"";throw new Error(`Request failed with status code ${p}.${
|
|
24
|
+
${y}`:"";throw new Error(`Request failed with status code ${p}.${w}`)}throw m}}async function ne(n){return (await n.axios.get("whoAmI/api/json")).data}async function re(n){return (await n.axios.get("api/json?tree=jobs[name,url,color]")).data.jobs??[]}async function oe(n,e){return (await n.axios.get(`${h(e)}/api/json?tree=name,fullName,url,buildable,inQueue,nextBuildNumber,color,healthReport[description,score],lastBuild[number,url,building,result,timestamp,duration],lastCompletedBuild[number,url,result,timestamp,duration]`)).data}async function ie(n,e,t){let r=Math.max(1,t?.limit??20);return ((await n.axios.get(`${h(e)}/api/json?tree=builds[number,url,building,result,timestamp,duration,actions[parameters[name,value]]]{0,${r}}`)).data.builds??[]).map(i=>({number:i.number,result:i.result,building:i.building,timestamp:i.timestamp,duration:i.duration,url:i.url,parameters:O(i.actions)}))}async function se(n,e,t){let r=await n.axios.get(`${h(e)}/${t}/consoleText`,{responseType:"text"});return String(r.data??"")}async function ae(n,e,t,r){let o=Math.max(0,r?.start??0),s=Math.max(200,r?.intervalMs??1e3);for(;;){let i=await n.axios.get(`${h(e)}/${t}/logText/progressiveText?start=${o}`,{responseType:"text"}),a=String(i.data??"");a&&process.stdout.write(a);let l=i.headers["x-text-size"],u=i.headers["x-more-data"],c=l?Number(l):NaN;if(Number.isNaN(c)||(o=c),!(String(u??"").toLowerCase()==="true"))break;await new Promise(p=>setTimeout(p,s));}}async function ce(n,e){return ((await n.axios.get(`${h(e)}/api/json?tree=property[parameterDefinitions[name,type,description,defaultParameterValue[value],choices]]`)).data?.property??[]).flatMap(s=>s?.parameterDefinitions??[]).filter(Boolean).map(s=>({name:s.name,type:s.type,description:s.description,default:s.defaultParameterValue?.value,choices:s.choices}))}async function le(n,e){let t=await n.axios.get(`${h(e)}/config.xml`,{responseType:"text"});return String(t.data??"")}async function g(){let n=Me("Loading configuration...").start();try{let e=await X();n.succeed("Configuration loaded");let t=ee(e.apiToken);return await te(t),{config:e,jenkins:t}}catch(e){n.fail(f.red(e.message)),process.exit(1);}}var Qe=We(fileURLToPath(import.meta.url),{interopDefault:!0});async function M(n){return await Promise.resolve(n)}function _e(n){let e=String(n??"").trim();if(!e)return null;let t=e.split(":");if(t.length<2)return null;if(t.length===2){let[i,a]=t;return !i||!a?null:{file:i,kind:"Var",exportName:a}}let r=t.at(-2),o=t.at(-1);if(r!=="Fun"&&r!=="Var"||!o)return null;let s=t.slice(0,-2).join(":");return s?{file:s,kind:r,exportName:o}:null}function Ge(n,e){return S.isAbsolute(e)?e:S.join(n,e)}function de(n){return !!n&&typeof n=="object"&&!Array.isArray(n)}async function pe(n,e){let t=_e(e);if(!t)return null;let r=Ge(n,t.file);if(!await C.pathExists(r))throw new Error(`configs reference not found: ${t.file}`);let o=Qe(r),s=de(o)?o:{default:o},i=t.exportName==="default"?s.default:s[t.exportName];if(i===void 0)throw new Error(`configs reference export not found: ${e}`);return {kind:t.kind,value:i}}async function me(n,e){if(typeof e!="string")return e;let t=await pe(n,e);if(!t)return e;if(t.kind==="Var"){if(typeof t.value=="function"){let o=t.value();return await M(o)}return await M(t.value)}if(typeof t.value!="function")throw new Error(`configs reference expected a function: ${e}`);let r=t.value();return await M(r)}async function fe(n,e){let t=Array.isArray(n)?n:[];if(t.length===0)return [];let r=String(e.projectRoot??"").trim()||process.cwd(),o=[];for(let s of t){if(!de(s))continue;let i={...s};if(i.choices!==void 0){i.choices=await me(r,i.choices);let a=String(i.type??"").toLowerCase(),l=i.choices;if((a==="list"||a==="rawlist"||a==="checkbox")&&typeof l!="function"&&!Array.isArray(l))if(l==null)i.choices=[];else if(typeof l=="string"||typeof l=="number"||typeof l=="boolean")i.choices=[String(l)];else if(typeof l[Symbol.iterator]=="function")i.choices=Array.from(l).map(c=>String(c));else throw new Error(`configs "${String(i.name??"")}" choices must resolve to an array (got ${typeof l})`)}if(i.default!==void 0&&(i.default=await me(r,i.default)),i.validate!==void 0){let a=i.validate;if(typeof a=="string"){let l=await pe(r,a);if(!l)i.validate=a;else if(l.kind==="Var"){if(typeof l.value!="function")throw new Error(`validate reference must be a function: ${a}`);i.validate=l.value;}else {if(typeof l.value!="function")throw new Error(`validate reference must be a function: ${a}`);i.validate=(u,c)=>l.value(u,c);}}else typeof a=="function"&&(i.validate=a);}o.push(i);}return o}function ge(n,e){let t=new Set(e),r={};for(let[o,s]of Object.entries(n))if(!t.has(o)&&s!==void 0){if(s===null){r[o]="";continue}if(Array.isArray(s)){r[o]=s.map(i=>String(i)).join(",");continue}if(typeof s=="object"){try{r[o]=JSON.stringify(s);}catch{r[o]=String(s);}continue}r[o]=String(s);}return r}async function be(){console.log(f.bold.blue(`
|
|
25
25
|
\u{1F680} Jenkins CLI - Jenkins Deployment CLI
|
|
26
26
|
`));let{config:n,jenkins:e}=await g(),[t,r]=await Promise.all([V(),H()]),o=()=>{console.log(f.yellow(`
|
|
27
|
-
\u{1F44B} Cancelled by user`)),process.exit(130);},s,i={};try{process.prependOnceListener("SIGINT",o);let l=await
|
|
27
|
+
\u{1F44B} Cancelled by user`)),process.exit(130);},s,i={};try{process.prependOnceListener("SIGINT",o);let l=await fe(n.configs,{projectRoot:n.projectRoot}),u=new Set(["branch","modes","mode"]);for(let m of l){let p=String(m?.name??"").trim();if(u.has(p))throw new Error(`configs name "${p}" is reserved. Use another name.`)}let c=await He.prompt([{type:"list",name:"branch",message:"\u8BF7\u9009\u62E9\u8981\u6253\u5305\u7684\u5206\u652F:",choices:t,default:t.indexOf(r)},{type:"checkbox",name:"modes",message:"\u8BF7\u9009\u62E9\u8981\u6253\u5305\u7684\u73AF\u5883:",choices:n.modes,validate:m=>m.length===0?"You must select at least one environment":!0},...l]);s={branch:String(c.branch??""),modes:c.modes??[]},i=ge(c,["branch","modes"]);}catch(l){let u=l,c=u?.message?String(u.message):String(u);((u?.name?String(u.name):"")==="ExitPromptError"||c.toLowerCase().includes("cancelled")||c.toLowerCase().includes("canceled"))&&(console.log(f.yellow(`
|
|
28
28
|
\u{1F44B} Cancelled by user`)),process.exit(0)),console.log(f.red(`
|
|
29
29
|
\u274C Prompt failed: ${c}
|
|
30
|
-
`)),process.exit(1);}finally{process.off("SIGINT",o);}console.log();let a=s.modes.map(async l=>{let u=
|
|
30
|
+
`)),process.exit(1);}finally{process.off("SIGINT",o);}console.log();let a=s.modes.map(async l=>{let u=Me(`Triggering build for ${f.yellow(l)}...`).start();try{let c=await L(e,n.job,{...i,branch:s.branch,mode:l});u.succeed(`${f.green(l)} - Triggered! Queue: ${c}`);}catch(c){throw u.fail(`${f.red(l)} - ${c.message}`),c}});try{await Promise.all(a),console.log();}catch{console.log(f.bold.red(`
|
|
31
31
|
\u274C Some builds failed. Check the output above.
|
|
32
|
-
`)),process.exit(1);}}function b(n,e){return (e??"").trim()||n}function
|
|
32
|
+
`)),process.exit(1);}}function b(n,e){return (e??"").trim()||n}function k(n,e){let t=Number(n);if(!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function he(n){let e=n.command("queue").description("\u7B49\u5F85\u6784\u5EFA\u961F\u5217\u76F8\u5173\u64CD\u4F5C");e.command("list").description("\u83B7\u53D6\u7B49\u5F85\u6784\u5EFA\u7684\u961F\u5217\u5217\u8868").option("-j, --job <job>","\u4EC5\u663E\u793A\u6307\u5B9A Job \u7684\u7B49\u5F85\u6784\u5EFA\u961F\u5217\u9879").action(async t=>{let{config:r,jenkins:o}=await g(),s=t.job?b(r.job,t.job):void 0,i=await J(o,s);console.table((i??[]).map(a=>({id:a.id,job:a.task?.name,why:a.why})));}),e.command("cancel").description("\u53D6\u6D88\u7B49\u5F85\u6784\u5EFA\u7684\u961F\u5217\u9879").argument("<id>").action(async t=>{let{jenkins:r}=await g(),o=await A(r,k(t,"id"));console.log(o?f.green("Cancelled"):f.red("Cancel failed"));});}function d(n){return {[Ye.inspect.custom]:()=>n}}function j(n){let e=String(n??""),t=e.trim();if(!t)return d(f.gray("-"));let r=s=>d(s),o=t.toLowerCase();if(o.startsWith("http://")||o.startsWith("https://"))try{let i=(new URL(t).hostname??"").toLowerCase(),a=i==="localhost"||i==="127.0.0.1"||i==="::1",l=/^10\./.test(i)||/^192\.168\./.test(i)||/^127\./.test(i)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(i);return r(a||l?f.cyanBright(e):f.hex("#4EA1FF")(e))}catch{return r(f.hex("#4EA1FF")(e))}return o.startsWith("ws://")||o.startsWith("wss://")?r(f.cyan(e)):o.startsWith("ssh://")||o.startsWith("git+ssh://")||o.startsWith("git@")?r(f.magenta(e)):o.startsWith("file://")?r(f.yellow(e)):o.startsWith("mailto:")?r(f.green(e)):o.startsWith("javascript:")||o.startsWith("data:")?r(f.red(e)):t.startsWith("/")||t.startsWith("./")||t.startsWith("../")?r(f.cyan(e)):/^[a-z0-9.-]+(?::\d+)?(\/|$)/i.test(t)?r(f.blue(e)):r(e)}function $(n){let e=new Date(n),t=r=>String(r).padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function E(n,e){if(e===!0)return d(f.cyan("BUILDING"));let t=String(n??"").toUpperCase();return d(t?t==="SUCCESS"?f.green(t):t==="ABORTED"?f.gray(t):t==="FAILURE"?f.red(t):t==="UNSTABLE"?f.yellow(t):t==="NOT_BUILT"?f.gray(t):t:"-")}function D(n){let e=String(n??"");if(!e)return d("-");let t=e.endsWith("_anime"),r=t?e.slice(0,-6):e,o=(()=>{switch(r){case"blue":return t?f.blueBright(e):f.blue(e);case"red":return t?f.redBright(e):f.red(e);case"yellow":return t?f.yellowBright(e):f.yellow(e);case"aborted":return f.gray(e);case"disabled":case"notbuilt":case"grey":case"gray":return f.gray(e);default:return e}})();return d(o)}function ze(n){let e=Object.entries(n??{}).filter(([r])=>r);if(!e.length)return d("-");e.sort(([r],[o])=>r.localeCompare(o,"en",{sensitivity:"base"}));let t=e.map(([r,o])=>{if(o===void 0)return `${r}=`;if(o===null)return `${r}=null`;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return `${r}=${o}`;try{return `${r}=${JSON.stringify(o)}`}catch{return `${r}=${String(o)}`}}).join(", ");return d(t)}function we(n){let e=n.command("builds").description("\u6784\u5EFA\u76F8\u5173\u64CD\u4F5C");e.command("list").description("\u83B7\u53D6\u6784\u5EFA\u5217\u8868").option("-j, --job <job>","\u6307\u5B9A job").option("-n, --limit <n>","\u6570\u91CF","20").action(async t=>{let{config:r,jenkins:o}=await g(),s=b(r.job,t.job),i=await ie(o,s,{limit:Number(t.limit)});console.table(i.map(a=>({number:a.number,result:E(a.result,a.building),building:a.building,durationS:Number((Number(a.duration??0)/1e3).toFixed(3)),date:d($(Number(a.timestamp??0)))})));}),e.command("running").description("\u83B7\u53D6\u6B63\u5728\u8FD0\u884C\u7684\u6784\u5EFA").option("-j, --job <job>","\u6307\u5B9A job").option("-a, --all","\u67E5\u8BE2 Jenkins \u4E0B\u6240\u6709\u6B63\u5728\u8FD0\u884C\u7684\u6784\u5EFA").action(async t=>{let{config:r,jenkins:o}=await g(),s=t.all?await B(o):await N(o,b(r.job,t.job));console.table((s??[]).map(i=>({...t.all?{job:d(String(i.job??""))}:{},number:i.number,date:d(i.timestamp?$(Number(i.timestamp)):"-"),parameters:ze(i.parameters),url:j(String(i.url??""))})));});}function xe(n){n.command("log").description("\u83B7\u53D6\u6784\u5EFA\u63A7\u5236\u53F0\u65E5\u5FD7").argument("<id>").option("-j, --job <job>","\u6307\u5B9A job").option("--tail <n>","\u4EC5\u8F93\u51FA\u6700\u540E N \u884C").option("-f, --follow","\u6301\u7EED\u8F93\u51FA\uFF08\u76F4\u5230 Jenkins \u8868\u793A\u65E0\u66F4\u591A\u65E5\u5FD7\uFF09").option("--interval <ms>","follow \u62C9\u53D6\u95F4\u9694","1000").action(async(e,t)=>{let{config:r,jenkins:o}=await g(),s=b(r.job,t.job),i=k(e,"id");if(t.follow){await ae(o,s,i,{intervalMs:Number(t.interval)});return}let a=await se(o,s,i);if(t.tail){let l=k(t.tail,"tail"),u=a.split(`
|
|
33
33
|
`);console.log(u.slice(Math.max(0,u.length-l)).join(`
|
|
34
|
-
`));return}process.stdout.write(a);});}function ke(n){n.command("stop").description("\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u6784\u5EFA
|
|
34
|
+
`));return}process.stdout.write(a);});}function ke(n){n.command("stop").description("\u6E05\u7406\u7B49\u5F85\u6784\u5EFA\u7684\u961F\u5217\u4E2D\u7684\u4EFB\u52A1\u5E76\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u6784\u5EFA").argument("[id]","\u6784\u5EFA\u7F16\u53F7").option("-j, --job <job>","\u6307\u5B9A Jenkins Job").option("-a, --all","\u53D6\u6D88\u8BE5 Job \u7684\u7B49\u5F85\u6784\u5EFA\u961F\u5217\u9879\uFF0C\u5E76\u505C\u6B62\u8BE5 Jenkins Job \u4E0B\u6240\u6709\u6B63\u5728\u8FD0\u884C\u7684\u6784\u5EFA").option("-A, --ALL","\u53D6\u6D88 Jenkins \u4E0A\u6240\u6709\u7B49\u5F85\u6784\u5EFA\u961F\u5217\u9879\uFF0C\u5E76\u505C\u6B62\u6240\u6709\u6B63\u5728\u8FD0\u884C\u7684\u6784\u5EFA").action(async(e,t)=>{let{config:r,jenkins:o}=await g(),s=b(r.job,t.job);if(t.ALL){let[i,a]=await Promise.all([J(o),B(o)]),l=(i??[]).map(c=>Number(c.id)).filter(c=>!Number.isNaN(c)),u=(a??[]).map(c=>({number:Number(c.number),job:String(c.job??"")})).filter(c=>c.job&&!Number.isNaN(c.number));for(let c of l)await A(o,c);for(let c of u)await R(o,c.job,c.number);console.log(f.green(`Requested: cancelled ${l.length} queue item(s), stopped ${u.length} running build(s).`));return}if(t.all){let[i,a]=await Promise.all([J(o,s),N(o,s)]),l=(i??[]).map(c=>Number(c.id)).filter(c=>!Number.isNaN(c)),u=(a??[]).map(c=>Number(c.number)).filter(c=>!Number.isNaN(c));for(let c of l)await A(o,c);for(let c of u)await R(o,s,c);console.log(f.green(`Requested: cancelled ${l.length} queue item(s), stopped ${u.length} running build(s).`));return}if(!e){console.log(f.red("Missing build id. Provide <id> or use -a/--all."));return}await R(o,s,k(e,"id")),console.log(f.green("Stop requested"));});}function je(n){n.command("params").description("\u83B7\u53D6 job \u53C2\u6570\u5B9A\u4E49").option("-j, --job <job>","\u6307\u5B9A job").action(async e=>{let{config:t,jenkins:r}=await g(),o=b(t.job,e.job),s=await ce(r,o),i=Math.max(0,...s.map(a=>String(a?.name??"").length));console.table((s??[]).map(a=>({name:d(String(a?.name??"").padEnd(i," ")),type:d(String(a?.type??"")),description:d(String(a?.description??"")),default:d(a?.default===void 0?"-":String(a.default)),choices:d(Array.isArray(a?.choices)?a.choices.join(", "):a?.choices??"-")})));});}function Ce(n){n.command("whoami").description("\u67E5\u770B\u5F53\u524D Token \u5BF9\u5E94\u7684 Jenkins \u7528\u6237\u4FE1\u606F").action(async()=>{let{jenkins:e}=await g(),t=await ne(e),r=t&&typeof t=="object"?t:{value:t},o=(u,c)=>{let m=u.length;if(m>=c)return u;let p=c-m,y=Math.floor(p/2),w=p-y;return `${" ".repeat(y)}${u}${" ".repeat(w)}`},s=r.name??r.fullName??r.id??"",i=s==null?"":String(s),a=Math.max(20,i.length),l={};l.name=d(o(i,a));for(let u of Object.keys(r).sort((c,m)=>c.localeCompare(m,"en"))){if(u==="name")continue;let c=r[u],m=u.toLowerCase();if((m==="url"||m.endsWith("url")||m.includes("url"))&&(typeof c=="string"||typeof c=="number")){l[u]=j(String(c));continue}let y=c==null?"":typeof c=="object"?JSON.stringify(c):String(c);l[u]=d(y);}console.table([l]);});}function Se(n){n.command("config").description("\u8BFB\u53D6 Jenkins Job \u914D\u7F6E").command("read").description("\u8BFB\u53D6 job \u914D\u7F6E").option("-j, --job <job>","\u6307\u5B9A job").option("-f, --format <format>","\u8F93\u51FA\u683C\u5F0F\uFF1Axml \u6216 json","xml").action(async t=>{let{config:r,jenkins:o}=await g(),s=b(r.job,t.job),i=String(t.format??"xml").toLowerCase();if(i!=="xml"&&i!=="json")throw new Error(`Invalid format: ${t.format}. Expected: xml or json`);let a=await le(o,s);if(i==="xml"){process.stdout.write(a);return}let u=new XMLParser({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(a);console.log(JSON.stringify(u,null,2));});}function Je(n){let e=n.command("job").description("Job \u76F8\u5173\u64CD\u4F5C"),t=(r,o)=>{let s=String(o??"").trim();if(!s)return !0;if(!/[*?]/.test(s))return r.includes(s);let l=`^${s.replace(/[$()*+.?[\\\]^{|}]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,".")}$`;try{return new RegExp(l).test(r)}catch{return r.includes(s)}};e.command("list").description("\u83B7\u53D6\u6240\u6709 job").option("--search <keyword>","\u6309\u540D\u79F0\u8FC7\u6EE4\uFF08\u652F\u6301 glob\uFF09").action(async r=>{let{jenkins:o}=await g(),s=await re(o),i=(r.search??"").trim(),a=i?s.filter(c=>t(String(c.name??""),i)):s;a.sort((c,m)=>String(c?.name??"").localeCompare(String(m?.name??""),"en",{sensitivity:"base"}));let l=Math.max(0,...a.map(c=>String(c?.name??"").length)),u=Math.max(0,...a.map(c=>String(c?.url??"").length));console.table((a??[]).map(c=>({name:d(String(c.name??"").padEnd(l," ")),color:D(c.color),url:j(String(c.url??"").padEnd(u," "))})));}),e.command("info").description("\u83B7\u53D6 job \u4FE1\u606F").option("-j, --job <job>","\u6307\u5B9A job").option("--json","\u8F93\u51FA\u539F\u59CB JSON").action(async r=>{let{config:o,jenkins:s}=await g(),i=b(o.job,r.job),a=await oe(s,i);if(r.json){console.log(JSON.stringify(a,null,2));return}let l=a?.lastBuild,u=a?.lastCompletedBuild,c=Array.isArray(a?.healthReport)?a.healthReport:[];console.table([{name:d(String(a?.name??"")),url:j(String(a?.url??"")),color:D(a?.color),buildable:a?.buildable,inQueue:a?.inQueue,nextBuildNumber:a?.nextBuildNumber,healthScore:c[0]?.score??"-",lastBuild:d(l?.number?`#${l.number}`:"-"),lastResult:E(l?.result,l?.building),lastDurationS:l?.duration===void 0?"-":Number((Number(l.duration)/1e3).toFixed(3)),lastDate:d(l?.timestamp?$(Number(l.timestamp)):"-"),lastCompleted:d(u?.number?`#${u.number}`:"-"),lastCompletedResult:E(u?.result,!1),lastCompletedDate:d(u?.timestamp?$(Number(u.timestamp)):"-")}]);});}function et(n){return n.split(",").map(e=>e.trim()).filter(Boolean)}function tt(n){let e=n.indexOf("=");if(e<=0)throw new Error(`Invalid --param: "${n}". Expected: key=value`);let t=n.slice(0,e).trim(),r=n.slice(e+1).trim();if(!t)throw new Error(`Invalid --param: "${n}". Key is empty`);return {key:t,value:r}}function $e(n){n.command("trigger").description("\u975E\u4EA4\u4E92\u89E6\u53D1 Jenkins \u6784\u5EFA").requiredOption("-b, --branch <branch>","\u5206\u652F\uFF08\u4F8B\u5982 origin/develop\uFF09").option("-m, --mode <mode>","\u90E8\u7F72\u73AF\u5883\uFF08\u53EF\u91CD\u590D\u4F20\u5165\uFF0C\u6216\u7528\u9017\u53F7\u5206\u9694\uFF1A-m dev -m uat / -m dev,uat\uFF09",(e,t)=>t.concat(et(e)),[]).option("--param <key=value>","\u989D\u5916\u53C2\u6570\uFF08\u53EF\u91CD\u590D\u4F20\u5165\uFF0C\u4F8B\u5982\uFF1A--param foo=bar\uFF09",(e,t)=>t.concat(e),[]).option("-j, --job <job>","\u6307\u5B9A job").action(async e=>{let{config:t,jenkins:r}=await g(),o=b(t.job,e.job),s=String(e.branch??"").trim();if(!s)throw new Error("branch is required");let i=(e.mode??[]).map(String).map(c=>c.trim()).filter(Boolean),a=Array.from(new Set(i));if(a.length===0)throw new Error("mode is required. Example: jenkins-cli trigger -b origin/develop -m dev -m uat");let l={};for(let c of e.param??[]){let{key:m,value:p}=tt(String(c));l[m]=p;}console.log();let u=a.map(async c=>{let m=Me(`Triggering build for ${f.yellow(c)}...`).start();try{let p=await L(r,o,{...l,branch:s,mode:c});m.succeed(`${f.green(c)} - Triggered! Queue: ${p}`);}catch(p){throw m.fail(`${f.red(c)} - ${p.message}`),p}});try{await Promise.all(u),console.log();}catch{console.log(f.bold.red(`
|
|
35
35
|
\u274C Some builds failed. Check the output above.
|
|
36
|
-
`)),process.exit(1);}});}function
|
|
36
|
+
`)),process.exit(1);}});}function ve(n){we(n),Se(n),Je(n),xe(n),je(n),he(n),ke(n),$e(n),Ce(n);}program.name("jenkins-cli").description(_).version(Q,"-v, --version").helpOption("-h, --help").action(be);ve(program);program.parse();
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ts-org/jenkins-cli",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
4
4
|
"description": "Jenkins deployment CLI",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -34,7 +34,8 @@
|
|
|
34
34
|
"files": [
|
|
35
35
|
"dist",
|
|
36
36
|
"README.md",
|
|
37
|
-
"LICENSE"
|
|
37
|
+
"LICENSE",
|
|
38
|
+
"docs/images/demo.png"
|
|
38
39
|
],
|
|
39
40
|
"dependencies": {
|
|
40
41
|
"axios": "^1.13.4",
|
|
@@ -70,4 +71,4 @@
|
|
|
70
71
|
"doc": "docs"
|
|
71
72
|
},
|
|
72
73
|
"types": "./dist/index.d.ts"
|
|
73
|
-
}
|
|
74
|
+
}
|