Created
July 16, 2023 22:23
-
-
Save ChukwuEmekaAjah/03603bf057a84695aadaf79b313a50f2 to your computer and use it in GitHub Desktop.
A basic implementation of how files to be ignored in 'ignore' files are found and ignored
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 * as path from "path" | |
import * as fs from "fs" | |
// find all files that match the corresponding splitted directory component | |
// find all files and folders that match the regular expression of the corresponding path | |
// filter out all unmatched files/folders from the list based on splitted path | |
function getIgnoredFiles(ignorePath: string) :string[]{ | |
const allFiles = walk(process.cwd(), [], {}) | |
const regex = buildRegex(ignorePath) | |
return allFiles.filter((file) => { | |
return file.match(regex) | |
}) | |
} | |
function buildRegex(ignorePath: string): RegExp { | |
const fileDirectoryPath: string[] = ignorePath.split(path.sep) | |
fileDirectoryPath.unshift(...process.cwd().split(path.sep)) | |
const regexString = fileDirectoryPath.map((str) => { | |
if(str === "**"){ | |
return "(.*?)+" | |
} | |
else if(str === "*"){ | |
return `[^\\${path.sep}]+` | |
} | |
else if(str.match(/\*\.\w+/)){ | |
return `[\\w]+\\.${str.slice(str.indexOf('.')+1)}` | |
} | |
else { | |
return str | |
} | |
}) | |
return new RegExp(regexString.join(`${path.sep}${path.sep}`)) | |
} | |
function walk(filePath: string, unvisited: string[], visited: {[key: string]: boolean}) : string []{ | |
let allFiles = fs.readdirSync(filePath, { | |
recursive: true, | |
}) | |
unvisited = unvisited.concat((allFiles as string[]).map((file) => { | |
return `${filePath}${path.sep}${file}` | |
})) | |
while(unvisited.length){ | |
let file = unvisited.pop() | |
if(!fs.statSync(file).isDirectory()){ | |
visited[file] = true | |
continue | |
} | |
return walk(file, unvisited, visited) | |
} | |
return Object.keys(visited) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment