yos

package
v0.0.0-...-a823632 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2020 License: MIT Imports: 12 Imported by: 19

Documentation

Overview

Package yos is yet another wrapper of platform-independent interface to operating system functionality.

Environments

Check architecture of current system:

  • IsOn32bitArch
  • IsOn64bitArch

Check current operating system:

  • IsOnLinux
  • IsOnMacOS
  • IsOnMacOS

Change working directory:

  • ChangeExeDir

File Operations

Basic operations:

| Ops \ Type  | Directory      | File            | Symbolic Link      |
| ----------- | -------------- | --------------- | ------------------ |
| Check Exist | ExistDir       | ExistFile       | ExistSymlink       |
| Check Empty | IsDirEmpty     | IsFileEmpty     | -                  |
| Get Size    | GetDirSize     | GetFileSize     | GetSymlinkSize     |
| Compare     | SameDirEntries | SameFileContent | SameSymlinkContent |
| List        | ListDir        | ListFile        | ListSymlink        |
| Copy        | CopyDir        | CopyFile        | CopySymlink        |
| Move        | MoveDir        | MoveFile        | MoveSymlink        |

Miscellaneous operations:

  • ListMatch
  • JoinPath
  • Exist
  • NotExist
  • MakeDir

Sorting helpers for a slice of *FilePathInfo:

  • SortListByName
  • SortListBySize
  • SortListByModTime
Example

This example moves all image files from sub-folders of the source directory to the same destination directory.

package main

import (
	"fmt"
	"sort"

	"github.com/1set/gut/yos"
)

func main() {
	srcRoot := "source"
	destRoot := "collect"

	srcFiles, err := yos.ListMatch(srcRoot, yos.ListIncludeFile|yos.ListRecursive|yos.ListToLower, "*.jpg", "*.jpeg", "*.png", "*.gif")
	if err != nil {
		fmt.Printf("fail to list %q: %v\n", srcRoot, err)
		return
	}
	sort.Stable(yos.SortListByModTime(srcFiles))

	if err = yos.MakeDir(destRoot); err != nil {
		fmt.Printf("fail to mkdir %q: %v\n", destRoot, err)
		return
	}

	cntMove, cntSkip := 0, 0
	for _, src := range srcFiles {
		destPath := yos.JoinPath(destRoot, src.Info.Name())
		// skip if the same file already exists
		if yos.ExistFile(destPath) {
			if same, err := yos.SameFileContent(src.Path, destPath); same && err == nil {
				cntSkip++
				continue
			}
		}

		if err := yos.MoveFile(src.Path, destPath); err == nil {
			cntMove++
		}
	}

	fmt.Printf("total: %d\nmove : %d\nskip : %d\nfail : %d\n", len(srcFiles), cntMove, cntSkip, len(srcFiles)-cntMove-cntSkip)
}
Output:

Index

Examples

Constants

View Source
const (
	// ListRecursive indicates ListMatch to recursively list directory entries encountered.
	ListRecursive int = 1 << iota
	// ListToLower indicates ListMatch to convert file name to lower case before the pattern matching.
	ListToLower
	// ListUseRegExp indicates ListMatch to use regular expression for the pattern matching.
	ListUseRegExp
	// ListIncludeDir indicates ListMatch to include matched directories in the returned list.
	ListIncludeDir
	// ListIncludeFile indicates ListMatch to include matched files in the returned list.
	ListIncludeFile
	// ListIncludeSymlink indicates ListMatch to include matched symbolic link in the returned list.
	ListIncludeSymlink
)

The flags are used by the ListMatch method.

View Source
const (
	// ListIncludeAll indicates ListMatch to include all the matched in the returned list.
	ListIncludeAll = ListIncludeDir | ListIncludeFile | ListIncludeSymlink
)

Variables

This section is empty.

Functions

func ChangeExeDir

func ChangeExeDir() (err error)

ChangeExeDir changes the current working directory to the directory of the executable that started the current process.

If a symbolic link is used to start the process, the current working directory will be changed to the directory of the executable that the link pointed to.

func CopyDir

func CopyDir(src, dest string) (err error)

CopyDir copies a directory to a target directory recursively. Symbolic links inside the directories will be copied instead of being followed.

If the target is an existing file, an error will be returned.

If the target is an existing directory, the source directory will be copied to the directory with the same name.

If the target doesn't exist but its parent directory does, the source directory will be copied to the parent directory with the target name.

It stops and returns immediately if any error occurs, and the error will be of type *os.PathError.

Example

This example copies all files in the current directory to the destination.

package main

import (
	"fmt"

	"github.com/1set/gut/yos"
)

func main() {
	destRoot := "../backup"
	if err := yos.CopyDir(".", destRoot); err != nil {
		fmt.Printf("fail to back up current dir to %q: %v\n", destRoot, err)
		return
	}
}
Output:

func CopyFile

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

CopyFile copies a file to a target file or directory. Symbolic links are followed.

If the target is an existing file, the target will be overwritten with the source file.

If the target is an existing directory, the source file will be copied to the directory with the same file name.

If the target doesn't exist but its parent directory does, the source file will be copied to the parent directory with the target name.

If there is an error, it will be of type *os.PathError.

func CopySymlink(src, dest string) (err error)

CopySymlink copies a symbolic link to a target file.

CopySymlink only copies the content in the link and makes no attempt to read the file that the link pointed to.

If there is an error, it will be of type *os.PathError.

func Exist

func Exist(path string) bool

Exist checks whether the given path exists.

If the file is a symbolic link, it will attempt to follow the link and check if the source file exists.

Example

This example checks if the annoying thumbnail file exists in the current directory as per the operating system.

package main

import (
	"fmt"

	"github.com/1set/gut/yos"
)

func main() {
	switch {
	case yos.IsOnMacOS():
		fmt.Println("macOS", yos.Exist(".DS_Store"))
	case yos.IsOnWindows():
		fmt.Println("Windows", yos.Exist("Thumbs.db"))
	}
}
Output:

func ExistDir

func ExistDir(path string) bool

ExistDir checks whether the specified path exists and is a directory.

If the path is a symbolic link, it will attempt to follow the link and check.

func ExistFile

func ExistFile(path string) bool

ExistFile checks whether the specified path exists and is a file.

If the path is a symbolic link, it will attempt to follow the link and check.

func ExistSymlink(path string) bool

ExistSymlink checks whether the specified path exists and is a symbolic link.

It only checks the path itself and makes no attempt to follow the link.

func GetDirSize

func GetDirSize(path string) (size int64, err error)

GetDirSize returns total size in bytes for all regular files and symbolic links in a directory.

If the given path is a symbolic link, it will be followed, but symbolic links inside the directory won't.

func GetFileSize

func GetFileSize(path string) (size int64, err error)

GetFileSize returns the size in bytes for a regular file.

If the given path is a symbolic link, it will be followed.

func GetSymlinkSize

func GetSymlinkSize(path string) (size int64, err error)

GetSymlinkSize returns the size in bytes for a symbolic link.

func IsDirEmpty

func IsDirEmpty(path string) (empty bool, err error)

IsDirEmpty checks whether the given directory contains nothing.

func IsFileEmpty

func IsFileEmpty(path string) (empty bool, err error)

IsFileEmpty checks whether the given file is empty.

func IsOn32bitArch

func IsOn32bitArch() bool

IsOn32bitArch indicates whether the application is running on 32-bit architecture.

func IsOn64bitArch

func IsOn64bitArch() bool

IsOn64bitArch indicates whether the application is running on 64-bit architecture.

func IsOnLinux

func IsOnLinux() bool

IsOnLinux indicates whether the application is running on Linux.

func IsOnMacOS

func IsOnMacOS() bool

IsOnMacOS indicates whether the application is running on macOS.

func IsOnWindows

func IsOnWindows() bool

IsOnWindows indicates whether the application is running on Windows.

func JoinPath

func JoinPath(elem ...string) string

JoinPath joins any number of path elements into a single path, adding a separator if necessary.

func MakeDir

func MakeDir(path string) (err error)

MakeDir creates a directory named path with 0755 permission bits, along with any necessary parents.

0755 permission bits indicates that the owner can read, write and execute, whereas everyone else can read and execute but not modify.

If the path is already a directory, MakeDir does nothing and returns nil.

func MoveDir

func MoveDir(src, dest string) (err error)

MoveDir moves a directory to a target directory recursively. Symbolic links inside the directories will not be followed.

If the target is an existing file, it will be replaced by the source directory.

If the target is an existing directory, the source directory will be moved to the directory with the same name.

If the target doesn't exist but its parent directory does, the source directory will be moved to the parent directory with the target name.

MoveDir stops and returns immediately if any error occurs, and the error will be of type *os.PathError.

func MoveFile

func MoveFile(src, dest string) (err error)

MoveFile moves a file to a target file or directory. Symbolic links will be not be followed.

If the target is an existing file, the target will be overwritten with the source file.

If the target is an existing directory, the source file will be moved to the directory with the same name.

If the target doesn't exist but its parent directory does, the source file will be moved to the parent directory with the target name.

If there is an error, it will be of type *os.PathError.

func MoveSymlink(src, dest string) (err error)

MoveSymlink moves a symbolic link to a target file. It makes no attempt to read the referenced file.

If the target is an existing file or link, the target will be overwritten with the source link.

If the target is an existing directory, the source link will be moved to the directory with the same name.

If the target doesn't exist but its parent directory does, the source link will be moved to the parent directory with the target name.

If there is an error, it will be of type *os.PathError.

func NotExist

func NotExist(path string) bool

NotExist checks whether the given path doesn't exist.

If the file is a symbolic link, it will attempt to follow the link and check if the source file doesn't exist.

func SameDirEntries

func SameDirEntries(path1, path2 string) (same bool, err error)

SameDirEntries checks if the two directories have the same entries. Symbolic links other than the given paths will be not be followed, and only compares content of links.

func SameFileContent

func SameFileContent(path1, path2 string) (same bool, err error)

SameFileContent checks if the two given files have the same content or are the same file. Symbolic links are followed. Errors are returned if any files doesn't exist or is broken.

func SameSymlinkContent

func SameSymlinkContent(path1, path2 string) (same bool, err error)

SameSymlinkContent checks if the two symbolic links have the same destination.

Types

type FilePathInfo

type FilePathInfo struct {
	Path string
	Info os.FileInfo
}

A FilePathInfo describes path and stat of a file or directory.

func ListAll

func ListAll(root string) (entries []*FilePathInfo, err error)

ListAll returns a list of all entries in the given directory in lexical order. The given directory is not included in the list.

It searches recursively, but symbolic links other than the given path will be not be followed.

func ListDir

func ListDir(root string) (entries []*FilePathInfo, err error)

ListDir returns a list of nested directory entries in the given directory in lexical order. The given directory is not included in the list.

It searches recursively, but symbolic links other than the given path will be not be followed.

func ListFile

func ListFile(root string) (entries []*FilePathInfo, err error)

ListFile returns a list of file entries in the given directory in lexical order. The given directory is not included in the list.

It searches recursively, but symbolic links other than the given path will be not be followed.

Example

This example lists all files in the current directory and its sub-directories.

package main

import (
	"fmt"

	"github.com/1set/gut/yos"
)

func main() {
	entries, err := yos.ListFile(".")
	if err != nil {
		fmt.Println("got error:", err)
		return
	}

	for _, info := range entries {
		fmt.Println(info.Path, info.Info.Size())
	}
}
Output:

func ListMatch

func ListMatch(root string, flag int, patterns ...string) (entries []*FilePathInfo, err error)

ListMatch returns a list of directory entries that matches any given pattern in the directory in lexical order.

Symbolic links other than the given path will be not be followed. The given directory is not included in the list.

ListMatch requires the pattern to match the full file name, not just a substring. Errors are returned if any pattern is malformed.

There are two types of patterns are supported:

  1. wildcard described in filepath.Match(), this is default;
  2. regular expression accepted by google/RE2, use the ListUseRegExp flag to enable;
Example

This example lists all .txt and .md files in the current directory and its sub-directories.

package main

import (
	"fmt"

	"github.com/1set/gut/yos"
)

func main() {
	entries, err := yos.ListMatch(".", yos.ListIncludeFile|yos.ListRecursive|yos.ListToLower, "*.txt", "*.md")
	if err != nil {
		fmt.Println("got error:", err)
		return
	}

	for _, info := range entries {
		fmt.Println(info.Path, info.Info.Size())
	}
}
Output:

func ListSymlink(root string) (entries []*FilePathInfo, err error)

ListSymlink returns a list of symbolic link entries in the given directory in lexical order. The given directory is not included in the list.

It searches recursively, but symbolic links other than the given path will be not be followed.

type SortListByModTime

type SortListByModTime []*FilePathInfo

SortListByModTime implements sort.Interface based on the Info.ModTime() field of FilePathInfo.

Example

This example lists all files in the current directory and sorts by last modified time in ascending order.

package main

import (
	"sort"

	"github.com/1set/gut/yos"
)

func main() {
	if srcFiles, err := yos.ListMatch(".", yos.ListIncludeFile|yos.ListRecursive, "*"); err == nil {
		sort.Stable(yos.SortListByModTime(srcFiles))
	}
}
Output:

func (SortListByModTime) Len

func (t SortListByModTime) Len() int

func (SortListByModTime) Less

func (t SortListByModTime) Less(i, j int) bool

func (SortListByModTime) Swap

func (t SortListByModTime) Swap(i, j int)

type SortListByName

type SortListByName []*FilePathInfo

SortListByName implements sort.Interface based on the Info.Name() field of FilePathInfo.

Example

This example lists all Go source code files in the current directory and sorts alphabetically.

package main

import (
	"sort"

	"github.com/1set/gut/yos"
)

func main() {
	if srcFiles, err := yos.ListMatch(".", yos.ListIncludeFile|yos.ListRecursive, "*.go"); err == nil {
		sort.Stable(yos.SortListByName(srcFiles))
	}
}
Output:

func (SortListByName) Len

func (n SortListByName) Len() int

func (SortListByName) Less

func (n SortListByName) Less(i, j int) bool

func (SortListByName) Swap

func (n SortListByName) Swap(i, j int)

type SortListBySize

type SortListBySize []*FilePathInfo

SortListBySize implements sort.Interface based on the Info.Size() field of FilePathInfo.

Example

This example lists all files in the current directory and sorts by size in descending order.

package main

import (
	"sort"

	"github.com/1set/gut/yos"
)

func main() {
	if srcFiles, err := yos.ListMatch(".", yos.ListIncludeFile|yos.ListRecursive, "*"); err == nil {
		sort.Stable(sort.Reverse(yos.SortListBySize(srcFiles)))
	}
}
Output:

func (SortListBySize) Len

func (s SortListBySize) Len() int

func (SortListBySize) Less

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

func (SortListBySize) Swap

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

Jump to

Keyboard shortcuts

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