@@ -14,23 +14,25 @@ const (
1414 endMarkerTemplate = "# END: Devbox: '%s' project"
1515)
1616
17- func Save (projectName string , entries []string ) error {
17+ // Save updates the hosts file with the given entries. Returns (changed, error).
18+ // If no changes were needed, changed is false and no write occurs.
19+ func Save (projectName string , entries []string ) (bool , error ) {
1820 return save (defaultHostFile , projectName , entries )
1921}
2022
21- func save (hostFile , projectName string , entries []string ) error {
23+ func save (hostFile , projectName string , entries []string ) ( bool , error ) {
2224 markerBegin := fmt .Sprintf (beginMarkerTemplate , projectName )
2325 markerEnd := fmt .Sprintf (endMarkerTemplate , projectName )
2426
2527 fileInfo , err := os .Stat (hostFile )
2628 if err != nil {
27- return fmt .Errorf ("failed to stat hosts file: %w" , err )
29+ return false , fmt .Errorf ("failed to stat hosts file: %w" , err )
2830 }
2931 fileMode := fileInfo .Mode ()
3032
3133 oldContent , err := os .ReadFile (hostFile )
3234 if err != nil {
33- return fmt .Errorf ("failed to read hosts file: %w" , err )
35+ return false , fmt .Errorf ("failed to read hosts file: %w" , err )
3436 }
3537
3638 var newContent strings.Builder
@@ -68,10 +70,10 @@ func save(hostFile, projectName string, entries []string) error {
6870 }
6971
7072 if lookupForEnd {
71- return fmt .Errorf ("unexpected end of file" )
73+ return false , fmt .Errorf ("unexpected end of file" )
7274 }
7375
74- if ! replaced {
76+ if ! replaced && len ( entries ) > 0 {
7577 newContent .WriteString (markerBegin + "\n " )
7678 for _ , entry := range entries {
7779 newContent .WriteString (entry + "\n " )
@@ -80,8 +82,12 @@ func save(hostFile, projectName string, entries []string) error {
8082 }
8183
8284 if newContent .String () == string (oldContent ) {
83- return nil
85+ return false , nil
8486 }
8587
86- return os .WriteFile (hostFile , []byte (newContent .String ()), fileMode )
88+ err = os .WriteFile (hostFile , []byte (newContent .String ()), fileMode )
89+ if err != nil {
90+ return false , fmt .Errorf ("failed to write hosts file: %w" , err )
91+ }
92+ return true , nil
8793}
0 commit comments