Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created September 6, 2020 19:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save threepointone/9b18bd047a676c87d73a12dc96587576 to your computer and use it in GitHub Desktop.
Save threepointone/9b18bd047a676c87d73a12dc96587576 to your computer and use it in GitHub Desktop.
import tree from "./tree";
test("it should serialise the tree", () => {
expect(tree("path/to/folder")).toMatchInlineSnapshot(); // jest will fill this in automatically
});
// 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