-
Notifications
You must be signed in to change notification settings - Fork 7
/
copy.go
99 lines (86 loc) · 1.84 KB
/
copy.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
var (
pkgLinePrefix = []byte("package ")
)
type errFileExists string
func (e errFileExists) Error() string {
return "file exists: " + string(e)
}
func copy(dest, src, path, id, license string, files ...string) ([]string, error) {
pkgName, err := getPkgName(dest)
if err != nil {
return nil, err
}
var copied []string
for _, file := range files {
destFile, err := copyfile(dest, src, path, file, id, pkgName, license)
if err != nil {
return nil, err
}
copied = append(copied, destFile)
}
return copied, nil
}
func copyfile(dest, src, path, file, id, pkgName, license string) (string, error) {
fname := filepath.Base(file)
destFile := filepath.Join(dest, fmt.Sprintf(filenameFormat, fname))
destFilename := filepath.Base(destFile)
info("cp", fname, destFilename)
in, err := os.Open(file)
if err != nil {
return "", err
}
defer in.Close()
if !forceOverwrite {
// make sure we don't overwrite unless -f is set
_, err = os.Stat(destFile)
if !os.IsNotExist(err) /* file exists */ {
return "", errFileExists(destFile)
}
}
out, err := os.Create(destFile)
if err != nil {
return "", err
}
defer out.Close()
if shouldProcess(fname) {
err = writeHeader(out, src, path, id, license)
if err != nil {
return "", err
}
s := bufio.NewScanner(in)
for s.Scan() {
if bytes.HasPrefix(s.Bytes(), pkgLinePrefix) {
fmt.Fprintln(out, "package", pkgName)
continue
}
fmt.Fprintln(out, s.Text())
}
} else {
// normal copy
_, err = io.Copy(out, in)
if err != nil {
return "", err
}
}
err = out.Sync()
if err != nil {
return "", err
}
on("+", destFilename)
return destFile, nil
}
func shouldProcess(filename string) bool {
ext := filepath.Ext(filename)
ext = strings.ToLower(ext)
return ext == ".go"
}