forked from netlify/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.js
More file actions
314 lines (276 loc) · 8.79 KB
/
Copy pathcommand.js
File metadata and controls
314 lines (276 loc) · 8.79 KB
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
const process = require('process')
const { URL } = require('url')
const { format, inspect } = require('util')
const resolveConfig = require('@netlify/config')
const { Command, flags: flagsLib } = require('@oclif/command')
const oclifParser = require('@oclif/parser')
const merge = require('lodash/merge')
const argv = require('minimist')(process.argv.slice(2))
const API = require('netlify')
const semverLessThan = require('semver/functions/lt')
const { getAgent } = require('../lib/http-agent')
const chalkInstance = require('./chalk')
const globalConfig = require('./global-config')
const { NETLIFYDEVWARN } = require('./logo')
const openBrowser = require('./open-browser')
const StateConfig = require('./state-config')
const { track, identify } = require('./telemetry')
const { NETLIFY_AUTH_TOKEN, NETLIFY_API_URL } = process.env
// Netlify CLI client id. Lives in bot@netlify.com
// Todo setup client for multiple environments
const CLIENT_ID = 'd6f37de6614df7ae58664cfca524744d73807a377f5ee71f1a254f78412e3750'
// 'api' command uses JSON output by default
// 'functions:invoke' need to return the data from the function as is
const isDefaultJson = () => argv._[0] === 'functions:invoke' || (argv._[0] === 'api' && argv.list !== true)
const warnOnOldNodeVersion = ({ log, chalk }) => {
if (semverLessThan(process.version, '10.0.0')) {
log(
`${NETLIFYDEVWARN} ${chalk.bold('Netlify CLI')} will require ${chalk.magenta.bold(
'Node.js 10',
)} or greater soon. Please update your Node.js version.`,
)
}
}
const getToken = (tokenFromFlag) => {
// 1. First honor command flag --auth
if (tokenFromFlag) {
return [tokenFromFlag, 'flag']
}
// 2. then Check ENV var
if (NETLIFY_AUTH_TOKEN && NETLIFY_AUTH_TOKEN !== 'null') {
return [NETLIFY_AUTH_TOKEN, 'env']
}
// 3. If no env var use global user setting
const userId = globalConfig.get('userId')
const tokenFromConfig = globalConfig.get(`users.${userId}.auth.token`)
if (tokenFromConfig) {
return [tokenFromConfig, 'config']
}
return [null, 'not found']
}
class BaseCommand extends Command {
// Initialize context
async init() {
const cwd = argv.cwd || process.cwd()
// Grab netlify API token
const authViaFlag = getAuthArg(argv)
const [token] = this.getConfigToken(authViaFlag)
// Get site id & build state
const state = new StateConfig(cwd)
const cachedConfig = await this.getConfig(cwd, state, token)
const { configPath, config, buildDir, siteInfo } = cachedConfig
const { flags } = this.parse(BaseCommand)
const agent = await getAgent({
log: this.log,
exit: this.exit,
httpProxy: flags.httpProxy,
certificateFile: flags.httpProxyCertificateFilename,
})
const apiOpts = { agent }
if (NETLIFY_API_URL) {
const apiUrl = new URL(NETLIFY_API_URL)
apiOpts.scheme = apiUrl.protocol.slice(0, -1)
apiOpts.host = apiUrl.host
apiOpts.pathPrefix = NETLIFY_API_URL === `${apiUrl.protocol}//${apiUrl.host}` ? '/api/v1' : apiUrl.pathname
}
this.netlify = {
// api methods
api: new API(token || '', apiOpts),
// current site context
site: {
root: buildDir,
configPath,
get id() {
return state.get('siteId')
},
set id(id) {
state.set('siteId', id)
},
},
// Site information retrieved using the API
siteInfo,
// Configuration from netlify.[toml/yml]
config,
// Used to avoid calling @neltify/config again
cachedConfig,
// global cli config
globalConfig,
// state of current site dir
state,
}
warnOnOldNodeVersion({ log: this.log, chalk: this.chalk })
}
// Find and resolve the Netlify configuration
async getConfig(cwd, state, token) {
try {
return await resolveConfig({
config: argv.config,
cwd,
context: argv.context,
debug: argv.debug,
siteId: argv.siteId || (typeof argv.site === 'string' && argv.site) || state.get('siteId'),
token,
mode: 'cli',
})
} catch (error) {
const message = error.type === 'userError' ? error.message : error.stack
console.error(message)
this.exit(1)
}
}
async isLoggedIn() {
try {
await this.netlify.api.getCurrentUser()
return true
} catch (_) {
return false
}
}
logJson(message = '') {
if (argv.json || isDefaultJson()) {
process.stdout.write(JSON.stringify(message, null, 2))
}
}
log(message = '', ...args) {
/* If --silent or --json flag passed disable logger */
if (argv.silent || argv.json || isDefaultJson()) {
return
}
message = typeof message === 'string' ? message : inspect(message)
process.stdout.write(`${format(message, ...args)}\n`)
}
/* Modified flag parser to support global --auth, --json, & --silent flags */
parse(opts, args = this.argv) {
/* Set flags object for commands without flags */
if (!opts.flags) {
opts.flags = {}
}
/* enrich parse with global flags */
const globalFlags = {}
if (!opts.flags.silent) {
globalFlags.silent = {
parse: (value) => value,
description: 'Silence CLI output',
allowNo: false,
type: 'boolean',
}
}
if (!opts.flags.json) {
globalFlags.json = {
parse: (value) => value,
description: 'Output return values as JSON',
allowNo: false,
type: 'boolean',
}
}
if (!opts.flags.auth) {
globalFlags.auth = {
parse: (value) => value,
description: 'Netlify auth token',
input: [],
multiple: false,
type: 'option',
}
}
// enrich with flags here
opts.flags = { ...opts.flags, ...globalFlags }
return oclifParser.parse(args, {
context: this,
...opts,
})
}
get chalk() {
// If --json flag disable chalk colors
return chalkInstance(argv.json)
}
/**
* Get user netlify API token
* @param {string} - [tokenFromFlag] - value passed in by CLI flag
* @return {[string, string]} - tokenValue & location of resolved Netlify API token
*/
getConfigToken(tokenFromFlag) {
return getToken(tokenFromFlag)
}
authenticate(tokenFromFlag) {
const [token] = this.getConfigToken(tokenFromFlag)
if (token) {
return token
}
return this.expensivelyAuthenticate()
}
async expensivelyAuthenticate() {
const webUI = process.env.NETLIFY_WEB_UI || 'https://app.netlify.com'
this.log(`Logging into your Netlify account...`)
// Create ticket for auth
const ticket = await this.netlify.api.createTicket({
clientId: CLIENT_ID,
})
// Open browser for authentication
const authLink = `${webUI}/authorize?response_type=ticket&ticket=${ticket.id}`
this.log(`Opening ${authLink}`)
await openBrowser({ url: authLink, log: this.log })
const accessToken = await this.netlify.api.getAccessToken(ticket)
if (!accessToken) {
this.error('Could not retrieve access token')
}
const user = await this.netlify.api.getCurrentUser()
const userID = user.id
const userData = merge(this.netlify.globalConfig.get(`users.${userID}`), {
id: userID,
name: user.full_name,
email: user.email,
auth: {
token: accessToken,
github: {
user: undefined,
token: undefined,
},
},
})
// Set current userId
this.netlify.globalConfig.set('userId', userID)
// Set user data
this.netlify.globalConfig.set(`users.${userID}`, userData)
const { email } = user
await identify({
name: user.full_name,
email,
}).then(() =>
track('user_login', {
email,
}),
)
// Log success
this.log()
this.log(`${this.chalk.greenBright('You are now logged into your Netlify account!')}`)
this.log()
this.log(`Run ${this.chalk.cyanBright('netlify status')} for account details`)
this.log()
this.log(`To see all available commands run: ${this.chalk.cyanBright('netlify help')}`)
this.log()
return accessToken
}
}
const getAuthArg = function (cliArgs) {
// If deploy command. Support shorthand 'a' flag
if (cliArgs && cliArgs._ && cliArgs._[0] === 'deploy') {
return cliArgs.auth || cliArgs.a
}
return cliArgs.auth
}
BaseCommand.strict = false
BaseCommand.flags = {
debug: flagsLib.boolean({
description: 'Print debugging information',
}),
httpProxy: flagsLib.string({
description: 'Proxy server address to route requests through.',
default: process.env.HTTP_PROXY || process.env.HTTPS_PROXY,
}),
httpProxyCertificateFilename: flagsLib.string({
description: 'Certificate file to use when connecting using a proxy server',
default: process.env.NETLIFY_PROXY_CERTIFICATE_FILENAME,
}),
}
BaseCommand.getToken = getToken
module.exports = BaseCommand