diff --git a/pkg/paths/README.md b/pkg/paths/README.md new file mode 100644 index 00000000..87721b6f --- /dev/null +++ b/pkg/paths/README.md @@ -0,0 +1,51 @@ +## paths: a golang library to simplify handling of paths + +This library aims to simplify handling of the most common operations with paths. + +For example code that looked like this: + +```go +buildPath := getPathFromSomewhere() // returns string +if buildPath != "" { + cachePath, err := filepath.Abs(filepath.Join(buildPath, "cache")) + ... +} +``` + +can be transformed to: + +```go +buildPath := getPathFromSomewhere() // returns *paths.Path +if buildPath != nil { + cachePath, err := buildPath.Join("cache").Abs() + ... +} +``` + +most operations that usually requires a bit of convoluted system calls are now simplified, for example to check if a path is a directory: + +```go +buildPath := "/path/to/somewhere" +srcPath := filepath.Join(buildPath, "src") +if info, err := os.Stat(srcPath); err == nil && !info.IsDir() { + os.MkdirAll(srcPath) +} +``` + +using this library can be done this way: + +```go +buildPath := paths.New("/path/to/somewhere") +srcPath := buildPath.Join("src") +if !srcPath.IsDir() { + scrPath.MkdirAll() +} +``` + +## Security + +If you think you found a vulnerability or other security-related bug in this project, please read our +[security policy](https://github.com/arduino/go-paths-helper/security/policy) and report the bug to our Security Team 🛡️ +Thank you! + +e-mail contact: security@arduino.cc diff --git a/pkg/paths/constructors.go b/pkg/paths/constructors.go new file mode 100644 index 00000000..e3b70c92 --- /dev/null +++ b/pkg/paths/constructors.go @@ -0,0 +1,80 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2018 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package paths + +import ( + "io/ioutil" + "os" +) + +// NullPath return the path to the /dev/null equivalent for the current OS +func NullPath() *Path { + return New("/dev/null") +} + +// TempDir returns the default path to use for temporary files +func TempDir() *Path { + return New(os.TempDir()).Canonical() +} + +// MkTempDir creates a new temporary directory in the directory +// dir with a name beginning with prefix and returns the path of +// the new directory. If dir is the empty string, TempDir uses the +// default directory for temporary files +func MkTempDir(dir, prefix string) (*Path, error) { + path, err := ioutil.TempDir(dir, prefix) + if err != nil { + return nil, err + } + return New(path).Canonical(), nil +} + +// MkTempFile creates a new temporary file in the directory dir with a name beginning with prefix, +// opens the file for reading and writing, and returns the resulting *os.File. If dir is nil, +// MkTempFile uses the default directory for temporary files (see paths.TempDir). Multiple programs +// calling TempFile simultaneously will not choose the same file. The caller can use f.Name() to +// find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed. +func MkTempFile(dir *Path, prefix string) (*os.File, error) { + tmpDir := "" + if dir != nil { + tmpDir = dir.String() + } + return ioutil.TempFile(tmpDir, prefix) +} + +// Getwd returns a rooted path name corresponding to the current +// directory. +func Getwd() (*Path, error) { + wd, err := os.Getwd() + if err != nil { + return nil, err + } + return New(wd), nil +} diff --git a/pkg/paths/list.go b/pkg/paths/list.go new file mode 100644 index 00000000..fbab13c5 --- /dev/null +++ b/pkg/paths/list.go @@ -0,0 +1,214 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2018 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package paths + +import ( + "sort" +) + +// PathList is a list of Path +type PathList []*Path + +// NewPathList creates a new PathList with the given paths +func NewPathList(paths ...string) PathList { + res := PathList{} + for _, path := range paths { + res = append(res, New(path)) + } + return res +} + +// Clone returns a copy of the current PathList +func (p *PathList) Clone() PathList { + res := PathList{} + for _, path := range *p { + res.Add(path.Clone()) + } + return res +} + +// AsStrings return this path list as a string array +func (p *PathList) AsStrings() []string { + res := []string{} + for _, path := range *p { + res = append(res, path.String()) + } + return res +} + +// FilterDirs remove all entries except directories +func (p *PathList) FilterDirs() { + res := (*p)[:0] + for _, path := range *p { + if path.IsDir() { + res = append(res, path) + } + } + *p = res +} + +// FilterOutDirs remove all directories entries +func (p *PathList) FilterOutDirs() { + res := (*p)[:0] + for _, path := range *p { + if !path.IsDir() { + res = append(res, path) + } + } + *p = res +} + +// FilterOutHiddenFiles remove all hidden files (files with the name +// starting with ".") +func (p *PathList) FilterOutHiddenFiles() { + p.FilterOutPrefix(".") +} + +// Filter will remove all the elements of the list that do not match +// the specified acceptor function +func (p *PathList) Filter(acceptorFunc func(*Path) bool) { + res := (*p)[:0] + for _, path := range *p { + if acceptorFunc(path) { + res = append(res, path) + } + } + *p = res +} + +// FilterOutPrefix remove all entries having one of the specified prefixes +func (p *PathList) FilterOutPrefix(prefixes ...string) { + filterFunction := func(path *Path) bool { + return !path.HasPrefix(prefixes...) + } + p.Filter(filterFunction) +} + +// FilterPrefix remove all entries not having one of the specified prefixes +func (p *PathList) FilterPrefix(prefixes ...string) { + filterFunction := func(path *Path) bool { + return path.HasPrefix(prefixes...) + } + p.Filter(filterFunction) +} + +// FilterOutSuffix remove all entries having one of the specified suffixes +func (p *PathList) FilterOutSuffix(suffixies ...string) { + filterFunction := func(path *Path) bool { + return !path.HasSuffix(suffixies...) + } + p.Filter(filterFunction) +} + +// FilterSuffix remove all entries not having one of the specified suffixes +func (p *PathList) FilterSuffix(suffixies ...string) { + filterFunction := func(path *Path) bool { + return path.HasSuffix(suffixies...) + } + p.Filter(filterFunction) +} + +// Add adds a Path to the PathList +func (p *PathList) Add(path *Path) { + *p = append(*p, path) +} + +// AddAll adds all Paths in the list passed as argument +func (p *PathList) AddAll(paths PathList) { + *p = append(*p, paths...) +} + +// AddIfMissing adds a Path to the PathList if the path is not already +// in the list +func (p *PathList) AddIfMissing(path *Path) { + if (*p).Contains(path) { + return + } + (*p).Add(path) +} + +// AddAllMissing adds all paths to the PathList excluding the paths already +// in the list +func (p *PathList) AddAllMissing(pathsToAdd PathList) { + for _, pathToAdd := range pathsToAdd { + (*p).AddIfMissing(pathToAdd) + } +} + +// ToAbs calls Path.ToAbs() method on each path of the list. +// It stops at the first error and returns it. If all ToAbs calls +// are successful nil is returned. +func (p *PathList) ToAbs() error { + for _, path := range *p { + if err := path.ToAbs(); err != nil { + return err + } + } + return nil +} + +// Contains check if the list contains a path that match +// exactly (EqualsTo) to the specified path +func (p *PathList) Contains(pathToSearch *Path) bool { + for _, path := range *p { + if path.EqualsTo(pathToSearch) { + return true + } + } + return false +} + +// ContainsEquivalentTo check if the list contains a path +// that is equivalent (EquivalentTo) to the specified path +func (p *PathList) ContainsEquivalentTo(pathToSearch *Path) bool { + for _, path := range *p { + if path.EquivalentTo(pathToSearch) { + return true + } + } + return false +} + +// Sort sorts this pathlist +func (p *PathList) Sort() { + sort.Sort(p) +} + +func (p *PathList) Len() int { + return len(*p) +} + +func (p *PathList) Less(i, j int) bool { + return (*p)[i].path < (*p)[j].path +} + +func (p *PathList) Swap(i, j int) { + (*p)[i], (*p)[j] = (*p)[j], (*p)[i] +} diff --git a/pkg/paths/list_test.go b/pkg/paths/list_test.go new file mode 100644 index 00000000..eaafc82c --- /dev/null +++ b/pkg/paths/list_test.go @@ -0,0 +1,169 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2018 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package paths + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestListConstructors(t *testing.T) { + list0 := NewPathList() + require.Len(t, list0, 0) + + list1 := NewPathList("test") + require.Len(t, list1, 1) + require.Equal(t, "[test]", fmt.Sprintf("%s", list1)) + + list3 := NewPathList("a", "b", "c") + require.Len(t, list3, 3) + require.Equal(t, "[a b c]", fmt.Sprintf("%s", list3)) + + require.False(t, list3.Contains(New("d"))) + require.True(t, list3.Contains(New("a"))) + require.False(t, list3.Contains(New("d/../a"))) + + require.False(t, list3.ContainsEquivalentTo(New("d"))) + require.True(t, list3.ContainsEquivalentTo(New("a"))) + require.True(t, list3.ContainsEquivalentTo(New("d/../a"))) + + list4 := list3.Clone() + require.Equal(t, "[a b c]", fmt.Sprintf("%s", list4)) + list4.AddIfMissing(New("d")) + require.Equal(t, "[a b c d]", fmt.Sprintf("%s", list4)) + list4.AddIfMissing(New("b")) + require.Equal(t, "[a b c d]", fmt.Sprintf("%s", list4)) + list4.AddAllMissing(NewPathList("a", "e", "i", "o", "u")) + require.Equal(t, "[a b c d e i o u]", fmt.Sprintf("%s", list4)) +} + +func TestListSorting(t *testing.T) { + list := NewPathList( + "pointless", + "spare", + "carve", + "unwieldy", + "empty", + "bow", + "tub", + "grease", + "error", + "energetic", + "depend", + "property") + require.Equal(t, "[pointless spare carve unwieldy empty bow tub grease error energetic depend property]", fmt.Sprintf("%s", list)) + list.Sort() + require.Equal(t, "[bow carve depend empty energetic error grease pointless property spare tub unwieldy]", fmt.Sprintf("%s", list)) +} + +func TestListFilters(t *testing.T) { + list := NewPathList( + "aaaa", + "bbbb", + "cccc", + "dddd", + "eeff", + "aaaa/bbbb", + "eeee/ffff", + "gggg/hhhh", + ) + + l1 := list.Clone() + l1.FilterPrefix("a") + require.Equal(t, "[aaaa]", fmt.Sprintf("%s", l1)) + + l2 := list.Clone() + l2.FilterPrefix("b") + require.Equal(t, "[bbbb aaaa/bbbb]", fmt.Sprintf("%s", l2)) + + l3 := list.Clone() + l3.FilterOutPrefix("b") + require.Equal(t, "[aaaa cccc dddd eeff eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l3)) + + l4 := list.Clone() + l4.FilterPrefix("a", "b") + require.Equal(t, "[aaaa bbbb aaaa/bbbb]", fmt.Sprintf("%s", l4)) + + l5 := list.Clone() + l5.FilterPrefix("test") + require.Equal(t, "[]", fmt.Sprintf("%s", l5)) + + l6 := list.Clone() + l6.FilterOutPrefix("b", "c", "h") + require.Equal(t, "[aaaa dddd eeff eeee/ffff]", fmt.Sprintf("%s", l6)) + + l7 := list.Clone() + l7.FilterSuffix("a") + require.Equal(t, "[aaaa]", fmt.Sprintf("%s", l7)) + + l8 := list.Clone() + l8.FilterSuffix("a", "h") + require.Equal(t, "[aaaa gggg/hhhh]", fmt.Sprintf("%s", l8)) + + l9 := list.Clone() + l9.FilterSuffix("test") + require.Equal(t, "[]", fmt.Sprintf("%s", l9)) + + l10 := list.Clone() + l10.FilterOutSuffix("a") + require.Equal(t, "[bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l10)) + + l11 := list.Clone() + l11.FilterOutSuffix("a", "h") + require.Equal(t, "[bbbb cccc dddd eeff aaaa/bbbb eeee/ffff]", fmt.Sprintf("%s", l11)) + + l12 := list.Clone() + l12.FilterOutSuffix("test") + require.Equal(t, "[aaaa bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l12)) + + l13 := list.Clone() + l13.FilterOutSuffix() + require.Equal(t, "[aaaa bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l13)) + + l14 := list.Clone() + l14.FilterSuffix() + require.Equal(t, "[]", fmt.Sprintf("%s", l14)) + + l15 := list.Clone() + l15.FilterOutPrefix() + require.Equal(t, "[aaaa bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l15)) + + l16 := list.Clone() + l16.FilterPrefix() + require.Equal(t, "[]", fmt.Sprintf("%s", l16)) + + l17 := list.Clone() + l17.Filter(func(p *Path) bool { + return p.Base() == "bbbb" + }) + require.Equal(t, "[bbbb aaaa/bbbb]", fmt.Sprintf("%s", l17)) +} diff --git a/pkg/paths/paths.go b/pkg/paths/paths.go new file mode 100644 index 00000000..a734d17e --- /dev/null +++ b/pkg/paths/paths.go @@ -0,0 +1,565 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2018 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package paths + +import ( + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "syscall" + "time" +) + +// Path represents a path +type Path struct { + path string +} + +// New creates a new Path object. If path is the empty string +// then nil is returned. +func New(path ...string) *Path { + if len(path) == 0 { + return nil + } + if len(path) == 1 && path[0] == "" { + return nil + } + res := &Path{path: path[0]} + if len(path) > 1 { + return res.Join(path[1:]...) + } + return res +} + +// NewFromFile creates a new Path object using the path name +// obtained from the File object (see os.File.Name function). +func NewFromFile(file *os.File) *Path { + return New(file.Name()) +} + +// Stat returns a FileInfo describing the named file. The result is +// cached internally for next queries. To ensure that the cached +// FileInfo entry is updated just call Stat again. +func (p *Path) Stat() (fs.FileInfo, error) { + return os.Stat(p.path) +} + +// Lstat returns a FileInfo describing the named file. If the file is +// a symbolic link, the returned FileInfo describes the symbolic link. +// Lstat makes no attempt to follow the link. If there is an error, it +// will be of type *PathError. +func (p *Path) Lstat() (fs.FileInfo, error) { + return os.Lstat(p.path) +} + +// Clone create a copy of the Path object +func (p *Path) Clone() *Path { + return New(p.path) +} + +// Join create a new Path by joining the provided paths +func (p *Path) Join(paths ...string) *Path { + return New(filepath.Join(p.path, filepath.Join(paths...))) +} + +// JoinPath create a new Path by joining the provided paths +func (p *Path) JoinPath(paths ...*Path) *Path { + res := p.Clone() + for _, path := range paths { + res = res.Join(path.path) + } + return res +} + +// Base returns the last element of path +func (p *Path) Base() string { + return filepath.Base(p.path) +} + +// Ext returns the file name extension used by path +func (p *Path) Ext() string { + return filepath.Ext(p.path) +} + +// HasPrefix returns true if the file name has one of the +// given prefixes (the Base() method is used to obtain the +// file name used for the comparison) +func (p *Path) HasPrefix(prefixes ...string) bool { + filename := p.Base() + for _, prefix := range prefixes { + if strings.HasPrefix(filename, prefix) { + return true + } + } + return false +} + +// HasSuffix returns true if the file name has one of the +// given suffixies +func (p *Path) HasSuffix(suffixies ...string) bool { + filename := p.String() + for _, suffix := range suffixies { + if strings.HasSuffix(filename, suffix) { + return true + } + } + return false +} + +// RelTo returns a relative Path that is lexically equivalent to r when +// joined to the current Path. +// +// For example paths.New("/my/path/ab/cd").RelTo(paths.New("/my/path")) +// returns "../..". +func (p *Path) RelTo(r *Path) (*Path, error) { + rel, err := filepath.Rel(p.path, r.path) + if err != nil { + return nil, err + } + return New(rel), nil +} + +// RelFrom returns a relative Path that when joined with r is lexically +// equivalent to the current path. +// +// For example paths.New("/my/path/ab/cd").RelFrom(paths.New("/my/path")) +// returns "ab/cd". +func (p *Path) RelFrom(r *Path) (*Path, error) { + rel, err := filepath.Rel(r.path, p.path) + if err != nil { + return nil, err + } + return New(rel), nil +} + +// Abs returns the absolute path of the current Path +func (p *Path) Abs() (*Path, error) { + abs, err := filepath.Abs(p.path) + if err != nil { + return nil, err + } + return New(abs), nil +} + +// IsAbs returns true if the Path is absolute +func (p *Path) IsAbs() bool { + return filepath.IsAbs(p.path) +} + +// ToAbs transofrm the current Path to the corresponding absolute path +func (p *Path) ToAbs() error { + abs, err := filepath.Abs(p.path) + if err != nil { + return err + } + p.path = abs + return nil +} + +// Clean Clean returns the shortest path name equivalent to path by +// purely lexical processing +func (p *Path) Clean() *Path { + return New(filepath.Clean(p.path)) +} + +// IsInsideDir returns true if the current path is inside the provided +// dir +func (p *Path) IsInsideDir(dir *Path) (bool, error) { + rel, err := filepath.Rel(dir.path, p.path) + if err != nil { + // If the dir cannot be made relative to this path it means + // that it belong to a different filesystems, so it cannot be + // inside this path. + return false, nil + } + return !strings.Contains(rel, ".."+string(os.PathSeparator)) && + rel != ".." && + rel != ".", nil +} + +// Parent returns all but the last element of path, typically the path's +// directory or the parent directory if the path is already a directory +func (p *Path) Parent() *Path { + return New(filepath.Dir(p.path)) +} + +// Mkdir create a directory denoted by the current path +func (p *Path) Mkdir() error { + return os.Mkdir(p.path, 0755) +} + +// MkdirAll creates a directory named path, along with any necessary +// parents, and returns nil, or else returns an error +func (p *Path) MkdirAll() error { + return os.MkdirAll(p.path, os.FileMode(0755)) +} + +// Remove removes the named file or directory +func (p *Path) Remove() error { + return os.Remove(p.path) +} + +// RemoveAll removes path and any children it contains. It removes +// everything it can but returns the first error it encounters. If +// the path does not exist, RemoveAll returns nil (no error). +func (p *Path) RemoveAll() error { + return os.RemoveAll(p.path) +} + +// Rename renames (moves) the path to newpath. If newpath already exists +// and is not a directory, Rename replaces it. OS-specific restrictions +// may apply when oldpath and newpath are in different directories. If +// there is an error, it will be of type *os.LinkError. +func (p *Path) Rename(newpath *Path) error { + return os.Rename(p.path, newpath.path) +} + +// MkTempDir creates a new temporary directory inside the path +// pointed by the Path object with a name beginning with prefix +// and returns the path of the new directory. +func (p *Path) MkTempDir(prefix string) (*Path, error) { + return MkTempDir(p.path, prefix) +} + +// FollowSymLink transforms the current path to the path pointed by the +// symlink if path is a symlink, otherwise it does nothing +func (p *Path) FollowSymLink() error { + resolvedPath, err := filepath.EvalSymlinks(p.path) + if err != nil { + return err + } + p.path = resolvedPath + return nil +} + +// Exist return true if the file denoted by this path exists, false +// in any other case (also in case of error). +func (p *Path) Exist() bool { + exist, err := p.ExistCheck() + return exist && err == nil +} + +// NotExist return true if the file denoted by this path DO NOT exists, false +// in any other case (also in case of error). +func (p *Path) NotExist() bool { + exist, err := p.ExistCheck() + return !exist && err == nil +} + +// ExistCheck return true if the path exists or false if the path doesn't exists. +// In case the check fails false is returned together with the corresponding error. +func (p *Path) ExistCheck() (bool, error) { + _, err := p.Stat() + if err == nil { + return true, nil + } + if os.IsNotExist(err) { + return false, nil + } + if err.(*os.PathError).Err == syscall.ENOTDIR { + return false, nil + } + return false, err +} + +// IsDir returns true if the path exists and is a directory. In all the other +// cases (and also in case of any error) false is returned. +func (p *Path) IsDir() bool { + isdir, err := p.IsDirCheck() + return isdir && err == nil +} + +// IsNotDir returns true if the path exists and is NOT a directory. In all the other +// cases (and also in case of any error) false is returned. +func (p *Path) IsNotDir() bool { + isdir, err := p.IsDirCheck() + return !isdir && err == nil +} + +// IsDirCheck return true if the path exists and is a directory or false +// if the path exists and is not a directory. In all the other case false and +// the corresponding error is returned. +func (p *Path) IsDirCheck() (bool, error) { + info, err := p.Stat() + if err == nil { + return info.IsDir(), nil + } + return false, err +} + +// CopyTo copies the contents of the file named src to the file named +// by dst. The file will be created if it does not already exist. If the +// destination file exists, all it's contents will be replaced by the contents +// of the source file. The file mode will be copied from the source and +// the copied data is synced/flushed to stable storage. +func (p *Path) CopyTo(dst *Path) error { + if p.EqualsTo(dst) { + return fmt.Errorf("%s and %s are the same file", p.path, dst.path) + } + + in, err := os.Open(p.path) + if err != nil { + return err + } + defer in.Close() + + out, err := os.Create(dst.path) + if err != nil { + return err + } + defer out.Close() + + if _, err := io.Copy(out, in); err != nil { + return err + } + + if err := out.Sync(); err != nil { + return err + } + + si, err := p.Stat() + if err != nil { + return err + } + + err = os.Chmod(dst.path, si.Mode()) + if err != nil { + return err + } + + return nil +} + +// CopyDirTo recursively copies the directory denoted by the current path to +// the destination path. The source directory must exist and the destination +// directory must NOT exist (no implicit destination name allowed). +// Symlinks are not copied, they will be supported in future versions. +func (p *Path) CopyDirTo(dst *Path) error { + src := p.Clean() + dst = dst.Clean() + + srcFiles, err := src.ReadDir() + if err != nil { + return fmt.Errorf("error reading source dir %s: %s", src, err) + } + + if exist, err := dst.ExistCheck(); exist { + return fmt.Errorf("destination %s already exists", dst) + } else if err != nil { + return fmt.Errorf("checking if %s exists: %s", dst, err) + } + + if err := dst.MkdirAll(); err != nil { + return fmt.Errorf("creating destination dir %s: %s", dst, err) + } + + srcInfo, err := src.Stat() + if err != nil { + return fmt.Errorf("getting stat info for %s: %s", src, err) + } + if err := os.Chmod(dst.path, srcInfo.Mode()); err != nil { + return fmt.Errorf("setting permission for dir %s: %s", dst, err) + } + + for _, srcPath := range srcFiles { + srcPathInfo, err := srcPath.Stat() + if err != nil { + return fmt.Errorf("getting stat info for %s: %s", srcPath, err) + } + dstPath := dst.Join(srcPath.Base()) + + if srcPathInfo.IsDir() { + if err := srcPath.CopyDirTo(dstPath); err != nil { + return fmt.Errorf("copying %s to %s: %s", srcPath, dstPath, err) + } + continue + } + + // Skip symlinks. + if srcPathInfo.Mode()&os.ModeSymlink != 0 { + // TODO + continue + } + + if err := srcPath.CopyTo(dstPath); err != nil { + return fmt.Errorf("copying %s to %s: %s", srcPath, dstPath, err) + } + } + return nil +} + +// Chmod changes the mode of the named file to mode. If the file is a +// symbolic link, it changes the mode of the link's target. If there +// is an error, it will be of type *os.PathError. +func (p *Path) Chmod(mode fs.FileMode) error { + return os.Chmod(p.path, mode) +} + +// Chtimes changes the access and modification times of the named file, +// similar to the Unix utime() or utimes() functions. +func (p *Path) Chtimes(atime, mtime time.Time) error { + return os.Chtimes(p.path, atime, mtime) +} + +// ReadFile reads the file named by filename and returns the contents +func (p *Path) ReadFile() ([]byte, error) { + return os.ReadFile(p.path) +} + +// WriteFile writes data to a file named by filename. If the file +// does not exist, WriteFile creates it otherwise WriteFile truncates +// it before writing. +func (p *Path) WriteFile(data []byte) error { + return os.WriteFile(p.path, data, os.FileMode(0644)) +} + +// WriteToTempFile writes data to a newly generated temporary file. +// dir and prefix have the same meaning for MkTempFile. +// In case of success the Path to the temp file is returned. +func WriteToTempFile(data []byte, dir *Path, prefix string) (res *Path, err error) { + f, err := MkTempFile(dir, prefix) + if err != nil { + return nil, err + } + defer f.Close() + if n, err := f.Write(data); err != nil { + return nil, err + } else if n < len(data) { + return nil, fmt.Errorf("could not write all data (written %d bytes out of %d)", n, len(data)) + } + return New(f.Name()), nil +} + +// ReadFileAsLines reads the file named by filename and returns it as an +// array of lines. This function takes care of the newline encoding +// differences between different OS +func (p *Path) ReadFileAsLines() ([]string, error) { + data, err := p.ReadFile() + if err != nil { + return nil, err + } + txt := string(data) + txt = strings.Replace(txt, "\r\n", "\n", -1) + return strings.Split(txt, "\n"), nil +} + +// Truncate create an empty file named by path or if the file already +// exist it truncates it (delete all contents) +func (p *Path) Truncate() error { + return p.WriteFile([]byte{}) +} + +// Open opens a file for reading. It calls os.Open on the +// underlying path. +func (p *Path) Open() (*os.File, error) { + return os.Open(p.path) +} + +// Create creates or truncates a file. It calls os.Create +// on the underlying path. +func (p *Path) Create() (*os.File, error) { + return os.Create(p.path) +} + +// Append opens a file for append or creates it if the file doesn't exist. +func (p *Path) Append() (*os.File, error) { + return os.OpenFile(p.path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666) +} + +// EqualsTo return true if both paths are equal +func (p *Path) EqualsTo(other *Path) bool { + return p.path == other.path +} + +// EquivalentTo return true if both paths are equivalent (they points to the +// same file even if they are lexicographically different) based on the current +// working directory. +func (p *Path) EquivalentTo(other *Path) bool { + if p.Clean().path == other.Clean().path { + return true + } + + if infoP, err := p.Stat(); err != nil { + // go ahead with the next test... + } else if infoOther, err := other.Stat(); err != nil { + // go ahead with the next test... + } else if os.SameFile(infoP, infoOther) { + return true + } + + if absP, err := p.Abs(); err != nil { + return false + } else if absOther, err := other.Abs(); err != nil { + return false + } else { + return absP.path == absOther.path + } +} + +// Parents returns all the parents directories of the current path. If the path is absolute +// it starts from the current path to the root, if the path is relative is starts from the +// current path to the current directory. +// The path should be clean for this method to work properly (no .. or . or other shortcuts). +// This function does not performs any check on the returned paths. +func (p *Path) Parents() []*Path { + res := []*Path{} + dir := p + for { + res = append(res, dir) + parent := dir.Parent() + if parent.EquivalentTo(dir) { + break + } + dir = parent + } + return res +} + +func (p *Path) String() string { + return p.path +} + +// Canonical return a "canonical" Path for the given filename. +// The meaning of "canonical" is OS-dependent but the goal of this method +// is to always return the same path for a given file (factoring out all the +// possibile ambiguities including, for example, relative paths traversal, +// symlinks, drive volume letter case, etc). +func (p *Path) Canonical() *Path { + canonical := p.Clone() + // https://github.com/golang/go/issues/17084#issuecomment-246645354 + canonical.FollowSymLink() + if absPath, err := canonical.Abs(); err == nil { + canonical = absPath + } + return canonical +} diff --git a/pkg/paths/paths_test.go b/pkg/paths/paths_test.go new file mode 100644 index 00000000..27fde624 --- /dev/null +++ b/pkg/paths/paths_test.go @@ -0,0 +1,432 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2018 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package paths + +import ( + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func pathEqualsTo(t *testing.T, expected string, actual *Path) { + require.Equal(t, expected, filepath.ToSlash(actual.String())) +} + +func TestPathNew(t *testing.T) { + test1 := New("path") + require.Equal(t, "path", test1.String()) + + test2 := New("path", "path") + require.Equal(t, filepath.Join("path", "path"), test2.String()) + + test3 := New() + require.Nil(t, test3) + + test4 := New("") + require.Nil(t, test4) +} + +func TestPath(t *testing.T) { + testPath := New("testdata", "fileset") + pathEqualsTo(t, "testdata/fileset", testPath) + isDir, err := testPath.IsDirCheck() + require.True(t, isDir) + require.NoError(t, err) + require.True(t, testPath.IsDir()) + require.False(t, testPath.IsNotDir()) + exist, err := testPath.ExistCheck() + require.True(t, exist) + require.NoError(t, err) + require.True(t, testPath.Exist()) + require.False(t, testPath.NotExist()) + + folderPath := testPath.Join("folder") + pathEqualsTo(t, "testdata/fileset/folder", folderPath) + isDir, err = folderPath.IsDirCheck() + require.True(t, isDir) + require.NoError(t, err) + require.True(t, folderPath.IsDir()) + require.False(t, folderPath.IsNotDir()) + + exist, err = folderPath.ExistCheck() + require.True(t, exist) + require.NoError(t, err) + require.True(t, folderPath.Exist()) + require.False(t, folderPath.NotExist()) + + filePath := testPath.Join("file") + pathEqualsTo(t, "testdata/fileset/file", filePath) + isDir, err = filePath.IsDirCheck() + require.False(t, isDir) + require.NoError(t, err) + require.False(t, filePath.IsDir()) + require.True(t, filePath.IsNotDir()) + exist, err = filePath.ExistCheck() + require.True(t, exist) + require.NoError(t, err) + require.True(t, filePath.Exist()) + require.False(t, filePath.NotExist()) + + anotherFilePath := filePath.Join("notexistent") + pathEqualsTo(t, "testdata/fileset/file/notexistent", anotherFilePath) + isDir, err = anotherFilePath.IsDirCheck() + require.False(t, isDir) + require.Error(t, err) + require.False(t, anotherFilePath.IsDir()) + require.False(t, anotherFilePath.IsNotDir()) + exist, err = anotherFilePath.ExistCheck() + require.False(t, exist) + require.NoError(t, err) + require.False(t, anotherFilePath.Exist()) + require.True(t, anotherFilePath.NotExist()) + + list, err := folderPath.ReadDir() + require.NoError(t, err) + require.Len(t, list, 4) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[0]) + pathEqualsTo(t, "testdata/fileset/folder/file2", list[1]) + pathEqualsTo(t, "testdata/fileset/folder/file3", list[2]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[3]) + + list2 := list.Clone() + list2.FilterDirs() + require.Len(t, list2, 1) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list2[0]) + + list2 = list.Clone() + list2.FilterOutHiddenFiles() + require.Len(t, list2, 3) + pathEqualsTo(t, "testdata/fileset/folder/file2", list2[0]) + pathEqualsTo(t, "testdata/fileset/folder/file3", list2[1]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list2[2]) + + list2 = list.Clone() + list2.FilterOutPrefix("file") + require.Len(t, list2, 2) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", list2[0]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list2[1]) +} + +func TestResetStatCacheWhenFollowingSymlink(t *testing.T) { + testdata := New("testdata", "fileset") + files, err := testdata.ReadDir() + require.NoError(t, err) + for _, file := range files { + if file.Base() == "symlinktofolder" { + err = file.FollowSymLink() + require.NoError(t, err) + isDir, err := file.IsDirCheck() + require.NoError(t, err) + require.True(t, isDir) + break + } + } +} + +func TestIsInsideDir(t *testing.T) { + notInside := func(a, b *Path) { + isInside, err := a.IsInsideDir(b) + require.NoError(t, err) + require.False(t, isInside, "%s is inside %s", a, b) + } + + inside := func(a, b *Path) { + isInside, err := a.IsInsideDir(b) + require.NoError(t, err) + require.True(t, isInside, "%s is inside %s", a, b) + notInside(b, a) + } + + f1 := New("/a/b/c") + f2 := New("/a/b/c/d") + f3 := New("/a/b/c/d/e") + + notInside(f1, f1) + notInside(f1, f2) + inside(f2, f1) + notInside(f1, f3) + inside(f3, f1) + + r1 := New("a/b/c") + r2 := New("a/b/c/d") + r3 := New("a/b/c/d/e") + r4 := New("f/../a/b/c/d/e") + r5 := New("a/b/c/d/e/f/..") + + notInside(r1, r1) + notInside(r1, r2) + inside(r2, r1) + notInside(r1, r3) + inside(r3, r1) + inside(r4, r1) + notInside(r1, r4) + inside(r5, r1) + notInside(r1, r5) + + f4 := New("/home/megabug/aide/arduino-1.8.6/hardware/arduino/avr") + f5 := New("/home/megabug/a15/packages") + notInside(f5, f4) + notInside(f4, f5) + + if runtime.GOOS == "windows" { + f6 := New("C:\\", "A") + f7 := New("C:\\", "A", "B", "C") + f8 := New("E:\\", "A", "B", "C") + inside(f7, f6) + notInside(f8, f6) + } +} + +func TestReadFileAsLines(t *testing.T) { + lines, err := New("testdata/fileset/anotherFile").ReadFileAsLines() + require.NoError(t, err) + require.Len(t, lines, 4) + require.Equal(t, "line 1", lines[0]) + require.Equal(t, "line 2", lines[1]) + require.Equal(t, "", lines[2]) + require.Equal(t, "line 3", lines[3]) +} + +func TestCanonicaTempDir(t *testing.T) { + require.Equal(t, TempDir().String(), TempDir().Canonical().String()) +} + +func TestCopyDir(t *testing.T) { + tmp, err := MkTempDir("", "") + require.NoError(t, err) + defer tmp.RemoveAll() + + src := New("testdata", "fileset") + err = src.CopyDirTo(tmp.Join("dest")) + require.NoError(t, err, "copying dir") + + exist, err := tmp.Join("dest", "folder", "subfolder", "file4").ExistCheck() + require.True(t, exist) + require.NoError(t, err) + + isdir, err := tmp.Join("dest", "folder", "subfolder", "file4").IsDirCheck() + require.False(t, isdir) + require.NoError(t, err) + + err = src.CopyDirTo(tmp.Join("dest")) + require.Error(t, err, "copying dir to already existing") + + err = src.Join("file").CopyDirTo(tmp.Join("dest2")) + require.Error(t, err, "copying file as dir") +} + +func TestParents(t *testing.T) { + parents := New("/a/very/long/path").Parents() + require.Len(t, parents, 5) + pathEqualsTo(t, "/a/very/long/path", parents[0]) + pathEqualsTo(t, "/a/very/long", parents[1]) + pathEqualsTo(t, "/a/very", parents[2]) + pathEqualsTo(t, "/a", parents[3]) + pathEqualsTo(t, "/", parents[4]) + + parents2 := New("a/very/relative/path").Parents() + require.Len(t, parents, 5) + pathEqualsTo(t, "a/very/relative/path", parents2[0]) + pathEqualsTo(t, "a/very/relative", parents2[1]) + pathEqualsTo(t, "a/very", parents2[2]) + pathEqualsTo(t, "a", parents2[3]) + pathEqualsTo(t, ".", parents2[4]) +} + +func TestFilterDirs(t *testing.T) { + testPath := New("testdata", "fileset") + + list, err := testPath.ReadDir() + require.NoError(t, err) + require.Len(t, list, 6) + + pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) + pathEqualsTo(t, "testdata/fileset/file", list[1]) + pathEqualsTo(t, "testdata/fileset/folder", list[2]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[3]) + pathEqualsTo(t, "testdata/fileset/test.txt", list[4]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[5]) + + list.FilterDirs() + require.Len(t, list, 2) + pathEqualsTo(t, "testdata/fileset/folder", list[0]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[1]) +} + +func TestFilterOutDirs(t *testing.T) { + { + testPath := New("testdata", "fileset") + + list, err := testPath.ReadDir() + require.NoError(t, err) + require.Len(t, list, 6) + + pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) + pathEqualsTo(t, "testdata/fileset/file", list[1]) + pathEqualsTo(t, "testdata/fileset/folder", list[2]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[3]) + pathEqualsTo(t, "testdata/fileset/test.txt", list[4]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[5]) + + list.FilterOutDirs() + require.Len(t, list, 4) + pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) + pathEqualsTo(t, "testdata/fileset/file", list[1]) + pathEqualsTo(t, "testdata/fileset/test.txt", list[2]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[3]) + } + + { + list, err := New("testdata", "broken_symlink", "dir_1").ReadDirRecursive() + require.NoError(t, err) + + require.Len(t, list, 7) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/broken_link", list[0]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/file2", list[1]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_dir", list[2]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_dir/file1", list[3]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_file", list[4]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/real_dir", list[5]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/real_dir/file1", list[6]) + + list.FilterOutDirs() + require.Len(t, list, 5) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/broken_link", list[0]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/file2", list[1]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_dir/file1", list[2]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_file", list[3]) + pathEqualsTo(t, "testdata/broken_symlink/dir_1/real_dir/file1", list[4]) + } +} + +func TestEquivalentPaths(t *testing.T) { + wd, err := Getwd() + require.NoError(t, err) + require.True(t, New("file1").EquivalentTo(New("file1", "somethingelse", ".."))) + require.True(t, New("file1", "abc").EquivalentTo(New("file1", "abc", "def", ".."))) + require.True(t, wd.Join("file1").EquivalentTo(New("file1"))) + require.True(t, wd.Join("file1").EquivalentTo(New("file1", "abc", ".."))) + + if runtime.GOOS == "windows" { + q := New("testdata", "fileset", "anotherFile") + r := New("testdata", "fileset", "ANOTHE~1") + require.True(t, q.EquivalentTo(r)) + require.True(t, r.EquivalentTo(q)) + } +} + +func TestCanonicalize(t *testing.T) { + wd, err := Getwd() + require.NoError(t, err) + + p := New("testdata", "fileset", "anotherFile").Canonical() + require.Equal(t, wd.Join("testdata", "fileset", "anotherFile").String(), p.String()) + + p = New("testdata", "fileset", "nonexistentFile").Canonical() + require.Equal(t, wd.Join("testdata", "fileset", "nonexistentFile").String(), p.String()) + + if runtime.GOOS == "windows" { + q := New("testdata", "fileset", "ANOTHE~1").Canonical() + require.Equal(t, wd.Join("testdata", "fileset", "anotherFile").String(), q.String()) + + r := New("c:\\").Canonical() + require.Equal(t, "C:\\", r.String()) + + tmp, err := MkTempDir("", "pref") + require.NoError(t, err) + require.Equal(t, tmp.String(), tmp.Canonical().String()) + } +} + +func TestRelativeTo(t *testing.T) { + res, err := New("/my/abs/path/123/456").RelTo(New("/my/abs/path")) + require.NoError(t, err) + pathEqualsTo(t, "../..", res) + + res, err = New("/my/abs/path").RelTo(New("/my/abs/path/123/456")) + require.NoError(t, err) + pathEqualsTo(t, "123/456", res) + + res, err = New("my/path").RelTo(New("/other/path")) + require.Error(t, err) + require.Nil(t, res) + + res, err = New("/my/abs/path/123/456").RelFrom(New("/my/abs/path")) + pathEqualsTo(t, "123/456", res) + require.NoError(t, err) + + res, err = New("/my/abs/path").RelFrom(New("/my/abs/path/123/456")) + require.NoError(t, err) + pathEqualsTo(t, "../..", res) + + res, err = New("my/path").RelFrom(New("/other/path")) + require.Error(t, err) + require.Nil(t, res) +} + +func TestWriteToTempFile(t *testing.T) { + tmpDir := New("testdata", "fileset", "tmp") + err := tmpDir.MkdirAll() + require.NoError(t, err) + defer tmpDir.RemoveAll() + + tmpData := []byte("test") + tmp, err := WriteToTempFile(tmpData, tmpDir, "prefix") + defer tmp.Remove() + require.NoError(t, err) + require.True(t, strings.HasPrefix(tmp.Base(), "prefix")) + isInside, err := tmp.IsInsideDir(tmpDir) + require.NoError(t, err) + require.True(t, isInside) + data, err := tmp.ReadFile() + require.NoError(t, err) + require.Equal(t, tmpData, data) +} + +func TestCopyToSamePath(t *testing.T) { + tmpDir := New(t.TempDir()) + srcFile := tmpDir.Join("test_file") + dstFile := srcFile + + // create the source file in tmp dir + err := srcFile.WriteFile([]byte("hello")) + require.NoError(t, err) + content, err := srcFile.ReadFile() + require.NoError(t, err) + require.Equal(t, []byte("hello"), content) + + // cannot copy the same file + err = srcFile.CopyTo(dstFile) + require.Error(t, err) + require.Contains(t, err.Error(), "are the same file") +} diff --git a/pkg/paths/process.go b/pkg/paths/process.go new file mode 100644 index 00000000..4c869286 --- /dev/null +++ b/pkg/paths/process.go @@ -0,0 +1,226 @@ +// +// This file is part of PathsHelper library. +// +// Copyright 2023 Arduino AG (http://www.arduino.cc/) +// +// PathsHelper library 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 2 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, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// As a special exception, you may use this file as part of a free software +// library without restriction. Specifically, if other files instantiate +// templates or use macros or inline functions from this file, or you compile +// this file and link it with other files to produce an executable, this +// file does not by itself cause the resulting executable to be covered by +// the GNU General Public License. This exception does not however +// invalidate any other reasons why the executable file might be covered by +// the GNU General Public License. +// + +package paths + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "os/exec" +) + +// Process is representation of an external process run +type Process struct { + cmd *exec.Cmd +} + +// NewProcess creates a command with the provided command line arguments +// and environment variables (that will be added to the parent os.Environ). +// The argument args[0] is the path to the executable, the remainder are the +// arguments to the command. +func NewProcess(extraEnv []string, args ...string) (*Process, error) { + if len(args) == 0 { + return nil, errors.New("no executable specified") + } + p := &Process{ + cmd: exec.Command(args[0], args[1:]...), + } + p.cmd.Env = append(os.Environ(), extraEnv...) + p.TellCommandNotToSpawnShell() + + // This is required because some tools detects if the program is running + // from terminal by looking at the stdin/out bindings. + // https://github.com/arduino/arduino-cli/issues/844 + p.cmd.Stdin = nullReaderInstance + return p, nil +} + +// TellCommandNotToSpawnShell avoids that the specified Cmd display a small +// command prompt while runnning on Windows. It has no effects on other OS. +func (p *Process) TellCommandNotToSpawnShell() { + tellCommandNotToSpawnShell(p.cmd) +} + +// NewProcessFromPath creates a command from the provided executable path, +// additional environment vars (in addition to the system default ones) +// and command line arguments. +func NewProcessFromPath(extraEnv []string, executable *Path, args ...string) (*Process, error) { + processArgs := []string{executable.String()} + processArgs = append(processArgs, args...) + return NewProcess(extraEnv, processArgs...) +} + +// RedirectStdoutTo will redirect the process' stdout to the specified +// writer. Any previous redirection will be overwritten. +func (p *Process) RedirectStdoutTo(out io.Writer) { + p.cmd.Stdout = out +} + +// RedirectStderrTo will redirect the process' stdout to the specified +// writer. Any previous redirection will be overwritten. +func (p *Process) RedirectStderrTo(out io.Writer) { + p.cmd.Stderr = out +} + +// StdinPipe returns a pipe that will be connected to the command's standard +// input when the command starts. The pipe will be closed automatically after +// Wait sees the command exit. A caller need only call Close to force the pipe +// to close sooner. For example, if the command being run will not exit until +// standard input is closed, the caller must close the pipe. +func (p *Process) StdinPipe() (io.WriteCloser, error) { + if p.cmd.Stdin == nullReaderInstance { + p.cmd.Stdin = nil + } + return p.cmd.StdinPipe() +} + +// StdoutPipe returns a pipe that will be connected to the command's standard +// output when the command starts. +// +// Wait will close the pipe after seeing the command exit, so most callers +// don't need to close the pipe themselves. It is thus incorrect to call Wait +// before all reads from the pipe have completed. +// For the same reason, it is incorrect to call Run when using StdoutPipe. +func (p *Process) StdoutPipe() (io.ReadCloser, error) { + return p.cmd.StdoutPipe() +} + +// StderrPipe returns a pipe that will be connected to the command's standard +// error when the command starts. +// +// Wait will close the pipe after seeing the command exit, so most callers +// don't need to close the pipe themselves. It is thus incorrect to call Wait +// before all reads from the pipe have completed. +// For the same reason, it is incorrect to use Run when using StderrPipe. +func (p *Process) StderrPipe() (io.ReadCloser, error) { + return p.cmd.StderrPipe() +} + +// Start will start the underliyng process. +func (p *Process) Start() error { + return p.cmd.Start() +} + +// Wait waits for the command to exit and waits for any copying to stdin or copying +// from stdout or stderr to complete. +func (p *Process) Wait() error { + // TODO: make some helpers to retrieve exit codes out of *ExitError. + return p.cmd.Wait() +} + +// Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented. +func (p *Process) Signal(sig os.Signal) error { + return p.cmd.Process.Signal(sig) +} + +// Kill causes the Process to exit immediately. Kill does not wait until the Process has +// actually exited. This only kills the Process itself, not any other processes it may +// have started. +func (p *Process) Kill() error { + return p.cmd.Process.Kill() +} + +// SetDir sets the working directory of the command. If Dir is the empty string, Run +// runs the command in the calling process's current directory. +func (p *Process) SetDir(dir string) { + p.cmd.Dir = dir +} + +// GetDir gets the working directory of the command. +func (p *Process) GetDir() string { + return p.cmd.Dir +} + +// SetDirFromPath sets the working directory of the command. If path is nil, Run +// runs the command in the calling process's current directory. +func (p *Process) SetDirFromPath(path *Path) { + if path == nil { + p.cmd.Dir = "" + } else { + p.cmd.Dir = path.String() + } +} + +// Run starts the specified command and waits for it to complete. +func (p *Process) Run() error { + return p.cmd.Run() +} + +// SetEnvironment set the environment for the running process. Each entry is of the form "key=value". +// System default environments will be wiped out. +func (p *Process) SetEnvironment(values []string) { + p.cmd.Env = append([]string{}, values...) +} + +// RunWithinContext starts the specified command and waits for it to complete. If the given context +// is canceled before the normal process termination, the process is killed. +func (p *Process) RunWithinContext(ctx context.Context) error { + if err := p.Start(); err != nil { + return err + } + completed := make(chan struct{}) + defer close(completed) + go func() { + select { + case <-ctx.Done(): + p.Kill() + case <-completed: + } + }() + return p.Wait() +} + +// RunAndCaptureOutput starts the specified command and waits for it to complete. If the given context +// is canceled before the normal process termination, the process is killed. The standard output and +// standard error of the process are captured and returned at process termination. +func (p *Process) RunAndCaptureOutput(ctx context.Context) ([]byte, []byte, error) { + stdout := &bytes.Buffer{} + stderr := &bytes.Buffer{} + p.RedirectStdoutTo(stdout) + p.RedirectStderrTo(stderr) + err := p.RunWithinContext(ctx) + return stdout.Bytes(), stderr.Bytes(), err +} + +// GetArgs returns the command arguments +func (p *Process) GetArgs() []string { + return p.cmd.Args +} + +// nullReaderInstance is an io.Reader that will always return EOF +var nullReaderInstance = &nullReader{} + +type nullReader struct{} + +func (r *nullReader) Read(buff []byte) (int, error) { + return 0, io.EOF +} diff --git a/pkg/paths/process_others.go b/pkg/paths/process_others.go new file mode 100644 index 00000000..39bd3e16 --- /dev/null +++ b/pkg/paths/process_others.go @@ -0,0 +1,38 @@ +// +// This file is part of PathsHelper library. +// +// Copyright 2023 Arduino AG (http://www.arduino.cc/) +// +// PathsHelper library 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 2 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, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// As a special exception, you may use this file as part of a free software +// library without restriction. Specifically, if other files instantiate +// templates or use macros or inline functions from this file, or you compile +// this file and link it with other files to produce an executable, this +// file does not by itself cause the resulting executable to be covered by +// the GNU General Public License. This exception does not however +// invalidate any other reasons why the executable file might be covered by +// the GNU General Public License. +// + +//go:build !windows + +package paths + +import "os/exec" + +func tellCommandNotToSpawnShell(_ *exec.Cmd) { + // no op +} diff --git a/pkg/paths/process_test.go b/pkg/paths/process_test.go new file mode 100644 index 00000000..5346dda0 --- /dev/null +++ b/pkg/paths/process_test.go @@ -0,0 +1,56 @@ +// +// This file is part of PathsHelper library. +// +// Copyright 2023 Arduino AG (http://www.arduino.cc/) +// +// PathsHelper library 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 2 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, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// As a special exception, you may use this file as part of a free software +// library without restriction. Specifically, if other files instantiate +// templates or use macros or inline functions from this file, or you compile +// this file and link it with other files to produce an executable, this +// file does not by itself cause the resulting executable to be covered by +// the GNU General Public License. This exception does not however +// invalidate any other reasons why the executable file might be covered by +// the GNU General Public License. +// + +package paths + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestProcessWithinContext(t *testing.T) { + // Build `delay` helper inside testdata/delay + builder, err := NewProcess(nil, "go", "build") + require.NoError(t, err) + builder.SetDir("testdata/delay") + require.NoError(t, builder.Run()) + + // Run delay and test if the process is terminated correctly due to context + process, err := NewProcess(nil, "testdata/delay/delay") + require.NoError(t, err) + start := time.Now() + ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond) + err = process.RunWithinContext(ctx) + require.Error(t, err) + require.Less(t, time.Since(start), 500*time.Millisecond) + cancel() +} diff --git a/pkg/paths/readdir.go b/pkg/paths/readdir.go new file mode 100644 index 00000000..985fed54 --- /dev/null +++ b/pkg/paths/readdir.go @@ -0,0 +1,257 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2018-2022 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package paths + +import ( + "errors" + "os" + "strings" +) + +// ReadDirFilter is a filter for Path.ReadDir and Path.ReadDirRecursive methods. +// The filter should return true to accept a file or false to reject it. +type ReadDirFilter func(file *Path) bool + +// ReadDir returns a PathList containing the content of the directory +// pointed by the current Path. The resulting list is filtered by the given filters chained. +func (p *Path) ReadDir(filters ...ReadDirFilter) (PathList, error) { + infos, err := os.ReadDir(p.path) + if err != nil { + return nil, err + } + + accept := func(p *Path) bool { + for _, filter := range filters { + if !filter(p) { + return false + } + } + return true + } + + paths := PathList{} + for _, info := range infos { + path := p.Join(info.Name()) + if !accept(path) { + continue + } + paths.Add(path) + } + return paths, nil +} + +// ReadDirRecursive returns a PathList containing the content of the directory +// and its subdirectories pointed by the current Path +func (p *Path) ReadDirRecursive() (PathList, error) { + return p.ReadDirRecursiveFiltered(nil) +} + +// ReadDirRecursiveFiltered returns a PathList containing the content of the directory +// and its subdirectories pointed by the current Path, filtered by the given skipFilter +// and filters: +// - `recursionFilter` is a filter that is checked to determine if the subdirectory must +// by visited recursively (if the filter rejects the entry, the entry is not visited +// but can still be added to the result) +// - `filters` are the filters that are checked to determine if the entry should be +// added to the resulting PathList +func (p *Path) ReadDirRecursiveFiltered(recursionFilter ReadDirFilter, filters ...ReadDirFilter) (PathList, error) { + var search func(*Path) (PathList, error) + + explored := map[string]bool{} + search = func(currPath *Path) (PathList, error) { + canonical := currPath.Canonical().path + if explored[canonical] { + return nil, errors.New("directories symlink loop detected") + } + explored[canonical] = true + defer delete(explored, canonical) + + infos, err := os.ReadDir(currPath.path) + if err != nil { + return nil, err + } + + accept := func(p *Path) bool { + for _, filter := range filters { + if !filter(p) { + return false + } + } + return true + } + + paths := PathList{} + for _, info := range infos { + path := currPath.Join(info.Name()) + + if accept(path) { + paths.Add(path) + } + + if recursionFilter == nil || recursionFilter(path) { + if path.IsDir() { + subPaths, err := search(path) + if err != nil { + return nil, err + } + paths.AddAll(subPaths) + } + } + } + return paths, nil + } + + return search(p) +} + +// FilterDirectories is a ReadDirFilter that accepts only directories +func FilterDirectories() ReadDirFilter { + return func(path *Path) bool { + return path.IsDir() + } +} + +// FilterOutDirectories is a ReadDirFilter that rejects all directories +func FilterOutDirectories() ReadDirFilter { + return func(path *Path) bool { + return !path.IsDir() + } +} + +// FilterNames is a ReadDirFilter that accepts only the given filenames +func FilterNames(allowedNames ...string) ReadDirFilter { + return func(file *Path) bool { + for _, name := range allowedNames { + if file.Base() == name { + return true + } + } + return false + } +} + +// FilterOutNames is a ReadDirFilter that rejects the given filenames +func FilterOutNames(rejectedNames ...string) ReadDirFilter { + return func(file *Path) bool { + for _, name := range rejectedNames { + if file.Base() == name { + return false + } + } + return true + } +} + +// FilterSuffixes creates a ReadDirFilter that accepts only the given +// filename suffixes +func FilterSuffixes(allowedSuffixes ...string) ReadDirFilter { + return func(file *Path) bool { + for _, suffix := range allowedSuffixes { + if strings.HasSuffix(file.String(), suffix) { + return true + } + } + return false + } +} + +// FilterOutSuffixes creates a ReadDirFilter that rejects all the given +// filename suffixes +func FilterOutSuffixes(rejectedSuffixes ...string) ReadDirFilter { + return func(file *Path) bool { + for _, suffix := range rejectedSuffixes { + if strings.HasSuffix(file.String(), suffix) { + return false + } + } + return true + } +} + +// FilterPrefixes creates a ReadDirFilter that accepts only the given +// filename prefixes +func FilterPrefixes(allowedPrefixes ...string) ReadDirFilter { + return func(file *Path) bool { + name := file.Base() + for _, prefix := range allowedPrefixes { + if strings.HasPrefix(name, prefix) { + return true + } + } + return false + } +} + +// FilterOutPrefixes creates a ReadDirFilter that rejects all the given +// filename prefixes +func FilterOutPrefixes(rejectedPrefixes ...string) ReadDirFilter { + return func(file *Path) bool { + name := file.Base() + for _, prefix := range rejectedPrefixes { + if strings.HasPrefix(name, prefix) { + return false + } + } + return true + } +} + +// OrFilter creates a ReadDirFilter that accepts all items that are accepted +// by any (at least one) of the given filters +func OrFilter(filters ...ReadDirFilter) ReadDirFilter { + return func(path *Path) bool { + for _, f := range filters { + if f(path) { + return true + } + } + return false + } +} + +// AndFilter creates a ReadDirFilter that accepts all items that are accepted +// by all the given filters +func AndFilter(filters ...ReadDirFilter) ReadDirFilter { + return func(path *Path) bool { + for _, f := range filters { + if !f(path) { + return false + } + } + return true + } +} + +// NotFilter creates a ReadDifFilter that accepts all items rejected by x and viceversa +func NotFilter(x ReadDirFilter) ReadDirFilter { + return func(path *Path) bool { + return !x(path) + } +} diff --git a/pkg/paths/readdir_test.go b/pkg/paths/readdir_test.go new file mode 100644 index 00000000..ae25ede9 --- /dev/null +++ b/pkg/paths/readdir_test.go @@ -0,0 +1,343 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2018-2022 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package paths + +import ( + "fmt" + "io/fs" + "os" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestReadDirRecursive(t *testing.T) { + testPath := New("testdata", "fileset") + + list, err := testPath.ReadDirRecursive() + require.NoError(t, err) + require.Len(t, list, 16) + + pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) + pathEqualsTo(t, "testdata/fileset/file", list[1]) + pathEqualsTo(t, "testdata/fileset/folder", list[2]) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[3]) + pathEqualsTo(t, "testdata/fileset/folder/file2", list[4]) + pathEqualsTo(t, "testdata/fileset/folder/file3", list[5]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[6]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder/file4", list[7]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[8]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", list[9]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", list[10]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", list[11]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", list[12]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", list[13]) + pathEqualsTo(t, "testdata/fileset/test.txt", list[14]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[15]) +} + +func TestReadDirRecursiveSymLinkLoop(t *testing.T) { + // Test symlink loop + tmp, err := MkTempDir("", "") + require.NoError(t, err) + defer tmp.RemoveAll() + + folder := tmp.Join("folder") + err = os.Symlink(tmp.String(), folder.String()) + require.NoError(t, err) + + l, err := tmp.ReadDirRecursive() + require.Error(t, err) + fmt.Println(err) + require.Nil(t, l) + + l, err = tmp.ReadDirRecursiveFiltered(nil) + require.Error(t, err) + fmt.Println(err) + require.Nil(t, l) +} + +func TestReadDirFiltered(t *testing.T) { + folderPath := New("testdata/fileset/folder") + list, err := folderPath.ReadDir() + require.NoError(t, err) + require.Len(t, list, 4) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[0]) + pathEqualsTo(t, "testdata/fileset/folder/file2", list[1]) + pathEqualsTo(t, "testdata/fileset/folder/file3", list[2]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[3]) + + list, err = folderPath.ReadDir(FilterDirectories()) + require.NoError(t, err) + require.Len(t, list, 1) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[0]) + + list, err = folderPath.ReadDir(FilterOutPrefixes("file")) + require.NoError(t, err) + require.Len(t, list, 2) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[0]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[1]) +} + +func TestReadDirRecursiveFiltered(t *testing.T) { + testdata := New("testdata", "fileset") + l, err := testdata.ReadDirRecursiveFiltered(nil) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 16) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/file", l[1]) + pathEqualsTo(t, "testdata/fileset/folder", l[2]) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[3]) + pathEqualsTo(t, "testdata/fileset/folder/file2", l[4]) + pathEqualsTo(t, "testdata/fileset/folder/file3", l[5]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[6]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder/file4", l[7]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[8]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[9]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[10]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[11]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[12]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", l[13]) + pathEqualsTo(t, "testdata/fileset/test.txt", l[14]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[15]) + + l, err = testdata.ReadDirRecursiveFiltered(FilterOutDirectories()) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 6) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/file", l[1]) + pathEqualsTo(t, "testdata/fileset/folder", l[2]) // <- this is listed but not traversed + pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[3]) // <- this is listed but not traversed + pathEqualsTo(t, "testdata/fileset/test.txt", l[4]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[5]) + + l, err = testdata.ReadDirRecursiveFiltered(nil, FilterOutDirectories()) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 12) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/file", l[1]) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[2]) + pathEqualsTo(t, "testdata/fileset/folder/file2", l[3]) + pathEqualsTo(t, "testdata/fileset/folder/file3", l[4]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder/file4", l[5]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[6]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[7]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[8]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", l[9]) + pathEqualsTo(t, "testdata/fileset/test.txt", l[10]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[11]) + + l, err = testdata.ReadDirRecursiveFiltered(FilterOutDirectories(), FilterOutDirectories()) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 4) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/file", l[1]) + pathEqualsTo(t, "testdata/fileset/test.txt", l[2]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[3]) + + l, err = testdata.ReadDirRecursiveFiltered(FilterOutPrefixes("sub"), FilterOutSuffixes("3")) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 12) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/file", l[1]) + pathEqualsTo(t, "testdata/fileset/folder", l[2]) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[3]) + pathEqualsTo(t, "testdata/fileset/folder/file2", l[4]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[5]) // <- subfolder skipped by Prefix("sub") + pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[6]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[7]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[8]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[9]) // <- subfolder skipped by Prefix("sub") + pathEqualsTo(t, "testdata/fileset/test.txt", l[10]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[11]) + + l, err = testdata.ReadDirRecursiveFiltered(FilterOutPrefixes("sub"), AndFilter(FilterOutSuffixes("3"), FilterOutPrefixes("fil"))) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 9) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/folder", l[1]) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[2]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[3]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[4]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[5]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[6]) + pathEqualsTo(t, "testdata/fileset/test.txt", l[7]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[8]) + + l, err = testdata.ReadDirRecursiveFiltered(FilterOutPrefixes("sub"), AndFilter(FilterOutSuffixes("3"), FilterOutPrefixes("fil"), FilterOutSuffixes(".gz"))) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 8) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/folder", l[1]) + pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[2]) + pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[3]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[4]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[5]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[6]) + pathEqualsTo(t, "testdata/fileset/test.txt", l[7]) + + l, err = testdata.ReadDirRecursiveFiltered(OrFilter(FilterPrefixes("sub"), FilterSuffixes("tofolder"))) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 11) + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/file", l[1]) + pathEqualsTo(t, "testdata/fileset/folder", l[2]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[3]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[4]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[5]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[6]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[7]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", l[8]) + pathEqualsTo(t, "testdata/fileset/test.txt", l[9]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[10]) + + l, err = testdata.ReadDirRecursiveFiltered(nil, FilterNames("folder")) + require.NoError(t, err) + l.Sort() + require.Len(t, l, 1) + pathEqualsTo(t, "testdata/fileset/folder", l[0]) + + l, err = testdata.ReadDirRecursiveFiltered(FilterNames("symlinktofolder"), FilterOutNames(".hidden")) + require.NoError(t, err) + require.Len(t, l, 9) + l.Sort() + pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) + pathEqualsTo(t, "testdata/fileset/file", l[1]) + pathEqualsTo(t, "testdata/fileset/folder", l[2]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[3]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[4]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[5]) + pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[6]) + pathEqualsTo(t, "testdata/fileset/test.txt", l[7]) + pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[8]) +} + +func TestReadDirRecursiveLoopDetection(t *testing.T) { + loopsPath := New("testdata", "loops") + unbuondedReaddir := func(testdir string) (PathList, error) { + var files PathList + var err error + done := make(chan bool) + go func() { + files, err = loopsPath.Join(testdir).ReadDirRecursive() + done <- true + }() + require.Eventually( + t, + func() bool { + select { + case <-done: + return true + default: + return false + } + }, + 5*time.Second, + 10*time.Millisecond, + "Infinite symlink loop while loading sketch", + ) + return files, err + } + + for _, dir := range []string{"loop_1", "loop_2", "loop_3", "loop_4"} { + l, err := unbuondedReaddir(dir) + require.EqualError(t, err, "directories symlink loop detected", "loop not detected in %s", dir) + require.Nil(t, l) + } + + { + l, err := unbuondedReaddir("regular_1") + require.NoError(t, err) + require.Len(t, l, 4) + l.Sort() + pathEqualsTo(t, "testdata/loops/regular_1/dir1", l[0]) + pathEqualsTo(t, "testdata/loops/regular_1/dir1/file1", l[1]) + pathEqualsTo(t, "testdata/loops/regular_1/dir2", l[2]) + pathEqualsTo(t, "testdata/loops/regular_1/dir2/file1", l[3]) + } + + { + l, err := unbuondedReaddir("regular_2") + require.NoError(t, err) + require.Len(t, l, 6) + l.Sort() + pathEqualsTo(t, "testdata/loops/regular_2/dir1", l[0]) + pathEqualsTo(t, "testdata/loops/regular_2/dir1/file1", l[1]) + pathEqualsTo(t, "testdata/loops/regular_2/dir2", l[2]) + pathEqualsTo(t, "testdata/loops/regular_2/dir2/dir1", l[3]) + pathEqualsTo(t, "testdata/loops/regular_2/dir2/dir1/file1", l[4]) + pathEqualsTo(t, "testdata/loops/regular_2/dir2/file2", l[5]) + } + + { + l, err := unbuondedReaddir("regular_3") + require.NoError(t, err) + require.Len(t, l, 7) + l.Sort() + pathEqualsTo(t, "testdata/loops/regular_3/dir1", l[0]) + pathEqualsTo(t, "testdata/loops/regular_3/dir1/file1", l[1]) + pathEqualsTo(t, "testdata/loops/regular_3/dir2", l[2]) + pathEqualsTo(t, "testdata/loops/regular_3/dir2/dir1", l[3]) + pathEqualsTo(t, "testdata/loops/regular_3/dir2/dir1/file1", l[4]) + pathEqualsTo(t, "testdata/loops/regular_3/dir2/file2", l[5]) + pathEqualsTo(t, "testdata/loops/regular_3/link", l[6]) // broken symlink is reported in files + } + + if runtime.GOOS != "windows" { + dir1 := loopsPath.Join("regular_4_with_permission_error", "dir1") + + l, err := unbuondedReaddir("regular_4_with_permission_error") + require.NoError(t, err) + require.NotEmpty(t, l) + + dir1Stat, err := dir1.Stat() + require.NoError(t, err) + err = dir1.Chmod(fs.FileMode(0)) // Enforce permission error + require.NoError(t, err) + t.Cleanup(func() { + // Restore normal permission after the test + dir1.Chmod(dir1Stat.Mode()) + }) + + l, err = unbuondedReaddir("regular_4_with_permission_error") + require.Error(t, err) + require.Nil(t, l) + } +} diff --git a/pkg/paths/testdata/broken_symlink/dir_1/broken_link b/pkg/paths/testdata/broken_symlink/dir_1/broken_link new file mode 120000 index 00000000..86a410dd --- /dev/null +++ b/pkg/paths/testdata/broken_symlink/dir_1/broken_link @@ -0,0 +1 @@ +broken \ No newline at end of file diff --git a/pkg/paths/testdata/broken_symlink/dir_1/file2 b/pkg/paths/testdata/broken_symlink/dir_1/file2 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/broken_symlink/dir_1/linked_dir b/pkg/paths/testdata/broken_symlink/dir_1/linked_dir new file mode 120000 index 00000000..4b019049 --- /dev/null +++ b/pkg/paths/testdata/broken_symlink/dir_1/linked_dir @@ -0,0 +1 @@ +real_dir \ No newline at end of file diff --git a/pkg/paths/testdata/broken_symlink/dir_1/linked_file b/pkg/paths/testdata/broken_symlink/dir_1/linked_file new file mode 120000 index 00000000..30d67d46 --- /dev/null +++ b/pkg/paths/testdata/broken_symlink/dir_1/linked_file @@ -0,0 +1 @@ +file2 \ No newline at end of file diff --git a/pkg/paths/testdata/broken_symlink/dir_1/real_dir/file1 b/pkg/paths/testdata/broken_symlink/dir_1/real_dir/file1 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/delay/.gitignore b/pkg/paths/testdata/delay/.gitignore new file mode 100644 index 00000000..fd5812a4 --- /dev/null +++ b/pkg/paths/testdata/delay/.gitignore @@ -0,0 +1 @@ +delay* diff --git a/pkg/paths/testdata/delay/main.go b/pkg/paths/testdata/delay/main.go new file mode 100644 index 00000000..fa6030c4 --- /dev/null +++ b/pkg/paths/testdata/delay/main.go @@ -0,0 +1,40 @@ +/* + * This file is part of PathsHelper library. + * + * Copyright 2023 Arduino AG (http://www.arduino.cc/) + * + * PathsHelper library 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + */ + +package main + +import ( + "fmt" + "time" +) + +func main() { + time.Sleep(3 * time.Second) + fmt.Println("Elapsed!") +} diff --git a/pkg/paths/testdata/fileset/anotherFile b/pkg/paths/testdata/fileset/anotherFile new file mode 100644 index 00000000..27649646 --- /dev/null +++ b/pkg/paths/testdata/fileset/anotherFile @@ -0,0 +1,4 @@ +line 1 +line 2 + +line 3 \ No newline at end of file diff --git a/pkg/paths/testdata/fileset/file b/pkg/paths/testdata/fileset/file new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/fileset/folder/.hidden b/pkg/paths/testdata/fileset/folder/.hidden new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/fileset/folder/file2 b/pkg/paths/testdata/fileset/folder/file2 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/fileset/folder/file3 b/pkg/paths/testdata/fileset/folder/file3 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/fileset/folder/subfolder/file4 b/pkg/paths/testdata/fileset/folder/subfolder/file4 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/fileset/symlinktofolder b/pkg/paths/testdata/fileset/symlinktofolder new file mode 120000 index 00000000..01196353 --- /dev/null +++ b/pkg/paths/testdata/fileset/symlinktofolder @@ -0,0 +1 @@ +folder \ No newline at end of file diff --git a/pkg/paths/testdata/fileset/test.txt b/pkg/paths/testdata/fileset/test.txt new file mode 100644 index 00000000..d3ded994 --- /dev/null +++ b/pkg/paths/testdata/fileset/test.txt @@ -0,0 +1,20 @@ +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. + diff --git a/pkg/paths/testdata/fileset/test.txt.gz b/pkg/paths/testdata/fileset/test.txt.gz new file mode 100644 index 00000000..e75120ae Binary files /dev/null and b/pkg/paths/testdata/fileset/test.txt.gz differ diff --git a/pkg/paths/testdata/loops/loop_1/dir1/loop b/pkg/paths/testdata/loops/loop_1/dir1/loop new file mode 120000 index 00000000..c9f3ab1e --- /dev/null +++ b/pkg/paths/testdata/loops/loop_1/dir1/loop @@ -0,0 +1 @@ +../dir1 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/loop_2/dir1/loop2 b/pkg/paths/testdata/loops/loop_2/dir1/loop2 new file mode 120000 index 00000000..d014eb49 --- /dev/null +++ b/pkg/paths/testdata/loops/loop_2/dir1/loop2 @@ -0,0 +1 @@ +../dir2 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/loop_2/dir2/loop1 b/pkg/paths/testdata/loops/loop_2/dir2/loop1 new file mode 120000 index 00000000..c9f3ab1e --- /dev/null +++ b/pkg/paths/testdata/loops/loop_2/dir2/loop1 @@ -0,0 +1 @@ +../dir1 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/loop_3/dir1/loop2 b/pkg/paths/testdata/loops/loop_3/dir1/loop2 new file mode 120000 index 00000000..d014eb49 --- /dev/null +++ b/pkg/paths/testdata/loops/loop_3/dir1/loop2 @@ -0,0 +1 @@ +../dir2 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/loop_3/dir2/dir3/loop2 b/pkg/paths/testdata/loops/loop_3/dir2/dir3/loop2 new file mode 120000 index 00000000..85babfdb --- /dev/null +++ b/pkg/paths/testdata/loops/loop_3/dir2/dir3/loop2 @@ -0,0 +1 @@ +../../dir1/ \ No newline at end of file diff --git a/pkg/paths/testdata/loops/loop_4/dir1/dir2/loop2 b/pkg/paths/testdata/loops/loop_4/dir1/dir2/loop2 new file mode 120000 index 00000000..3fd50ca4 --- /dev/null +++ b/pkg/paths/testdata/loops/loop_4/dir1/dir2/loop2 @@ -0,0 +1 @@ +../dir3 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/loop_4/dir1/dir3/dir4/loop1 b/pkg/paths/testdata/loops/loop_4/dir1/dir3/dir4/loop1 new file mode 120000 index 00000000..4f388a66 --- /dev/null +++ b/pkg/paths/testdata/loops/loop_4/dir1/dir3/dir4/loop1 @@ -0,0 +1 @@ +../../../dir1 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/regular_1/dir1/file1 b/pkg/paths/testdata/loops/regular_1/dir1/file1 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/loops/regular_1/dir2 b/pkg/paths/testdata/loops/regular_1/dir2 new file mode 120000 index 00000000..df490f83 --- /dev/null +++ b/pkg/paths/testdata/loops/regular_1/dir2 @@ -0,0 +1 @@ +dir1 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/regular_2/dir1/file1 b/pkg/paths/testdata/loops/regular_2/dir1/file1 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/loops/regular_2/dir2/dir1 b/pkg/paths/testdata/loops/regular_2/dir2/dir1 new file mode 120000 index 00000000..c9f3ab1e --- /dev/null +++ b/pkg/paths/testdata/loops/regular_2/dir2/dir1 @@ -0,0 +1 @@ +../dir1 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/regular_2/dir2/file2 b/pkg/paths/testdata/loops/regular_2/dir2/file2 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/loops/regular_3/dir1/file1 b/pkg/paths/testdata/loops/regular_3/dir1/file1 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/loops/regular_3/dir2/dir1 b/pkg/paths/testdata/loops/regular_3/dir2/dir1 new file mode 120000 index 00000000..c9f3ab1e --- /dev/null +++ b/pkg/paths/testdata/loops/regular_3/dir2/dir1 @@ -0,0 +1 @@ +../dir1 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/regular_3/dir2/file2 b/pkg/paths/testdata/loops/regular_3/dir2/file2 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/loops/regular_3/link b/pkg/paths/testdata/loops/regular_3/link new file mode 120000 index 00000000..86a410dd --- /dev/null +++ b/pkg/paths/testdata/loops/regular_3/link @@ -0,0 +1 @@ +broken \ No newline at end of file diff --git a/pkg/paths/testdata/loops/regular_4_with_permission_error/dir1/file1 b/pkg/paths/testdata/loops/regular_4_with_permission_error/dir1/file1 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/loops/regular_4_with_permission_error/dir2/dir1 b/pkg/paths/testdata/loops/regular_4_with_permission_error/dir2/dir1 new file mode 120000 index 00000000..c9f3ab1e --- /dev/null +++ b/pkg/paths/testdata/loops/regular_4_with_permission_error/dir2/dir1 @@ -0,0 +1 @@ +../dir1 \ No newline at end of file diff --git a/pkg/paths/testdata/loops/regular_4_with_permission_error/dir2/file2 b/pkg/paths/testdata/loops/regular_4_with_permission_error/dir2/file2 new file mode 100644 index 00000000..e69de29b diff --git a/pkg/paths/testdata/loops/regular_4_with_permission_error/link b/pkg/paths/testdata/loops/regular_4_with_permission_error/link new file mode 120000 index 00000000..86a410dd --- /dev/null +++ b/pkg/paths/testdata/loops/regular_4_with_permission_error/link @@ -0,0 +1 @@ +broken \ No newline at end of file