-
Notifications
You must be signed in to change notification settings - Fork 376
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
tetragon-rthooks: move code to apply changes
Move applyChanges used to patch the containerd configuration file to its own file. Useful for next commit. Signed-off-by: Kornilios Kourtis <[email protected]>
- Loading branch information
Showing
2 changed files
with
80 additions
and
68 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// Copyright Authors of Tetragon | ||
|
||
package main | ||
|
||
import ( | ||
"bufio" | ||
"os" | ||
"strings" | ||
|
||
"github.com/pelletier/go-toml" | ||
) | ||
|
||
// special line number to append at the end of the file | ||
const appendAtEndLine = -10 | ||
|
||
type addLine struct { | ||
pos toml.Position | ||
line string | ||
replaceLine bool | ||
} | ||
|
||
func applyChanges(fnameIn, fnameOut string, changes []addLine) error { | ||
fIn, err := os.Open(fnameIn) | ||
if err != nil { | ||
return err | ||
} | ||
defer fIn.Close() | ||
cr := "\n" | ||
if usesCR(fIn) { | ||
cr = "\r\n" | ||
} | ||
|
||
fOut, err := os.Create(fnameOut) | ||
if err != nil { | ||
return err | ||
} | ||
defer fOut.Close() | ||
|
||
inLine := 0 | ||
inSc := bufio.NewScanner(fIn) | ||
out := bufio.NewWriter(fOut) | ||
defer out.Flush() | ||
for inSc.Scan() { | ||
inLine++ | ||
lines := []string{} | ||
replaceLine := false | ||
for i := range changes { | ||
ch := &changes[i] | ||
if ch.pos.Line == inLine { | ||
line := strings.Repeat(" ", ch.pos.Col-1) + ch.line + cr | ||
lines = append(lines, line) | ||
if ch.replaceLine { | ||
replaceLine = true | ||
} | ||
} | ||
} | ||
if !replaceLine { | ||
out.WriteString(inSc.Text()) | ||
out.WriteString(cr) | ||
} | ||
for _, line := range lines { | ||
out.WriteString(line) | ||
} | ||
} | ||
|
||
for i := range changes { | ||
ch := &changes[i] | ||
if ch.pos.Line == appendAtEndLine { | ||
indent := "" | ||
if ch.pos.Col > 0 { | ||
indent = strings.Repeat(" ", ch.pos.Col-1) | ||
} | ||
line := indent + ch.line + cr | ||
out.WriteString(line) | ||
} | ||
} | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters