Created
February 23, 2020 06:05
-
-
Save justingreenberg/189f75c365c0e74497248cfd462c31b2 to your computer and use it in GitHub Desktop.
Recursively prepend a header banner to all files in directory
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
const fs = require('fs').promises; | |
const path = require('path'); | |
interface Params { | |
dir: string; | |
header: string; | |
predicate: (filePath: string) => Boolean; | |
} | |
interface WalkTree { | |
(params: Omit<Params, 'header'>): AsyncGenerator<string, void, void>; | |
} | |
interface Headers { | |
(params: Params): Promise<void>; | |
} | |
export const walkTree: WalkTree = async function*({ dir, predicate }) { | |
const files = await fs.readdir(dir); | |
for (const file of files) { | |
const filePath = path.join(dir, file); | |
const stat = await fs.stat(filePath); | |
if (stat.isDirectory()) { | |
yield* walkTree({ dir: filePath, predicate }); | |
} else if (predicate(file)) { | |
yield filePath; | |
} | |
} | |
}; | |
export const headers: Headers = async ({ dir, header, predicate }) => { | |
for await (const filePath of walkTree({ dir, predicate })) { | |
const start = process.hrtime(); | |
const data = Buffer.from(await fs.readFile(filePath)); | |
if (data.indexOf(header) === 0) continue; | |
const fd = await fs.open(filePath, 'w+'); | |
await fd.write(header, 0, header.length, 0); | |
await fd.write(data, 0, data.length, header.length); | |
await fd.close(); | |
const [, ns] = process.hrtime(start); | |
const ms = ns / 1000000; | |
console.info(`${filePath} ${ms}ms`); | |
} | |
}; | |
const header = `\/** | |
* Copyright (c) Seamless Payments, Inc. | |
* | |
* This source code is licensed under the MIT license found in the | |
* LICENSE file in the root directory of this source tree. | |
*/\n\n`; | |
headers({ | |
dir: '.', | |
header, | |
predicate: filePath => /\.java$/.test(filePath), | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment