Documentation
¶
Overview ¶
Package remotefs provides fs.FS implementations for remote filesystems.
Index ¶
- Constants
- Variables
- func DiscardPartial(fsys FS, url, dst string) error
- func Download(ctx context.Context, fsys FS, url, dst string, opts ...DownloadOption) error
- func HTTPStatusInsecure(ctx context.Context, fs FS, url string) (int, error)
- func PatchFile(fsys FS, path string, patches []Patch, opts ...PatchOption) error
- func PathError(op, path string, err error) *fs.PathError
- func PathErrorf(op, path string, template string, args ...any) *fs.PathError
- func RegisterDefaults(r *Registry)
- func RegisterPosix(r *Registry)
- func RegisterWindows(r *Registry)
- func Upload(fsys FS, src, dst string, opts ...UploadOption) error
- func WriteFileAtomic(host OS, path string, data []byte, perm fs.FileMode) error
- type Copier
- type DownloadOption
- type Downloader
- type FS
- type FSProvider
- type Factory
- type File
- type FileInfo
- func (f *FileInfo) FullPath() string
- func (f *FileInfo) Info() (fs.FileInfo, error)
- func (f *FileInfo) IsDir() bool
- func (f *FileInfo) ModTime() time.Time
- func (f *FileInfo) Mode() fs.FileMode
- func (f *FileInfo) Name() string
- func (f *FileInfo) Size() int64
- func (f *FileInfo) Sys() any
- func (f *FileInfo) Type() fs.FileMode
- func (f *FileInfo) UnmarshalJSON(b []byte) error
- type LineMatch
- type OS
- type Opener
- type Patch
- func AppendIfMissing(line string) Patch
- func DeleteMatching(match LineMatch) Patch
- func InsertAfter(match LineMatch, line string) Patch
- func InsertBefore(match LineMatch, line string) Patch
- func ReplaceOrAppend(match LineMatch, line string) Patch
- func Transform(fn func(lines []string) ([]string, error)) Patch
- type PatchOption
- type PosixDir
- type PosixFS
- func (s *PosixFS) Base(p string) string
- func (s *PosixFS) Chmod(name string, mode fs.FileMode) error
- func (s *PosixFS) Chown(name string, owner string) error
- func (s *PosixFS) ChownInt(name string, uid, gid int) error
- func (s *PosixFS) ChownTree(name string, owner string) error
- func (s *PosixFS) ChownTreeInt(name string, uid, gid int) error
- func (s *PosixFS) Chtimes(name string, atime, mtime int64) error
- func (s *PosixFS) CommandExist(name string) bool
- func (s *PosixFS) CreateTemp(dir, prefix string) (string, error)
- func (s *PosixFS) Dir(p string) string
- func (s *PosixFS) DownloadURL(url, dst string) error
- func (s *PosixFS) FileContains(name, substr string) (bool, error)
- func (s *PosixFS) FileExist(name string) bool
- func (s *PosixFS) Follow(ctx context.Context, path string, w io.Writer) error
- func (s *PosixFS) Getenv(key string) string
- func (s *PosixFS) Hostname() (string, error)
- func (s *PosixFS) IsContainer() (bool, error)
- func (s *PosixFS) Join(elem ...string) string
- func (s *PosixFS) LongHostname() (string, error)
- func (s *PosixFS) LookPath(name string) (string, error)
- func (s *PosixFS) MachineID() (string, error)
- func (s *PosixFS) Mkdir(name string, perm fs.FileMode) error
- func (s *PosixFS) MkdirAll(name string, perm fs.FileMode) error
- func (s *PosixFS) MkdirTemp(dir, prefix string) (string, error)
- func (s *PosixFS) NativePath(p string) string
- func (s *PosixFS) Open(name string) (fs.File, error)
- func (s *PosixFS) OpenFile(name string, flags int, perm fs.FileMode) (File, error)
- func (s *PosixFS) ReadDir(name string) ([]fs.DirEntry, error)
- func (s *PosixFS) ReadFile(filename string) ([]byte, error)
- func (s *PosixFS) Reboot(ctx context.Context) error
- func (s *PosixFS) Remove(name string) error
- func (s *PosixFS) RemoveAll(name string) error
- func (s *PosixFS) Rename(oldpath, newpath string) error
- func (s *PosixFS) Sha256(name string) (string, error)
- func (s *PosixFS) ShellQuote(str string) string
- func (s *PosixFS) Stat(name string) (fs.FileInfo, error)
- func (s *PosixFS) SystemTime() (time.Time, error)
- func (s *PosixFS) TempDir() string
- func (s *PosixFS) Touch(name string, ts ...time.Time) error
- func (s *PosixFS) Truncate(name string, size int64) error
- func (s *PosixFS) UserCacheDir() string
- func (s *PosixFS) UserConfigDir() string
- func (s *PosixFS) UserHomeDir() string
- func (s *PosixFS) WriteFile(filename string, data []byte, perm fs.FileMode) error
- type PosixFile
- func (f *PosixFile) Close() error
- func (f *PosixFile) CopyFrom(src io.Reader) (int64, error)
- func (f *PosixFile) CopyTo(dst io.Writer) (int64, error)
- func (w *PosixFile) Name() string
- func (f *PosixFile) Read(p []byte) (int, error)
- func (f *PosixFile) Seek(offset int64, whence int) (int64, error)
- func (f *PosixFile) Stat() (fs.FileInfo, error)
- func (f *PosixFile) Write(p []byte) (int, error)
- type Provider
- type Registry
- type Sha256summer
- type URLInfo
- type UploadOption
- type WinFS
- func (s *WinFS) Base(path string) string
- func (s *WinFS) Chmod(name string, mode fs.FileMode) error
- func (s *WinFS) Chown(name string, _ string) error
- func (s *WinFS) ChownInt(name string, _, _ int) error
- func (s *WinFS) ChownTree(name string, _ string) error
- func (s *WinFS) ChownTreeInt(name string, _, _ int) error
- func (s *WinFS) Chtimes(name string, atime, mtime int64) error
- func (s *WinFS) CommandExist(name string) bool
- func (s *WinFS) CreateTemp(dir, prefix string) (string, error)
- func (s *WinFS) Dir(path string) string
- func (s *WinFS) DownloadURL(url, dst string) error
- func (s *WinFS) FileContains(name, substr string) (bool, error)
- func (s *WinFS) FileExist(name string) bool
- func (s *WinFS) Follow(ctx context.Context, path string, w io.Writer) error
- func (s *WinFS) Getenv(key string) string
- func (s *WinFS) Hostname() (string, error)
- func (s *WinFS) IsContainer() (bool, error)
- func (s *WinFS) Join(elem ...string) string
- func (s *WinFS) LongHostname() (string, error)
- func (s *WinFS) LookPath(name string) (string, error)
- func (s *WinFS) MachineID() (string, error)
- func (s *WinFS) Mkdir(name string, _ fs.FileMode) error
- func (s *WinFS) MkdirAll(name string, _ fs.FileMode) error
- func (s *WinFS) MkdirTemp(dir, prefix string) (string, error)
- func (s *WinFS) NativePath(p string) string
- func (s *WinFS) Open(name string) (fs.File, error)
- func (s *WinFS) OpenFile(name string, flags int, _ fs.FileMode) (File, error)
- func (s *WinFS) ReadDir(name string) (entries []fs.DirEntry, err error)
- func (s *WinFS) ReadFile(name string) (contents []byte, err error)
- func (s *WinFS) Reboot(ctx context.Context) error
- func (s *WinFS) Remove(name string) error
- func (s *WinFS) RemoveAll(name string) error
- func (s *WinFS) Rename(oldpath, newpath string) error
- func (s *WinFS) Sha256(name string) (string, error)
- func (s *WinFS) ShellQuote(str string) string
- func (s *WinFS) Stat(name string) (fs.FileInfo, error)
- func (s *WinFS) SystemTime() (time.Time, error)
- func (s *WinFS) TempDir() string
- func (s *WinFS) Touch(name string, ts ...time.Time) error
- func (s *WinFS) Truncate(name string, size int64) error
- func (s *WinFS) UserCacheDir() string
- func (s *WinFS) UserConfigDir() string
- func (s *WinFS) UserHomeDir() string
- func (s *WinFS) WriteFile(name string, data []byte, mode fs.FileMode) (err error)
Constants ¶
const ( OpClose = "close" // OpClose Close operation OpOpen = "open" // OpOpen Open operation OpRead = "read" // OpRead Read operation OpRemove = "remove" // OpRemove Remove operation OpRemoveAll = "remove all" // OpRemoveAll RemoveAll operation OpSeek = "seek" // OpSeek Seek operation OpStat = "stat" // OpStat Stat operation OpWrite = "write" // OpWrite Write operation OpCopyTo = "copy-to" // OpCopyTo CopyTo operation OpCopyFrom = "copy-from" // OpCopyFrom CopyFrom operation )
Operation constants for remote filesystem operations.
Variables ¶
var ( // DefaultRegistry is the default registry of remote filesystem implementations. DefaultRegistry = sync.OnceValue(func() *Registry { r := NewRegistry() RegisterDefaults(r) return r }) // ErrNoFS is returned when no supported remote filesystem implementation is found. ErrNoFS = errors.New("no supported remote filesystem implementation found") )
var ( // ErrNilPatch is returned by PatchFile when a Patch with a nil apply function is encountered. ErrNilPatch = errors.New("patch has nil apply function") // ErrInvalidMatch is returned when a zero-value LineMatch (no matcher function set) is used. ErrInvalidMatch = errors.New("invalid line match: use ByPrefix, ByExact, ByContains, or ByRegex") // ErrMultilinePatch is returned by patch constructors when the line argument contains newline characters. ErrMultilinePatch = errors.New("patch line contains newline characters") // ErrNotRegularFile is returned by PatchFile when the target path is not a regular file. ErrNotRegularFile = errors.New("not a regular file") )
var ErrChecksumMismatch = errors.New("checksum mismatch")
ErrChecksumMismatch is returned when the checksum of the uploaded file does not match the local checksum.
var ErrDownloadNotSupported = errors.New("download not supported by this filesystem type")
ErrDownloadNotSupported is returned by the DownloadURL methods when the FS implementation cannot fetch URLs, so a caller can tell that apart from a transfer that was attempted and failed.
Download never raises it itself, since every remotefs.FS exposes DownloadURL for it to fall back to, but it does propagate one raised by the FS it was given -- so testing for it with errors.Is stays meaningful there.
var ErrEmptyMachineID = errors.New("machine-id: empty")
ErrEmptyMachineID is returned by MachineID when the host returns an empty value.
var ErrHTTPHeadNotSupported = errors.New("http head not supported by this filesystem type")
ErrHTTPHeadNotSupported is returned by HTTPHead when the FS implementation or the remote host cannot perform HTTP HEAD requests. Callers can detect this with errors.Is.
var ErrHTTPStatusNotSupported = errors.New("http status check not supported by this filesystem type")
ErrHTTPStatusNotSupported is returned by HTTPStatusInsecure when the FS implementation does not support HTTP status checks. Callers can detect this with errors.Is.
var ( // ErrNotSupported is returned when a function is not supported on Windows. ErrNotSupported = errors.New("not supported on windows") )
var ErrTimeout = fmt.Errorf("rigrcp session stalled: %w", context.DeadlineExceeded)
ErrTimeout is returned by operations on a file on a Windows host when the rigrcp session backing the file stops making progress for 30 seconds. That means the session has died -- typically the host went away mid-transfer without the shell ever being torn down on this end -- so the session is aborted when it happens: the remote helper is stopped and further operations on the file fail too. It wraps context.DeadlineExceeded, so a caller that does not want to depend on this sentinel can match that instead.
Functions ¶
func DiscardPartial ¶ added in v2.2.0
DiscardPartial removes the partially transferred file that a Download with WithResume leaves behind for this url and destination.
Call it when abandoning a download for good. The partial is deliberately kept across failures so that a later attempt can continue it, which means nothing else will ever remove it, and an abandoned one holds its bytes on the destination's filesystem indefinitely. For a large artifact that is the whole download sitting there unreferenced.
Having nothing to discard is not an error, so it is safe to call after a download that succeeded or never started one.
func Download ¶ added in v2.2.0
Download fetches url to dst on the remote host.
The transfer goes to a file beside dst and is renamed onto it only once it completes, so dst is never observed half-written.
Downloads are not retried here. A failed call returns its error and the caller decides whether to try again; see WithResume for making that retry continue where the last attempt stopped rather than starting over.
An FS from outside this package is transferred through its exported DownloadURL, so it still gets the atomic move and the url validation, but neither cancellation nor resume: both need the richer internal provider that PosixFS and WinFS implement.
func HTTPStatusInsecure ¶
HTTPStatusInsecure checks whether url is reachable and returns the HTTP status code, skipping TLS certificate verification. On Windows with PowerShell 5.x, TLS certificate verification is not skipped and requests will fail for self-signed certificates.
func PatchFile ¶
func PatchFile(fsys FS, path string, patches []Patch, opts ...PatchOption) error
PatchFile reads path, applies each patch in sequence, and writes the result back atomically via WriteFileAtomic. Existing permission bits (rwxrwxrwx) are preserved; setuid, setgid, and sticky bits are not. If the file does not exist and WithCreate is provided, the file is created with the given mode; otherwise ErrNotExist is returned. Non-regular files (directories, FIFOs, devices) are rejected with ErrNotRegularFile.
If path is a symlink, the link itself is replaced by the rewritten file; the symlink target is not modified. On platforms where stat follows symlinks (GNU Linux), the target's permission bits are preserved. On platforms where stat reports the link itself (BSD), symlink permissions are meaningless (0o777), so the replacement file is created with 0o600 instead.
CRLF handling: if the original file contains any CR+LF sequence, the entire output is written with CR+LF line endings. Files with mixed line endings are fully normalised to CRLF. Bare CR bytes (old Mac-style) are not treated as line endings and are left as-is. Otherwise LF is used throughout.
The trailing newline status of the original file is preserved: files that end with a newline will continue to do so; files that do not will not gain one. New files created via WithCreate get a trailing newline when the output is non-empty; an empty result (or an existing empty file) produces an empty file.
Because WriteFileAtomic replaces the original inode via a temp-file rename, only permission bits are restored. Owner, group, ACLs, extended attributes, hard links, and timestamps of the original file are not preserved.
PatchFile performs a read-then-write cycle without inter-process locking. A concurrent writer between the read and the rename will have its changes silently overwritten by the atomic rename.
If the patches produce output identical to the original content, WriteFileAtomic is skipped and the file (including any symlink) is left untouched.
func PathErrorf ¶
PathErrorf returns a fs.PathError with the given operation, path and error created using a sprintf style format string and arguments.
func RegisterDefaults ¶ added in v2.2.0
func RegisterDefaults(r *Registry)
RegisterDefaults registers the filesystem implementations rig ships with, which is what DefaultRegistry holds. Use it to build a registry of your own without having to list them, and without missing implementations added in later versions.
The factories are appended, so one of your own that has to take precedence over them must be registered before this call, or with Registry.RegisterFirst.
func RegisterPosix ¶
func RegisterPosix(r *Registry)
RegisterPosix registers the POSIX filesystem implementation.
func RegisterWindows ¶
func RegisterWindows(r *Registry)
RegisterWindows registers the Windows filesystem implementation.
func Upload ¶
func Upload(fsys FS, src, dst string, opts ...UploadOption) error
Upload a file to the remote host atomically: the content is written to a temporary file in the same directory as dst, verified via SHA-256, and then renamed into place. The temporary file is removed on failure, except when the remote session timed out: the connection is gone at that point, so the cleanup would block on it, and the file is left for the next upload.
Permissions: the temporary file is created with mode 0o600 and then chmod'd to perm before the rename. When WithPermissions is not given, perm is taken from the local file's mode. This means that overwriting an existing remote file always sets its mode to perm — unlike a direct truncating write, which would leave the remote file's existing mode unchanged.
func WriteFileAtomic ¶
WriteFileAtomic writes data to path atomically: a temp file is created in the same directory, written with restricted permissions, chmod'd to perm, then renamed into place. Parent directories are created as needed. Cleanup of the temp file is always attempted; if it fails the error is ignored.
Types ¶
type Copier ¶
type Copier interface {
CopyFrom(src io.Reader) (int64, error)
CopyTo(dst io.Writer) (int64, error)
}
Copier is a file-like struct that can copy data to and from io.Reader and io.Writer.
type DownloadOption ¶ added in v2.2.0
type DownloadOption func(*downloadOptions)
DownloadOption configures Download.
func WithResume ¶ added in v2.2.0
func WithResume() DownloadOption
WithResume keeps the partially transferred file when a download fails, and continues it on the next Download call for the same url and destination instead of starting over. Retrying is left to the caller; this only makes a retry cheap.
The partial is kept beside the destination under a name derived from both the destination and the url, so a later call can only continue a file that its own url and destination produced. Without this option a failed download leaves nothing behind.
Resuming assumes the bytes already on disk are a prefix of what the url serves now. That holds for an interrupted transfer of unchanging content, which is what versioned artifact URLs provide. It does not hold if the content behind the url is replaced between attempts: neither curl nor wget can detect that, and the result would be half of each version.
To catch that before spending a transfer on it, record the ETag or LastModified that HTTPHead reports for the url alongside the download, compare it before retrying, and call DiscardPartial when it has changed. A checksum over the finished file catches what no header can say.
Windows hosts always restart the transfer: Invoke-WebRequest under Windows PowerShell 5.1 cannot continue one. So does an FS from outside this package, which can only be driven through its exported DownloadURL. The partial is still kept and the result is still correct, so the option is safe to pass in both cases, it just saves nothing.
type Downloader ¶
Downloader can download content from a URL to a file on the remote host.
type FS ¶
type FS interface {
fs.FS
fs.StatFS
fs.ReadFileFS
fs.ReadDirFS
OS
Downloader
Opener
Sha256summer
}
FS is a filesystem on the remote host.
type FSProvider ¶
FSProvider is a function that returns a remote filesystem implementation given a runner.
type File ¶
File is a file in the remote filesystem.
func CreateTemp ¶
CreateTemp creates a new temporary file in the directory dir with a name built using the pattern, opens the file for reading and writing, and returns the resulting File. If dir is the empty string, CreateTemp uses the default directory for temporary files.
type FileInfo ¶
type FileInfo struct {
FName string `json:"name"`
FSize int64 `json:"size"`
FMode fs.FileMode `json:"mode"`
FUnix fs.FileMode `json:"unixMode"`
FModTime time.Time `json:"-"`
FIsDir bool `json:"isDir"`
ModtimeS int64 `json:"modTime"`
// contains filtered or unexported fields
}
FileInfo implements fs.FileInfo for stat on remote files.
func (*FileInfo) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type LineMatch ¶
type LineMatch struct {
// contains filtered or unexported fields
}
LineMatch matches a single text line. It is created by ByPrefix, ByExact, ByContains, or ByRegex and consumed by Patch constructors.
func ByContains ¶
ByContains returns a LineMatch that matches lines containing s.
type OS ¶
type OS interface {
Remove(path string) error
RemoveAll(path string) error
Mkdir(path string, perm fs.FileMode) error
MkdirAll(path string, perm fs.FileMode) error
MkdirTemp(dir, prefix string) (string, error)
CreateTemp(dir, prefix string) (string, error)
WriteFile(path string, data []byte, perm fs.FileMode) error
FileExist(path string) bool
LookPath(cmd string) (string, error)
Join(elem ...string) string
Chmod(path string, mode fs.FileMode) error
Chown(path string, owner string) error
ChownInt(path string, uid, gid int) error
ChownTree(path string, owner string) error
ChownTreeInt(path string, uid, gid int) error
Chtimes(path string, atime, mtime int64) error
Touch(path string, ts ...time.Time) error
Truncate(path string, size int64) error
Getenv(key string) string
Rename(oldpath, newpath string) error
FileContains(path, substr string) (bool, error)
Follow(ctx context.Context, path string, w io.Writer) error
IsContainer() (bool, error)
Hostname() (string, error)
LongHostname() (string, error)
MachineID() (string, error)
SystemTime() (time.Time, error)
TempDir() string
UserCacheDir() string
UserConfigDir() string
UserHomeDir() string
Dir(path string) string
Base(path string) string
CommandExist(name string) bool
Reboot(ctx context.Context) error
NativePath(path string) string
ShellQuote(s string) string
}
OS is a os/filesystem utility interface, these operations are modeled after stdlib's OS package.
type Patch ¶
type Patch struct {
// contains filtered or unexported fields
}
Patch is a single file-editing operation that transforms a slice of lines. Construct patches with ReplaceOrAppend, DeleteMatching, AppendIfMissing, InsertAfter, InsertBefore, or Transform.
func AppendIfMissing ¶
AppendIfMissing appends line if no existing line is exactly equal to it.
func DeleteMatching ¶
DeleteMatching removes all lines matching match.
func InsertAfter ¶
InsertAfter inserts line after the first line matching match. If no line matches, the file is left unchanged.
func InsertBefore ¶
InsertBefore inserts line before the first line matching match. If no line matches, the file is left unchanged.
func ReplaceOrAppend ¶
ReplaceOrAppend replaces the first line matching match with line, or appends line if no existing line matches.
type PatchOption ¶
type PatchOption func(*patchOptions)
PatchOption is a functional option for PatchFile.
func WithCreate ¶
func WithCreate(perm fs.FileMode) PatchOption
WithCreate causes PatchFile to create the file with the given permissions if it does not already exist. Without this option, PatchFile returns an error when the target file is missing.
type PosixDir ¶
type PosixDir struct {
PosixFile
// contains filtered or unexported fields
}
PosixDir implements fs.ReadDirFile for a remote directory.
type PosixFS ¶
type PosixFS struct {
cmd.Runner
log.LoggerInjectable
// contains filtered or unexported fields
}
PosixFS implements fs.FS for a remote filesystem that uses POSIX commands for access.
func NewPosixFS ¶
NewPosixFS returns a fs.FS implementation for a remote filesystem that uses POSIX commands for access.
func (*PosixFS) Chmod ¶
Chmod changes the mode of the named file to mode. The permission bits and the setuid, setgid and sticky bits are applied; the file type bits are ignored, as chmod has no representation for them.
func (*PosixFS) Chown ¶
Chown changes the ownership of the named file. The owner parameter follows the standard chown format: "user", "user:group", or ":group".
func (*PosixFS) ChownInt ¶
ChownInt changes the ownership of the named file using numeric uid and gid.
func (*PosixFS) ChownTree ¶
ChownTree recursively changes the ownership of path and all its contents. The owner parameter follows the standard chown format: "user", "user:group", or ":group".
func (*PosixFS) ChownTreeInt ¶
ChownTreeInt recursively changes the ownership of path and all its contents using numeric uid and gid.
func (*PosixFS) CommandExist ¶
CommandExist reports whether the named command is available on the remote host.
func (*PosixFS) CreateTemp ¶
CreateTemp creates a new temporary file in the directory dir with a name beginning with prefix and returns the path of the new file. If dir is empty, TempDir() is used.
func (*PosixFS) DownloadURL ¶
DownloadURL downloads the contents of url to dst.
The transfer goes to a temporary file next to dst and is renamed into place only once it completes, so an interrupted download never leaves a truncated file sitting at dst looking complete.
func (*PosixFS) FileContains ¶
FileContains reports whether the file at path contains the given substring. Returns a not-exist error if the file does not exist.
func (*PosixFS) Follow ¶
Follow streams new content appended to path to w until ctx is cancelled. Cancelling ctx is the expected way to stop following and does not return an error.
func (*PosixFS) IsContainer ¶
IsContainer reports whether the remote host is running inside a container (Docker, Podman, LXC, nspawn, etc.).
func (*PosixFS) Join ¶
Join joins any number of path elements into a single path, adding a separating slash if necessary.
func (*PosixFS) LongHostname ¶
LongHostname returns the FQDN of the host.
func (*PosixFS) Mkdir ¶
Mkdir creates a new directory with the specified name and permission bits.
The permission bits and the setgid, setuid and sticky bits of perm are applied; the file type bits are ignored.
func (*PosixFS) MkdirAll ¶
MkdirAll creates a new directory structure with the specified name and permission bits. If the directory already exists, MkDirAll does nothing and returns nil.
The permission bits of perm are applied to every directory that is created, like os.MkdirAll does; directories that already exist are left alone. The setgid, setuid and sticky bits of perm are applied to the last directory of the path only. The file type bits are ignored.
The mode comes from a umask instead of `install -d -m ...` because the uutils (Rust) reimplementation of coreutils, the default on Ubuntu 25.10 and later, applies -m only to the last component of the path while GNU install applies it to every directory it creates, leaving the intermediate directories at the remote default mode. A umask covers all of them, but only the nine permission bits, so the special bits need the trailing chmod.
Note that a perm without u+wx makes creating nested directories fail for a non-root user, as it does with os.MkdirAll: the intermediate directory can't be written to once it has been created.
func (*PosixFS) MkdirTemp ¶
MkdirTemp creates a new temporary directory in the directory dir with a name beginning with prefix and returns the path of the new directory.
func (*PosixFS) NativePath ¶
NativePath returns the path unchanged; on POSIX systems the native separator is already a forward slash.
func (*PosixFS) OpenFile ¶
OpenFile is used to open a file with access/creation flags for reading or writing. For info on flags, see https://pkg.go.dev/os#pkg-constants
func (*PosixFS) ReadDir ¶
ReadDir reads the directory named by dirname and returns a list of directory entries.
func (*PosixFS) Reboot ¶
Reboot triggers an immediate restart of the remote host. It first tries the simple 'reboot' command; if that fails with a logical error (not a transport tear-down), it falls back to 'shutdown -r now'. A transport-level error from either is treated as success since the kernel is already going down.
func (*PosixFS) Remove ¶
Remove deletes the named file. A path that does not exist is an error, matching os.Remove.
Unlike os.Remove it does not delete an empty directory: rm refuses one without an option POSIX does not require it to have. Use RemoveAll for a directory.
func (*PosixFS) RemoveAll ¶
RemoveAll removes path and any children it contains. A path that does not exist is not an error, matching os.RemoveAll.
func (*PosixFS) ShellQuote ¶
ShellQuote returns a shell-escaped version of str, safe for use as a single argument in a POSIX shell command.
func (*PosixFS) SystemTime ¶
SystemTime returns the current UTC time on the remote host. Note: date +%s is not POSIX but is supported on GNU coreutils, busybox, and macOS.
func (*PosixFS) Touch ¶
Touch creates a new empty file at path or updates the timestamps of an existing file. Without ts, both access and modification times are set to the current time. When ts is supplied, both times are set to the first timestamp provided.
func (*PosixFS) Truncate ¶
Truncate changes the size of the named file or creates a new file if it doesn't exist.
func (*PosixFS) UserCacheDir ¶
UserCacheDir returns the default root directory to use for user-specific cached data.
func (*PosixFS) UserConfigDir ¶
UserConfigDir returns the default root directory to use for user-specific configuration data.
func (*PosixFS) UserHomeDir ¶
UserHomeDir returns the current user's home directory.
func (*PosixFS) WriteFile ¶
WriteFile writes data to a file named by filename. Any missing parent directories are created.
The file is created via a shell redirect instead of `install -m ... /dev/stdin` because the uutils (Rust) reimplementation of coreutils, the default on Ubuntu 25.10 and later, fails with "install: No such file or directory" when the source is /dev/stdin and the destination already exists — which is exactly what writing to a mktemp'd file does. See https://github.com/uutils/coreutils/issues/12407.
The umask keeps a newly created file from being more permissive than perm while the content is written; the trailing chmod then applies perm's permission bits along with its setuid, setgid and sticky bits, also to a file that already existed. The file type bits of perm are ignored, as chmod has no representation for them. A umask only covers the nine permission bits, so the special bits come from the chmod alone — which is the safe ordering anyway, as the content is fully written by then. The umask is set after mkdir so that it does not affect the mode of the created parent directories.
Missing parent directories get the remote default mode (0777 minus the remote umask) instead of the fixed 0755 that GNU `install -D` used. Use MkdirAll if the parent directories need a specific mode.
type PosixFile ¶
type PosixFile struct {
// contains filtered or unexported fields
}
PosixFile implements fs.File for a remote file.
func (*PosixFile) Close ¶
Close closes the file, rendering it unusable for I/O. It returns an error, if any.
func (*PosixFile) Read ¶
Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered.
func (*PosixFile) Seek ¶
Seek sets the offset for the next Read or Write to offset, interpreted according to whence: io.SeekStart means relative to the origin of the file, io.SeekCurrent means relative to the current offset, and io.SeekEnd means relative to the end. Seek returns the new offset relative to the start of the file and an error, if any.
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider provides a unified interface to interact with the filesystem on a remote host. It ensures that a suitable remotefs.FS implementation is lazily initialized and made available for filesystem operations. It supports operations like opening files and implements io/fs.FS.
func NewRemoteFSProvider ¶
func NewRemoteFSProvider(get FSProvider, runner cmd.Runner) *Provider
NewRemoteFSProvider creates a new instance of Provider with the provided FSProvider function and runner.
type Sha256summer ¶
Sha256summer implementing struct can calculate sha256 checksum of a file.
type URLInfo ¶ added in v2.2.0
type URLInfo struct {
// StatusCode is the status of the final response, after any redirects.
StatusCode int
// ContentLength is the Content-Length of the final response, or -1 when the
// server did not report one, which happens under chunked transfer encoding.
ContentLength int64
// ETag is the entity tag exactly as the server sent it, including the quotes
// and any weak validator prefix, or empty when the server sent none. It is
// opaque: compare it for equality with a previously recorded value, never
// try to derive a content hash from it.
ETag string
// LastModified is the parsed Last-Modified header, or the zero time when the
// server sent none or it could not be parsed.
LastModified time.Time
// AcceptRanges reports whether the server advertised support for range
// requests.
AcceptRanges bool
}
URLInfo describes what an HTTP HEAD request reported about a URL. It carries the values that are useful for deciding whether a previously downloaded file is still current.
func HTTPHead ¶ added in v2.2.0
HTTPHead performs an HTTP HEAD request for url from the remote host and reports what the server said about it. Unlike HTTPStatusInsecure, TLS certificates are verified.
The request is made from the remote host rather than from the machine running rig, so the result reflects what that host can actually reach. This matters when the two do not share a view of the network, as with an internal mirror.
A non-2xx StatusCode is returned without an error; inspecting it is left to the caller. Servers that reject HEAD typically answer 405, which is reported the same way.
type UploadOption ¶
type UploadOption func(*uploadOptions)
UploadOption is a functional option for Upload.
func WithPermissions ¶
func WithPermissions(mode fs.FileMode) UploadOption
WithPermissions sets the file mode for the uploaded file. If not set, the local file's mode is used.
type WinFS ¶
type WinFS struct {
cmd.Runner
log.LoggerInjectable
}
WinFS is a fs.FS implemen{.
func NewWindowsFS ¶
NewWindowsFS returns a new fs.FS implementing filesystem for Windows targets.
func (*WinFS) Base ¶
Base returns the last element of path. Both forward and backward slashes are recognised as separators.
func (*WinFS) Chmod ¶
Chmod changes the mode of the named file to mode. On Windows, only the 0200 bit (owner writable) of mode is used: if set, the read-only attribute is cleared; if unset, it is set.
func (*WinFS) Chown ¶
Chown changes the ownership of the named file. On Windows it returns an error.
func (*WinFS) ChownInt ¶
ChownInt changes the ownership using numeric uid and gid. On Windows it returns an error.
func (*WinFS) ChownTree ¶
ChownTree recursively changes the ownership. On Windows it returns an error.
func (*WinFS) ChownTreeInt ¶
ChownTreeInt recursively changes the ownership using numeric uid and gid. On Windows it returns an error.
func (*WinFS) Chtimes ¶
Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions.
func (*WinFS) CommandExist ¶
CommandExist reports whether the named command is available on the remote host.
func (*WinFS) CreateTemp ¶
CreateTemp creates a new temporary file in the directory dir with a name beginning with prefix and returns the path of the new file. If dir is empty, TempDir() is used.
func (*WinFS) Dir ¶
Dir returns all but the last element of path, typically the path's directory. Both forward and backward slashes are recognised as separators.
func (*WinFS) DownloadURL ¶
DownloadURL downloads the contents of url to dst using Invoke-WebRequest.
The transfer goes to a temporary file next to dst and is renamed into place only once it completes, so an interrupted download never leaves a truncated file sitting at dst looking complete.
func (*WinFS) FileContains ¶
FileContains reports whether the file at path contains the given substring. Returns a not-exist error if the file does not exist.
func (*WinFS) FileExist ¶
FileExist checks if a file exists on the host. It is a more efficient shortcut for something like:
if _, err := fs.Stat(name); os.IsNotExist(err) { ... }
if !fs.FileExist(name) { ... }
func (*WinFS) Follow ¶
Follow streams new content appended to path to w until ctx is cancelled. Cancelling ctx is the expected way to stop following and does not return an error.
func (*WinFS) IsContainer ¶
IsContainer reports whether the host is running inside a container. Container detection is not supported on Windows.
func (*WinFS) Join ¶
Join joins any number of path elements into a single path, adding a separating slash if necessary.
func (*WinFS) LongHostname ¶
LongHostname resolves the FQDN (long) hostname.
func (*WinFS) Mkdir ¶
Mkdir creates a new directory with the specified name and permission bits. The permission bits are ignored on Windows.
func (*WinFS) MkdirAll ¶
MkdirAll creates a directory named path, along with any necessary parents. The permission bits are ignored on Windows.
func (*WinFS) MkdirTemp ¶
MkdirTemp creates a new temporary directory in the directory dir with a name beginning with prefix and returns the path of the new directory.
func (*WinFS) NativePath ¶
NativePath converts forward slashes in path to backslashes, returning a Windows-native path.
func (*WinFS) Open ¶
Open opens the named file for reading and returns fs.File. Use OpenFile to get a file that can be written to or if you need any of the methods not available on fs.File interface without type assertion.
func (*WinFS) OpenFile ¶
OpenFile opens the named remote file with the specified flags. os.O_EXCL and permission bits are ignored on Windows. For a description of the flags, see https://pkg.go.dev/os#pkg-constants
func (*WinFS) ReadDir ¶
ReadDir reads the directory named by dirname and returns a list of directory entries.
func (*WinFS) Reboot ¶
Reboot triggers an immediate restart of the remote host via a SYSTEM-context on-demand scheduled task running 'shutdown.exe /r /f /t 5'. Running via a scheduled task bypasses the filtered Administrator token used by WinRM sessions (e.g. on AWS EC2) which lacks SeShutdownPrivilege — issuing 'shutdown /r' directly in such a session is silently ignored by the OS.
The task is registered without a time-based trigger so it can only fire when explicitly started via Start-ScheduledTask. A best-effort Unregister-ScheduledTask is attempted in all cases.
func (*WinFS) Remove ¶
Remove deletes the named file or (empty) directory. A path that does not exist is an error, matching os.Remove.
Every failure is reported as a *fs.PathError whose Op is OpRemove, so a caller reading it sees the call it made rather than one of the commands used to carry it out.
func (*WinFS) RemoveAll ¶
RemoveAll deletes the named file or directory and all its child items. A path that does not exist is not an error, matching os.RemoveAll.
Failures are reported as a *fs.PathError whose Op is OpRemoveAll, on the same reasoning as Remove.
func (*WinFS) ShellQuote ¶
ShellQuote returns a single-quoted version of str, safe for use as a single argument in a PowerShell command. Single-quoting prevents PowerShell variable interpolation (e.g. $var, $()) and is safe with untrusted input.
func (*WinFS) SystemTime ¶
SystemTime returns the current UTC time on the remote host.
func (*WinFS) Touch ¶
Touch creates a new file with the given name if it does not exist. Without ts, the file's modification time is set to the current time. When ts is supplied, the file's modification time is set to the first timestamp provided.
func (*WinFS) UserCacheDir ¶
UserCacheDir returns the default root directory to use for user-specific non-essential data files.
func (*WinFS) UserConfigDir ¶
UserConfigDir returns the default root directory to use for user-specific configuration data.
func (*WinFS) UserHomeDir ¶
UserHomeDir returns the current user's home directory.