Skip to content

Commit 2b23681

Browse files
committed
use lockedfile to write hosts
1 parent b876acc commit 2b23681

File tree

2 files changed

+5
-22
lines changed

2 files changed

+5
-22
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ require (
1212
github.com/olekukonko/tablewriter v0.0.5
1313
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
1414
github.com/pkg/sftp v1.13.7
15+
github.com/rogpeppe/go-internal v1.13.1
1516
github.com/urfave/cli/v3 v3.0.0-alpha9.7
1617
golang.org/x/crypto v0.33.0
1718
golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac
@@ -73,7 +74,6 @@ require (
7374
github.com/opencontainers/go-digest v1.0.0 // indirect
7475
github.com/pkg/errors v0.9.1 // indirect
7576
github.com/rivo/uniseg v0.4.7 // indirect
76-
github.com/rogpeppe/go-internal v1.13.1 // indirect
7777
github.com/spf13/pflag v1.0.5 // indirect
7878
github.com/stretchr/testify v1.10.0 // indirect
7979
github.com/x448/float16 v0.8.4 // indirect

pkg/system/hosts.go

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ package system
22

33
import (
44
"fmt"
5-
"io"
65
"os"
76
"runtime"
87
"slices"
98
"strings"
9+
10+
"github.com/rogpeppe/go-internal/lockedfile"
1011
)
1112

1213
type HostsSection struct {
@@ -54,15 +55,7 @@ func (s *HostsSection) Flush() error {
5455
ln = "\r\n"
5556
}
5657

57-
file, err := os.OpenFile(s.path, os.O_RDWR, 0644)
58-
59-
if err != nil {
60-
return err
61-
}
62-
63-
defer file.Close()
64-
65-
data, err := io.ReadAll(file)
58+
data, err := lockedfile.Read(s.path)
6659

6760
if err != nil {
6861
return err
@@ -97,17 +90,7 @@ func (s *HostsSection) Flush() error {
9790

9891
text = strings.TrimRight(text, ln) + ln
9992

100-
if _, err := file.Seek(0, 0); err != nil {
101-
return err
102-
}
103-
104-
if err := file.Truncate(0); err != nil {
105-
return err
106-
}
107-
108-
if _, err := file.WriteString(text); err != nil {
109-
return err
110-
}
93+
lockedfile.Write(s.path, strings.NewReader(text), 0644)
11194

11295
return nil
11396
}

0 commit comments

Comments
 (0)