1 | const path = require('path')
|
2 | const fs = require('fs-extra')
|
3 | const chalk = require('chalk')
|
4 | const spawn = require('cross-spawn')
|
5 | const spinner = require('./spinner')
|
6 | const logger = require('./logger')
|
7 | const SherryError = require('./SherryError')
|
8 |
|
9 | module.exports = class GeneratorContext {
|
10 | constructor(sherry, generator) {
|
11 | this.sherry = sherry
|
12 | this.generator = generator
|
13 | this.spinner = spinner
|
14 | this.chalk = chalk
|
15 | this.logger = logger
|
16 | this.fs = fs
|
17 | }
|
18 |
|
19 | set data(data) {
|
20 | this._data = data
|
21 | }
|
22 |
|
23 | get data() {
|
24 | return this._data
|
25 | }
|
26 |
|
27 | get pkg() {
|
28 | try {
|
29 | return require(path.join(this.outDir, 'package.json'))
|
30 | } catch (err) {
|
31 | return {}
|
32 | }
|
33 | }
|
34 |
|
35 | get answers() {
|
36 | return this._answers
|
37 | }
|
38 |
|
39 | get gitUser() {
|
40 | return require('./gitInfo')(this.sherry.opts.mock)
|
41 | }
|
42 |
|
43 | get outFolder() {
|
44 | return path.basename(this.sherry.opts.outDir)
|
45 | }
|
46 |
|
47 | get outDir() {
|
48 | return this.sherry.opts.outDir
|
49 | }
|
50 |
|
51 | get npmClient() {
|
52 | return this.sherry.opts.npmClient
|
53 | }
|
54 |
|
55 | gitInit() {
|
56 | const ps = spawn.sync('git', ['init'], {
|
57 | stdio: 'ignore',
|
58 | cwd: this.outDir
|
59 | })
|
60 | if (ps.status === 0) {
|
61 | logger.success('Initialized empty Git repository')
|
62 | } else {
|
63 | logger.debug(`git init failed in ${this.outDir}`)
|
64 | }
|
65 | }
|
66 |
|
67 | npmInstall(opts) {
|
68 | return require('./installPackages')(
|
69 | Object.assign(
|
70 | {
|
71 | registry: this.sherry.opts.registry,
|
72 | cwd: this.outDir
|
73 | },
|
74 | opts
|
75 | )
|
76 | )
|
77 | }
|
78 |
|
79 | showProjectTips() {
|
80 | spinner.stop()
|
81 | logger.success(`Generated into ${chalk.underline(this.outDir)}`)
|
82 | }
|
83 |
|
84 | createError(message) {
|
85 | return new SherryError(message)
|
86 | }
|
87 |
|
88 | getCustomContext(key) {
|
89 | return this._customContext && this._customContext[key]
|
90 | }
|
91 | }
|