avfs

package module
v0.33.0 Latest Latest
Warning

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

Go to latest
Published: May 21, 2023 License: Apache-2.0 Imports: 17 Imported by: 2

README

AVFS

Another Virtual File System for Go

CI codecov PkgGoDev Release License Built with Mage

Overview

AVFS is a virtual file system abstraction, inspired mostly by Afero and Go standard library. It provides an abstraction layer to emulate the behavior of a file system that provides several features :

  • a set of constants, interfaces and types for all file systems
  • a test suite for all file systems (emulated or real)
  • each file system has its own package
  • a very basic identity manager allows testing of user related functions (Chown, Lchown) and file system permissions

Additionally, some file systems support :

  • user file creation mode mask (Umask) (MemFS, OrefaFS)
  • chroot (OSFS on Linux)
  • hard links (MemFS, OrefaFS)
  • symbolic links (MemFS)
  • multiple users concurrently (MemFS)
  • Linux and Windows emulation regardless of host operating system (MemFS, OrefaFS)

Installation

This package can be installed with the go install command :

go install github.com/avfs/avfs@latest

It is only tested with Go version >= 1.18

Getting started

To make an existing code work with AVFS :

  • replace all references of os, path/filepath with the variable used to initialize the file system (vfs in the following examples)
  • import the packages of the file systems and, if necessary, the avfs package and initialize the file system variable.
  • some file systems provide specific options available at initialization. For instance MemFS needs WithSystemDirs option to create /home, /root and /tmp directories.

Examples

The example below demonstrates the creation of a file, a symbolic link to this file, for a different file systems (depending on an environment variable). Error management has been omitted for the sake of simplicity :

package main

import (
	"bytes"
	"log"
	"os"
	
	"github.com/avfs/avfs"
	"github.com/avfs/avfs/vfs/memfs"
	"github.com/avfs/avfs/vfs/osfs"
)

func main() {
	var vfs avfs.VFS

	switch os.Getenv("ENV") {
	case "PROD": // The real file system for production.
		vfs = osfs.NewWithNoIdm()
	default: // in memory for tests.
		vfs = memfs.New()
	}

	// From this point all references of 'os', 'path/filepath'
	// should be replaced by 'vfs'
	rootDir, _ := vfs.MkdirTemp("", "avfs")
	defer vfs.RemoveAll(rootDir)

	aFilePath := vfs.Join(rootDir, "aFile.txt")

	content := []byte("randomContent")
	_ = vfs.WriteFile(aFilePath, content, 0o644)

	aFilePathSl := vfs.Join(rootDir, "aFileSymlink.txt")
	_ = vfs.Symlink(aFilePath, aFilePathSl)

	gotContentSl, _ := vfs.ReadFile(aFilePathSl)
	if !bytes.Equal(content, gotContentSl) {
		log.Fatalf("Symlink %s : want content to be %v, got %v",
			aFilePathSl, content, gotContentSl)
	}

	log.Printf("content from symbolic link %s : %s", aFilePathSl, gotContentSl)
}
Multiple users creating simultaneously directories

The example below demonstrates the concurrent creation of subdirectories under a root directory by several users in different goroutines (works only with MemFS) :

package main

import (
	"fmt"
	"log"
	"sync"

	"github.com/avfs/avfs"
	"github.com/avfs/avfs/idm/memidm"
	"github.com/avfs/avfs/vfs/memfs"
)

func main() {
	const (
		maxUsers  = 100
		groupName = "test_users"
	)

	idm := memidm.New()
	vfs := memfs.New()

	rootDir, _ := vfs.MkdirTemp("", "avfs")
	vfs.Chmod(rootDir, 0o777)

	g, _ := idm.GroupAdd(groupName)

	var wg sync.WaitGroup
	wg.Add(maxUsers)

	for i := 0; i < maxUsers; i++ {
		go func(i int) {
			defer wg.Done()

			userName := fmt.Sprintf("user_%08d", i)
			idm.UserAdd(userName, g.Name())

			vfsU, _ := vfs.Sub("/")
			vfsU.SetUser(userName)

			path := vfsU.Join(rootDir, userName)
			vfsU.Mkdir(path, avfs.DefaultDirPerm)
		}(i)
	}

	wg.Wait()

	entries, _ := vfs.ReadDir(rootDir)

	log.Println("number of dirs :", len(entries))
	for _, entry := range entries {
		info, _ := entry.Info()
		sst := vfs.ToSysStat(info)

		u, _ := idm.LookupUserId(sst.Uid())

		log.Println("dir :", info.Name(),
			", mode :", info.Mode(),
			", owner :", u.Name())
	}
}

Status

Almost ready for Windows.

File systems

All file systems implement at least avfs.FS and avfs.File interfaces. By default, each file system supported methods are the most commonly used from packages os and path/filepath. All methods have identical names as their functions counterparts. The following file systems are currently available :

File system Comments
BasePathFS file system that restricts all operations to a given path within a file system
MemFS In memory file system supporting major features of a linux file system (hard links, symbolic links, chroot, umask)
OrefaFS Afero like in memory file system
OsFS Operating system native file system
RoFS Read only file system

Supported methods

File system methods
avfs.VFS
Comments
Abs equivalent to filepath.Abs
Base equivalent to filepath.Base
Chdir equivalent to os.Chdir
Chmod equivalent to os.Chmod
Chown equivalent to os.Chown
Chtimes equivalent to os.Chtimes
Clean equivalent to filepath.Clean
Create equivalent to os.Create
CreateTemp equivalent to os.CreateTemp
Dir equivalent to filepath.Dir
EvalSymlinks equivalent to filepath.EvalSymlinks
FromSlash equivalent to filepath.FromSlash
Features returns the set of features provided by the file system or identity manager
Getwd equivalent to os.Getwd
Glob equivalent to filepath.Glob
HasFeature returns true if the file system or identity manager provides a given feature
Idm returns the identity manager of the file system
IsAbs equivalent to filepath.IsAbs
IsPathSeparator equivalent to filepath.IsPathSeparator
Join equivalent to filepath.Join
Lchown equivalent to os.Lchown
Link equivalent to os.Link
Lstat equivalent to os.Lstat
Match equivalent to filepath.Match
Mkdir equivalent to os.Mkdir
MkdirAll equivalent to os.MkdirAll
MkdirTemp equivalent to os.MkdirTemp
Open equivalent to os.Open
OpenFile equivalent to os.OpenFile
OSType returns the operating system type of the file system
PathSeparator equivalent to os.PathSeparator
ReadDir equivalent to os.ReadDir
ReadFile equivalent to os.ReadFile
Readlink equivalent to os.Readlink
Rel equivalent to filepath.Rel
Remove equivalent to os.Remove
RemoveAll equivalent to os.RemoveAll
Rename equivalent to os.Rename
SameFile equivalent to os.SameFile
SetUMask sets the file mode creation mask
SetUser sets and returns the current user
Split equivalent to filepath.Split
Stat equivalent to os.Stat
Sub equivalent to fs.Sub
Symlink equivalent to os.Symlink
TempDir equivalent to os.TempDir
ToSlash equivalent to filepath.ToSlash
ToSysStat takes a value from fs.FileInfo.Sys() and returns a value that implements interface avfs.SysStater
Truncate equivalent to os.Truncate
UMask returns the file mode creation mask
User returns the current user
Utils returns the file utils of the current file system
WalkDir equivalent to filepath.WalkDir
WriteFile equivalent to os.WriteFile
File methods
avfs.File
Comments
Chdir equivalent to os.File.Chdir
Chmod equivalent to os.File.Chmod
Chown equivalent to os.File.Chown
Close equivalent to os.File.Close
Fd equivalent to os.File.Fd
Name equivalent to os.File.Name
Read equivalent to os.File.Read
ReadAt equivalent to os.File.ReadAt
ReadDir equivalent to os.File.ReadDir
Readdirnames equivalent to os.File.Readdirnames
Seek equivalent to os.File.Seek
Stat equivalent to os.File.Stat
Truncate equivalent to os.File.Truncate
Write equivalent to os.File.Write
WriteAt equivalent to os.File.WriteAt
WriteString equivalent to os.File.WriteString

Identity Managers

Identity managers allow users and groups management. The ones implemented in avfs are just here to allow testing of functions related to users (Chown, Lchown) and access rights, so they just allow one default group per user.

All file systems supporting identity manager implement by default the identity manager DummyIdm where all functions returns avfs.ErrPermDenied.

Identity Manager Comments
DummyIdm dummy identity manager where all functions are not implemented
MemIdm In memory identity manager
OsIdm Identity manager using os functions
SQLiteIdm Identity manager backed by a SQLite database
Identity Manager methods
avfs.FS
avfs.IdentityMgr
Comments
AdminGroup returns the administrator group (root for Linux)
AdminUser returns the administrator user (root for Linux)
GroupAdd adds a new group
GroupDel deletes an existing group
LookupGroup looks up a group by name
LookupGroupId looks up a group by groupid
LookupUser looks up a user by username
LookupUserId looks up a user by userid
UserAdd adds a new user
UserDel deletes an existing user

Documentation

Overview

Package avfs defines interfaces, errors types used by all file systems implementations.

Index

Constants

View Source
const (
	DefaultDirPerm  = fs.FileMode(0o777) // DefaultDirPerm is the default permission for directories.
	DefaultFilePerm = fs.FileMode(0o666) // DefaultFilePerm is the default permission for files.
	DefaultName     = "Default"          // DefaultName is the default name.
	DefaultVolume   = "C:"               // DefaultVolume is the default volume name for Windows.
	NotImplemented  = "not implemented"  // NotImplemented is the return string of a non-implemented feature.

	// FileModeMask is the bitmask used for permissions.
	FileModeMask = fs.ModePerm | fs.ModeSticky | fs.ModeSetuid | fs.ModeSetgid
)

Variables

This section is empty.

Functions

func AdminGroupName added in v0.3.2

func AdminGroupName(osType OSType) string

AdminGroupName returns the name of the administrator group of the file system.

func AdminUserName added in v0.3.2

func AdminUserName(osType OSType) string

AdminUserName returns the name of the administrator of the file system.

func CopyFile added in v0.3.2

func CopyFile(dstFs, srcFs VFSBase, dstPath, srcPath string) error

CopyFile copies a file between file systems and returns an error if any.

func CopyFileHash added in v0.3.2

func CopyFileHash(dstFs, srcFs VFSBase, dstPath, srcPath string, hasher hash.Hash) (sum []byte, err error)

CopyFileHash copies a file between file systems and returns the hash sum of the source file.

func DirExists added in v0.3.2

func DirExists(vfs VFSBase, path string) (bool, error)

DirExists checks if a path exists and is a directory.

func Exists added in v0.3.2

func Exists(vfs VFSBase, path string) (bool, error)

Exists Check if a file or directory exists.

func FromUnixPath added in v0.3.2

func FromUnixPath(path string) string

FromUnixPath returns valid path for Unix or Windows from a unix path. For Windows systems, absolute paths are prefixed with the default volume and relative paths are preserved.

func HashFile added in v0.3.2

func HashFile(vfs VFSBase, name string, hasher hash.Hash) (sum []byte, err error)

HashFile hashes a file and returns the hash sum.

func HomeDirPerm

func HomeDirPerm() fs.FileMode

HomeDirPerm return the default permission for home directories.

func IsDir added in v0.3.2

func IsDir(vfs VFSBase, path string) (bool, error)

IsDir checks if a given path is a directory.

func IsEmpty added in v0.3.2

func IsEmpty(vfs VFSBase, path string) (bool, error)

IsEmpty checks if a given file or directory is empty.

func SetUMask added in v0.3.2

func SetUMask(mask fs.FileMode)

SetUMask sets the file mode creation mask. Umask must be set to 0 using umask(2) system call to be read, so its value is cached and protected by a mutex.

func ShortPathName added in v0.3.2

func ShortPathName(path string) string

ShortPathName Retrieves the short path form of the specified path (Windows only).

func UMask added in v0.3.2

func UMask() fs.FileMode

UMask returns the file mode creation mask.

Types

type AlreadyExistsGroupError

type AlreadyExistsGroupError string

AlreadyExistsGroupError is returned when the group name already exists.

func (AlreadyExistsGroupError) Error

func (e AlreadyExistsGroupError) Error() string

type AlreadyExistsUserError

type AlreadyExistsUserError string

AlreadyExistsUserError is returned when the user name already exists.

func (AlreadyExistsUserError) Error

func (e AlreadyExistsUserError) Error() string

type ChRooter

type ChRooter interface {
	// Chroot changes the root to that specified in path.
	// If the user has not root privileges avfs.errPermDenied is returned.
	// If there is an error, it will be of type *PathError.
	Chroot(path string) error
}

ChRooter is the interface that wraps the Chroot method.

type Cloner

type Cloner interface {
	// Clone returns a shallow copy of the current file system (see MemFs).
	Clone() VFS
}

Cloner is the interface that wraps the Clone method.

type CustomError added in v0.3.2

type CustomError uintptr
const (
	ErrNegativeOffset      CustomError = customErrorBase + 1 // negative offset
	ErrFileClosing         CustomError = customErrorBase + 2 // use of closed file
	ErrPatternHasSeparator CustomError = customErrorBase + 3 // pattern contains path separator
	ErrVolumeAlreadyExists CustomError = customErrorBase + 4 // Volume already exists.
	ErrVolumeNameInvalid   CustomError = customErrorBase + 5 // Volume name is invalid.
	ErrVolumeWindows       CustomError = customErrorBase + 6 // Volumes are available for Windows only.
)

func (CustomError) Error added in v0.3.2

func (i CustomError) Error() string

func (CustomError) String added in v0.3.2

func (i CustomError) String() string

type DirInfo added in v0.3.2

type DirInfo struct {
	Path string
	Perm fs.FileMode
}

DirInfo contains information to create a directory.

type ErrorIdentifier added in v0.3.2

type ErrorIdentifier interface {
	error

	// Is returns true if the error can be treated as equivalent to a target error.
	// target is one of fs.ErrPermission, fs.ErrExist, fs.ErrNotExist.
	Is(target error) bool
}

ErrorIdentifier is the interface that wraps the Is method of an error.

type Errors added in v0.3.2

type Errors struct {
	BadFileDesc     error // bad file descriptor.
	DirNotEmpty     error // Directory not empty.
	FileExists      error // File exists.
	InvalidArgument error // invalid argument
	IsADirectory    error // File Is a directory.
	NoSuchDir       error // No such directory.
	NoSuchFile      error // No such file.
	NotADirectory   error // Not a directory.
	OpNotPermitted  error // operation not permitted.
	PermDenied      error // Permission denied.
	TooManySymlinks error // Too many levels of symbolic links.
}

Errors regroups errors depending on the OS emulated.

func (*Errors) SetOSType added in v0.3.2

func (e *Errors) SetOSType(osType OSType)

SetOSType sets errors depending on the operating system.

type Featurer

type Featurer interface {
	// Features returns the set of features provided by the file system or identity manager.
	Features() Features

	// HasFeature returns true if the file system or identity manager provides a given feature.
	HasFeature(feature Features) bool
}

Featurer is the interface that wraps the Features and HasFeature methods.

type Features added in v0.3.2

type Features uint64

Features defines the set of features available on a file system.

const (
	// FeatHardlink indicates that the file system supports hard links (link(), readlink() functions).
	FeatHardlink Features = 1 << iota

	// FeatIdentityMgr indicates that the file system features and identity manager and supports multiple users.
	FeatIdentityMgr

	// FeatSetOSType is set if the OS of the emulated file system can be changed (see MemFS).
	FeatSetOSType

	// FeatReadOnly is set for read only file systems (see RoFs).
	FeatReadOnly

	// FeatReadOnlyIdm is set when identity manager is read only (see OsIdm).
	FeatReadOnlyIdm

	// FeatRealFS indicates that the file system is a real one, not emulated (see OsFS).
	FeatRealFS

	// FeatSubFS allow to create a new file system from the subtree rooted at an arbitrary directory.
	FeatSubFS

	// FeatSymlink indicates that the file system supports symbolic links (symlink(), evalSymlink() functions).
	FeatSymlink

	// FeatSystemDirs is set when system directories  (/home, /root and /tmp for linux).
	FeatSystemDirs
)

func BuildFeatures added in v0.3.2

func BuildFeatures() Features

BuildFeatures returns the features available depending on build tags.

func (Features) String added in v0.3.2

func (i Features) String() string

type File

type File interface {
	fs.File
	fs.ReadDirFile
	io.Reader
	io.ReaderAt
	io.StringWriter
	io.Writer
	io.WriterAt
	io.WriteSeeker

	// Chdir changes the current working directory to the file,
	// which must be a directory.
	// If there is an error, it will be of type *PathError.
	Chdir() error

	// Chmod changes the mode of the file to mode.
	// If there is an error, it will be of type *PathError.
	Chmod(mode fs.FileMode) error

	// Chown changes the numeric uid and gid of the named file.
	// If there is an error, it will be of type *PathError.
	//
	// On Windows, it always returns the syscall.EWINDOWS error, wrapped
	// in *PathError.
	Chown(uid, gid int) error

	// Fd returns the integer Unix file descriptor referencing the open file.
	// The file descriptor is valid only until f.Close is called or f is garbage collected.
	// On Unix systems this will cause the SetDeadline methods to stop working.
	Fd() uintptr

	// Name returns the name of the file as presented to Open.
	Name() string

	// Readdirnames reads and returns a slice of names from the directory f.
	//
	// If n > 0, Readdirnames returns at most n names. In this case, if
	// Readdirnames returns an empty slice, it will return a non-nil error
	// explaining why. At the end of a directory, the error is io.EOF.
	//
	// If n <= 0, Readdirnames returns all the names from the directory in
	// a single slice. In this case, if Readdirnames succeeds (reads all
	// the way to the end of the directory), it returns the slice and a
	// nil error. If it encounters an error before the end of the
	// directory, Readdirnames returns the names read until that point and
	// a non-nil error.
	Readdirnames(n int) (names []string, err error)

	// Sync commits the current contents of the file to stable storage.
	// Typically, this means flushing the file system's in-memory copy
	// of recently written data to disk.
	Sync() error

	// Truncate changes the size of the file.
	// It does not change the I/O offset.
	// If there is an error, it will be of type *PathError.
	Truncate(size int64) error
}

File represents a file in the file system.

type GroupIdentifier added in v0.3.2

type GroupIdentifier interface {
	// Gid returns the primary group id.
	Gid() int
}

GroupIdentifier is the interface that wraps the Gid method.

type GroupReader

type GroupReader interface {
	GroupIdentifier
	Namer
}

GroupReader interface reads group information.

type IOFS added in v0.3.2

type IOFS interface {
	VFSBase
	fs.FS
	fs.GlobFS
	fs.ReadDirFS
	fs.ReadFileFS
	fs.StatFS
	fs.SubFS
}

IOFS is the virtual file system interface implementing io/fs interfaces.

type IdentityMgr

type IdentityMgr interface {
	Featurer
	OSTyper
	Typer

	// AdminGroup returns the administrator (root) group.
	AdminGroup() GroupReader

	// AdminUser returns the administrator (root) user.
	AdminUser() UserReader

	// GroupAdd adds a new group.
	// If the group already exists, the returned error is of type AlreadyExistsGroupError.
	GroupAdd(name string) (GroupReader, error)

	// GroupDel deletes an existing group.
	// If the group is not found, the returned error is of type UnknownGroupError.
	GroupDel(name string) error

	// LookupGroup looks up a group by name.
	// If the group is not found, the returned error is of type UnknownGroupError.
	LookupGroup(name string) (GroupReader, error)

	// LookupGroupId looks up a group by groupid.
	// If the group is not found, the returned error is of type UnknownGroupIdError.
	LookupGroupId(gid int) (GroupReader, error)

	// LookupUser looks up a user by username.
	// If the user cannot be found, the returned error is of type UnknownUserError.
	LookupUser(name string) (UserReader, error)

	// LookupUserId looks up a user by userid.
	// If the user cannot be found, the returned error is of type UnknownUserIdError.
	LookupUserId(uid int) (UserReader, error)

	// UserAdd adds a new user.
	// If the user already exists, the returned error is of type AlreadyExistsUserError.
	UserAdd(name, groupName string) (UserReader, error)

	// UserDel deletes an existing user.
	UserDel(name string) error
}

IdentityMgr interface manages identities (users and groups).

type LinuxError added in v0.3.2

type LinuxError uintptr

LinuxError replaces syscall.Errno for Linux operating systems.

const (
	ErrBadFileDesc     LinuxError = errEBADF     // bad file descriptor
	ErrCrossDevLink    LinuxError = errEXDEV     // invalid cross-device link
	ErrDirNotEmpty     LinuxError = errENOTEMPTY // directory not empty
	ErrFileExists      LinuxError = errEEXIST    // file exists
	ErrInvalidArgument LinuxError = errEINVAL    // invalid argument
	ErrIsADirectory    LinuxError = errEISDIR    // is a directory
	ErrNoSuchFileOrDir LinuxError = errENOENT    // no such file or directory
	ErrNotADirectory   LinuxError = errENOTDIR   // not a directory
	ErrOpNotPermitted  LinuxError = errEPERM     // operation not permitted
	ErrPermDenied      LinuxError = errEACCES    // permission denied
	ErrTooManySymlinks LinuxError = errELOOP     // too many levels of symbolic links

)

Errors for Linux operating systems. See https://github.com/torvalds/linux/blob/master/tools/include/uapi/asm-generic/errno-base.h

func (LinuxError) Error added in v0.3.2

func (i LinuxError) Error() string

Error returns the error string of the Linux operating system.

func (LinuxError) Is added in v0.3.2

func (i LinuxError) Is(target error) bool

Is returns true if the LinuxError can be treated as equivalent to a target error. target is one of fs.ErrPermission, fs.ErrExist, fs.ErrNotExist.

func (LinuxError) String added in v0.3.2

func (i LinuxError) String() string

type Namer

type Namer interface {
	Name() string
}

Namer is the interface that wraps the Name method.

type OSType added in v0.3.2

type OSType uint16

OSType defines the operating system type.

const (
	OsUnknown OSType = iota // Unknown
	OsLinux                 // Linux
	OsWindows               // Windows
	OsDarwin                // Darwin
)

func CurrentOSType added in v0.3.2

func CurrentOSType() OSType

CurrentOSType returns the current OSType.

func (OSType) String added in v0.3.2

func (i OSType) String() string

type OSTyper added in v0.3.2

type OSTyper interface {
	// OSType returns the operating system type of the file system.
	OSType() OSType
}

OSTyper is the interface that wraps the OSType method.

type OpenMode added in v0.3.2

type OpenMode uint16

OpenMode defines constants used by OpenFile and CheckPermission functions.

const (
	OpenLookup     OpenMode = 0o001     // OpenLookup checks for lookup permission on a directory.
	OpenWrite      OpenMode = 0o002     // OpenWrite opens or checks for write permission.
	OpenRead       OpenMode = 0o004     // OpenRead opens or checks for read permission.
	OpenAppend     OpenMode = 1 << iota // OpenAppend opens a file for appending (os.O_APPEND).
	OpenCreate                          // OpenCreate creates a file (os.O_CREATE).
	OpenCreateExcl                      // OpenCreateExcl creates a non existing file (os.O_EXCL).
	OpenTruncate                        // OpenTruncate truncates a file (os.O_TRUNC).
)

type PathIterator added in v0.3.2

type PathIterator[T VFSBase] struct {
	// contains filtered or unexported fields
}

PathIterator iterates through an absolute path. It returns each part of the path in successive calls to Next. The volume name (for Windows) is not considered as part of the path it is returned by VolumeName.

Sample code :

pi := NewPathIterator(vfs, path)
for pi.Next() {
  fmt.Println(pi.Part())
}

The path below shows the different results of the PathIterator methods when thirdPart is the current Part :

/firstPart/secondPart/thirdPart/fourthPart/fifthPart
                     |- Part --|
                   Start      End
|------- Left -------|         |------ Right ------|
|----- LeftPart ---------------|
                     |----------- RightPart -------|

func NewPathIterator added in v0.3.2

func NewPathIterator[T VFSBase](vfs T, path string) *PathIterator[T]

NewPathIterator creates a new path iterator from an absolute path.

func (*PathIterator[_]) End added in v0.3.2

func (pi *PathIterator[_]) End() int

End returns the end position of the current Part.

func (*PathIterator[_]) IsLast added in v0.3.2

func (pi *PathIterator[_]) IsLast() bool

IsLast returns true if the current Part is the last one.

func (*PathIterator[_]) Left added in v0.3.2

func (pi *PathIterator[_]) Left() string

Left returns the left path of the current Part.

func (*PathIterator[_]) LeftPart added in v0.3.2

func (pi *PathIterator[_]) LeftPart() string

LeftPart returns the left path and current Part.

func (*PathIterator[_]) Next added in v0.3.2

func (pi *PathIterator[_]) Next() bool

Next iterates through the next Part of the path. It returns false if there's no more parts.

func (*PathIterator[_]) Part added in v0.3.2

func (pi *PathIterator[_]) Part() string

Part returns the current Part.

func (*PathIterator[_]) Path added in v0.3.2

func (pi *PathIterator[_]) Path() string

Path returns the path to iterate.

func (*PathIterator[_]) ReplacePart added in v0.3.2

func (pi *PathIterator[_]) ReplacePart(newPath string) bool

ReplacePart replaces the current Part of the path with the new path. If the path iterator has been reset it returns true. It can be used in symbolic link replacement.

func (*PathIterator[_]) Reset added in v0.3.2

func (pi *PathIterator[_]) Reset()

Reset resets the iterator.

func (*PathIterator[_]) Right added in v0.3.2

func (pi *PathIterator[_]) Right() string

Right returns the right path of the current Part.

func (*PathIterator[_]) RightPart added in v0.3.2

func (pi *PathIterator[_]) RightPart() string

RightPart returns the right path and the current Part.

func (*PathIterator[_]) Start added in v0.3.2

func (pi *PathIterator[_]) Start() int

Start returns the start position of the current Part.

func (*PathIterator[_]) VolumeName added in v0.3.2

func (pi *PathIterator[_]) VolumeName() string

VolumeName returns leading volume name.

func (*PathIterator[_]) VolumeNameLen added in v0.3.2

func (pi *PathIterator[_]) VolumeNameLen() int

VolumeNameLen returns length of the leading volume name on Windows. It returns 0 elsewhere.

type RndTree added in v0.3.2

type RndTree struct {
	RndTreeOpts // RndTreeOpts regroups the options of the tree.
	// contains filtered or unexported fields
}

RndTree is a random file system tree generator of directories, files and symbolic links.

func NewRndTree added in v0.3.2

func NewRndTree(vfs VFSBase, opts *RndTreeOpts) *RndTree

NewRndTree returns a new random tree generator.

func (*RndTree) CreateDirs added in v0.3.2

func (rt *RndTree) CreateDirs(baseDir string) error

CreateDirs creates random directories.

func (*RndTree) CreateFiles added in v0.3.2

func (rt *RndTree) CreateFiles(baseDir string) error

CreateFiles creates random files.

func (rt *RndTree) CreateSymlinks(baseDir string) error

CreateSymlinks creates random symbolic links.

func (*RndTree) CreateTree added in v0.3.2

func (rt *RndTree) CreateTree(baseDir string) error

CreateTree creates a random tree structure.

func (*RndTree) Dirs added in v0.3.2

func (rt *RndTree) Dirs() []*RndTreeDir

func (*RndTree) Files added in v0.3.2

func (rt *RndTree) Files() []*RndTreeFile

func (*RndTree) GenTree added in v0.3.2

func (rt *RndTree) GenTree()

GenTree generates a random tree and populates RndTree.Dirs, RndTree.Files and RndTree.SymLinks.

func (rt *RndTree) SymLinks() []*RndTreeSymLink

type RndTreeDir added in v0.3.2

type RndTreeDir struct {
	Name  string
	Depth int
}

RndTreeDir contains parameters to create a directory.

type RndTreeFile added in v0.3.2

type RndTreeFile struct {
	Name string
	Size int
}

RndTreeFile contains parameters to create a file.

type RndTreeOpts added in v0.3.2

type RndTreeOpts struct {
	NbDirs      int // NbDirs is the number of directories.
	NbFiles     int // NbFiles is the number of files.
	NbSymlinks  int // NbSymlinks is the number of symbolic links.
	MaxFileSize int // MaxFileSize is maximum size of a file.
	MaxDepth    int // MaxDepth is the maximum depth of the tree.
}

RndTreeOpts defines the parameters to generate a random file system tree of directories, files and symbolic links.

type RndTreeSymLink struct {
	OldName, NewName string
}

RndTreeSymLink contains parameters to create a symbolic link.

type SysStater added in v0.3.2

type SysStater interface {
	GroupIdentifier
	UserIdentifier
	Nlink() uint64
}

SysStater is the interface returned by ToSysStat on all file systems.

type SystemDirMgr added in v0.3.2

type SystemDirMgr interface {
	// CreateHomeDir creates and returns the home directory of a user.
	// If there is an error, it will be of type *PathError.
	CreateHomeDir(u UserReader) (string, error)

	// CreateSystemDirs creates the system directories of a file system.
	CreateSystemDirs(basePath string) error

	// HomeDirUser returns the home directory of the user.
	// If the file system does not have an identity manager, the root directory is returned.
	HomeDirUser(u UserReader) string

	// SystemDirs returns the system directories of the file system.
	SystemDirs(basePath string) []DirInfo
}

SystemDirMgr is the interface that wraps system directories functions.

type Typer

type Typer interface {
	// Type returns the type of the fileSystem or Identity manager.
	Type() string
}

Typer is the interface that wraps the Type method.

type UnknownError

type UnknownError string

UnknownError is returned when there is an unknown error.

func (UnknownError) Error

func (e UnknownError) Error() string

type UnknownGroupError

type UnknownGroupError string

UnknownGroupError is returned by LookupGroup when a group cannot be found.

func (UnknownGroupError) Error

func (e UnknownGroupError) Error() string

type UnknownGroupIdError

type UnknownGroupIdError int

UnknownGroupIdError is returned by LookupGroupId when a group cannot be found.

func (UnknownGroupIdError) Error

func (e UnknownGroupIdError) Error() string

type UnknownUserError

type UnknownUserError string

UnknownUserError is returned by Lookup when a user cannot be found.

func (UnknownUserError) Error

func (e UnknownUserError) Error() string

type UnknownUserIdError

type UnknownUserIdError int

UnknownUserIdError is returned by LookupUserId when a user cannot be found.

func (UnknownUserIdError) Error

func (e UnknownUserIdError) Error() string

type UserIdentifier added in v0.3.2

type UserIdentifier interface {
	// Uid returns the user id.
	Uid() int
}

UserIdentifier is the interface that wraps the Uid method.

type UserReader

type UserReader interface {
	GroupIdentifier
	UserIdentifier
	Namer

	// IsAdmin returns true if the user has administrator (root) privileges.
	IsAdmin() bool
}

UserReader reads user information.

type UserSetter added in v0.3.2

type UserSetter interface {
	// SetUser sets and returns the current user.
	// If the user is not found, the returned error is of type UnknownUserError.
	SetUser(name string) (UserReader, error)

	// User returns the current user.
	User() UserReader
}

UserSetter is the interface that wraps the SetUser and User methods.

type Utils added in v0.3.2

type Utils[T VFSBase] struct {
	// contains filtered or unexported fields
}

Utils regroups common functions used by emulated file systems.

Most of these functions are extracted from Go standard library and adapted to be used indifferently on Unix or Windows system.

func (*Utils[T]) Abs added in v0.3.2

func (ut *Utils[T]) Abs(vfs T, path string) (string, error)

Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique. Abs calls Clean on the result.

func (*Utils[_]) Base added in v0.3.2

func (ut *Utils[_]) Base(path string) string

Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.

func (*Utils[_]) Clean added in v0.3.2

func (ut *Utils[_]) Clean(path string) string

Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

  1. Replace multiple Separator elements with a single one.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path, assuming Separator is '/'.

The returned path ends in a slash only if it represents a root directory, such as "/" on Unix or `C:\` on Windows.

Finally, any occurrences of slash are replaced by Separator.

If the result of this process is an empty string, Clean returns the string ".".

See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html

func (*Utils[T]) Create added in v0.3.2

func (*Utils[T]) Create(vfs T, name string) (File, error)

Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0666 (before umask). If successful, methods on the returned DummyFile can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

func (*Utils[T]) CreateHomeDir added in v0.3.2

func (ut *Utils[T]) CreateHomeDir(vfs T, u UserReader) (string, error)

CreateHomeDir creates and returns the home directory of a user. If there is an error, it will be of type *PathError.

func (*Utils[T]) CreateSystemDirs added in v0.3.2

func (ut *Utils[T]) CreateSystemDirs(vfs T, basePath string) error

CreateSystemDirs creates the system directories of a file system.

func (*Utils[T]) CreateTemp added in v0.3.2

func (ut *Utils[T]) CreateTemp(vfs T, dir, pattern string) (File, error)

CreateTemp creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file. The caller can use the file's Name method to find the pathname of the file. It is the caller's responsibility to remove the file when it is no longer needed.

func (*Utils[_]) Dir added in v0.3.2

func (ut *Utils[_]) Dir(path string) string

Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.

func (*Utils[_]) Features added in v0.3.2

func (ut *Utils[_]) Features() Features

Features returns the set of features provided by the file system or identity manager.

func (*Utils[_]) FromSlash added in v0.3.2

func (ut *Utils[_]) FromSlash(path string) string

FromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators.

func (*Utils[T]) Glob added in v0.3.2

func (ut *Utils[T]) Glob(vfs T, pattern string) (matches []string, err error)

Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in Match. The pattern may describe hierarchical names such as /usr/*/bin/ed (assuming the Separator is '/').

Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is ErrBadPattern, when pattern is malformed.

func (*Utils[_]) HasFeature added in v0.3.2

func (ut *Utils[_]) HasFeature(feature Features) bool

HasFeature returns true if the file system or identity manager provides a given features.

func (*Utils[_]) HomeDir added in v0.3.2

func (ut *Utils[_]) HomeDir() string

HomeDir returns the home directory of the file system.

func (*Utils[T]) HomeDirUser added in v0.3.2

func (ut *Utils[T]) HomeDirUser(u UserReader) string

HomeDirUser returns the home directory of the user. If the file system does not have an identity manager, the root directory is returned.

func (*Utils[_]) IsAbs added in v0.3.2

func (ut *Utils[_]) IsAbs(path string) bool

IsAbs reports whether the path is absolute.

func (*Utils[_]) IsExist added in v0.3.2

func (*Utils[_]) IsExist(err error) bool

IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists. It is satisfied by ErrExist as well as some syscall errors.

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrExist).

func (*Utils[_]) IsNotExist added in v0.3.2

func (*Utils[_]) IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist).

func (*Utils[_]) IsPathSeparator added in v0.3.2

func (ut *Utils[_]) IsPathSeparator(c uint8) bool

IsPathSeparator reports whether c is a directory separator character.

func (*Utils[_]) Join added in v0.3.2

func (ut *Utils[_]) Join(elem ...string) string

Join joins any number of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string. On Windows, the result will only be a UNC path if the first non-empty element is a UNC path.

func (*Utils[_]) Match added in v0.3.2

func (ut *Utils[_]) Match(pattern, name string) (matched bool, err error)

Match reports whether name matches the shell file name pattern. The pattern syntax is:

pattern:
	{ term }
term:
	'*'         matches any sequence of non-Separator characters
	'?'         matches any single non-Separator character
	'[' [ '^' ] { character-range } ']'
	            character class (must be non-empty)
	c           matches character c (c != '*', '?', '\\', '[')
	'\\' c      matches character c

character-range:
	c           matches character c (c != '\\', '-', ']')
	'\\' c      matches character c
	lo '-' hi   matches character c for lo <= c <= hi

Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.

On Windows, escaping is disabled. Instead, '\\' is treated as path separator.

func (*Utils[T]) MkdirTemp added in v0.3.2

func (ut *Utils[T]) MkdirTemp(vfs T, dir, pattern string) (string, error)

MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. If pattern includes a "*", the random string replaces the last "*" instead. If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when it is no longer needed.

func (*Utils[_]) OSType added in v0.3.2

func (ut *Utils[_]) OSType() OSType

OSType returns the operating system type of the file system.

func (*Utils[T]) Open added in v0.3.2

func (*Utils[T]) Open(vfs T, name string) (File, error)

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

func (*Utils[_]) OpenMode added in v0.3.2

func (*Utils[_]) OpenMode(flag int) OpenMode

OpenMode returns the open mode from the input flags.

func (*Utils[_]) PathSeparator added in v0.3.2

func (ut *Utils[_]) PathSeparator() uint8

PathSeparator return the OS-specific path separator.

func (*Utils[T]) ReadDir added in v0.3.2

func (*Utils[T]) ReadDir(vfs T, name string) ([]fs.DirEntry, error)

ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.

func (*Utils[T]) ReadFile added in v0.3.2

func (*Utils[T]) ReadFile(vfs T, name string) ([]byte, error)

ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

func (*Utils[_]) Rel added in v0.3.2

func (ut *Utils[_]) Rel(basepath, targpath string) (string, error)

Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it. Rel calls Clean on the result.

func (*Utils[_]) SetFeatures added in v0.3.2

func (ut *Utils[_]) SetFeatures(feature Features)

SetFeatures sets the features of the file system or identity manager.

func (*Utils[_]) SetOSType added in v0.3.2

func (ut *Utils[_]) SetOSType(osType OSType)

SetOSType sets the osType.

func (*Utils[_]) Split added in v0.3.2

func (ut *Utils[_]) Split(path string) (dir, file string)

Split splits path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.

func (*Utils[_]) SplitAbs added in v0.3.2

func (ut *Utils[_]) SplitAbs(path string) (dir, file string)

SplitAbs splits an absolute path immediately preceding the final Separator, separating it into a directory and file name component. If there is no Separator in path, splitPath returns an empty dir and file set to path. The returned values have the property that path = dir + PathSeparator + file.

func (*Utils[_]) SystemDirs added in v0.3.2

func (ut *Utils[_]) SystemDirs(basePath string) []DirInfo

SystemDirs returns an array of system directories always present in the file system.

func (*Utils[_]) TempDir added in v0.3.2

func (ut *Utils[_]) TempDir(userName string) string

TempDir returns the default directory to use for temporary files.

On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

The directory is neither guaranteed to exist nor have accessible permissions.

func (*Utils[_]) ToSlash added in v0.3.2

func (ut *Utils[_]) ToSlash(path string) string

ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.

func (*Utils[_]) VolumeName added in v0.3.2

func (ut *Utils[_]) VolumeName(path string) string

VolumeName returns leading volume name. Given "C:\foo\bar" it returns "C:" on Windows. Given "\\host\share\foo" it returns "\\host\share". On other platforms it returns "".

func (*Utils[_]) VolumeNameLen added in v0.3.2

func (ut *Utils[_]) VolumeNameLen(path string) int

VolumeNameLen returns length of the leading volume name on Windows. It returns 0 elsewhere.

func (*Utils[T]) WalkDir added in v0.3.2

func (ut *Utils[T]) WalkDir(vfs T, root string, fn fs.WalkDirFunc) error

WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.

The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.

WalkDir does not follow symbolic links.

func (*Utils[T]) WriteFile added in v0.3.2

func (*Utils[T]) WriteFile(vfs T, name string, data []byte, perm fs.FileMode) error

WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.

type VFS added in v0.3.2

type VFS interface {
	VFSBase

	// Open opens the named file for reading. If successful, methods on
	// the returned file can be used for reading; the associated file
	// descriptor has mode O_RDONLY.
	// If there is an error, it will be of type *PathError.
	Open(name string) (File, error)

	// Sub returns an FS corresponding to the subtree rooted at dir.
	Sub(dir string) (VFS, error)
}

VFS is the virtual file system interface. Any simulated or real file system should implement this interface.

type VFSBase added in v0.3.2

type VFSBase interface {
	Featurer
	Namer
	SystemDirMgr
	OSTyper
	Typer
	UserSetter

	// Abs returns an absolute representation of path.
	// If the path is not absolute it will be joined with the current
	// working directory to turn it into an absolute path. The absolute
	// path name for a given file is not guaranteed to be unique.
	// Abs calls Clean on the result.
	Abs(path string) (string, error)

	// Base returns the last element of path.
	// Trailing path separators are removed before extracting the last element.
	// If the path is empty, Base returns ".".
	// If the path consists entirely of separators, Base returns a single separator.
	Base(path string) string

	// Chdir changes the current working directory to the named directory.
	// If there is an error, it will be of type *PathError.
	Chdir(dir string) 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 *PathError.
	//
	// A different subset of the mode bits are used, depending on the
	// operating system.
	//
	// On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
	// ModeSticky are used.
	//
	// On Windows, only the 0200 bit (owner writable) of mode is used; it
	// controls whether the file's read-only attribute is set or cleared.
	// The other bits are currently unused. For compatibility with Go 1.12
	// and earlier, use a non-zero mode. Use mode 0400 for a read-only
	// file and 0600 for a readable+writable file.
	//
	// On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
	// and ModeTemporary are used.
	Chmod(name string, mode fs.FileMode) error

	// Chown changes the numeric uid and gid of the named file.
	// If the file is a symbolic link, it changes the uid and gid of the link's target.
	// A uid or gid of -1 means to not change that value.
	// If there is an error, it will be of type *PathError.
	//
	// On Windows or Plan 9, Chown always returns the syscall.EWINDOWS or
	// EPLAN9 error, wrapped in *PathError.
	Chown(name string, uid, gid int) error

	// Chtimes changes the access and modification times of the named
	// file, similar to the Unix utime() or utimes() functions.
	//
	// The underlying file system may truncate or round the values to a
	// less precise time unit.
	// If there is an error, it will be of type *PathError.
	Chtimes(name string, atime, mtime time.Time) error

	// Clean returns the shortest path name equivalent to path
	// by purely lexical processing. It applies the following rules
	// iteratively until no further processing can be done:
	//
	//	1. Replace multiple Separator elements with a single one.
	//	2. Eliminate each . path name element (the current directory).
	//	3. Eliminate each inner .. path name element (the parent directory)
	//	   along with the non-.. element that precedes it.
	//	4. Eliminate .. elements that begin a rooted path:
	//	   that is, replace "/.." by "/" at the beginning of a path,
	//	   assuming Separator is '/'.
	//
	// The returned path ends in a slash only if it represents a root directory,
	// such as "/" on Unix or `C:\` on Windows.
	//
	// Finally, any occurrences of slash are replaced by Separator.
	//
	// If the result of this process is an empty string, Clean
	// returns the string ".".
	//
	// See also Rob Pike, “Lexical File Names in Plan 9 or
	// Getting Dot-Dot Right,”
	// https://9p.io/sys/doc/lexnames.html
	Clean(path string) string

	// Create creates the named file with mode 0666 (before umask), truncating
	// it if it already exists. If successful, methods on the returned
	// File can be used for I/O; the associated file descriptor has mode
	// O_RDWR.
	// If there is an error, it will be of type *PathError.
	Create(name string) (File, error)

	// CreateTemp creates a new temporary file in the directory dir,
	// opens the file for reading and writing, and returns the resulting file.
	// The filename is generated by taking pattern and adding a random string to the end.
	// If pattern includes a "*", the random string replaces the last "*".
	// If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by TempDir.
	// Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file.
	// The caller can use the file's Name method to find the pathname of the file.
	// It is the caller's responsibility to remove the file when it is no longer needed.
	CreateTemp(dir, pattern string) (File, error)

	// Dir returns all but the last element of path, typically the path's directory.
	// After dropping the final element, Dir calls Clean on the path and trailing
	// slashes are removed.
	// If the path is empty, Dir returns ".".
	// If the path consists entirely of separators, Dir returns a single separator.
	// The returned path does not end in a separator unless it is the root directory.
	Dir(path string) string

	// EvalSymlinks returns the path name after the evaluation of any symbolic
	// links.
	// If path is relative the result will be relative to the current directory,
	// unless one of the components is an absolute symbolic link.
	// EvalSymlinks calls Clean on the result.
	EvalSymlinks(path string) (string, error)

	// FromSlash returns the result of replacing each slash ('/') character
	// in path with a separator character. Multiple slashes are replaced
	// by multiple separators.
	FromSlash(path string) string

	// Getwd returns a rooted path name corresponding to the
	// current directory. If the current directory can be
	// reached via multiple paths (due to symbolic links),
	// Getwd may return any one of them.
	Getwd() (dir string, err error)

	// Glob returns the names of all files matching pattern or nil
	// if there is no matching file. The syntax of patterns is the same
	// as in Match. The pattern may describe hierarchical names such as
	// /usr/*/bin/ed (assuming the Separator is '/').
	//
	// Glob ignores file system errors such as I/O errors reading directories.
	// The only possible returned error is ErrBadPattern, when pattern
	// is malformed.
	Glob(pattern string) (matches []string, err error)

	// Idm returns the identity manager of the file system.
	// if the file system does not have an identity manager, avfs.DummyIdm is returned.
	Idm() IdentityMgr

	// IsAbs reports whether the path is absolute.
	IsAbs(path string) bool

	// IsPathSeparator reports whether c is a directory separator character.
	IsPathSeparator(c uint8) bool

	// Join joins any number of path elements into a single path, adding a
	// separating slash if necessary. The result is Cleaned; in particular,
	// all empty strings are ignored.
	Join(elem ...string) string

	// Lchown changes the numeric uid and gid of the named file.
	// If the file is a symbolic link, it changes the uid and gid of the link itself.
	// If there is an error, it will be of type *PathError.
	//
	// On Windows, it always returns the syscall.EWINDOWS error, wrapped
	// in *PathError.
	Lchown(name string, uid, gid int) error

	// Link creates newname as a hard link to the oldname file.
	// If there is an error, it will be of type *LinkError.
	Link(oldname, newname string) 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.
	Lstat(name string) (fs.FileInfo, error)

	// Match reports whether name matches the shell file name pattern.
	// The pattern syntax is:
	//
	//	pattern:
	//		{ term }
	//	term:
	//		'*'         matches any sequence of non-Separator characters
	//		'?'         matches any single non-Separator character
	//		'[' [ '^' ] { character-range } ']'
	//		            character class (must be non-empty)
	//		c           matches character c (c != '*', '?', '\\', '[')
	//		'\\' c      matches character c
	//
	//	character-range:
	//		c           matches character c (c != '\\', '-', ']')
	//		'\\' c      matches character c
	//		lo '-' hi   matches character c for lo <= c <= hi
	//
	// Match requires pattern to match all of name, not just a substring.
	// The only possible returned error is ErrBadPattern, when pattern
	// is malformed.
	//
	// On Windows, escaping is disabled. Instead, '\\' is treated as
	// path separator.
	//
	Match(pattern, name string) (matched bool, err error)

	// Mkdir creates a new directory with the specified name and permission
	// bits (before umask).
	// If there is an error, it will be of type *PathError.
	Mkdir(name string, perm fs.FileMode) error

	// MkdirAll creates a directory named path,
	// along with any necessary parents, and returns nil,
	// or else returns an error.
	// The permission bits perm (before umask) are used for all
	// directories that MkdirAll creates.
	// If path is already a directory, MkdirAll does nothing
	// and returns nil.
	MkdirAll(path string, perm fs.FileMode) error

	// MkdirTemp creates a new temporary directory in the directory dir
	// and returns the pathname of the new directory.
	// The new directory's name is generated by adding a random string to the end of pattern.
	// If pattern includes a "*", the random string replaces the last "*" instead.
	// If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by TempDir.
	// Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory.
	// It is the caller's responsibility to remove the directory when it is no longer needed.
	MkdirTemp(dir, pattern string) (string, error)

	// OpenFile is the generalized open call; most users will use Open
	// or Create instead. It opens the named file with specified flag
	// (O_RDONLY etc.) and perm (before umask), if applicable. If successful,
	// methods on the returned File can be used for I/O.
	// If there is an error, it will be of type *PathError.
	OpenFile(name string, flag int, perm fs.FileMode) (File, error)

	// PathSeparator return the OS-specific path separator.
	PathSeparator() uint8

	// ReadDir reads the named directory,
	// returning all its directory entries sorted by filename.
	// If an error occurs reading the directory,
	// ReadDir returns the entries it was able to read before the error,
	// along with the error.
	ReadDir(name string) ([]fs.DirEntry, error)

	// ReadFile reads the file named by filename and returns the contents.
	// A successful call returns err == nil, not err == EOF. Because ReadFile
	// reads the whole file, it does not treat an EOF from Read as an error
	// to be reported.
	ReadFile(filename string) ([]byte, error)

	// Readlink returns the destination of the named symbolic link.
	// If there is an error, it will be of type *PathError.
	Readlink(name string) (string, error)

	// Rel returns a relative path that is lexically equivalent to targpath when
	// joined to basepath with an intervening separator. That is,
	// Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
	// On success, the returned path will always be relative to basepath,
	// even if basepath and targpath share no elements.
	// An error is returned if targpath can't be made relative to basepath or if
	// knowing the current working directory would be necessary to compute it.
	// Rel calls Clean on the result.
	Rel(basepath, targpath string) (string, error)

	// Remove removes the named file or (empty) directory.
	// If there is an error, it will be of type *PathError.
	Remove(name string) 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).
	RemoveAll(path string) error

	// Rename renames (moves) oldpath 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 *LinkError.
	Rename(oldpath, newpath string) error

	// SameFile reports whether fi1 and fi2 describe the same file.
	// For example, on Unix this means that the device and inode fields
	// of the two underlying structures are identical; on other systems
	// the decision may be based on the path names.
	// SameFile only applies to results returned by this package's Stat.
	// It returns false in other cases.
	SameFile(fi1, fi2 fs.FileInfo) bool

	// SetUMask sets the file mode creation mask.
	SetUMask(mask fs.FileMode)

	// Stat returns a FileInfo describing the named file.
	// If there is an error, it will be of type *PathError.
	Stat(name string) (fs.FileInfo, error)

	// Split splits path immediately following the final Separator,
	// separating it into a directory and file name component.
	// If there is no Separator in path, Split returns an empty dir
	// and file set to path.
	// The returned values have the property that path = dir+file.
	Split(path string) (dir, file string)

	// SplitAbs splits an absolute path immediately preceding the final Separator,
	// separating it into a directory and file name component.
	// If there is no Separator in path, splitPath returns an empty dir
	// and file set to path.
	// The returned values have the property that path = dir + PathSeparator + file.
	SplitAbs(path string) (dir, file string)

	// Symlink creates newname as a symbolic link to oldname.
	// If there is an error, it will be of type *LinkError.
	Symlink(oldname, newname string) error

	// TempDir returns the default directory to use for temporary files.
	//
	// On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
	// On Windows, it uses GetTempPath, returning the first non-empty
	// value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
	// On Plan 9, it returns /tmp.
	//
	// The directory is neither guaranteed to exist nor have accessible
	// permissions.
	TempDir() string

	// ToSlash returns the result of replacing each separator character
	// in path with a slash ('/') character. Multiple separators are
	// replaced by multiple slashes.
	ToSlash(path string) string

	// ToSysStat takes a value from fs.FileInfo.Sys() and returns a value that implements interface avfs.SysStater.
	ToSysStat(info fs.FileInfo) SysStater

	// Truncate changes the size of the named file.
	// If the file is a symbolic link, it changes the size of the link's target.
	// If there is an error, it will be of type *PathError.
	Truncate(name string, size int64) error

	// UMask returns the file mode creation mask.
	UMask() fs.FileMode

	// WalkDir walks the file tree rooted at root, calling fn for each file or
	// directory in the tree, including root.
	//
	// All errors that arise visiting files and directories are filtered by fn:
	// see the fs.WalkDirFunc documentation for details.
	//
	// The files are walked in lexical order, which makes the output deterministic
	// but requires WalkDir to read an entire directory into memory before proceeding
	// to walk that directory.
	//
	// WalkDir does not follow symbolic links.
	WalkDir(root string, fn fs.WalkDirFunc) error

	// WriteFile writes data to a file named by filename.
	// If the file does not exist, WriteFile creates it with permissions perm;
	// otherwise WriteFile truncates it before writing.
	WriteFile(filename string, data []byte, perm fs.FileMode) error
}

VFSBase regroups the common methods to VFS and IOFS.

type VolumeManager added in v0.3.2

type VolumeManager interface {
	// VolumeAdd adds a new volume to a Windows file system.
	// If there is an error, it will be of type *PathError.
	VolumeAdd(name string) error

	// VolumeDelete deletes an existing volume and all its files from a Windows file system.
	// If there is an error, it will be of type *PathError.
	VolumeDelete(name string) error

	// VolumeList returns the volumes of the file system.
	VolumeList() []string
}

VolumeManager is the interface that manage volumes for Windows file systems.

type WindowsError added in v0.3.2

type WindowsError uintptr

WindowsError replaces syscall.Errno for Windows operating systems.

const (
	ErrWinAccessDenied     WindowsError = 5          // Access is denied.
	ErrWinAlreadyExists    WindowsError = 183        // Cannot create a file when that file already exists.
	ErrWinBadNetPath       WindowsError = 53         // Bad network path.
	ErrWinDirNameInvalid   WindowsError = 0x10B      // The directory name is invalid.
	ErrWinDirNotEmpty      WindowsError = 145        // The directory is not empty.
	ErrWinFileExists       WindowsError = 80         // The file exists.
	ErrWinFileNotFound     WindowsError = 2          // The system cannot find the file specified.
	ErrWinIncorrectFunc    WindowsError = 1          // Incorrect function.
	ErrWinIsADirectory     WindowsError = 21         // is a directory
	ErrWinNegativeSeek     WindowsError = 0x83       // An attempt was made to move the file pointer before the beginning of the file.
	ErrWinNotReparsePoint  WindowsError = 4390       // The file or directory is not a reparse point.
	ErrWinInvalidHandle    WindowsError = 6          // The handle is invalid.
	ErrWinSharingViolation WindowsError = 32         // The process cannot access the file because it is being used by another process.
	ErrWinNotSupported     WindowsError = 0x20000082 // not supported by windows
	ErrWinPathNotFound     WindowsError = 3          // The system cannot find the path specified.
	ErrWinPrivilegeNotHeld WindowsError = 1314       // A required privilege is not held by the client.
)

Errors for Windows operating systems. See https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes

func (WindowsError) Error added in v0.3.2

func (i WindowsError) Error() string

Error returns the error string of the Windows operating system.

func (WindowsError) Is added in v0.3.2

func (i WindowsError) Is(target error) bool

Is returns true if the WindowsError can be treated as equivalent to a target error. target is one of fs.ErrPermission, fs.ErrExist, fs.ErrNotExist.

func (WindowsError) String added in v0.3.2

func (i WindowsError) String() string

Directories

Path Synopsis
idm
memidm
Package memidm implements an in memory identity manager.
Package memidm implements an in memory identity manager.
osidm
Package osidm implements an identity manager using os functions.
Package osidm implements an identity manager using os functions.
Package test implements a test suite available to all file systems.
Package test implements a test suite available to all file systems.
vfs
basepathfs
Package basepathfs restricts all operations to a given path within a file system.
Package basepathfs restricts all operations to a given path within a file system.
memfs
Package memfs implements an in memory file system.
Package memfs implements an in memory file system.
mountfs
Package mountfs implements a file system composed of different file systems.
Package mountfs implements a file system composed of different file systems.
orefafs
Package orefafs implements an Afero like in memory file system.
Package orefafs implements an Afero like in memory file system.
osfs
Package osfs implements a file system using functions from os and path/filepath packages.
Package osfs implements a file system using functions from os and path/filepath packages.
rofs
Package rofs provides a read only file system on top of any other Avfs file system.
Package rofs provides a read only file system on top of any other Avfs file system.

Jump to

Keyboard shortcuts

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