path

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: Apache-2.0 Imports: 16 Imported by: 53

README

godoc codecov Go Report Card

path - utilities and convenience wrappers for all sorts of unix and URL path operations

The heading says it all. This package is likely a great candidate for a general refactoring into more targeted Go packages, however, it has proven quite convenient for Go-Enjin to have all these sorts of things in one place.

Installation

> go get github.com/go-corelibs/path@latest

Examples

There are too many things to demonstrate, see the godoc for the full details.

Go-CoreLibs

Go-CoreLibs is a repository of shared code between the Go-Curses and Go-Enjin projects.

License

Copyright 2023 The Go-CoreLibs Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use file except in compliance with the License.
You may obtain a copy of the license at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	RxIncrementNameSuffix = regexp.MustCompile(`\((\d+)\)\s*$`)
	RxIncrementPathSuffix = regexp.MustCompile(`.(\d+)\s*$`)
)
View Source
var (
	// DefaultPathPerms are the default permissions used when creating
	// new directories
	DefaultPathPerms = os.FileMode(0770)
	// DefaultFilePerms are the default permissions used when creating
	// new files
	DefaultFilePerms = os.FileMode(0660)
)
View Source
var (
	ErrExistingFile = errors.New("path is an existing file")
)

Functions

func Abs

func Abs(path string) (absolute string, err error)

Abs is a convenience wrapper around filepath.Abs

func BackupAndOverwrite

func BackupAndOverwrite(path, content string, argv ...interface{}) (backup string, err error)

BackupAndOverwrite uses BackupName (passing argv along) to derive a non-existing file name, uses CopyFile to back up the current file contents and then uses Overwrite to update the original file contents.

func BackupName

func BackupName(name string, argv ...interface{}) (modified string)

BackupName is a more flexible version of IncrementFileBackup, with a variable length list of values configuring the backup file naming process. The following is a breakdown of the `argv` patterns based on the number of arguments in the `argv`:

defaults: ext="~", leader=".", prefix="", suffix="", inc=1

0: all defaults used
1: ext=argv[0].(string)
2: 1 + leader=argv[1].(string)
3: 2 + inc=argv[2].(int)
4: 2 + prefix=argv[2].(string) + suffix=argv[3].(string)
5: 4 + inc=argv[4].(int)

Examples:

  • zero argv BackupName("file.txt") == "file.txt~" BackupName("file.txt~") == "file.txt.1~"
  • one argv BackupName("file.txt", ".bak") == "file.txt.bak" BackupName("file.txt.bak", ".bak") == "file.txt.1.bak"
  • two argv BackupName("file.txt", ".bak", "~") == "file.txt~1.bak" BackupName("file.txt~1.bak", ".bak", "~") == "file.txt~2.bak"
  • three argv BackupName("file.txt", ".bak", "~", 2) == "file.txt~1.bak" BackupName("file.txt~1.bak", ".bak", "~", 2) == "file.txt~3.bak"
  • four argv BackupName("file.txt", ".bak", "~", "[", "]") == "file.txt.bak" BackupName("file.txt.bak", ".bak", "~", "[", "]") == "file.txt~[1].bak"
  • five argv BackupName("file.txt", ".bak", "~", "[", "]", 2) == "file.txt.bak" BackupName("file.txt~[1].bak", ".bak", "~", "[", "]", 2) == "file.txt~[3].bak"

func Base

func Base(path string) (name string)

Base returns the base name of the path without any file extensions

func BasePath

func BasePath(path string) (basePath string)

BasePath returns the path without any primary or secondary file extensions, tertiary and other extensions present will remain as-is

Example:

BasePath("one/file.txt.tmpl.bak") == "one/file.txt"

func ChmodAll added in v1.2.0

func ChmodAll(src string) error

ChmodAll uses Walk to traverse the filesystem and change all regular file permissions to the DefaultFilePerms (0660) and all directory permissions to the DefaultPathPerms (0770).

Stops on the first error

func Clean

func Clean(path string) (cleaned string)

Clean is a convenience wrapper around filepath.Clean

func CleanWithSlash

func CleanWithSlash(path string) (clean string)

CleanWithSlash trims all leading and trailing space from the `path` given, uses filepath.Clean on the trimmed results. The cleaned results are prefixed with a leading slash producing the `clean` value of `path`.

CleanWithSlash supports the Go-Enjin convention of a special type of path that is prefixed with a `!` instead of a slash and will correctly return the `clean` value with that prefix if it was present and if not uses that normal path separator slash.

CleanWithSlash produces absolute paths but do not mistake these for actual filesystem paths. CleanWithSlash is intended for use in working with URL paths.

func CleanWithSlashes

func CleanWithSlashes(path string) (clean string)

CleanWithSlashes is a wrapper around CleanWithSlash which ensures the `clean` path begins and ends with a slash

func CopyFile

func CopyFile(src, dst string) (copied int64, err error)

CopyFile copies the regular file `src` to `dst`

func Dir

func Dir(path string) (name string)

Dir is a convenience wrapper around filepath.Dir

func DirSize added in v1.4.0

func DirSize(path string) (size uint64)

DirSize uses filepath.WalkDir to traverse the given directory recursively and add up the size of each file present (includes hidden and any non-directory entries)

func Exists

func Exists(path string) bool

Exists returns true if the path is present on the local filesystem (could be a directory or any type of file)

func Ext

func Ext(path string) (extn string)

Ext returns the extension of the file (without the dot)

func ExtExt

func ExtExt(path string) (primary, secondary string)

ExtExt returns the extension of the file (without the dot) and any secondary extension found in the path

Example:

ExtExt("page.html.tmpl") => "tmpl", "html"

func FileSize added in v1.1.0

func FileSize(path string) (size int64)

FileSize returns the size of regular files

func FindFileRelativeToPath

func FindFileRelativeToPath(name, path string) (file string)

FindFileRelativeToPath looks for the named file within the directory path given and if not found, walks up the parent directories, checking each of them and returning the first named file found (as an absolute path)

The intent is something similar to how the `git` command knows it's in a repository even though the command may be run from within a subdirectory of the repository

func FindFileRelativeToPwd

func FindFileRelativeToPwd(name string) (file string)

FindFileRelativeToPwd is a convenience wrapper for FindFileRelativeToPath, specifying the given name and a path of "."

func HasAnyExt

func HasAnyExt(path string, extensions ...string) (present bool)

HasAnyExt returns true

func HasExt

func HasExt(path, extension string) (present bool)

HasExt returns true if either the primary or secondary file extension matches the one given

func HasPermission added in v1.2.0

func HasPermission(path string, expected os.FileMode) (present bool)

func IncrementFileBackup

func IncrementFileBackup(name, extension string) (modified string)

IncrementFileBackup removes the given extension if present, uses IncrementFilePath to modify the name with the extension appended. If the extension is empty, a "~" is used.

Examples:

IncrementFileBackup("test.txt", ".bak") == "test.txt.bak"
IncrementFileBackup("test.txt.bak", ".bak") == "test.txt.1.bak"
IncrementFileBackup("test.txt.1.bak", ".bak") == "test.txt.2.bak"

func IncrementFileName

func IncrementFileName(name string) (modified string)

IncrementFileName is a wrapper around IncrementLabel, equivalent to: `IncrementLabel(name, " ", "(", ")", 1)`

func IncrementFilePath

func IncrementFilePath(name string) (modified string)

IncrementFilePath is a wrapper around IncrementLabel, equivalent to: `IncrementLabel(name, ".", "", "", 1)`

func IncrementLabel

func IncrementLabel(label, leader, prefix, suffix string, increment int) (modified string, integer int)

IncrementLabel examines the given label for the specific sequence of leader, prefix, one or more digits and suffix characters. If the sequence is found, the digits are parsed into an integer and incremented by the given increment value and reassembled into the modified label output. If the sequence is not found, the sequence is appended to the whole label given with a number of 1.

If the increment given is zero, an increment of 1 is assumed as an increment of zero would not actually increment anything. Negative increments are valid, resulting in a decrement rather than actual increment.

Examples:

IncrementLabel("Title", " ", "(", ")", 1) == "Title (1)"
IncrementLabel("Title (10)", " ", "(", ")", 1) == "Title (11)"
IncrementLabel("filename", ".", "", "", 1) == "filename.1"
IncrementLabel("filename.10", ".", "", "", 1) == "filename.11"
IncrementLabel("filename.10", ".", "", "", -1) == "filename.9"

func IsBackup

func IsBackup(path string) bool

IsBackup returns true if the path ends with a tilde

func IsDir

func IsDir(path string) bool

IsDir returns true if the path is an existing directory

func IsFile

func IsFile(path string) bool

IsFile returns true if the path is an existing file (could be a char device, pipe or other unix goodness, but not a directory)

func IsHidden

func IsHidden(path string) bool

IsHidden returns true if the base of the path starts with a period

func IsHiddenPath

func IsHiddenPath(path string) (hidden bool)

IsHiddenPath returns true if any of the path segments starts with a period and will panic if filepath.Abs fails to resolve an absolute path, which is not something that just happens randomly. Likely culprits of a panic are situations where the current working directory doesn't exist anymore or some other calamity of that nature

func IsPermission added in v1.2.0

func IsPermission(path string, expected os.FileMode) (present bool)

func IsPlainText

func IsPlainText(path string) (isPlain bool)

IsPlainText returns true if the path is a file and the file's mimetype is of `text/plain` type

func IsRegularFile

func IsRegularFile(path string) bool

IsRegularFile returns true if the path is an existing regular file

func Join

func Join(parts ...string) (joined string)

Join joins the given URL path parts and uses filepath.Clean on the results

func JoinWithSlash

func JoinWithSlash(paths ...string) (joined string)

JoinWithSlash joins the given URL path parts and uses CleanWithSlash on the results

func JoinWithSlashes

func JoinWithSlashes(paths ...string) (joined string)

JoinWithSlashes joins the given URL path parts and uses CleanWithSlashes on the results

func List

func List(path string, includeHidden bool) (paths []string, err error)

List returns a list of directories and files, sorted in natural order with hidden things first and directories grouped before files

func ListAllDirs

func ListAllDirs(path string, includeHidden bool) (paths []string, err error)

ListAllDirs is similar to ListDirs except returning all directories found recursively

func ListAllFiles

func ListAllFiles(path string, includeHidden bool) (paths []string, err error)

ListAllFiles is similar to ListAllDirs except returning only files

func ListDirs

func ListDirs(path string, includeHidden bool) (paths []string, err error)

ListDirs is similar to List except returning only directories

func ListFiles

func ListFiles(path string, includeHidden bool) (paths []string, err error)

ListFiles is similar to ListDirs except returning only files

func MatchCut

func MatchCut(path, prefix string) (suffix string, matched bool)

MatchCut returns the suffix of path if path is prefixed with the given prefix path. If the path and prefix match exactly, suffix will be empty and matched will be true

Examples:

MatchCut("/one/two/", "one/two") == "", true
MatchCut("/one/two/many", "one/two") == "many", true
MatchCut("/one/two/many", "one") == "two/many", true

func MatchExact

func MatchExact(path, prefix string) (match bool)

MatchExact compares cleaned versions of path and prefix

func MkdirAll added in v1.2.0

func MkdirAll(path string) (err error)

MkdirAll is a wrapper around os.MkdirAll with DefaultPathPerms (0770)

func MoveFile

func MoveFile(src, dst string) (err error)

MoveFile tries to rename `src` to `dst` and if that works, nothing else is done. If renaming did not work, MoveFile copies `src` to `dst` and if successful, removes the original file. MoveFile can only move regular files and not pipes, char devices, etc.

func Overwrite

func Overwrite(path, content string) (err error)

Overwrite overwrites the given file, preserving existing permissions

func OverwriteWithPerms

func OverwriteWithPerms(path, content string, perms fs.FileMode) (err error)

OverwriteWithPerms overwrites the given file and ensures the permissions are specifically the perms given. Normal unix umask may prevent correct permissions, use: `old := syscall.Umask(0); defer syscall.Umask(old)` to guarantee the specified perms

func ParseParentPaths

func ParseParentPaths(path string) (parents []string)

ParseParentPaths is expecting a directory path and returns a list that walks up the total path with each item in the list

Example:

ParseParentPaths("one/two/many") == []string{
    "one",
    "one/two",
    "one/two/many",
}

func Permissions

func Permissions(path string) (perms fs.FileMode, err error)

Permissions is a wrapper around os.Stat, returning just the stat.Mode().Perm() value and any error from the stat call

func PruneEmptyDirs

func PruneEmptyDirs(path string) (err error)

PruneEmptyDirs finds all directories starting at the given path, checks if

func Pwd added in v1.2.0

func Pwd() (pwd string)

Pwd is a wrapper around os.Getwd

func ReadDir

func ReadDir(path string) (paths []fs.DirEntry, err error)

ReadDir is a convenience wrapper around os.ReadDir

func ReadFile

func ReadFile(path string) (content []byte, err error)

ReadFile is a convenience wrapper around os.ReadFile

func SafeConcatRelPath

func SafeConcatRelPath(root string, paths ...string) (out string)

SafeConcatRelPath prunes all empty and current dir paths from the list given, using TrimSlashes, then joins all the paths together, ensuring the output is prefixed with the given root, and has no leading or trailing slash and has is filepath.Clean

func SafeConcatUrlPath

func SafeConcatUrlPath(root string, paths ...string) (out string)

SafeConcatUrlPath wraps SafeConcatRelPath with a prefixing slash making an absolute URL path

func Stat

func Stat(path string) (spec times.Timespec, err error)

Stat is a convenience wrapper around github.com/djherbis/times.Stat

func TopDirectory

func TopDirectory(path string) (name string)

TopDirectory returns the top directory in the path given or an empty string if there are no parent directories present

func TrimDotSlash

func TrimDotSlash(path string) (out string)

TrimDotSlash trims any leading `./` from the given path

func TrimExt

func TrimExt(path string) (out string)

TrimExt returns the path without the last extension, if there are any

func TrimPrefix

func TrimPrefix(path, prefix string) (modified string)

TrimPrefix is like strings.TrimPrefix but for URL paths so that the prefix looked for is a prefixing URL path regardless of any slashes present in the prefix or path argument values.

TrimPrefix is primarily used in Go-Enjin filesystem driver implementations to coalesce given path into an underlying filesystem's actual path.

Example:

TrimPrefix("/one", "one") == ""
TrimPrefix("/one/two/many", "one") == "two/many"
TrimPrefix("/one/two/many", "two/many") == "one/two/many"

func TrimRelativeToRoot

func TrimRelativeToRoot(path, root string) (rel string)

TrimRelativeToRoot truncates the root from path and removes any leading or trailing slashes. If the root is not present in the path, rel is empty

func TrimSlash

func TrimSlash(path string) (clean string)

TrimSlash returns the filepath cleaned and without any trailing slash

func TrimSlashes

func TrimSlashes(path string) (clean string)

TrimSlashes returns the filepath cleaned and without any leading or trailing slashes

func Walk

func Walk(root string, fn filepath.WalkFunc) (err error)

Walk is a convenience wrapper around filepath.Walk

func Which

func Which(name string) (path string)

Which is a convenience wrapper around exec.LookPath and filepath.Abs

Types

type CListPath

type CListPath struct {
	Path   string
	Hidden struct {
		Dirs  []string
		Files []string
	}
	Normal struct {
		Dirs  []string
		Files []string
	}
	Others map[string]ListPaths
}

func ListMatching

func ListMatching(path string, includeHidden, recurse bool, matcher func(dir bool, path string) (matched bool)) (list *CListPath, err error)

ListMatching is a general purpose filesystem listing function, used by all other List functions in this package. It accepts a custom matcher func used to determine whether to include the specific path or not and it returns a new *CListPath instance which contains all the results of the list process. ListMatching will return at the first error

func NewListPath

func NewListPath(path string) (l *CListPath)

func (*CListPath) AddHiddenDir

func (l *CListPath) AddHiddenDir(paths ...string)

func (*CListPath) AddHiddenFile

func (l *CListPath) AddHiddenFile(paths ...string)

func (*CListPath) AddListPath

func (l *CListPath) AddListPath(parent string, other *CListPath)

func (*CListPath) AddNormalDir

func (l *CListPath) AddNormalDir(paths ...string)

func (*CListPath) AddNormalFile

func (l *CListPath) AddNormalFile(paths ...string)

func (*CListPath) List

func (l *CListPath) List() (sorted []string)

func (*CListPath) Sort

func (l *CListPath) Sort()

type ListPaths

type ListPaths []*CListPath

func (ListPaths) List

func (l ListPaths) List() (list []string)

func (ListPaths) Sort

func (l ListPaths) Sort()

Jump to

Keyboard shortcuts

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