+// Utility functions useful for file-related tests
+
+// Copyright (C) 2021 Simon Ruderich
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+package filetest
+
+import (
+ "io/fs"
+ "os"
+ "os/user"
+ "path/filepath"
+ "strconv"
+ "syscall"
+)
+
+type File struct {
+ Path string
+ Mode fs.FileMode
+ Data []byte
+}
+
+func WalkDir(basePath string) ([]File, error) {
+ var res []File
+ err := filepath.WalkDir(basePath, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ info, err := d.Info()
+ if err != nil {
+ return err
+ }
+ rel, err := filepath.Rel(basePath, path)
+ if err != nil {
+ return err
+ }
+
+ f := File{
+ Path: rel,
+ Mode: info.Mode(),
+ }
+ if f.Mode.Type() == 0 {
+ x, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ f.Data = x
+ } else if f.Mode.Type() == fs.ModeSymlink {
+ x, err := os.Readlink(path)
+ if err != nil {
+ return err
+ }
+ f.Data = []byte(x)
+ }
+ res = append(res, f)
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return res, nil
+}
+
+func CurrentUserAndGroup() (string, int, string, int) {
+ u, err := user.Current()
+ if err != nil {
+ panic(err)
+ }
+ g, err := user.LookupGroupId(u.Gid)
+ if err != nil {
+ panic(err)
+ }
+ uid, err := strconv.Atoi(u.Uid)
+ if err != nil {
+ panic(err)
+ }
+ gid, err := strconv.Atoi(g.Gid)
+ if err != nil {
+ panic(err)
+ }
+ return u.Username, uid, g.Name, gid
+}
+
+func CreateFile(path string, data string, mode fs.FileMode) {
+ err := os.WriteFile(path, []byte(data), 0644)
+ if err != nil {
+ panic(err)
+ }
+ err = os.Chmod(path, mode)
+ if err != nil {
+ panic(err)
+ }
+}
+
+func CreateSymlink(path string, data string) {
+ err := os.Symlink(data, path)
+ if err != nil {
+ panic(err)
+ }
+}
+
+func CreateDirectory(path string, mode fs.FileMode) {
+ err := os.Mkdir(path, 0700)
+ if err != nil {
+ panic(err)
+ }
+ err = os.Chmod(path, mode)
+ if err != nil {
+ panic(err)
+ }
+}
+
+func CreateFifo(path string, mode fs.FileMode) {
+ err := syscall.Mkfifo(path, 0600)
+ if err != nil {
+ panic(err)
+ }
+ err = os.Chmod(path, mode)
+ if err != nil {
+ panic(err)
+ }
+}