Created
October 25, 2022 18:05
-
-
Save TerrorJack/acc284f73b3c8c906b9b6a244af177a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env -S deno run --allow-read --allow-write | |
import * as flags from "https://deno.land/std@0.160.0/flags/mod.ts"; | |
import * as fs from "https://deno.land/std@0.160.0/fs/mod.ts"; | |
function hash_decomp(p: string) { | |
const i = p.search(/ [a-f0-9]{32}/); | |
if (i === -1) { | |
return [p, null]; | |
} | |
return [`${p.slice(0, i)}${p.slice(i + 33)}`, p.slice(i + 1, i + 33)]; | |
} | |
async function hash_collect(p0: string, p1: string): Set<string> { | |
let s = new Set(); | |
const [_, h] = hash_decomp(p1); | |
if (h) { | |
s.add(h); | |
} | |
const p = `${p0}/${p1}`; | |
const { isDirectory } = await Deno.stat(p); | |
if (isDirectory) { | |
for await (const { name } of Deno.readDir(p)) { | |
s = new Set([...s, ...(await hash_collect(p, name))]); | |
} | |
} | |
return s; | |
} | |
function should_rewrite(p: string) { | |
for (const ext of ["csv", "md"]) { | |
if (p.endsWith(`.${ext}`)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
async function hash_rewrite(s: Set<string>, p0: string, p1: string) { | |
const [p2, h] = hash_decomp(p1); | |
let p = `${p0}/${p1}`; | |
if (h) { | |
if (!s.has(h)) { | |
throw new Error(`hash_rewrite ${p}: non-existent hash ${h}`); | |
} | |
await Deno.rename(p, `${p0}/${p2}`); | |
p = `${p0}/${p2}`; | |
} | |
console.log(p); | |
const { isDirectory } = await Deno.stat(p); | |
if (isDirectory) { | |
for await (const { name } of Deno.readDir(p)) { | |
await hash_rewrite(s, p, name); | |
} | |
return; | |
} | |
if (should_rewrite(p)) { | |
let str = await Deno.readTextFile(p); | |
for(const s0 of s) { | |
str = str.replaceAll(`%20${s0}`,""); | |
} | |
await Deno.writeTextFile(p, str); | |
} | |
} | |
const hashes = await hash_collect("/", "/workspace/deno-playground/tmp.Nx2ow27kGt"); | |
await hash_rewrite(hashes, "/", "/workspace/deno-playground/tmp.Nx2ow27kGt"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment