aboutsummaryrefslogtreecommitdiff
path: root/adopt.go
blob: 2689722366c68a34b8859e8a9cda563636e0f4ae (plain)
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
package main

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

func adopt(conf *Conf, args []string) error {
	if len(args) < 1 {
		return errors.New("must specify at least one file to adopt")
	}
	for _, name := range args {
		if err := adoptFile(conf, name); err != nil {
			return err
		}
	}
	return nil
}

func adoptFile(conf *Conf, name string) error {
	fromPath := filepath.Join(conf.Dest, name)
	toPath := filepath.Join(conf.Source, "templates", name)
	if err := os.MkdirAll(filepath.Dir(toPath), 0700); err != nil {
		return err
	}
	from, err := os.Open(fromPath)
	if err != nil {
		return err
	}
	defer from.Close()
	fromInfo, err := os.Stat(fromPath)
	if err != nil {
		return err
	}
	to, err := os.OpenFile(toPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fromInfo.Mode())
	if err != nil {
		return err
	}
	defer to.Close()
	if _, err = io.Copy(to, from); err != nil {
		return err
	}
	return nil
}