@@ -88,6 +88,13 @@ func NewConfig(root *yaml.Node) Config {
8888 }
8989}
9090
91+ func NewBlankConfig () Config {
92+ return NewConfig (& yaml.Node {
93+ Kind : yaml .DocumentNode ,
94+ Content : []* yaml.Node {{Kind : yaml .MappingNode }},
95+ })
96+ }
97+
9198// This type implements a Config interface and represents a config file on disk.
9299type fileConfig struct {
93100 ConfigMap
@@ -136,7 +143,10 @@ func (c *fileConfig) Set(hostname, key, value string) error {
136143 return c .SetStringValue (key , value )
137144 } else {
138145 hostCfg , err := c .configForHost (hostname )
139- if err != nil {
146+ var notFound * NotFoundError
147+ if errors .As (err , & notFound ) {
148+ hostCfg = c .makeConfigForHost (hostname )
149+ } else if err != nil {
140150 return err
141151 }
142152 return hostCfg .SetStringValue (key , value )
@@ -154,7 +164,7 @@ func (c *fileConfig) configForHost(hostname string) (*HostConfig, error) {
154164 return hc , nil
155165 }
156166 }
157- return nil , fmt .Errorf ("could not find config entry for %q" , hostname )
167+ return nil , & NotFoundError { fmt .Errorf ("could not find config entry for %q" , hostname )}
158168}
159169
160170func (c * fileConfig ) Write () error {
@@ -186,6 +196,35 @@ func (c *fileConfig) hostEntries() ([]*HostConfig, error) {
186196 return hostConfigs , nil
187197}
188198
199+ func (c * fileConfig ) makeConfigForHost (hostname string ) * HostConfig {
200+ hostRoot := & yaml.Node {Kind : yaml .MappingNode }
201+ hostCfg := & HostConfig {
202+ Host : hostname ,
203+ ConfigMap : ConfigMap {Root : hostRoot },
204+ }
205+
206+ var notFound * NotFoundError
207+ _ , hostsEntry , err := c .FindEntry ("hosts" )
208+ if errors .As (err , & notFound ) {
209+ hostsEntry = & yaml.Node {Kind : yaml .MappingNode }
210+ c .Root .Content = append (c .Root .Content ,
211+ & yaml.Node {
212+ Kind : yaml .ScalarNode ,
213+ Value : "hosts" ,
214+ }, hostsEntry )
215+ } else if err != nil {
216+ panic (err )
217+ }
218+
219+ hostsEntry .Content = append (hostsEntry .Content ,
220+ & yaml.Node {
221+ Kind : yaml .ScalarNode ,
222+ Value : hostname ,
223+ }, hostRoot )
224+
225+ return hostCfg
226+ }
227+
189228func (c * fileConfig ) parseHosts (hostsEntry * yaml.Node ) ([]* HostConfig , error ) {
190229 hostConfigs := []* HostConfig {}
191230
0 commit comments