osutil

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: MIT Imports: 34 Imported by: 13

README

osutil GoDoc build

The os package of the std packages of Go does not support some functionality which is then implemented over and over again in a lot of projects. One example is to copy a file. This looks simple at first but is very complicated if everything has to be done right (e.g. permissions, ACLs, attributes, ...). osutil handles the simple cases which can be done right. If you have any ideas on how to improve this package or have problems of any kind with it, please submit an issue through the issue tracker.

Documentation

Index

Constants

View Source
const (
	// CompressionTypeNone indicates no compression.
	CompressionTypeNone = CompressionType("")
	// CompressionTypeGNUZipped indicates a GNU zipped compression.
	CompressionTypeGNUZipped = CompressionType("gz")
	// CompressionTypeXZ indicates a XZ compression.
	CompressionTypeXZ = CompressionType("xz")
)
View Source
const (
	// KernelVersionIdentifier holds the identifier for the kernel version OS information.
	KernelVersionIdentifier = "KernelVersion"
	// OperatingSystemIdentifier holds the identifier for the OS name OS information.
	OperatingSystemIdentifier = "ProductName"
	// OperatingSystemVersionIdentifier holds the identifier for the OS version OS information.
	OperatingSystemVersionIdentifier = "ProductVersion"
)
View Source
const (
	// Darwin holds the value of GOOS on MacOS.
	Darwin = "darwin"
	// Linux holds the value of GOOS on Linux.
	Linux = "linux"
	// Windows holds the value of GOOS on Windows.
	Windows = "windows"
)
View Source
const (
	// EnvironmentPathIdentifier holds the environment variable identifier for the "PATH" variable.
	EnvironmentPathIdentifier = "PATH"
)
View Source
const (
	// LineEnding holds the line ending for text files.
	LineEnding = "\n"
)

Variables

View Source
var (
	// ErrNotADirectory indicates that the given directory does not exist.
	ErrNotADirectory = errors.New("not a directory")
	// ErrNotAFile indicates thate the given file does not exist.
	ErrNotAFile = errors.New("not a file")
)
View Source
var ErrDirectoryNotEmpty = syscall.ENOTEMPTY

ErrDirectoryNotEmpty indicates that a directory is not empty.

View Source
var HTTPClient *http.Client = func() *http.Client {
	c := &http.Client{

		Transport: &http.Transport{
			Dial: (&net.Dialer{
				Timeout:   30 * time.Second,
				KeepAlive: 30 * time.Second,
			}).Dial,
			TLSHandshakeTimeout:   10 * time.Second,
			ResponseHeaderTimeout: 10 * time.Second,
			ExpectContinueTimeout: 1 * time.Second,
		},
		Timeout: 0,
	}
	c.Jar, _ = cookiejar.New(nil)

	return c
}()

HTTPClient defines an HTTP client with sane default settings.

Functions

func ActivityIndicator

func ActivityIndicator(stream io.Writer, description ...string) (stopIndicator func())

ActivityIndicator prints a spinning activity indicator to the given stream until the indicator is stopped.

func AnySliceToTypeSlice

func AnySliceToTypeSlice[T any](anySlice []any) (typeSlice []T)

AnySliceToTypeSlice returns a slice of the designated type with the values from the given "any" slice that match the type.

func AppendToFile

func AppendToFile(name string) (*os.File, error)

AppendToFile opens the named file. If the file does not exist it is created.

func BatchFileExtension

func BatchFileExtension() (extension string)

BatchFileExtension returns the common file extension of a batch file.

func BinaryExtension

func BinaryExtension() (extension string)

BinaryExtension returns the common file extension of a binary.

func CanonicalizeAndEvaluateSymlinks(path string) (resolvedPath string, err error)

CanonicalizeAndEvaluateSymlinks returns the path after canonicalizing it and the evaluation of any symbolic links.

func Capture

func Capture(call func()) (output []byte, err error)

Capture captures stderr and stdout of a given function call.

func CaptureWithCGo

func CaptureWithCGo(call func()) (output []byte, err error)

CaptureWithCGo captures stderr and stdout as well as stderr and stdout of C of a given function call. Currently this function cannot be nested.

func Chdir

func Chdir(workingDirectory string, call func() error) (err error)

Chdir temporarily changes to the given working directory while calling the given function.

func ChecksumForPath

func ChecksumForPath(path string) (digest []byte, err error)

ChecksumForPath computes a checksum of a file or directory.

func ChecksumsSHA256ForFiles

func ChecksumsSHA256ForFiles(filePath string) (err error)

ChecksumsSHA256ForFiles creates checksum-files with SHA-256 recursively for all files in a directory.

func CommandFileExtension

func CommandFileExtension() (extension string)

CommandFileExtension returns the common file extension of a command file.

func CompressDirectory

func CompressDirectory(srcDirectory string, archive string) (err error)

CompressDirectory reads the directory srcDirectory and writes a compressed version to archive.

func CopyFile

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

CopyFile copies a file from src to dst.

func CopyFileCompressed

func CopyFileCompressed(src string, dst string, compressionLevel int) (err error)

CopyFileCompressed reads the file src and writes a compressed version to dst. The compression level can be gzip.DefaultCompression, gzip.NoCompression, gzip.HuffmanOnly or any integer value between gzip.BestSpeed and gzip.BestCompression inclusive.

func CopyTree

func CopyTree(sourcePath string, destinationPath string) (err error)

CopyTree copies a whole file system tree from the source path to destination path.

func DirExists

func DirExists(filePath string) error

DirExists checks if a directory exists.

func DirectoriesRecursive

func DirectoriesRecursive(directoryPath string) (directories []string, err error)

DirectoriesRecursive returns all subdirectories of the given path including the given path.

func DirectoryPermissionOfParent

func DirectoryPermissionOfParent(path string) (permission fs.FileMode, err error)

DirectoryPermissionOfParent looks at parent directory of the given path and returns a directory permission based on the permission of the parent. The returned permission copies the read, write and execute permissions.

func DownloadFile

func DownloadFile(url string, filePath string) (err error)

DownloadFile downloads a file from the URL to the file path.

func DownloadFileWithProgress

func DownloadFileWithProgress(url string, filePath string) (err error)

DownloadFileWithProgress downloads a file from the URL to the file path while printing a progress to STDOUT.

func EnforceProcessTreeLimits

func EnforceProcessTreeLimits(limits ProcessTreeLimits)

EnforceProcessTreeLimits constrains the current process and all descendant processes to the specified limits. The current process exits when the limits are exceeded.

func EnvOrDefault

func EnvOrDefault(key string, defaultValue string) (value string)

EnvOrDefault returns the environment variable with the given key, or the default value if the key is not defined.

func EnvironMap added in v1.2.0

func EnvironMap() (environMap map[string]string)

EnvironMap returns a map of the current environment variables.

func EnvironmentPathList

func EnvironmentPathList() (filePaths []string)

EnvironmentPathList returns the list of file paths contained in the "PATH" environment variable.

func ExtractFile

func ExtractFile(archiveFilePath string, destinationPath string) (err error)

ExtractFile extracts a compressed file to a given path. How the archive is compressed and packed is automatically inferred, e.g. by the file extension.

func FileChange

func FileChange(filePath string, change func(data []byte) (changed []byte, err error)) error

FileChange changes the content of a file.

func FileExists

func FileExists(filePath string) error

FileExists checks if a file exists while following symlinks.

func FileOrSymlinkExists

func FileOrSymlinkExists(filepath string) error

FileOrSymlinkExists checks if a file exists while not following symlinks.

func FilePermissionOfParent

func FilePermissionOfParent(path string) (permission fs.FileMode, err error)

FilePermissionOfParent looks at parent directory of the given path and returns a file permission based on the permission of the parent. The returned permission copies the read and write permissions but not the execute permission.

func FilesRecursive

func FilesRecursive(path string) (files []string, err error)

FilesRecursive returns all files in a given path and its subpaths.

func ForEachFile

func ForEachFile(path string, handle func(filePath string) error) error

ForEachFile walks through the given path and calls the given callback with every file.

func GreatestCommonDirectory

func GreatestCommonDirectory(paths []string) string

GreatestCommonDirectory computes the greatest common part of the given paths. The resulting string must be the prefix of all the given paths.

func Info

func Info() (info map[string]string, err error)

Info returns a list of OS relevant information.

func IsArchitectureARMWith32Bit

func IsArchitectureARMWith32Bit() bool

IsArchitectureARMWith32Bit returns wheter the operating system runs on ARM with 32 bits.

func IsArchitectureARMWith64Bit

func IsArchitectureARMWith64Bit() bool

IsArchitectureARMWith64Bit returns wheter the operating system runs on ARM with 64 bits.

func IsArchitectureX86With32Bit

func IsArchitectureX86With32Bit() bool

IsArchitectureX86With32Bit returns wheter the operating system runs on x86 with 32 bits.

func IsArchitectureX86With64Bit

func IsArchitectureX86With64Bit() bool

IsArchitectureX86With64Bit returns wheter the operating system runs on x86 with 64 bits.

func IsDarwin

func IsDarwin() bool

IsDarwin returns whether the operating system is Darwin.

func IsEnvEnabled

func IsEnvEnabled(key string, additionalEnabledValues ...string) bool

IsEnvEnabled checks if the environment variable is enabled. By default an environment variable is considered enabled if it is set to "1", "true", "on" or "yes". Further such values can be provided as well. Capitalization is ignored.

func IsLinux

func IsLinux() bool

IsLinux returns whether the operating system is Linux.

func IsWindows

func IsWindows() bool

IsWindows returns whether the operating system is Windows.

func MakeFileCopyTargets

func MakeFileCopyTargets(sourceMakefilePath string, destinationMakefilePath string, makeTargets []string) (err error)

MakeFileCopyTargets copyies Make targets of a Makefile to another Makefile that can have a manually-writen parts until a `# REMARK Do not edit` line.

func MkdirAll

func MkdirAll(path string) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.

func ProgressBar

func ProgressBar(stream io.Writer, max int, description ...string) (progress *progressbar.ProgressBar)

ProgressBar returns a progress bar for counting items with sane defaults that prints its updates to the given writer.

func ProgressBarBytes

func ProgressBarBytes(stream io.Writer, length int, description ...string) (progress *progressbar.ProgressBar)

ProgressBarBytes returns a progress bar for counting bytes with sane defaults that prints its updates to the given writer.

func RemoveFileIfExists

func RemoveFileIfExists(filePath string) error

RemoveFileIfExists checks if a file exists, and removes the file if it does exist. Symlinks are not followed, since they are files and should be removable by this function.

func RemoveFromEnvironmentPathBySearchTerm

func RemoveFromEnvironmentPathBySearchTerm(searchTerms ...string) (newEnvironmentPath string)

RemoveFromEnvironmentPathBySearchTerm returns the content of the "PATH" environment variable where file paths containing the given search terms are removed.

func RemoveTemporaryDirectory

func RemoveTemporaryDirectory(directoryPath string)

RemoveTemporaryDirectory removes the given temporary directory path from disk with special handling for Windows. The reason we need special handling is because Windows seems to be colossally stupid when it comes to handling the open-ess of files and directories. https://$INTERNAL/symflower/symflower/-/merge_requests/2399#note_293837.

func ReplaceVariablesInFile

func ReplaceVariablesInFile(filePath string, variables map[string]string) (err error)

ReplaceVariablesInFile replaces all variables in a file. A variable in a file has the syntax `{{$key}}` and which is then replaced by its value.

func RequireEnv

func RequireEnv(key string) (value string, err error)

RequireEnv returns the environment variable with the given key, or an error if the key is not defined.

func RewriteStaticIndexFile

func RewriteStaticIndexFile(filePath string) (err error)

RewriteStaticIndexFile rewrites a `github.com/bouk/staticfiles` index file to be extendable by replacing inlined code to common code.

func SetRLimitFiles

func SetRLimitFiles(limit uint64, call func(limit uint64)) (err error)

SetRLimitFiles temporarily changes the file descriptor resource limit while calling the given function.

func Stat

func Stat(filePath string) (os.FileInfo, error)

Stat retuns a FileInfo structure describing the given file.

func Tar

func Tar(archiveFilePath string, path string) error

Tar archives a given path into a compressed TAR file.

func TarExtract

func TarExtract(stream io.Reader, destinationPath string, compressionType CompressionType) (err error)

TarExtract reads the gzip-compressed tar file from the reader and writes it into the destination path.

func TarExtractFile

func TarExtractFile(archiveFilePath string, destinationPath string) (err error)

TarExtractFile extracts a compressed TAR file to a given path.

func TestCapture

func TestCapture(t *testing.T)

func TestCaptureRecursive

func TestCaptureRecursive(t *testing.T)

func TestCaptureWithCGo

func TestCaptureWithCGo(t *testing.T)

func TestCaptureWithCGoWithHugeOutput

func TestCaptureWithCGoWithHugeOutput(t *testing.T)

func TestCaptureWithCGoWithPanic

func TestCaptureWithCGoWithPanic(t *testing.T)

func TestCaptureWithHugeOutput

func TestCaptureWithHugeOutput(t *testing.T)

func TestCaptureWithPanic

func TestCaptureWithPanic(t *testing.T)

func Uncompress

func Uncompress(archive io.Reader, dstDirectory string) (err error)

Uncompress extracts the given archive into the given destination.

func ValidateChecksumForPath

func ValidateChecksumForPath(path string, checksumFile string) (valid bool, err error)

ValidateChecksumForPath computes a checksum of a file or directory and returns an error if it does not match the checksum stored in the given file.

func WriteChecksumForPath

func WriteChecksumForPath(path string, checksumFile string) error

WriteChecksumForPath computes a checksum of a file or directory and writes it to the given file.

func ZipExtractFile

func ZipExtractFile(archiveFilePath string, destinationPath string) (err error)

ZipExtractFile extracts a zipped file to a given path.

Types

type CompressionType

type CompressionType string

CompressionType defines the compression type.

type FilePathsByHierarchy

type FilePathsByHierarchy []string

FilePathsByHierarchy sorts file paths by their hierarchy.

func (FilePathsByHierarchy) Len

func (s FilePathsByHierarchy) Len() int

Len is the number of elements in the collection.

func (FilePathsByHierarchy) Less

func (s FilePathsByHierarchy) Less(i, j int) bool

Less reports whether the element with index i must sort before the element with index j.

func (FilePathsByHierarchy) Swap

func (s FilePathsByHierarchy) Swap(i, j int)

Swap swaps the elements with indexes i and j.

type InMemoryStream

type InMemoryStream struct {
	// contains filtered or unexported fields
}

InMemoryStream allows to read and write to an in-memory stream.

func NewInMemoryStream

func NewInMemoryStream(reader io.ReadCloser, writer io.WriteCloser) *InMemoryStream

func (*InMemoryStream) Close

func (s *InMemoryStream) Close() error

Close closes the stream.

func (*InMemoryStream) Read

func (s *InMemoryStream) Read(buffer []byte) (n int, err error)

Read reads from the stream until the given buffer is full.

func (*InMemoryStream) Write

func (s *InMemoryStream) Write(data []byte) (n int, err error)

Write writes the given data to the stream.

type ProcessTreeLimits

type ProcessTreeLimits struct {
	// MaxMemoryInMiB holds the limit for the memory usage of the current process and all descendants in 1024-based mebibytes.
	// Zero means no limit.
	MaxMemoryInMiB uint
	// OnOutOfMemory may or may not run when the memory limit is reached, depending on the enforcement strategy. If it runs, the process will not be killed automatically and the function should end the process.
	OnMemoryLimitReached func(currentMemoryInMiB uint, maxMemoryInMiB uint)
	// WatchdogInterval holds the amount of time to sleep between checks if the limits have been exceeded, if a watchdog strategy is used.
	// The default is two seconds.
	WatchdogInterval time.Duration
}

ProcessTreeLimits holds limits to apply to the current process's resource usage, including the resource usage of its descendant processes.

type StandardStream

type StandardStream struct{}

StandardStream allows to read from STDIN and write to STDOUT.

func (*StandardStream) Close

func (s *StandardStream) Close() error

Close closes the stream.

func (*StandardStream) Read

func (s *StandardStream) Read(buffer []byte) (n int, err error)

Read reads from the stream until the given buffer is full.

func (*StandardStream) Write

func (s *StandardStream) Write(data []byte) (n int, err error)

Write writes the given data to the stream.

type StaticFile

type StaticFile struct {
	Data  string
	Mime  string
	Mtime time.Time
	// Size is the size before compression.
	// If 0, it means the data is uncompressed.
	Size int
	// Hash is a SHA-256 hash of the file contents, which is used for the Etag, and useful for caching.
	Hash string
	// Directory determines if this file is a directory.
	Directory bool
}

StaticFile holds a single file or directory in-memory.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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