]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - cmd/safcm/sync_changes.go
config: tests: replace FullPermToFileMode() with fs constants
[safcm/safcm.git] / cmd / safcm / sync_changes.go
1 // "sync" sub-command: format changes
2
3 // Copyright (C) 2021  Simon Ruderich
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 package main
19
20 import (
21         "fmt"
22         "io/fs"
23         "strings"
24
25         "ruderich.org/simon/safcm"
26         "ruderich.org/simon/safcm/cmd/safcm/config"
27 )
28
29 // NOTE: Be careful when implementing new format* functions. All input from
30 // the remote helper is untrusted and must be either escaped with %q or by
31 // calling EscapeControlCharacters().
32
33 func (s *Sync) formatChanges(resp safcm.MsgSyncResp) string {
34         var changes []string
35         if len(resp.FileChanges) > 0 {
36                 changes = append(changes,
37                         s.formatFileChanges(resp.FileChanges))
38         }
39         if len(resp.PackageChanges) > 0 {
40                 changes = append(changes,
41                         s.formatPackageChanges(resp.PackageChanges))
42         }
43         if len(resp.ServiceChanges) > 0 {
44                 changes = append(changes,
45                         s.formatServiceChanges(resp.ServiceChanges))
46         }
47         if len(resp.CommandChanges) > 0 {
48                 changes = append(changes,
49                         s.formatCommandChanges(resp.CommandChanges))
50         }
51         if len(changes) == 0 {
52                 // Notify user that the host was synced successfully
53                 return "no changes"
54         }
55
56         x := strings.Join(changes, "\n")
57         // If quiet is used and only commands without output were executed
58         // then don't prepend a newline so that the whole change output of a
59         // host fits in a single line. This makes the output much more
60         // readable with multiple hosts.
61         if strings.Count(x, "\n") == 1 {
62                 return x
63         }
64         return "\n" + x
65 }
66
67 func (s *Sync) formatFileChanges(changes []safcm.FileChange) string {
68         var buf strings.Builder
69         fmt.Fprintf(&buf, "changed %d file(s):", len(changes))
70         if s.config.DryRun {
71                 fmt.Fprintf(&buf, " (dry-run)")
72         }
73         fmt.Fprintf(&buf, "\n")
74         for _, x := range changes {
75                 fmt.Fprintf(&buf, "%s:", s.formatTarget(x.Path))
76
77                 var info []string
78                 if x.Created {
79                         info = append(info,
80                                 ColorString(s.isTTY, ColorGreen, "created"),
81                                 formatFileType(x.New),
82                                 formatFileUserGroup(x.New),
83                                 formatFilePerm(x.New),
84                         )
85                 } else {
86                         if x.Old.Mode.Type() != x.New.Mode.Type() {
87                                 info = append(info, fmt.Sprintf("%s -> %s",
88                                         formatFileType(x.Old),
89                                         formatFileType(x.New),
90                                 ))
91                         }
92                         if x.Old.User != x.New.User ||
93                                 x.Old.Uid != x.New.Uid ||
94                                 x.Old.Group != x.New.Group ||
95                                 x.Old.Gid != x.New.Gid {
96                                 info = append(info, fmt.Sprintf("%s -> %s",
97                                         formatFileUserGroup(x.Old),
98                                         formatFileUserGroup(x.New),
99                                 ))
100                         }
101                         if config.FileModeToFullPerm(x.Old.Mode) !=
102                                 config.FileModeToFullPerm(x.New.Mode) {
103                                 info = append(info, fmt.Sprintf("%s -> %s",
104                                         formatFilePerm(x.Old),
105                                         formatFilePerm(x.New),
106                                 ))
107                         }
108                 }
109                 if len(info) > 0 {
110                         fmt.Fprint(&buf, " ")
111                         fmt.Fprint(&buf, strings.Join(info, ", "))
112                 }
113
114                 if x.DataDiff != "" {
115                         fmt.Fprintf(&buf, "\n%s", s.formatDiff(x.DataDiff))
116                 }
117                 fmt.Fprintf(&buf, "\n")
118         }
119
120         return buf.String()
121 }
122 func formatFileType(info safcm.FileChangeInfo) string {
123         switch info.Mode.Type() {
124         case 0: // regular file
125                 return "file"
126         case fs.ModeSymlink:
127                 return "symlink"
128         case fs.ModeDir:
129                 return "dir"
130         default:
131                 return fmt.Sprintf("invalid type %v", info.Mode.Type())
132         }
133 }
134 func formatFileUserGroup(info safcm.FileChangeInfo) string {
135         return fmt.Sprintf("%s(%d) %s(%d)",
136                 EscapeControlCharacters(false, info.User), info.Uid,
137                 EscapeControlCharacters(false, info.Group), info.Gid)
138 }
139 func formatFilePerm(info safcm.FileChangeInfo) string {
140         return fmt.Sprintf("%#o", config.FileModeToFullPerm(info.Mode))
141 }
142
143 func (s *Sync) formatPackageChanges(changes []safcm.PackageChange) string {
144         var buf strings.Builder
145         fmt.Fprintf(&buf, "installed %d package(s):", len(changes))
146         if s.config.DryRun {
147                 fmt.Fprintf(&buf, " (dry-run)")
148         }
149         fmt.Fprintf(&buf, "\n")
150         for _, x := range changes {
151                 // TODO: indicate if installation failed
152                 fmt.Fprintf(&buf, "%s\n", s.formatTarget(x.Name))
153         }
154         return buf.String()
155 }
156
157 func (s *Sync) formatServiceChanges(changes []safcm.ServiceChange) string {
158         var buf strings.Builder
159         fmt.Fprintf(&buf, "modified %d service(s):", len(changes))
160         if s.config.DryRun {
161                 fmt.Fprintf(&buf, " (dry-run)")
162         }
163         fmt.Fprintf(&buf, "\n")
164         for _, x := range changes {
165                 var info []string
166                 if x.Started {
167                         info = append(info, "started")
168                 }
169                 if x.Enabled {
170                         info = append(info, "enabled")
171                 }
172                 fmt.Fprintf(&buf, "%s: %s\n",
173                         s.formatTarget(x.Name),
174                         strings.Join(info, ", "))
175         }
176         return buf.String()
177 }
178
179 func (s *Sync) formatCommandChanges(changes []safcm.CommandChange) string {
180         const indent = "   > "
181
182         // Quiet hides all successful, non-trigger commands which produce no
183         // output. This is useful as many commands will be used to enforce a
184         // certain state (e.g. file not-present, `ainsl`, etc.) and are run on
185         // each sync. Displaying them provides not much useful information.
186         // Instead, quiet shows them only when they produce output (e.g.
187         // `ainsl`, `rm -v`) and thus modify the host's state.
188         var noOutput int
189         if s.config.Quiet {
190                 for _, x := range changes {
191                         if x.Trigger == "" &&
192                                 x.Error == "" &&
193                                 x.Output == "" {
194                                 noOutput++
195                         }
196                 }
197         }
198
199         var buf strings.Builder
200         fmt.Fprintf(&buf, "executed %d command(s)", len(changes))
201         if noOutput > 0 && !s.config.DryRun {
202                 fmt.Fprintf(&buf, ", %d with no output", noOutput)
203         }
204         if noOutput != len(changes) {
205                 fmt.Fprintf(&buf, ":")
206         }
207         if s.config.DryRun {
208                 fmt.Fprintf(&buf, " (dry-run)")
209         }
210         fmt.Fprintf(&buf, "\n")
211         for _, x := range changes {
212                 if noOutput > 0 &&
213                         x.Trigger == "" && x.Error == "" && x.Output == "" {
214                         continue
215                 }
216
217                 fmt.Fprintf(&buf, "%s", s.formatTarget(x.Command))
218                 if x.Trigger != "" {
219                         fmt.Fprintf(&buf, ", trigger for %q", x.Trigger)
220                 }
221                 if x.Error != "" {
222                         fmt.Fprintf(&buf, ", failed: %q", x.Error)
223                 }
224                 if x.Output != "" {
225                         // TODO: truncate very large outputs?
226                         x := indentBlock(x.Output, indent)
227                         fmt.Fprintf(&buf, ":\n%s",
228                                 EscapeControlCharacters(s.isTTY, x))
229                 }
230                 fmt.Fprintf(&buf, "\n")
231         }
232         return buf.String()
233 }
234
235 func (s *Sync) formatTarget(x string) string {
236         x = fmt.Sprintf("%q", x) // escape!
237         return ColorString(s.isTTY, ColorCyan, x)
238 }
239
240 func (s *Sync) formatDiff(diff string) string {
241         const indent = "   "
242
243         diff = indentBlock(diff, indent)
244         // Never color diff content as we want to color the whole diff
245         diff = EscapeControlCharacters(false, diff)
246         if !s.isTTY {
247                 return diff
248         }
249
250         var res []string
251         for _, x := range strings.Split(diff, "\n") {
252                 if strings.HasPrefix(x, indent+"+") {
253                         x = ColorString(s.isTTY, ColorGreen, x)
254                 } else if strings.HasPrefix(x, indent+"-") {
255                         x = ColorString(s.isTTY, ColorRed, x)
256                 }
257                 res = append(res, x)
258         }
259         return strings.Join(res, "\n")
260 }
261
262 func indentBlock(x string, sep string) string {
263         lines := strings.Split(x, "\n")
264         if lines[len(lines)-1] == "" {
265                 lines = lines[:len(lines)-1]
266         } else {
267                 lines = append(lines, "\\ No newline at end of file")
268         }
269
270         return sep + strings.Join(lines, "\n"+sep)
271 }