11package config
22
33import (
4+ "errors"
45 "fmt"
56
67 "gopkg.in/yaml.v3"
@@ -11,14 +12,6 @@ type AliasConfig struct {
1112 Parent Config
1213}
1314
14- // TODO at what point should the alias top level be added? Lazily on first write, I think;
15- // but then we aren't initializing the default aliases that we want. also want to ensure that we
16- // don't re-add the default aliases if people delete them.
17- //
18- // I think I'm not going to worry about it for now; config setup will add the aliases and existing
19- // users can take some step later on to add them if they want them. we'll otherwise lazily create
20- // the aliases: section on first write.
21-
2215func (a * AliasConfig ) Exists (alias string ) bool {
2316 if a .Empty () {
2417 return false
@@ -36,18 +29,43 @@ func (a *AliasConfig) Get(alias string) string {
3629
3730func (a * AliasConfig ) Add (alias , expansion string ) error {
3831 if a .Root == nil {
39- // then we don't actually have an aliases stanza in the config yet.
40- keyNode := & yaml.Node {
41- Kind : yaml .ScalarNode ,
42- Value : "aliases" ,
32+ // TODO awful hack bad type conversion i'm sorry
33+ entry , err := a .Parent .(* fileConfig ).FindEntryPrime ("aliases" )
34+
35+ var notFound * NotFoundError
36+
37+ if err != nil && ! errors .As (err , & notFound ) {
38+ return err
4339 }
4440 valueNode := & yaml.Node {
4541 Kind : yaml .MappingNode ,
4642 Value : "" ,
4743 }
4844
4945 a .Root = valueNode
50- a .Parent .Root ().Content = append (a .Parent .Root ().Content , keyNode , valueNode )
46+ if errors .As (err , & notFound ) {
47+ // No aliases: key; just append new aliases key and empty map to end
48+ keyNode := & yaml.Node {
49+ Kind : yaml .ScalarNode ,
50+ Value : "aliases" ,
51+ }
52+ a .Parent .Root ().Content = append (a .Parent .Root ().Content , keyNode , valueNode )
53+ } else {
54+ // Empty aliases; inject new value node after existing aliases key
55+ newContent := []* yaml.Node {}
56+ for i := 0 ; i < len (a .Parent .Root ().Content ); i ++ {
57+ node := a .Parent .Root ().Content [i ]
58+ if i == entry .Index {
59+ }
60+ if i == entry .Index {
61+ newContent = append (newContent , entry .KeyNode , valueNode )
62+ i ++
63+ } else {
64+ newContent = append (newContent , a .Parent .Root ().Content [i ])
65+ }
66+ }
67+ a .Parent .Root ().Content = newContent
68+ }
5169 }
5270
5371 err := a .SetStringValue (alias , expansion )
0 commit comments