-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathcreate.ts
More file actions
281 lines (254 loc) · 6.92 KB
/
create.ts
File metadata and controls
281 lines (254 loc) · 6.92 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
import process from 'node:process'
import readline from 'node:readline/promises'
import meow from 'meow'
import open from 'open'
import colors from 'yoctocolors-cjs'
import { Spinner } from '@socketsecurity/registry/lib/spinner'
import { handleApiCall, handleUnsuccessfulApiResponse } from '../../utils/api'
import { AuthError } from '../../utils/errors'
import { getFlagListOutput } from '../../utils/output-formatting'
import { getPackageFilesFullScans } from '../../utils/path-resolve'
import { getDefaultToken, setupSdk } from '../../utils/sdk'
import type { CliSubcommand } from '../../utils/meow-with-subcommands'
export const create: CliSubcommand = {
description: 'Create a scan',
async run(argv, importMeta, { parentName }) {
const name = `${parentName} create`
const input = await setupCommand(name, create.description, argv, importMeta)
if (input) {
const apiToken = getDefaultToken()
if (!apiToken) {
throw new AuthError(
'User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.'
)
}
const spinnerText = 'Creating a scan... \n'
const spinner = new Spinner({ text: spinnerText }).start()
await createFullScan(input, spinner, apiToken, input.cwd)
}
}
}
const createFullScanFlags: { [key: string]: any } = {
repo: {
type: 'string',
shortFlag: 'r',
default: '',
description: 'Repository name'
},
branch: {
type: 'string',
shortFlag: 'b',
default: '',
description: 'Branch name'
},
commitMessage: {
type: 'string',
shortFlag: 'm',
default: '',
description: 'Commit message'
},
commitHash: {
type: 'string',
shortFlag: 'ch',
default: '',
description: 'Commit hash'
},
cwd: {
type: 'string',
description: 'working directory, defaults to process.cwd()'
},
pullRequest: {
type: 'number',
shortFlag: 'pr',
description: 'Commit hash'
},
committers: {
type: 'string',
shortFlag: 'c',
default: '',
description: 'Committers'
},
defaultBranch: {
type: 'boolean',
shortFlag: 'db',
default: false,
description: 'Make default branch'
},
pendingHead: {
type: 'boolean',
shortFlag: 'ph',
default: false,
description: 'Set as pending head'
},
tmp: {
type: 'boolean',
shortFlag: 't',
default: false,
description: 'Set the visibility (true/false) of the scan in your dashboard'
}
}
// Internal functions
type CommandContext = {
cwd: string
orgSlug: string
repoName: string
branchName: string
committers: string
commitMessage: string
commitHash: string
pullRequest: number | undefined
defaultBranch: boolean
pendingHead: boolean
tmp: boolean
packagePaths: string[]
}
async function setupCommand(
name: string,
description: string,
argv: readonly string[],
importMeta: ImportMeta
): Promise<CommandContext | undefined> {
const flags: { [key: string]: any } = {
...createFullScanFlags
}
const cli = meow(
`
Usage
$ ${name} [...options] <org> <TARGET> [TARGET ...]
Where TARGET is a FILE or DIR that _must_ be inside the CWD.
When a FILE is given only that FILE is targeted. Otherwise any eligible
files in the given DIR will be considered.
Options
${getFlagListOutput(flags, 6)}
Examples
$ ${name} --repo=test-repo --branch=main FakeOrg ./package.json
`,
{
argv,
description,
importMeta,
flags
}
)
let showHelp = cli.flags['help']
const socketSdk = await setupSdk()
const supportedFiles = await socketSdk
.getReportSupportedFiles()
.then(res => {
if (!res.success)
handleUnsuccessfulApiResponse(
'getReportSupportedFiles',
res,
new Spinner()
)
return (res as any).data
})
.catch(
/** @type {(cause: Error) => never} */
cause => {
throw new Error('Failed getting supported files for report', {
cause
})
}
)
// TODO: I think the cwd should be set to the DIR|FILE arg of this command and the DIR/FILE be either '.' or the filename() of the arg
const cwd =
cli.flags['cwd'] && cli.flags['cwd'] !== 'process.cwd()'
? String(cli.flags['cwd'])
: process.cwd()
const [orgSlug, ...targets] = cli.input
const packagePaths = await getPackageFilesFullScans(
cwd,
targets,
supportedFiles
)
const { branch: branchName, repo: repoName } = cli.flags
if (!orgSlug || !repoName || !branchName || !packagePaths.length) {
showHelp = true
console.error(`${colors.bgRed(colors.white('Input error'))}: Please provide the required fields:\n
- Org name as first arg ${!orgSlug ? colors.red('(missing!)') : colors.green('(ok)')}\n
- Repository name using --repo ${!repoName ? colors.red('(missing!)') : colors.green('(ok)')}\n
- Branch name using --branch ${!branchName ? colors.red('(missing!)') : colors.green('(ok)')}\n
- At least one file path (e.g. ./package.json) ${
!packagePaths.length
? colors.red(
targets.length > 0
? '(TARGET' +
(targets.length ? 's' : '') +
' contained no matching/supported files!)'
: '(missing)'
)
: colors.green('(ok)')
}`)
}
if (showHelp) {
cli.showHelp()
return
}
return <CommandContext>{
cwd,
orgSlug,
repoName,
branchName,
commitMessage: cli.flags['commitMessage'],
defaultBranch: cli.flags['defaultBranch'],
pendingHead: cli.flags['pendingHead'],
tmp: cli.flags['tmp'],
packagePaths,
commitHash: cli.flags['commitHash'],
committers: cli.flags['committers'],
pullRequest: cli.flags['pullRequest']
}
}
async function createFullScan(
input: CommandContext,
spinner: Spinner,
apiToken: string,
cwd: string = process.cwd()
): Promise<void> {
const socketSdk = await setupSdk(apiToken)
const {
branchName,
commitMessage,
defaultBranch,
orgSlug,
packagePaths,
pendingHead,
repoName,
tmp
} = input
const result = await handleApiCall(
socketSdk.createOrgFullScan(
orgSlug,
{
repo: repoName,
branch: branchName,
commit_message: commitMessage,
make_default_branch: defaultBranch,
set_as_pending_head: pendingHead,
tmp
},
packagePaths,
cwd
),
'Creating scan'
)
if (!result.success) {
handleUnsuccessfulApiResponse('CreateOrgFullScan', result, spinner)
return
}
spinner.success('Scan created successfully')
const link = colors.underline(colors.cyan(`${result.data.html_report_url}`))
console.log(`Available at: ${link}`)
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const answer = await rl.question(
'Would you like to open it in your browser? (y/n)'
)
if (answer.toLowerCase() === 'y') {
await open(`${result.data.html_report_url}`)
}
rl.close()
}