Created
November 12, 2022 14:09
-
-
Save taverasmisael/e790fbd833f076e14200261f98593488 to your computer and use it in GitHub Desktop.
Simple and non-recursive way to rename index files on a directory to have the same name as the directory it is in
This file contains hidden or 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
import path from 'path' | |
import fs from 'fs' | |
const cwd = path.resolve('[YOUR DIR]') | |
const dirs = fs.readdirSync(cwd) | |
const isFile = (baseDir: string) => (dir: string) => | |
fs.lstatSync(path.join(baseDir, dir)).isFile() | |
const and = | |
<T>(...args: ((v: T) => boolean)[]) => | |
(v: T): boolean => | |
args.reduce((a, b) => a && b(v), true) | |
const files = dirs.reduce((acc, dir) => { | |
const currentPath = path.join(cwd, dir) | |
const stats = fs.lstatSync(currentPath) | |
if (stats.isDirectory()) { | |
// we just want the first level | |
const indexFile = fs | |
.readdirSync(currentPath) | |
.find( | |
and( | |
isFile(currentPath), | |
(name: string) => name.split('.')[0] === 'index' | |
) | |
) | |
if (!indexFile) { | |
// skip directories without index files. | |
return acc | |
} | |
return { ...acc, [dir]: indexFile } | |
} | |
return acc | |
}, {} as Record<string, string>) //? | |
const entries = Object.entries(files) //? $.length | |
const rename = (entries: [string, string][]) => | |
entries.forEach(([dir, name]) => { | |
const oldName = path.join(cwd, dir, name) | |
const newName = path.join(cwd, dir, `${dir}${path.extname(name)}`) | |
fs.renameSync(oldName, newName) | |
}) | |
// rename(entries) // Uncomment this and see the magic happen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This snippet assumes an astro content collection type of thing.