aboutsummaryrefslogtreecommitdiff
path: root/cmd/mv.go
blob: c3f4b5b1dbb84350e8786f99732ef6013a18edff (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
47
48
49
50
51
52
53
54
55
56
57
58
59
package cmd

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

	"github.com/spf13/cobra"

	"gxlin.org/zk/pkg"
)

func init() {
	rootCmd.AddCommand(mvCmd)
}

var mvCmd = &cobra.Command{
	Use:  "mv [source] [target]",
	Args: mvCmdArgs,
	Run:  mvCmdRun,
}

func mvCmdArgs(cmd *cobra.Command, args []string) error {
	if len(args) != 2 {
		return errors.New("requires 2 args")
	}

	return nil
}

func mvCmdRun(cmd *cobra.Command, args []string) {
	rename(args[0], args[1])
}

func rename(source, target string) {
	source, err := filepath.Abs(source)
	if err != nil {
		panic("Unable to get abspath of " + source)
	}

	target, err = filepath.Abs(target)
	if err != nil {
		panic("Unable to get abspath of " + target)
	}

	if !pkg.DocCollection.Contain(source) {
		panic("Database doesn't contain " + source)
	}

	if err := os.Rename(source, target); err != nil {
		panic(err)
	}

	doc := pkg.DocCollection[source]
	for backlink := range doc.Backlinks {
		pkg.DocCollection[backlink].UpdateLinks(source, target)
	}

}