pathlib

package module
v0.3.1-0...-4fb7cb5 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2020 License: Apache-2.0 Imports: 7 Imported by: 0

README

pathlib

Build Status go.dev reference GitHub release (latest by date) codecov GitHub go.mod Go version License

Inspired by Python's pathlib, made better by Golang.

pathlib is an "object-oriented" package for manipulating filesystem path objects. It takes many cues from Python's pathlib, although it does not strictly adhere to its design philosophy. It provides a simple, intuitive, easy, and abstracted interface for dealing with many different types of filesystems.

pathlib is currently in the alpha stage of development, meaning the API is subject to change. However, the current state of the project is already proving to be highly useful.

Table of Contents

Examples

OsFs

Beacuse pathlib treats afero filesystems as first-class citizens, you can instantiate a Path object with the filesystem of your choosing.

Code
package main

import (
	"fmt"
	"os"

	"github.com/chigopher/pathlib"
	"github.com/spf13/afero"
)

func main() {
	// Create a path on your regular OS filesystem
	path := pathlib.NewPathAfero("/home/ltclipp", afero.NewOsFs())

	subdirs, err := path.ReadDir()
	if err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}

	for _, dir := range subdirs {
		fmt.Println(dir.Name())
	}
}
Output
[ltclipp@landon-virtualbox examples]$ go build .
[ltclipp@landon-virtualbox examples]$ ./examples | tail
Music
Pictures
Public
Templates
Videos
git
go
mockery_test
snap
software
In-memory FS
Code
package main

import (
	"fmt"
	"os"

	"github.com/chigopher/pathlib"
	"github.com/spf13/afero"
)

func main() {
	// Create a path using an in-memory filesystem
	path := pathlib.NewPathAfero("/", afero.NewMemMapFs())
	hello := path.Join("hello_world.txt")
	hello.WriteFile([]byte("hello world!"), 0o644)

	subpaths, err := path.ReadDir()
	if err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}

	for _, subpath := range subpaths {
		fmt.Printf("Name: %s Mode: %o Size: %d\n", subpath.Name(), subpath.Mode(), subpath.Size())
	}

	bytes, _ := hello.ReadFile()
	fmt.Println(string(bytes))
}
Output
[ltclipp@landon-virtualbox examples]$ go build
[ltclipp@landon-virtualbox examples]$ ./examples 
Name: hello_world.txt Mode: 644 Size: 12
hello world!

Design Philosophy

The design philosophy of this package is to be as thin of a layer as possible to existing community-standard packages, like io, afero, and os. Additional functionality is provided in consise and logical ways to extend the existing community APIs.

filepath.Path

The API of filepath.Path can be grouped into a few main categories:

  1. github.com/spf13/afero.Fs wrappers: these are methods that have nearly identical signatures to afero.Fs, with the exception of the path string (which is stored in the pathlib.Path object itself. afero.Fs is an object that is meant to interact directly with the filesystem.
  2. github.com/spf13/afero.Afero wrappers: these are methods that again have nearly identical signatures to afero.Afero. afero.Afero is a convenience object that provides higher-level behavior to the underlying afero.Fs object.
  3. Filesystem-specific methods: these are methods that are implemented by some, but not all, of the afero filesystems. These methods may fail at runtime if the filesystem you provide does not implement the required interface.
  4. Python's Pathlib-inspired methods: these are methods that are not implemented in the previous two steps, and that provide the power behind the object-oriented design.
  5. github.com/chigopher/pathlib-specific methods: these are miscellaneous methods that are not covered by any of the previous categories. These methods are typically conveniences around methods in one of the previous categories.
filepath.File

filepath.File is intended to be a thin wrapper around afero.File. We avoid simply returning this interface on calls to Open() and OpenFile() (etc) because we want the ability to extend our API beyond what afero provides. So, we create our own File object which embeds afero.File, but might possibly contain further functionality.

Frequently Asked Questions

Why pathlib and not filepath?

filepath is a package that is tightly coupled to the OS filesystem APIs and also is not written in an object-oriented way. pathlib uses afero under the hood for its abstracted filesystem interface, which allows you to represent a vast array of different filesystems (e.g. SFTP, HTTP, in-memory, and of course OS filesystems) using the same Path object.

Why not use afero directly?

You certainly could, however afero does not represent a filesystem object in an object-oriented way. It is only object-oriented with respect to the filesystem itself. pathlib is simply a thin layer on top of afero that provides the filesystem-object-orientation.

Does this provide any benefit to my unit tests?

Most certainly! pathlib allows you to create in-memory filesystems, which have the nice property of being automatically garbage collected by Golang's GC when they go out of scope. You don't have to worry about defering any Remove() functions or setting up temporary dirs in /tmp. Just instantiate a MemMapFs and you're good to go!

What filesystems does this support?

Currently only POSIX-style paths are supported.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDoesNotImplement = errors.Errorf("doesn't implement required interface")
)

Functions

This section is empty.

Types

type File

type File struct {
	afero.File
}

File represents a file in the filesystem. It inherits the afero.File interface but might also include additional functionality.

type Path

type Path struct {

	// DefaultFileMode is the mode that is used when creating new files in functions
	// that do not accept os.FileMode as a parameter.
	DefaultFileMode os.FileMode
	// contains filtered or unexported fields
}

Path is an object that represents a path

func Glob

func Glob(fs afero.Fs, pattern string) ([]*Path, error)

Glob returns all of the path objects matched by the given pattern inside of the afero filesystem.

func NewPath

func NewPath(path string) *Path

NewPath returns a new OS path

func NewPathAfero

func NewPathAfero(path string, fs afero.Fs) *Path

NewPathAfero returns a Path object with the given Afero object

func (*Path) Chmod

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

Chmod changes the file mode of the given path

func (*Path) Chtimes

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

Chtimes changes the modification and access time of the given path.

func (*Path) Create

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

Create creates a file if possible, returning the file and an error, if any happens.

func (*Path) DirExists

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

DirExists returns whether or not the path represents a directory that exists

func (*Path) Equals

func (p *Path) Equals(other *Path) (bool, error)

Equals returns whether or not the path pointed to by other has the same resolved filepath as self.

func (*Path) Exists

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

Exists returns whether the path exists

func (*Path) FileContainsAnyBytes

func (p *Path) FileContainsAnyBytes(subslices [][]byte) (bool, error)

FileContainsAnyBytes returns whether or not the path contains any of the listed bytes.

func (*Path) FileContainsBytes

func (p *Path) FileContainsBytes(subslice []byte) (bool, error)

FileContainsBytes returns whether or not the given file contains the bytes

func (*Path) Fs

func (p *Path) Fs() afero.Fs

Fs returns the internal afero.Fs object.

func (*Path) GetLatest

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

GetLatest returns the file or directory that has the most recent mtime. Only works if this path is a directory and it exists. If the directory is empty, the returned Path object will be nil.

func (*Path) Glob

func (p *Path) Glob(pattern string) ([]*Path, error)

Glob returns all matches of pattern relative to this object's path.

func (*Path) IsAbsolute

func (p *Path) IsAbsolute() bool

IsAbsolute returns whether or not the path is an absolute path. This is determined by checking if the path starts with a slash.

func (*Path) IsDir

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

IsDir checks if a given path is a directory.

func (*Path) IsEmpty

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

IsEmpty checks if a given file or directory is empty.

func (*Path) IsFile

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

IsFile returns true if the given path is a file.

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

IsSymlink returns true if the given path is a symlink. Fails if the filesystem doesn't implement afero.Lstater.

func (*Path) Join

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

Join joins the current object's path with the given elements and returns the resulting Path object.

func (*Path) Mkdir

func (p *Path) Mkdir(perm os.FileMode) error

Mkdir makes the current dir. If the parents don't exist, an error is returned.

func (*Path) MkdirAll

func (p *Path) MkdirAll(perm os.FileMode) error

MkdirAll makes all of the directories up to, and including, the given path.

func (*Path) Mtime

func (p *Path) Mtime() (time.Time, error)

Mtime returns the modification time of the given path.

func (*Path) Name

func (p *Path) Name() string

Name returns the string representing the final path component

func (*Path) Open

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

Open opens a file for read-only, returning it or an error, if any happens.

func (*Path) OpenFile

func (p *Path) OpenFile(flag int, perm os.FileMode) (*File, error)

OpenFile opens a file using the given flags and the given mode. See the list of flags at: https://golang.org/pkg/os/#pkg-constants

func (*Path) Parent

func (p *Path) Parent() *Path

Parent returns the Path object of the parent directory

func (*Path) Path

func (p *Path) Path() string

Path returns the string representation of the path

func (*Path) ReadDir

func (p *Path) ReadDir() ([]*Path, error)

ReadDir reads the current path and returns a list of the corresponding Path objects.

func (*Path) ReadFile

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

ReadFile reads the given path and returns the data. If the file doesn't exist or is a directory, an error is returned.

func (*Path) RelativeTo

func (p *Path) RelativeTo(other *Path) (*Path, error)

RelativeTo computes a relative version of path to the other path. For instance, if the object is /path/to/foo.txt and you provide /path/ as the argment, the returned Path object will represent to/foo.txt.

func (*Path) Remove

func (p *Path) Remove() error

Remove removes a file, returning an error, if any happens.

func (*Path) RemoveAll

func (p *Path) RemoveAll() error

RemoveAll removes the given path and all of its children.

func (*Path) Rename

func (p *Path) Rename(newname string) error

Rename renames a file

func (*Path) RenamePath

func (p *Path) RenamePath(target *Path) error

RenamePath is the same as Rename except the argument is a Path object. The attributes of the path object is retained and does not inherit anything from target.

func (*Path) Resolve

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

Resolve resolves the path to a real path

func (*Path) SafeWriteReader

func (p *Path) SafeWriteReader(r io.Reader) error

SafeWriteReader is the same as WriteReader but checks to see if file/directory already exists.

func (*Path) Stat

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

Stat returns the os.FileInfo of the given path

func (p *Path) Symlink(target *Path) error

Symlink symlinks to the target location. This will fail if the underlying afero filesystem does not implement afero.Linker.

func (*Path) Walk

func (p *Path) Walk(walkFn filepath.WalkFunc) error

Walk walks path, using the given filepath.WalkFunc to handle each

func (*Path) WriteFile

func (p *Path) WriteFile(data []byte, perm os.FileMode) error

WriteFile writes the given data to the path (if possible). If the file exists, the file is truncated. If the file is a directory, or the path doesn't exist, an error is returned.

func (*Path) WriteReader

func (p *Path) WriteReader(r io.Reader) error

WriteReader takes a reader and writes the content

Jump to

Keyboard shortcuts

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