ConfigTransform.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const transforms = require('./util/configTransforms')
  2. class ConfigTransform {
  3. constructor (options) {
  4. this.fileDescriptor = options.file
  5. }
  6. transform (value, checkExisting, files, context) {
  7. let file
  8. if (checkExisting) {
  9. file = this.findFile(files)
  10. }
  11. if (!file) {
  12. file = this.getDefaultFile()
  13. }
  14. const { type, filename } = file
  15. const transform = transforms[type]
  16. let source
  17. let existing
  18. if (checkExisting) {
  19. source = files[filename]
  20. if (source) {
  21. existing = transform.read({
  22. source,
  23. filename,
  24. context
  25. })
  26. }
  27. }
  28. const content = transform.write({
  29. source,
  30. filename,
  31. context,
  32. value,
  33. existing
  34. })
  35. return {
  36. filename,
  37. content
  38. }
  39. }
  40. findFile (files) {
  41. for (const type of Object.keys(this.fileDescriptor)) {
  42. const descriptors = this.fileDescriptor[type]
  43. for (const filename of descriptors) {
  44. if (files[filename]) {
  45. return { type, filename }
  46. }
  47. }
  48. }
  49. }
  50. getDefaultFile () {
  51. const [type] = Object.keys(this.fileDescriptor)
  52. const [filename] = this.fileDescriptor[type]
  53. return { type, filename }
  54. }
  55. }
  56. module.exports = ConfigTransform