@qse/ssh-sftp 1.1.0 → 1.3.0

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/src/index.js ADDED
@@ -0,0 +1,504 @@
1
+ import Client from 'ssh2-sftp-client'
2
+ import ora from 'ora'
3
+ import * as glob from 'glob'
4
+ import fs from 'fs'
5
+ import * as minimatch from 'minimatch'
6
+ import inquirer from 'inquirer'
7
+ import { exitWithError, injectTiming, warn } from './utils.js'
8
+ import chalk from 'chalk'
9
+ import { presets, servers } from './presets.js'
10
+ import path from 'path'
11
+ import pLimit from 'p-limit'
12
+
13
+ const limit = pLimit(6)
14
+
15
+ /** @type {Options} */
16
+ const defualtOpts = {
17
+ localPath: 'dist',
18
+ noWarn: false,
19
+ keepAlive: false,
20
+ cleanRemoteFiles: true,
21
+ ignore: ['**/*.LICENSE.txt'],
22
+ securityLock: true,
23
+ }
24
+
25
+ /**
26
+ * get upload files
27
+ *
28
+ * @param {string} localPath
29
+ * @param {string} remotePath
30
+ * @param {string[]} ignore
31
+ */
32
+ function getFilesPath(localPath, remotePath, ignore) {
33
+ const files = glob.sync(`${localPath}/**/*`, {
34
+ ignore: getSafePattern(ignore, localPath),
35
+ dot: true,
36
+ })
37
+ return files.map((localFilePath) => {
38
+ return {
39
+ localPath: localFilePath,
40
+ remotePath: localFilePath.replace(localPath, remotePath),
41
+ }
42
+ })
43
+ }
44
+
45
+ /**
46
+ * get remote ls deep
47
+ *
48
+ * @typedef {Object} FilesOptions
49
+ * @property {true|string[]} [patterns]
50
+ *
51
+ * @param {Client} sftp
52
+ * @param {string} remotePath
53
+ * @param {FilesOptions} [options]
54
+ * @return {Promise<{isDir:boolean;path:string}[]>}
55
+ */
56
+ async function getRemoteDeepFiles(sftp, remotePath, options) {
57
+ const { patterns } = options
58
+ const data = []
59
+ const queue = [remotePath]
60
+ const LIST_CONCURRENCY = 6
61
+
62
+ while (queue.length > 0) {
63
+ const batch = queue.splice(0, LIST_CONCURRENCY)
64
+ const results = await Promise.all(
65
+ batch.map(async (base) => {
66
+ try {
67
+ return { base, list: await sftp.list(base) }
68
+ } catch {
69
+ return { base, list: [] }
70
+ }
71
+ }),
72
+ )
73
+
74
+ for (const { base, list } of results) {
75
+ for (const item of list) {
76
+ const p = `${base}/${item.name}`
77
+ if (item.type === 'd') {
78
+ data.push({ isDir: true, path: p })
79
+ queue.push(p)
80
+ } else {
81
+ data.push({ isDir: false, path: p })
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ const ls = data.filter((o) => o.path)
88
+
89
+ if (patterns.length > 0) {
90
+ const safePatterns = getSafePattern(patterns, remotePath)
91
+ return ls.filter((o) => safePatterns.some((reg) => minimatch(o.path, reg)))
92
+ }
93
+ return ls
94
+ }
95
+
96
+ function ensureDiff(local, remote) {
97
+ return remote.map((file) => {
98
+ const isSame = local.some((local) => local.remotePath === file.path)
99
+ return { ...file, isSame }
100
+ })
101
+ }
102
+
103
+ /**
104
+ * @typedef {Object} Options
105
+ * @property {string} [localPath]
106
+ * @property {string} [remotePath]
107
+ * @property {{context?:string;folder?:string;server?:string}} [preset]
108
+ * @property {import('ssh2').ConnectConfig} [connectOptions]
109
+ * @property {string[]} [ignore]
110
+ * @property {boolean|string[]} [cleanRemoteFiles]
111
+ * @property {boolean} [securityLock]
112
+ * @property {boolean} [keepAlive]
113
+ * @property {boolean} [noWarn]
114
+ * @property {boolean} [skipPrompt]
115
+ * @property {{remotePath:string;connectOptions?:import('ssh2').ConnectConfig}[]} [targets]
116
+ * @param {Options} opts
117
+ */
118
+
119
+ async function sshSftp(opts) {
120
+ opts = parseOpts(opts)
121
+
122
+ const results = []
123
+ // 这里只返回第一个目标的结果,是为了兼容以前的代码
124
+ for (const target of opts.targets) {
125
+ results.push(await _sshSftp({ ...opts, ...target }))
126
+ }
127
+ return results[0]
128
+ }
129
+
130
+ /**
131
+ * @param {Options} opts
132
+ */
133
+ async function _sshSftp(opts) {
134
+ const { deployedURL, sftpURL } = getDeployURL(opts)
135
+
136
+ console.log('部署网址:', chalk.green(deployedURL))
137
+ const spinner = injectTiming(ora(`连接服务器 ${sftpURL}`)).start()
138
+ const sftp = new Client()
139
+ try {
140
+ await sftp.connect(opts.connectOptions)
141
+ spinner.succeed(`已连接 ${sftpURL}`)
142
+
143
+ if (!(await sftp.exists(opts.remotePath))) {
144
+ let confirm = false
145
+ if (opts.skipPrompt) {
146
+ confirm = true
147
+ } else {
148
+ const ans = await inquirer.prompt({
149
+ name: 'confirm',
150
+ message: `远程文件夹不存在,是否要创建一个`,
151
+ type: 'confirm',
152
+ })
153
+ confirm = ans.confirm
154
+ }
155
+
156
+ if (confirm) {
157
+ await sftp.mkdir(opts.remotePath, true)
158
+ } else {
159
+ process.exit()
160
+ }
161
+ }
162
+
163
+ let remoteDeletefiles = []
164
+ let localUploadFiles = []
165
+
166
+ spinner.start('对比本地/远程的文件数量')
167
+
168
+ localUploadFiles = getFilesPath(opts.localPath, opts.remotePath, opts.ignore || [])
169
+
170
+ spinner.succeed(`本地文件数量:${localUploadFiles.length}`)
171
+ if (opts.cleanRemoteFiles) {
172
+ remoteDeletefiles = await getRemoteDeepFiles(sftp, opts.remotePath, {
173
+ patterns: opts.cleanRemoteFiles === true ? [] : opts.cleanRemoteFiles,
174
+ })
175
+
176
+ spinner.succeed(`远程文件数量:${remoteDeletefiles.length}`)
177
+
178
+ const Confirm = {
179
+ delete: Symbol(),
180
+ skip: Symbol(),
181
+ stop: Symbol(),
182
+ showDeleteFile: Symbol(),
183
+ }
184
+ let confirm = Confirm.delete
185
+ if (remoteDeletefiles.length > localUploadFiles.length && !opts.skipPrompt) {
186
+ const showSelect = async () => {
187
+ const { confirm } = await inquirer.prompt({
188
+ name: 'confirm',
189
+ message: `远程需要删除的文件数(${remoteDeletefiles.length})比本地(${localUploadFiles.length})多,确定要删除吗?`,
190
+ type: 'list',
191
+ choices: [
192
+ { name: '删除', value: Confirm.delete },
193
+ { name: '不删除,继续部署', value: Confirm.skip },
194
+ { name: '中止部署', value: Confirm.stop },
195
+ { name: '显示需要删除的文件', value: Confirm.showDeleteFile },
196
+ ],
197
+ })
198
+ return confirm
199
+ }
200
+
201
+ do {
202
+ confirm = await showSelect()
203
+ if (confirm === Confirm.stop) {
204
+ process.exit()
205
+ }
206
+ if (confirm === Confirm.showDeleteFile) {
207
+ const diffFiles = ensureDiff(localUploadFiles, remoteDeletefiles)
208
+
209
+ diffFiles.forEach((o) => {
210
+ const path = o.isSame ? o.path : chalk.red(o.path)
211
+ console.log(` - ${path}`)
212
+ })
213
+ }
214
+ } while (confirm === Confirm.showDeleteFile)
215
+ }
216
+
217
+ if (confirm === Confirm.delete) {
218
+ spinner.start('开始删除远程文件')
219
+ remoteDeletefiles = mergeDelete(remoteDeletefiles)
220
+ await Promise.all(
221
+ remoteDeletefiles.map((o, i) =>
222
+ limit(async () => {
223
+ spinner.text = `[${i + 1}/${remoteDeletefiles.length}] 正在删除 ${o.path}`
224
+ try {
225
+ if (o.isDir) await sftp.rmdir(o.path, true)
226
+ else await sftp.delete(o.path)
227
+ } catch (e) {
228
+ console.error(`删除失败: ${o.path}`, e.message)
229
+ }
230
+ }),
231
+ ),
232
+ )
233
+ spinner.succeed(`已删除 ${opts.remotePath}`)
234
+ }
235
+ }
236
+
237
+ spinner.start(`开始上传 ${opts.localPath} 到 ${opts.remotePath}`)
238
+
239
+ if (Array.isArray(opts.ignore) && opts.ignore.length > 0) {
240
+ const dirs = localUploadFiles.filter((o) => fs.statSync(o.localPath).isDirectory())
241
+ const files = localUploadFiles.filter((o) => !fs.statSync(o.localPath).isDirectory())
242
+
243
+ // 先并发创建目录
244
+ await Promise.all(
245
+ dirs.map((o) =>
246
+ limit(async () => {
247
+ try {
248
+ if (!(await sftp.exists(o.remotePath))) {
249
+ await sftp.mkdir(o.remotePath)
250
+ }
251
+ } catch {}
252
+ }),
253
+ ),
254
+ )
255
+
256
+ // 再并发上传文件
257
+ await Promise.all(
258
+ files.map((o, i) =>
259
+ limit(async () => {
260
+ spinner.text = `[${i + 1}/${files.length}] 正在上传 ${o.localPath} 到 ${o.remotePath}`
261
+ await sftp.fastPut(o.localPath, o.remotePath)
262
+ }),
263
+ ),
264
+ )
265
+ } else {
266
+ await sftp.uploadDir(opts.localPath, opts.remotePath)
267
+ }
268
+ spinner.succeed(`已上传 ${opts.localPath} 到 ${opts.remotePath}`)
269
+
270
+ return { sftp, opts }
271
+ } catch (error) {
272
+ spinner.fail('异常中断')
273
+ if (error.message.includes('sftpConnect')) {
274
+ exitWithError(`登录失败,请检查 connectOptions 配置项\n原始信息:${error.message}`)
275
+ } else {
276
+ console.error(error)
277
+ }
278
+ } finally {
279
+ if (!opts.keepAlive) {
280
+ await sftp.end()
281
+ }
282
+ }
283
+ }
284
+
285
+ /**
286
+ * @param {Options} opts
287
+ * @param {{d:boolean,u:boolean,i:boolean}} lsOpts
288
+ */
289
+ async function sshSftpLS(opts, lsOpts) {
290
+ opts = parseOpts(opts)
291
+
292
+ for (const target of opts.targets) {
293
+ await _sshSftpLS({ ...opts, ...target }, lsOpts)
294
+ }
295
+ }
296
+
297
+ async function _sshSftpLS(opts, lsOpts) {
298
+ const sftp = new Client()
299
+ try {
300
+ await sftp.connect(opts.connectOptions)
301
+
302
+ if (lsOpts.d) {
303
+ if (opts.cleanRemoteFiles) {
304
+ const ls = await getRemoteDeepFiles(sftp, opts.remotePath, {
305
+ patterns: opts.cleanRemoteFiles === true ? [] : opts.cleanRemoteFiles,
306
+ })
307
+ console.log(`删除文件 ${opts.remotePath}(${ls.length}):`)
308
+ for (const o of ls) {
309
+ console.log(` - ${o.path}`)
310
+ }
311
+ }
312
+ }
313
+
314
+ if (lsOpts.i && Array.isArray(opts.ignore) && opts.ignore.length > 0) {
315
+ let ls = glob.sync(`${opts.localPath}/**/*`)
316
+ ls = ls.filter((s) =>
317
+ getSafePattern(opts.ignore, opts.localPath).some((reg) => minimatch(s, reg)),
318
+ )
319
+
320
+ console.log(`忽略文件 (${ls.length}):`)
321
+ for (const s of ls) {
322
+ console.log(` - ${s}`)
323
+ }
324
+ }
325
+
326
+ if (lsOpts.u) {
327
+ if (opts.ignore && opts.ignore.length > 0) {
328
+ const ls = getFilesPath(opts.localPath, opts.remotePath, opts.ignore)
329
+ console.log(`上传文件 (${ls.length}): `)
330
+ for (const o of ls) {
331
+ console.log(` + ${o.localPath}`)
332
+ }
333
+ } else {
334
+ console.log(`上传 ${opts.localPath} 全部文件到 ${opts.remotePath}`)
335
+ }
336
+ }
337
+ } catch (error) {
338
+ console.error(error)
339
+ } finally {
340
+ await sftp.end()
341
+ }
342
+ }
343
+
344
+ /**
345
+ * @param {{isDir:boolean;path:string}[]} files
346
+ */
347
+ function mergeDelete(files) {
348
+ let dirs = files.filter((o) => o.isDir)
349
+ dirs.forEach(({ path }) => {
350
+ files = files.filter((o) => !(o.path.startsWith(path) && path !== o.path))
351
+ })
352
+ return files
353
+ }
354
+
355
+ /**
356
+ * @param {string[]} patterns
357
+ * @param {string} prefixPath
358
+ */
359
+ function getSafePattern(patterns, prefixPath) {
360
+ const safePatterns = patterns
361
+ .map((s) => s.replace(/^[./]*/, prefixPath + '/'))
362
+ .reduce((acc, s) => [...acc, s, s + '/**/*'], [])
363
+ return safePatterns
364
+ }
365
+
366
+ /**
367
+ * @param {Options} opts
368
+ */
369
+ function parseOpts(opts) {
370
+ opts = Object.assign({}, defualtOpts, opts)
371
+
372
+ process.env.__SFTP_NO_WARN = opts.noWarn
373
+
374
+ const pkg = JSON.parse(fs.readFileSync(path.resolve('package.json'), 'utf-8'))
375
+ if (!pkg.name) {
376
+ exitWithError('package.json 中的 name 字段不能为空')
377
+ }
378
+ if (pkg.name.startsWith('@')) {
379
+ // 如果包含scope需要无视掉
380
+ pkg.name = pkg.name.replace(/@.*\//, '')
381
+ }
382
+
383
+ if (opts.preset && opts.preset.server) {
384
+ if (!servers[opts.preset.server]) exitWithError('未知的 preset.server')
385
+ const server = { ...servers[opts.preset.server] }
386
+ opts.connectOptions = server
387
+ }
388
+ if (opts.preset && opts.preset.context) {
389
+ if (!presets[opts.preset.context]) exitWithError('未知的 preset.context')
390
+ const preset = { ...presets[opts.preset.context] }
391
+
392
+ const folder = opts.preset.folder || pkg.name
393
+ preset.remotePath = path.join(preset.remotePath, folder)
394
+
395
+ opts = Object.assign({}, preset, opts)
396
+ }
397
+
398
+ if (!fs.existsSync(opts.localPath)) {
399
+ exitWithError(`localPath 配置错误,未找到需要上传的文件夹(${opts.localPath})`)
400
+ }
401
+
402
+ if (!fs.statSync(opts.localPath).isDirectory()) {
403
+ exitWithError('localPath 配置错误,必须是一个文件夹')
404
+ }
405
+
406
+ opts.connectOptions = {
407
+ ...opts.connectOptions,
408
+ readyTimeout: 2 * 60 * 1000,
409
+ }
410
+
411
+ opts.targets = opts.targets || []
412
+ if (opts.targets.length === 0 && !opts.remotePath) {
413
+ exitWithError('remotePath 或 targets 未配置')
414
+ }
415
+ if (opts.targets.length === 0) {
416
+ opts.targets.push({ remotePath: opts.remotePath, connectOptions: opts.connectOptions })
417
+ } else {
418
+ opts.targets.forEach((target) => {
419
+ target.connectOptions = target.connectOptions || opts.connectOptions
420
+ })
421
+ }
422
+
423
+ if (opts.targets.length > 1 && opts.keepAlive) {
424
+ exitWithError('keepAlive 选项在多目标上传时不支持,请设置为 false')
425
+ }
426
+
427
+ if (typeof opts.securityLock !== 'boolean') {
428
+ opts.securityLock = true
429
+ }
430
+
431
+ if (opts.securityLock === false) {
432
+ warn('请确保自己清楚关闭安全锁(securityLock)后的风险')
433
+ } else {
434
+ for (const target of opts.targets) {
435
+ if (!target.remotePath.includes(pkg.name)) {
436
+ exitWithError(
437
+ [
438
+ `remotePath 中不包含项目名称`,
439
+ `为防止错误上传/删除和保证服务器目录可读性,你必须让remotePath中包含你的项目名称`,
440
+ `remotePath:${target.remotePath}`,
441
+ `项目名称:${pkg.name} // 源自 package.json 中的 name 字段,忽略scope字段`,
442
+ `\n你可以设置 "securityLock": false 来关闭这个验证`,
443
+ ].join('\n'),
444
+ )
445
+ }
446
+ }
447
+ }
448
+
449
+ if (opts.ignore) {
450
+ opts.ignore = [opts.ignore].flat(1).filter(Boolean)
451
+ }
452
+
453
+ if (opts.cleanRemoteFiles === true) {
454
+ opts.cleanRemoteFiles = []
455
+ }
456
+
457
+ if (opts.cleanRemoteFiles) {
458
+ opts.cleanRemoteFiles = [opts.cleanRemoteFiles].flat(1).filter(Boolean)
459
+ }
460
+
461
+ return opts
462
+ }
463
+
464
+ function getDeployURL(target) {
465
+ const _r = target.connectOptions
466
+ const sftpURL = `sftp://${_r.username}:${_r.password}@${_r.host}:${_r.port}/${target.remotePath}`
467
+
468
+ let deployedURL = '未知'
469
+ for (const context in presets) {
470
+ const preset = presets[context]
471
+ if (!target.remotePath.startsWith(preset.remotePath)) continue
472
+
473
+ const fullPath = target.remotePath.replace(preset.remotePath, '').slice(1)
474
+
475
+ deployedURL = ['http://www.zhidianbao.cn:8088', context, fullPath, ''].join('/')
476
+ break
477
+ }
478
+
479
+ return { sftpURL, deployedURL }
480
+ }
481
+
482
+ /**
483
+ * @param {Options} opts
484
+ */
485
+ function sshSftpShowUrl(opts) {
486
+ opts = parseOpts(opts)
487
+
488
+ for (const target of opts.targets) {
489
+ const { deployedURL } = getDeployURL(target)
490
+ console.log('部署网址:', chalk.green(deployedURL))
491
+ }
492
+ }
493
+
494
+ function sshSftpShowConfig(opts) {
495
+ opts = parseOpts(opts)
496
+
497
+ console.log(JSON.stringify(opts, null, 2))
498
+
499
+ sshSftpShowUrl(opts)
500
+ sshSftpLS(opts, { u: true, d: true, i: true })
501
+ }
502
+
503
+ export default sshSftp
504
+ export { sshSftp, sshSftpLS, sshSftpShowUrl, sshSftpShowConfig, parseOpts, Client }
@@ -1,34 +1,31 @@
1
- "use strict";
2
-
3
1
  const servers = {
4
2
  19: {
5
3
  host: '192.168.10.19',
6
4
  port: 22,
7
5
  username: 'root',
8
- password: 'eduweb19@'
6
+ password: 'eduweb19@',
9
7
  },
10
8
  171: {
11
9
  host: '192.168.10.171',
12
10
  port: 22,
13
11
  username: 'root',
14
- password: 'qsweb1@'
15
- }
16
- };
12
+ password: 'qsweb1@',
13
+ },
14
+ }
15
+
17
16
  const presets = {
18
17
  qsxxwapdev: {
19
18
  remotePath: '/erp/edumaven/edu-page-v1',
20
- connectOptions: servers[19]
19
+ connectOptions: servers[19],
21
20
  },
22
21
  eduwebngv1: {
23
22
  remotePath: '/erp/edumaven/edu-web-page-v1',
24
- connectOptions: servers[19]
23
+ connectOptions: servers[19],
25
24
  },
26
25
  qsxxadminv1: {
27
26
  remotePath: '/erp/edumaven/edu-admin-page-dev',
28
- connectOptions: servers[19]
29
- }
30
- };
31
- module.exports = {
32
- presets,
33
- servers
34
- };
27
+ connectOptions: servers[19],
28
+ },
29
+ }
30
+
31
+ export { presets, servers }
package/src/utils.js ADDED
@@ -0,0 +1,57 @@
1
+ import chalk from 'chalk'
2
+
3
+ /**
4
+ * @param {string} message
5
+ * @return {never}
6
+ */
7
+ function exitWithError(message) {
8
+ console.log(`${chalk.bgRed.white.bold(' ERROR ')} ${chalk.redBright(message)}`)
9
+ process.exit()
10
+ }
11
+
12
+ function warn(message) {
13
+ if (process.env.__SFTP_NO_WARN) return
14
+ console.log(`${chalk.bgYellow.white.bold(' WARN ')} ${chalk.yellow.bold(message)}`)
15
+ }
16
+
17
+ function splitOnFirst(string, separator) {
18
+ if (!(typeof string === 'string' && typeof separator === 'string')) {
19
+ throw new TypeError('Expected the arguments to be of type `string`')
20
+ }
21
+
22
+ if (string === '' || separator === '') {
23
+ return []
24
+ }
25
+
26
+ const separatorIndex = string.indexOf(separator)
27
+
28
+ if (separatorIndex === -1) {
29
+ return []
30
+ }
31
+
32
+ return [string.slice(0, separatorIndex), string.slice(separatorIndex + separator.length)]
33
+ }
34
+
35
+ /**
36
+ *
37
+ * @param {import('ora').Ora} ora
38
+ */
39
+ function injectTiming(ora) {
40
+ const oldStart = ora.start
41
+
42
+ let current = 0
43
+ ora.start = (message) => {
44
+ current = performance.now()
45
+ return oldStart.call(ora, message)
46
+ }
47
+ const oldSucceed = ora.succeed
48
+ ora.succeed = (message) => {
49
+ const now = performance.now()
50
+ const diff = (now - current) / 1000
51
+ return oldSucceed.call(ora, `${message} ${chalk.dim(`(${diff.toFixed(2)}s)`)}`)
52
+ }
53
+
54
+ return ora
55
+ }
56
+
57
+ export { splitOnFirst, exitWithError, warn, injectTiming }
package/lib/cli.js DELETED
@@ -1,103 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
-
4
- const {
5
- sshSftp,
6
- sshSftpLS,
7
- sshSftpShowUrl,
8
- sshSftpShowConfig
9
- } = require('./index');
10
- const fs = require('fs');
11
- const ora = require('ora');
12
- const {
13
- exitWithError
14
- } = require('./utils');
15
- const updateNotifier = require('update-notifier');
16
- const pkg = require('../package.json');
17
- const presets = require('./presets');
18
- updateNotifier({
19
- pkg,
20
- updateCheckInterval: 1000 * 60 * 60 * 24 * 7,
21
- shouldNotifyInNpmScript: true
22
- }).notify();
23
- require('yargs').usage('使用: $0 [command] \n\n代码:svn://192.168.10.168/edu/code/A0.New-system/0A2.front-end-component/ssh-sftp/trunk').command('*', '上传文件', yargs => yargs.option('no-clear', {
24
- desc: '不删除文件'
25
- }).option('yes', {
26
- alias: 'y',
27
- desc: '不存在的目录不再询问,直接创建',
28
- type: 'boolean'
29
- }), upload).command('init', '生成 .sftprc.json 配置文件', {}, generateDefaultConfigJSON).command(['list', 'ls'], '列出所有需要上传/忽略/删除的文件', yargs => yargs.option('u', {
30
- desc: '列出需要上传的文件'
31
- }).option('d', {
32
- desc: '列出需要删除的文件'
33
- }).option('i', {
34
- desc: '列出忽略的文件'
35
- }), ls).command(['show-config', 'sc'], '显示部署的完整信息', {}, showConfig).command(['show-presets', 'sp'], '显示预设配置', {}, showPresets).command(['show-url', 'su'], '显示部署网址', {}, showUrl).alias({
36
- v: 'version',
37
- h: 'help'
38
- }).argv;
39
- function getOpts() {
40
- isRoot();
41
- if (!fs.existsSync('.sftprc.json')) {
42
- return exitWithError('没找到 .sftprc.json 文件,请先执行 ssh-sftp init');
43
- }
44
- const opts = fs.readFileSync('.sftprc.json', 'utf-8');
45
- return JSON.parse(opts);
46
- }
47
- function isRoot() {
48
- if (!fs.existsSync('package.json')) {
49
- exitWithError('请在项目的根目录运行(package.json所在的目录)');
50
- }
51
- }
52
- function upload({
53
- clear,
54
- yes
55
- }) {
56
- const opts = getOpts();
57
- if (clear === false) {
58
- opts.cleanRemoteFiles = false;
59
- }
60
- if (yes) {
61
- opts.skipPrompt = true;
62
- }
63
- sshSftp(opts);
64
- }
65
- function generateDefaultConfigJSON() {
66
- isRoot();
67
- if (fs.existsSync('.sftprc.json')) {
68
- return exitWithError('已存在 .sftprc.json 文件,请勿重复生成');
69
- }
70
- fs.writeFileSync('.sftprc.json', JSON.stringify({
71
- $schema: 'http://www.zhidianbao.cn:8088/qsxxwapdev/edu-ssh-sftp/sftprc.schema.json',
72
- localPath: '/path/to/localDir',
73
- remotePath: '/path/to/remoteDir',
74
- connectOptions: {
75
- host: '127.0.0.1',
76
- port: 22,
77
- username: '',
78
- password: ''
79
- },
80
- ignore: ['**/something[optional].js'],
81
- cleanRemoteFiles: false
82
- }, null, 2), {
83
- encoding: 'utf-8'
84
- });
85
- ora().succeed('.sftprc.json 生成在项目根目录');
86
- }
87
- function ls(argv) {
88
- if (!argv.u && !argv.d && !argv.i) {
89
- argv.u = true;
90
- argv.d = true;
91
- argv.i = true;
92
- }
93
- sshSftpLS(getOpts(), argv);
94
- }
95
- function showUrl() {
96
- sshSftpShowUrl(getOpts());
97
- }
98
- function showConfig() {
99
- sshSftpShowConfig(getOpts());
100
- }
101
- function showPresets() {
102
- console.log(JSON.stringify(presets, null, 2));
103
- }