-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathhandle-patch-rm.mts
More file actions
167 lines (140 loc) · 4.37 KB
/
handle-patch-rm.mts
File metadata and controls
167 lines (140 loc) · 4.37 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
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { UTF8 } from '@socketsecurity/lib/constants/encoding'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { DOT_SOCKET_DIR } from '@socketsecurity/lib/paths/dirnames'
import { MANIFEST_JSON } from '@socketsecurity/lib/paths/filenames'
import { normalizePath } from '@socketsecurity/lib/paths/normalize'
import { pluralize } from '@socketsecurity/lib/words'
import { PatchManifestSchema } from './manifest-schema.mts'
import { outputPatchRmResult } from './output-patch-rm-result.mts'
import { getErrorCause, InputError } from '../../utils/error/errors.mjs'
import {
cleanupBackups,
getPatchMetadata,
restoreAllBackups,
} from '../../utils/manifest/patch-backup.mts'
import { removePatch } from '../../utils/manifest/patches.mts'
import { normalizePurl } from '../../utils/purl/parse.mjs'
import type { OutputKind } from '../../types.mts'
import type { Spinner } from '@socketsecurity/lib/spinner'
const logger = getDefaultLogger()
export interface PatchRmData {
filesRestored: number
purl: string
}
export interface HandlePatchRmConfig {
cwd: string
keepBackups: boolean
outputKind: OutputKind
purl: string
spinner: Spinner | null
}
export async function handlePatchRm({
cwd,
keepBackups,
outputKind,
purl,
spinner,
}: HandlePatchRmConfig): Promise<void> {
try {
spinner?.start('Reading patch manifest')
const dotSocketDirPath = normalizePath(path.join(cwd, DOT_SOCKET_DIR))
const manifestPath = normalizePath(
path.join(dotSocketDirPath, MANIFEST_JSON),
)
const manifestContent = await fs.readFile(manifestPath, UTF8)
const manifestData = JSON.parse(manifestContent)
const validated = PatchManifestSchema.parse(manifestData)
const normalizedPurl = normalizePurl(purl)
const patch = validated.patches[normalizedPurl]
if (!patch) {
spinner?.stop()
throw new InputError(`Patch not found for PURL: ${purl}`)
}
// Check if patch has backups.
const uuid = patch.uuid
if (!uuid) {
spinner?.stop()
throw new InputError('Patch does not have a UUID for backup restoration')
}
spinner?.text('Checking for backups')
const metadata = await getPatchMetadata(uuid)
if (!metadata) {
spinner?.stop()
if (outputKind === 'text') {
logger.warn(
'No backups found for this patch. Original files cannot be restored.',
)
logger.log('Removing patch from manifest only.')
}
}
let filesRestored = 0
if (metadata) {
spinner?.text('Restoring original files from backups')
// Restore all backed up files.
const restoreResults = await restoreAllBackups(uuid)
filesRestored = restoreResults.restored.length
if (restoreResults.failed.length > 0) {
spinner?.stop()
if (outputKind === 'text') {
logger.warn(
`Failed to restore ${restoreResults.failed.length} ${pluralize('file', { count: restoreResults.failed.length })}:`,
)
for (const filePath of restoreResults.failed) {
logger.log(` - ${filePath}`)
}
}
}
if (!keepBackups) {
spinner?.text('Cleaning up backups')
await cleanupBackups(uuid)
}
}
spinner?.text('Removing patch from manifest')
// Remove patch from manifest.
await removePatch(normalizedPurl, cwd)
spinner?.stop()
if (outputKind === 'text') {
logger.log(`Removed patch for ${normalizedPurl}`)
if (filesRestored > 0) {
logger.log(
`Restored ${filesRestored} ${pluralize('file', { count: filesRestored })} from backups`,
)
}
}
await outputPatchRmResult(
{
ok: true,
data: {
filesRestored,
purl: normalizedPurl,
},
},
outputKind,
)
} catch (e) {
spinner?.stop()
if (e instanceof InputError) {
throw e
}
let message = 'Failed to remove patch'
let cause = getErrorCause(e)
if (e instanceof SyntaxError) {
message = `Invalid JSON in ${MANIFEST_JSON}`
cause = e.message
} else if (e instanceof Error && 'issues' in e) {
message = 'Schema validation failed'
cause = String(e)
}
await outputPatchRmResult(
{
ok: false,
code: 1,
message,
cause,
},
outputKind,
)
}
}