@gigatrappeur/ldraw-index 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +22 -2
- package/package.json +53 -4
- package/src/cli/get.ts +122 -0
- package/src/cli/getGeometry.ts +113 -0
- package/src/cli/index.ts +65 -0
- package/src/cli/init.ts +145 -0
- package/src/cli/report.ts +77 -0
- package/src/cli/search.ts +129 -0
- package/src/index.ts +2 -0
- package/src/lib/db.ts +258 -0
- package/src/lib/format.ts +4 -0
- package/src/lib/geometry.ts +267 -0
- package/src/lib/index.ts +7 -0
- package/src/lib/keyword.ts +24 -0
- package/src/lib/ldraw-index.ts +269 -0
- package/src/lib/material.ts +122 -0
- package/src/lib/part.ts +143 -0
- package/src/lib/weld.ts +259 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ldraw-index
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
To install dependencies:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bun install
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
To run:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun run index.ts
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
To type check:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
bun check
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Run `bun fmt` to format the code.
|
|
22
|
+
|
|
23
|
+
This project was created using `bun init` in bun v1.4.4. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
"name": "@gigatrappeur/ldraw-index",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Catalogue de pièces LEGO/LDraw avec recherche full-text (FTS5), mapping Rebrickable et génération SVG/GLB",
|
|
5
|
+
"author": "Gigatrapper",
|
|
6
|
+
"homepage": "https://github.com/Gigatrappeur/ldraw-index#readme",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/Gigatrappeur/ldraw-index"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [ "lego", "ldraw", "glb", "svg", "catalog", "brick", "3d", "model", "toy" ],
|
|
14
|
+
"engines": {
|
|
15
|
+
"bun": ">=1"
|
|
16
|
+
},
|
|
17
|
+
"workspaces": [ "helpers/*" ],
|
|
18
|
+
"main": "./src/index.ts",
|
|
19
|
+
"types": "./src/index.ts",
|
|
20
|
+
"bin": {
|
|
21
|
+
"ldraw-index": "./src/cli/index.ts"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./src/index.ts",
|
|
26
|
+
"import": "./src/index.ts"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"report": "bun run src/cli/report.ts",
|
|
31
|
+
"init": "bun run src/cli/init.ts",
|
|
32
|
+
"search": "bun run src/cli/search.ts",
|
|
33
|
+
"get": "bun run src/cli/get.ts",
|
|
34
|
+
"get:svg": "bun run src/cli/get.ts --format svg",
|
|
35
|
+
"get:geometry": "bun run src/cli/getGeometry.ts",
|
|
36
|
+
"test": "bun test",
|
|
37
|
+
"typecheck": "tsc --noEmit"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@gigatrappeur/ldraw-parser": "^1.0.2",
|
|
41
|
+
"@types/adm-zip": "^0.5.8",
|
|
42
|
+
"adm-zip": "^0.6.1",
|
|
43
|
+
"yargs-parser": "^22.0.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/bun": "latest",
|
|
47
|
+
"@types/yargs-parser": "^21.0.3",
|
|
48
|
+
"typescript": "^7.0.2"
|
|
49
|
+
},
|
|
50
|
+
"files": [
|
|
51
|
+
"src/",
|
|
52
|
+
"README.md",
|
|
53
|
+
"LICENSE"
|
|
54
|
+
]
|
|
6
55
|
}
|
package/src/cli/get.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// cli/get.ts — Récupérer les métadonnées ou générer un SVG d'une pièce
|
|
3
|
+
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import parser from "yargs-parser";
|
|
6
|
+
import { displayPartMetadata } from "../lib/part";
|
|
7
|
+
import BrickIndex from "..";
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
function printHelp(): void {
|
|
11
|
+
console.log(`
|
|
12
|
+
Usage: bun run cli/get.ts <ref> [options]
|
|
13
|
+
|
|
14
|
+
Options:
|
|
15
|
+
--data <path> Path vers dossier ou est extrait brick-index-data
|
|
16
|
+
--format <type> Format de sortie (json|human) (default: human)
|
|
17
|
+
--color <id> Couleur LDraw (default: 47)
|
|
18
|
+
--output <path> Fichier de sortie (default: <ref>.svg)
|
|
19
|
+
--width <px> Largeur SVG (default: 512)
|
|
20
|
+
--azimuth <deg> Azimut caméra (default: 30)
|
|
21
|
+
--elevation <deg> Élévation caméra (default: 15)
|
|
22
|
+
--help Afficher cette aide
|
|
23
|
+
|
|
24
|
+
Exemples:
|
|
25
|
+
bun run cli/get.ts 3001 # Métadonnées
|
|
26
|
+
bun run cli/get.ts 3001 --format json # Métadonnées en JSON prettifié
|
|
27
|
+
bun run cli/get.ts 3001 --format svg # SVG
|
|
28
|
+
bun run cli/get.ts 3001 --format svg --color 15 # SVG couleur rouge
|
|
29
|
+
bun run cli/get.ts 3001pb01 # Métadonnées par element ID
|
|
30
|
+
`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface ParsedArgs {
|
|
34
|
+
_: string[];
|
|
35
|
+
format: string;
|
|
36
|
+
color: number;
|
|
37
|
+
output: string;
|
|
38
|
+
width: number;
|
|
39
|
+
azimuth: number;
|
|
40
|
+
elevation: number;
|
|
41
|
+
help: boolean;
|
|
42
|
+
h: boolean;
|
|
43
|
+
data: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function run(args: string[] = []): Promise<void> {
|
|
47
|
+
const parsed = parser(args, {
|
|
48
|
+
alias: { h: "help" },
|
|
49
|
+
string: ["output", "format", "data"],
|
|
50
|
+
number: ["color", "width", "azimuth", "elevation"],
|
|
51
|
+
boolean: ["help", "h"],
|
|
52
|
+
default: {
|
|
53
|
+
color: 47,
|
|
54
|
+
width: 512,
|
|
55
|
+
azimuth: 30,
|
|
56
|
+
elevation: 15,
|
|
57
|
+
data: join(import.meta.dir, "..", "..", "data")
|
|
58
|
+
},
|
|
59
|
+
}) as ParsedArgs;
|
|
60
|
+
|
|
61
|
+
if (parsed.help || parsed.h) {
|
|
62
|
+
printHelp();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const ref = parsed._[0];
|
|
67
|
+
if (!ref) {
|
|
68
|
+
printHelp();
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const colorCode = parsed.color;
|
|
73
|
+
const width = parsed.width;
|
|
74
|
+
const azimuth = parsed.azimuth;
|
|
75
|
+
const elevation = parsed.elevation;
|
|
76
|
+
|
|
77
|
+
const index = new BrickIndex({dataDir: parsed.data})
|
|
78
|
+
|
|
79
|
+
if (['svg', 'glb', 'gltf'].includes(parsed.format)) {
|
|
80
|
+
|
|
81
|
+
const outputPath = parsed.output || `${ref}.${parsed.format}`;
|
|
82
|
+
|
|
83
|
+
if (parsed.format === 'svg') {
|
|
84
|
+
console.log(`Génération SVG pour ${ref}...`);
|
|
85
|
+
console.log(` Couleur: ${colorCode}`);
|
|
86
|
+
console.log(` Sortie: ${outputPath}`);
|
|
87
|
+
console.log(` Taille: ${width}x${width}`);
|
|
88
|
+
console.log(` Camera: azimuth=${azimuth}°, elevation=${elevation}°\n`);
|
|
89
|
+
} else {
|
|
90
|
+
console.log(`Génération ${parsed.format.toLocaleUpperCase()} pour ${ref}...`);
|
|
91
|
+
console.log(` Couleur: ${colorCode}`);
|
|
92
|
+
console.log(` Sortie: ${outputPath}`);
|
|
93
|
+
}
|
|
94
|
+
let file: string | Uint8Array;
|
|
95
|
+
if (parsed.format === 'svg' || parsed.format === 'gltf') {
|
|
96
|
+
file = await index.generate(ref, parsed.format as "svg" | "gltf", { width, azimuth, elevation, color: colorCode });
|
|
97
|
+
} else {
|
|
98
|
+
file = await index.generate(ref, parsed.format as "glb", { color: colorCode });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
await Bun.write(outputPath, file);
|
|
102
|
+
console.log(`${parsed.format.toUpperCase()} généré: ${outputPath} (${(file.length / 1024).toFixed(1)} Ko)`);
|
|
103
|
+
} else {
|
|
104
|
+
const metadata = await index.get(ref);
|
|
105
|
+
if (parsed.format === 'json') {
|
|
106
|
+
console.log(JSON.stringify(metadata, null, 2));
|
|
107
|
+
} else {
|
|
108
|
+
// Format « human readable » (défaut) : affichage libellé.
|
|
109
|
+
displayPartMetadata(metadata);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
index.close()
|
|
113
|
+
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Exécution directe (bun run cli/get.ts)
|
|
117
|
+
if (process.argv[1]?.replace(/\\/g, "/").endsWith("/get.ts")) {
|
|
118
|
+
run(process.argv.slice(2)).catch((err) => {
|
|
119
|
+
console.error("Erreur:", err);
|
|
120
|
+
process.exit(1);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// cli/getGeometry.ts — Récupérer la géométrie jsonifiable d'une pièce
|
|
3
|
+
// (meshs indexés par couleur + matériau), pour reconstruire un mesh côté front.
|
|
4
|
+
//
|
|
5
|
+
// Commande équivalente : `brick-index get:geometry <ref> [options]`.
|
|
6
|
+
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import parser from "yargs-parser";
|
|
9
|
+
import BrickIndex from "..";
|
|
10
|
+
import type { GeometryLengthUnit } from "../lib/geometry";
|
|
11
|
+
|
|
12
|
+
function printHelp(): void {
|
|
13
|
+
console.log(`
|
|
14
|
+
Usage: bun run cli/getGeometry.ts <ref> [options]
|
|
15
|
+
|
|
16
|
+
Récupère la géométrie triangulée d'une pièce, jsonifiable, groupée par couleur
|
|
17
|
+
et munie de son matériau (prêt à monter sur un BufferGeometry + matériau).
|
|
18
|
+
|
|
19
|
+
Commande équivalente : \`brick-index get:geometry <ref> [options]\`.
|
|
20
|
+
|
|
21
|
+
Options:
|
|
22
|
+
--data <path> Path vers dossier ou est extrait brick-index-data
|
|
23
|
+
--out <path> Fichier de sortie (defaut : stdout)
|
|
24
|
+
--normals <mode> "flat" (defaut) | "smooth" | "none" — normals de face / lissées / absentes
|
|
25
|
+
--no-weld Ne pas souder les sommets (soupe de triangles, indices séquentiels)
|
|
26
|
+
--unit <unité> Unité de sortie : ldu|mm|cm|m|in|studs (defaut : studs)
|
|
27
|
+
--help Afficher cette aide
|
|
28
|
+
|
|
29
|
+
Exemples:
|
|
30
|
+
bun run cli/getGeometry.ts 3001 # géométrie en JSON (weld + normals de face)
|
|
31
|
+
bun run cli/getGeometry.ts 3001 --unit mm # en millimètres
|
|
32
|
+
bun run cli/getGeometry.ts 3001 --normals smooth # normals lissées (fente 60°)
|
|
33
|
+
bun run cli/getGeometry.ts 3001 --normals none # sans normals
|
|
34
|
+
bun run cli/getGeometry.ts 3001 --no-weld # sans weld (soupe de triangles)
|
|
35
|
+
bun run cli/getGeometry.ts 3001 --out 3001.json # écrire dans un fichier
|
|
36
|
+
`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface ParsedArgs {
|
|
40
|
+
_: string[];
|
|
41
|
+
unit: string;
|
|
42
|
+
normals: string;
|
|
43
|
+
weld: boolean;
|
|
44
|
+
out: string;
|
|
45
|
+
help: boolean;
|
|
46
|
+
h: boolean;
|
|
47
|
+
data: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function run(args: string[] = []): Promise<void> {
|
|
51
|
+
const parsed = parser(args, {
|
|
52
|
+
alias: { h: "help" },
|
|
53
|
+
string: ["data", "out", "unit", "normals"],
|
|
54
|
+
boolean: ["help", "h", "weld"],
|
|
55
|
+
default: {
|
|
56
|
+
unit: "studs",
|
|
57
|
+
normals: "flat",
|
|
58
|
+
weld: true,
|
|
59
|
+
data: join(import.meta.dir, "..", "..", "data"),
|
|
60
|
+
},
|
|
61
|
+
}) as ParsedArgs;
|
|
62
|
+
|
|
63
|
+
if (parsed.help || parsed.h) {
|
|
64
|
+
printHelp();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const ref = parsed._[0];
|
|
69
|
+
if (!ref) {
|
|
70
|
+
printHelp();
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const unit = parsed.unit as GeometryLengthUnit;
|
|
75
|
+
const validUnits: GeometryLengthUnit[] = ["ldu", "mm", "cm", "m", "in", "studs"];
|
|
76
|
+
if (!validUnits.includes(unit)) {
|
|
77
|
+
console.error(`Unité inconnue : "${unit}". Valeurs possibles : ${validUnits.join(", ")}`);
|
|
78
|
+
process.exit(1);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const normals = parsed.normals === "none" ? false
|
|
82
|
+
: parsed.normals === "smooth" ? "smooth"
|
|
83
|
+
: "flat";
|
|
84
|
+
const weld = parsed.weld;
|
|
85
|
+
|
|
86
|
+
const index = new BrickIndex({ dataDir: parsed.data });
|
|
87
|
+
try {
|
|
88
|
+
console.error(`Génération de la géométrie pour ${ref}...`);
|
|
89
|
+
console.error(` Unité : ${unit}`);
|
|
90
|
+
console.error(` Normales : ${normals === false ? "aucune" : (normals === "smooth" ? "lissées (fente 60°)" : "de face (flat)")}`);
|
|
91
|
+
console.error(` Weld : ${weld ? "activé" : "désactivé (soupe de triangles)"}`);
|
|
92
|
+
|
|
93
|
+
const geometry = await index.getGeometry(ref, { unit, normals, weld: weld ? {} : false });
|
|
94
|
+
|
|
95
|
+
const json = JSON.stringify(geometry, null, 2);
|
|
96
|
+
if (parsed.out) {
|
|
97
|
+
await Bun.write(parsed.out, json);
|
|
98
|
+
console.error(`Géométrie générée : ${parsed.out} (${(json.length / 1024).toFixed(1)} Ko)`);
|
|
99
|
+
} else {
|
|
100
|
+
console.log(json);
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
index.close();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Exécution directe (bun run cli/getGeometry.ts)
|
|
108
|
+
if (process.argv[1]?.replace(/\\/g, "/").endsWith("/getGeometry.ts")) {
|
|
109
|
+
run(process.argv.slice(2)).catch((err) => {
|
|
110
|
+
console.error("Erreur:", err);
|
|
111
|
+
process.exit(1);
|
|
112
|
+
});
|
|
113
|
+
}
|
package/src/cli/index.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// cli/index.ts — CLI unifié pour brick-index
|
|
3
|
+
|
|
4
|
+
import { run as searchRun } from "./search";
|
|
5
|
+
import { run as getRun } from "./get";
|
|
6
|
+
import { run as getGeometryRun } from "./getGeometry";
|
|
7
|
+
import { runInit } from "./init";
|
|
8
|
+
|
|
9
|
+
const HELP = `
|
|
10
|
+
brick-index — catalogue de pièces LEGO/LDraw
|
|
11
|
+
|
|
12
|
+
Usage:
|
|
13
|
+
brick-index <command> [options]
|
|
14
|
+
|
|
15
|
+
Commandes:
|
|
16
|
+
init Télécharger les données (SQLite + LDraw)
|
|
17
|
+
search <query> Recherche de pièces (FTS5 + filtres)
|
|
18
|
+
get <ref> Métadonnées d'une pièce ou génération SVG/GLB
|
|
19
|
+
get:geometry <ref> Géométrie jsonifiable (meshs indexés + matériau)
|
|
20
|
+
|
|
21
|
+
Options:
|
|
22
|
+
--help, -h Afficher cette aide
|
|
23
|
+
|
|
24
|
+
Exemples:
|
|
25
|
+
brick-index init --version v1.0.0
|
|
26
|
+
brick-index search "brick 2x4" --category Bricks
|
|
27
|
+
brick-index get 3001 --format svg --color 15
|
|
28
|
+
brick-index get:geometry 3001 --unit mm
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
type Subcommand = "init" | "search" | "get" | "get:geometry";
|
|
32
|
+
|
|
33
|
+
const COMMANDS: Record<Subcommand, (args: string[]) => Promise<void>> = {
|
|
34
|
+
search: searchRun,
|
|
35
|
+
get: getRun,
|
|
36
|
+
"get:geometry": getGeometryRun,
|
|
37
|
+
init: runInit,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function printHelp(): void {
|
|
41
|
+
console.log(HELP);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function main(): Promise<void> {
|
|
45
|
+
const [command, ...args] = process.argv.slice(2);
|
|
46
|
+
|
|
47
|
+
if (!command || command === "help" || command === "-h" || command === "--help") {
|
|
48
|
+
printHelp();
|
|
49
|
+
process.exit(0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const handler = COMMANDS[command as Subcommand];
|
|
53
|
+
if (!handler) {
|
|
54
|
+
console.error(`Commande inconnue: "${command}"`);
|
|
55
|
+
console.error("Utilisez \"--help\" pour voir les commandes disponibles.");
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
await handler(args);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
main().catch((err) => {
|
|
63
|
+
console.error("[cli] Erreur:", err);
|
|
64
|
+
process.exit(1);
|
|
65
|
+
});
|
package/src/cli/init.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// cli/init.ts — Télécharger et extraire les données brick-index-data
|
|
3
|
+
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import { mkdir, rm } from "node:fs/promises";
|
|
7
|
+
import AdmZip from "adm-zip";
|
|
8
|
+
import parser from "yargs-parser";
|
|
9
|
+
|
|
10
|
+
function printHelp(): void {
|
|
11
|
+
console.log(`
|
|
12
|
+
Usage: bun run cli/init.ts [options]
|
|
13
|
+
|
|
14
|
+
Options:
|
|
15
|
+
--data <path> Dossier de destination (default: data/)
|
|
16
|
+
--url <url> URL directe de l'archive à télécharger
|
|
17
|
+
--version <tag> Tag GitHub release (default: latest)
|
|
18
|
+
--repo <owner/repo> Dépôt GitHub (default: Gigatrappeur/ldraw-index)
|
|
19
|
+
--force Forcer le téléchargement même si les données existent
|
|
20
|
+
--help Afficher cette aide
|
|
21
|
+
|
|
22
|
+
Exemples:
|
|
23
|
+
bun run cli/init.ts
|
|
24
|
+
bun run cli/init.ts --version v1.0.0
|
|
25
|
+
bun run cli/init.ts --url https://github.com/Gigatrappeur/ldraw-index/releases/download/v1.0.0/data.zip
|
|
26
|
+
bun run cli/init.ts --data /tmp/ldraw-data --force
|
|
27
|
+
`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function downloadFile(url: string, destPath: string): Promise<number> {
|
|
31
|
+
console.log(`[init] Téléchargement depuis ${url}...`);
|
|
32
|
+
|
|
33
|
+
const response = await fetch(url);
|
|
34
|
+
if (!response.ok || !response.body) {
|
|
35
|
+
throw new Error(`Échec du téléchargement (HTTP ${response.status})`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const totalBytes = Number(response.headers.get("content-length") ?? 0);
|
|
39
|
+
let received = 0;
|
|
40
|
+
let lastPercent = -1;
|
|
41
|
+
|
|
42
|
+
const file = Bun.file(destPath).writer();
|
|
43
|
+
const reader = response.body.getReader();
|
|
44
|
+
|
|
45
|
+
while (true) {
|
|
46
|
+
const { done, value } = await reader.read();
|
|
47
|
+
if (done) break;
|
|
48
|
+
file.write(value);
|
|
49
|
+
received += value.byteLength;
|
|
50
|
+
if (totalBytes > 0) {
|
|
51
|
+
const percent = Math.floor((received / totalBytes) * 100);
|
|
52
|
+
if (percent !== lastPercent && percent % 10 === 0) {
|
|
53
|
+
console.log(`[init] ${percent}% (${(received / 1024 / 1024).toFixed(0)} Mo)`);
|
|
54
|
+
lastPercent = percent;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
await file.end();
|
|
59
|
+
console.log(`[init] Téléchargement terminé (${(received / 1024 / 1024).toFixed(1)} Mo)`);
|
|
60
|
+
return received;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function getLatestReleaseTag(repo: string): Promise<string> {
|
|
64
|
+
console.log(`[init] Recherche dernière release de ${repo}...`);
|
|
65
|
+
const response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`);
|
|
66
|
+
if (!response.ok) {
|
|
67
|
+
throw new Error(`Impossible de récupérer la dernière release: HTTP ${response.status}`);
|
|
68
|
+
}
|
|
69
|
+
const data = (await response.json()) as { tag_name: string };
|
|
70
|
+
return data.tag_name;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function extractZip(archivePath: string, destDir: string): Promise<void> {
|
|
74
|
+
const zip = new AdmZip(archivePath);
|
|
75
|
+
zip.extractAllTo(destDir, true);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function runInit(args: string[] = []): Promise<void> {
|
|
79
|
+
const parsed = parser(args, {
|
|
80
|
+
alias: { h: "help" },
|
|
81
|
+
string: ["data", "url", "version", "repo"],
|
|
82
|
+
boolean: ["help", "h", "force"],
|
|
83
|
+
default: {
|
|
84
|
+
data: join(process.cwd(), "data"),
|
|
85
|
+
repo: "Gigatrappeur/ldraw-index",
|
|
86
|
+
},
|
|
87
|
+
}) as Record<string, unknown>;
|
|
88
|
+
|
|
89
|
+
if ((parsed['help'] as boolean) || (parsed['h'] as boolean)) {
|
|
90
|
+
printHelp();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const dataDir = parsed['data'] as string;
|
|
95
|
+
const explicitUrl = parsed['url'] as string | undefined;
|
|
96
|
+
const version = parsed['version'] as string | undefined;
|
|
97
|
+
const repo = parsed['repo'] as string;
|
|
98
|
+
const force = parsed['force'] as boolean;
|
|
99
|
+
|
|
100
|
+
// Vérifier si les données existent déjà
|
|
101
|
+
const sqlitePath = join(dataDir, "ldraw-data.sqlite");
|
|
102
|
+
if (!force && existsSync(sqlitePath)) {
|
|
103
|
+
console.log(`[init] Les données existent déjà dans ${dataDir}`);
|
|
104
|
+
console.log(` Utilisez --force pour re-télécharger.`);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
let downloadUrl: string;
|
|
109
|
+
|
|
110
|
+
if (explicitUrl) {
|
|
111
|
+
downloadUrl = explicitUrl;
|
|
112
|
+
} else {
|
|
113
|
+
let tag = version ?? (await getLatestReleaseTag(repo));
|
|
114
|
+
// GitHub API renvoie souvent le tag avec le préfixe 'v' (ex: v1.1.0)
|
|
115
|
+
// mais le nom du fichier archive n'inclut pas le préfixe (brick-data-1.1.0.zip)
|
|
116
|
+
const cleanTag = tag.startsWith('v') ? tag.slice(1) : tag;
|
|
117
|
+
console.log(`[init] Release: ${tag} (fichier: ${cleanTag})`);
|
|
118
|
+
downloadUrl = `https://github.com/${repo}/releases/download/${tag}/ldraw-data-${cleanTag}.zip`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
await mkdir(dataDir, { recursive: true });
|
|
122
|
+
|
|
123
|
+
const tmpFile = join(dataDir, ".data-download.zip");
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
await downloadFile(downloadUrl, tmpFile);
|
|
127
|
+
console.log("[init] Extraction (zip)...");
|
|
128
|
+
await extractZip(tmpFile, dataDir);
|
|
129
|
+
|
|
130
|
+
console.log(`[init] Données extraites dans ${dataDir}`);
|
|
131
|
+
} finally {
|
|
132
|
+
// Nettoyage du fichier temporaire
|
|
133
|
+
if (existsSync(tmpFile)) {
|
|
134
|
+
await rm(tmpFile);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Exécution directe (bun run cli/init.ts)
|
|
140
|
+
if (process.argv[1]?.replace(/\\/g, "/").endsWith("/init.ts")) {
|
|
141
|
+
runInit(process.argv.slice(2)).catch((err) => {
|
|
142
|
+
console.error("[init] Erreur:", err.message);
|
|
143
|
+
process.exit(1);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// cli/report.ts — Rapport de taille du cache
|
|
3
|
+
|
|
4
|
+
import { readdir } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
|
|
7
|
+
// TODO ajouter dans le calcul, le dossier contenantl base et les fichiers ldraw
|
|
8
|
+
const cacheDirs = ["cache/glb", "cache/sprite"];
|
|
9
|
+
// , "data/ldraw"
|
|
10
|
+
|
|
11
|
+
async function getTotalSize(dir: string): Promise<{ size: number; files: number }> {
|
|
12
|
+
let totalSize = 0;
|
|
13
|
+
let files = 0;
|
|
14
|
+
|
|
15
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
16
|
+
for (const entry of entries) {
|
|
17
|
+
const fullPath = join(dir, entry.name);
|
|
18
|
+
if (entry.isDirectory()) {
|
|
19
|
+
const sub = await getTotalSize(fullPath);
|
|
20
|
+
totalSize += sub.size;
|
|
21
|
+
files += sub.files;
|
|
22
|
+
} else if (entry.isFile()) {
|
|
23
|
+
const stat = await Bun.file(fullPath).stat();
|
|
24
|
+
totalSize += stat.size;
|
|
25
|
+
files++;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return { size: totalSize, files };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function formatReport(dir: string, sizeBytes: number, fileCount: number): string {
|
|
33
|
+
return `${dir}: ${(sizeBytes / 1024 / 1024).toFixed(2)} Mo (${fileCount} fichiers)`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
export async function run(): Promise<void> {
|
|
38
|
+
console.log("[report] Rapport de taille\n");
|
|
39
|
+
|
|
40
|
+
let grandTotal = 0;
|
|
41
|
+
|
|
42
|
+
for (const dir of cacheDirs) {
|
|
43
|
+
let stat;
|
|
44
|
+
try {
|
|
45
|
+
stat = await Bun.file(dir).stat();
|
|
46
|
+
} catch {
|
|
47
|
+
console.log(`${dir}: [non existant]`);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (!stat.isDirectory) {
|
|
51
|
+
console.log(`${dir}: [non existant]`);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const { size: totalSize, files } = await getTotalSize(dir);
|
|
56
|
+
grandTotal += totalSize;
|
|
57
|
+
console.log(formatReport(dir, totalSize, files));
|
|
58
|
+
console.log("");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Taille de la base
|
|
62
|
+
// const dbStat = await Bun.file(DB.PATH).stat();
|
|
63
|
+
// grandTotal += dbStat.size;
|
|
64
|
+
// console.log(`data/brick-data.sqlite:`);
|
|
65
|
+
// console.log(` Taille: ${(dbStat.size / 1024 / 1024).toFixed(2)} Mo`);
|
|
66
|
+
// console.log("");
|
|
67
|
+
|
|
68
|
+
console.log(`Total: ${(grandTotal / 1024 / 1024).toFixed(2)} Mo`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Exécution directe (bun run cli/report.ts)
|
|
72
|
+
if (process.argv[1]?.replace(/\\/g, "/").endsWith("/report.ts")) {
|
|
73
|
+
run().catch((err) => {
|
|
74
|
+
console.error("[report] Erreur:", err);
|
|
75
|
+
process.exit(1);
|
|
76
|
+
});
|
|
77
|
+
}
|