-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdestroy.ts
More file actions
186 lines (147 loc) · 6.97 KB
/
destroy.ts
File metadata and controls
186 lines (147 loc) · 6.97 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
import { InitializationResult, PluginInitOrchestrator } from '../common/initialize-plugins.js';
import { Plan } from '../entities/plan.js';
import { Project } from '../entities/project.js';
import { ResourceConfig } from '../entities/resource-config.js';
import { ResourceInfo } from '../entities/resource-info.js';
import { ProcessName, SubProcessName, ctx } from '../events/context.js';
import { DependencyMap, PluginManager } from '../plugins/plugin-manager.js';
import { PromptType, Reporter } from '../ui/reporters/reporter.js';
import { wildCardMatch } from '../utils/wild-card-match.js';
export interface DestroyArgs {
typeIds: string[];
path?: string;
secureMode?: boolean;
verbosityLevel?: number;
}
export class DestroyOrchestrator {
static async run(args: DestroyArgs, reporter: Reporter) {
const typeIds = args.typeIds?.filter(Boolean)
ctx.processStarted(ProcessName.DESTROY)
const initializationResult = await PluginInitOrchestrator.run(
{ ...args, allowEmptyProject: true, },
reporter
);
const { pluginManager, project } = initializationResult;
if ((!typeIds || typeIds.length === 0) && project.isEmpty()) {
throw new Error('At least one resource [type] must be specified. Ex: "codify destroy homebrew". Or the destroy command must be run in a directory with a valid codify file')
}
const { plan, destroyProject } = (!typeIds || typeIds.length === 0)
? await DestroyOrchestrator.destroyExistingProject(reporter, initializationResult)
: await DestroyOrchestrator.destroySpecificResources(typeIds, reporter, initializationResult)
plan.sortByEvalOrder(project.evaluationOrder);
destroyProject.removeNoopFromEvaluationOrder(plan);
reporter.displayPlan(plan);
// Short circuit and exit if every change is NOOP
if (plan.isEmpty()) {
console.log('No changes necessary. Exiting');
return;
}
const confirm = await reporter.promptConfirmation('Do you want to destroy?')
if (!confirm) {
return;
}
const filteredPlan = plan.filterNoopResources()
await ctx.process(ProcessName.DESTROY, () =>
pluginManager.apply(destroyProject, filteredPlan)
)
await reporter.displayMessage(`
🎉 Finished applying 🎉
Open a new terminal or source '.zshrc' for the new changes to be reflected`);
}
/** This method is responsible for generating a plan for specific resources specified by the user */
private static async destroySpecificResources(
typeIds: string[],
reporter: Reporter,
initializeResult: InitializationResult
): Promise<{ plan: Plan, destroyProject: Project }> {
const { project, pluginManager, typeIdsToDependenciesMap } = initializeResult;
// TODO: In the future if a user supplies resourceId.name (naming a specific resource) destroy that resource instead of stripping the name out.
const matchedTypes = this.matchTypeIds(typeIds.map((id) => id.split('.').at(0) ?? ''), [...typeIdsToDependenciesMap.keys()])
await DestroyOrchestrator.validateTypeIds(matchedTypes, project, pluginManager, typeIdsToDependenciesMap);
const resourceInfoList = (await pluginManager.getMultipleResourceInfo(matchedTypes));
const resourcesToDestroy = await DestroyOrchestrator.getDestroyParameters(reporter, project, resourceInfoList);
const destroyProject = new Project(
null,
resourcesToDestroy,
project.codifyFiles
).toDestroyProject();
destroyProject.resolveDependenciesAndCalculateEvalOrder(typeIdsToDependenciesMap);
const plan = await ctx.subprocess(ProcessName.PLAN, () =>
pluginManager.plan(destroyProject)
)
return { plan, destroyProject };
}
/** This method is responsible for generating the plan when no args are specified (ie: destroy all resources inside a codify.json file) **/
private static async destroyExistingProject(
reporter: Reporter,
initializeResult: InitializationResult
): Promise<{ plan: Plan, destroyProject: Project }> {
const { pluginManager, project, typeIdsToDependenciesMap } = initializeResult;
await ctx.subprocess(SubProcessName.VALIDATE, async () => {
project.validateTypeIds(typeIdsToDependenciesMap);
const validationResults = await pluginManager.validate(project);
project.handlePluginResourceValidationResults(validationResults);
})
const destroyProject = project.toDestroyProject();
destroyProject.resolveDependenciesAndCalculateEvalOrder(typeIdsToDependenciesMap);
const plan = await ctx.subprocess(ProcessName.PLAN, () =>
pluginManager.plan(destroyProject)
)
return { plan, destroyProject };
}
private static matchTypeIds(typeIds: string[], validTypeIds: string[]): string[] {
const result: string[] = [];
const unsupportedTypeIds: string[] = [];
for (const typeId of typeIds) {
if (!typeId.includes('*') && !typeId.includes('?')) {
const matched = validTypeIds.includes(typeId);
if (!matched) {
unsupportedTypeIds.push(typeId);
continue;
}
result.push(typeId)
continue;
}
const matched = validTypeIds.filter((valid) => wildCardMatch(valid, typeId))
if (matched.length === 0) {
unsupportedTypeIds.push(typeId);
continue;
}
result.push(...matched);
}
if (unsupportedTypeIds.length > 0) {
throw new Error(`The following resources cannot be destroyed. No plugins found that support the following types:
${JSON.stringify(unsupportedTypeIds)}`);
}
return result;
}
private static async validateTypeIds(typeIds: string[], project: Project, pluginManager: PluginManager, dependencyMap: DependencyMap): Promise<void> {
project.validateTypeIds(dependencyMap);
const unsupportedTypeIds = typeIds.filter((type) => !dependencyMap.has(type));
if (unsupportedTypeIds.length > 0) {
throw new Error(`The following resources cannot be destroyed. No plugins found that support the following types:
${JSON.stringify(unsupportedTypeIds)}`);
}
}
private static async getDestroyParameters(reporter: Reporter, project: Project, resourceInfoList: ResourceInfo[]): Promise<Array<ResourceConfig>> {
// Figure out which resources we need to prompt the user for additional info (based on the resource info)
const [noPrompt, askPrompt] = resourceInfoList.reduce((result, info) => {
info.getRequiredParameters().length === 0 ? result[0].push(info) : result[1].push(info);
return result;
}, [<ResourceInfo[]>[], <ResourceInfo[]>[]])
askPrompt.forEach((info) => {
const matchedResources = project.findAll(info.type);
if (matchedResources.length > 0) {
info.attachDefaultValues(matchedResources[0]);
}
})
if (askPrompt.length > 0) {
await reporter.displayImportWarning(askPrompt.map((r) => r.type), noPrompt.map((r) => r.type));
}
const userSupplied = await reporter.promptUserForValues(askPrompt, PromptType.DESTROY);
return [
...noPrompt.map((info) => new ResourceConfig({ type: info.type })),
...userSupplied
]
}
}