generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 21
/
mdapi.ts
214 lines (196 loc) · 6.94 KB
/
mdapi.ts
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
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { dirname, resolve } from 'node:path';
import fs from 'node:fs';
import { Messages, SfError } from '@salesforce/core';
import {
ComponentSet,
ComponentSetBuilder,
ConvertResult,
MetadataConverter,
RegistryAccess,
} from '@salesforce/source-deploy-retrieve';
import {
arrayWithDeprecation,
Flags,
loglevel,
orgApiVersionFlagWithDeprecations,
SfCommand,
} from '@salesforce/sf-plugins-core';
import { Interfaces } from '@oclif/core';
import { ConvertMdapiJson } from '../../../utils/types.js';
import { MetadataConvertResultFormatter } from '../../../formatters/metadataConvertResultFormatter.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-deploy-retrieve', 'convert.mdapi');
export type EnsureFsFlagOptions = {
flagName: string;
path: string;
type: 'dir' | 'file' | 'any';
throwOnENOENT?: boolean;
};
export class Mdapi extends SfCommand<ConvertMdapiJson> {
public static readonly aliases = ['force:mdapi:convert'];
public static readonly deprecateAliases = true;
public static readonly summary = messages.getMessage('summary');
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessages('examples');
public static readonly requiresProject = true;
public static readonly flags = {
'api-version': orgApiVersionFlagWithDeprecations,
loglevel,
'root-dir': Flags.directory({
aliases: ['rootdir'],
deprecateAliases: true,
char: 'r',
summary: messages.getMessage('flags.root-dir.summary'),
required: true,
exists: true,
}),
'output-dir': Flags.directory({
aliases: ['outputdir'],
deprecateAliases: true,
char: 'd',
summary: messages.getMessage('flags.output-dir.summary'),
}),
manifest: Flags.file({
char: 'x',
description: messages.getMessage('flags.manifest.description'),
summary: messages.getMessage('flags.manifest.summary'),
exists: true,
}),
'metadata-dir': arrayWithDeprecation({
char: 'p',
aliases: ['metadatapath'],
deprecateAliases: true,
description: messages.getMessage('flags.metadata-dir.description'),
summary: messages.getMessage('flags.metadata-dir.summary'),
exclusive: ['manifest', 'metadata'],
}),
metadata: arrayWithDeprecation({
char: 'm',
summary: messages.getMessage('flags.metadata.summary'),
exclusive: ['manifest', 'metadatapath'],
}),
};
private flags!: Interfaces.InferredFlags<typeof Mdapi.flags>;
private componentSet?: ComponentSet;
private convertResult?: ConvertResult;
public async run(): Promise<ConvertMdapiJson> {
this.flags = (await this.parse(Mdapi)).flags;
await this.convert();
return this.formatResult();
}
protected async convert(): Promise<void> {
const [outputDir] = await Promise.all([
resolveOutputDir(this.flags['output-dir'] ?? this.project!.getDefaultPackage().path),
resolveMetadataPaths(this.flags['metadata-dir'] ?? []),
]);
let paths: string[] = [];
if (this.flags['metadata-dir']) {
paths = this.flags['metadata-dir'];
} else if (!this.flags.manifest && !this.flags.metadata) {
paths = [this.flags['root-dir']];
}
this.componentSet = await ComponentSetBuilder.build({
sourcepath: paths,
manifest: this.flags.manifest
? {
manifestPath: this.flags.manifest,
directoryPaths: [this.flags['root-dir']],
}
: undefined,
metadata: this.flags.metadata
? {
metadataEntries: this.flags.metadata,
directoryPaths: [this.flags['root-dir']],
}
: undefined,
...(this.project ? { projectDir: this.project?.getPath() } : {}),
});
const numOfComponents = this.componentSet.getSourceComponents().toArray().length;
if (numOfComponents > 0) {
this.spinner.start(`Converting ${numOfComponents} metadata components`);
const converter = new MetadataConverter(new RegistryAccess(undefined, this.project?.getPath()));
this.convertResult = await converter.convert(this.componentSet, 'source', {
type: 'directory',
outputDirectory: outputDir,
genUniqueDir: false,
});
this.spinner.stop();
}
}
protected async formatResult(): Promise<ConvertMdapiJson> {
if (!this.convertResult) {
throw new SfError('No results to format');
}
const formatter = new MetadataConvertResultFormatter(this.convertResult);
if (!this.jsonEnabled()) {
await formatter.display();
}
return formatter.getJson();
}
}
const resolveOutputDir = async (outputDir: string): Promise<string> =>
ensureFlagPath({
flagName: 'outputdir',
path: outputDir,
type: 'dir',
});
const resolveMetadataPaths = async (metadataPaths: string[]): Promise<string[]> =>
Promise.all(
metadataPaths
.filter((mdPath) => mdPath?.length)
.map((mdPath) =>
ensureFlagPath({
flagName: 'metadatapath',
path: mdPath,
type: 'any',
throwOnENOENT: true,
})
)
);
/**
* Ensures command flags that are file system paths are set properly before
* continuing command execution. Can also create directories that don't yet
* exist in the path.
*
* @param options defines the path to resolve and the expectations
* @returns the resolved flag path
*/
const ensureFlagPath = async (options: EnsureFsFlagOptions): Promise<string> => {
const { flagName, path, type, throwOnENOENT } = options;
const resolvedPath = resolve(path?.trim());
try {
const stats = await fs.promises.stat(resolvedPath);
if (type !== 'any') {
const isDir = stats.isDirectory();
if (type === 'dir' && !isDir) {
throw messages.createError('InvalidFlagPath', [flagName, path, messages.getMessage('expectedDirectory')]);
} else if (type === 'file' && isDir) {
throw messages.createError(
messages.getMessage('InvalidFlagPath', [flagName, path, messages.getMessage('expectedFile')])
);
}
}
return resolvedPath;
} catch (error) {
if (error instanceof Error && 'code' in error && error.code !== 'ENOENT') {
throw error;
} else {
if (throwOnENOENT) {
const enoent = messages.getMessage('notFound');
throw new SfError(messages.getMessage('InvalidFlagPath', [flagName, path, enoent]), 'InvalidFlagPath');
}
const dir = type === 'dir' ? resolvedPath : dirname(resolvedPath);
await fs.promises.mkdir(dir, { recursive: true }).catch((err) => {
throw SfError.wrap(err);
});
// `fs.mkdir` will return only the first dir in the path so we return the full path here
return dir;
}
}
};