UNPKG

3.1 kBJavaScriptView Raw
1const Command = require('../base')
2const { flags } = require('@oclif/command')
3const renderShortDesc = require('../utils/renderShortDescription')
4const path = require('path')
5const chalk = require('chalk')
6const linkPrompt = require('../utils/link/link-by-prompt')
7const { track } = require('../utils/telemetry')
8
9class LinkCommand extends Command {
10 async run() {
11 await this.authenticate()
12
13 const { flags } = this.parse(LinkCommand)
14 const { api, site, state } = this.netlify
15 const siteId = site.get('siteId')
16
17 let siteData
18 try {
19 siteData = await api.getSite({ siteId })
20 } catch (e) {
21 // silent api error
22 }
23
24 // Site id is incorrect
25 if (siteId && !siteData) {
26 console.log(`No site "${siteId}" found in your netlify account.`)
27 console.log(`Please double check your siteID and which account you are logged into via \`netlify status\`.`)
28 return this.exit()
29 }
30
31 // If already linked to site. exit and prompt for unlink
32 if (siteData) {
33 this.log(`Site already linked to "${siteData.name}"`)
34 this.log(`Admin url: ${siteData.admin_url}`)
35 this.log()
36 this.log(`To unlink this site, run: ${chalk.cyanBright('netlify unlink')}`)
37 return this.exit()
38 }
39
40 if (flags.id) {
41 try {
42 siteData = await api.getSite({ site_id: flags.id })
43 } catch (e) {
44 if (e.status === 404) {
45 this.error(new Error(`Site id ${flags.id} not found`))
46 } else {
47 this.error(e)
48 }
49 }
50
51 // Save site ID
52 state.set('siteId', siteData.id)
53 this.log(`Linked to ${siteData.name} in ${state.path}`)
54
55 await track('sites_linked', {
56 siteId: siteData.id,
57 linkType: 'manual',
58 kind: 'byId'
59 })
60
61 return this.exit()
62 }
63
64 if (flags.name) {
65 let results
66 try {
67 results = await api.listSites({
68 name: flags.name,
69 filter: 'all'
70 })
71 } catch (e) {
72 if (e.status === 404) {
73 this.error(new Error(`${flags.name} not found`))
74 } else {
75 this.error(e)
76 }
77 }
78
79 if (results.length === 0) {
80 this.error(new Error(`No sites found named ${flags.name}`))
81 }
82 siteData = results[0]
83 state.set('siteId', siteData.id)
84 this.log(`Linked to ${siteData.name} in ${path.relative(path.join(process.cwd(), '..'), state.path)}`)
85
86 await track('sites_linked', {
87 siteId: siteData && siteData.id || siteId,
88 linkType: 'manual',
89 kind: 'byName'
90 })
91
92 return this.exit()
93 }
94
95 siteData = await linkPrompt(this)
96 return siteData
97 }
98}
99
100LinkCommand.description = `${renderShortDesc('Link a local repo or project folder to an existing site on Netlify')}`
101
102LinkCommand.examples = [
103 'netlify link',
104 'netlify link --id 123-123-123-123',
105 'netlify link --name my-site-name'
106]
107
108LinkCommand.flags = {
109 id: flags.string({
110 description: 'ID of site to link to'
111 }),
112 name: flags.string({
113 description: 'Name of site to link to'
114 })
115}
116
117module.exports = LinkCommand