all repos — vite @ 81b8a3faf63f5b53e9d6e95aa09149941c4a2f11

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

util/copy.go (view raw)

 1package util
 2
 3import (
 4	"fmt"
 5	"io"
 6	"os"
 7	"path/filepath"
 8)
 9
10// CopyFile copies a file from src to dst.
11func CopyFile(src, dst string) error {
12	in, err := os.Open(src)
13	if err != nil {
14		return err
15	}
16	defer in.Close()
17
18	out, err := os.Create(dst)
19	if err != nil {
20		return err
21	}
22	defer out.Close()
23
24	_, err = io.Copy(out, in)
25	if err != nil {
26		return err
27	}
28
29	// Copy modes.
30	f, err := os.Stat(src)
31	if err == nil {
32		err = os.Chmod(dst, f.Mode())
33		if err != nil {
34			return err
35		}
36	}
37
38	return out.Close()
39}
40
41// CopyDir copies an entire directory tree from
42// src to dst.
43func CopyDir(src, dst string) error {
44	fi, err := os.Stat(src)
45	if err != nil {
46		return err
47	}
48
49	if !fi.IsDir() {
50		return fmt.Errorf("error: %q is not a directory", fi)
51	}
52
53	if err = os.MkdirAll(dst, 0755); err != nil {
54		return err
55	}
56
57	items, _ := os.ReadDir(src)
58	for _, item := range items {
59		srcFilename := filepath.Join(src, item.Name())
60		dstFilename := filepath.Join(dst, item.Name())
61		if item.IsDir() {
62			if err := CopyDir(srcFilename, dstFilename); err != nil {
63				return err
64			}
65		} else {
66			if err := CopyFile(srcFilename, dstFilename); err != nil {
67				return err
68			}
69		}
70	}
71
72	return nil
73}