fsutil

package
v12.125.1 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2024 License: Apache-2.0 Imports: 12 Imported by: 25

Documentation

Overview

Package fsutil provides methods for working with files on POSIX compatible systems

Package fsutil provides methods for working with files on POSIX compatible systems

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrEmptyPath = errors.New("Path is empty")

ErrEmptyPath can be returned by different methods if given path is empty and can't be used

Functions

func CheckPerms

func CheckPerms(perms, path string) bool

CheckPerms checks many permissions at once

Permissions:

  • F: is file
  • D: is directory
  • X: is executable
  • L: is link
  • W: is writable
  • R: is readable
  • B: is block device
  • C: is character device
  • S: not empty (only for files)
Example
dir := "/home/john"
file := dir + "/test.txt"

// Target is file, readable and non-empty
if CheckPerms("FRS", file) {
	fmt.Println("Everything fine!")
}

// Target is readable, writable and executable
if CheckPerms("RWX", file) {
	fmt.Println("Everything fine!")
}

// Target is directory, readable, writable and executable
if CheckPerms("DRWX", file) {
	fmt.Println("Everything fine!")
}
Output:

func CopyAttr added in v12.45.0

func CopyAttr(from, to string) error

CopyAttr copies attributes (mode, ownership, timestamps) from one object (file or directory) to another

Example
source := "/home/john/test1.txt"
target := "/home/john/test2.txt"

err := CopyAttr(source, target)

if err != nil {
	panic(err.Error())
}

fmt.Print("File attributes successfully copied")
Output:

func CopyDir

func CopyDir(from, to string) error

CopyDir copies directory content recursively to target directory

Example
target := "/home/john/documents"

err := CopyDir(target, "/home/bob/")

if err != nil {
	panic(err.Error())
}

fmt.Printf("Directory %s successfully copied to bob user directory\n", target)
Output:

func CopyFile

func CopyFile(from, to string, perms ...os.FileMode) error

CopyFile copies file using bufio with given permissions

Example
target := "/home/john/test.txt"
err := CopyFile(target, "/home/bob/test.txt", 0644)

if err != nil {
	panic(err.Error())
}

fmt.Printf("File %s successfully copied to bob user directory\n", target)

target = "/home/john/test.txt"

// Permissions and target file name are optional and can be omitted
err = CopyFile(target, "/home/bob")

if err != nil {
	panic(err.Error())
}

fmt.Printf("File %s successfully copied to bob user directory\n", target)
Output:

func CountLines

func CountLines(file string) (int, error)

CountLines returns number of lines in given file

Example
file := "/home/john/test.txt"

lineNum, err := CountLines(file)

if err != nil {
	panic(err.Error())
}

fmt.Printf("File %s contains %d lines of text\n", file, lineNum)
Output:

func GetATime

func GetATime(path string) (time.Time, error)

GetATime returns time of last access

Example
target := "/home/john/test.txt"
aTime, err := GetATime(target)

if err != nil {
	panic(err.Error())
}

fmt.Printf("Access timestamp (atime): %v\n", aTime)
Output:

func GetCTime

func GetCTime(path string) (time.Time, error)

GetCTime returns time of creation

Example
target := "/home/john/test.txt"
aTime, err := GetCTime(target)

if err != nil {
	panic(err.Error())
}

fmt.Printf("Change timestamp (ctime): %v\n", aTime)
Output:

func GetMTime

func GetMTime(path string) (time.Time, error)

GetMTime returns time of modification

Example
target := "/home/john/test.txt"
aTime, err := GetMTime(target)

if err != nil {
	panic(err.Error())
}

fmt.Printf("Modified timestamp (mtime): %v\n", aTime)
Output:

func GetMode

func GetMode(path string) os.FileMode

GetMode returns file mode bits

Example
target := "/home/john/test.txt"
mode := GetMode(target)

if mode != 0 {
	fmt.Printf("File mode: %v\n", mode)
}
Output:

func GetOwner

func GetOwner(path string) (int, int, error)

GetOwner returns object owner UID and GID

Example
target := "/home/john/test.txt"

uid, gid, err := GetOwner(target)

if err != nil {
	panic(err.Error())
}

fmt.Printf("Owner UID (User ID): %d\n", uid)
fmt.Printf("Owner GID (Group ID): %d\n", gid)
Output:

func GetSize

func GetSize(path string) int64

GetSize returns file size in bytes

Example
target := "/home/john/test.txt"
size := GetSize(target)

if size != -1 {
	fmt.Printf("File size: %d bytes\n", size)
}
Output:

func GetTimes

func GetTimes(path string) (time.Time, time.Time, time.Time, error)

GetTimes returns time of access, modification, and creation at once

func GetTimestamps

func GetTimestamps(path string) (int64, int64, int64, error)

GetTimestamps returns time of access, modification, and creation at once as unix timestamp

func IsBlockDevice

func IsBlockDevice(path string) bool

IsBlockDevice returns true if the given object is a device

Example
target := "/dev/sda"

if IsBlockDevice(target) {
	fmt.Printf("%s is a block device!\n", target)
} else {
	fmt.Printf("%s is NOT a block device!\n", target)
}
Output:

func IsCharacterDevice

func IsCharacterDevice(path string) bool

IsCharacterDevice returns true if the given object is a character device

Example
target := "/dev/tty0"

if IsCharacterDevice(target) {
	fmt.Printf("%s is a character device!\n", target)
} else {
	fmt.Printf("%s is NOT a character device!\n", target)
}
Output:

func IsDir

func IsDir(path string) bool

IsDir returns true if the given object is a directory

Example
target := "/home/john"

if IsDir(target) {
	fmt.Printf("%s is a directory!\n", target)
} else {
	fmt.Printf("%s is NOT a directory!\n", target)
}
Output:

func IsEmpty

func IsEmpty(path string) bool

IsEmpty returns true if given file is empty

Example
target := "/home/john/test.txt"

if IsEmpty(target) {
	fmt.Printf("%s is an empty file!\n", target)
} else {
	fmt.Printf("%s is NOT an empty file!\n", target)
}
Output:

func IsEmptyDir

func IsEmptyDir(path string) bool

IsEmptyDir returns true if given directory es empty

Example
target := "/home/john/myfiles"

if IsEmptyDir(target) {
	fmt.Printf("%s is an empty directory!\n", target)
} else {
	fmt.Printf("%s is NOT an empty directory!\n", target)
}
Output:

func IsExecutable

func IsExecutable(path string) bool

IsExecutable returns true if given object is executable by current user

Example
target := "/home/john/myapp"

if IsExecutable(target) {
	fmt.Printf("%s is executable!\n", target)
} else {
	fmt.Printf("%s is NOT executable!\n", target)
}
Output:

func IsExecutableByUser

func IsExecutableByUser(path, userName string) bool

IsExecutableByUser returns true if given object is executable by some user

Example
target := "/home/john/myapp"
user := "johndoe"

if IsExecutableByUser(target, user) {
	fmt.Printf("%s is executable for user %s!\n", target, user)
} else {
	fmt.Printf("%s is NOT executable for user %s!\n", target, user)
}
Output:

func IsExist

func IsExist(path string) bool

IsExist returns true if the given object is exist

Example
file := "/home/john/test.txt"

if IsExist(file) {
	fmt.Printf("File %s is found on system!\n", file)
} else {
	fmt.Printf("File %s does not exist!\n", file)
}
Output:

func IsLink(path string) bool

IsLink returns true if the given object is a link

func IsNonEmpty deprecated

func IsNonEmpty(path string) bool

IsNonEmpty returns true if given file is not empty

Deprecated: Use method IsEmpty instead

func IsReadable

func IsReadable(path string) bool

IsReadable returns true if given object is readable by current user

Example
target := "/home/john/test.txt"

if IsReadable(target) {
	fmt.Printf("%s is readable!\n", target)
} else {
	fmt.Printf("%s is NOT readable!\n", target)
}
Output:

func IsReadableByUser

func IsReadableByUser(path, userName string) bool

IsReadableByUser returns true if given object is readable by some user

Example
target := "/home/john/test.txt"
user := "johndoe"

if IsReadableByUser(target, user) {
	fmt.Printf("%s is readable for user %s!\n", target, user)
} else {
	fmt.Printf("%s is NOT readable for user %s!\n", target, user)
}
Output:

func IsRegular

func IsRegular(path string) bool

IsRegular returns true if the given object is a regular file

Example
target := "/home/john/test.txt"

if IsRegular(target) {
	fmt.Printf("%s is a regular file!\n", target)
} else {
	fmt.Printf("%s is NOT a regular file!\n", target)
}
Output:

func IsSocket

func IsSocket(path string) bool

IsSocket returns true if the given object is a socket

Example
target := "/var/run/myapp.sock"

if IsSocket(target) {
	fmt.Printf("%s is a socket file!\n", target)
} else {
	fmt.Printf("%s is NOT a socket file!\n", target)
}
Output:

func IsWritable

func IsWritable(path string) bool

IsWritable returns true if given object is writable by current user

Example
target := "/home/john/test.txt"

if IsWritable(target) {
	fmt.Printf("%s is writable!\n", target)
} else {
	fmt.Printf("%s is NOT writable!\n", target)
}
Output:

func IsWritableByUser

func IsWritableByUser(path, userName string) bool

IsWritableByUser returns true if given object is writable by some user

Example
target := "/home/john/test.txt"
user := "johndoe"

if IsWritableByUser(target, user) {
	fmt.Printf("%s is writable for user %s!\n", target, user)
} else {
	fmt.Printf("%s is NOT writable for user %s!\n", target, user)
}
Output:

func List

func List(dir string, ignoreHidden bool, filters ...ListingFilter) []string

List is lightweight method for listing directory

Example
dir := "/home/john/documents"

// List all objects including hidden (files and directories
// with the dot at the beginning of the file name)
objects := List(dir, false)

if len(objects) == 0 {
	fmt.Printf("Directory %s is empty", dir)
	return
}

fmt.Printf("Directory %s contains:\n", dir)

for _, object := range objects {
	fmt.Printf("  %s\n", object)
}
Output:

func ListAll

func ListAll(dir string, ignoreHidden bool, filters ...ListingFilter) []string

ListAll is lightweight method for listing all files and directories

Example
dir := "/home/john/documents"

// List all objects excluding hidden (files and directories
// with the dot at the beginning of the file name)
objects := ListAll(dir, true)

if len(objects) == 0 {
	fmt.Printf("Directory %s is empty", dir)
	return
}

fmt.Printf("Directory %s contains:\n", dir)

for _, object := range objects {
	fmt.Printf("  %s\n", object)
}
Output:

func ListAllDirs

func ListAllDirs(dir string, ignoreHidden bool, filters ...ListingFilter) []string

ListAllDirs is lightweight method for listing all directories

Example
target := "/home/john/documents"

// List all directories including hidden (directories
// with the dot at the beginning of the file name)
dirs := ListAllDirs(target, true)

if len(dirs) == 0 {
	fmt.Printf("Directory %s is empty", target)
	return
}

fmt.Printf("Directory %s contains:\n", target)

for _, dir := range dirs {
	fmt.Printf("  %s\n", dir)
}
Output:

func ListAllFiles

func ListAllFiles(dir string, ignoreHidden bool, filters ...ListingFilter) []string

ListAllFiles is lightweight method for listing all files

Example
target := "/home/john/documents"

// List all files including hidden (files with the dot
// at the beginning of the file name)
files := ListAllFiles(target, true)

if len(files) == 0 {
	fmt.Printf("Directory %s is empty", target)
	return
}

fmt.Printf("Directory %s contains:\n", target)

for _, file := range files {
	fmt.Printf("  %s\n", file)
}
Output:

func ListToAbsolute

func ListToAbsolute(path string, list []string)

ListToAbsolute converts slice with relative paths to slice with absolute paths

Example
dir := "/home/john/documents"

// List all objects including hidden (files and directories
// with the dot at the beginning of the file name)
objects := List(dir, false)

if len(objects) == 0 {
	fmt.Printf("Directory %s is empty", dir)
	return
}

// The method adds the path to the beginning of every item in the slice
ListToAbsolute(dir, objects)
Output:

func MoveFile

func MoveFile(from, to string, perms ...os.FileMode) error

MoveFile moves file

Example
target := "/home/john/test.txt"
err := MoveFile(target, "/home/bob/test.txt", 0644)

if err != nil {
	panic(err.Error())
}

fmt.Printf("File %s successfully moved to bob user directory\n", target)

target = "/home/john/test.txt"

// Permissions and target file name are optional and can be omitted
err = MoveFile(target, "/home/bob/")

if err != nil {
	panic(err.Error())
}

fmt.Printf("File %s successfully moved to bob user directory\n", target)
Output:

func Pop

func Pop() string

Pop changes current working directory to previous in stack

Example
// Current working directory is the directory where binary was executed

cwd := Push("/home/john/documents")

// Current working directory set to /home/john/documents

cwd = Push("/home/john/documents/work")
fmt.Println(cwd)

// Current working directory set to /home/john/documents/work

fmt.Println(cwd)
cwd = Pop()

// Current working directory set to /home/john/documents

cwd = Pop()
fmt.Println(cwd)

// Current working directory set to initial working directory
Output:

func ProperPath

func ProperPath(perms string, paths []string) string

ProperPath returns the first proper path from a given slice

Permissions:

  • F: is file
  • D: is directory
  • X: is executable
  • L: is link
  • W: is writable
  • R: is readable
  • B: is block device
  • C: is character device
  • S: not empty (only for files)
Example
paths := []string{
	"/home/john/.config/myapp/config",
	"/home/john/.myappconfig",
	"/etc/myapp.conf",
}

config := ProperPath("FRS", paths)

if config != "" {
	fmt.Printf("Used configuration file: %s\n", config)
} else {
	fmt.Println("Can't find configuration file")
}
Output:

func Push

func Push(dir string) string

Push changes current working directory and add previous working directory to stack

Example
// Current working directory is the directory where binary was executed

cwd := Push("/home/john/documents")

// Current working directory set to /home/john/documents

cwd = Push("/home/john/documents/work")
fmt.Println(cwd)

// Current working directory set to /home/john/documents/work

cwd = Pop()
fmt.Println(cwd)

// Current working directory set to /home/john/documents

cwd = Pop()
fmt.Println(cwd)

// Current working directory set to initial working directory
Output:

func TouchFile

func TouchFile(path string, perm os.FileMode) error

TouchFile creates empty file

Example
err := TouchFile("/srv/myapp/.lock", 0600)

if err != nil {
	panic(err.Error())
}

fmt.Println("Lock file successfully created!")
Output:

func ValidatePerms

func ValidatePerms(perms, path string) error

ValidatePerms validates permissions for file or directory

Permissions:

  • F: is file
  • D: is directory
  • X: is executable
  • L: is link
  • W: is writable
  • R: is readable
  • B: is block device
  • C: is character device
  • S: not empty (only for files)
Example
dir := "/home/john"
file := dir + "/test.txt"

// Target is file, readable and non-empty
err := ValidatePerms("FRS", file)

if err != nil {
	fmt.Println(err.Error())
}
Output:

Types

type ListingFilter

type ListingFilter struct {
	MatchPatterns    []string // Slice with shell file name patterns
	NotMatchPatterns []string // Slice with shell file name patterns

	ATimeOlder   int64 // Files with ATime less or equal to defined timestamp (BEFORE date)
	ATimeYounger int64 // Files with ATime greater or equal to defined timestamp (AFTER date)
	CTimeOlder   int64 // Files with CTime less or equal to defined timestamp (BEFORE date)
	CTimeYounger int64 // Files with CTime greater or equal to defined timestamp (AFTER date)
	MTimeOlder   int64 // Files with MTime less or equal to defined timestamp (BEFORE date)
	MTimeYounger int64 // Files with MTime greater or equal to defined timestamp (AFTER date)

	SizeLess    int64 // Files with size less than defined
	SizeGreater int64 // Files with size greater than defined
	SizeEqual   int64 // Files with size equals to defined
	SizeZero    bool  // Empty files

	Perms    string // Permission (see fsutil.CheckPerms for more info)
	NotPerms string // Permission (see fsutil.CheckPerms for more info)
}

ListingFilter is struct with properties for filtering listing output

Example
dir := "/home/john/documents"

filter := ListingFilter{
	MatchPatterns: []string{"*.doc", "*.docx", "*.pdf"},
	MTimeOlder:    time.Now().Unix() - 3600,
	SizeGreater:   50 * 1024,
	Perms:         "FR",
}

docs := List(dir, false, filter)

if len(docs) == 0 {
	fmt.Printf("No documents found in %s\n", dir)
	return
}

fmt.Println("Found documents:")

for _, doc := range docs {
	fmt.Printf("  %s\n", doc)
}
Output:

Jump to

Keyboard shortcuts

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