load_theme_config.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const { join, parse } = require('path');
  3. const tildify = require('tildify');
  4. const { exists, readdir } = require('hexo-fs');
  5. const { magenta } = require('chalk');
  6. const { deepMerge } = require('hexo-util');
  7. module.exports = ctx => {
  8. if (!ctx.env.init) return;
  9. if (!ctx.config.theme) return;
  10. let configPath = join(ctx.base_dir, `_config.${String(ctx.config.theme)}.yml`);
  11. return exists(configPath).then(exist => {
  12. return exist ? configPath : findConfigPath(configPath);
  13. }).then(path => {
  14. if (!path) return;
  15. configPath = path;
  16. return ctx.render.render({ path });
  17. }).then(config => {
  18. if (!config || typeof config !== 'object') return;
  19. ctx.log.debug('Second Theme Config loaded: %s', magenta(tildify(configPath)));
  20. // ctx.config.theme_config should have highest priority
  21. // If ctx.config.theme_config exists, then merge it with _config.[theme].yml
  22. // If ctx.config.theme_config doesn't exist, set it to _config.[theme].yml
  23. ctx.config.theme_config = ctx.config.theme_config
  24. ? deepMerge(config, ctx.config.theme_config) : config;
  25. });
  26. };
  27. function findConfigPath(path) {
  28. const { dir, name } = parse(path);
  29. return readdir(dir).then(files => {
  30. const item = files.find(item => item.startsWith(name));
  31. if (item != null) return join(dir, item);
  32. });
  33. }