This repository has been archived on 2020-11-18. You can view files and clone it, but cannot push or open issues or pull requests.
get/copy.go
jolheiser 98795c6735
Initial Commit
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2020-10-30 00:42:30 -05:00

64 lines
1.1 KiB
Go

package get
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// Copy copies files from a Getfile repo to local dist
func Copy(base, from, to string) error {
return copyExpand(base, from, to, false)
}
func copyExpand(base, from, to string, expand bool) error {
globs, err := filepath.Glob(filepath.Join(base, from))
if err != nil {
return err
}
if err := os.MkdirAll(to, os.ModePerm); err != nil {
return err
}
for _, g := range globs {
t := strings.TrimPrefix(g, base)
t = strings.TrimLeft(t, string(os.PathSeparator))
if err := copyFile(g, filepath.Join(to, t), expand); err != nil {
return err
}
}
return nil
}
func copyFile(from, to string, expand bool) error {
fromFi, err := os.Open(from)
if err != nil {
return err
}
defer fromFi.Close()
toFi, err := os.Create(to)
if err != nil {
return err
}
defer toFi.Close()
data, err := ioutil.ReadAll(fromFi)
if err != nil {
return err
}
contents := string(data)
if expand {
contents = os.ExpandEnv(contents)
}
if _, err := toFi.WriteString(contents); err != nil {
return err
}
return nil
}