Skip to content

Instantly share code, notes, and snippets.

@Namaskar-1F64F
Last active April 21, 2023 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Namaskar-1F64F/6515b349e596bd712e4593a4d9a345c9 to your computer and use it in GitHub Desktop.
Save Namaskar-1F64F/6515b349e596bd712e4593a4d9a345c9 to your computer and use it in GitHub Desktop.
Replace paths for IPFS
/* eslint-disable */
const fs = require("fs/promises");
const path = require('path')
const process = require('process')
const replaceRules = [
// Replace all absolute paths with relative paths
// Replace src="/example" with src="example" and href="/example" with href="example"
[/ (src|href)="\/(?!\/)/g, ' $1="'],
// Replace url("/example") with url("example")
[/url\((('|")?\/(?!\/))/g, 'url($2'],
// Replace src="/example" with src="example"
[/src:("|')\/(?!\/)/g, 'src:$1'],
// Replace href=\"\/example\" with href=\"example\"
[/href=\\("|')\/(?!\/)/g, 'href=\\$1'],
// Replace href: \"\/example\" with href: \"example\"
[/(href|path): \\("|')\/(?!\/)/g, '$1: \\$2'],
// Replace href: "/example" with href: "example" and path: "/example" with path: "example"
[/(href|path):("|')\/(?!\/)/g, '$1:$2'],
// Replace all /_next with _next
[/\/_next/g, '_next'],
]
function replaceContent(content) {
let totalReplacements = 0;
for (const [pattern, replacement] of replaceRules) {
const before = content;
content = content.replace(pattern, replacement);
totalReplacements += (before.length - content.length) / (replacement.length - pattern.toString().length);
}
return { content, totalReplacements };
}
async function processFile(filePath) {
const content = await fs.readFile(filePath, "utf-8");
const { content: updatedContent, totalReplacements } = replaceContent(content);
await fs.writeFile(filePath, updatedContent);
return totalReplacements;
}
async function processDirectory(dir) {
let totalReplacements = 0;
const files = await fs.readdir(dir);
const tasks = files.map(async (file) => {
const filePath = path.join(dir, file);
const stats = await fs.stat(filePath);
if (stats.isDirectory()) {
totalReplacements += await processDirectory(filePath);
} else if ([".js", ".html", ".css", ".map"].includes(path.extname(file))) {
totalReplacements += await processFile(filePath);
}
});
await Promise.all(tasks);
return totalReplacements;
}
async function main() {
try {
const directory = process.argv[2];
if (!directory) {
console.error("Please provide a directory as an argument.");
process.exit(1);
}
const totalReplacements = await processDirectory(directory);
console.log(`Total replacements: ${totalReplacements}`);
} catch (error) {
console.error(`Error: ${error.message}`);
process.exit(1);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment