~welt/murse

murse/files.go -rw-r--r-- 1.4 KiB
f0e4c0e5welt Add tagging support. 4 months ago
                                                                                
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
package main

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

var ErrEscapesPath = errors.New("the path supplied would escape the install directory")

func getInstalledRevision(path string) (int, error) {
	rev := -1
	bytes, err := os.ReadFile(filepath.Join(filepath.FromSlash(path), ".revision"))
	if os.IsNotExist(err) {
		return rev, nil
	}
	if err != nil {
		return rev, err
	}

	return strconv.Atoi(strings.TrimSpace(string(bytes)))
}

func resolvePath(installpath, changepath string) (string, error) {
	absinst, err := filepath.Abs(installpath)
	if err != nil {
		return "", err
	}

	absfinal, err := filepath.Abs(filepath.Join(absinst, filepath.FromSlash(changepath)))
	if err != nil {
		return "", err
	}

	if !strings.HasPrefix(absfinal, absinst) {
		return "", ErrEscapesPath
	}

	return absfinal, nil

}

// Operating systems like Windows are very picky about
// moving files with a naked rename. This will fallback
// to copying the file contents if there was an error.

func move(oldpath string, newpath string) error {
	err := os.Rename(oldpath, newpath)
	if err != nil {
		old, err := os.Open(oldpath)
		if err != nil {
			return err
		}

		defer old.Close()

		new, err := os.OpenFile(newpath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0700)
		if err != nil {
			return err
		}

		defer new.Close()

		_, err = io.Copy(new, old)
		if err != nil {
			return err
		}

		err = os.Remove(oldpath)
		if err != nil {
			return err
		}
	}

	return nil

}