Documentation ¶
Index ¶
- Constants
- Variables
- func Expand(path string) string
- func ExpandUser(path string) string
- func IsJSON(data []byte) bool
- func ListFilesWithGlob(fs afero.Fs, rootDir, pattern string) ([]string, error)
- func ResolveAbsPath(filePath string) (string, error)
- func SanitizeJSON(rawJSON string, template interface{}) ([]byte, error)
- func StructToJSONMap(src interface{}) (map[string]interface{}, error)
- func ToSlices(reader io.Reader, separator rune) ([][]string, error)
- type CompressOption
- type CompressOptions
- type FsPath
- func (p *FsPath) AbsPath() string
- func (p *FsPath) AppendBytes(data []byte) error
- func (p *FsPath) AppendText(data string) error
- func (p *FsPath) BaseDir() string
- func (p *FsPath) CSVGetSlices() ([][]string, error)
- func (p *FsPath) Chmod(mode os.FileMode) error
- func (p *FsPath) Copy(newfile string) error
- func (p *FsPath) Cwd() (*FsPath, error)
- func (p *FsPath) Dir() *FsPath
- func (p *FsPath) Exists() bool
- func (p *FsPath) Expand() *FsPath
- func (p *FsPath) ExpandUser() *FsPath
- func (p *FsPath) Fs() afero.Fs
- func (p *FsPath) GetBytes() ([]byte, error)
- func (p *FsPath) GetJSON(raw interface{}) error
- func (p *FsPath) GetLines() ([]string, error)
- func (p *FsPath) GetMD5() (string, error)
- func (p *FsPath) GetString() (string, error)
- func (p *FsPath) Home() (*FsPath, error)
- func (p *FsPath) IsDir() bool
- func (p *FsPath) Join(others ...string) *FsPath
- func (p *FsPath) LastNSegments(num int) string
- func (p *FsPath) LastSegment() string
- func (p *FsPath) ListFileNamesWithGlob(pattern string) ([]string, error)
- func (p *FsPath) ListFilesWithGlob(pattern string) ([]string, error)
- func (p *FsPath) MkParentDir() error
- func (p *FsPath) Mkdir(perm os.FileMode, parents bool) error
- func (p *FsPath) MkdirAll(perm os.FileMode) error
- func (p *FsPath) Mkdirs() error
- func (p *FsPath) Move(newfile string) error
- func (p *FsPath) MustAppendBytes(data []byte)
- func (p *FsPath) MustAppendText(data string)
- func (p *FsPath) MustCSVGetSlices() [][]string
- func (p *FsPath) MustGetBytes() []byte
- func (p *FsPath) MustGetJSON(v interface{})
- func (p *FsPath) MustGetLines() []string
- func (p *FsPath) MustGetString() string
- func (p *FsPath) MustReadBytes() []byte
- func (p *FsPath) MustReadText() string
- func (p *FsPath) MustSetString(data string)
- func (p *FsPath) MustTSVGetSlices() [][]string
- func (p *FsPath) MustWriteBytes(data []byte)
- func (p *FsPath) MustWriteText(data string)
- func (p *FsPath) NoSuffix(str string) string
- func (p *FsPath) Parent() *FsPath
- func (p *FsPath) Parents() []*FsPath
- func (p *FsPath) ParentsUpTo(num int) *FsPath
- func (p *FsPath) Parts() []string
- func (p *FsPath) ReadBytes() ([]byte, error)
- func (p *FsPath) ReadText() (string, error)
- func (p *FsPath) Reader() (io.Reader, error)
- func (p *FsPath) RelativeTo(other string) (string, error)
- func (p *FsPath) Rename(newfile string) error
- func (p *FsPath) Rmdir() error
- func (p *FsPath) SetBytes(data []byte) error
- func (p *FsPath) SetString(data string) error
- func (p *FsPath) Split(pathStr string) (dir, name string)
- func (p *FsPath) Stat() (fs.FileInfo, error)
- func (p *FsPath) String() string
- func (p *FsPath) Suffixes() []string
- func (p *FsPath) TSVGetSlices() ([][]string, error)
- func (p *FsPath) TarGzDir(tarGzFileName string) (*FsPath, int, error)
- func (p *FsPath) Touch() error
- func (p *FsPath) Unlink(missingOK bool) error
- func (p *FsPath) Untar(destDir string, opts ...CompressOption) error
- func (p *FsPath) Unzip(destDir string, opts ...CompressOption) error
- func (p *FsPath) Walk(walkFn WalkFunc) error
- func (p *FsPath) WithName(name string) *FsPath
- func (p *FsPath) WithRenamedParentDir(newParentName string) *FsPath
- func (p *FsPath) WithReplacedDirAndSuffix(dirName, newSuffix string) *FsPath
- func (p *FsPath) WithStem(stem string) *FsPath
- func (p *FsPath) WithSuffix(suffix string) *FsPath
- func (p *FsPath) WithSuffixAndSuffixedParentDir(newSuffix string) *FsPath
- func (p *FsPath) WriteBytes(data []byte) error
- func (p *FsPath) WriteText(data string) error
- func (p *FsPath) ZipDir(zipFileName string) (*FsPath, int, error)
- type WalkFunc
Constants ¶
const ( SepRuneCsv = ',' SepRuneTsv = '\t' )
Variables ¶
var ( ErrIllegalFilePath = errors.New("illegal file path") ErrFileTooLarge = errors.New("file exceeded maximum allowed size") ErrIncompleteWrite = errors.New("incomplete write: consider increasing the maxSize parameter or checking for disk space issues") )
var ( ErrNotDirectory = errors.New("path is not a directory") ErrDirectoryNotEmpty = errors.New("directory not empty") ErrCannotUnlinkDir = errors.New("cannot unlink directory: use Rmdir() instead") )
var ( FileMode644 = os.FileMode(_mode644) DirMode755 = os.FileMode(_mode755) )
var ErrCannotCreateSiblingDir = errors.New("cannot create sibling directory to parent: current path is at root or one level below")
Functions ¶
func Expand ¶
Expand takes a file path and expands any environment variables and user home directory references.
This function performs the following expansions:
- Expands the user's home directory (e.g., "~" or "~username")
- Expands environment variables (e.g., "$HOME" or "${HOME}")
The function first expands the user's home directory using ExpandUser, then expands any environment variables using os.ExpandEnv.
Parameters:
- path: A string representing the file path to be expanded.
Returns:
- string: The expanded path.
Example:
expanded := Expand("~/documents/$USER/file.txt") // This might return "/home/username/documents/username/file.txt"
Note: This function does not check if the expanded path actually exists in the file system.
func ExpandUser ¶
ExpandUser replaces a leading ~ or ~user with the user's home directory.
This function handles the following cases:
- "~" or "~/..." expands to the current user's home directory
- "~username" or "~username/..." expands to the specified user's home directory
If the user's home directory cannot be determined, the original path is returned.
Parameters:
- path: A string representing the file path to be expanded.
Returns:
- string: The expanded path with the user's home directory.
Example:
expanded := ExpandUser("~/documents") // This might return "/home/username/documents" expanded := ExpandUser("~otheruser/documents") // This might return "/home/otheruser/documents"
Note: This function does not expand environment variables. Use Expand for full expansion.
func IsJSON ¶
IsJSON checks if the given byte slice contains valid JSON data.
This function attempts to unmarshal the input data into a json.RawMessage. If the unmarshal operation succeeds, it means the data is valid JSON.
Parameters:
- data: A byte slice containing the data to be checked.
Returns:
- bool: true if the data is valid JSON, false otherwise.
The function returns true for valid JSON structures including objects, arrays, strings, numbers, booleans, and null. It returns false for any input that cannot be parsed as valid JSON.
Example:
validJSON := []byte(`{"name": "John", "age": 30}`) fmt.Println(IsJSON(validJSON)) // Output: true invalidJSON := []byte(`{"name": "John", "age": }`) fmt.Println(IsJSON(invalidJSON)) // Output: false
Note: This function does not provide information about why the JSON might be invalid. For more detailed error information, use json.Unmarshal directly.
func ListFilesWithGlob ¶
ListFilesWithGlob lists files in the specified directory matching the given pattern.
This function uses the provided file system (fs) to perform the glob operation. If fs is nil, it defaults to the OS file system.
Parameters:
- fs: The file system to use. If nil, uses the OS file system.
- rootDir: The root directory in which to perform the glob operation.
- pattern: The glob pattern to match files against. If empty, defaults to "*".
Returns:
- []string: A slice of matched file paths.
- error: An error if the glob operation fails.
The function expands the rootDir to handle home directory references and environment variables. It then performs a glob operation using the specified pattern in the given root directory.
If the pattern is an empty string, it defaults to "*", matching all files in the root directory.
Example usage:
// List all .txt files in the user's home directory files, err := ListFilesWithGlob(nil, "~/Documents", "*.txt") if err != nil { log.Fatal(err) } for _, file := range files { fmt.Println(file) }
Note: This function does not recurse into subdirectories unless specified in the pattern.
func ResolveAbsPath ¶
ResolveAbsPath takes a file path and returns its absolute path.
This function first expands any environment variables or user home directory references in the given path. Then, it converts the expanded path to an absolute path without resolving symbolic links.
Parameters:
- filePath: A string representing the file path to be converted.
Returns:
- string: The absolute path of the input file path.
If the function encounters an error while converting to an absolute path, it returns the expanded path instead.
Example:
absPath := ResolveAbsPath("~/documents/file.txt") // On a Unix system, this might return "/home/user/documents/file.txt"
Note: This function does not check if the path actually exists in the file system.
func SanitizeJSON ¶
SanitizeJSON cleans a JSON string by removing empty fields. It unmarshals the raw JSON into the provided struct template, then marshals it back to JSON, effectively removing any empty or zero-value fields.
Parameters:
- rawJSON: The input JSON string to sanitize.
- template: A pointer to a struct that defines the expected schema of the JSON.
Returns:
- []byte: The sanitized JSON as a byte slice.
- error: Any error encountered during the process.
Example usage:
type Person struct { Name string `json:"name,omitempty"` Age int `json:"age,omitempty"` } input := `{"name":"John","age":0,"extra":""}` cleaned, err := SanitizeJSON(input, &Person{}) if err != nil { // Handle error } // cleaned will be: `{"name":"John"}`
Note: This function relies on the `omitempty` tag for fields that should be removed when empty. Make sure your struct is properly tagged for the desired behavior.
func StructToJSONMap ¶
StructToJSONMap converts a struct to a map[string]interface{} representation of JSON. This function uses JSON marshaling and unmarshaling to perform the conversion, which means it respects JSON tags and only includes exported fields.
Parameters:
- src: The source struct to convert.
Returns:
- map[string]interface{}: A map representing the JSON structure of the input struct.
- error: An error if the conversion process fails.
Example usage:
type Person struct { Name string `json:"name"` Age int `json:"age"` } person := Person{Name: "John Doe", Age: 30} jsonMap, err := StructToJSONMap(person) if err != nil { // Handle error } // jsonMap will be: map[string]interface{}{"name": "John Doe", "age": 30}
Note: This function will only include fields that would be marshaled to JSON. Unexported fields and fields with `json:"-"` tags will be omitted.
Types ¶
type CompressOption ¶
type CompressOption func(*CompressOptions)
CompressOption defines the method to modify CompressOptions
func WithMaxSize ¶
func WithMaxSize(maxSize int64) CompressOption
WithMaxSize sets the MaxSize option
type CompressOptions ¶
type CompressOptions struct {
MaxSize int64
}
CompressOptions holds the options for compression and decompression operations
type FsPath ¶
type FsPath struct { // Stem represents the base name of the file or directory without any suffix (file extension). // For files, it's the file name without the extension. For directories, it's the directory name. // // Examples: // - For a file "/tmp/folder/file.txt", Stem would be "file" // - For a directory "/tmp/folder/", Stem would be "folder" // - For a file "document.tar.gz", Stem would be "document.tar" // // This field is useful when you need to work with the core name of a file or directory // without considering its extension or full path. Stem string // Name represents the base name of the file or directory, including any suffix (file extension). // For files, it's the file name with the extension. For directories, it's the same as the Name field. // // Examples: // - For a file "/tmp/folder/file.txt", Name would be "file.txt" // - For a directory "/tmp/folder/", Name would be "folder" // - For a file "document.tar.gz", Name would be "document.tar.gz" // // This field is useful when you need to work with the full name of a file including its extension, // or when you need to distinguish between files with the same base name but different extensions. Name string // Suffix represents the file extension, including the leading dot. // For files without an extension or for directories, it will be an empty string. // // Examples: // - For a file "document.txt", Suffix would be ".txt" // - For a file "archive.tar.gz", Suffix would be ".gz" // - For a file "README" or a directory, Suffix would be "" // // This field is useful for identifying file types, filtering files by extension, // or when you need to work with or modify file extensions. Suffix string RawPath string // contains filtered or unexported fields }
FsPath represents a file system entity with various properties
func (*FsPath) AppendBytes ¶
AppendBytes appends the given byte slice to the file, creating the file if it doesn't exist.
func (*FsPath) AppendText ¶
AppendText appends the given string data to the file, creating the file if it doesn't exist.
func (*FsPath) BaseDir ¶
BaseDir returns the name of the directory containing the file or directory represented by this FSPath.
For a file path, it returns the name of the directory containing the file. For a directory path, it returns the name of the directory itself. For the root directory, it returns "/".
This method is useful when you need to know the name of the immediate parent directory without getting the full path to that directory.
Returns:
- string: The name of the base directory.
Examples:
For a file path "/home/user/documents/file.txt": BaseDir() returns "documents"
For a directory path "/home/user/documents/": BaseDir() returns "documents"
For a file in the root directory "/file.txt": BaseDir() returns "/"
For the root directory "/": BaseDir() returns "/"
Note:
- This method does not check if the directory actually exists in the file system.
- It works with the absolute path of the FSPath, regardless of how the FSPath was originally created.
Usage:
file := Path("/home/user/documents/file.txt") baseDirName := file.BaseDir() // baseDirName is "documents"
func (*FsPath) CSVGetSlices ¶
CSVGetSlices reads the CSV file and returns its content as slices.
This method reads the file at the FsPath's location as a CSV (Comma-Separated Values) file and returns its content as a slice of string slices. Each inner slice represents a row in the CSV file, with each string in the slice representing a field in that row.
Returns:
- [][]string: A slice of slices containing the CSV data.
- error: An error if the file cannot be read or parsed.
The method uses a comma (',') as the field separator and '#' as the comment character. Empty lines and lines starting with '#' (after trimming spaces) are skipped.
Example usage:
data, err := path.CSVGetSlices() if err != nil { // handle error } for _, row := range data { // process each row }
Note: This method reads the entire file into memory. For very large files, consider using a streaming approach instead.
func (*FsPath) Chmod ¶
Chmod changes the mode of the file to the given mode.
Parameters:
- mode: The new file mode.
Returns:
- error: An error if the operation failed.
Example:
err := path.Chmod(0644) if err != nil { log.Fatal(err) }
func (*FsPath) Copy ¶
Copy creates a copy of the file at the current path to a new location.
This method copies the content of the current file to a new file at the specified path. It also attempts to preserve the file mode (permissions) of the original file.
Parameters:
- newfile: A string representing the path where the new copy should be created.
Returns:
- error: An error if the operation failed. Possible reasons for failure include:
- The source file cannot be opened for reading.
- The destination file cannot be created or opened for writing.
- An error occurs during the copy operation.
- The file mode (permissions) cannot be set on the new file.
The method performs the following steps: 1. Opens the source file for reading. 2. Creates the destination file. 3. Copies the content from the source to the destination. 4. Attempts to set the file mode of the new file to match the original.
Example:
sourcePath := Path("/path/to/source/file.txt") err := sourcePath.Copy("/path/to/destination/file_copy.txt") if err != nil { log.Fatalf("Failed to copy file: %v", err) }
Note: This method does not handle copying directories. It's designed for single file operations.
func (*FsPath) Cwd ¶
Cwd returns a new FsPath representing the current working directory.
This method is equivalent to calling the Cwd() function.
Returns:
- *FsPath: A new FsPath instance representing the current working directory.
- error: An error if the current working directory couldn't be determined.
Example:
cwdPath, err := path.Cwd() if err != nil { log.Fatal(err) } fmt.Println(cwdPath.absPath)
func (*FsPath) Expand ¶
Expand expands environment variables and user's home directory in the path.
This method is equivalent to calling the Expand() function on the path.
Returns:
- A new FsPath with the expanded path.
func (*FsPath) ExpandUser ¶
ExpandUser replaces a leading ~ or ~user with the user's home directory.
This method is equivalent to calling the ExpandUser() function on the path.
Returns:
- A new FsPath with the expanded path.
func (*FsPath) GetJSON ¶
GetJSON reads the file and unmarshals its content into the provided interface.
This method reads the entire file content using GetBytes, then uses json.Unmarshal to parse the JSON data into the provided interface.
Parameters:
- v: A pointer to the variable where the unmarshaled data should be stored.
Returns:
- error: An error if the file cannot be read or if the JSON unmarshaling fails.
Example usage:
type Config struct { Name string `json:"name"` Version int `json:"version"` } var config Config err := path.GetJSON(&config) if err != nil { // handle error } fmt.Printf("Name: %s, Version: %d\n", config.Name, config.Version)
Note: This method reads the entire file into memory. For very large files, consider using a streaming JSON parser instead.
func (*FsPath) GetLines ¶
GetLines reads the file and returns its contents as a slice of strings.
Each string in the returned slice represents a line in the file. The newline characters are stripped from the end of each line.
Returns:
- []string: A slice containing each line of the file.
- error: An error if the file cannot be read or processed.
Example usage:
lines, err := path.GetLines() if err != nil { // handle error } for _, line := range lines { fmt.Println(line) }
Note: This method reads the entire file into memory. For very large files, consider using a streaming approach instead.
func (*FsPath) Home ¶
Home returns a new FsPath representing the user's home directory.
This method is equivalent to calling the Home() function.
Returns:
- *FsPath: A new FsPath instance representing the user's home directory.
- error: An error if the home directory couldn't be determined.
Example:
homePath, err := path.Home() if err != nil { log.Fatal(err) } fmt.Println(homePath.absPath)
func (*FsPath) Join ¶
Join joins one or more path components to the current path.
If the current FSPath represents a file, the method joins the components to the parent directory of the file. If it's a directory, it joins directly to the current path.
Parameters:
- others: One or more path components to join to the current path.
Returns:
- A new FSPath instance representing the joined path.
Examples:
For a directory "/home/user": path.Join("documents", "file.txt") returns a new FSPath for "/home/user/documents/file.txt"
For a file "/home/user/file.txt": path.Join("documents", "newfile.txt") returns a new FSPath for "/home/user/documents/newfile.txt"
For a path "/": path.Join("etc", "config") returns a new FSPath for "/etc/config"
Note: This method does not modify the original FSPath instance or create any directories. It only returns a new FSPath instance representing the joined path.
func (*FsPath) LastNSegments ¶
LastNSegments returns the last n segments of the path.
- If n is 0, it returns just the file name.
- If n is greater than or equal to the number of segments, it returns the full path.
func (*FsPath) LastSegment ¶
LastSegment returns the last segment of the path.
This is equivalent to calling LastNSegments(1).
func (*FsPath) ListFileNamesWithGlob ¶
ListFileNamesWithGlob lists file names in the working directory matching the given pattern.
This method performs a glob operation in the directory of the current FSPath, using the pattern provided. It returns only the base names of the matched files, not their full paths.
Parameters:
- pattern: The glob pattern to match files against. If empty, defaults to "*".
Returns:
- []string: A sorted slice of matched file names (not full paths).
- error: An error if the glob operation fails.
The method uses the directory of the current FSPath as the root for the glob operation. If the pattern is an empty string, it defaults to "*", matching all files in the directory.
Example usage:
path := Path("/home/user/documents") files, err := path.ListFileNamesWithGlob("*.txt") if err != nil { log.Fatal(err) } for _, file := range files { fmt.Println(file) }
Note: This method does not recurse into subdirectories unless specified in the pattern. The returned names are just the base names of the files, not their full paths. The returned slice is sorted alphabetically.
func (*FsPath) ListFilesWithGlob ¶
ListFilesWithGlob lists files in the working directory matching the given pattern
This method performs a glob operation in the directory of the current FSPath, using the pattern provided. It leverages the underlying file system associated with this FSPath instance.
Parameters:
- pattern: The glob pattern to match files against. If empty, defaults to "*".
Returns:
- []string: A slice of matched file paths.
- error: An error if the glob operation fails.
The method uses the directory of the current FSPath as the root for the glob operation. If the pattern is an empty string, it defaults to "*", matching all files in the directory.
Example usage:
path := Path("/home/user/documents") files, err := path.ListFilesWithGlob("*.txt") if err != nil { log.Fatal(err) } for _, file := range files { fmt.Println(file) }
Note: This method does not recurse into subdirectories unless specified in the pattern. The returned paths are relative to the working directory of the FSPath.
func (*FsPath) MkParentDir ¶
MkParentDir creates the parent directory for the given path
func (*FsPath) Mkdir ¶
Mkdir creates a new directory with the specified permissions. If the directory already exists, Mkdir does nothing and returns nil.
Parameters:
- perm: The file mode bits to use for the new directory.
- parents: If true, any missing parents of this path are created as needed; if false and the parent directory does not exist, an error is returned.
Returns:
- error: An error if the operation failed.
Examples:
// Create a single directory err := path.Mkdir(0755, false) if err != nil { log.Fatal(err) } // Create a directory and all necessary parents err := path.Mkdir(0755, true) if err != nil { log.Fatal(err) }
Note:
- When parents is true, this method behaves like MkdirAll in the os package.
- When parents is false, it behaves like Mkdir in the os package.
- Using parents=true is generally safer and more convenient in most situations.
func (*FsPath) MustAppendBytes ¶
MustAppendBytes appends the given byte slice to the file, creating the file if it doesn't exist. It panics on error.
func (*FsPath) MustAppendText ¶
MustAppendText appends the given string data to the file, creating the file if it doesn't exist. It panics on error.
func (*FsPath) MustCSVGetSlices ¶
func (*FsPath) MustGetBytes ¶
func (*FsPath) MustGetJSON ¶
func (p *FsPath) MustGetJSON(v interface{})
MustGetJSON reads the file, unmarshals its content into the provided interface, and panics on error.
This method is similar to GetJSON but panics if an error occurs during reading or unmarshaling.
Parameters:
- v: A pointer to the variable where the unmarshaled data should be stored.
Example usage:
type Config struct { Name string `json:"name"` Version int `json:"version"` } var config Config path.MustGetJSON(&config) fmt.Printf("Name: %s, Version: %d\n", config.Name, config.Version)
Note: Use this method only when you're sure the file exists and contains valid JSON, or if you want to halt execution on error.
func (*FsPath) MustGetLines ¶
MustGetLines reads the file and returns its contents as a slice of strings. It panics if an error occurs.
This is a convenience wrapper around GetLines.
Returns:
- []string: A slice containing each line of the file.
Example usage:
lines := path.MustGetLines() for _, line := range lines { fmt.Println(line) }
Note: Use this method only when you're sure the file exists and can be read, or if you want to halt execution on error.
func (*FsPath) MustGetString ¶
func (*FsPath) MustReadBytes ¶
MustReadBytes reads the contents of the file and returns it as a byte slice. It panics on error.
func (*FsPath) MustReadText ¶
MustReadText reads the contents of the file and returns it as a string. It panics on error.
func (*FsPath) MustSetString ¶
MustSetString sets the file content as a string, panics on error
func (*FsPath) MustTSVGetSlices ¶
func (*FsPath) MustWriteBytes ¶
MustWriteBytes writes the given byte slice to the file, creating the file if it doesn't exist, and overwriting it if it does. It panics on error.
func (*FsPath) MustWriteText ¶
MustWriteText writes the given string data to the file, creating the file if it doesn't exist, and overwriting it if it does. It panics on error.
func (*FsPath) Parent ¶
Parent returns the immediate parent directory path of the current path.
Returns:
A string representing the parent directory path.
This method is a convenience wrapper around Parents(1), providing quick access to the immediate parent directory.
Behavior:
- For a file or directory not at the root, it returns the containing directory.
- For the root directory, it returns an empty string.
Examples:
For a file "/home/user/documents/file.txt": parent := path.Parent() // parent is "/home/user/documents"
For a directory "/var/log/": parent := path.Parent() // parent is "/var"
For the root directory "/": parent := path.Parent() // parent is ""
Note:
- This method does not check if the parent directory actually exists in the file system.
- It works with the absolute path of the FSPath, regardless of how the FSPath was originally created.
Use cases:
- Quickly accessing the parent directory without specifying the number of levels to go up.
- Simplifying code when only the immediate parent is needed.
func (*FsPath) Parents ¶
Parents returns an iterator of this path's logical parents.
Returns:
- A slice of FsPath instances representing all the logical parents of the path.
The first parent is the immediate parent of the path, and the last parent is the root path.
func (*FsPath) ParentsUpTo ¶
ParentsUpTo returns the parent directory path up to the specified number of levels.
Parameters:
- num: The number of directory levels to go up.
Returns:
- A new FSPath instance representing the parent directory path.
This method traverses up the directory tree by the specified number of levels. It works with both absolute and relative paths.
Examples:
- For an absolute path "/home/user/documents/file.txt": - ParentsUpTo(1) returns FSPath("/home/user/documents") - ParentsUpTo(2) returns FSPath("/home/user") - ParentsUpTo(3) returns FSPath("/home") - ParentsUpTo(4) or higher returns FSPath("/")
Note:
- If num is 0, it returns the current path.
- If num is greater than or equal to the number of directories in the path, it returns the root directory for absolute paths or "." for relative paths.
func (*FsPath) Parts ¶
Parts splits the path into its components. It takes the absolute path of the FSPath and returns a slice of strings, where each string is a component of the path.
The function preserves the leading "/" if present in the original path.
Examples:
For a path "/usr/bin/golang": parts := path.Parts() // parts will be []string{"/", "usr", "bin", "golang"} For a path "usr/bin/golang" (without leading slash): parts := path.Parts() // parts will be []string{"usr", "bin", "golang"} For the root directory "/": parts := path.Parts() // parts will be []string{"/"}
Note:
- Trailing slashes are ignored.
- Empty components (resulting from consecutive slashes) are omitted.
func (*FsPath) RelativeTo ¶
RelativeTo returns a relative path to p from the given path.
func (*FsPath) Rmdir ¶
Rmdir removes the empty directory pointed to by the path. If the directory is not empty, or if the path points to a file or a symbolic link, an error is returned.
Returns:
- error: nil if the operation was successful, otherwise an error explaining the failure.
Possible errors:
- If the path does not exist, it returns an os.ErrNotExist error.
- If the path is not a directory, it returns an error wrapping ErrNotDirectory.
- If the directory is not empty, it returns an error wrapping ErrDirectoryNotEmpty.
- Other errors may be returned depending on the underlying filesystem operation.
Example:
err := path.Rmdir() if err != nil { switch { case errors.Is(err, ErrNotDirectory): log.Println("Path is not a directory") case errors.Is(err, ErrDirectoryNotEmpty): log.Println("Directory is not empty") case os.IsNotExist(err): log.Println("Directory does not exist") default: log.Printf("Failed to remove directory: %v", err) } }
Note: This method only removes empty directories. It does not recursively remove directory contents.
func (*FsPath) Split ¶
SplitPath splits the given path into its directory and file name components.
Returns:
- dir: The directory portion of the path.
- name: The file name portion of the path.
Examples:
For a file path "/home/user/file.txt": - dir would be "/home/user/" - name would be "file.txt"
For a directory path "/home/user/docs/": - dir would be "/home/user/docs/" - name would be ""
For a root-level file "/file.txt": - dir would be "/" - name would be "file.txt"
Note: This method uses filepath.Split internally and works with both file and directory paths.
func (*FsPath) TSVGetSlices ¶
TSVGetSlices reads the TSV file and returns its content as slices.
This method reads the file at the FsPath's location as a TSV (Tab-Separated Values) file and returns its content as a slice of string slices. Each inner slice represents a row in the TSV file, with each string in the slice representing a field in that row.
Returns:
- [][]string: A slice of slices containing the TSV data.
- error: An error if the file cannot be read or parsed.
The method uses a tab character ('\t') as the field separator and '#' as the comment character. Empty lines and lines starting with '#' (after trimming spaces) are skipped.
Example usage:
data, err := path.TSVGetSlices() if err != nil { // handle error } for _, row := range data { // process each row }
Note: This method reads the entire file into memory. For very large files, consider using a streaming approach instead.
func (*FsPath) TarGzDir ¶
TarGzDir compresses the directory represented by this FsPath into a tar.gz file. The tar.gz file is created in the same folder as the directory.
Parameters:
- tarGzFileName: The name of the tar.gz file to be created. If it doesn't end with ".tar.gz", the ".tar.gz" extension will be automatically added.
Returns:
- *FsPath: A new FsPath representing the created tar.gz file.
- int: The total number of files compressed into the tar.gz file.
- error: An error if any step of the compression process fails.
The function performs the following steps:
- Checks if the current FsPath represents a directory.
- Prepares the compression by creating the tar.gz file.
- Creates a new gzip writer.
- Creates a new tar writer.
- Walks through the directory, adding each file to the tar archive.
- Closes the tar writer, gzip writer, and the file.
Possible errors include:
- ErrNotDirectory if the current FsPath is not a directory.
- I/O errors during file creation or writing.
- Errors encountered while walking the directory structure.
- Errors in creating tar headers or writing tar entries.
Example usage:
dirPath := Path("/path/to/directory") tarGzPath, fileCount, err := dirPath.TarGzDir("archive.tar.gz") if err != nil { log.Fatalf("Failed to create tar.gz: %v", err) } fmt.Printf("Created tar.gz at %s with %d files\n", tarGzPath, fileCount)
Note: This function compresses the entire directory structure, including subdirectories. Empty directories are included in the archive.
func (*FsPath) Touch ¶
Touch creates a new file or updates the modification time of an existing file. If the file doesn't exist, it is created with mode 0666 (before umask). If the file exists, its modification time is updated to the current time.
Returns:
- error: An error if the operation failed.
Example:
err := path.Touch() if err != nil { log.Fatal(err) }
func (*FsPath) Unlink ¶
Unlink removes the file or symbolic link pointed to by the path. If the path points to a directory, an error is returned.
Parameters:
- missingOK: If true, no error is returned if the file does not exist.
Returns:
- error: nil if the operation was successful, otherwise an error explaining the failure.
Possible errors:
- If the path does not exist and missingOK is false, it returns an os.ErrNotExist error.
- If the path points to a directory, it returns an error wrapping ErrCannotUnlinkDir.
- Other errors may be returned depending on the underlying filesystem operation.
Example:
err := path.Unlink(false) if err != nil { if errors.Is(err, ErrCannotUnlinkDir) { log.Println("Cannot unlink a directory") } else if os.IsNotExist(err) { log.Println("File does not exist") } else { log.Printf("Failed to unlink: %v", err) } }
Note: This method does not recursively remove directories. Use Rmdir() for removing empty directories.
func (*FsPath) Untar ¶
func (p *FsPath) Untar(destDir string, opts ...CompressOption) error
Untar extracts the contents of the tar file to the specified destination directory.
func (*FsPath) Unzip ¶
func (p *FsPath) Unzip(destDir string, opts ...CompressOption) error
Unzip extracts the contents of the zip file to the specified destination directory.
func (*FsPath) Walk ¶
Walk walks the file tree rooted at the FsPath, calling walkFn for each file or directory in the tree, including the root.
Walk follows symbolic links if they point to directories, but it does not follow symbolic links that point to files. It uses the afero.Walk function internally, which provides a consistent interface across different file systems.
Parameters:
walkFn: A function with the signature func(path string, info fs.FileInfo, err error) error This function is called for each file or directory visited by Walk.
The path argument contains the path to the file or directory, relative to the root of the Walk. The info argument is the fs.FileInfo for the file or directory. If there was a problem walking to the file or directory, the err argument will describe the problem. If an error is returned by the walkFn, the Walk will stop and return that error.
Returns:
- error: An error if the Walk function encounters any issues during traversal.
The walkFn may be called with a non-nil err argument for directory entries that could not be opened. If an error is returned by walkFn, Walk stops the traversal and returns the error.
The files are walked in lexical order, which makes the output deterministic but means that for very large directories Walk can be inefficient. Walk does not follow symbolic links unless they point to directories.
Example usage:
root := Path("/path/to/root") err := root.Walk(func(path string, info fs.FileInfo, err error) error { if err != nil { return err // Handle the error if you want to continue despite errors } fmt.Printf("Visited: %s\n", path) return nil }) if err != nil { log.Fatal(err) }
Note: This method uses relative paths in the walkFn to maintain consistency with the standard library's filepath.Walk function.
func (*FsPath) WithName ¶
WithName returns a new FSPath with the name changed.
This method creates a new FSPath instance with the same parent directory as the original, but with a different name. It's similar to Python's pathlib.Path.with_name() method.
Parameters:
- name: The new name for the file or directory.
Returns:
- A new FSPath instance with the updated name.
Examples:
For a file path "/home/user/file.txt": path.WithName("newfile.txt") would return a new FSPath for "/home/user/newfile.txt"
For a directory path "/home/user/docs/": path.WithName("newdocs") would return a new FSPath for "/home/user/newdocs"
For a root-level file "/file.txt": path.WithName("newfile.txt") would return a new FSPath for "/newfile.txt"
Note: This method does not actually rename the file or directory on the file system. It only creates a new FSPath instance with the updated name.
func (*FsPath) WithRenamedParentDir ¶
WithRenamedParentDir creates a new FSPath with the parent directory renamed.
This method generates a new FSPath that represents the current file or directory placed within a renamed parent directory. The new parent directory name replaces the current parent directory name at the same level in the path hierarchy.
Parameters:
- newParentName: The new name for the parent directory.
Returns:
- A new *FSPath instance representing the path with the renamed parent directory.
Behavior:
- For files: It creates a new path with the file in the renamed parent directory.
- For directories: It creates a new path with the current directory as a subdirectory of the renamed parent.
- For the root directory: It returns the original FSPath without changes.
Examples:
For a file "/tmp/a/b/file.txt" with newParentName "c": Result: FSPath representing "/tmp/a/c/file.txt"
For a directory "/tmp/a/b/" with newParentName "c": Result: FSPath representing "/tmp/a/c/b"
For a file "/file.txt" with newParentName "newdir": Result: FSPath representing "/newdir/file.txt"
For the root directory "/" with any newParentName: Result: FSPath representing "/" (unchanged)
Note:
- This method only generates a new FSPath and does not actually rename directories or move files on the filesystem.
- The method preserves the original file name or the last directory name in the new path.
- If the current path is the root directory, the method returns the original path unchanged.
Usage:
file := Path("/tmp/a/b/file.txt") newPath := file.WithRenamedParentDir("c") // newPath now represents "/tmp/a/c/file.txt"
func (*FsPath) WithReplacedDirAndSuffix ¶
func (*FsPath) WithSuffix ¶
func (*FsPath) WithSuffixAndSuffixedParentDir ¶
WithSuffixAndSuffixedParentDir generates a new file path with a changed suffix, and places it in a new directory named with the same suffix appended to the original parent directory name.
Parameters:
- newSuffix: The new file suffix (extension) to use, with or without the leading dot.
Returns:
- A new *FSPath representing the generated file path.
Behavior:
- Changes the file's suffix to the provided newSuffix.
- Appends the new suffix (without the dot) to the current parent directory name.
- For files in the root directory: Creates a new directory prefixed with an underscore and the new suffix (without the dot).
Examples:
File in subdirectory: "/path/to/file.txt" -> "/path/to_json/file.json"
File in root directory: "/file.txt" -> "/_json/file.json"
Notes:
- This method only generates a new FSPath and does not actually create any files or directories.
- If newSuffix is empty, the resulting file will have no extension, but the parent directory will still be renamed.
Usage:
file := Path("/tmp/docs/report.txt") newPath := file.WithSuffixAndSuffixedParentDir(".pdf") // newPath now represents "/tmp/docs_pdf/report.pdf"
func (*FsPath) WriteBytes ¶
WriteBytes writes the given byte slice to the file, creating the file if it doesn't exist, and overwriting it if it does.
func (*FsPath) WriteText ¶
WriteText writes the given string data to the file, creating the file if it doesn't exist, and overwriting it if it does.
func (*FsPath) ZipDir ¶
ZipDir compresses the directory represented by this FsPath into a zip file. The zip file is created in the same folder as the directory.
Parameters:
- zipFileName: The name of the zip file to be created. If it doesn't end with ".zip", the ".zip" extension will be automatically added.
Returns:
- *FsPath: A new FsPath representing the created zip file.
- int: The total number of files compressed into the zip file.
- error: An error if any step of the compression process fails.
The function performs the following steps:
- Checks if the current FsPath represents a directory.
- Prepares the compression by creating the zip file.
- Creates a new zip writer.
- Walks through the directory, adding each file to the zip archive.
- Closes the zip writer and the file.
Possible errors include:
- ErrNotDirectory if the current FsPath is not a directory.
- I/O errors during file creation or writing.
- Errors encountered while walking the directory structure.
Example usage:
dirPath := Path("/path/to/directory") zipPath, fileCount, err := dirPath.ZipDir("archive.zip") if err != nil { log.Fatalf("Failed to create zip: %v", err) } fmt.Printf("Created zip at %s with %d files\n", zipPath, fileCount)