-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathconvertBehavior.ts
More file actions
205 lines (190 loc) · 7.03 KB
/
convertBehavior.ts
File metadata and controls
205 lines (190 loc) · 7.03 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
/*
* Copyright 2026, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { readdirSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { SfError, SfProject, SfProjectJson, Messages } from '@salesforce/core';
import {
ComponentSet,
ComponentSetBuilder,
ConvertResult,
MetadataConverter,
MetadataRegistry,
RegistryAccess,
SourceComponent,
presetMap,
} from '@salesforce/source-deploy-retrieve';
import { isString } from '@salesforce/ts-types';
export type ComponentSetAndPackageDirPath = { packageDirPath: string; cs: ComponentSet };
// TODO: there could be a cleaner way to read this
const PRESET_DIR = join(
fileURLToPath(import.meta.resolve('@salesforce/source-deploy-retrieve')),
'..',
'registry',
'presets'
);
export const PRESETS_PROP = 'sourceBehaviorOptions';
export const PRESET_CHOICES = [...presetMap.keys()];
export const TMP_DIR = process.env.SF_MDAPI_TEMP_DIR ?? 'decompositionConverterTempDir';
export const DRY_RUN_DIR = 'DRY-RUN-RESULTS';
/** returns packageDirectories and ComponentsSets where there is metadata of the type we'll change the behavior for */
export const getPackageDirectoriesForPreset = async (
project: SfProject,
preset: string
): Promise<ComponentSetAndPackageDirPath[]> => {
const projectDir = project.getPath();
const messages = loadMessages();
const output = (
await Promise.all(
project
.getPackageDirectories()
.map((pd) => pd.path)
.map(componentSetFromPackageDirectory(projectDir)(await getTypesFromPreset(preset)))
)
).filter(componentSetIsNonEmpty);
if (output.length === 0) {
throw messages.createError('error.noTargetTypes', [preset]);
}
return output;
};
/** converts the composed metadata to mdapi format in a temp dir */
export const convertToMdapi = async (packageDirsWithDecomposable: ComponentSetAndPackageDirPath[]): Promise<string[]> =>
(
await Promise.all(
packageDirsWithDecomposable.map(async (pd) => {
// convert to the mdapi targetDir
await new MetadataConverter().convert(pd.cs, 'metadata', {
type: 'directory',
outputDirectory: join(TMP_DIR, pd.packageDirPath),
genUniqueDir: false,
});
return getComponentSetFiles(pd.cs);
})
)
)
.flat()
.map((f) => resolve(f));
/** get the LOCAL project json, throws if not present OR the preset already exists */
export const getValidatedProjectJson = (preset: string, project: SfProject): SfProjectJson => {
const projectJson = project.getSfProjectJson(false);
if (projectJson.get<string[]>(PRESETS_PROP)?.includes(preset)) {
throw SfError.create({
name: 'sourceBehaviorOptionAlreadyExists',
message: `sourceBehaviorOption ${preset} already exists in sfdx-project.json`,
});
}
return projectJson;
};
/** converts the temporary mdapi back to source, return a list of the created files */
export const convertBackToSource = async ({
packageDirsWithPreset,
projectDir,
dryRun,
}: {
packageDirsWithPreset: ComponentSetAndPackageDirPath[];
projectDir: string;
/** if provided, will output the results into a separate directory outside the project's packageDirectories */
dryRun: boolean;
}): Promise<string[]> => [
...new Set(
(
await convertToSource({
packageDirsWithPreset,
projectDir,
dryRunDir: dryRun ? DRY_RUN_DIR : undefined,
})
)
.flatMap((cr) => cr.converted ?? [])
// we can't use walkContent because there's a conditional inside it
.flatMap(getSourceComponentFiles)
.filter(isString)
),
];
const getSourceComponentFiles = (c: SourceComponent): string[] =>
[c.xml, ...(c.content ? fullPathsFromDir(c.content) : [])].filter(isString);
const fullPathsFromDir = (dir: string): string[] =>
readdirSync(dir, { withFileTypes: true }).map((d) => join(d.parentPath, d.name));
/** build a component set from the original project for each pkgDir */
const componentSetFromPackageDirectory =
(projectDir: string) =>
(metadataEntries: string[]) =>
async (packageDir: string): Promise<ComponentSetAndPackageDirPath> => ({
packageDirPath: packageDir,
cs: await ComponentSetBuilder.build({
metadata: {
metadataEntries,
directoryPaths: [packageDir],
},
projectDir,
}),
});
const convertToSource = async ({
packageDirsWithPreset,
projectDir,
dryRunDir,
}: {
packageDirsWithPreset: ComponentSetAndPackageDirPath[];
projectDir: string;
dryRunDir?: string;
}): Promise<ConvertResult[]> => {
// mdapi=>source convert the target dir back to the project
// it's a new converter because the project has changed and it should reload the project's registry.
SfProject.clearInstances(); // break the singleton so SDR will re-read to get the new preset
const converter = new MetadataConverter(new RegistryAccess(undefined, projectDir));
return Promise.all(
packageDirsWithPreset.map(async (pd) =>
converter.convert(
// componentSet based on each mdapi folder
await ComponentSetBuilder.build({ sourcepath: [join(TMP_DIR, pd.packageDirPath)], projectDir }),
'source',
dryRunDir
? // dryRun outputs to a dir outside the real packageDirs folder to avoid changing real stuff
{
type: 'directory',
outputDirectory: join(projectDir, dryRunDir),
packageName: pd.packageDirPath,
genUniqueDir: false,
}
: {
type: 'merge',
mergeWith: (
await ComponentSetBuilder.build({
sourcepath: [pd.packageDirPath],
projectDir,
})
).getSourceComponents(),
defaultDirectory: join(projectDir, pd.packageDirPath),
}
)
)
);
};
export const getTypesFromPreset = async (preset: string): Promise<string[]> =>
Object.values(
(JSON.parse(await readFile(join(PRESET_DIR, `${preset}.json`), 'utf-8')) as MetadataRegistry).types
).map((t) => t.name);
const getComponentSetFiles = (cs: ComponentSet): string[] =>
cs
.getSourceComponents()
.toArray()
.flatMap((c) => [c.xml, ...c.walkContent()])
.filter(isString);
const loadMessages = (): Messages<string> => {
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
return Messages.loadMessages('@salesforce/plugin-deploy-retrieve', 'convert.source-behavior');
};
const componentSetIsNonEmpty = (i: ComponentSetAndPackageDirPath): boolean => i.cs.size > 0;