all repos — vite @ 767dbd64730834c6e367344c7809531862a0afa5

a fast (this time, actually) and minimal static site generator

util/copy.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
package util

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

// CopyFile copies a file from src to dst.
func CopyFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	if err != nil {
		return err
	}

	// Copy modes.
	f, err := os.Stat(src)
	if err == nil {
		err = os.Chmod(dst, f.Mode())
		if err != nil {
			return err
		}
	}

	return out.Close()
}

// CopyDir copies an entire directory tree from
// src to dst.
func CopyDir(src, dst string) error {
	fi, err := os.Stat(src)
	if err != nil {
		return err
	}

	if !fi.IsDir() {
		return fmt.Errorf("error: %q is not a directory", fi)
	}

	if err = os.MkdirAll(dst, 0755); err != nil {
		return err
	}

	items, _ := os.ReadDir(src)
	for _, item := range items {
		srcFilename := filepath.Join(src, item.Name())
		dstFilename := filepath.Join(dst, item.Name())
		if item.IsDir() {
			if err := CopyDir(srcFilename, dstFilename); err != nil {
				return err
			}
		} else {
			if err := CopyFile(srcFilename, dstFilename); err != nil {
				return err
			}
		}
	}

	return nil
}