paths

package module
v1.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2024 License: GPL-2.0 Imports: 17 Imported by: 133

README

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:

buildPath := getPathFromSomewhere() // returns string
if buildPath != "" {
	cachePath, err := filepath.Abs(filepath.Join(buildPath, "cache"))
	...
}

can be transformed to:

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:

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:

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 and report the bug to our Security Team 🛡️ Thank you!

e-mail contact: security@arduino.cc

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GUnzip added in v1.6.0

func GUnzip(src, dest *Path) error

GUnzip decompress src with gzip and writes the uncompressed file on dst

func MkTempFile

func MkTempFile(dir *Path, prefix string) (*os.File, error)

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.

Types

type Path

type Path struct {
	// contains filtered or unexported fields
}

Path represents a path

func Getwd

func Getwd() (*Path, error)

Getwd returns a rooted path name corresponding to the current directory.

func MkTempDir

func MkTempDir(dir, prefix string) (*Path, error)

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 New

func New(path ...string) *Path

New creates a new Path object. If path is the empty string then nil is returned.

func NewFromFile

func NewFromFile(file *os.File) *Path

NewFromFile creates a new Path object using the path name obtained from the File object (see os.File.Name function).

func NullPath

func NullPath() *Path

NullPath return the path to the /dev/null equivalent for the current OS

func TempDir

func TempDir() *Path

TempDir returns the default path to use for temporary files

func WriteToTempFile added in v1.4.0

func WriteToTempFile(data []byte, dir *Path, prefix string) (res *Path, err error)

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 (*Path) Abs

func (p *Path) Abs() (*Path, error)

Abs returns the absolute path of the current Path

func (*Path) Append added in v1.3.3

func (p *Path) Append() (*os.File, error)

Append opens a file for append or creates it if the file doesn't exist.

func (*Path) Base

func (p *Path) Base() string

Base returns the last element of path

func (*Path) Canonical added in v1.5.0

func (p *Path) Canonical() *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 (*Path) Chmod added in v1.12.0

func (p *Path) Chmod(mode fs.FileMode) error

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 (*Path) Chtimes

func (p *Path) Chtimes(atime, mtime time.Time) error

Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions.

func (*Path) Clean

func (p *Path) Clean() *Path

Clean Clean returns the shortest path name equivalent to path by purely lexical processing

func (*Path) Clone

func (p *Path) Clone() *Path

Clone create a copy of the Path object

func (*Path) CopyDirTo

func (p *Path) CopyDirTo(dst *Path) error

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 (*Path) CopyTo

func (p *Path) CopyTo(dst *Path) error

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 (*Path) Create added in v1.2.0

func (p *Path) Create() (*os.File, error)

Create creates or truncates a file. It calls os.Create on the underlying path.

func (*Path) EqualsTo

func (p *Path) EqualsTo(other *Path) bool

EqualsTo return true if both paths are equal

func (*Path) EquivalentTo

func (p *Path) EquivalentTo(other *Path) bool

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 (*Path) Exist

func (p *Path) Exist() bool

Exist return true if the file denoted by this path exists, false in any other case (also in case of error).

func (*Path) ExistCheck

func (p *Path) ExistCheck() (bool, error)

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 (*Path) Ext

func (p *Path) Ext() string

Ext returns the file name extension used by path

func (p *Path) FollowSymLink() error

FollowSymLink transforms the current path to the path pointed by the symlink if path is a symlink, otherwise it does nothing

func (*Path) HasPrefix

func (p *Path) HasPrefix(prefixes ...string) bool

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 (*Path) HasSuffix

func (p *Path) HasSuffix(suffixies ...string) bool

HasSuffix returns true if the file name has one of the given suffixies

func (*Path) IsAbs

func (p *Path) IsAbs() bool

IsAbs returns true if the Path is absolute

func (*Path) IsDir

func (p *Path) IsDir() bool

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 (*Path) IsDirCheck

func (p *Path) IsDirCheck() (bool, error)

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 (*Path) IsInsideDir

func (p *Path) IsInsideDir(dir *Path) (bool, error)

IsInsideDir returns true if the current path is inside the provided dir

func (*Path) IsNotDir

func (p *Path) IsNotDir() bool

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 (*Path) Join

func (p *Path) Join(paths ...string) *Path

Join create a new Path by joining the provided paths

func (*Path) JoinPath

func (p *Path) JoinPath(paths ...*Path) *Path

JoinPath create a new Path by joining the provided paths

func (*Path) Lstat added in v1.12.0

func (p *Path) Lstat() (fs.FileInfo, error)

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 (*Path) MarshalJSON

func (p *Path) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (*Path) MkTempDir

func (p *Path) MkTempDir(prefix string) (*Path, error)

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 (*Path) Mkdir

func (p *Path) Mkdir() error

Mkdir create a directory denoted by the current path

func (*Path) MkdirAll

func (p *Path) MkdirAll() error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error

func (*Path) NotExist

func (p *Path) NotExist() bool

NotExist return true if the file denoted by this path DO NOT exists, false in any other case (also in case of error).

func (*Path) Open added in v1.1.0

func (p *Path) Open() (*os.File, error)

Open opens a file for reading. It calls os.Open on the underlying path.

func (*Path) Parent

func (p *Path) Parent() *Path

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 (*Path) Parents

func (p *Path) Parents() []*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 (*Path) ReadDir

func (p *Path) ReadDir(filters ...ReadDirFilter) (PathList, error)

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 (*Path) ReadDirRecursive added in v1.3.0

func (p *Path) ReadDirRecursive() (PathList, error)

ReadDirRecursive returns a PathList containing the content of the directory and its subdirectories pointed by the current Path

func (*Path) ReadDirRecursiveFiltered added in v1.7.0

func (p *Path) ReadDirRecursiveFiltered(recursionFilter ReadDirFilter, filters ...ReadDirFilter) (PathList, error)

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 (*Path) ReadFile

func (p *Path) ReadFile() ([]byte, error)

ReadFile reads the file named by filename and returns the contents

func (*Path) ReadFileAsLines

func (p *Path) ReadFileAsLines() ([]string, error)

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 (*Path) RelFrom added in v1.4.0

func (p *Path) RelFrom(r *Path) (*Path, error)

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 (*Path) RelTo

func (p *Path) RelTo(r *Path) (*Path, error)

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 (*Path) Remove

func (p *Path) Remove() error

Remove removes the named file or directory

func (*Path) RemoveAll

func (p *Path) RemoveAll() error

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 (*Path) Rename

func (p *Path) Rename(newpath *Path) error

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 (*Path) Stat

func (p *Path) Stat() (fs.FileInfo, error)

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 (*Path) String

func (p *Path) String() string

func (*Path) ToAbs

func (p *Path) ToAbs() error

ToAbs transofrm the current Path to the corresponding absolute path

func (*Path) Truncate

func (p *Path) Truncate() error

Truncate create an empty file named by path or if the file already exist it truncates it (delete all contents)

func (*Path) UnmarshalJSON

func (p *Path) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

func (*Path) WriteFile

func (p *Path) WriteFile(data []byte) error

WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it otherwise WriteFile truncates it before writing.

type PathList

type PathList []*Path

PathList is a list of Path

func NewPathList

func NewPathList(paths ...string) PathList

NewPathList creates a new PathList with the given paths

func (*PathList) Add

func (p *PathList) Add(path *Path)

Add adds a Path to the PathList

func (*PathList) AddAll

func (p *PathList) AddAll(paths PathList)

AddAll adds all Paths in the list passed as argument

func (*PathList) AddAllMissing

func (p *PathList) AddAllMissing(pathsToAdd PathList)

AddAllMissing adds all paths to the PathList excluding the paths already in the list

func (*PathList) AddIfMissing

func (p *PathList) AddIfMissing(path *Path)

AddIfMissing adds a Path to the PathList if the path is not already in the list

func (*PathList) AsStrings

func (p *PathList) AsStrings() []string

AsStrings return this path list as a string array

func (*PathList) Clone

func (p *PathList) Clone() PathList

Clone returns a copy of the current PathList

func (*PathList) Contains

func (p *PathList) Contains(pathToSearch *Path) bool

Contains check if the list contains a path that match exactly (EqualsTo) to the specified path

func (*PathList) ContainsEquivalentTo

func (p *PathList) ContainsEquivalentTo(pathToSearch *Path) bool

ContainsEquivalentTo check if the list contains a path that is equivalent (EquivalentTo) to the specified path

func (*PathList) Filter added in v1.11.0

func (p *PathList) Filter(acceptorFunc func(*Path) bool)

Filter will remove all the elements of the list that do not match the specified acceptor function

func (*PathList) FilterDirs

func (p *PathList) FilterDirs()

FilterDirs remove all entries except directories

func (*PathList) FilterOutDirs

func (p *PathList) FilterOutDirs()

FilterOutDirs remove all directories entries

func (*PathList) FilterOutHiddenFiles

func (p *PathList) FilterOutHiddenFiles()

FilterOutHiddenFiles remove all hidden files (files with the name starting with ".")

func (*PathList) FilterOutPrefix

func (p *PathList) FilterOutPrefix(prefixes ...string)

FilterOutPrefix remove all entries having one of the specified prefixes

func (*PathList) FilterOutSuffix

func (p *PathList) FilterOutSuffix(suffixies ...string)

FilterOutSuffix remove all entries having one of the specified suffixes

func (*PathList) FilterPrefix

func (p *PathList) FilterPrefix(prefixes ...string)

FilterPrefix remove all entries not having one of the specified prefixes

func (*PathList) FilterSuffix

func (p *PathList) FilterSuffix(suffixies ...string)

FilterSuffix remove all entries not having one of the specified suffixes

func (*PathList) Len

func (p *PathList) Len() int

func (*PathList) Less

func (p *PathList) Less(i, j int) bool

func (*PathList) Sort

func (p *PathList) Sort()

Sort sorts this pathlist

func (*PathList) Swap

func (p *PathList) Swap(i, j int)

func (*PathList) ToAbs

func (p *PathList) ToAbs() error

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.

type Process added in v1.10.0

type Process struct {
	// contains filtered or unexported fields
}

Process is representation of an external process run

func NewProcess added in v1.10.0

func NewProcess(extraEnv []string, args ...string) (*Process, error)

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 NewProcessFromPath added in v1.10.0

func NewProcessFromPath(extraEnv []string, executable *Path, args ...string) (*Process, error)

NewProcessFromPath creates a command from the provided executable path, additional environment vars (in addition to the system default ones) and command line arguments.

func (*Process) GetArgs added in v1.10.0

func (p *Process) GetArgs() []string

GetArgs returns the command arguments

func (*Process) GetDir added in v1.10.0

func (p *Process) GetDir() string

GetDir gets the working directory of the command.

func (*Process) Kill added in v1.10.0

func (p *Process) Kill() error

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 (*Process) RedirectStderrTo added in v1.10.0

func (p *Process) RedirectStderrTo(out io.Writer)

RedirectStderrTo will redirect the process' stdout to the specified writer. Any previous redirection will be overwritten.

func (*Process) RedirectStdoutTo added in v1.10.0

func (p *Process) RedirectStdoutTo(out io.Writer)

RedirectStdoutTo will redirect the process' stdout to the specified writer. Any previous redirection will be overwritten.

func (*Process) Run added in v1.10.0

func (p *Process) Run() error

Run starts the specified command and waits for it to complete.

func (*Process) RunAndCaptureOutput added in v1.10.0

func (p *Process) RunAndCaptureOutput(ctx context.Context) ([]byte, []byte, error)

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 (*Process) RunWithinContext added in v1.10.0

func (p *Process) RunWithinContext(ctx context.Context) error

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 (*Process) SetDir added in v1.10.0

func (p *Process) SetDir(dir string)

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 (*Process) SetDirFromPath added in v1.10.0

func (p *Process) SetDirFromPath(path *Path)

SetDirFromPath sets the working directory of the command. If path is nil, Run runs the command in the calling process's current directory.

func (*Process) SetEnvironment added in v1.10.0

func (p *Process) SetEnvironment(values []string)

SetEnvironment set the environment for the running process. Each entry is of the form "key=value". System default environments will be wiped out.

func (*Process) Signal added in v1.10.0

func (p *Process) Signal(sig os.Signal) error

Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented.

func (*Process) Start added in v1.10.0

func (p *Process) Start() error

Start will start the underliyng process.

func (*Process) StderrPipe added in v1.10.0

func (p *Process) StderrPipe() (io.ReadCloser, error)

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 (*Process) StdinPipe added in v1.10.0

func (p *Process) StdinPipe() (io.WriteCloser, error)

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 (*Process) StdoutPipe added in v1.10.0

func (p *Process) StdoutPipe() (io.ReadCloser, error)

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 (*Process) TellCommandNotToSpawnShell added in v1.10.0

func (p *Process) TellCommandNotToSpawnShell()

TellCommandNotToSpawnShell avoids that the specified Cmd display a small command prompt while runnning on Windows. It has no effects on other OS.

func (*Process) Wait added in v1.10.0

func (p *Process) Wait() error

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

type ReadDirFilter added in v1.7.0

type ReadDirFilter func(file *Path) bool

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.

func AndFilter added in v1.7.0

func AndFilter(filters ...ReadDirFilter) ReadDirFilter

AndFilter creates a ReadDirFilter that accepts all items that are accepted by all the given filters

func FilterDirectories added in v1.7.0

func FilterDirectories() ReadDirFilter

FilterDirectories is a ReadDirFilter that accepts only directories

func FilterNames added in v1.8.0

func FilterNames(allowedNames ...string) ReadDirFilter

FilterNames is a ReadDirFilter that accepts only the given filenames

func FilterOutDirectories added in v1.7.0

func FilterOutDirectories() ReadDirFilter

FilterOutDirectories is a ReadDirFilter that rejects all directories

func FilterOutNames added in v1.8.0

func FilterOutNames(rejectedNames ...string) ReadDirFilter

FilterOutNames is a ReadDirFilter that rejects the given filenames

func FilterOutPrefixes added in v1.7.0

func FilterOutPrefixes(rejectedPrefixes ...string) ReadDirFilter

FilterOutPrefixes creates a ReadDirFilter that rejects all the given filename prefixes

func FilterOutSuffixes added in v1.7.0

func FilterOutSuffixes(rejectedSuffixes ...string) ReadDirFilter

FilterOutSuffixes creates a ReadDirFilter that rejects all the given filename suffixes

func FilterPrefixes added in v1.7.0

func FilterPrefixes(allowedPrefixes ...string) ReadDirFilter

FilterPrefixes creates a ReadDirFilter that accepts only the given filename prefixes

func FilterSuffixes added in v1.7.0

func FilterSuffixes(allowedSuffixes ...string) ReadDirFilter

FilterSuffixes creates a ReadDirFilter that accepts only the given filename suffixes

func NotFilter added in v1.7.0

func NotFilter(x ReadDirFilter) ReadDirFilter

NotFilter creates a ReadDifFilter that accepts all items rejected by x and viceversa

func OrFilter added in v1.7.0

func OrFilter(filters ...ReadDirFilter) ReadDirFilter

OrFilter creates a ReadDirFilter that accepts all items that are accepted by any (at least one) of the given filters

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL