|
| 1 | +import fs from "fs"; |
| 2 | +import { resolve, join } from "path"; |
| 3 | +/** |
| 4 | + * Return the value for a key in config file. |
| 5 | + * @param {string} key - The key in the config file |
| 6 | + * @param {string} path - The full path. |
| 7 | + * @returns {string} - The part of the path before 'src'. |
| 8 | + */ |
| 9 | +function getConfig(key, folderPath) { |
| 10 | + // Read the JSON configuration file |
| 11 | + |
| 12 | + const spConfigFilePath = findFileInParentFolders( |
| 13 | + "sp.config.json", |
| 14 | + folderPath |
| 15 | + ); |
| 16 | + const config = JSON.parse(fs.readFileSync(spConfigFilePath, "utf-8")); |
| 17 | + |
| 18 | + return config[key]; |
| 19 | +} |
| 20 | + |
| 21 | +/* Finds a file in the closest parent folder. |
| 22 | + * @param {string} fileName - The name of the file to find. |
| 23 | + * @param {string} [currentDir] - The directory to start the search from. Defaults to the current working directory. |
| 24 | + * @returns {string|null} - The path to the file if found, otherwise null. |
| 25 | + */ |
| 26 | +function findFileInParentFolders(fileName, currentDir) { |
| 27 | + // Start from the current directory or the provided directory |
| 28 | + let dir = currentDir || process.cwd(); |
| 29 | + |
| 30 | + // Loop until we reach the root directory |
| 31 | + while (true) { |
| 32 | + // Construct the path to the file |
| 33 | + const filePath = join(dir, fileName); |
| 34 | + |
| 35 | + // Check if the file exists |
| 36 | + if (fs.existsSync(filePath)) { |
| 37 | + return filePath; // Return the path if the file is found |
| 38 | + } |
| 39 | + |
| 40 | + // Get the parent directory |
| 41 | + const parentDir = resolve(dir, ".."); |
| 42 | + |
| 43 | + // If we've reached the root directory, stop the loop |
| 44 | + if (parentDir === dir) { |
| 45 | + break; |
| 46 | + } |
| 47 | + |
| 48 | + // Move up to the parent directory |
| 49 | + dir = parentDir; |
| 50 | + } |
| 51 | + |
| 52 | + // Return null if the file is not found |
| 53 | + return null; |
| 54 | +} |
| 55 | +export { getConfig }; |
0 commit comments