1 | #!/usr/bin/env node
|
2 |
|
3 | "use strict";
|
4 |
|
5 | var program = require('commander')
|
6 | var semver = require('semver')
|
7 | var fs = require('fs.extra')
|
8 | var zlib = require('zlib')
|
9 | var tar = require('tar')
|
10 | var path = require('path')
|
11 | var debug = require('debug')('mosaic')
|
12 | var mosaic = require('../lib/mosaic')
|
13 |
|
14 |
|
15 | program
|
16 | .usage('[options] :family/:name/:version')
|
17 | .option('--keep -k', 'Keep package.tgz')
|
18 |
|
19 | program.on('--help', function() {
|
20 | console.log(' Examples')
|
21 | console.log('')
|
22 | console.log(' $ mo install mosaics/pagination/1.0.0')
|
23 | console.log(' $ mo install mosaics/pagination')
|
24 | console.log('')
|
25 | })
|
26 |
|
27 | program.parse(process.argv)
|
28 |
|
29 |
|
30 | var MOPATH_PATTERN = /([^\/]+)\/([^\/]+)\/((?:\d+\.){2}\d+)$/
|
31 |
|
32 | var mopath = program.args[0] || ''
|
33 | var parts = mopath.match(MOPATH_PATTERN)
|
34 |
|
35 | if (!mopath || !parts) {
|
36 | process.stdout.write(program.helpInformation())
|
37 | program.emit('--help')
|
38 | process.exit()
|
39 | }
|
40 |
|
41 | var family = parts[1]
|
42 | var name = parts[2]
|
43 | var version = parts[3]
|
44 |
|
45 | if (fs.existsSync(mopath)) {
|
46 | var question = "Mosaic exists, reinstall? (y/n): "
|
47 | var handler = function(ok) {
|
48 | if (ok) {
|
49 | install(mopath, 'Mosaic reinstalled!')
|
50 | }
|
51 | else {
|
52 | process.exit(0)
|
53 | }
|
54 | }
|
55 |
|
56 | program.confirm(question, handler)
|
57 | }
|
58 | else if (family && name && version && semver.valid(version)) {
|
59 | install(mopath, 'Mosaic installed!')
|
60 | }
|
61 |
|
62 | function install(fpath, msg){
|
63 | var req = mosaic.agent().get(mosaic.remote(fpath + '.tgz'), function(res) {
|
64 | if (res.statusCode === 404) {
|
65 | mosaic.fatal(404)
|
66 | mosaic.fatal(res.text)
|
67 | }
|
68 | else if (res.statusCode === 200 && res.text && res.text.indexOf('统一登录中心') >= 0) {
|
69 | res.req.url = req.url
|
70 | mosaic.login(res).done(function() {
|
71 | install(fpath, msg)
|
72 | })
|
73 | }
|
74 | else {
|
75 | debug('mkdir ' + fpath)
|
76 | fs.mkdirp(fpath)
|
77 |
|
78 | debug('extract ' + fpath)
|
79 | res
|
80 | .pipe(zlib.Gunzip())
|
81 | .pipe(tar.Extract({ path: fpath, strip: 1 }))
|
82 | .on('end', function() {
|
83 | if (!program.keep) {
|
84 | var pkg = path.join(fpath, 'package.tgz')
|
85 | debug('remove ' + pkg)
|
86 | fs.unlinkSync(pkg)
|
87 | }
|
88 | mosaic.log('success', msg)
|
89 | process.exit(0)
|
90 | })
|
91 | }
|
92 | }, true)
|
93 | }
|
94 |
|
95 |
|