1
- const fs = require ( 'fs' )
1
+ const fs = require ( 'fs-extra ' )
2
2
const path = require ( 'path' )
3
3
const yaml = require ( 'js-yaml' )
4
4
const clone = require ( 'clone' )
5
+ const stringifyJS = require ( 'javascript-stringify' )
5
6
// Connectors
6
7
const cwd = require ( './cwd' )
7
8
const plugins = require ( './plugins' )
@@ -52,6 +53,25 @@ function findFile (config, context) {
52
53
}
53
54
}
54
55
56
+ function getDefaultFile ( config , context ) {
57
+ if ( ! config . files ) {
58
+ return null
59
+ }
60
+
61
+ const keys = Object . keys ( config . files )
62
+ if ( keys . length ) {
63
+ for ( const key of keys ) {
64
+ if ( key !== 'package' ) {
65
+ const file = config . files [ key ] [ 0 ]
66
+ return {
67
+ type : key ,
68
+ path : path . resolve ( cwd . get ( ) , file )
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+
55
75
function readData ( config , context ) {
56
76
const file = findFile ( config , context )
57
77
config . file = file
@@ -74,9 +94,15 @@ function readData (config, context) {
74
94
}
75
95
76
96
function writeData ( { config, data, changedFields } , context ) {
77
- const file = findFile ( config , context )
97
+ let file = findFile ( config , context )
98
+
99
+ if ( ! file ) {
100
+ file = getDefaultFile ( config , context )
101
+ }
102
+
78
103
if ( file ) {
79
- log ( 'Config write' , config . id , data , changedFields )
104
+ log ( 'Config write' , config . id , data , changedFields , file . path )
105
+ fs . ensureFileSync ( file . path )
80
106
let rawContent
81
107
if ( file . type === 'package' ) {
82
108
const pkg = folders . readPackage ( cwd . get ( ) , context )
@@ -88,12 +114,16 @@ function writeData ({ config, data, changedFields }, context) {
88
114
} else if ( file . type === 'yaml' ) {
89
115
rawContent = yaml . safeDump ( data )
90
116
} else if ( file . type === 'js' ) {
91
- const changedData = changedFields . reduce ( ( obj , field ) => {
92
- obj [ field ] = data [ field ]
93
- return obj
94
- } , { } )
95
- const source = fs . readFileSync ( file . path , { encoding : 'utf8' } )
96
- rawContent = extendJSConfig ( changedData , source )
117
+ let source = fs . readFileSync ( file . path , { encoding : 'utf8' } )
118
+ if ( ! source . trim ( ) ) {
119
+ rawContent = `module.exports = ${ stringifyJS ( data , null , 2 ) } `
120
+ } else {
121
+ const changedData = changedFields . reduce ( ( obj , field ) => {
122
+ obj [ field ] = data [ field ]
123
+ return obj
124
+ } , { } )
125
+ rawContent = extendJSConfig ( changedData , source )
126
+ }
97
127
}
98
128
}
99
129
fs . writeFileSync ( file . path , rawContent , { encoding : 'utf8' } )
0 commit comments