config.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. const yaml = require('js-yaml');
  3. const fs = require('hexo-fs');
  4. const { extname } = require('path');
  5. const Promise = require('bluebird');
  6. function configConsole(args) {
  7. const key = args._[0];
  8. let value = args._[1];
  9. if (!key) {
  10. console.log(this.config);
  11. return Promise.resolve();
  12. }
  13. if (!value) {
  14. value = getProperty(this.config, key);
  15. if (value) console.log(value);
  16. return Promise.resolve();
  17. }
  18. const configPath = this.config_path;
  19. const ext = extname(configPath);
  20. return fs.exists(configPath).then(exist => {
  21. if (!exist) return {};
  22. return this.render.render({path: configPath});
  23. }).then(config => {
  24. if (!config) config = {};
  25. setProperty(config, key, castValue(value));
  26. const result = ext === '.json' ? JSON.stringify(config) : yaml.dump(config);
  27. return fs.writeFile(configPath, result);
  28. });
  29. }
  30. function getProperty(obj, key) {
  31. const split = key.split('.');
  32. let result = obj[split[0]];
  33. for (let i = 1, len = split.length; i < len; i++) {
  34. result = result[split[i]];
  35. }
  36. return result;
  37. }
  38. function setProperty(obj, key, value) {
  39. const split = key.split('.');
  40. let cursor = obj;
  41. const lastKey = split.pop();
  42. for (let i = 0, len = split.length; i < len; i++) {
  43. const name = split[i];
  44. cursor[name] = cursor[name] || {};
  45. cursor = cursor[name];
  46. }
  47. cursor[lastKey] = value;
  48. }
  49. function castValue(value) {
  50. switch (value) {
  51. case 'true':
  52. return true;
  53. case 'false':
  54. return false;
  55. case 'null':
  56. return null;
  57. case 'undefined':
  58. return undefined;
  59. }
  60. const num = Number(value);
  61. if (!isNaN(num)) return num;
  62. return value;
  63. }
  64. module.exports = configConsole;