-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.ts
374 lines (337 loc) · 12 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import path from 'path'
import inquirer from 'inquirer'
import minimist from 'minimist'
import netrc, { Machines } from 'netrc-parser'
import { rcFile } from 'rc-config-loader'
import { pretty, showVersion, usageExit, loadRequiedFile } from './util'
import type { Opts, Ginuerc, Commands, BaseOpts, AppDic } from './types'
export const loadKintoneCommands = async ({
commands,
exclude,
}: {
commands: Commands
exclude: keyof Commands | (keyof Commands)[]
}) => {
const kintoneCommands = commands || loadRequiedFile<Commands>(path.join(__dirname, 'commands'))
if (exclude) {
// TODO: -aオプションの複数指定もこの仕様に合わせた方が良いかも。。
const excludeCommands = Array.isArray(exclude) ? exclude : [exclude]
for (const excludeCommand of excludeCommands) {
if (!kintoneCommands[excludeCommand]) {
console.error(`ERROR: '${excludeCommand}' no such command!`)
process.exit(1)
}
delete kintoneCommands[excludeCommand]
}
}
return kintoneCommands
}
const loadGinuerc = async (): Promise<BaseOpts[]> => {
const ginuercFile = rcFile<Ginuerc>('ginue')
if (!ginuercFile) {
return [{}]
}
const _ginuerc: Ginuerc = ginuercFile.config
if (Array.isArray(_ginuerc)) {
console.error(`ERROR: The top-level structure of .ginuerc must not be array. (Since v2.0)`)
process.exit(1)
}
const { env, ...ginuerc } = _ginuerc
if (!env) {
return [ginuerc]
}
return Object.entries(env).map(([envName, envGinuerc]) => {
envGinuerc.environment = envName
// 内側のlocationはプロパティ名を変更しておく
envGinuerc.envLocation = envGinuerc.location
envGinuerc.location = ginuerc.location
// location以外のプロパティは(外側 < 内側)の優先度で設定
const props = ['fileType', 'preview', 'alt', 'oauth', 'commands', 'downloadJs', 'proxy'] as const
props.forEach((prop) => {
if (ginuerc[prop] && envGinuerc[prop] === undefined) {
// @ts-expect-error
envGinuerc[prop] = ginuerc[prop]
}
})
return envGinuerc
})
}
const inputKintoneInfo = async (name: string, type = 'input'): Promise<string> => {
const value = await inquirer.prompt([
{
name,
type,
message: `Enter your kintone ${name}:`,
validate: (value) => {
if (value.length) {
return true
} else {
return `Please enter your ${name}`
}
},
},
])
return value[name]
}
const stdInputOptions = async (opts: BaseOpts) => {
const TYPE_PASSWORD = 'password'
// .netrcファイルの読み込み
netrc.loadSync()
const netrcMachines = netrc.machines
// 標準入力しないオプションを画面表示(複数環境のアカウント情報入力などで間違えないため)
for (const [optName, optValue] of Object.entries(opts)) {
if (optValue) {
// TODO: chalkなど使って色をつけたい
let dispValue = pretty(optValue)
switch (optName) {
case 'password':
case 'basic':
dispValue = '[hidden]'
break
case 'pushTarget':
continue
}
console.info(`${optName}: ${dispValue}`)
}
}
// プロキシサーバーの認証情報がnetrcにある場合は読み取る
// 認証はオプションなので、認証情報が見つからなくても標準入力はさせない
if (opts.proxy instanceof Object && !opts.proxy.auth) {
const netrcProxyProps = netrcMachines[opts.proxy.hostname]
if (netrcProxyProps) {
opts.proxy.auth = `${netrcProxyProps.login}:${netrcProxyProps.password}`
}
}
opts.domain = opts.domain || (await inputKintoneInfo('domain'))
const netrcProps: Machines[string] = !opts.oauth ? netrcMachines[opts.domain] ?? {} : {}
const netrcBasic = netrcProps.account
// TODO: コマンドライン引数のbasic処理と共通化したい
if (!opts.basic && netrcBasic) {
if (netrcBasic.includes(':')) {
opts.basic = netrcBasic
;[opts.basic_user, opts.basic_password] = netrcBasic.split(':')
} else if (!opts.basic_user) {
opts.basic_user = netrcBasic
}
}
if (opts.basic_user && !opts.basic_password) {
// Basic認証のパスワードが省略された時だけ標準入力で問い合わせ
// そもそもbasicオプションが指定されなかった場合は無視
const basicPassword = await inputKintoneInfo('Basic Authentication password', TYPE_PASSWORD)
opts.basic = `${opts.basic_user}:${basicPassword}`
}
if (!opts.oauth) {
opts.username =
opts.username || netrcProps.login || process.env.GINUE_USERNAME || (await inputKintoneInfo('username'))
opts.password =
opts.password ||
netrcProps.password ||
process.env.GINUE_PASSWORD ||
(await inputKintoneInfo('password', TYPE_PASSWORD))
opts.basic = opts.basic || process.env.GINUE_BASIC
}
// クライアント認証書のオプション
opts.pfxFilepath = opts.pfxFilepath || process.env.GINUE_PFX_FILEPATH
opts.pfxPassword =
opts.pfxPassword ||
process.env.GINUE_PFX_PASSWORD ||
(opts.pfxFilepath && (await inputKintoneInfo('client certificate password', TYPE_PASSWORD)))
// @ts-expect-error
opts.app = opts.app || (await inputKintoneInfo('app'))
console.info()
// TODO: 「is guest space?(Y/N)」のように問い合わせて、YならguestSpaceIdを入力
// opts.guestSpaceId = opts.guestSpaceId || await inputKintoneInfo('guestSpaceID')
}
const parseArgumentOptions = () => {
const argv = minimist(process.argv.slice(2), {
// booleanを明記するとデフォルトfalseになってginuercとマージしづらいので書かない
// 有効なオプションが分かるようにコメントとしては残しておく
// boolean: ['version', 'help', 'preview', 'acl', 'alt', 'oauth'],
string: [
'location',
'domain',
'username',
'password',
'app',
'guest',
'basic',
'exclude',
'fileType',
'appName',
'pfxFilepath',
'pfxPassword',
],
alias: {
v: 'version',
h: 'help',
l: 'location',
d: 'domain',
u: 'username',
p: 'password',
a: 'app',
g: 'guest',
b: 'basic',
x: 'exclude',
t: 'fileType',
A: 'appName',
F: 'pfxFilepath',
P: 'pfxPassword',
},
})
if (argv.domain || argv.username || argv.password || argv.app || argv.guest) {
argv.priority = true
}
if (argv._[0]) {
argv.type = argv._[0]
}
if (argv._[1]) {
argv.target = argv._[1]
}
return argv
}
// TODO: minimistやめて、もっとリッチなライブラリを使う
// 引数や設定ファイルの組み合わせからオプション値を抽出
// firstObjを優先し、firstObjに存在しないプロパティはsecondObjを使用
const pluckOpts = (firstObj: any, secondObj?: any) => {
// TODO: previewやjsなどのboolean値はfirstObjがfalseでも必ず使われてしまうのを修正
const obj = Object.assign({}, secondObj, firstObj)
const opts: Opts = {
location: obj.location,
envLocation: obj.envLocation,
environment: obj.environment,
// TODO: プロキシ設定のドキュメント書く
// ginuercに以下のいずれかで定義
// proxy: {
// protocol: 'https',
// auth: 'username:password',
// hostname: 'proxy.example.com',
// port: 443,
// },
// proxy: 'https://username:password@proxy.example.com:443'
// もしくは環境変数に書いてもOK(一般的な設定)
// HTTPS_PROXY='https://username:password@proxy.example.com:443'
proxy: obj.proxy,
domain: obj.domain,
username: obj.username,
password: obj.password,
app: obj.app,
guestSpaceId: obj.guest,
pushTarget: obj.pushTarget,
// TODO: ginue diffコマンドを叩くとpreviewと運用環境との差分を表示したい(diffコマンドへのエイリアス?)
preview: obj.preview,
acl: obj.acl,
field_acl: obj.field_acl,
exclude: obj.exclude,
fileType: obj.fileType,
appName: obj.appName,
alt: obj.alt,
oauth: obj.oauth,
commands: obj.commands,
downloadJs: obj.downloadJs,
pfxFilepath: obj.pfxFilepath,
pfxPassword: obj.pfxPassword,
}
// Basic認証のパスワード有無でプロパティ名を変えておく
const basic = obj.basic
if (basic) {
if (basic.includes(':')) {
opts.basic = basic
} else {
opts.basic_user = basic
}
}
return opts
}
const createAppDic = (app: string | (string | number)[] | AppDic): AppDic => {
if (typeof app === 'string') {
app = app.split(',').map((str) => str.trim())
}
if (Array.isArray(app)) {
return app.reduce<AppDic>((obj, id) => {
obj[id.toString()] = id
return obj
}, {})
}
return app
}
export const createOptionValues = async () => {
const argv = parseArgumentOptions()
if (argv.version) {
showVersion()
}
if (argv.help) {
usageExit(0, argv.type)
}
if (!argv.type || !['pull', 'push', 'reset', 'deploy', 'erd', 'diff'].includes(argv.type)) {
usageExit(1)
}
const ginuerc = await loadGinuerc()
let opts: Opts | Opts[] = {}
if (argv.target) {
const [target, pushTarget] = argv.target.split(':')
// push先target(コロンの右側)はginue pushの場合のみ指定可能
if (pushTarget && !['push', 'diff'].includes(argv.type)) {
usageExit(1, argv.type)
}
const targetGinuercElem = ginuerc.find((g): g is Opts => g.environment === target)
if (!targetGinuercElem) {
console.error(`ERROR: environment '${target}' not found.`)
process.exit(1)
}
if (pushTarget) {
// TODO: コマンドライン引数と組み合わさった場合の各種パターンを要テスト
const pushTargetGinuercElem = ginuerc.find((g) => g.environment === pushTarget)
if (!pushTargetGinuercElem) {
console.error(`ERROR: environment '${pushTarget}' not found.`)
process.exit(1)
}
if (Array.isArray(pushTargetGinuercElem.app) || Array.isArray(targetGinuercElem.app)) {
console.error(`ERROR: 'app' should be Object if 'ginue push <env>:<env>' is specified.`)
usageExit(1, 'push')
}
targetGinuercElem.pushTarget = pushTargetGinuercElem
}
opts = pluckOpts(argv, targetGinuercElem)
} else if (ginuerc.length === 1) {
// ginuercに単一環境だけ指定されている場合は、
// argvを優先し、argvに存在しないオプションだけginuercを使う
opts = pluckOpts(argv, ginuerc[0])
} else if (argv.priority) {
// ginuercに複数環境が指定され、argvにpriorityなオプションがある場合は、
// ginuercを無視してargvのオプションだけ使う
// argvには1種類の環境しか指定できず、ginuercの一部だけ使うことが難しいため
opts = pluckOpts(argv)
} else if (['push', 'reset', 'deploy'].includes(argv.type)) {
// 送信系のコマンドは単一環境のみを対象にするため、ここまでの条件に合致しなければエラー
// 複数環境への一括pushも技術的には難しくないけど、ヒューマンエラー防止のため非対応
console.error('ERROR: <target environment> is required if .ginuerc has multiple environments.')
usageExit(1, argv.type)
} else {
// 複数環境対応コマンドでargvにpriorityなオプションがなければ
// ginuercの複数環境を全て使用
// argvに何かしらオプションがあれば全環境でargvを優先
opts = ginuerc.map((g) => pluckOpts(argv, g))
}
const allOpts = Array.isArray(opts) ? opts : [opts]
for (const opts of allOpts) {
await stdInputOptions(opts)
if (opts.pushTarget) {
await stdInputOptions(opts.pushTarget)
}
opts.apps = createAppDic(opts.app!)
opts.type = argv.type
}
if (['push', 'reset', 'deploy'].includes(argv.type)) {
const { isConfirmed } = await inquirer.prompt([
{
name: 'isConfirmed',
type: 'confirm',
message: `[${argv.type}] Are you sure?`,
},
])
if (!isConfirmed) {
process.exit(0)
}
}
return allOpts
}