Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply handle pattern to diff-scan #375

Merged
merged 1 commit into from
Mar 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions src/commands/diff-scan/cmd-diff-scan-get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import colors from 'yoctocolors-cjs'

import { logger } from '@socketsecurity/registry/lib/logger'

import { getDiffScan } from './get-diff-scan'
import { handleDiffScan } from './handle-diff-scan'
import constants from '../../constants'
import { commonFlags } from '../../flags'
import { meowOrExit } from '../../utils/meow-with-subcommands'
Expand Down Expand Up @@ -85,8 +85,8 @@ async function run(
parentName
})

const before = String(cli.flags['before'] || '')
const after = String(cli.flags['after'] || '')
const { after, before, depth, file, json, markdown } = cli.flags

const [orgSlug = ''] = cli.input

if (!before || !after || cli.input.length < 1) {
Expand All @@ -107,12 +107,12 @@ async function run(
return
}

await getDiffScan({
outputJson: Boolean(cli.flags['json']),
before,
after,
depth: Number(cli.flags['depth']),
await handleDiffScan({
before: String(before || ''),
after: String(after || ''),
depth: Number(depth),
orgSlug,
file: String(cli.flags['file'] || '')
outputKind: json ? 'json' : markdown ? 'markdown' : 'text',
file: String(file || '')
})
}
73 changes: 73 additions & 0 deletions src/commands/diff-scan/fetch-diff-scan.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import colors from 'yoctocolors-cjs'

import constants from '../../constants'
import { handleAPIError, handleApiCall, queryAPI } from '../../utils/api'
import { AuthError } from '../../utils/errors'
import { getDefaultToken } from '../../utils/sdk'

import type { SocketSdkReturnType } from '@socketsecurity/sdk'

export async function fetchDiffScan({
after,
before,
orgSlug
}: {
after: string
before: string
orgSlug: string
}): Promise<SocketSdkReturnType<'GetOrgDiffScan'>['data'] | undefined> {
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.'
)
}

return await fetchDiffScanWithToken(apiToken, {
after,
before,
orgSlug
})
}

export async function fetchDiffScanWithToken(
apiToken: string,
{
after,
before,
orgSlug
}: {
after: string
before: string
orgSlug: string
}
): Promise<SocketSdkReturnType<'GetOrgDiffScan'>['data'] | undefined> {
// Lazily access constants.spinner.
const { spinner } = constants

spinner.start('Fetching diff-scan...')

const response = await queryAPI(
`orgs/${orgSlug}/full-scans/diff?before=${encodeURIComponent(before)}&after=${encodeURIComponent(after)}`,
apiToken
)

spinner?.successAndStop('Received diff-scan response')

if (!response.ok) {
const err = await handleAPIError(response.status)
spinner.errorAndStop(
`${colors.bgRed(colors.white(response.statusText))}: ${err}`
)
return
}

const result = await handleApiCall(
(await response.json()) as Promise<
SocketSdkReturnType<'GetOrgDiffScan'>['data']
>,
'Deserializing json'
)

return result
}
31 changes: 31 additions & 0 deletions src/commands/diff-scan/handle-diff-scan.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { fetchDiffScan } from './fetch-diff-scan'
import { outputDiffScan } from './output-diff-scan'

export async function handleDiffScan({
after,
before,
depth,
file,
orgSlug,
outputKind
}: {
after: string
before: string
depth: number
file: string
orgSlug: string
outputKind: 'json' | 'markdown' | 'text'
}): Promise<void> {
const data = await fetchDiffScan({
after,
before,
orgSlug
})
if (!data) return

await outputDiffScan(data, {
depth,
file,
outputKind
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,98 +5,29 @@ import colors from 'yoctocolors-cjs'

import { logger } from '@socketsecurity/registry/lib/logger'

import constants from '../../constants'
import { handleAPIError, handleApiCall, queryAPI } from '../../utils/api'
import { AuthError } from '../../utils/errors'
import { getDefaultToken } from '../../utils/sdk'

import type { SocketSdkReturnType } from '@socketsecurity/sdk'

export async function getDiffScan({
after,
before,
depth,
file,
orgSlug,
outputJson
}: {
after: string
before: string
depth: number
file: string
orgSlug: string
outputJson: boolean
}): Promise<void> {
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.'
)
}

await getDiffScanWithToken({
after,
before,
export async function outputDiffScan(
result: SocketSdkReturnType<'GetOrgDiffScan'>['data'],
{
depth,
file,
orgSlug,
outputJson,
apiToken
})
}
export async function getDiffScanWithToken({
after,
apiToken,
before,
depth,
file,
orgSlug,
outputJson
}: {
after: string
apiToken: string
depth: number
before: string
file: string
orgSlug: string
outputJson: boolean
}): Promise<void> {
// Lazily access constants.spinner.
const { spinner } = constants

spinner.start('Getting diff scan...')

const response = await queryAPI(
`orgs/${orgSlug}/full-scans/diff?before=${encodeURIComponent(before)}&after=${encodeURIComponent(after)}`,
apiToken
)

if (!response.ok) {
const err = await handleAPIError(response.status)
spinner.errorAndStop(
`${colors.bgRed(colors.white(response.statusText))}: ${err}`
)
return
outputKind
}: {
depth: number
file: string
outputKind: 'json' | 'markdown' | 'text'
}

const result = await handleApiCall(
(await response.json()) as Promise<
SocketSdkReturnType<'GetOrgDiffScan'>['data']
>,
'Deserializing json'
)

spinner.stop()

const dashboardUrl = (result as any)?.['diff_report_url']
): Promise<void> {
const dashboardUrl = result.diff_report_url
const dashboardMessage = dashboardUrl
? `\n View this diff scan in the Socket dashboard: ${colors.cyan(dashboardUrl)}`
: ''

// When forcing json, or dumping to file, serialize to string such that it
// won't get truncated. The only way to dump the full raw JSON to stdout is
// to use `--json --file -` (the dash is a standard notation for stdout)
if (outputJson || file) {
if (outputKind === 'json' || file) {
let json
try {
json = JSON.stringify(result, null, 2)
Expand Down
Loading