-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Expand file tree
/
Copy pathfix_image_paths_correct.js
More file actions
67 lines (55 loc) · 2.17 KB
/
fix_image_paths_correct.js
File metadata and controls
67 lines (55 loc) · 2.17 KB
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
const fs = require('fs');
const path = require('path');
function getAllMdFiles(dir) {
let files = [];
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...getAllMdFiles(fullPath));
} else if (entry.name.endsWith('.md')) {
files.push(fullPath);
}
}
return files;
}
// Find corresponding Chinese version images
function findChineseImages(enMdPath) {
// en/dishes/soup/昂刺鱼豆腐汤/昂刺鱼豆腐汤.md → dishes/soup/昂刺鱼豆腐汤/
const relative = path.relative('/home/anduin/Desktop/HowToCook/en', enMdPath);
const chinesePath = path.join('/home/anduin/Desktop/HowToCook', relative);
const chineseDir = path.dirname(chinesePath);
if (!fs.existsSync(chineseDir)) return [];
return fs.readdirSync(chineseDir)
.filter(f => /\.(jpg|jpeg|png|gif)$/i.test(f))
.sort();
}
const mdFiles = getAllMdFiles('/home/anduin/Desktop/HowToCook/en');
let fixed = 0;
for (const mdFile of mdFiles) {
let content = fs.readFileSync(mdFile, 'utf8');
const originalContent = content;
const chineseImages = findChineseImages(mdFile);
if (chineseImages.length === 0) continue;
// Replace all image references with relative paths to Chinese images
const imageRegex = /!\[([^\]]*)\]\(\.\/([^)]*)\)/g;
let match;
let imageIndex = 0;
content = content.replace(imageRegex, (fullMatch, alt, imageName) => {
if (imageIndex < chineseImages.length) {
const correctImage = chineseImages[imageIndex];
// Use relative path going up to dishes/ then down to Chinese image
const relPath = `../../dishes${mdFile.substring('/home/anduin/Desktop/HowToCook/en/dishes'.length).replace(/\/[^\/]+\.md$/, '')}/${correctImage}`;
console.log(`Fixed: ${path.relative('/home/anduin/Desktop/HowToCook', mdFile)}`);
console.log(` ${imageName} -> ${relPath}`);
imageIndex++;
fixed++;
return ``;
}
return fullMatch;
});
if (content !== originalContent) {
fs.writeFileSync(mdFile, content);
}
}
console.log(`\nTotal images fixed: ${fixed}`);