forked from near/create-near-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·208 lines (181 loc) · 7.08 KB
/
index.js
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
#!/usr/bin/env node
const yargs = require('yargs')
const { basename, resolve } = require('path')
const replaceInFiles = require('replace-in-files')
const ncp = require('ncp').ncp
ncp.limit = 16
const fs = require('fs')
const spawn = require('cross-spawn')
const chalk = require('chalk')
const which = require('which')
const sh = require('shelljs')
const path = require('path')
const rustSetup = require('./utils/rust-setup')
const mixpanel =require('./utils/tracking')
const renameFile = async function(oldPath, newPath) {
return new Promise((resolve, reject) => {
fs.rename(oldPath, newPath, (err) => {
if (err) {
console.error(err)
return reject(err)
}
console.log(`Renamed ${oldPath} to ${newPath}`)
resolve()
})
})
}
// Wrap `ncp` tool to wait for the copy to finish when using `await`
// Allow passing `skip` variable to skip copying an array of filenames
function copyDir (source, dest, { skip, veryVerbose } = {}) {
return new Promise((resolve, reject) => {
const copied = []
const skipped = []
const filter = skip && function (filename) {
const shouldCopy = !skip.find(f => filename.includes(f))
shouldCopy ? copied.push(filename) : skipped.push(filename)
return !skip.find(f => filename.includes(f))
}
ncp(source, dest, { filter }, (err) => {
if (err) return reject(err)
if (veryVerbose) {
console.log('Copied:')
copied.forEach(f => console.log(' ' + f))
console.log('Skipped:')
skipped.forEach(f => console.log(' ' + f))
}
resolve()
})
})
}
const createProject = async function({ contract, frontend, projectDir, veryVerbose }) {
if (frontend === 'angular') {
console.log(chalk`{yellow Angular frontend is deprecated. You can choose vanilla, react or vue.}`)
}
const templateDir = `/templates/${frontend}`
const sourceTemplateDir = __dirname + templateDir
mixpanel.track(frontend, contract)
console.log(`Copying files to new project directory (${projectDir}) from template source (${sourceTemplateDir}).`)
await copyDir(sourceTemplateDir, projectDir, { veryVerbose, skip: [
// our frontend templates are set up with symlinks for easy development,
// developing right in these directories also results in build artifacts;
// we don't want to copy these
path.join(sourceTemplateDir, '.cache'),
path.join(sourceTemplateDir, 'dist'),
path.join(sourceTemplateDir, 'out'),
path.join(sourceTemplateDir, 'node_modules'),
path.join(sourceTemplateDir, 'yarn.lock'),
path.join(sourceTemplateDir, 'package-lock.json'),
path.join(sourceTemplateDir, 'contract'),
...sh.ls(`${__dirname}/common/frontend`).map(f => path.join('src', f))
]})
// copy common files
await copyDir(`${__dirname}/common/frontend`, `${projectDir}/src`)
const contractSourceDir = `${__dirname}/common/contracts/${contract}`
await copyDir(contractSourceDir, `${projectDir}/contract`, { veryVerbose, skip: [
// as above, skip rapid-development build artifacts
path.join(contractSourceDir, 'node_modules'),
path.join(contractSourceDir, 'yarn.lock'),
path.join(contractSourceDir, 'package-lock.json'),
]})
// update package name
let projectName = basename(resolve(projectDir))
await replaceInFiles({
files: [
// NOTE: These can use globs if necessary later
`${projectDir}/README.md`,
`${projectDir}/package.json`,
`${projectDir}/contract/README.md`,
`${projectDir}/src/config.js`,
`${projectDir}/src/App.vue`,
`${projectDir}/angular.json`,
`${projectDir}/karma.conf.js`,
`${projectDir}/set-contract-name.js`,
],
from: /near-blank-project/g,
to: projectName
})
if (contract === 'rust') {
await replaceInFiles({ files: `${projectDir}/src/**/*`, from: /getGreeting/g, to: 'get_greeting' })
await replaceInFiles({ files: `${projectDir}/src/**/*`, from: /setGreeting/g, to: 'set_greeting' })
await replaceInFiles({ files: `${projectDir}/src/**/*`, from: /{ accountId:/g, to: '{ account_id:' })
await replaceInFiles({ files: `${projectDir}/package.json`, from: 'cd contract && npm run test', to: 'cd contract && cargo test -- --nocapture' })
await replaceInFiles({ files: `${projectDir}/package.json`, from: 'watch contract -e ts', to: 'watch contract/src -e rs' })
}
await renameFile(`${projectDir}/near.gitignore`, `${projectDir}/.gitignore`)
console.log('Copying project files complete.\n')
const hasNpm = which.sync('npm', { nothrow: true })
const hasYarn = which.sync('yarn', { nothrow: true })
//console.log('hasYarn:' + hasYarn + ' hasNmp:' + hasNpm)
if (hasYarn) {
await replaceInFiles({ files: `${projectDir}/README.md`, from: /npm\b( run)?/g, to: 'yarn' })
}
// setup rust
let wasRustupInstalled = false
if (contract === 'rust') {
wasRustupInstalled = await rustSetup.setupRustAndWasm32Target()
}
if (hasNpm || hasYarn) {
console.log('Installing project dependencies...')
spawn.sync(hasYarn ? 'yarn' : 'npm', ['install'], { cwd: projectDir, stdio: 'inherit' })
if (contract === 'assemblyscript') {
spawn.sync('npm', ['install', '--legacy-peer-deps'], { cwd: `${projectDir}/contract`, stdio: 'inherit' })
}
}
const runCommand = hasYarn ? 'yarn' : 'npm run'
console.log(chalk`
Success! Created ${projectDir}
Inside that directory, you can run several commands:
{bold ${runCommand} dev}
Starts the development server. Both contract and client-side code will
auto-reload once you change source files.
{bold ${runCommand} test}
Starts the test runner.
{bold ${runCommand} deploy}
Deploys contract in permanent location (as configured in {bold src/config.js}).
Also deploys web frontend using GitHub Pages.
Consult with {bold README.md} for details on how to deploy and {bold package.json} for full list of commands.
We suggest that you begin by typing:`)
if (wasRustupInstalled) {
console.log(chalk`
{bold source $HOME/.cargo/env}
{bold cd ${projectDir}}
{bold ${runCommand} dev}`)
} else {
console.log(chalk`
{bold cd ${projectDir}}
{bold ${runCommand} dev}`)
}
console.log(chalk`
Happy hacking!`)
}
const opts = yargs
.strict()
.usage('$0 <projectDir>', 'Create a new NEAR project')
// BUG: does not work; https://github.com/yargs/yargs/issues/1331
.example('$0 new-app', 'Create a project called "new-app"')
.option('frontend', {
desc: 'template to use',
choices: ['vanilla', 'react', 'vue', 'angular'],
default: 'vanilla',
})
.option('contract', {
desc: 'language for smart contract',
choices: ['assemblyscript', 'rust'],
default: 'assemblyscript'
})
.option('very-verbose', {
desc: 'turn on very verbose logging',
type: 'boolean',
default: false,
hidden: true,
})
.help()
.argv
createProject(opts).catch(e => {
// work around silly node error:
// (node:56892) [DEP0018] DeprecationWarning: Unhandled promise rejections
// are deprecated. In the future, promise rejections that are not handled
// will terminate the Node.js process with a non-zero exit code.
console.error('Error:', e)
process.exit(1)
})