diff --git a/pkg/inject/inject.go b/pkg/inject/inject.go new file mode 100644 index 0000000..01f991c --- /dev/null +++ b/pkg/inject/inject.go @@ -0,0 +1,38 @@ +package inject + +import ( + "fmt" + "os" + "path/filepath" +) + +// Injector writes node config into a mounted image (boot/root paths supplied by caller). +type Injector struct { + BootPath string + RootPath string +} + +// FileSpec describes a file to write. +type FileSpec struct { + Path string + Content []byte + Mode os.FileMode + RootFS bool // if true, write under root path; else boot path +} + +func (i *Injector) Write(files []FileSpec) error { + for _, f := range files { + base := i.BootPath + if f.RootFS { + base = i.RootPath + } + target := filepath.Join(base, f.Path) + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return fmt.Errorf("mkdir %s: %w", filepath.Dir(target), err) + } + if err := os.WriteFile(target, f.Content, f.Mode); err != nil { + return fmt.Errorf("write %s: %w", target, err) + } + } + return nil +} diff --git a/tests/test_inject.py b/tests/test_inject.py new file mode 100644 index 0000000..d309805 --- /dev/null +++ b/tests/test_inject.py @@ -0,0 +1,16 @@ +from pathlib import Path + +from metis.pkg.inject import Injector, FileSpec + + +def test_inject_write(tmp_path): + boot = tmp_path / "boot" + root = tmp_path / "root" + inj = Injector(BootPath=str(boot), RootPath=str(root)) + files = [ + FileSpec(Path="config.txt", Content=b"bootcfg", Mode=0o644, RootFS=False), + FileSpec(Path="etc/hostname", Content=b"node", Mode=0o644, RootFS=True), + ] + inj.Write(files) + assert (boot / "config.txt").read_bytes() == b"bootcfg" + assert (root / "etc/hostname").read_bytes() == b"node"