feat(app/utils): improve single file language analyzer [skip ci]

This commit is contained in:
lowlighter
2021-11-04 00:19:48 -04:00
parent ecbc6c7e5a
commit 57d4ebb9eb

View File

@@ -161,34 +161,38 @@ export async function chartist() {
} }
/**Language analyzer (single file) */ /**Language analyzer (single file) */
export async function language({filename, patch, prefix = ""}) { export async function language({filename, patch, prefix = "", timeout = 20*1000}) {
const path = paths.join(os.tmpdir(), `${prefix}-${Math.random()}`.replace(/[^\w-]/g, "")) const path = paths.join(os.tmpdir(), `${prefix}-${Math.random()}`.replace(/[^\w-]/g, ""))
try { return new Promise(async (solve, reject) => {
//Create temp dir setTimeout(() => {
console.debug(`metrics/language > creating temp dir ${path} for ${filename}`) console.debug(`metrics/language > ${filename} > timeout`)
await fs.mkdir(path, {recursive:true}) reject("timeout")
}, timeout)
try {
//Create temp dir
console.debug(`metrics/language > ${filename} > creating temp dir at ${path}`)
await fs.mkdir(path, {recursive:true})
//Create file and remove diff syntax //Create file and remove diff syntax
await fs.writeFile(paths.join(path, paths.basename(filename)), patch.replace(/^@@ -\d+,\d+ \+\d+,\d+ @@/gm, "").replace(/^[+-]/gm, "")) await fs.writeFile(paths.join(path, paths.basename(filename)), patch.replace(/^@@ -\d+,\d+ \+\d+,\d+ @@/gm, "").replace(/^[+-]/gm, ""))
//Create temp git repository //Call linguist
console.debug(`metrics/language > creating temp repository at ${path} for ${filename}`) console.debug(`metrics/language > ${filename} > calling linguist`)
await git(path).init().add(".").addConfig("user.name", "linguist").addConfig("user.email", "<>").commit("linguist") const {languages:{results}} = await linguist(path)
.status() const result = (Object.keys(results).shift() ?? "unknown").toLocaleLowerCase()
console.debug(`metrics/language > ${filename} > result: ${result}`)
//Call linguists solve(result)
const {languages:{results}} = await linguist(path) }
return (Object.keys(results).shift() ?? "unknown").toLocaleLowerCase() catch (error) {
} console.debug(`metrics/language > ${filename} > ${error}`)
catch (error) { reject(error)
console.debug(`metrics/language > ${error}`) }
return "unknown" finally {
} //Clean temp dir
finally { console.debug(`metrics/language > ${filename} > cleaning temp dir at ${path}`)
//Clean temp dir fs.rm(path, {recursive:true, force:true}).catch(error => console.debug(`metrics/language > ${filename} > failed to clean temp dir at ${path} > ${error}`))
console.debug(`metrics/language > clean temp dir ${path} for ${filename}`) }
await fs.rm(path, {recursive:true, force:true}) })
}
} }
/**Run command (use this to execute commands and process whole output at once, may not be suitable for large outputs) */ /**Run command (use this to execute commands and process whole output at once, may not be suitable for large outputs) */