@spyglassmc/mcdoc-cli 0.1.6 → 0.1.7

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.
Files changed (2) hide show
  1. package/lib/index.js +31 -154
  2. package/package.json +5 -3
package/lib/index.js CHANGED
@@ -1,22 +1,17 @@
1
1
  #!/usr/bin/env -S node
2
- import { dirname, join, parse, resolve } from 'path';
2
+ import { dirname, join, resolve } from 'path';
3
3
  import { fileURLToPath, pathToFileURL } from 'url';
4
4
  import fs from 'fs-extra';
5
5
  import walk from 'klaw';
6
- import lineColumn from 'line-column';
7
6
  import yargs from 'yargs';
8
7
  import { hideBin } from 'yargs/helpers';
9
8
  import { ConfigService, fileUtil, Service, VanillaConfig, } from '@spyglassmc/core';
10
9
  import { NodeJsExternals } from '@spyglassmc/core/lib/nodejs.js';
11
10
  import * as mcdoc from '@spyglassmc/mcdoc';
12
- const parentPath = dirname(fileURLToPath(import.meta.url));
13
- const cacheRoot = join(parentPath, 'cache');
11
+ import { generate } from './generate/index.js';
12
+ import { update_locales } from './update_locales/index.js';
13
+ const cache_root = join(dirname(fileURLToPath(import.meta.url)), 'cache');
14
14
  const CLI = yargs(hideBin(process.argv));
15
- function removeWindowsCruft(str) {
16
- if (str.includes('\r'))
17
- return str.replaceAll('\r', '');
18
- return str;
19
- }
20
15
  await CLI.scriptName('mcdoc')
21
16
  .command('generate [source]', 'Generate JSON files', () => CLI.positional('source', {
22
17
  describe: 'path to directory containing mcdoc source.',
@@ -63,181 +58,62 @@ await CLI.scriptName('mcdoc')
63
58
  info: (...log_args) => args.verbose ? console.info(...log_args) : false,
64
59
  trace: (message, ...params) => console.trace(message, ...params),
65
60
  };
66
- const projectPath = resolve(process.cwd(), args.source);
67
- await fileUtil.ensureDir(NodeJsExternals, projectPath);
61
+ const project_path = resolve(process.cwd(), args.source);
62
+ await fileUtil.ensureDir(NodeJsExternals, project_path);
68
63
  const service = new Service({
69
64
  logger,
70
65
  project: {
71
- cacheRoot: fileUtil.ensureEndingSlash(pathToFileURL(cacheRoot).toString()),
66
+ cacheRoot: fileUtil.ensureEndingSlash(pathToFileURL(cache_root).toString()),
72
67
  defaultConfig: ConfigService.merge(VanillaConfig, {
73
68
  env: { dependencies: [] },
74
69
  }),
75
70
  externals: NodeJsExternals,
76
71
  initializers: [mcdoc.initialize],
77
- projectRoot: fileUtil.ensureEndingSlash(pathToFileURL(projectPath).toString()),
72
+ projectRoot: fileUtil.ensureEndingSlash(pathToFileURL(project_path).toString()),
78
73
  },
79
74
  });
80
75
  await service.project.ready();
81
76
  await service.project.cacheService.save();
82
- const generated = join('out', 'generated');
77
+ const generated_path = join('out', 'generated');
83
78
  if (args.dry !== true) {
84
- await fs.ensureDir(generated);
79
+ await fs.ensureDir(generated_path);
85
80
  if (args.module) {
86
- await fs.ensureDir(join(generated, 'module'));
81
+ await fs.ensureDir(join(generated_path, 'module'));
87
82
  }
88
83
  if (args.locale) {
89
84
  await fs.ensureDir(join('out', 'locale'));
90
85
  }
91
86
  }
92
87
  const symbols = [];
93
- const internal_locales = {};
94
- const locales = {};
88
+ let locales = {};
95
89
  let errors = 0;
96
- for await (const doc_file of walk(projectPath)) {
90
+ for await (const doc_file of walk(project_path)) {
97
91
  if (doc_file.path.endsWith('.mcdoc')) {
98
- const DocumentUri = pathToFileURL(doc_file.path).toString();
99
- const doc_contents = await fs.readFile(doc_file.path, 'utf-8');
100
- await service.project.onDidOpen(DocumentUri, 'mcdoc', 0, doc_contents);
101
- const check = await service.project.ensureClientManagedChecked(DocumentUri);
102
- if (check && check.doc && check.node) {
103
- const { doc, node } = check;
104
- const path = parse(fileURLToPath(doc.uri));
105
- const resource = join(path.dir.replace(`${projectPath}`, ''), path.name).replace(/^\//, '');
106
- logger.info(`parsing ${resource}\n`);
107
- if (node.children[0]) {
108
- const children = node.children;
109
- function flattenChild(parent, self, _parent, _child) {
110
- const child = {};
111
- const known_error = false;
112
- /* @ts-ignore */
113
- child.self = self;
114
- /* @ts-ignore */
115
- if (_child.parent)
116
- child.parent = parent;
117
- /* @ts-ignore */
118
- if (_child.parentMap)
119
- child.parentMap = parent;
120
- if (_child.children) {
121
- child.children = [];
122
- for (const [i, __child] of Object.entries(_child.children)) {
123
- /* @ts-ignore */
124
- child.children[Number(i)] = flattenChild(self, `${self}[${i}]`, _child, __child);
125
- }
126
- }
127
- child.type = _child.type;
128
- if (child.type === 'resource_location') {
129
- /* @ts-ignore */
130
- child.namespace = _child.namespace;
131
- /* @ts-ignore */
132
- child.path = _child.path;
133
- }
134
- if (Object.hasOwn(_child, 'isOptional')) {
135
- /* @ts-ignore */
136
- child.isOptional = _child.isOptional;
137
- }
138
- if (Object.hasOwn(_child, 'colorTokenType')) {
139
- /* @ts-ignore */
140
- child.colorTokenType = _child.colorTokenType;
141
- }
142
- /* @ts-ignore */
143
- if (Object.hasOwn(_child, 'value')) {
144
- /* @ts-ignore */
145
- child.value = _child.value;
146
- if (internal_locales[parent]) {
147
- locales[`mcdoc.${resource.replace(/[\/\\]/g, '.')}.${child.value}`] = removeWindowsCruft(internal_locales[parent].join('').trimEnd());
148
- delete internal_locales[parent];
149
- }
150
- }
151
- if (child.type === 'mcdoc:struct/map_key' &&
152
- internal_locales[parent]) {
153
- locales[`mcdoc.${resource.replace(/[\/\\]/g, '.')}.map_key`] = removeWindowsCruft(internal_locales[parent].join('').trimEnd());
154
- delete internal_locales[parent];
155
- }
156
- if (Object.hasOwn(_child, 'comment')) {
157
- /* @ts-ignore */
158
- const comment = _child.comment;
159
- child.comment = comment;
160
- if (!args.dry && args.locale &&
161
- _parent?.type === 'mcdoc:doc_comments') {
162
- const key = parent.replace(/\[\d+\]$/, '');
163
- if (!internal_locales[key]) {
164
- internal_locales[key] = [];
165
- }
166
- internal_locales[key].push(comment.slice(1));
167
- }
168
- }
169
- if (_child.hover)
170
- child.hover = _child.hover;
171
- if (_child.color)
172
- child.color = _child.color;
173
- if (child.type !== 'error')
174
- return child;
175
- else {
176
- errors++;
177
- const lc = lineColumn(doc_contents);
178
- function range(range) {
179
- const start = lc.fromIndex(range.start);
180
- const end = lc.fromIndex(range.end);
181
- return `L${start?.line}${start?.col ? `:C${start?.col}` : ''} -> L${end?.line}${end?.col ? `:C${end?.col}` : ''}`;
182
- }
183
- if (!known_error) {
184
- console.warn(`mcdoc error(s):`);
185
- /* @ts-ignore */
186
- if (_child.parent?.parserErrors.length !== 0) {
187
- console.warn(' parser:');
188
- /* @ts-ignore */
189
- _child.parent?.parserErrors.forEach(error => {
190
- console.warn(` ${error.message}\n Location: ${range(error.range)}. Severity ${error.severity}.`);
191
- });
192
- }
193
- /* @ts-ignore */
194
- if (_child.parent?.binderErrors.length !== 0) {
195
- console.warn(' binder:');
196
- /* @ts-ignore */
197
- _child.parent?.binderErrors.forEach(error => {
198
- console.warn(` ${error.message}\n Location: ${range(error.range)}. Severity ${error.severity}.`);
199
- });
200
- }
201
- }
202
- console.warn(`error @ ${doc_file.path}\n\n`);
203
- return false;
204
- }
205
- }
206
- children.forEach((child, i) => {
207
- /* @ts-ignore */
208
- children[i] = flattenChild(resource, `${resource}.[${i}]`, undefined, child);
209
- });
210
- const symbol = {
211
- resource,
212
- children,
213
- };
214
- symbols.push(symbol);
215
- if (!args.dry && args.module) {
216
- const dir = parse(join(generated, 'module', resource)).dir;
217
- if (dir !== '')
218
- await fs.ensureDir(dir);
219
- await fs.writeFile(join(generated, 'module', `${resource}.mcdoc.json`), JSON.stringify(symbol));
220
- if (args.pretty) {
221
- await fs.writeFile(join(generated, 'module', `${resource}.pretty.mcdoc.json`), JSON.stringify(symbol, undefined, 3));
222
- }
223
- }
224
- }
225
- }
92
+ const response = await generate(project_path, generated_path, args, doc_file, service, logger);
93
+ symbols.push(...response[0]);
94
+ locales = { ...locales, ...response[1] };
95
+ errors += response[2];
226
96
  }
227
97
  }
228
98
  if (!args.dry) {
229
- await fs.writeFile(join(generated, 'generated.mcdoc.json'), JSON.stringify(symbols));
99
+ await fs.writeFile(join(generated_path, 'generated.mcdoc.json'), JSON.stringify(symbols));
230
100
  if (args.pretty) {
231
- await fs.writeFile(join(generated, 'generated.pretty.mcdoc.json'), JSON.stringify(symbols, undefined, 3));
101
+ await fs.writeFile(join(generated_path, 'generated.pretty.mcdoc.json'), JSON.stringify(symbols, undefined, 3));
232
102
  }
233
103
  if (args.module) {
234
- await fs.writeFile(join(generated, 'module', 'index.json'), JSON.stringify(symbols.map(symbol => symbol.resource)));
104
+ await fs.writeFile(join(generated_path, 'module', 'index.json'), JSON.stringify(symbols.map(symbol => symbol.resource)));
235
105
  }
236
106
  if (args.locale) {
237
- const orphaned_doc = Object.keys(internal_locales);
238
- if (orphaned_doc.length !== 0) {
239
- console.warn(`parsing error, ${orphaned_doc.length} orphaned doc comments or incorrectly parsed markup comments`);
240
- console.warn(internal_locales);
107
+ const locale_path = join('out', 'locale', 'en-us.json');
108
+ if (await fs.exists(locale_path)) {
109
+ const old_locales = JSON.parse(await fs.readFile(locale_path, 'utf-8'));
110
+ await fs.ensureDir(join('out', 'meta'));
111
+ await fs.writeFile(join('out', 'meta', 'locale.json'), JSON.stringify({
112
+ old_keys: Object.keys(old_locales),
113
+ old_values: Object.values(old_locales),
114
+ new_keys: Object.keys(locales),
115
+ new_values: Object.values(locales),
116
+ }, undefined, 3));
241
117
  }
242
118
  await fs.writeFile(join('out', 'locale', 'en-us.json'), JSON.stringify(locales, undefined, 3));
243
119
  }
@@ -245,6 +121,7 @@ await CLI.scriptName('mcdoc')
245
121
  console.log(`Generated JSON files with ${errors} errors.`);
246
122
  await service.project.close();
247
123
  })
124
+ .command('update_locales', 'Attempt automatic upgrade of locales.', update_locales)
248
125
  .strict()
249
126
  .demandCommand(1)
250
127
  .parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spyglassmc/mcdoc-cli",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "type": "module",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -24,15 +24,17 @@
24
24
  "scripts": {
25
25
  "release": "npm publish",
26
26
  "release:dry": "npm publish --dry-run",
27
- "test": "rm -rf vanilla-mcdoc && rm -rf src/out && git clone https://github.com/SpyglassMC/vanilla-mcdoc && cd src && npx tsx src/index.mts generate ../vanilla-mcdoc/ -p -m -l"
27
+ "setup": "git clone https://github.com/SpyglassMC/vanilla-mcdoc",
28
+ "test": "rm -rf out/generated/module/* && cd vanilla-mcdoc && git pull && cd .. && tsc -b && node lib/index.js generate vanilla-mcdoc/ -l -m -p"
28
29
  },
29
30
  "dependencies": {
30
31
  "fs-extra": "^11.1.1",
31
32
  "klaw": "^4.1.0",
32
33
  "line-column": "^1.0.2",
34
+ "ofetch": "^1.3.4",
33
35
  "yargs": "17.6.2",
34
36
  "@spyglassmc/core": "0.4.5",
35
- "@spyglassmc/mcdoc": "0.3.7"
37
+ "@spyglassmc/mcdoc": "0.3.8"
36
38
  },
37
39
  "devDependencies": {
38
40
  "@types/fs-extra": "^11.0.2",