Tim van der Lippe | 706ec96 | 2021-06-04 13:24:42 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | const fs = require('fs'); |
| 4 | const path = require('path'); |
| 5 | const { |
| 6 | extendDefaultPlugins, |
| 7 | optimize, |
| 8 | createContentItem, |
| 9 | } = require('./svgo.js'); |
| 10 | |
| 11 | const importConfig = async (configFile) => { |
| 12 | const config = require(configFile); |
| 13 | if (config == null || typeof config !== 'object' || Array.isArray(config)) { |
| 14 | throw Error(`Invalid config file "${configFile}"`); |
| 15 | } |
| 16 | return config; |
| 17 | }; |
| 18 | |
| 19 | const isFile = async (file) => { |
| 20 | try { |
| 21 | const stats = await fs.promises.stat(file); |
| 22 | return stats.isFile(); |
| 23 | } catch { |
| 24 | return false; |
| 25 | } |
| 26 | }; |
| 27 | |
| 28 | const loadConfig = async (configFile, cwd = process.cwd()) => { |
| 29 | if (configFile != null) { |
| 30 | if (path.isAbsolute(configFile)) { |
| 31 | return await importConfig(configFile); |
| 32 | } else { |
| 33 | return await importConfig(path.join(cwd, configFile)); |
| 34 | } |
| 35 | } |
| 36 | let dir = cwd; |
| 37 | // eslint-disable-next-line no-constant-condition |
| 38 | while (true) { |
| 39 | const file = path.join(dir, 'svgo.config.js'); |
| 40 | if (await isFile(file)) { |
| 41 | return await importConfig(file); |
| 42 | } |
| 43 | const parent = path.dirname(dir); |
| 44 | if (dir === parent) { |
| 45 | return null; |
| 46 | } |
| 47 | dir = parent; |
| 48 | } |
| 49 | }; |
| 50 | |
| 51 | exports.loadConfig = loadConfig; |
| 52 | exports.extendDefaultPlugins = extendDefaultPlugins; |
| 53 | exports.optimize = optimize; |
| 54 | exports.createContentItem = createContentItem; |