Skip to content

Instantly share code, notes, and snippets.

@dfee
Created May 14, 2020 19:18
Show Gist options
  • Save dfee/bd743564b0dd30b4aae8b5751a134aef to your computer and use it in GitHub Desktop.
Save dfee/bd743564b0dd30b4aae8b5751a134aef to your computer and use it in GitHub Desktop.
type MapDirContentsOptions = {
dirPath: string;
pattern: string;
};
const mapDirContents = ({
dirPath,
pattern,
}: MapDirContentsOptions): Map<string, string> => {
const fileNames = glob.sync(path.join(dirPath, pattern), {
dot: true,
nodir: true,
});
fileNames.sort((a, b) => a.localeCompare(b));
return new Map(
fileNames.map((fileName) => [
path.relative(dirPath, fileName),
fs.readFileSync(fileName).toString(),
]),
);
};
describe("mapDirContents", () => {
let tmpDir: DirResult;
beforeAll(() => {
tmpDir = tmp.dirSync({ unsafeCleanup: true });
});
afterAll(() => {
tmpDir.removeCallback();
});
const writeFile = (relPath: string, contents: string) => {
const filePath = path.join(tmpDir.name, relPath);
mkdirp.sync(path.parse(filePath).dir);
fs.writeFileSync(filePath, contents);
};
it("should produce expected content", () => {
const data = new Map([
[".env", "HELLO=WORLD"],
["package.json", JSON.stringify({ name: "mypkg" })],
["src/index.ts", 'export const PACKAGE_NAME = "mypkg";'],
]);
Array.from(data).forEach(([fileName, contents]) =>
writeFile(fileName, contents),
);
const result = mapDirContents({ dirPath: tmpDir.name, pattern: "**" });
expect(result).toEqual(data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment