Create Memory Space
Creates the directory structure and files for a memory space based on schema
Source Code
import * as fs from "fs";
import * as path from "path";
const [basePath, schema, files] = process.argv.slice(2);
if (!basePath || !schema) {
console.error("Usage: code:memory.space.create <basePath> <schema> [files]");
process.exit(1);
}
try {
const schemaObj = JSON.parse(schema);
const filesArr = files ? JSON.parse(files) : [];
// Create base directory
const fullBasePath = path.resolve(basePath);
fs.mkdirSync(fullBasePath, { recursive: true });
console.log(`Created base directory: ${fullBasePath}`);
// Write schema.json
const schemaPath = path.join(fullBasePath, "schema.json");
fs.writeFileSync(schemaPath, JSON.stringify(schemaObj, null, 2));
console.log(`Wrote schema: ${schemaPath}`);
// Create assets directory for raw files (PDFs, receipts, etc.)
const assetsPath = path.join(fullBasePath, "assets");
fs.mkdirSync(assetsPath, { recursive: true });
console.log(`Created assets directory: ${assetsPath}`);
// Create directories for static file locations
const createdDirs = new Set();
for (const location of schemaObj.locations || []) {
if (location.type === "file") {
const filePath = path.join(fullBasePath, location.path);
const dirPath = path.dirname(filePath);
if (dirPath !== fullBasePath && !createdDirs.has(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
createdDirs.add(dirPath);
console.log(`Created directory: ${dirPath}`);
}
} else if (location.type === "glob") {
// For globs, create the parent directory if it has a static prefix
// e.g., "drafts/[slug].md" → create "drafts/"
const globPath = location.path;
const staticPrefix = globPath.split("[")[0];
if (staticPrefix && staticPrefix !== globPath) {
const dirPath = path.join(fullBasePath, staticPrefix);
if (!createdDirs.has(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
createdDirs.add(dirPath);
console.log(`Created directory for glob: ${dirPath}`);
}
}
}
}
// Write starter files
for (const file of filesArr) {
const filePath = path.join(fullBasePath, file.path);
const dirPath = path.dirname(filePath);
fs.mkdirSync(dirPath, { recursive: true });
fs.writeFileSync(filePath, file.content);
console.log(`Wrote starter file: ${filePath}`);
}
// Summary
console.log("\n--- Memory Space Created ---");
console.log(`Name: ${schemaObj.name}`);
console.log(`Location: ${fullBasePath}`);
console.log(`Locations defined: ${(schemaObj.locations || []).length}`);
console.log(`Starter files written: ${filesArr.length}`);
console.log(`\nSchema saved to: ${schemaPath}`);
} catch (error) {
console.error(`Error creating memory space: ${error.message}`);
process.exit(1);
}