-
Notifications
You must be signed in to change notification settings - Fork 89
/
file_unix.go
96 lines (86 loc) · 2.44 KB
/
file_unix.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
// Copyright 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
//go:build !windows
// +build !windows
package utils
import (
"fmt"
"os"
"os/user"
"strconv"
"strings"
"syscall"
"github.com/juju/errors"
)
func homeDir(userName string) (string, error) {
u, err := user.Lookup(userName)
if err != nil {
return "", errors.NewUserNotFound(err, "no such user")
}
return u.HomeDir, nil
}
// MoveFile atomically moves the source file to the destination, returning
// whether the file was moved successfully. If the destination already exists,
// it returns an error rather than overwrite it.
//
// On unix systems, an error may occur with a successful move, if the source
// file location cannot be unlinked.
func MoveFile(source, destination string) (bool, error) {
err := os.Link(source, destination)
if err != nil {
return false, err
}
err = os.Remove(source)
if err != nil {
return true, err
}
return true, nil
}
// ReplaceFile atomically replaces the destination file or directory
// with the source. The errors that are returned are identical to
// those returned by os.Rename.
func ReplaceFile(source, destination string) error {
return os.Rename(source, destination)
}
// MakeFileURL returns a file URL if a directory is passed in else it does nothing
func MakeFileURL(in string) string {
if strings.HasPrefix(in, "/") {
return "file://" + in
}
return in
}
// ChownPath sets the uid and gid of path to match that of the user
// specified.
func ChownPath(path, username string) error {
u, err := user.Lookup(username)
if err != nil {
return fmt.Errorf("cannot lookup %q user id: %v", username, err)
}
uid, err := strconv.Atoi(u.Uid)
if err != nil {
return fmt.Errorf("invalid user id %q: %v", u.Uid, err)
}
gid, err := strconv.Atoi(u.Gid)
if err != nil {
return fmt.Errorf("invalid group id %q: %v", u.Gid, err)
}
return os.Chown(path, uid, gid)
}
// IsFileOwner checks to see if the ownership of the file corresponds to
// the same username
func IsFileOwner(path, username string) (bool, error) {
u, err := user.Lookup(username)
if err != nil {
return false, errors.Annotatef(err, "cannot lookup %q user id", username)
}
info, err := os.Stat(path)
if err != nil {
return false, errors.Trace(err)
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return false, fmt.Errorf("cannot lookup %q file", path)
}
return (strconv.Itoa(int(stat.Uid)) == u.Uid &&
strconv.Itoa(int(stat.Gid)) == u.Gid), nil
}