Created
September 6, 2020 19:33
-
-
Save threepointone/9b18bd047a676c87d73a12dc96587576 to your computer and use it in GitHub Desktop.
The implementation behind https://twitter.com/threepointone/status/1302620352250605568
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 tree from "./tree"; | |
test("it should serialise the tree", () => { | |
expect(tree("path/to/folder")).toMatchInlineSnapshot(); // jest will fill this in automatically | |
}); |
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
// this is typescript, feel free to remove the type signatures and stuff | |
import fs from 'fs'; | |
import path from 'path'; | |
import asciiTree from 'ascii-tree'; | |
import hash from '@emotion/hash'; | |
function times(str: string, length: number) { | |
return Array.from({ length }, () => str).join(''); | |
} | |
const ignores = [ | |
'node_modules', | |
'.git', | |
'.DS_Store', | |
// ignoring lockfiles here because it can be different | |
// on different runs; since we install the latest versions | |
// of some packages when making a repository | |
// you maye want to include them, or whatever. | |
'yarn.lock', | |
'package-lock.json', | |
]; | |
function tree(_path: string, level = 1): string { | |
const stat = fs.statSync(_path); | |
if (stat.isDirectory()) { | |
const children = fs.readdirSync(_path); | |
const dirArr = _path.split('/'); | |
const dir = dirArr[dirArr.length - 1]; | |
// todo - should these be sorted? | |
// todo - handle symlinks, etc | |
return `${times('#', level)}${dir}\n${children | |
.filter((child) => !ignores.includes(child)) | |
.map((child) => tree(path.join(_path, child), level + 1)) | |
.join('\n')}`; | |
} else { | |
return `${times('#', level)}${path.basename(_path)} #${hash( | |
fs.readFileSync(_path, 'utf8'), | |
)}`; | |
} | |
} | |
export default function generate(_path: string): string { | |
return asciiTree.generate(tree(_path)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment