Skip to content

Instantly share code, notes, and snippets.

@evoactivity
Created February 17, 2023 16:32
Show Gist options
  • Save evoactivity/74554b84fb7217e89cbaf8ca558546b3 to your computer and use it in GitHub Desktop.
Save evoactivity/74554b84fb7217e89cbaf8ca558546b3 to your computer and use it in GitHub Desktop.
Deduplicate Git Ignore (.gitignore)
/**
* Remove duplicates from .gitignore
*
* This function reads the .gitignore file, removes duplicates, and overwrites the gitignore file.
*
* @param pathToLocalRepo - Path to the local git repository. Default is the current working directory.
*/
async function dedupeGitIgnore(pathToLocalRepo: string | null = null): Promise<void> {
if (!pathToLocalRepo) {
pathToLocalRepo = Deno.cwd();
}
stopIfDirNotExist(pathToLocalRepo);
const input = await readGitIgnore(pathToLocalRepo);
const output: string[] = [];
const seen: Set<string> = new Set();
input.forEach((line, index) => {
if (line === '' || !seen.has(line)) {
seen.add(line);
output.push(line);
} else if (line.startsWith('#')) {
// Preserve duplicate comment lines
output.push(line);
}
});
const gitignore_path = `${pathToLocalRepo}/.gitignore`;
await Deno.writeTextFile(gitignore_path, output.join('\n') + '\n');
}
async function readGitIgnore(path_to_local_repo: string): Promise<string[]> {
const gitignore_path = `${path_to_local_repo}/.gitignore`;
try {
const data = await Deno.readTextFile(gitignore_path);
return data.trim().split('\n');
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
return [];
}
throw e;
}
}
function stopIfDirNotExist(path_to_local_repo: string): void {
try {
const stats = Deno.statSync(path_to_local_repo);
if (!stats.isDirectory) {
throw new Error(`Directory not found: ${path_to_local_repo}`);
}
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
throw new Error(`Directory not found: ${path_to_local_repo}`);
}
throw e;
}
}
dedupeGitIgnore();
@evoactivity
Copy link
Author

Run with

deno run dedupe.ts

or

deno run --allow-read --allow-write dedupe.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment