package apply import ( "fmt" "os" "path/filepath" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "novit.nc/direktil/pkg/config" ) // Files writes the files from the given config func Files(cfg *config.Config, prefix string, filters ...string) error { accept := func(n string) bool { return true } if len(filters) > 0 { accept = func(n string) bool { for _, filter := range filters { if matched, err := filepath.Match(filter, n); err != nil { log.Error().Err(err).Str("filter", filter).Msg("bad filter, ignored") } else if matched { return true } } return false } } failed := 0 for _, file := range cfg.Files { if !accept(file.Path) { continue } filePath := filepath.Join(prefix, file.Path) mode := file.Mode if mode == 0 { mode = 0644 } log := log.With().Str("file", filePath).Str("mode", fmt.Sprintf("%04o", mode)).Logger() content := []byte(file.Content) err := writeFile( log, filePath, content, mode, 0755, cfg, ) if err != nil { failed++ continue } } if failed != 0 { err := fmt.Errorf("%d writes failed", failed) log.Error().Err(err).Send() return err } return nil } func writeFile(log zerolog.Logger, path string, content []byte, fileMode, dirMode os.FileMode, cfg *config.Config) (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 }