@backstage/repo-tools 0.6.0-next.1 → 0.6.0-next.3

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # @backstage/repo-tools
2
2
 
3
+ ## 0.6.0-next.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 60a68f1: Introduced `knip` to the `knip-reports` command, which generates a `knip-report.md` file for your packages with dependency warnings, if any.
8
+ - Updated dependencies
9
+ - @backstage/backend-common@0.21.0-next.3
10
+ - @backstage/cli-node@0.2.3-next.0
11
+ - @backstage/catalog-model@1.4.4-next.0
12
+ - @backstage/cli-common@0.1.13
13
+ - @backstage/errors@1.2.3
14
+
15
+ ## 0.6.0-next.2
16
+
17
+ ### Minor Changes
18
+
19
+ - 4c62935: **BREAKING**: The `schema openapi *` commands are now renamed into `package schema openapi *` and `repo schema openapi *`. The aim is to make it more clear what the command is operating on, the entire repo or just a single package.
20
+
21
+ The following commands now live under the `package` namespace,
22
+
23
+ - `schema openapi generate` is now `package schema openapi generate --server`
24
+ - `schema openapi generate-client` is now `package schema openapi generate --client-package`
25
+ - `schema openapi init` is now `package schema openapi init`
26
+
27
+ And these commands live under the new `repo` namespace,
28
+
29
+ - `schema openapi lint` is now `repo schema openapi lint`
30
+ - `schema openapi test` is now `repo schema openapi test`
31
+ - `schema openapi verify` is now `repo schema openapi verify`
32
+
33
+ The `package schema openapi generate` now supports defining both `--server` and `--client-package` to generate both at once.This update also reworks the `--client-package` flag to accept only an output directory as the input directory can now be inferred.
34
+
35
+ ### Patch Changes
36
+
37
+ - aa91cd6: Resolved an issue with generate-catalog-info where it was replacing upper case characters with -.
38
+ - Updated dependencies
39
+ - @backstage/backend-common@0.21.0-next.2
40
+ - @backstage/catalog-model@1.4.4-next.0
41
+ - @backstage/cli-common@0.1.13
42
+ - @backstage/cli-node@0.2.2
43
+ - @backstage/errors@1.2.3
44
+
3
45
  ## 0.6.0-next.1
4
46
 
5
47
  ### Patch Changes
@@ -2,7 +2,6 @@
2
2
 
3
3
  var lodash = require('lodash');
4
4
  var path = require('path');
5
- var child_process = require('child_process');
6
5
  var fs = require('fs-extra');
7
6
  var apiExtractor = require('@microsoft/api-extractor');
8
7
  var tsdoc = require('@microsoft/tsdoc');
@@ -16,6 +15,8 @@ var CustomMarkdownEmitter = require('@microsoft/api-documenter/lib/markdown/Cust
16
15
  var paths = require('./paths-9ab9b8a8.cjs.js');
17
16
  var minimatch = require('minimatch');
18
17
  var entryPoints = require('./entryPoints-c9b88245.cjs.js');
18
+ var util = require('./util-40303646.cjs.js');
19
+ var child_process = require('child_process');
19
20
  require('@backstage/cli-common');
20
21
  require('@backstage/cli-node');
21
22
 
@@ -207,10 +208,10 @@ function logApiReportInstructions() {
207
208
  "*************************************************************************************"
208
209
  );
209
210
  console.log(
210
- "* You have uncommitted changes to the public API of a package. *"
211
+ "* You have uncommitted changes to the public API or reports of a package. *"
211
212
  );
212
213
  console.log(
213
- "* To solve this, run `yarn build:api-reports` and commit all api-report.md changes. *"
214
+ "* To solve this, run `yarn build:api-reports` and commit all md file changes. *"
214
215
  );
215
216
  console.log(
216
217
  "*************************************************************************************"
@@ -921,30 +922,6 @@ async function categorizePackageDirs(packageDirs) {
921
922
  );
922
923
  return { tsPackageDirs, cliPackageDirs };
923
924
  }
924
- function createBinRunner(cwd, path) {
925
- return async (...command) => new Promise((resolve, reject) => {
926
- child_process.execFile(
927
- "node",
928
- [path, ...command],
929
- {
930
- cwd,
931
- shell: true,
932
- timeout: 6e4,
933
- maxBuffer: 1024 * 1024
934
- },
935
- (err, stdout, stderr) => {
936
- if (err) {
937
- reject(new Error(`${err.message}
938
- ${stderr}`));
939
- } else if (stderr) {
940
- reject(new Error(`Command printed error output: ${stderr}`));
941
- } else {
942
- resolve(stdout);
943
- }
944
- }
945
- );
946
- });
947
- }
948
925
  function parseHelpPage(helpPageContent) {
949
926
  var _a;
950
927
  const [, usage] = (_a = helpPageContent.match(/^\s*Usage: (.*)$/im)) != null ? _a : [];
@@ -1044,12 +1021,12 @@ async function runCliExtraction({
1044
1021
  }
1045
1022
  const models = new Array();
1046
1023
  if (typeof pkgJson.bin === "string") {
1047
- const run = createBinRunner(fullDir, pkgJson.bin);
1024
+ const run = util.createBinRunner(fullDir, pkgJson.bin);
1048
1025
  const helpPages = await exploreCliHelpPages(run);
1049
1026
  models.push({ name: path.basename(pkgJson.bin), helpPages });
1050
1027
  } else {
1051
1028
  for (const [name, path] of Object.entries(pkgJson.bin)) {
1052
- const run = createBinRunner(fullDir, path);
1029
+ const run = util.createBinRunner(fullDir, path);
1053
1030
  const helpPages = await exploreCliHelpPages(run);
1054
1031
  models.push({ name, helpPages });
1055
1032
  }
@@ -1178,4 +1155,4 @@ function parseArrayOption(value) {
1178
1155
  }
1179
1156
 
1180
1157
  exports.buildApiReports = buildApiReports;
1181
- //# sourceMappingURL=api-reports-143209ff.cjs.js.map
1158
+ //# sourceMappingURL=api-reports-ebc5b5dd.cjs.js.map
@@ -25,6 +25,12 @@ function isBackstagePackage(packageJson) {
25
25
  }
26
26
  const isRejected = (input) => input.status === "rejected";
27
27
  const isFulfilled = (input) => input.status === "fulfilled";
28
+ const safeEntityName = (packageName) => {
29
+ return packageName.replace(/^[^\w\s]|[^a-z0-9]$/g, "").replace(/[^A-Za-z0-9_\-.]+/g, "-").replace(
30
+ /([a-z])([A-Z])/g,
31
+ (_, a, b) => `${a}-${b.toLocaleLowerCase("en-US")}`
32
+ ).replace(/^(.)/, (_, a) => a.toLocaleLowerCase("en-US"));
33
+ };
28
34
 
29
35
  async function loadCodeowners() {
30
36
  const maybeFiles = await Promise.allSettled(
@@ -139,7 +145,7 @@ async function fixCatalogInfoYaml(options) {
139
145
  codeowners,
140
146
  path.relative(".", yamlPath)
141
147
  );
142
- const safeName = packageJson.name.replace(/[^a-z0-9_\-\.]+/g, "-").replace(/^[^a-z0-9]|[^a-z0-9]$/g, "");
148
+ const safeName = safeEntityName(packageJson.name);
143
149
  let yamlJson;
144
150
  try {
145
151
  yamlJson = YAML__default["default"].load(yamlString);
@@ -189,7 +195,7 @@ async function fixCatalogInfoYaml(options) {
189
195
  }
190
196
  function createOrMergeEntity(packageJson, owner, existingEntity = {}) {
191
197
  var _a;
192
- const safeEntityName = packageJson.name.replace(/[^a-z0-9_\-\.]+/g, "-").replace(/^[^a-z0-9]|[^a-z0-9]$/g, "");
198
+ const entityName = safeEntityName(packageJson.name);
193
199
  return {
194
200
  ...existingEntity,
195
201
  apiVersion: "backstage.io/v1alpha1",
@@ -197,7 +203,7 @@ function createOrMergeEntity(packageJson, owner, existingEntity = {}) {
197
203
  metadata: {
198
204
  ...existingEntity.metadata,
199
205
  // Provide default name/title/description values.
200
- name: safeEntityName,
206
+ name: entityName,
201
207
  title: packageJson.name,
202
208
  ...packageJson.description && !((_a = existingEntity.metadata) == null ? void 0 : _a.description) ? { description: packageJson.description } : void 0
203
209
  },
@@ -211,4 +217,4 @@ function createOrMergeEntity(packageJson, owner, existingEntity = {}) {
211
217
  }
212
218
 
213
219
  exports["default"] = generateCatalogInfo;
214
- //# sourceMappingURL=generate-catalog-info-c0260878.cjs.js.map
220
+ //# sourceMappingURL=generate-catalog-info-e7071c1c.cjs.js.map
@@ -1,5 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ var fs = require('fs-extra');
4
+ var paths = require('./paths-9ab9b8a8.cjs.js');
5
+ var path = require('path');
6
+
3
7
  const YAML_SCHEMA_PATH = "src/schema/openapi.yaml";
4
8
  const TS_MODULE = "src/schema/openapi.generated";
5
9
  const TS_SCHEMA_PATH = `${TS_MODULE}.ts`;
@@ -36,9 +40,31 @@ const OPENAPI_IGNORE_FILES = [
36
40
  "tsconfig.json"
37
41
  ];
38
42
 
43
+ const getPathToFile = async (directory, filename) => {
44
+ return path.resolve(directory, filename);
45
+ };
46
+ const getRelativePathToFile = async (filename) => {
47
+ return await getPathToFile(paths.paths.targetDir, filename);
48
+ };
49
+ const assertExists = async (path) => {
50
+ if (!await fs.pathExists(path)) {
51
+ throw new Error(`Could not find ${path}.`);
52
+ }
53
+ return path;
54
+ };
55
+ const getPathToOpenApiSpec = async (directory) => {
56
+ return await assertExists(await getPathToFile(directory, YAML_SCHEMA_PATH));
57
+ };
58
+ const getPathToCurrentOpenApiSpec = async () => {
59
+ return await assertExists(await getRelativePathToFile(YAML_SCHEMA_PATH));
60
+ };
61
+
39
62
  exports.OPENAPI_IGNORE_FILES = OPENAPI_IGNORE_FILES;
40
63
  exports.OUTPUT_PATH = OUTPUT_PATH;
41
64
  exports.TS_MODULE = TS_MODULE;
42
65
  exports.TS_SCHEMA_PATH = TS_SCHEMA_PATH;
43
66
  exports.YAML_SCHEMA_PATH = YAML_SCHEMA_PATH;
44
- //# sourceMappingURL=constants-10c5aa52.cjs.js.map
67
+ exports.getPathToCurrentOpenApiSpec = getPathToCurrentOpenApiSpec;
68
+ exports.getPathToOpenApiSpec = getPathToOpenApiSpec;
69
+ exports.getRelativePathToFile = getRelativePathToFile;
70
+ //# sourceMappingURL=helpers-712dfada.cjs.js.map
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+
3
+ var chalk = require('chalk');
4
+ var path = require('path');
5
+ var helpers = require('./helpers-712dfada.cjs.js');
6
+ var paths = require('./paths-9ab9b8a8.cjs.js');
7
+ var fs = require('fs-extra');
8
+ var exec$1 = require('./exec-7bf444eb.cjs.js');
9
+ var backendCommon = require('@backstage/backend-common');
10
+ var YAML = require('js-yaml');
11
+ var util = require('util');
12
+ var child_process = require('child_process');
13
+ require('@backstage/cli-common');
14
+ require('@backstage/cli-node');
15
+ require('minimatch');
16
+
17
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
18
+
19
+ var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
20
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
21
+ var YAML__default = /*#__PURE__*/_interopDefaultLegacy(YAML);
22
+
23
+ async function generate$1(outputDirectory) {
24
+ const resolvedOpenapiPath = await helpers.getPathToCurrentOpenApiSpec();
25
+ const resolvedOutputDirectory = paths.paths.resolveTargetRoot(
26
+ outputDirectory,
27
+ helpers.OUTPUT_PATH
28
+ );
29
+ fs.mkdirpSync(resolvedOutputDirectory);
30
+ await fs__default["default"].mkdirp(resolvedOutputDirectory);
31
+ await fs__default["default"].writeFile(
32
+ path.resolve(resolvedOutputDirectory, ".openapi-generator-ignore"),
33
+ helpers.OPENAPI_IGNORE_FILES.join("\n")
34
+ );
35
+ await exec$1.exec(
36
+ "node",
37
+ [
38
+ backendCommon.resolvePackagePath("@openapitools/openapi-generator-cli", "main.js"),
39
+ "generate",
40
+ "-i",
41
+ resolvedOpenapiPath,
42
+ "-o",
43
+ resolvedOutputDirectory,
44
+ "-g",
45
+ "typescript",
46
+ "-c",
47
+ backendCommon.resolvePackagePath(
48
+ "@backstage/repo-tools",
49
+ "templates/typescript-backstage.yaml"
50
+ ),
51
+ "--generator-key",
52
+ "v3.0"
53
+ ],
54
+ {
55
+ maxBuffer: Number.MAX_VALUE,
56
+ cwd: backendCommon.resolvePackagePath("@backstage/repo-tools"),
57
+ env: {
58
+ ...process.env
59
+ }
60
+ }
61
+ );
62
+ await exec$1.exec(
63
+ `yarn backstage-cli package lint --fix ${resolvedOutputDirectory}`
64
+ );
65
+ const prettier = paths.paths.resolveTargetRoot("node_modules/.bin/prettier");
66
+ if (prettier) {
67
+ await exec$1.exec(`${prettier} --write ${resolvedOutputDirectory}`);
68
+ }
69
+ fs__default["default"].removeSync(path.resolve(resolvedOutputDirectory, ".openapi-generator-ignore"));
70
+ fs__default["default"].rmSync(path.resolve(resolvedOutputDirectory, ".openapi-generator"), {
71
+ recursive: true,
72
+ force: true
73
+ });
74
+ }
75
+ async function command$2(outputPackage) {
76
+ try {
77
+ await generate$1(outputPackage);
78
+ console.log(
79
+ chalk__default["default"].green(`Generated client in ${outputPackage}/${helpers.OUTPUT_PATH}`)
80
+ );
81
+ } catch (err) {
82
+ console.log();
83
+ console.log(chalk__default["default"].red(`Client generation failed:`));
84
+ console.log(err);
85
+ process.exit(1);
86
+ }
87
+ }
88
+
89
+ const exec = util.promisify(child_process.exec);
90
+ async function generate() {
91
+ const openapiPath = await helpers.getPathToCurrentOpenApiSpec();
92
+ const yaml = YAML__default["default"].load(await fs__default["default"].readFile(openapiPath, "utf8"));
93
+ const tsPath = paths.paths.resolveTarget(helpers.TS_SCHEMA_PATH);
94
+ await fs__default["default"].writeFile(
95
+ tsPath,
96
+ `//
97
+
98
+ // ******************************************************************
99
+ // * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. *
100
+ // ******************************************************************
101
+ import {createValidatedOpenApiRouter} from '@backstage/backend-openapi-utils';
102
+ export const spec = ${JSON.stringify(yaml, null, 2)} as const;
103
+ export const createOpenApiRouter = async (
104
+ options?: Parameters<typeof createValidatedOpenApiRouter>['1'],
105
+ ) => createValidatedOpenApiRouter<typeof spec>(spec, options);
106
+ `
107
+ );
108
+ await exec(`yarn backstage-cli package lint --fix ${tsPath}`);
109
+ if (await paths.paths.resolveTargetRoot("node_modules/.bin/prettier")) {
110
+ await exec(`yarn prettier --write ${tsPath}`, {
111
+ cwd: paths.paths.targetRoot
112
+ });
113
+ }
114
+ }
115
+ async function command$1() {
116
+ try {
117
+ await generate();
118
+ console.log(chalk__default["default"].green("Generated all files."));
119
+ } catch (err) {
120
+ console.log(chalk__default["default"].red(`OpenAPI server stub generation failed.`));
121
+ console.log(err.message);
122
+ process.exit(1);
123
+ }
124
+ }
125
+
126
+ async function command(opts) {
127
+ if (!opts.clientPackage && !opts.server) {
128
+ console.log(
129
+ chalk__default["default"].red("Either --client-package or --server must be defined.")
130
+ );
131
+ process.exit(1);
132
+ }
133
+ if (opts.clientPackage) {
134
+ await command$2(opts.clientPackage);
135
+ }
136
+ if (opts.server) {
137
+ await command$1();
138
+ }
139
+ }
140
+
141
+ exports.command = command;
142
+ //# sourceMappingURL=index-c6ffc4f4.cjs.js.map
@@ -1,17 +1,14 @@
1
1
  'use strict';
2
2
 
3
3
  var fs = require('fs-extra');
4
- var path = require('path');
5
- var constants = require('./constants-10c5aa52.cjs.js');
4
+ var helpers = require('./helpers-712dfada.cjs.js');
6
5
  var paths = require('./paths-9ab9b8a8.cjs.js');
7
- var runner = require('./runner-0e5fc9a8.cjs.js');
8
6
  var chalk = require('chalk');
9
7
  var exec = require('./exec-7bf444eb.cjs.js');
8
+ require('path');
10
9
  require('@backstage/cli-common');
11
10
  require('@backstage/cli-node');
12
11
  require('minimatch');
13
- require('p-limit');
14
- require('portfinder');
15
12
  require('util');
16
13
  require('child_process');
17
14
 
@@ -24,14 +21,15 @@ const ROUTER_TEST_PATHS = [
24
21
  "src/service/router.test.ts",
25
22
  "src/service/createRouter.test.ts"
26
23
  ];
27
- async function init(directoryPath) {
28
- const openapiPath = path.join(directoryPath, constants.YAML_SCHEMA_PATH);
29
- if (!await fs__default["default"].pathExists(openapiPath)) {
24
+ async function init() {
25
+ try {
26
+ await helpers.getPathToCurrentOpenApiSpec();
27
+ } catch (err) {
30
28
  throw new Error(
31
- `You do not have an OpenAPI YAML file at ${openapiPath}. Please create one and retry this command. If you already have existing test cases for your router, see 'backstage-repo-tools schema openapi test --update'`
29
+ `OpenAPI.yaml not found in ${helpers.YAML_SCHEMA_PATH}. Please create one and retry this command.`
32
30
  );
33
31
  }
34
- const opticConfigFilePath = path.join(directoryPath, "optic.yml");
32
+ const opticConfigFilePath = await helpers.getRelativePathToFile("optic.yml");
35
33
  if (await fs__default["default"].pathExists(opticConfigFilePath)) {
36
34
  throw new Error(`This directory already has an optic.yml file. Exiting.`);
37
35
  }
@@ -40,9 +38,9 @@ async function init(directoryPath) {
40
38
  `ruleset:
41
39
  - breaking-changes
42
40
  capture:
43
- ${constants.YAML_SCHEMA_PATH}:
41
+ ${helpers.YAML_SCHEMA_PATH}:
44
42
  # \u{1F527} Runnable example with simple get requests.
45
- # Run with "PORT=3000 optic capture ${constants.YAML_SCHEMA_PATH} --update interactive" in '${directoryPath}'
43
+ # Run with "PORT=3000 optic capture ${helpers.YAML_SCHEMA_PATH} --update interactive" in '${paths.paths.targetDir}'
46
44
  # You can change the server and the 'requests' section to experiment
47
45
  server:
48
46
  # This will not be used by 'backstage-repo-tools schema openapi test', but may be useful for interactive updates.
@@ -60,27 +58,16 @@ capture:
60
58
  await exec.exec(`yarn prettier`, ["--write", opticConfigFilePath]);
61
59
  }
62
60
  }
63
- async function initCommand(paths = []) {
64
- const resultsList = await runner.runner(paths, (dir) => init(dir), {
65
- concurrencyLimit: 5
66
- });
67
- let failed = false;
68
- for (const { relativeDir, resultText } of resultsList) {
69
- if (resultText) {
70
- console.log();
71
- console.log(
72
- chalk__default["default"].red(`Failed to initialize ${relativeDir} for OpenAPI commands.`)
73
- );
74
- console.log(resultText.trimStart());
75
- failed = true;
76
- }
77
- }
78
- if (failed) {
61
+ async function singleCommand() {
62
+ try {
63
+ await init();
64
+ console.log(chalk__default["default"].green(`Successfully configured.`));
65
+ } catch (err) {
66
+ console.log(chalk__default["default"].red(`OpenAPI tooling initialization failed.`));
67
+ console.log(err.message);
79
68
  process.exit(1);
80
- } else {
81
- console.log(chalk__default["default"].green(`All directories have already been configured.`));
82
69
  }
83
70
  }
84
71
 
85
- exports["default"] = initCommand;
86
- //# sourceMappingURL=init-1a079f00.cjs.js.map
72
+ exports.singleCommand = singleCommand;
73
+ //# sourceMappingURL=init-3d29e55d.cjs.js.map
@@ -0,0 +1,185 @@
1
+ 'use strict';
2
+
3
+ var paths = require('./paths-9ab9b8a8.cjs.js');
4
+ var pLimit = require('p-limit');
5
+ var os = require('os');
6
+ var path = require('path');
7
+ var fs = require('fs-extra');
8
+ var util = require('./util-40303646.cjs.js');
9
+ require('@backstage/cli-common');
10
+ require('@backstage/cli-node');
11
+ require('minimatch');
12
+ require('child_process');
13
+
14
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15
+
16
+ var pLimit__default = /*#__PURE__*/_interopDefaultLegacy(pLimit);
17
+ var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
18
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
19
+
20
+ const ignoredPackages = ["packages/techdocs-cli-embedded-app"];
21
+ function logKnipReportInstructions() {
22
+ console.log("");
23
+ console.log(
24
+ "*************************************************************************************"
25
+ );
26
+ console.log(
27
+ "* You have uncommitted changes to the knip reports of a package. *"
28
+ );
29
+ console.log(
30
+ "* To solve this, run `yarn build:knip-reports` and commit all md file changes. *"
31
+ );
32
+ console.log(
33
+ "*************************************************************************************"
34
+ );
35
+ console.log("");
36
+ }
37
+ async function generateKnipConfig({ packageDir }) {
38
+ const knipConfig = {
39
+ entry: [
40
+ "dev/index.{ts,tsx}",
41
+ "src/index.{ts,tsx}",
42
+ "src/alpha.{ts,tsx}",
43
+ "src/routes.ts",
44
+ "src/run.ts"
45
+ ],
46
+ jest: {
47
+ entry: ["src/setupTests.ts", "**/*.test.{ts,tsx}"]
48
+ },
49
+ storybook: { entry: "src/components/**/*.stories.tsx" },
50
+ ignore: [
51
+ ".eslintrc.js",
52
+ "config.d.ts",
53
+ "knexfile.js",
54
+ "node_modules/**",
55
+ "dist/**",
56
+ "{fixtures,migrations,templates}/**"
57
+ ],
58
+ ignoreDependencies: [
59
+ "@backstage/cli",
60
+ // everything depends on this for its package.json commands
61
+ "@backstage/theme"
62
+ // this uses `declare module` in .d.ts so is implicitly used whenever extensions are needed
63
+ ]
64
+ };
65
+ await fs__default["default"].writeFile(
66
+ `${packageDir}/knip.json`,
67
+ JSON.stringify(knipConfig, null, 2)
68
+ );
69
+ }
70
+ function cleanKnipConfig({ packageDir }) {
71
+ if (fs__default["default"].existsSync(`${packageDir}/knip.json`)) {
72
+ fs__default["default"].rmSync(`${packageDir}/knip.json`);
73
+ }
74
+ }
75
+ async function handlePackage({
76
+ packageDir,
77
+ knipDir,
78
+ isLocalBuild
79
+ }) {
80
+ console.log(`## Processing ${packageDir}`);
81
+ if (ignoredPackages.includes(packageDir)) {
82
+ console.log(`Skipping ${packageDir}`);
83
+ return;
84
+ }
85
+ const fullDir = paths.paths.resolveTargetRoot(packageDir);
86
+ const reportPath = path.resolve(fullDir, "knip-report.md");
87
+ const run = util.createBinRunner(fullDir, "");
88
+ await generateKnipConfig({ packageDir: fullDir });
89
+ const report = await run(
90
+ `${knipDir}/knip.js`,
91
+ `--directory ${fullDir}`,
92
+ // Run in the package directory
93
+ "--config knip.json",
94
+ "--no-exit-code",
95
+ // Removing this will end the process in case there are findings by knip
96
+ "--no-progress",
97
+ // Remove unnecessary debugging from output
98
+ // TODO: Add more checks when dependencies start to look ok, see https://knip.dev/reference/cli#--include
99
+ "--include dependencies,unlisted",
100
+ "--reporter markdown"
101
+ );
102
+ cleanKnipConfig({ packageDir: fullDir });
103
+ const existingReport = await fs__default["default"].readFile(reportPath, "utf8").catch((error) => {
104
+ if (error.code === "ENOENT") {
105
+ return void 0;
106
+ }
107
+ throw error;
108
+ });
109
+ if (existingReport !== report) {
110
+ if (isLocalBuild) {
111
+ console.warn(`Knip report changed for ${packageDir}`);
112
+ await fs__default["default"].writeFile(reportPath, report);
113
+ } else {
114
+ logKnipReportInstructions();
115
+ if (existingReport) {
116
+ console.log("");
117
+ console.log(
118
+ `The conflicting file is ${path.relative(
119
+ paths.paths.targetRoot,
120
+ reportPath
121
+ )}, expecting the following content:`
122
+ );
123
+ console.log("");
124
+ console.log(report);
125
+ logKnipReportInstructions();
126
+ }
127
+ throw new Error(`Knip report changed for ${packageDir}, `);
128
+ }
129
+ }
130
+ }
131
+ async function runKnipReports({
132
+ packageDirs,
133
+ isLocalBuild
134
+ }) {
135
+ const knipDir = paths.paths.resolveTargetRoot("./node_modules/knip/bin/");
136
+ const limiter = pLimit__default["default"](os__default["default"].cpus().length);
137
+ try {
138
+ await Promise.all(
139
+ packageDirs.map(
140
+ (packageDir) => limiter(
141
+ async () => handlePackage({ packageDir, knipDir, isLocalBuild })
142
+ )
143
+ )
144
+ );
145
+ } catch (e) {
146
+ console.log(
147
+ `Error occurred during knip reporting: ${e}, cleaning knip configs`
148
+ );
149
+ packageDirs.map((packageDir) => {
150
+ const fullDir = paths.paths.resolveTargetRoot(packageDir);
151
+ cleanKnipConfig({ packageDir: fullDir });
152
+ });
153
+ }
154
+ }
155
+
156
+ const buildKnipReports = async (paths$1 = [], opts) => {
157
+ const isCiBuild = opts.ci;
158
+ const isAllPackages = !(paths$1 == null ? void 0 : paths$1.length);
159
+ const selectedPackageDirs = await paths.resolvePackagePaths({
160
+ paths: paths$1,
161
+ include: opts.include,
162
+ exclude: opts.exclude
163
+ });
164
+ if (isAllPackages && !isCiBuild) {
165
+ console.log("");
166
+ console.log(
167
+ "TIP: You can generate knip-reports for select packages by passing package paths:"
168
+ );
169
+ console.log("");
170
+ console.log(
171
+ " yarn build:knip-reports packages/config packages/core-plugin-api plugins/*"
172
+ );
173
+ console.log("");
174
+ }
175
+ if (selectedPackageDirs.length > 0) {
176
+ console.log("# Generating package knip reports");
177
+ await runKnipReports({
178
+ packageDirs: selectedPackageDirs,
179
+ isLocalBuild: !isCiBuild
180
+ });
181
+ }
182
+ };
183
+
184
+ exports.buildKnipReports = buildKnipReports;
185
+ //# sourceMappingURL=knip-reports-1871d475.cjs.js.map
@@ -5,16 +5,16 @@ var spectralParsers = require('@stoplight/spectral-parsers');
5
5
  var ruleset = require('@apisyouwonthate/style-guide');
6
6
  var fs = require('fs-extra');
7
7
  var chalk = require('chalk');
8
- var path = require('path');
9
- var runner = require('./runner-0e5fc9a8.cjs.js');
10
- var constants = require('./constants-10c5aa52.cjs.js');
8
+ var runner = require('./runner-d5b73286.cjs.js');
11
9
  var spectralRulesets = require('@stoplight/spectral-rulesets');
12
10
  var types = require('@stoplight/types');
13
11
  var spectralFormatters = require('@stoplight/spectral-formatters');
12
+ var helpers = require('./helpers-712dfada.cjs.js');
14
13
  require('./paths-9ab9b8a8.cjs.js');
15
14
  require('@backstage/cli-common');
16
15
  require('@backstage/cli-node');
17
16
  require('minimatch');
17
+ require('path');
18
18
  require('p-limit');
19
19
  require('portfinder');
20
20
 
@@ -25,13 +25,12 @@ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
25
25
  var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
26
26
 
27
27
  async function lint(directoryPath, config) {
28
- const { skipMissingYamlFile, strict } = config != null ? config : {};
29
- const openapiPath = path.resolve(directoryPath, constants.YAML_SCHEMA_PATH);
30
- if (!await fs__default["default"].pathExists(openapiPath)) {
31
- if (skipMissingYamlFile) {
32
- return;
33
- }
34
- throw new Error(`Could not find a file at ${openapiPath}.`);
28
+ const { strict } = config != null ? config : {};
29
+ let openapiPath = "";
30
+ try {
31
+ openapiPath = await helpers.getPathToOpenApiSpec(directoryPath);
32
+ } catch {
33
+ return;
35
34
  }
36
35
  const openapiFileContent = await fs__default["default"].readFile(openapiPath, "utf8");
37
36
  const document = new spectralCore.Document(openapiFileContent, spectralParsers.Yaml, openapiPath);
@@ -72,7 +71,7 @@ async function lint(directoryPath, config) {
72
71
  async function bulkCommand(paths = [], options) {
73
72
  const resultsList = await runner.runner(
74
73
  paths,
75
- (dir) => lint(dir, { skipMissingYamlFile: true, strict: !!options.strict })
74
+ (dir) => lint(dir, { strict: !!options.strict })
76
75
  );
77
76
  let failed = false;
78
77
  for (const { relativeDir, resultText } of resultsList) {
@@ -93,4 +92,4 @@ async function bulkCommand(paths = [], options) {
93
92
  }
94
93
 
95
94
  exports.bulkCommand = bulkCommand;
96
- //# sourceMappingURL=lint-4f8f9fee.cjs.js.map
95
+ //# sourceMappingURL=lint-5433166f.cjs.js.map
@@ -46,4 +46,4 @@ async function runner(paths$1, command, options) {
46
46
  }
47
47
 
48
48
  exports.runner = runner;
49
- //# sourceMappingURL=runner-0e5fc9a8.cjs.js.map
49
+ //# sourceMappingURL=runner-d5b73286.cjs.js.map
@@ -3,8 +3,8 @@
3
3
  var fs = require('fs-extra');
4
4
  var path = require('path');
5
5
  var chalk = require('chalk');
6
- var runner = require('./runner-0e5fc9a8.cjs.js');
7
- var constants = require('./constants-10c5aa52.cjs.js');
6
+ var runner = require('./runner-d5b73286.cjs.js');
7
+ var helpers = require('./helpers-712dfada.cjs.js');
8
8
  var paths = require('./paths-9ab9b8a8.cjs.js');
9
9
  var exec = require('./exec-7bf444eb.cjs.js');
10
10
  require('p-limit');
@@ -21,8 +21,10 @@ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
21
21
  var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
22
22
 
23
23
  async function test(directoryPath, { port }, options) {
24
- const openapiPath = path.join(directoryPath, constants.YAML_SCHEMA_PATH);
25
- if (!await fs__default["default"].pathExists(openapiPath)) {
24
+ let openapiPath = path.join(directoryPath, helpers.YAML_SCHEMA_PATH);
25
+ try {
26
+ openapiPath = await helpers.getPathToOpenApiSpec(directoryPath);
27
+ } catch {
26
28
  return;
27
29
  }
28
30
  const opticConfigFilePath = path.join(directoryPath, "optic.yml");
@@ -41,7 +43,7 @@ async function test(directoryPath, { port }, options) {
41
43
  await exec.exec(
42
44
  `${opticLocation.trim()} capture`,
43
45
  [
44
- constants.YAML_SCHEMA_PATH,
46
+ helpers.YAML_SCHEMA_PATH,
45
47
  "--server-override",
46
48
  `http://localhost:${port}`,
47
49
  (options == null ? void 0 : options.update) ? "--update" : ""
@@ -93,4 +95,4 @@ async function bulkCommand(paths = [], options) {
93
95
  }
94
96
 
95
97
  exports.bulkCommand = bulkCommand;
96
- //# sourceMappingURL=index-33bf032f.cjs.js.map
98
+ //# sourceMappingURL=test-df73bb76.cjs.js.map
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ var child_process = require('child_process');
4
+
5
+ function createBinRunner(cwd, path) {
6
+ return async (...command) => new Promise((resolve, reject) => {
7
+ child_process.execFile(
8
+ "node",
9
+ [path, ...command],
10
+ {
11
+ cwd,
12
+ shell: true,
13
+ timeout: 6e4,
14
+ maxBuffer: 1024 * 1024
15
+ },
16
+ (err, stdout, stderr) => {
17
+ if (err) {
18
+ reject(new Error(`${err.message}
19
+ ${stderr}`));
20
+ } else if (stderr) {
21
+ reject(new Error(`Command printed error output: ${stderr}`));
22
+ } else {
23
+ resolve(stdout);
24
+ }
25
+ }
26
+ );
27
+ });
28
+ }
29
+
30
+ exports.createBinRunner = createBinRunner;
31
+ //# sourceMappingURL=util-40303646.cjs.js.map
@@ -6,9 +6,9 @@ var lodash = require('lodash');
6
6
  var path = require('path');
7
7
  var chalk = require('chalk');
8
8
  var Parser = require('@apidevtools/swagger-parser');
9
- var runner = require('./runner-0e5fc9a8.cjs.js');
9
+ var runner = require('./runner-d5b73286.cjs.js');
10
10
  var paths = require('./paths-9ab9b8a8.cjs.js');
11
- var constants = require('./constants-10c5aa52.cjs.js');
11
+ var helpers = require('./helpers-712dfada.cjs.js');
12
12
  require('p-limit');
13
13
  require('portfinder');
14
14
  require('@backstage/cli-common');
@@ -41,24 +41,26 @@ var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
41
41
  var Parser__default = /*#__PURE__*/_interopDefaultLegacy(Parser);
42
42
 
43
43
  async function verify(directoryPath) {
44
- const openapiPath = path.join(directoryPath, constants.YAML_SCHEMA_PATH);
45
- if (!await fs__default["default"].pathExists(openapiPath)) {
44
+ let openapiPath = "";
45
+ try {
46
+ openapiPath = await helpers.getPathToOpenApiSpec(directoryPath);
47
+ } catch {
46
48
  return;
47
49
  }
48
50
  const yaml = YAML__default["default"].load(await fs__default["default"].readFile(openapiPath, "utf8"));
49
51
  await Parser__default["default"].validate(lodash.cloneDeep(yaml));
50
- const schemaPath = path.join(directoryPath, constants.TS_SCHEMA_PATH);
52
+ const schemaPath = path.join(directoryPath, helpers.TS_SCHEMA_PATH);
51
53
  if (!await fs__default["default"].pathExists(schemaPath)) {
52
- throw new Error(`No \`${constants.TS_SCHEMA_PATH}\` file found.`);
54
+ throw new Error(`No \`${helpers.TS_SCHEMA_PATH}\` file found.`);
53
55
  }
54
- const schema = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path.resolve(path.join(directoryPath, constants.TS_MODULE)));
56
+ const schema = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path.resolve(path.join(directoryPath, helpers.TS_MODULE)));
55
57
  if (!schema.spec) {
56
- throw new Error(`\`${constants.TS_SCHEMA_PATH}\` needs to have a 'spec' export.`);
58
+ throw new Error(`\`${helpers.TS_SCHEMA_PATH}\` needs to have a 'spec' export.`);
57
59
  }
58
60
  if (!lodash.isEqual(schema.spec, yaml)) {
59
61
  const path$1 = path.relative(paths.paths.targetRoot, directoryPath);
60
62
  throw new Error(
61
- `\`${constants.YAML_SCHEMA_PATH}\` and \`${constants.TS_SCHEMA_PATH}\` do not match. Please run \`yarn backstage-repo-tools schema openapi generate ${path$1}\` to regenerate \`${constants.TS_SCHEMA_PATH}\`.`
63
+ `\`${helpers.YAML_SCHEMA_PATH}\` and \`${helpers.TS_SCHEMA_PATH}\` do not match. Please run \`yarn backstage-repo-tools package schema openapi generate\` from '${path$1}' to regenerate \`${helpers.TS_SCHEMA_PATH}\`.`
62
64
  );
63
65
  }
64
66
  }
@@ -81,4 +83,4 @@ async function bulkCommand(paths = []) {
81
83
  }
82
84
 
83
85
  exports.bulkCommand = bulkCommand;
84
- //# sourceMappingURL=verify-8c205e6a.cjs.js.map
86
+ //# sourceMappingURL=verify-dad6101f.cjs.js.map
package/dist/index.cjs.js CHANGED
@@ -44,29 +44,49 @@ ${chalk__default["default"].red(`${error}`)}
44
44
  }
45
45
  }
46
46
 
47
- function registerSchemaCommand(program) {
48
- const command = program.command("schema [command]").description("Various tools for working with API schema");
49
- const openApiCommand = command.command("openapi [command]").description("Tooling for OpenApi schema");
50
- openApiCommand.command("verify [paths...]").description(
51
- "Verify that all OpenAPI schemas are valid and have a matching `schemas/openapi.generated.ts` file."
47
+ function registerPackageCommand(program) {
48
+ const command = program.command("package [command]").description("Various tools for working with specific packages.");
49
+ const schemaCommand = command.command("schema [command]").description(
50
+ "Various tools for working with specific packages' API schema"
51
+ );
52
+ const openApiCommand = schemaCommand.command("openapi [command]").description("Tooling for OpenAPI schema");
53
+ openApiCommand.command("init").description(
54
+ "Initialize any required files to use the OpenAPI tooling for this package."
52
55
  ).action(
53
- lazy(() => Promise.resolve().then(function () { return require('./cjs/verify-8c205e6a.cjs.js'); }).then((m) => m.bulkCommand))
56
+ lazy(
57
+ () => Promise.resolve().then(function () { return require('./cjs/init-3d29e55d.cjs.js'); }).then((m) => m.singleCommand)
58
+ )
54
59
  );
55
- openApiCommand.command("generate [paths...]").description(
56
- "Generates a Typescript file from an OpenAPI yaml spec. For use with the `@backstage/backend-openapi-utils` ApiRouter type."
60
+ openApiCommand.command("generate").option(
61
+ "--client-package [package]",
62
+ "Top-level path to where the client should be generated, ie packages/catalog-client."
63
+ ).option("--server").description(
64
+ "Command to generate a client and/or a server stub from an OpenAPI spec."
57
65
  ).action(
58
- lazy(() => Promise.resolve().then(function () { return require('./cjs/generate-55ff9dff.cjs.js'); }).then((m) => m.bulkCommand))
66
+ lazy(
67
+ () => Promise.resolve().then(function () { return require('./cjs/index-c6ffc4f4.cjs.js'); }).then((m) => m.command)
68
+ )
69
+ );
70
+ }
71
+ function registerRepoCommand(program) {
72
+ const command = program.command("repo [command]").description("Tools for working across your entire repository.");
73
+ const schemaCommand = command.command("schema [command]").description("Various tools for working with API schema");
74
+ const openApiCommand = schemaCommand.command("openapi [command]").description("Tooling for OpenApi schema");
75
+ openApiCommand.command("verify [paths...]").description(
76
+ "Verify that all OpenAPI schemas are valid and have a matching `schemas/openapi.generated.ts` file."
77
+ ).action(
78
+ lazy(
79
+ () => Promise.resolve().then(function () { return require('./cjs/verify-dad6101f.cjs.js'); }).then((m) => m.bulkCommand)
80
+ )
59
81
  );
60
82
  openApiCommand.command("lint [paths...]").description("Lint OpenAPI schemas.").option(
61
83
  "--strict",
62
84
  "Fail on any linting severity messages, not just errors."
63
- ).action(lazy(() => Promise.resolve().then(function () { return require('./cjs/lint-4f8f9fee.cjs.js'); }).then((m) => m.bulkCommand)));
64
- openApiCommand.command("test [paths...]").description("Test OpenAPI schemas against written tests").option("--update", "Update the spec on failure.").action(lazy(() => Promise.resolve().then(function () { return require('./cjs/index-33bf032f.cjs.js'); }).then((m) => m.bulkCommand)));
65
- openApiCommand.command("init <paths...>").description("Creates any config needed for the test command.").action(lazy(() => Promise.resolve().then(function () { return require('./cjs/init-1a079f00.cjs.js'); }).then((m) => m.default)));
66
- openApiCommand.command("generate-client").requiredOption("--input-spec <file>").requiredOption("--output-directory <directory>").action(
67
- lazy(
68
- () => Promise.resolve().then(function () { return require('./cjs/generate-4e227b44.cjs.js'); }).then((m) => m.singleCommand)
69
- )
85
+ ).action(
86
+ lazy(() => Promise.resolve().then(function () { return require('./cjs/lint-5433166f.cjs.js'); }).then((m) => m.bulkCommand))
87
+ );
88
+ openApiCommand.command("test [paths...]").description("Test OpenAPI schemas against written tests").option("--update", "Update the spec on failure.").action(
89
+ lazy(() => Promise.resolve().then(function () { return require('./cjs/test-df73bb76.cjs.js'); }).then((m) => m.bulkCommand))
70
90
  );
71
91
  }
72
92
  function registerCommands(program) {
@@ -93,7 +113,7 @@ function registerCommands(program) {
93
113
  "Turn on release tag validation for the public, beta, and alpha APIs"
94
114
  ).description("Generate an API report for selected packages").action(
95
115
  lazy(
96
- () => Promise.resolve().then(function () { return require('./cjs/api-reports-143209ff.cjs.js'); }).then((m) => m.buildApiReports)
116
+ () => Promise.resolve().then(function () { return require('./cjs/api-reports-ebc5b5dd.cjs.js'); }).then((m) => m.buildApiReports)
97
117
  )
98
118
  );
99
119
  program.command("type-deps").description("Find inconsistencies in types of all packages and plugins").action(lazy(() => Promise.resolve().then(function () { return require('./cjs/type-deps-5eacd931.cjs.js'); }).then((m) => m.default)));
@@ -105,12 +125,18 @@ function registerCommands(program) {
105
125
  "CI run checks that there are no changes to catalog-info.yaml files"
106
126
  ).description("Create or fix info yaml files for all backstage packages").action(
107
127
  lazy(
108
- () => Promise.resolve().then(function () { return require('./cjs/generate-catalog-info-c0260878.cjs.js'); }).then(
128
+ () => Promise.resolve().then(function () { return require('./cjs/generate-catalog-info-e7071c1c.cjs.js'); }).then(
109
129
  (m) => m.default
110
130
  )
111
131
  )
112
132
  );
113
- registerSchemaCommand(program);
133
+ program.command("knip-reports [paths...]").option("--ci", "CI run checks that there is no changes on knip reports").description("Generate a knip report for selected packages").action(
134
+ lazy(
135
+ () => Promise.resolve().then(function () { return require('./cjs/knip-reports-1871d475.cjs.js'); }).then((m) => m.buildKnipReports)
136
+ )
137
+ );
138
+ registerPackageCommand(program);
139
+ registerRepoCommand(program);
114
140
  }
115
141
  function lazy(getActionFunc) {
116
142
  return async (...args) => {
@@ -125,7 +151,7 @@ function lazy(getActionFunc) {
125
151
  };
126
152
  }
127
153
 
128
- var version = "0.6.0-next.1";
154
+ var version = "0.6.0-next.3";
129
155
 
130
156
  const main = (argv) => {
131
157
  commander.program.name("backstage-repo-tools").version(version);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@backstage/repo-tools",
3
3
  "description": "CLI for Backstage repo tooling ",
4
- "version": "0.6.0-next.1",
4
+ "version": "0.6.0-next.3",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -32,10 +32,10 @@
32
32
  "dependencies": {
33
33
  "@apidevtools/swagger-parser": "^10.1.0",
34
34
  "@apisyouwonthate/style-guide": "^1.4.0",
35
- "@backstage/backend-common": "^0.21.0-next.1",
35
+ "@backstage/backend-common": "^0.21.0-next.3",
36
36
  "@backstage/catalog-model": "^1.4.4-next.0",
37
37
  "@backstage/cli-common": "^0.1.13",
38
- "@backstage/cli-node": "^0.2.2",
38
+ "@backstage/cli-node": "^0.2.3-next.0",
39
39
  "@backstage/errors": "^1.2.3",
40
40
  "@manypkg/get-packages": "^1.1.3",
41
41
  "@microsoft/api-documenter": "^7.22.33",
@@ -63,8 +63,8 @@
63
63
  "yaml-diff-patch": "^2.0.0"
64
64
  },
65
65
  "devDependencies": {
66
- "@backstage/backend-test-utils": "^0.3.0-next.1",
67
- "@backstage/cli": "^0.25.2-next.1",
66
+ "@backstage/backend-test-utils": "^0.3.0-next.3",
67
+ "@backstage/cli": "^0.25.2-next.3",
68
68
  "@backstage/types": "^1.1.1",
69
69
  "@types/is-glob": "^4.0.2",
70
70
  "@types/node": "^18.17.8",
@@ -1,86 +0,0 @@
1
- 'use strict';
2
-
3
- var chalk = require('chalk');
4
- var path = require('path');
5
- var constants = require('./constants-10c5aa52.cjs.js');
6
- var paths = require('./paths-9ab9b8a8.cjs.js');
7
- var fs = require('fs-extra');
8
- var exec = require('./exec-7bf444eb.cjs.js');
9
- var backendCommon = require('@backstage/backend-common');
10
- require('@backstage/cli-common');
11
- require('@backstage/cli-node');
12
- require('minimatch');
13
- require('util');
14
- require('child_process');
15
-
16
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
17
-
18
- var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
19
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
20
-
21
- async function generate(spec, outputDirectory) {
22
- const resolvedOpenapiPath = path.resolve(spec);
23
- const resolvedOutputDirectory = path.resolve(outputDirectory, constants.OUTPUT_PATH);
24
- fs.mkdirpSync(resolvedOutputDirectory);
25
- await fs__default["default"].mkdirp(resolvedOutputDirectory);
26
- await fs__default["default"].writeFile(
27
- path.resolve(resolvedOutputDirectory, ".openapi-generator-ignore"),
28
- constants.OPENAPI_IGNORE_FILES.join("\n")
29
- );
30
- await exec.exec(
31
- "node",
32
- [
33
- backendCommon.resolvePackagePath("@openapitools/openapi-generator-cli", "main.js"),
34
- "generate",
35
- "-i",
36
- resolvedOpenapiPath,
37
- "-o",
38
- resolvedOutputDirectory,
39
- "-g",
40
- "typescript",
41
- "-c",
42
- backendCommon.resolvePackagePath(
43
- "@backstage/repo-tools",
44
- "templates/typescript-backstage.yaml"
45
- ),
46
- "--generator-key",
47
- "v3.0"
48
- ],
49
- {
50
- maxBuffer: Number.MAX_VALUE,
51
- cwd: backendCommon.resolvePackagePath("@backstage/repo-tools"),
52
- env: {
53
- ...process.env
54
- }
55
- }
56
- );
57
- await exec.exec(
58
- `yarn backstage-cli package lint --fix ${resolvedOutputDirectory}`
59
- );
60
- const prettier = paths.paths.resolveTargetRoot("node_modules/.bin/prettier");
61
- if (prettier) {
62
- await exec.exec(`${prettier} --write ${resolvedOutputDirectory}`);
63
- }
64
- fs__default["default"].removeSync(path.resolve(resolvedOutputDirectory, ".openapi-generator-ignore"));
65
- fs__default["default"].rmSync(path.resolve(resolvedOutputDirectory, ".openapi-generator"), {
66
- recursive: true,
67
- force: true
68
- });
69
- }
70
- async function singleCommand({
71
- inputSpec,
72
- outputDirectory
73
- }) {
74
- try {
75
- await generate(inputSpec, outputDirectory);
76
- console.log(chalk__default["default"].green(`Generated client for ${inputSpec}`));
77
- } catch (err) {
78
- console.log();
79
- console.log(chalk__default["default"].red(`Client generation failed in ${outputDirectory}:`));
80
- console.log(err);
81
- process.exit(1);
82
- }
83
- }
84
-
85
- exports.singleCommand = singleCommand;
86
- //# sourceMappingURL=generate-4e227b44.cjs.js.map
@@ -1,81 +0,0 @@
1
- 'use strict';
2
-
3
- var fs = require('fs-extra');
4
- var YAML = require('js-yaml');
5
- var chalk = require('chalk');
6
- var path = require('path');
7
- var paths = require('./paths-9ab9b8a8.cjs.js');
8
- var runner = require('./runner-0e5fc9a8.cjs.js');
9
- var constants = require('./constants-10c5aa52.cjs.js');
10
- var util = require('util');
11
- var child_process = require('child_process');
12
- require('@backstage/cli-common');
13
- require('@backstage/cli-node');
14
- require('minimatch');
15
- require('p-limit');
16
- require('portfinder');
17
-
18
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
19
-
20
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
21
- var YAML__default = /*#__PURE__*/_interopDefaultLegacy(YAML);
22
- var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
23
-
24
- const exec = util.promisify(child_process.exec);
25
- async function generate(directoryPath, config) {
26
- const { skipMissingYamlFile } = config != null ? config : {};
27
- const openapiPath = path.resolve(directoryPath, constants.YAML_SCHEMA_PATH);
28
- if (!await fs__default["default"].pathExists(openapiPath)) {
29
- if (skipMissingYamlFile) {
30
- return;
31
- }
32
- throw new Error(`Could not find ${constants.YAML_SCHEMA_PATH} in root of directory.`);
33
- }
34
- const yaml = YAML__default["default"].load(await fs__default["default"].readFile(openapiPath, "utf8"));
35
- const tsPath = path.resolve(directoryPath, constants.TS_SCHEMA_PATH);
36
- await fs__default["default"].writeFile(
37
- tsPath,
38
- `//
39
-
40
- // ******************************************************************
41
- // * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. *
42
- // ******************************************************************
43
- import {createValidatedOpenApiRouter} from '@backstage/backend-openapi-utils';
44
- export const spec = ${JSON.stringify(yaml, null, 2)} as const;
45
- export const createOpenApiRouter = async (
46
- options?: Parameters<typeof createValidatedOpenApiRouter>['1'],
47
- ) => createValidatedOpenApiRouter<typeof spec>(spec, options);
48
- `
49
- );
50
- await exec(`yarn backstage-cli package lint --fix ${tsPath}`);
51
- if (await paths.paths.resolveTargetRoot("node_modules/.bin/prettier")) {
52
- await exec(`yarn prettier --write ${tsPath}`);
53
- }
54
- }
55
- async function bulkCommand(paths = []) {
56
- const resultsList = await runner.runner(
57
- paths,
58
- (dir) => generate(dir, { skipMissingYamlFile: true })
59
- );
60
- let failed = false;
61
- for (const { relativeDir, resultText } of resultsList) {
62
- if (resultText) {
63
- console.log();
64
- console.log(
65
- chalk__default["default"].red(
66
- `OpenAPI yaml to Typescript generation failed in ${relativeDir}:`
67
- )
68
- );
69
- console.log(resultText.trimStart());
70
- failed = true;
71
- }
72
- }
73
- if (failed) {
74
- process.exit(1);
75
- } else {
76
- console.log(chalk__default["default"].green("Generated all files."));
77
- }
78
- }
79
-
80
- exports.bulkCommand = bulkCommand;
81
- //# sourceMappingURL=generate-55ff9dff.cjs.js.map