Copy Directory Trees With os.CopyFS

Replicate a whole directory tree with os.CopyFS over an fs.FS, then walk the destination to verify every file landed before cleanup removes the temp roots.

GoCli Tooling

Code

gosnippet
59 lines
package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

// seed builds a small source directory tree to copy
func seed(dir string) error {
	if err := os.MkdirAll(filepath.Join(dir, "assets"), 0o755); err != nil {
		return err
	}
	if err := os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("env: dev\n"), 0o644); err != nil {
		return err
	}
	return os.WriteFile(filepath.Join(dir, "assets", "logo.txt"), []byte("svg placeholder\n"), 0o644)
}

func main() {
	src, err := os.MkdirTemp("", "copyfs-src-*")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(src)
	dst, err := os.MkdirTemp("", "copyfs-dst-*")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dst)
	if err := seed(src); err != nil {
		fmt.Println("seed:", err)
		return
	}
	// os.CopyFS copies the whole fs.FS tree verbatim into dst
	if err := os.CopyFS(dst, os.DirFS(src)); err != nil {
		fmt.Println("copy:", err)
		return
	}
	// WalkDir walks in lexical order, verifying the directory tree landed complete
	var copied []string
	err = filepath.WalkDir(dst, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if rel, relErr := filepath.Rel(dst, path); relErr == nil && rel != "." {
			copied = append(copied, filepath.ToSlash(rel))
		}
		return nil
	})
	if err != nil {
		fmt.Println("walk:", err)
		return
	}
	fmt.Println("copied:", copied)
}

How it works

Count the functions seed and main as the entire surface area of Copy Directory Trees With os.CopyFS.

Failures are values here: 8 sites check err and decide instead of letting one propagate. The function registers its cleanup up front with defer, so no exit path forgets it.

What to watch for

  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Using it

Signature: func seed(dir string) error

Running the file prints labeled results such as seed:, copy:, walk: — each operation’s effect is visible in the output.

The sequence seed lives in main; running the file triggers it.

Key statements

if err != nil {
fmt.Println(err)
return
}
if err != nil {
return err
}
if err != nil {
fmt.Println("walk:", err)
return
}

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
By return value: each fallible call hands back an `error`, checked at 8 places here.
What does Copy Directory Trees With os.CopyFS print when run?
Execute the whole file; each printed line is prefixed with a label like `seed:`, `copy:`, `walk:`.