config: support dir and symlink in file def

This commit is contained in:
Mikaël Cluseau 2024-01-20 17:59:21 +01:00
parent 29595df7b8
commit 8498a10279
2 changed files with 35 additions and 21 deletions

View File

@ -44,20 +44,42 @@ func Files(cfgFiles []config.FileDef, prefix string, filters ...string) error {
log := log.With().Str("file", filePath).Str("mode", fmt.Sprintf("%04o", mode)).Logger() log := log.With().Str("file", filePath).Str("mode", fmt.Sprintf("%04o", mode)).Logger()
content := []byte(file.Content) if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
log.Error().Err(err).Msg("failed to create parent dir")
err := writeFile(
log,
filePath,
content,
mode,
0755,
)
if err != nil {
failed++ failed++
continue continue
} }
switch {
case file.Symlink != "":
log := log.With().Str("target", file.Symlink).Logger()
if err := os.Symlink(file.Symlink, filePath); err == nil {
log.Info().Msg("created symlink")
} else {
log.Error().Err(err).Msg("failed to create symlink")
failed++
}
case file.Dir:
if err := os.Mkdir(filePath, mode); err == nil {
log.Info().Msg("created dir")
} else if os.IsExist(err) {
log.Warn().Msg("dir exist, ignoring error")
} else {
log.Error().Err(err).Msg("failed to create dir")
failed++
}
default:
content := []byte(file.Content)
if err := os.WriteFile(filePath, content, mode); err == nil {
log.Info().Msgf("wrote %d bytes", len(content))
} else {
log.Error().Err(err).Msg("write failed")
failed++
}
}
} }
if failed != 0 { if failed != 0 {
@ -69,16 +91,6 @@ func Files(cfgFiles []config.FileDef, prefix string, filters ...string) error {
} }
func writeFile(log zerolog.Logger, path string, content []byte, fileMode, dirMode os.FileMode) (err error) { func writeFile(log zerolog.Logger, path string, content []byte, fileMode, dirMode os.FileMode) (err error) {
if err = os.MkdirAll(filepath.Dir(path), dirMode); err != nil {
log.Error().Err(err).Msg("failed to create parent dir")
return
}
log.Info().Msgf("writing %d bytes", len(content))
if err = os.WriteFile(path, content, fileMode); err != nil {
log.Error().Err(err).Msg("write failed")
return
}
return return
} }

View File

@ -136,6 +136,8 @@ type FileDef struct {
Path string Path string
Mode os.FileMode Mode os.FileMode
Content string Content string
Symlink string
Dir bool
} }
type NetworkDef struct { type NetworkDef struct {