-
Notifications
You must be signed in to change notification settings - Fork 253
/
action.ts
168 lines (150 loc) · 5.54 KB
/
action.ts
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
import { Command, flags } from '@oclif/command'
import chalk from 'chalk'
import fs from 'fs-extra'
import globby from 'globby'
import { camelCase, startCase } from 'lodash'
import toTitleCase from 'to-title-case'
import ora from 'ora'
import path from 'path'
import { autoPrompt } from '../../lib/prompt'
import { renderTemplates } from '../../lib/templates'
import { addKeyToExport } from '../../lib/codemods'
import GenerateTypes from './types'
export default class GenerateAction extends Command {
private spinner: ora.Ora = ora()
static description = `Scaffolds a new integration action.`
static examples = [
`$ ./bin/run generate:action ACTION <browser|server>`,
`$ ./bin/run generate:action postToChannel server --directory=./destinations/slack`
]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static flags: flags.Input<any> = {
help: flags.help({ char: 'h' }),
force: flags.boolean({ char: 'f' }),
title: flags.string({ char: 't', description: 'the display name of the action' }),
directory: flags.string({ char: 'd', description: 'base directory to scaffold the action' })
}
static args = [
{ name: 'name', description: 'the action name', required: true },
{ name: 'type', description: 'the type of action (browser, server)', required: true }
]
async integrationDirs(glob: string) {
const integrationDirs = await globby(glob, {
expandDirectories: false,
onlyDirectories: true,
gitignore: true,
ignore: ['node_modules']
})
return integrationDirs
}
parseArgs(): flags.Output {
return this.parse(GenerateAction)
}
async run() {
const { args, flags } = this.parseArgs()
const isBrowserDestination = (args.type as string).includes('browser')
let integrationsGlob = './packages/destination-actions/src/destinations/*'
if (isBrowserDestination) {
integrationsGlob = './packages/browser-destinations/destinations/*'
}
const integrationDirs = await this.integrationDirs(integrationsGlob)
const answers = await autoPrompt(flags, [
{
type: 'text',
name: 'title',
message: 'Action title:',
initial: toTitleCase(args.name),
format: (val) => toTitleCase(val)
},
{
type: 'select',
name: 'directory',
message: 'Which integration (directory)?',
choices: integrationDirs.map((integrationPath) => {
const [name] = integrationPath.split(path.sep).reverse()
const value = isBrowserDestination ? path.join(integrationPath, 'src') : integrationPath
return {
title: name,
value: value
}
})
}
])
const slug = camelCase(args.name)
const directory = answers.directory || './'
const relativePath = path.join(directory, slug)
const targetDirectory = path.join(process.cwd(), relativePath)
const destinationFolder = path.parse(answers.directory).base
const destination = startCase(camelCase(destinationFolder)).replace(/ /g, '')
const snapshotPath = path.join(__dirname, '../../../templates/actions/action-snapshot')
let templatePath = path.join(__dirname, '../../../templates/actions/empty-action')
if (args.type === 'browser') {
templatePath = path.join(__dirname, '../../../templates/actions/empty-browser-action')
}
try {
this.spinner.start(`Creating ${chalk.bold(args.name)}`)
renderTemplates(
templatePath,
targetDirectory,
{
name: answers.title,
description: '',
slug,
destination
},
flags.force
)
this.spinner.succeed(`Scaffold action`)
} catch (err) {
this.spinner.fail(`Scaffold action: ${chalk.red(err.message)}`)
this.exit()
}
if (!isBrowserDestination) {
try {
this.spinner.start(`Creating snapshot tests for ${chalk.bold(`${destination}'s ${slug}`)} destination action`)
renderTemplates(
snapshotPath,
targetDirectory,
{
destination: destination,
actionSlug: slug
},
true
)
this.spinner.succeed(`Creating snapshot tests for ${chalk.bold(`${destination}'s ${slug}`)} destination action`)
} catch (err) {
this.spinner.fail(`Snapshot test creation failed: ${chalk.red(err.message)}`)
this.exit()
}
}
// Update destination with action
const entryFile = require.resolve(path.relative(__dirname, path.join(process.cwd(), directory)))
try {
this.spinner.start(chalk`Updating destination definition`)
const destinationStr = fs.readFileSync(entryFile, 'utf8')
const exportName = args.type === 'browser' ? 'destination' : 'default'
const updatedCode = addKeyToExport(destinationStr, exportName, 'actions', slug)
fs.writeFileSync(entryFile, updatedCode, 'utf8')
this.spinner.succeed()
} catch (err) {
this.spinner.fail(chalk`Failed to update your destination imports: ${err.message}`)
this.exit()
}
try {
this.spinner.start(chalk`Generating types for {magenta ${slug}} action`)
await GenerateTypes.run(['--path', entryFile])
this.spinner.succeed()
} catch (err) {
this.spinner.fail(chalk`Generating types for {magenta ${slug}} action: ${err.message}`)
this.exit()
}
this.log(chalk.green(`Done creating "${args.name}" 🎉`))
this.log(chalk.green(`Start coding! cd ${targetDirectory}`))
}
async catch(error: unknown) {
if (this.spinner?.isSpinning) {
this.spinner.fail()
}
throw error
}
}