@galacean/cli 0.0.6 → 0.1.1

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/README.md CHANGED
@@ -1,11 +1,66 @@
1
- # Project Diff
1
+ Galacean CLI
2
+ =================
2
3
 
3
- ## Usage
4
+ The all-in-one Galacean CLI that helps you build Galacean applications.
4
5
 
5
- ```bash
6
- $ npm i -g @galacean/cli
6
+ <!-- toc -->
7
+ * [Usage](#usage)
8
+ * [Commands](#commands)
9
+ <!-- tocstop -->
10
+ # Usage
11
+ <!-- usage -->
12
+ ```sh-session
13
+ $ npm install -g @galacean/cli
14
+ $ galacean COMMAND
15
+ running command...
16
+ $ galacean (--version)
17
+ @galacean/cli/0.1.1 darwin-arm64 node-v18.19.0
18
+ $ galacean --help [COMMAND]
19
+ USAGE
20
+ $ galacean COMMAND
21
+ ...
22
+ ```
23
+ <!-- usagestop -->
24
+ # Commands
25
+ <!-- commands -->
26
+ * [`galacean generate NAME`](#galacean-generate-name)
27
+ * [`galacean help [COMMAND]`](#galacean-help-command)
28
+
29
+ ## `galacean generate NAME`
30
+
31
+ generate a new Galacean Editor plugin
32
+
33
+ ```
34
+ USAGE
35
+ $ galacean generate NAME
36
+
37
+ ARGUMENTS
38
+ NAME directory name of new plugin
39
+
40
+ DESCRIPTION
41
+ generate a new Galacean Editor plugin
42
+ This will clone the specific folder in 'galacean/galacean-editor-plugin-examples' and update package properties
43
+ ```
44
+
45
+ _See code: [dist/commands/generate.ts](https://github.com/galacean/cli/blob/v0.1.1/dist/commands/generate.ts)_
46
+
47
+ ## `galacean help [COMMAND]`
48
+
49
+ Display help for galacean.
50
+
51
+ ```
52
+ USAGE
53
+ $ galacean help [COMMAND] [-n]
54
+
55
+ ARGUMENTS
56
+ COMMAND Command to show help for.
57
+
58
+ FLAGS
59
+ -n, --nested-commands Include all nested commands in the output.
7
60
 
8
- galacean diff <project1-url> <project2-url>
61
+ DESCRIPTION
62
+ Display help for galacean.
9
63
  ```
10
64
 
11
- 执行命令后会在命令文件夹下生成『项目 diff.md』文件,可以打开查看 diff 数据。
65
+ _See code: [@oclif/plugin-help](https://github.com/oclif/plugin-help/blob/v6.1.0/src/commands/help.ts)_
66
+ <!-- commandsstop -->
package/bin/dev ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+
3
+ const oclif = require('@oclif/core')
4
+
5
+ const path = require('path')
6
+ const project = path.join(__dirname, '..', 'tsconfig.json')
7
+
8
+ // In dev mode -> use ts-node and dev plugins
9
+ process.env.NODE_ENV = 'development'
10
+
11
+ require('ts-node').register({ project })
12
+
13
+ // In dev mode, always show stack traces
14
+ oclif.settings.debug = true;
15
+
16
+ // Start the CLI
17
+ oclif.run().then(oclif.flush).catch(oclif.Errors.handle)
package/bin/dev.cmd ADDED
@@ -0,0 +1,3 @@
1
+ @echo off
2
+
3
+ node "%~dp0\dev" %*
package/bin/run ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+
3
+ const oclif = require('@oclif/core')
4
+
5
+ oclif.run().then(require('@oclif/core/flush')).catch(require('@oclif/core/handle'))
package/bin/run.cmd ADDED
@@ -0,0 +1,3 @@
1
+ @echo off
2
+
3
+ node "%~dp0\run" %*
@@ -0,0 +1,10 @@
1
+ import { Command } from '@oclif/core';
2
+ export default class Generate extends Command {
3
+ static description: string;
4
+ static flags: {};
5
+ static args: {
6
+ name: import("@oclif/core/lib/interfaces").Arg<string, Record<string, unknown>>;
7
+ };
8
+ protected generate(type?: string, generatorOptions?: Record<string, unknown>): Promise<void>;
9
+ run(): Promise<void>;
10
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const core_1 = require("@oclif/core");
4
+ const yeoman_environment_1 = require("yeoman-environment");
5
+ class Generate extends core_1.Command {
6
+ async generate(type = 'plugin', generatorOptions = {}) {
7
+ const env = (0, yeoman_environment_1.createEnv)();
8
+ env.register(require.resolve(`../generators/${type}`), `galacean:${type}`);
9
+ await env.run(`galacean:${type}`, generatorOptions);
10
+ }
11
+ async run() {
12
+ const { args } = await this.parse(Generate);
13
+ await this.generate('plugin', { name: args.name, force: true });
14
+ }
15
+ }
16
+ exports.default = Generate;
17
+ Generate.description = `generate a new Galacean Editor plugin
18
+ This will clone the specific folder in 'galacean/galacean-editor-plugin-examples' and update package properties`;
19
+ Generate.flags = {};
20
+ Generate.args = {
21
+ name: core_1.Args.string({ required: true, description: 'directory name of new plugin' }),
22
+ };
@@ -0,0 +1,33 @@
1
+ import * as Generator from 'yeoman-generator';
2
+ export default class PluginGenerator extends Generator {
3
+ options: {
4
+ force: boolean;
5
+ };
6
+ exampleRepoUrl: string;
7
+ name: string;
8
+ pjson: any;
9
+ githubUser: string;
10
+ answers: {
11
+ name: string;
12
+ bin: string;
13
+ description: string;
14
+ version: string;
15
+ github: {
16
+ repo: string;
17
+ user: string;
18
+ };
19
+ author: string;
20
+ files: string;
21
+ license: string;
22
+ galacean: string;
23
+ pkg: string;
24
+ typescript: boolean;
25
+ eslint: boolean;
26
+ };
27
+ repository?: string;
28
+ constructor(args: string | string[], opts: Generator.GeneratorOptions);
29
+ prompting(): Promise<void>;
30
+ writing(): void;
31
+ end(): void;
32
+ private _gitignore;
33
+ }
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const child_process_1 = require("child_process");
4
+ const fs = require("fs");
5
+ const _ = require("lodash");
6
+ const path = require("path");
7
+ const nodeDebug = require("debug");
8
+ const Generator = require("yeoman-generator");
9
+ const debug = nodeDebug('galacean-plugin-generator');
10
+ const { version } = require('../../package.json');
11
+ class PluginGenerator extends Generator {
12
+ constructor(args, opts) {
13
+ super(args, opts);
14
+ this.exampleRepoUrl = 'git@github.com:galacean/galacean-editor-plugin-examples.git';
15
+ this.githubUser = '';
16
+ this.name = opts.name;
17
+ this.options.force = opts.force;
18
+ }
19
+ async prompting() {
20
+ this.log(`Galacean Editor Plugin Generator. version: ${version}`);
21
+ const { pluginType } = await this.prompt([
22
+ {
23
+ type: 'list',
24
+ name: 'pluginType',
25
+ message: 'Select a plugin type',
26
+ choices: [
27
+ { name: 'Basic', value: 'basic' },
28
+ { name: 'React', value: 'react' },
29
+ ],
30
+ default: 'blank',
31
+ },
32
+ ]);
33
+ const targetDir = path.resolve(this.name);
34
+ (0, child_process_1.execSync)(`git clone ${this.exampleRepoUrl} "${targetDir}" --depth=1`);
35
+ for (const f of fs.readdirSync(path.resolve(this.name)).filter(file => file !== pluginType)) {
36
+ const p = `${path.resolve(this.name, f)}`;
37
+ this.log(p);
38
+ fs.rmSync(p, { recursive: true, force: true });
39
+ }
40
+ (0, child_process_1.execSync)(`mv ${path.resolve(this.name, pluginType, '*')} ${path.resolve(this.name)}`);
41
+ fs.rmSync(`${path.resolve(this.name, pluginType)}`, { recursive: true, force: true });
42
+ this.destinationRoot(path.resolve(this.name));
43
+ this.env.cwd = this.destinationPath();
44
+ try {
45
+ this.githubUser = await this.user.github.username();
46
+ }
47
+ catch (error) {
48
+ debug(error);
49
+ }
50
+ this.pjson = {
51
+ name: '',
52
+ version: '',
53
+ description: '',
54
+ author: '',
55
+ bin: {},
56
+ homepage: '',
57
+ license: '',
58
+ main: '',
59
+ repository: '',
60
+ files: [],
61
+ dependencies: {},
62
+ devDependencies: {},
63
+ galacean: '',
64
+ scripts: {},
65
+ engines: {},
66
+ ...this.fs.readJSON(path.join(this.env.cwd, 'package.json'), {}),
67
+ };
68
+ let repository = this.destinationRoot().split(path.sep).slice(-2).join('/');
69
+ if (this.githubUser) {
70
+ repository = `${this.githubUser}/${repository.split('/')[1]}`;
71
+ }
72
+ const defaults = {
73
+ ...this.pjson,
74
+ name: (this.name || this.determineAppname()).replace(/ /g, '-'),
75
+ version: '0.0.0',
76
+ license: 'MIT',
77
+ author: this.githubUser ? `${this.user.git.name()} @${this.githubUser}` : this.user.git.name(),
78
+ dependencies: {},
79
+ repository,
80
+ engines: {
81
+ node: '>=12.0.0',
82
+ ...this.pjson.engines,
83
+ },
84
+ };
85
+ this.repository = defaults.repository;
86
+ if (this.repository && this.repository.url) {
87
+ this.repository = this.repository.url;
88
+ }
89
+ this.answers = await this.prompt([
90
+ {
91
+ type: 'input',
92
+ name: 'name',
93
+ message: 'plugin package name',
94
+ default: defaults.name,
95
+ },
96
+ {
97
+ type: 'input',
98
+ name: 'description',
99
+ message: 'description',
100
+ default: defaults.description,
101
+ },
102
+ {
103
+ type: 'input',
104
+ name: 'author',
105
+ message: 'author',
106
+ default: defaults.author,
107
+ },
108
+ {
109
+ type: 'input',
110
+ name: 'galacean',
111
+ message: 'The minimum version of Galacean that this plugin supports',
112
+ default: defaults.galacean,
113
+ },
114
+ {
115
+ type: 'input',
116
+ name: 'license',
117
+ message: 'license',
118
+ default: defaults.license,
119
+ },
120
+ {
121
+ type: 'input',
122
+ name: 'github.user',
123
+ message: 'Who is the GitHub owner of repository (https://github.com/OWNER/repo)',
124
+ default: repository.split('/').slice(0, -1).pop(),
125
+ },
126
+ {
127
+ type: 'input',
128
+ name: 'github.repo',
129
+ message: 'What is the GitHub name of repository (https://github.com/owner/REPO)',
130
+ default: (answers) => (answers.name || this.pjson.repository || this.pjson.name).split('/').pop(),
131
+ },
132
+ ]);
133
+ debug(this.answers);
134
+ this.pjson.name = this.answers.name || defaults.name;
135
+ this.pjson.description = this.answers.description || defaults.description;
136
+ this.pjson.version = this.answers.version || defaults.version;
137
+ this.pjson.engines.node = defaults.engines.node;
138
+ this.pjson.author = this.answers.author || defaults.author;
139
+ this.pjson.files = this.answers.files || defaults.files || '/lib';
140
+ this.pjson.license = this.answers.license || defaults.license;
141
+ // eslint-disable-next-line no-multi-assign
142
+ this.repository = this.pjson.repository = this.answers.github ? `${this.answers.github.user}/${this.answers.github.repo}` : defaults.repository;
143
+ this.pjson.homepage = `https://github.com/${this.repository}`;
144
+ this.pjson.bugs = `https://github.com/${this.repository}/issues`;
145
+ }
146
+ writing() {
147
+ this.pjson.files = _.uniq((this.pjson.files || []).sort());
148
+ this.fs.writeJSON(this.destinationPath('./package.json'), this.pjson);
149
+ this.fs.write(this.destinationPath('.gitignore'), this._gitignore());
150
+ this.fs.delete(this.destinationPath('LICENSE'));
151
+ }
152
+ end() {
153
+ var _a;
154
+ if ((_a = this.pjson.scripts) === null || _a === void 0 ? void 0 : _a.build) {
155
+ this.spawnCommandSync(this.env.options.nodePackageManager, ['run', 'build'], { cwd: this.env.cwd });
156
+ }
157
+ this.log(`\nCreated ${this.pjson.name} in ${this.destinationRoot()}`);
158
+ }
159
+ _gitignore() {
160
+ const existing = this.fs.exists(this.destinationPath('.gitignore')) ? this.fs.read(this.destinationPath('.gitignore')).split('\n') : [];
161
+ return _([
162
+ '*-debug.log',
163
+ '*-error.log',
164
+ 'node_modules',
165
+ '/tmp',
166
+ '/dist',
167
+ '/lib',
168
+ ])
169
+ .concat(existing)
170
+ .compact()
171
+ .uniq()
172
+ .sort()
173
+ .join('\n') + '\n';
174
+ }
175
+ }
176
+ exports.default = PluginGenerator;
@@ -0,0 +1 @@
1
+ export { run } from '@oclif/core';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.run = void 0;
4
+ var core_1 = require("@oclif/core");
5
+ Object.defineProperty(exports, "run", { enumerable: true, get: function () { return core_1.run; } });
@@ -0,0 +1,22 @@
1
+ {
2
+ "version": "0.1.1",
3
+ "commands": {
4
+ "generate": {
5
+ "id": "generate",
6
+ "description": "generate a new Galacean Editor plugin\nThis will clone the specific folder in 'galacean/galacean-editor-plugin-examples' and update package properties",
7
+ "strict": true,
8
+ "pluginName": "@galacean/cli",
9
+ "pluginAlias": "@galacean/cli",
10
+ "pluginType": "core",
11
+ "aliases": [],
12
+ "flags": {},
13
+ "args": {
14
+ "name": {
15
+ "name": "name",
16
+ "description": "directory name of new plugin",
17
+ "required": true
18
+ }
19
+ }
20
+ }
21
+ }
22
+ }
package/package.json CHANGED
@@ -1,44 +1,72 @@
1
1
  {
2
2
  "name": "@galacean/cli",
3
- "version": "0.0.6",
4
- "main": "lib/index.js",
5
- "type": "module",
6
- "author": {
7
- "name": "gz65555",
8
- "email": "gz65555@gmail.com"
9
- },
10
- "scripts": {
11
- "dev": "tsc -w",
12
- "build": "tsc"
13
- },
3
+ "version": "0.1.1",
4
+ "description": "All-in-one cli tool that help you using Galacean Framework.",
5
+ "author": "Kbscript @MrKou47",
14
6
  "bin": {
15
- "galacean": "./bin/cli.js"
7
+ "galacean": "./bin/run"
16
8
  },
9
+ "homepage": "https://github.com/galacean/cli",
10
+ "license": "MIT",
11
+ "main": "dist/index.js",
12
+ "repository": "galacean/cli",
17
13
  "files": [
18
- "dist",
19
- "bin",
20
- "lib",
21
- "types"
14
+ "/bin",
15
+ "/dist",
16
+ "/npm-shrinkwrap.json",
17
+ "/oclif.manifest.json"
22
18
  ],
23
- "types": "types",
24
- "license": "MIT",
19
+ "dependencies": {
20
+ "@oclif/core": "^4.0.2",
21
+ "@oclif/plugin-help": "^6.1.0",
22
+ "@oclif/plugin-plugins": "^2.4.7",
23
+ "yeoman-environment": "^3.19.3",
24
+ "yeoman-generator": "^5.9.0"
25
+ },
25
26
  "devDependencies": {
26
- "@types/fs-extra": "^9.0.12",
27
- "@types/inquirer": "^7.3.3",
28
- "prettier": "^2.3.2",
29
- "typescript": "^5"
27
+ "@oclif/test": "^2.4.0",
28
+ "@types/chai": "^4",
29
+ "@types/mocha": "^9.0.0",
30
+ "@types/node": "^16.18.39",
31
+ "@types/yeoman-generator": "^5.2.11",
32
+ "chai": "^4",
33
+ "eslint": "^7.32.0",
34
+ "eslint-config-oclif": "^4",
35
+ "eslint-config-oclif-typescript": "^1.0.3",
36
+ "mocha": "^9",
37
+ "oclif": "^3.10.0",
38
+ "shx": "^0.3.3",
39
+ "ts-node": "^10.9.1",
40
+ "tslib": "^2.6.1",
41
+ "typescript": "^4.9.5"
30
42
  },
31
- "dependencies": {
32
- "@types/lodash": "^4.14.202",
33
- "@types/lodash-es": "^4.17.12",
34
- "cac": "^6.7.3",
35
- "chalk": "^5.3.0",
36
- "copy-paste": "^1.5.3",
37
- "fs-extra": "^10.0.0",
38
- "inquirer": "^8.1.2",
39
- "json-diff-ts": "^2.2.1",
40
- "lodash": "^4.17.21",
41
- "lodash-es": "^4.17.21",
42
- "node-fetch": "^3.3.2"
43
+ "oclif": {
44
+ "bin": "galacean",
45
+ "dirname": "galacean",
46
+ "commands": "./dist/commands",
47
+ "plugins": [
48
+ "@oclif/plugin-help"
49
+ ]
50
+ },
51
+ "packageManager": "pnpm@8.6.2",
52
+ "engines": {
53
+ "node": ">=12.0.0"
54
+ },
55
+ "bugs": "https://github.com/galacean/cli/issues",
56
+ "keywords": [
57
+ "galacean",
58
+ "cli",
59
+ "plugin"
60
+ ],
61
+ "types": "dist/index.d.ts",
62
+ "publishConfig": {
63
+ "registry": "https://registry.npmjs.org"
64
+ },
65
+ "scripts": {
66
+ "build": "shx rm -rf dist && tsc -b",
67
+ "lint": "eslint . --ext .ts --config .eslintrc",
68
+ "posttest": "npm run lint",
69
+ "test": "mocha --forbid-only \"test/**/*.test.ts\"",
70
+ "version": "oclif readme && git add README.md"
43
71
  }
44
- }
72
+ }
package/bin/cli.js DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import "../lib/cli.js";
package/lib/Markdown.js DELETED
@@ -1,17 +0,0 @@
1
- import fs from "fs-extra";
2
- import path from "path";
3
- export const markdown = {
4
- _txt: "",
5
- get txt() {
6
- return this._txt;
7
- },
8
- addLine(line, tab = 0) {
9
- for (let i = 0; i < tab; i++) {
10
- line = "\t" + line;
11
- }
12
- this._txt += line + "\n";
13
- },
14
- generate() {
15
- fs.writeFileSync(path.join(process.cwd(), "项目 Diff.md"), this._txt);
16
- },
17
- };
package/lib/cli.js DELETED
@@ -1,68 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { cac } from "cac";
11
- import path from "path";
12
- import fs from "fs-extra";
13
- import * as url from "url";
14
- import { _diffProjects, diffProjects } from "./diff.js";
15
- import { getFileBufferFromUrl } from "./utils.js";
16
- import { markdown } from "./Markdown.js";
17
- import { mergeProject } from "./mergeProject.js";
18
- import * as ncp from "copy-paste";
19
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
20
- const cli = cac();
21
- cli.command("diff [...files]", "diff files").action((files) => {
22
- markdown.addLine("# 资产 Diff");
23
- markdown.addLine(``);
24
- markdown.addLine(`- ${files[0]}`);
25
- markdown.addLine(`- ${files[1]}`);
26
- markdown.addLine(``);
27
- Promise.all([
28
- getFileBufferFromUrl(files[0]),
29
- getFileBufferFromUrl(files[1]),
30
- ]).then((res) => __awaiter(void 0, void 0, void 0, function* () {
31
- const result = res.map((item) => JSON.parse(item.toString()));
32
- yield diffProjects(result[0], result[1]);
33
- markdown.generate();
34
- }));
35
- });
36
- cli
37
- .command("merge [...files]", "merge project.json by md5")
38
- .action((files) => __awaiter(void 0, void 0, void 0, function* () {
39
- const before = files[0];
40
- const after = files[1];
41
- yield Promise.all([
42
- getFileBufferFromUrl(before),
43
- getFileBufferFromUrl(after),
44
- ]).then((res) => {
45
- const result = res.map((item) => JSON.parse(item.toString()));
46
- const resProject = mergeProject(result[0], result[1]);
47
- const output = JSON.stringify(resProject, null, 2);
48
- // console.log(output);
49
- return new Promise((resolve) => {
50
- ncp.copy(output, () => {
51
- resolve();
52
- });
53
- });
54
- });
55
- }));
56
- export function diffProject(before, after) {
57
- return Promise.all([
58
- getFileBufferFromUrl(before),
59
- getFileBufferFromUrl(after),
60
- ]).then((res) => {
61
- const result = res.map((item) => JSON.parse(item.toString()));
62
- return _diffProjects(result[0], result[1]);
63
- });
64
- }
65
- const pkg = fs.readJSONSync(path.join(__dirname, "../package.json"));
66
- cli.help();
67
- cli.version(pkg.version);
68
- cli.parse();
package/lib/diff.js DELETED
@@ -1,253 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { Operation, diff, flattenChangeset } from "json-diff-ts";
11
- import { groupBy, cloneDeep } from "lodash-es";
12
- import { getFileBufferFromUrl } from "./utils.js";
13
- import { markdown } from "./Markdown.js";
14
- export function _diffProjects(project1, project2) {
15
- var _a, _b, _c;
16
- return __awaiter(this, void 0, void 0, function* () {
17
- const result = diff(project1, project2, { files: "id" });
18
- const changes = flattenChangeset(result);
19
- const assets1 = {};
20
- const assets2 = {};
21
- project1.files.forEach((item) => {
22
- assets1[item.id] = item;
23
- });
24
- project2.files.forEach((item) => {
25
- assets2[item.id] = item;
26
- });
27
- const diffs = groupBy(changes, "type");
28
- const sceneChanges = [];
29
- const assetsChangeInfo = { add: [], remove: [] };
30
- const scenesChangeInfo = {};
31
- (_a = diffs[Operation.ADD]) === null || _a === void 0 ? void 0 : _a.forEach((item) => {
32
- assetsChangeInfo.add.push(item.value.virtualPath);
33
- });
34
- (_b = diffs[Operation.REMOVE]) === null || _b === void 0 ? void 0 : _b.forEach((item) => {
35
- assetsChangeInfo.remove.push(item.value.virtualPath);
36
- });
37
- (_c = diffs[Operation.UPDATE]) === null || _c === void 0 ? void 0 : _c.forEach((item) => {
38
- const id = getIdFromPath(item.path);
39
- const asset = assets1[id];
40
- if (asset.type === "Scene") {
41
- sceneChanges.push(asset);
42
- }
43
- });
44
- yield Promise.all(sceneChanges.map((asset) => __awaiter(this, void 0, void 0, function* () {
45
- scenesChangeInfo[assets2[asset.id].virtualPath] = yield _diffScene(asset.path, assets2[asset.id].path);
46
- })));
47
- return { assetsChangeInfo, scenesChangeInfo };
48
- });
49
- }
50
- export function diffProjects(project1, project2) {
51
- var _a, _b, _c;
52
- return __awaiter(this, void 0, void 0, function* () {
53
- const result = diff(project1, project2, { files: "id" });
54
- const changes = flattenChangeset(result);
55
- const assets1 = {};
56
- const assets2 = {};
57
- project1.files.forEach((item) => {
58
- assets1[item.id] = item;
59
- });
60
- project2.files.forEach((item) => {
61
- assets2[item.id] = item;
62
- });
63
- const diffs = groupBy(changes, "type");
64
- const sceneChanges = [];
65
- markdown.addLine("## 资产");
66
- markdown.addLine(``);
67
- markdown.addLine(`- 资产新增`);
68
- (_a = diffs[Operation.ADD]) === null || _a === void 0 ? void 0 : _a.forEach((item) => {
69
- markdown.addLine(`- ${item.value.virtualPath}`, 1);
70
- });
71
- markdown.addLine(``);
72
- markdown.addLine(`- 资产移除`);
73
- (_b = diffs[Operation.REMOVE]) === null || _b === void 0 ? void 0 : _b.forEach((item) => {
74
- markdown.addLine(`- ${item.value.virtualPath}`, 1);
75
- });
76
- // markdown.addLine(``);
77
- // markdown.addLine(`- 资产修改`);
78
- // markdown.addLine(``);
79
- (_c = diffs[Operation.UPDATE]) === null || _c === void 0 ? void 0 : _c.forEach((item) => {
80
- const id = getIdFromPath(item.path);
81
- const asset = assets1[id];
82
- if (asset.type === "Scene") {
83
- sceneChanges.push(asset);
84
- }
85
- // markdown.addLine(`- ${asset.virtualPath}`, 1);
86
- });
87
- markdown.addLine(``);
88
- markdown.addLine("## 场景");
89
- markdown.addLine(``);
90
- yield Promise.all(sceneChanges.map((asset) => {
91
- markdown.addLine(`### ${assets2[asset.id].virtualPath}`);
92
- markdown.addLine(``);
93
- return diffScene(asset.path, assets2[asset.id].path);
94
- }));
95
- });
96
- }
97
- function diffScene(url1, url2) {
98
- var _a, _b, _c, _d;
99
- return __awaiter(this, void 0, void 0, function* () {
100
- const [scene1, scene2] = yield Promise.all([
101
- getFileBufferFromUrl(url1),
102
- getFileBufferFromUrl(url2),
103
- ]).then((res) => res.map((item) => JSON.parse(item.toString())));
104
- const { diffObj: diffObj1, entities } = getEntities(scene1);
105
- const { diffObj: diffObj2, entities: newEntities } = getEntities(scene2);
106
- const changes = flattenChangeset(diff(diffObj1, diffObj2));
107
- const groups = groupBy(changes, (item) => {
108
- if (item.path.includes(".components")) {
109
- return "components";
110
- }
111
- return "entities";
112
- });
113
- if (groups["entities"]) {
114
- markdown.addLine(`#### Entities`);
115
- markdown.addLine("");
116
- const changesGroup = groupBy(groups["entities"], "type");
117
- markdown.addLine(`- 新增`);
118
- (_a = changesGroup[Operation.ADD]) === null || _a === void 0 ? void 0 : _a.forEach((item) => {
119
- const entityPath = getEntityPath(item.key, newEntities);
120
- markdown.addLine(`- ${entityPath}`, 1);
121
- });
122
- markdown.addLine(`- 移除`);
123
- (_b = changesGroup[Operation.REMOVE]) === null || _b === void 0 ? void 0 : _b.forEach((item) => {
124
- const entityPath = getEntityPath(item.key, entities);
125
- markdown.addLine(`- ${entityPath}`, 1);
126
- });
127
- }
128
- if (groups["components"]) {
129
- markdown.addLine(``);
130
- markdown.addLine(`#### 组件`);
131
- markdown.addLine("");
132
- const changesGroup = groupBy(groups["components"], "type");
133
- markdown.addLine(`- 新增`);
134
- (_c = changesGroup[Operation.ADD]) === null || _c === void 0 ? void 0 : _c.forEach((item) => {
135
- const entityId = getComponentEntityId(item.path);
136
- const entityPath = getEntityPath(entityId, entities);
137
- const comp = item.value;
138
- markdown.addLine(`- ${entityPath} [${comp["class"]}]`, 1);
139
- });
140
- markdown.addLine(`- 移除`);
141
- (_d = changesGroup[Operation.REMOVE]) === null || _d === void 0 ? void 0 : _d.forEach((item) => {
142
- const entityId = getComponentEntityId(item.path);
143
- const entityPath = getEntityPath(entityId, entities);
144
- const comp = item.value;
145
- markdown.addLine(`- ${entityPath} [${comp["class"]}]`, 1);
146
- });
147
- }
148
- });
149
- }
150
- function _diffScene(url1, url2) {
151
- var _a, _b, _c, _d;
152
- return __awaiter(this, void 0, void 0, function* () {
153
- const [scene1, scene2] = yield Promise.all([
154
- getFileBufferFromUrl(url1),
155
- getFileBufferFromUrl(url2),
156
- ]).then((res) => res.map((item) => JSON.parse(item.toString())));
157
- const { diffObj: diffObj1, entities } = getEntities(scene1);
158
- const { diffObj: diffObj2, entities: newEntities } = getEntities(scene2);
159
- const changes = flattenChangeset(diff(diffObj1, diffObj2));
160
- const sceneChangeInfo = {
161
- entities: { add: [], remove: [] },
162
- components: { add: [], remove: [] },
163
- error: null,
164
- };
165
- if (Object.values(newEntities).length <= 0) {
166
- sceneChangeInfo.error = "Entities is empty";
167
- }
168
- const groups = groupBy(changes, (item) => {
169
- if (item.path.includes(".components")) {
170
- return "components";
171
- }
172
- return "entities";
173
- });
174
- if (groups["entities"]) {
175
- const changesGroup = groupBy(groups["entities"], "type");
176
- (_a = changesGroup[Operation.ADD]) === null || _a === void 0 ? void 0 : _a.forEach((item) => {
177
- const entityPath = getEntityPath(item.key, newEntities);
178
- sceneChangeInfo.entities.add.push(entityPath);
179
- });
180
- (_b = changesGroup[Operation.REMOVE]) === null || _b === void 0 ? void 0 : _b.forEach((item) => {
181
- const entityPath = getEntityPath(item.key, entities);
182
- sceneChangeInfo.entities.remove.push(entityPath);
183
- });
184
- }
185
- if (groups["components"]) {
186
- const changesGroup = groupBy(groups["components"], "type");
187
- (_c = changesGroup[Operation.ADD]) === null || _c === void 0 ? void 0 : _c.forEach((item) => {
188
- const entityId = getComponentEntityId(item.path);
189
- const entityPath = getEntityPath(entityId, entities);
190
- const comp = item.value;
191
- sceneChangeInfo.components.add.push(`- ${entityPath} [${comp["class"]}]`);
192
- });
193
- (_d = changesGroup[Operation.REMOVE]) === null || _d === void 0 ? void 0 : _d.forEach((item) => {
194
- const entityId = getComponentEntityId(item.path);
195
- const entityPath = getEntityPath(entityId, entities);
196
- const comp = item.value;
197
- sceneChangeInfo.components.remove.push(`- ${entityPath} [${comp["class"]}]`);
198
- });
199
- }
200
- return sceneChangeInfo;
201
- });
202
- }
203
- function getComponentEntityId(str) {
204
- let regex = /\.([^.]*?)\.components/;
205
- let matches = str.match(regex);
206
- if (matches) {
207
- return matches[1];
208
- }
209
- }
210
- function getEntityPath(id, entities) {
211
- const routes = [];
212
- let entity = entities[id];
213
- while (entity) {
214
- routes.unshift(entity.name);
215
- entity = entities[entity.parent];
216
- }
217
- return routes.join("/");
218
- }
219
- function getEntities(scene) {
220
- const obj = {};
221
- scene.entities.forEach((item) => {
222
- const comps = {};
223
- item.components.forEach((comp) => {
224
- comps[comp.id] = comp;
225
- });
226
- item.components = comps;
227
- item.children = {};
228
- obj[item.id] = item;
229
- });
230
- const entities = cloneDeep(obj);
231
- const hasParentItems = [];
232
- scene.entities.forEach((item) => {
233
- if (item.parent) {
234
- obj[item.parent].children[item.id] = item;
235
- hasParentItems.push(item.id);
236
- }
237
- });
238
- hasParentItems.forEach((id) => {
239
- delete obj[id];
240
- });
241
- return { diffObj: obj, entities };
242
- }
243
- function getIdFromPath(str) {
244
- const regex = /id=='([^']+)'/;
245
- const match = str.match(regex);
246
- if (match) {
247
- const id = match[1]; // 提取的 id 值
248
- return id;
249
- }
250
- else {
251
- console.log("No match found");
252
- }
253
- }
package/lib/index.js DELETED
@@ -1 +0,0 @@
1
- export * from "./cli.js";
@@ -1,21 +0,0 @@
1
- export function mergeProject(before, after) {
2
- const originFiles = {};
3
- before.files.forEach((file) => {
4
- originFiles[file.id] = file;
5
- });
6
- const afterFiles = {};
7
- after.files.forEach((file) => {
8
- afterFiles[file.id] = file;
9
- });
10
- const resultFiles = Object.assign({}, afterFiles);
11
- Object.keys(afterFiles).forEach((id) => {
12
- const originItem = originFiles[id];
13
- const afterItem = afterFiles[id];
14
- if (originItem && originItem.md5 && originItem.md5 === afterItem.md5) {
15
- // 资产修改
16
- afterItem.path = originItem.path;
17
- }
18
- });
19
- after.files = Object.values(resultFiles).filter((item) => item != undefined);
20
- return after;
21
- }
package/lib/type.js DELETED
@@ -1 +0,0 @@
1
- export {};
package/lib/utils.js DELETED
@@ -1,139 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import https from "https";
11
- import http from "http";
12
- import fs from "fs-extra";
13
- import path from "path";
14
- import fetch from "node-fetch";
15
- import { URL } from "url";
16
- export function streamToBuffer(stream) {
17
- return new Promise((resolve, reject) => {
18
- const buffers = [];
19
- stream.on("error", reject);
20
- // @ts-ignore
21
- stream.on("data", (data) => buffers.push(data));
22
- stream.on("end", () => resolve(Buffer.concat(buffers)));
23
- });
24
- }
25
- export function streamToString(stream) {
26
- const chunks = [];
27
- return new Promise((resolve, reject) => {
28
- stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
29
- stream.on("error", (err) => reject(err));
30
- stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
31
- });
32
- }
33
- export function toBuffer(view) {
34
- const buf = Buffer.alloc(view.byteLength);
35
- for (let i = 0; i < buf.length; ++i) {
36
- buf[i] = view[i];
37
- }
38
- return buf;
39
- }
40
- export function urlToBuffer(url) {
41
- return new Promise((resolve) => {
42
- let req = url.startsWith("https://")
43
- ? https.get(url, callback)
44
- : http.get(url, callback);
45
- let body = "";
46
- function callback(res) {
47
- res.on("data", (chunk) => {
48
- body += chunk;
49
- });
50
- res.on("end", () => {
51
- resolve(Buffer.from(body));
52
- });
53
- }
54
- });
55
- }
56
- export function getUrlSize(url, attempts = 0) {
57
- return new Promise((res, rej) => {
58
- let req = url.startsWith("https://") ? https.get(url) : http.get(url);
59
- req.once("response", (r) => {
60
- req.destroy();
61
- if (r.statusCode >= 300 && r.statusCode < 400 && r.headers.location) {
62
- if (attempts > 5) {
63
- return rej(new Error("Too many redirects"));
64
- }
65
- return res(getUrlSize(r.headers.location, attempts + 1));
66
- }
67
- let c = parseInt(r.headers["content-length"]);
68
- if (!isNaN(c))
69
- res(c);
70
- else
71
- rej("Couldn't get file size");
72
- });
73
- req.once("error", (e) => rej(e));
74
- });
75
- }
76
- export function sum(array) {
77
- let sum = 0;
78
- for (let i = 0; i < array.length; i++) {
79
- sum += array[i];
80
- }
81
- return sum;
82
- }
83
- export function getBufferAndNameFromUri(uri) {
84
- return __awaiter(this, void 0, void 0, function* () {
85
- let buffer;
86
- let name;
87
- const isUrl = /^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(uri);
88
- if (isUrl) {
89
- buffer = yield urlToBuffer(uri);
90
- const urlRegex = /\/([^/]+\.[^/.]+)$/;
91
- const matches = uri.match(urlRegex);
92
- if (matches) {
93
- name = matches[1];
94
- }
95
- else {
96
- name = "noname";
97
- }
98
- }
99
- else {
100
- uri = uri !== null && uri !== void 0 ? uri : ".";
101
- const filepath = path.isAbsolute(uri) ? uri : path.join(process.cwd(), uri);
102
- const stream = yield fs.createReadStream(filepath);
103
- buffer = yield streamToBuffer(stream);
104
- name = path.basename(filepath);
105
- }
106
- return { buffer, name };
107
- });
108
- }
109
- export function stringIsAValidUrl(s) {
110
- try {
111
- new URL(s);
112
- return true;
113
- }
114
- catch (err) {
115
- return false;
116
- }
117
- }
118
- export function getFileBufferFromUrl(url) {
119
- if (stringIsAValidUrl(url)) {
120
- return fetch(url)
121
- .then((response) => response.arrayBuffer())
122
- .then((ab) => Buffer.from(ab));
123
- }
124
- else {
125
- const filepath = path.isAbsolute(url) ? url : path.join(process.cwd(), url);
126
- return new Promise((resolve, reject) => {
127
- fs.readFile(filepath, (err, data) => {
128
- if (err)
129
- reject(err);
130
- resolve(data);
131
- });
132
- });
133
- }
134
- }
135
- export function getNameFromUrl(uri) {
136
- const urlRegex = /\/([^/]+\.[^/.]+)$/;
137
- const matches = uri.match(urlRegex);
138
- return matches ? matches[1] : "noname";
139
- }
@@ -1,6 +0,0 @@
1
- export declare const markdown: {
2
- _txt: string;
3
- readonly txt: any;
4
- addLine(line: string, tab?: number): void;
5
- generate(): void;
6
- };
package/types/cli.d.ts DELETED
@@ -1,7 +0,0 @@
1
- export declare function diffProject(before: string, after: string): Promise<{
2
- assetsChangeInfo: {
3
- add: any[];
4
- remove: any[];
5
- };
6
- scenesChangeInfo: {};
7
- }>;
package/types/diff.d.ts DELETED
@@ -1,8 +0,0 @@
1
- export declare function _diffProjects(project1: any, project2: any): Promise<{
2
- assetsChangeInfo: {
3
- add: any[];
4
- remove: any[];
5
- };
6
- scenesChangeInfo: {};
7
- }>;
8
- export declare function diffProjects(project1: any, project2: any): Promise<void>;
package/types/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./cli.js";
@@ -1,10 +0,0 @@
1
- interface IProject {
2
- files: Array<IFile>;
3
- }
4
- interface IFile {
5
- path: string;
6
- md5: string;
7
- id: string;
8
- }
9
- export declare function mergeProject(before: IProject, after: IProject): IProject;
10
- export {};
package/types/type.d.ts DELETED
@@ -1,15 +0,0 @@
1
- export type IVector3 = {
2
- x: number;
3
- y: number;
4
- z: number;
5
- };
6
- export type IEntity = {
7
- id: string;
8
- name: string;
9
- isActive: boolean;
10
- position: IVector3;
11
- rotation: IVector3;
12
- scale: IVector3;
13
- parent: string;
14
- isClone: boolean;
15
- };
package/types/utils.d.ts DELETED
@@ -1,14 +0,0 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- export declare function streamToBuffer(stream: any): Promise<Buffer>;
3
- export declare function streamToString(stream: any): Promise<string>;
4
- export declare function toBuffer(view: Uint8Array): Buffer;
5
- export declare function urlToBuffer(url: string): Promise<Buffer>;
6
- export declare function getUrlSize(url: string, attempts?: number): Promise<number>;
7
- export declare function sum(array: ArrayLike<number>): number;
8
- export declare function getBufferAndNameFromUri(uri: any): Promise<{
9
- buffer: any;
10
- name: any;
11
- }>;
12
- export declare function stringIsAValidUrl(s: string): boolean;
13
- export declare function getFileBufferFromUrl(url: string): Promise<Buffer>;
14
- export declare function getNameFromUrl(uri: string): string;