@neabyte/project-root
Version:
A TypeScript library for detecting project root directories by analyzing file patterns and indicators across multiple programming languages and build systems.
1 lines • 1.63 kB
JavaScript
import fs from"node:fs";import path from"node:path";import fg from"fast-glob";import{allIndicators,calculateScore,checkProjectRoot,isInsideBlacklist,isPathRelative,validateAndNormalizePath}from"./utils/index.js";import*as indicators from"./indicators/index.js";export function findProjectRoot(t){const e=validateAndNormalizePath(t);if(null===e)return null;const i=e.replace(/\\/g,"/"),o=i.split("/").filter(t=>t.length);let n={path:"",score:0};for(let t=o.length;t>0;t--){const e=/^[A-Za-z]:/.test(i)?`${o.slice(0,t).join("/")}`:`/${o.slice(0,t).join("/")}`;if(isInsideBlacklist(e))continue;const r=checkProjectRoot(e);if(r>n.score&&(n={path:e,score:r}),r>=15)return e}return n.score>=15?n.path:null}export function findProjectDeep(t,e=10,i=!1){if("string"!=typeof t||!t||0===t.trim().length)return[];let o=t;if(isPathRelative(t))try{o=path.resolve(t)}catch{return[]}if(!fs.existsSync(o)||!fs.statSync(o).isDirectory())return[];const n=[],r=new Set;return function t(o,s,c){if(!(-1!==e&&s>e||r.has(o)||(r.add(o),isInsideBlacklist(o))))try{const e=findProjectRoot(o);if(null!==e&&e===o&&(function(t,e,i){const o=allIndicators.map(t=>t.path),r=fg.sync(o,{cwd:t,onlyFiles:!1,onlyDirectories:!1,ignore:indicators.listBlacklist}),s=calculateScore(r),c={path:t,score:s,depth:e,relativePath:i||"."};n.find(e=>e.path===t)||n.push(c)}(o,s,c),!i))return;!function(e,i,o){const n=fs.readdirSync(e,{withFileTypes:!0});for(const r of n)if(r.isDirectory()){const n=path.join(e,r.name),s=o?path.join(o,r.name):r.name;isInsideBlacklist(n)||t(n,i+1,s)}}(o,s,c)}catch{return}}(o,0,"."),n.sort((t,e)=>e.score!==t.score?e.score-t.score:t.depth-e.depth)}