-
Notifications
You must be signed in to change notification settings - Fork 0
/
outbreak.ts
465 lines (406 loc) · 12.4 KB
/
outbreak.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import { walk } from "jsr:@std/fs/walk";
import {
basename,
dirname,
extname,
globToRegExp,
join,
relative,
} from "jsr:@std/path";
import { sprintf } from "jsr:@std/fmt/printf";
import { blue, cyan, dim, green, red, yellow } from "jsr:@std/fmt/colors";
import { Spinner } from "jsr:@std/cli/unstable-spinner";
import moment from "npm:moment";
import {
formatProperties,
parseFrontmatter,
renameAndFilterProperties,
translate,
} from "./translate.ts";
import { outlineChunks, splitIntoChunks } from "./outline.ts";
interface ObsidianDailyNotesConfig {
format?: string;
folder?: string;
}
interface ObsidianAppConfig {
attachmentFolderPath?: string;
}
interface MigrationConfig {
useNamespaces: boolean;
extraDailyNotesFormats: string[];
journalDateFormat: string;
ignoredPaths: string[];
dryRun: boolean;
}
interface MigrationPlan {
inputPath: string;
outputPath: string;
renamed?: { oldName: string; newName: string };
type: "journals" | "assets" | "pages";
message?: string;
}
// Function to read and parse Obsidian's daily notes configuration
async function readDailyNotesConfig(
vaultPath: string,
): Promise<ObsidianDailyNotesConfig> {
try {
const configPath = join(vaultPath, ".obsidian", "daily-notes.json");
const content = await Deno.readTextFile(configPath);
return JSON.parse(content);
} catch (_error) {
console.warn(
yellow("⚠️ Could not read daily notes config, using defaults"),
);
return {};
}
}
// Function to check if a file matches the daily notes format
function isDailyNote(
filePath: string,
dailyNotesConfig: ObsidianDailyNotesConfig,
migrationConfig: MigrationConfig,
): boolean {
const format = dailyNotesConfig.format || "YYYY-MM-DD";
const folder = dailyNotesConfig.folder || ""; // Default to root if not specified
// Construct full format including the folder
const fullFormat = folder ? `[${folder}]/${format}` : format;
// Drop the extension
const notePath = filePath.slice(0, -extname(filePath).length);
// Try to parse it with moment.js (strict mode)
const parsedMoment = moment(notePath, [
fullFormat,
...migrationConfig.extraDailyNotesFormats,
], true);
return parsedMoment.isValid();
}
// TODO: this might come handy in the future, but isn't used right now
async function _readObsidianAppConfig(
vaultPath: string,
): Promise<ObsidianAppConfig> {
try {
const configPath = join(vaultPath, ".obsidian", "app.json");
const content = await Deno.readTextFile(configPath);
return JSON.parse(content);
} catch (_error) {
console.warn(
yellow("⚠️ Could not read Obsidian config, using defaults"),
);
return {};
}
}
// Function to check if a file is an asset
function isAsset(filePath: string): boolean {
// const attachmentFolder = config.attachmentFolderPath || "attachments";
// return dirname(filePath).startsWith(attachmentFolder);
return extname(filePath) !== ".md";
}
function newPageName(filePath: string, useNamespaces: boolean): string {
const filename = useNamespaces
? filePath.replace(/[/]/g, "___") // Replace slashes with triple underscores (Logseq convention)
: basename(filePath); // Keep only the filename (note names should be unique in Obsidian)
return filename;
}
// Function to create migration plan for a single file
function planFileMigration(
inputPath: string,
inputDir: string,
outputDir: string,
dailyNotesConfig: ObsidianDailyNotesConfig,
config: MigrationConfig,
): MigrationPlan {
const relativePath = relative(inputDir, inputPath);
if (isDailyNote(relativePath, dailyNotesConfig, config)) {
const inputFilename = basename(relativePath, extname(relativePath));
const inputFormat = basename(dailyNotesConfig.format || "YYYY-MM-DD");
const outputFormat = config.journalDateFormat;
// Reformat the date string according to the configured format
const parsedDate = moment(inputFilename, [
inputFormat,
...config.extraDailyNotesFormats.map((f) => basename(f)),
]);
const reformattedDate = parsedDate.isValid()
? parsedDate.format(outputFormat)
: inputFilename;
const renamed = reformattedDate === inputFilename ? undefined : {
oldName: inputFilename,
newName: reformattedDate,
};
return {
inputPath: inputPath,
outputPath: join(outputDir, "journals", `${reformattedDate}.md`),
type: "journals",
renamed: renamed,
message: parsedDate.isValid()
? undefined
: yellow("⚠️ Could not parse as a date"),
};
}
// Handle assets
if (isAsset(relativePath)) {
return {
inputPath: inputPath,
outputPath: join(outputDir, "assets", basename(relativePath)),
type: "assets",
};
}
// Handle regular pages
return {
inputPath: inputPath,
outputPath: join(
outputDir,
"pages",
newPageName(relativePath, config.useNamespaces),
),
type: "pages",
};
}
// Function to print migration plan
function printMigrationPlan(
plans: MigrationPlan[],
inputDir: string,
outputDir: string,
): void {
const counts = {
journals: 0,
assets: 0,
pages: 0,
warnings: 0,
};
console.log("\n📋 Migration Plan:");
function sourceColor(t: string) {
return t === "journals" ? blue : t === "assets" ? cyan : green;
}
for (const plan of plans) {
counts[plan.type]++;
if (plan.message) counts.warnings++;
const logEntry = [
sourceColor(plan.type)(relative(inputDir, plan.inputPath)),
"\n ",
dim(relative(outputDir, plan.outputPath)),
plan.message ? plan.message : "",
].join(" ");
console.log(logEntry);
}
console.log("\nSummary:");
console.log(sourceColor("journals")(`📅 ${counts.journals} journals`));
console.log(sourceColor("assets")(`📎 ${counts.assets} assets`));
console.log(sourceColor("pages")(`📝 ${counts.pages} pages`));
if (counts.warnings > 0) {
console.log("\nWarnings:");
console.log(
yellow(
`⚠️ ${counts.warnings} files could not be parsed as dates (see above)`,
),
);
}
}
export function markdownToLogseq(
content: string,
plan?: MigrationPlan,
) {
// First process frontmatter
const { frontmatter, body } = parseFrontmatter(content);
const filteredFrontmatter = renameAndFilterProperties(frontmatter);
if (plan?.type === "journals") {
// remove "created" from frontmatter
delete filteredFrontmatter["created"];
// if the journals date format is not the same, add the old file name as an alias
if (plan.renamed) {
const aliases = new Set([
plan.renamed.oldName,
...(filteredFrontmatter["alias"] || []),
]);
aliases.delete(plan.renamed.newName);
filteredFrontmatter["alias"] = Array.from(aliases);
}
}
const properties = formatProperties(filteredFrontmatter);
const propertiesBlock = properties.length
? properties.join("\n") + "\n\n"
: "";
// Then split the body into chunks and apply conversion
const chunks = splitIntoChunks(body).map((chunk) => {
const translated = translate(chunk.content);
return { ...chunk, content: translated };
});
// Now outline translated chunks
const outline = outlineChunks(chunks, { listNesting: "paragraph" });
// Reconstruct the final content
const outlinedContent = propertiesBlock + outline;
return outlinedContent;
}
// Function to execute migration plan
async function executeMigrationPlan(
plans: MigrationPlan[],
): Promise<void> {
const spinner = new Spinner({
message: "Executing migration plan...",
color: "cyan",
});
spinner.start();
let processed = 0;
const total = plans.length;
for (const plan of plans) {
spinner.message = sprintf(
"Processing (%d/%d): %s",
processed + 1,
total,
dim(relative("", plan.inputPath)),
);
// Ensure destination directory exists
await Deno.mkdir(dirname(plan.outputPath), { recursive: true });
if (plan.type === "assets") {
// Simple copy for assets
await Deno.copyFile(plan.inputPath, plan.outputPath);
} else {
// Process markdown files
const content = await Deno.readTextFile(plan.inputPath);
const convertedContent = await markdownToLogseq(
content,
plan,
);
await Deno.writeTextFile(plan.outputPath, convertedContent);
}
processed++;
}
spinner.stop();
}
const defaultConfig: MigrationConfig = {
useNamespaces: false,
extraDailyNotesFormats: [
"[journal]/YYYY/YYYY-MM-DD",
"[journal]/YYYY/MM/YYYY-MM-DD",
],
journalDateFormat: "YYYY-MM-DD",
ignoredPaths: [
// "archive/**",
"**/*.txt",
"**/*.json",
".*/**", // any hidden directories in the root
"**/.*", // hidden files (anywhere)
],
dryRun: false,
};
export async function migrateVault(
inputDir: string,
outputDir: string,
options: Partial<MigrationConfig> = {},
) {
const prepSpinner = new Spinner({
message: "🦠 Outbreak: Migrating Obsidian vault to Logseq...",
color: "cyan",
});
prepSpinner.start();
const migrationConfig: MigrationConfig = {
...defaultConfig,
...options,
};
prepSpinner.stop();
// Request permissions to read from input directory
await Deno.permissions.request({ name: "read", path: inputDir });
// Initialize spinner for file discovery
const scanSpinner = new Spinner({
message: `📦 Finding files in ${dim(inputDir)}...`,
color: "cyan",
});
scanSpinner.start();
// Read Obsidian configuration
const dailyNotesConfig = await readDailyNotesConfig(inputDir);
// Find all files
const discoveredFiles = walk(inputDir, {
includeDirs: false,
// These are hard-ignored patterns:
skip: [
/\.DS_Store/,
/\.git/,
/\.obsidian/,
/\.trash/,
/\.vscode/,
],
});
const files: string[] = [];
// Track soft-ignored paths
const ignored: Record<string, number> = {};
for await (const entry of discoveredFiles) {
// Skip ignored paths
const ignorePattern = migrationConfig.ignoredPaths.find((pattern) =>
globToRegExp(pattern).test(relative(inputDir, entry.path))
);
if (ignorePattern) {
const key = ignorePattern.includes("**")
? dirname(relative(inputDir, entry.path)).split("/")[0]
: ignorePattern;
ignored[key] = (ignored[key] || 0) + 1;
continue;
}
files.push(entry.path);
}
scanSpinner.stop();
if (files.length === 0) {
console.log(yellow("\n⚠️ No files found in the specified directory.\n"));
return;
}
console.log(`\n🔄 Found ${green(files.length.toString())} files to process`);
// Create migration plans for all files
const plans = files.map((file) =>
planFileMigration(
file,
inputDir,
outputDir,
dailyNotesConfig,
migrationConfig,
)
);
// Print migration plan
printMigrationPlan(plans, inputDir, outputDir);
const ignoredTotal = Object.values(ignored).reduce((a, b) => a + b, 0);
console.log(dim(`\nIgnored: ${ignoredTotal} files`));
for (const [path, count] of Object.entries(ignored)) {
console.log(dim(`- ${path} (${count} files)`));
}
if (migrationConfig.dryRun) {
console.log(yellow("\n🔍 Dry run completed. No files were modified.\n"));
return;
}
// Ask for confirmation
const confirmed = await confirm(
"\nDo you want to proceed with the migration?",
);
if (!confirmed) {
console.log(red("\n❌ Operation cancelled by user\n"));
return;
}
// Execute migration
await Deno.permissions.request({ name: "write", path: outputDir });
await executeMigrationPlan(plans);
console.log(green("\n✅ Migration completed successfully!\n"));
}
// CLI handler
if (import.meta.main) {
const inputDir = Deno.args[0];
const outputDir = Deno.args[1];
const flags = new Set(Deno.args.slice(2));
if (!inputDir || !outputDir) {
console.log(
"Usage: deno run outbreak.ts <input-dir> <output-dir> [options]",
);
console.log("\nOptions:");
console.log(
" --use-namespaces Convert folder structure to Logseq namespaces",
);
console.log(
" --dry-run Show what would be migrated without making changes",
);
Deno.exit(1);
}
// Parse options
const options: Partial<MigrationConfig> = {
useNamespaces: flags.has("--use-namespaces"),
dryRun: flags.has("--dry-run"),
};
await migrateVault(inputDir, outputDir, options)
.catch((error) => {
console.error("\n❌ Error during migration:", error);
Deno.exit(1);
});
}