2015-12-23 16:46:15 +03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import "os"
|
|
|
|
|
2016-01-01 22:06:10 +03:00
|
|
|
type Arguments struct {
|
2015-12-23 16:46:15 +03:00
|
|
|
UID int
|
|
|
|
GID int
|
|
|
|
Flags int
|
|
|
|
Contents string
|
|
|
|
Permissions os.FileMode
|
|
|
|
}
|
|
|
|
|
2016-01-01 22:06:10 +03:00
|
|
|
type Argument func(*Arguments)
|
2015-12-23 16:46:15 +03:00
|
|
|
|
2016-01-01 22:06:10 +03:00
|
|
|
func UID(userID int) Argument {
|
|
|
|
return func(args *Arguments) {
|
2015-12-23 16:46:15 +03:00
|
|
|
args.UID = userID
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-01 22:06:10 +03:00
|
|
|
func GID(groupID int) Argument {
|
|
|
|
return func(args *Arguments) {
|
2015-12-23 16:46:15 +03:00
|
|
|
args.GID = groupID
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-01 22:06:10 +03:00
|
|
|
func Contents(c string) Argument {
|
|
|
|
return func(args *Arguments) {
|
2015-12-23 16:46:15 +03:00
|
|
|
args.Contents = c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-01 22:06:10 +03:00
|
|
|
func Permissions(perms os.FileMode) Argument {
|
|
|
|
return func(args *Arguments) {
|
2015-12-23 16:46:15 +03:00
|
|
|
args.Permissions = perms
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-01 22:06:10 +03:00
|
|
|
func New(filepath string, setters ...Argument) error {
|
|
|
|
// Default Arguments
|
|
|
|
args := &Arguments{
|
2015-12-23 16:46:15 +03:00
|
|
|
UID: os.Getuid(),
|
|
|
|
GID: os.Getgid(),
|
|
|
|
Contents: "",
|
|
|
|
Permissions: 0666,
|
|
|
|
Flags: os.O_CREATE | os.O_EXCL | os.O_WRONLY,
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, setter := range setters {
|
|
|
|
setter(args)
|
|
|
|
}
|
|
|
|
|
|
|
|
f, err := os.OpenFile(filepath, args.Flags, args.Permissions)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
} else {
|
|
|
|
defer f.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := f.WriteString(args.Contents); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return f.Chown(args.UID, args.GID)
|
|
|
|
}
|