multi_config_path.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const { isAbsolute, resolve, join, extname } = require('path');
  3. const fs = require('hexo-fs');
  4. const yml = require('js-yaml');
  5. const { deepMerge } = require('hexo-util');
  6. module.exports = ctx => function multiConfigPath(base, configPaths, outputDir) {
  7. const { log } = ctx;
  8. const defaultPath = join(base, '_config.yml');
  9. if (!configPaths) {
  10. log.w('No config file entered.');
  11. return join(base, '_config.yml');
  12. }
  13. let paths;
  14. // determine if comma or space separated
  15. if (configPaths.includes(',')) {
  16. paths = configPaths.replace(' ', '').split(',');
  17. } else {
  18. // only one config
  19. let configPath = isAbsolute(configPaths) ? configPaths : resolve(base, configPaths);
  20. if (!fs.existsSync(configPath)) {
  21. log.w(`Config file ${configPaths} not found, using default.`);
  22. configPath = defaultPath;
  23. }
  24. return configPath;
  25. }
  26. const numPaths = paths.length;
  27. // combine files
  28. let combinedConfig = {};
  29. let count = 0;
  30. for (let i = 0; i < numPaths; i++) {
  31. const configPath = isAbsolute(paths[i]) ? paths[i] : join(base, paths[i]);
  32. if (!fs.existsSync(configPath)) {
  33. log.w(`Config file ${paths[i]} not found.`);
  34. continue;
  35. }
  36. // files read synchronously to ensure proper overwrite order
  37. const file = fs.readFileSync(configPath);
  38. const ext = extname(paths[i]).toLowerCase();
  39. if (ext === '.yml') {
  40. combinedConfig = deepMerge(combinedConfig, yml.load(file));
  41. count++;
  42. } else if (ext === '.json') {
  43. combinedConfig = deepMerge(combinedConfig, yml.load(file, {json: true}));
  44. count++;
  45. } else {
  46. log.w(`Config file ${paths[i]} not supported type.`);
  47. }
  48. }
  49. if (count === 0) {
  50. log.e('No config files found. Using _config.yml.');
  51. return defaultPath;
  52. }
  53. log.i('Config based on', count, 'files');
  54. const multiconfigRoot = outputDir || base;
  55. const outputPath = join(multiconfigRoot, '_multiconfig.yml');
  56. log.d(`Writing _multiconfig.yml to ${outputPath}`);
  57. fs.writeFileSync(outputPath, yml.dump(combinedConfig));
  58. // write file and return path
  59. return outputPath;
  60. };