@sap/eslint-plugin-cds
Version:
ESLint plugin including recommended SAP Cloud Application Programming model and environment rules
76 lines (65 loc) • 2.17 kB
JavaScript
const path = require('node:path')
const cds = require('@sap/cds')
const { globalCache } = require('./Cache')
const fs = require('node:fs')
const commonCapProjectFiles = ['build.gradle', '.git', 'srv', 'db', 'app']
/**
* Searches for a directory containing cds roots.
*
* As of today, there is no unified way to find the root directory for a CDS project.
* ("The root is wherever the user typed `cds init`")
* We are therefore trying to resolve that path heuristically by ascending through the
* directory structure, looking for certain files.
*
* FIXME: Revisit and use a unified way once available, i.e. from @sap/cds
*
* @param {string} currentDir start here and search until root dir
* @returns {string} dir containing cds roots (empty if not exists)
*/
function getProjectRootPath(currentDir = '.') {
let dir = path.resolve(currentDir)
while (!couldBeProjectRoot(dir)) {
if (dir === path.resolve(dir, '..'))
return '' // we reached the file system root -> abort
dir = path.join(dir, '..')
}
cds.resolve.cache = {}
const roots = cds.resolve('*', { root: dir })
if (roots?.length > 0) {
globalCache.set(`roots:${dir}`, roots)
return dir
}
return ''
}
/**
* Checks whether the given directory could be a CDS project root.
*
* @param {string} dir
* @returns {boolean}
*/
function couldBeProjectRoot(dir) {
return isRootPackageJson(path.join(dir, 'package.json')) ||
commonCapProjectFiles.some(entry => fs.existsSync(path.join(dir, entry)))
}
function isRootPackageJson(filepath) {
const filename = path.basename(filepath)
if (filename !== 'package.json')
return false
try {
const config = JSON.parse(fs.readFileSync(filepath, 'utf8'))
return config && (config.cds ||
hasCdsPackage(config.dependencies) ||
hasCdsPackage(config.peerDependencies) ||
hasCdsPackage(config.devDependencies))
} catch {
return false
}
}
function hasCdsPackage(deps) {
return deps && (('@sap/cds' in deps) || ('@sap/cds-dk' in deps))
}
module.exports = {
getProjectRootPath,
hasProjectRoots: () => globalCache.has(`roots:${globalCache.get('rootpath')}`),
}