1 // "ainsl" sub-command: "append if no such line" (inspired by FAI's ainsl),
2 // append lines to files (if not present) without replacing the file
5 // FAI: https://fai-project.org
7 // Copyright (C) 2021-2024 Simon Ruderich
9 // This program is free software: you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation, either version 3 of the License, or
12 // (at your option) any later version.
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 // GNU General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program. If not, see <http://www.gnu.org/licenses/>.
34 "golang.org/x/sys/unix"
36 "ruderich.org/simon/safcm/remote/sync"
39 func Main(args []string) error {
41 fmt.Fprintf(os.Stderr,
42 "usage: %s ainsl [<options>] <path> <line>\n",
47 optionCreate := flag.Bool("create", false,
48 "create the path if it does not exist")
50 flag.CommandLine.Parse(args[2:]) //nolint:errcheck
57 changes, err := handle(flag.Args()[0], flag.Args()[1], *optionCreate)
59 return fmt.Errorf("ainsl: %v", err)
61 for _, x := range changes {
62 fmt.Fprintln(os.Stderr, x)
67 func handle(path string, line string, create bool) ([]string, error) {
68 // See safcm-remote/sync/files.go for details on the implementation
71 return nil, fmt.Errorf("empty line")
73 if strings.Contains(line, "\n") {
74 return nil, fmt.Errorf("line must not contain newlines: %q",
78 parentFd, baseName, err := sync.OpenParentDirectoryNoSymlinks(path)
82 defer unix.Close(parentFd)
88 data, stat, err := readFileAtNoFollow(parentFd, baseName)
90 if !os.IsNotExist(err) {
91 return nil, fmt.Errorf("%q: %v", path, err)
94 return nil, fmt.Errorf(
95 "%q: file does not exist, use -create",
99 uid, gid = os.Getuid(), os.Getgid()
100 // Read current umask. Don't do this in programs where
101 // multiple goroutines create files because this is inherently
102 // racy! No goroutines here, so it's fine.
103 umask := syscall.Umask(0)
105 // Apply umask to created file
106 mode = 0666 & ^fs.FileMode(umask)
108 changes = append(changes,
109 fmt.Sprintf("%q: created file (%d/%d %s)",
110 path, uid, gid, mode))
113 // Preserve user/group and mode of existing file
114 x, ok := stat.Sys().(*syscall.Stat_t)
116 return nil, fmt.Errorf("unsupported Stat().Sys()")
122 stat = nil //nolint:wastedassign // prevent accidental use
124 // Check if the expected line is present
126 for _, x := range bytes.Split(data, []byte("\n")) {
127 if string(x) == line {
132 // Make sure the file has a trailing newline. This enforces symmetry
133 // with our changes. Whenever we add a line we also append a trailing
134 // newline. When we conclude that no changes are necessary the file
135 // should be in the same state as we would leave it if there were
137 if len(data) != 0 && data[len(data)-1] != '\n' {
138 data = append(data, '\n')
139 changes = append(changes,
140 fmt.Sprintf("%q: added missing trailing newline",
144 // Line present, nothing to do
145 if found && len(changes) == 0 {
151 data = append(data, []byte(line+"\n")...)
152 changes = append(changes,
153 fmt.Sprintf("%q: added line %q", path, line))
156 // Write via temporary file and rename
157 tmpBase, err := sync.WriteTempAt(parentFd, "."+baseName,
158 data, uid, gid, mode)
162 err = unix.Renameat(parentFd, tmpBase, parentFd, baseName)
164 unix.Unlinkat(parentFd, tmpBase, 0 /* flags */) //nolint:errcheck
167 err = unix.Fsync(parentFd)
175 func readFileAtNoFollow(dirfd int, base string) ([]byte, fs.FileInfo, error) {
176 fh, err := sync.OpenAtNoFollow(dirfd, base)
182 stat, err := fh.Stat()
186 if stat.Mode().Type() != 0 /* regular file */ {
187 return nil, nil, fmt.Errorf("not a regular file but %s",
191 x, err := io.ReadAll(fh)