@adobe/aem-cli 15.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ /*
2
+ * Copyright 2018 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+ import fs from 'fs';
13
+ import path from 'path';
14
+ import os from 'os';
15
+ import ignore from 'ignore';
16
+ import ini from 'ini';
17
+ import fse from 'fs-extra';
18
+ import { GitUrl } from '@adobe/helix-shared-git';
19
+
20
+ import git from 'isomorphic-git';
21
+ // cache for isomorphic-git API
22
+ // see https://isomorphic-git.org/docs/en/cache
23
+ const cache = {};
24
+
25
+ export default class GitUtils {
26
+ /**
27
+ * Determines whether the working tree directory contains uncommitted or unstaged changes.
28
+ *
29
+ * @param {string} dir working tree directory path of the git repo
30
+ * @param {string} [homedir] optional users home directory
31
+ * @returns {Promise<boolean>} `true` if there are uncommitted/unstaged changes; otherwise `false`
32
+ */
33
+ static async isDirty(dir, homedir = os.homedir()) {
34
+ // see https://isomorphic-git.org/docs/en/statusMatrix
35
+ const HEAD = 1;
36
+ const WORKDIR = 2;
37
+ const STAGE = 3;
38
+ const matrix = await git.statusMatrix({ fs, dir, cache });
39
+ let modified = matrix
40
+ .filter((row) => !(row[HEAD] === row[WORKDIR] && row[WORKDIR] === row[STAGE]));
41
+ if (modified.length === 0) {
42
+ return false;
43
+ }
44
+
45
+ // ignore submodules
46
+ // see https://github.com/adobe/helix-cli/issues/614
47
+ const gitModules = path.resolve(dir, '.gitmodules');
48
+ if (await fse.pathExists(gitModules)) {
49
+ const modules = ini.parse(await fse.readFile(gitModules, 'utf-8'));
50
+ Object.keys(modules).forEach((key) => {
51
+ const module = modules[key];
52
+ if (module.path) {
53
+ modified = modified.filter((row) => !row[0].startsWith(module.path));
54
+ }
55
+ });
56
+ if (modified.length === 0) {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ // workaround for https://github.com/isomorphic-git/isomorphic-git/issues/1076
62
+ // TODO: remove once #1076 has been resolved.
63
+ let ign;
64
+ const localeIgnore = path.resolve(dir, '.gitignore');
65
+ if (await fse.pathExists(localeIgnore)) {
66
+ ign = ignore();
67
+ ign.add(await fse.readFile(localeIgnore, 'utf-8'));
68
+ }
69
+
70
+ // need to re-check the modified against the globally ignored
71
+ // see: https://github.com/isomorphic-git/isomorphic-git/issues/444
72
+ const globalConfig = path.resolve(homedir, '.gitconfig');
73
+ const config = ini.parse(await fse.readFile(globalConfig, 'utf-8'));
74
+ const globalIgnore = path.resolve(homedir, (config.core && config.core.excludesfile) || '.gitignore_global');
75
+ if (await fse.pathExists(globalIgnore)) {
76
+ ign = ign || ignore();
77
+ ign.add(await fse.readFile(globalIgnore, 'utf-8'));
78
+ }
79
+
80
+ if (ign) {
81
+ modified = modified.filter((row) => !ign.ignores(row[0]));
82
+ if (modified.length === 0) {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ // filter out the deleted ones for the checks below
88
+ const existing = modified.filter((row) => row[WORKDIR] > 0).map((row) => row[0]);
89
+ if (existing.length < modified.length) {
90
+ return true;
91
+ }
92
+
93
+ // we also need to filter out the non-files and non-symlinks.
94
+ // see: https://github.com/isomorphic-git/isomorphic-git/issues/705
95
+ const stats = await Promise.all(existing.map((file) => fse.lstat(path.resolve(dir, file))));
96
+ const files = stats.filter((stat) => stat.isFile() || stat.isSymbolicLink());
97
+ return files.length > 0;
98
+ }
99
+
100
+ /**
101
+ * Checks if the given file is missing or ignored by git.
102
+ *
103
+ * @param {string} dir working tree directory path of the git repo
104
+ * @param {string} filepath file to check
105
+ * @param {string} [homedir] optional users home directory
106
+ * @returns {Promise<boolean>} `true` if the file is ignored.
107
+ */
108
+ static async isIgnored(dir, filepath, homedir = os.homedir()) {
109
+ if (!(await fse.pathExists(path.resolve(dir, filepath)))) {
110
+ return true;
111
+ }
112
+ if (!(await fse.pathExists(path.resolve(dir, '.git')))) {
113
+ return true;
114
+ }
115
+
116
+ const status = await git.status({
117
+ fs, dir, filepath, cache,
118
+ });
119
+ if (status === 'ignored') {
120
+ return true;
121
+ }
122
+
123
+ // need to re-check the modified against the globally ignored
124
+ // see: https://github.com/isomorphic-git/isomorphic-git/issues/444
125
+ const globalConfig = path.resolve(homedir, '.gitconfig');
126
+ const config = ini.parse(await fse.readFile(globalConfig, 'utf-8'));
127
+ const globalIgnore = path.resolve(homedir, (config.core && config.core.excludesfile) || '.gitignore_global');
128
+ if (await fse.pathExists(globalIgnore)) {
129
+ const ign = ignore().add(await fse.readFile(globalIgnore, 'utf-8'));
130
+ return ign.ignores(filepath);
131
+ }
132
+
133
+ return false;
134
+ }
135
+
136
+ /**
137
+ * Returns the name of the current branch. If `HEAD` is at a tag, the name of the tag
138
+ * will be returned instead, if head is at a commit, fallback will be returned.
139
+ *
140
+ * @param {string} dir working tree directory path of the git repo
141
+ * @param {string} fallback fallback value if no branch or tag is found
142
+ * @returns {Promise<string>} current branch or tag
143
+ */
144
+ static async getBranch(dir, fallback = 'main') {
145
+ // current commit sha
146
+ const rev = await git.resolveRef({ fs, dir, ref: 'HEAD' });
147
+ // reverse-lookup tag from commit sha
148
+ const allTags = await git.listTags({ fs, dir });
149
+
150
+ // iterate sequentially over tags to avoid OOME
151
+ for (const tag of allTags) {
152
+ /* eslint-disable no-await-in-loop */
153
+ const oid = await git.resolveRef({ fs, dir, ref: tag });
154
+ const obj = await git.readObject({
155
+ fs, dir, oid, cache,
156
+ });
157
+ const commitSha = obj.type === 'tag'
158
+ ? await git.resolveRef({ fs, dir, ref: obj.object.object }) // annotated tag
159
+ : oid; // lightweight tag
160
+ if (commitSha === rev) {
161
+ return tag;
162
+ }
163
+ }
164
+
165
+ const currentBranch = await git.currentBranch({ fs, dir, fullname: false });
166
+ if (currentBranch) {
167
+ return currentBranch;
168
+ }
169
+
170
+ return fallback;
171
+ }
172
+
173
+ /**
174
+ * Returns the encoded (any non word character replaced by `-`) `origin` remote url.
175
+ * If no `origin` remote url is defined `local--<basename of current working dir>`
176
+ * will be returned instead.
177
+ *
178
+ * @param {string} dir working tree directory path of the git repo
179
+ * @returns {Promise<string>} `dirty` or encoded current branch/tag
180
+ */
181
+ static async getRepository(dir) {
182
+ const repo = (await GitUtils.getOrigin(dir))
183
+ .replace(/[\W]/g, '-');
184
+ return repo !== '' ? repo : `local--${path.basename(dir)}`;
185
+ }
186
+
187
+ /**
188
+ * Returns the `origin` remote url or `''` if none is defined.
189
+ *
190
+ * @param {string} dir working tree directory path of the git repo
191
+ * @returns {Promise<string>} `origin` remote url
192
+ */
193
+ static async getOrigin(dir) {
194
+ try {
195
+ const rmt = (await git.listRemotes({ fs, dir })).find((entry) => entry.remote === 'origin');
196
+ return typeof rmt === 'object' ? rmt.url : '';
197
+ } catch (e) {
198
+ // don't fail if directory is not a git repository
199
+ return '';
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Same as #getOrigin() but returns a `GitUrl` instance instead of a string.
205
+ *
206
+ * @param {string} dir working tree directory path of the git repo
207
+ * @returns {Promise<GitUrl>} `origin` remote url ot {@code null} if not available
208
+ * @param {GitUrl~JSON} defaults Defaults for creating the git url.
209
+ */
210
+ static async getOriginURL(dir, defaults) {
211
+ const origin = await GitUtils.getOrigin(dir);
212
+ return origin ? new GitUrl(origin, defaults) : null;
213
+ }
214
+
215
+ /**
216
+ * Returns the sha of the current (i.e. `HEAD`) commit.
217
+ *
218
+ * @param {string} dir working tree directory path of the git repo
219
+ * @returns {Promise<string>} sha of the current (i.e. `HEAD`) commit
220
+ */
221
+ static async getCurrentRevision(dir) {
222
+ return git.resolveRef({ fs, dir, ref: 'HEAD' });
223
+ }
224
+
225
+ /**
226
+ * Returns the commit oid of the curent commit referenced by `ref`
227
+ *
228
+ * @param {string} dir git repo path
229
+ * @param {string} ref reference (branch, tag or commit sha)
230
+ * @returns {Promise<string>} commit oid of the curent commit referenced by `ref`
231
+ * @throws {Errors.NotFoundError}: resource not found
232
+ */
233
+ static async resolveCommit(dir, ref) {
234
+ return git.resolveRef({ fs, dir, ref })
235
+ .catch(async (err) => {
236
+ if (err instanceof git.Errors.NotFoundError) {
237
+ // fallback: is ref a shortened oid prefix?
238
+ const oid = await git.expandOid({
239
+ fs, dir, oid: ref, cache,
240
+ })
241
+ .catch(() => { throw err; });
242
+ return git.resolveRef({ fs, dir, ref: oid });
243
+ }
244
+ // re-throw
245
+ throw err;
246
+ });
247
+ }
248
+
249
+ /**
250
+ * Returns the contents of the file at revision `ref` and `pathName`
251
+ *
252
+ * @param {string} dir git repo path
253
+ * @param {string} ref reference (branch, tag or commit sha)
254
+ * @param {string} filePath relative path to file
255
+ * @returns {Promise<Buffer>} content of specified file
256
+ * @throws {Errors.NotFoundError}: resource not found or invalid reference
257
+ */
258
+ static async getRawContent(dir, ref, pathName) {
259
+ return GitUtils.resolveCommit(dir, ref)
260
+ .then((oid) => git.readObject({
261
+ fs, dir, oid, filepath: pathName, format: 'content', cache,
262
+ }))
263
+ .then((obj) => obj.object);
264
+ }
265
+ }
@@ -0,0 +1,48 @@
1
+ /*
2
+ * Copyright 2019 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+ import chalk from 'chalk-template';
13
+ import opn from 'open';
14
+ import { AbstractCommand } from './abstract.cmd.js';
15
+
16
+ export default class HackCommand extends AbstractCommand {
17
+ constructor(logger) {
18
+ super(logger);
19
+ this._open = false;
20
+ this._hackathon = '';
21
+ }
22
+
23
+ // eslint-disable-next-line class-methods-use-this
24
+ get requireConfigFile() {
25
+ return false;
26
+ }
27
+
28
+ withHackathon(value) {
29
+ this._hackathon = value || 'README';
30
+ return this;
31
+ }
32
+
33
+ withOpen(o) {
34
+ this._open = !!o;
35
+ return this;
36
+ }
37
+
38
+ async run() {
39
+ await this.init();
40
+ const url = `https://github.com/adobe/helix-home/tree/main/hackathons/${encodeURIComponent(this._hackathon)}.md`;
41
+ if (this._open) {
42
+ await opn(url);
43
+ } else {
44
+ // eslint-disable-next-line no-console
45
+ this.log.info(chalk`Check out the AEM Hackathon at {blue ${url}}`);
46
+ }
47
+ }
48
+ }
package/src/hack.js ADDED
@@ -0,0 +1,50 @@
1
+ /*
2
+ * Copyright 2019 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+ import { getOrCreateLogger } from './log-common.js';
13
+
14
+ export default function hack() {
15
+ let executor;
16
+ return {
17
+ set executor(value) {
18
+ executor = value;
19
+ },
20
+ command: 'hack [hackathon]',
21
+ aliases: [],
22
+ builder: (yargs) => {
23
+ yargs
24
+ .option('open', {
25
+ describe: 'Open a browser window',
26
+ type: 'boolean',
27
+ default: true,
28
+ })
29
+ .positional('hackathon', {
30
+ describe: 'The hackathon to attend',
31
+ default: '',
32
+ array: false,
33
+ type: 'string',
34
+ })
35
+ .help();
36
+ },
37
+ handler: async (argv) => {
38
+ if (!executor) {
39
+ // eslint-disable-next-line global-require
40
+ const HackCommand = (await import('./hack.cmd.js')).default; // lazy load the handler to speed up execution time
41
+ executor = new HackCommand(getOrCreateLogger(argv));
42
+ executor.withHackathon(argv.hackathon);
43
+ executor.withOpen(argv.open);
44
+ }
45
+
46
+ await executor
47
+ .run();
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,103 @@
1
+ /*
2
+ * Copyright 2018 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+ import fse from 'fs-extra';
13
+ import path from 'path';
14
+ import chalk from 'chalk-template';
15
+ import git from 'isomorphic-git';
16
+ import http from 'isomorphic-git/http/node/index.js';
17
+ import { HelixImportProject } from './server/HelixImportProject.js';
18
+ import pkgJson from './package.cjs';
19
+ import { AbstractServerCommand } from './abstract-server.cmd.js';
20
+
21
+ export default class ImportCommand extends AbstractServerCommand {
22
+ constructor(logger) {
23
+ super(logger);
24
+ this._importerSubPath = 'tools/importer';
25
+ }
26
+
27
+ withSkipUI(value) {
28
+ this._skipUI = value;
29
+ return this;
30
+ }
31
+
32
+ withUIRepo(value) {
33
+ this._uiRepo = value;
34
+ return this;
35
+ }
36
+
37
+ async setupImporterUI() {
38
+ const importerFolder = path.join(this.directory, this._importerSubPath);
39
+ await fse.ensureDir(importerFolder);
40
+ const uiProjectName = path.basename(this._uiRepo, '.git');
41
+ const uiFolder = path.join(importerFolder, uiProjectName);
42
+ const getUIVersion = async () => ((await fse.readJson(path.resolve(uiFolder, 'package.json'))).version);
43
+ const exists = await fse.pathExists(uiFolder);
44
+ if (!exists) {
45
+ this.log.info('AEM Importer UI needs to be installed.');
46
+ this.log.info(`Cloning ${this._uiRepo} in ${importerFolder}.`);
47
+ // clone the ui project
48
+ await git.clone({
49
+ fs: fse,
50
+ http,
51
+ dir: uiFolder,
52
+ url: this._uiRepo,
53
+ depth: 1,
54
+ singleBranch: true,
55
+ });
56
+ this.log.info(`AEM Importer UI is ready. v${await getUIVersion()}`);
57
+ } else {
58
+ this.log.info('Fetching latest version of the AEM Importer UI...');
59
+ // clone the ui project
60
+ await git.pull({
61
+ fs: fse,
62
+ http,
63
+ dir: uiFolder,
64
+ url: this._uiRepo,
65
+ depth: 1,
66
+ singleBranch: true,
67
+ author: {
68
+ name: 'hlx import',
69
+ },
70
+ });
71
+ this.log.info(`AEM Importer UI is up-to-date. v${await getUIVersion()}`);
72
+ }
73
+ }
74
+
75
+ async init() {
76
+ await super.init();
77
+
78
+ // init dev default file params
79
+ this._project = new HelixImportProject()
80
+ .withCwd(this.directory)
81
+ .withLogger(this._logger)
82
+ .withKill(this._kill);
83
+ this.log.info(chalk`{yellow ___ ________ ___ __}`);
84
+ this.log.info(chalk`{yellow / | / ____/ |/ / (_)___ ___ ____ ____ _____/ /____ _____}`);
85
+ this.log.info(chalk`{yellow / /| | / __/ / /|_/ / / / __ \`__ \\/ __ \\/ __ \\/ ___/ __/ _ \\/ ___/}`);
86
+ this.log.info(chalk`{yellow / ___ |/ /___/ / / / / / / / / / / /_/ / /_/ / / / /_/ __/ /}`);
87
+ this.log.info(chalk`{yellow /_/ |_/_____/_/ /_/ /_/_/ /_/ /_/ .___/\\____/_/ \\__/\\___/_/}`);
88
+ this.log.info(chalk`{yellow /_/ v${pkgJson.version}}`);
89
+ this.log.info('');
90
+
91
+ await this.initSeverOptions();
92
+
93
+ if (!this._skipUI) {
94
+ await this.setupImporterUI();
95
+ }
96
+
97
+ try {
98
+ await this._project.init();
99
+ } catch (e) {
100
+ throw Error(`Unable to start AEM: ${e.message}`);
101
+ }
102
+ }
103
+ }
package/src/import.js ADDED
@@ -0,0 +1,110 @@
1
+ /*
2
+ * Copyright 2018 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+ import path from 'path';
13
+ import { getOrCreateLogger } from './log-common.js';
14
+
15
+ export default function up() {
16
+ let executor;
17
+ return {
18
+ set executor(value) {
19
+ executor = value;
20
+ },
21
+ command: 'import',
22
+ description: 'Run the AEM import server',
23
+ builder: (yargs) => {
24
+ yargs
25
+ .option('open', {
26
+ describe: 'Open a browser window at specified path',
27
+ type: 'string',
28
+ default: '/tools/importer/helix-importer-ui/index.html',
29
+ })
30
+ .option('ui-repo', {
31
+ alias: 'uiRepo',
32
+ describe: 'Git repository for the AEM Importer UI',
33
+ type: 'string',
34
+ default: 'https://github.com/adobe/helix-importer-ui',
35
+ })
36
+ .option('skip-ui', {
37
+ alias: 'skipUI',
38
+ describe: 'Do not install the AEM Importer UI',
39
+ type: 'boolean',
40
+ default: false,
41
+ })
42
+ .option('no-open', {
43
+ // negation of the open option (resets open default)
44
+ // see https://github.com/yargs/yargs/blob/master/docs/tricks.md#negating-boolean-arguments
45
+ alias: 'noOpen',
46
+ describe: 'Disable automatic opening of browser window',
47
+ type: 'boolean',
48
+ })
49
+ .option('port', {
50
+ describe: 'Start import server on port',
51
+ type: 'int',
52
+ default: 3001,
53
+ })
54
+ .option('addr', {
55
+ describe: 'Bind import server on addr. use * to bind to any address and allow external connections.',
56
+ type: 'string',
57
+ default: '127.0.0.1',
58
+ })
59
+ .option('stop-other', {
60
+ alias: 'stopOther',
61
+ describe: 'Stop other AEM CLI running on the above port',
62
+ type: 'boolean',
63
+ default: true,
64
+ })
65
+ .option('tls-cert', {
66
+ alias: 'tlsCert',
67
+ describe: 'File location for your .pem file for local TLS support',
68
+ type: 'string',
69
+ default: undefined,
70
+ })
71
+ .option('tls-key', {
72
+ alias: 'tlsKey',
73
+ describe: 'File location for your .key file for local TLS support',
74
+ type: 'string',
75
+ default: undefined,
76
+ })
77
+ .group(['port', 'addr', 'stop-other', 'tls-cert', 'tls-key'], 'Server options')
78
+ .option('cache', {
79
+ describe: 'Path to local folder to cache the responses',
80
+ type: 'string',
81
+ })
82
+ .group(['open', 'no-open', 'cache', 'ui-repo', 'skip-ui'], 'AEM Importer Options')
83
+
84
+ .help();
85
+ },
86
+ handler: async (argv) => {
87
+ // codecov:ignore:start
88
+ /* c8 ignore start */
89
+ if (!executor) {
90
+ // eslint-disable-next-line global-require
91
+ const ImportCommand = (await import('./import.cmd.js')).default; // lazy load the handler to speed up execution time
92
+ executor = new ImportCommand(getOrCreateLogger(argv));
93
+ }
94
+ // codecov:ignore:end
95
+ /* c8 ignore end */
96
+ await executor
97
+ .withHttpPort(argv.port)
98
+ .withBindAddr(argv.addr)
99
+ // only open browser window when executable is `aem`
100
+ // this prevents the window to be opened during integration tests
101
+ .withOpen(path.basename(argv.$0) === 'aem' ? argv.open : false)
102
+ .withTLS(argv.tlsKey, argv.tlsCert)
103
+ .withKill(argv.stopOther)
104
+ .withCache(argv.cache)
105
+ .withSkipUI(argv.skipUI)
106
+ .withUIRepo(argv.uiRepo)
107
+ .run();
108
+ },
109
+ };
110
+ }