os

package
v1.2.6 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2022 License: MIT Imports: 16 Imported by: 2

Documentation

Index

Examples

Constants

View Source
const (
	DefaultPermissionFile       os.FileMode = 0666
	DefaultPermissionDirectory  os.FileMode = 0755
	DefaultFlagCreateIfNotExist             = os.O_RDWR | os.O_CREATE
	DefaultFlagCreateTruncate               = os.O_RDWR | os.O_CREATE | os.O_TRUNC
	DefaultFlagCreate                       = DefaultFlagCreateTruncate
	DefaultFlagCreateAppend                 = os.O_RDWR | os.O_CREATE | os.O_APPEND
	DefaultFlagLock                         = os.O_RDWR | os.O_CREATE | os.O_EXCL
)

Variables

View Source
var ShutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}

Functions

func Append

func Append(dst string, src string) error

Append creates or appends the dst file or dir, filled with content from src file. If the dst file already exists, it is truncated. If the dst file does not exist, it is created with mode 0666 (before umask). If the dst dir does not exist, it is created with mode 0755 (before umask). parent dirs will not be created, otherwise, use AppendAll instead.

func AppendAll

func AppendAll(filename string, data []byte) error

AppendAll appends data to a file named by filename. If the file does not exist, AppendAll creates it with mode 0666 (before umask) If the dir does not exist, AppendAll creates it with 0755 (before umask) (before umask); otherwise AppendAll appends it before writing, without changing permissions.

func AppendAllFrom

func AppendAllFrom(filename string, r io.Reader) error

AppendAllFrom appends data to a file named by filename from r until EOF or error. If the file does not exist, AppendAllFrom creates it with mode 0666 (before umask) If the dir does not exist, AppendAllFrom creates it with 0755 (before umask) (before umask); otherwise AppendAllFrom appends it before writing, without changing permissions.

func AppendAllIfNotExist

func AppendAllIfNotExist(path string) (*os.File, error)

AppendAllIfNotExist appends the named file or dir. If the file does not exist, it is created with mode 0666 (before umask). If the dir does not exist, it is created with mode 0755 (before umask). If path is already a directory, CreateAllIfNotExist does nothing and returns nil.

func AppendFileAll

func AppendFileAll(filename string, data []byte, dirperm, fileperm os.FileMode) error

AppendFileAll is the generalized open call; most users will use AppendAll instead. It appends data to a file named by filename. If the file does not exist, AppendFileAll creates it with permissions fileperm (before umask) If the dir does not exist, AppendFileAll creates it with permissions dirperm (before umask) otherwise AppendFileAll appends it before writing, without changing permissions.

func AppendFileAllFrom

func AppendFileAllFrom(filename string, r io.Reader, dirperm, fileperm os.FileMode) error

AppendFileAllFrom is the generalized open call; most users will use AppendFileFrom instead. It appends data to a file named by filename from r until EOF or error. If the file does not exist, AppendFileAllFrom creates it with permissions fileperm (before umask) If the dir does not exist, AppendFileAllFrom creates it with permissions dirperm (before umask) otherwise AppendFileAllFrom appends it before writing, without changing permissions.

func AppendTruncate

func AppendTruncate(dst string, src string) error

AppendTruncate truncates the original src file in place after appending or creating a copy dst, instead of moving the src file to dir and optionally creating a new one src.

func AppendTruncateAll

func AppendTruncateAll(dst string, src string) error

AppendTruncateAll truncates the original src file in place after appending or creating a copy dst, instead of moving the src file to dir and optionally creating a new one src. parent dirs will be created with dirperm if not exist.

func ChtimesNow

func ChtimesNow(name string) error

ChtimesNow changes the access and modification times of the named file with Now, similar to the Unix utime() or utimes() functions.

The underlying filesystem may truncate or round the values to a less precise time unit. If there is an error, it will be of type *PathError.

func Copy

func Copy(dst string, src string) error

Copy creates or truncates the dst file or dir, filled with content from src file. If the dst file already exists, it is truncated. If the dst file does not exist, it is created with mode 0666 (before umask). If the dst dir does not exist, it is created with mode 0755 (before umask). parent dirs will not be created, otherwise, use CopyAll instead.

func CopyAll

func CopyAll(dst string, src string) error

CopyAll creates or truncates the dst file or dir, filled with content from src file. If the dst file already exists, it is truncated. If the dst file does not exist, it is created with mode 0666 (before umask). If the dst dir does not exist, it is created with mode 0755 (before umask).

func CopyAppendAll

func CopyAppendAll(dst string, src string) error

CopyAppendAll creates or appends the dst file or dir, filled with content from src file. If the dst file already exists, it is truncated. If the dst file does not exist, it is created with mode 0666 (before umask). If the dst dir does not exist, it is created with mode 0755 (before umask).

func CopyFile

func CopyFile(dst string, src string, flag int, perm os.FileMode) error

CopyFile is the generalized open call; most users will use Copy or Append instead. It opens the named file or directory with specified flag (O_RDONLY etc.). CopyFile copies from src to dst. parent dirs will not be created, otherwise, use CopyFileAll instead.

func CopyFileAll

func CopyFileAll(dst string, src string, flag int, dirperm, fileperm os.FileMode) error

CopyFileAll is the generalized open call; most users will use CopyAll or AppendAll instead. It opens the named file or directory with specified flag (O_RDONLY etc.). If the dst file does not exist, and the O_CREATE flag is passed, it is created with mode fileperm (before umask). If the dst directory does not exist, it is created with mode dirperm (before umask). If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

func CopyRename

func CopyRename(dst string, src string) error

CopyRename makes a copy of the src file, but don't change the original src at all. This option can be used, for instance, to make a snapshot of the current log file, or when some other utility needs to truncate or parse the file.

func CopyRenameAll

func CopyRenameAll(dst string, src string) error

CopyRenameAll makes a copy of the src file, but don't change the original src at all. This option can be used, for instance, to make a snapshot of the current log file, or when some other utility needs to truncate or parse the file. parent dirs will be created with dirperm if not exist.

func CopyRenameFile

func CopyRenameFile(dst string, src string, flag int, perm os.FileMode) error

CopyRenameFile is the generalized open call; most users will use CopyRename instead. It opens the named file or directory with specified flag (O_RDONLY etc.). CopyTruncateFile copies from src to dst and truncates src. parent dirs will not be created, otherwise, use CopyRenameFileAll instead.

func CopyRenameFileAll

func CopyRenameFileAll(dst string, src string, flag int, dirperm, fileperm os.FileMode) error

CopyRenameFileAll is the generalized open call; most users will use CopyRenameAll instead. It makes a copy of the src file, but don't change the original src at all. CopyRenameFileAll renames from src to dst and creates src if not exist. parent dirs will be created with dirperm if not exist. CopyRenameFileAll = RenameFileAll(src->dst) + OpenFile(src)

func CopyTruncate

func CopyTruncate(dst string, src string) error

CopyTruncate truncates the original src file in place after creating a copy dst, instead of moving the src file to dir and optionally creating a new one src. It can be used when some program can‐ not be told to close its logfile and thus might continue writing (appending) to the previous log file forever. Note that there is a very small time slice between copying the file and truncating it, so some logging data might be lost.

func CopyTruncateAll

func CopyTruncateAll(dst string, src string) error

CopyTruncateAll truncates the original src file in place after creating a copy dst, instead of moving the src file to dir and optionally creating a new one src. It can be used when some program can‐ not be told to close its logfile and thus might continue writing (appending) to the previous log file forever. Note that there is a very small time slice between copying the file and truncating it, so some logging data might be lost. parent dirs will be created with dirperm if not exist.

func CopyTruncateFile

func CopyTruncateFile(dst string, src string, flag int, perm os.FileMode, size int64) error

CopyTruncateFile is the generalized open call; most users will use CopyTruncate or AppendTruncate instead. It opens the named file or directory with specified flag (O_RDONLY etc.). CopyTruncateFile copies from src to dst and truncates src. parent dirs will not be created, otherwise, use CopyTruncateFileAll instead. CopyTruncateFile = CopyFile(src->dst) + Truncate(src)

func CopyTruncateFileAll

func CopyTruncateFileAll(dst string, src string, flag int, dirperm, fileperm os.FileMode, size int64) error

CopyTruncateFileAll is the generalized open call; most users will use CopyTruncateAll or AppendTruncateAll instead. It opens the named file or directory with specified flag (O_RDONLY etc.). CopyTruncateFileAll copies from src to dst and truncates src. parent dirs will be created with dirperm if not exist.

func CreateAll

func CreateAll(path string) (*os.File, error)

CreateAll creates or truncates the named file or dir. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0666 (before umask). If the dir does not exist, it is created with mode 0755 (before umask).

func CreateAllIfNotExist

func CreateAllIfNotExist(path string) (*os.File, error)

CreateAllIfNotExist creates the named file or dir. If the file does not exist, it is created with mode 0666 (before umask). If the dir does not exist, it is created with mode 0755 (before umask). If path is already a directory, CreateAllIfNotExist does nothing and returns nil.

func DiskUsage

func DiskUsage(path string) (total int64, free int64, avail int64, inodes int64, inodesFree int64, err error)

DiskUsage returns total and free bytes available in a directory, e.g. `/`.

Example
package main

import (
	os_ "github.com/searKing/golang/go/os"
)

func main() {
	total, free, avail, inodes, inodesFree, err := os_.DiskUsage("/tmp")
	if err != nil {
		return
	}

	_, _, _, _, _ = total, free, avail, inodes, inodesFree
	//fmt.Printf("total :%d B, free: %d B, avail: %d B, inodes: %d, inodesFree: %d", total, free, avail, inodes, inodesFree)
	// total :499963174912 B, free: 57534603264 B, avail: 57534603264 B, inodes: 566386444, inodesFree: 561861360

}
Output:

func GetAbsBinDir

func GetAbsBinDir() (dir string, err error)

func LockAll

func LockAll(path string) (*os.File, error)

LockAll creates the named file or dir. If the file already exists, error returned. If the file does not exist, it is created with mode 0666 (before umask). If the dir does not exist, it is created with mode 0755 (before umask).

func Make

func Make(name string) error

Make creates a directory named path and returns nil, or else returns an error. If the dir does not exist, it is created with mode 0755 (before umask).

func MakeAll

func MakeAll(name string) error

MakeAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. If the dir does not exist, it is created with mode 0755 (before umask).

func MaxSeq

func MaxSeq(pattern string) (prefix string, seq int, suffix string)

MaxSeq return max seq set by NextFile split pattern by the last wildcard "*"

func NextFile

func NextFile(pattern string, seq int) (f *os.File, seqUsed int, err error)

NextFile creates a new file, opens the file for reading and writing, and returns the resulting *os.File. The filename is generated by taking pattern and adding a seq increased string to the end. If pattern includes a "*", the random string replaces the last "*". Multiple programs calling NextFile simultaneously will not choose the same file. The caller can use f.Name() to find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed.

func OpenAll

func OpenAll(path string) (*os.File, error)

OpenAll opens the named file or dir for reading. If successful, methods on the returned file or dir 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 OpenFileAll

func OpenFileAll(path string, flag int, dirperm, fileperm os.FileMode) (*os.File, error)

OpenFileAll is the generalized open call; most users will use OpenAll or CreateAll instead. It opens the named file or directory with specified flag (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag is passed, it is created with mode fileperm (before umask). If the directory does not exist, it is created with mode dirperm (before umask). If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

func PathExists

func PathExists(path string) (bool, error)
func ReLink(oldname, newname string) error

ReLink creates or replaces newname as a hard link to the oldname file. If there is an error, it will be of type *LinkError.

func ReSymlink(oldname, newname string) error

ReSymlink creates or replace newname as a symbolic link to oldname. If there is an error, it will be of type *LinkError.

func RemoveIfExist

func RemoveIfExist(name string) error

RemoveIfExist removes the named file or (empty) directory. If the path does not exist, RemoveIfExist returns nil (no error). If there is an error, it will be of type *PathError.

func RenameAll

func RenameAll(oldpath, newpath string) error

RenameAll 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. If the dir does not exist, it is created with mode 0755 (before umask).

func RenameFileAll

func RenameFileAll(oldpath, newpath string, dirperm os.FileMode) error

RenameFileAll is the generalized open call; most users will use RenameAll instead. It renames (moves) oldpath to newpath.

func SameFile

func SameFile(fi1, fi2 string) bool

SameFile reports whether fi1 and fi2 describe the same file. Overload os.SameFile by file path

func TempAll

func TempAll(dir, pattern string) (f *os.File, err error)

TempAll creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting *os.File. If the file does not exist, TempAll creates it with mode 0600 (before umask) If the dir does not exist, TempAll creates it with 0755 (before umask) otherwise TempAll truncates it before writing, without changing permissions.

func TempFileAll

func TempFileAll(dir, pattern string, dirperm os.FileMode) (f *os.File, err error)

TempFileAll is the generalized open call; most users will use TempAll instead. If the directory does not exist, it is created with mode dirperm (before umask).

func TouchAll

func TouchAll(path string) (*os.File, error)

TouchAll creates the named file or dir. If the file already exists, it is touched to now. If the file does not exist, it is created with mode 0666 (before umask). If the dir does not exist, it is created with mode 0755 (before umask).

func UnlinkOldestFiles

func UnlinkOldestFiles(pattern string, maxAge time.Duration, maxCount int, used, iUsed float32) error

UnlinkOldestFiles unlink old files if need

func WriteAll

func WriteAll(filename string, data []byte) error

WriteAll writes data to a file named by filename. If the file does not exist, WriteAll creates it with mode 0666 (before umask) If the dir does not exist, WriteAll creates it with 0755 (before umask) otherwise WriteAll truncates it before writing, without changing permissions.

func WriteAllFrom

func WriteAllFrom(filename string, r io.Reader) error

WriteAllFrom writes data to a file named by filename from r until EOF or error. If the file does not exist, WriteAll creates it with mode 0666 (before umask) If the dir does not exist, WriteAll creates it with 0755 (before umask) otherwise WriteAll truncates it before writing, without changing permissions.

func WriteFileAll

func WriteFileAll(filename string, data []byte, dirperm, fileperm os.FileMode) error

WriteFileAll is the generalized open call; most users will use WriteAll instead. It writes data to a file named by filename. If the file does not exist, WriteFileAll creates it with permissions fileperm (before umask) If the dir does not exist, WriteFileAll creates it with permissions dirperm (before umask) otherwise WriteFileAll truncates it before writing, without changing permissions.

func WriteFileAllFrom

func WriteFileAllFrom(filename string, r io.Reader, dirperm, fileperm os.FileMode) error

WriteFileAllFrom is the generalized open call; most users will use WriteAllFrom instead. It writes data to a file named by filename from r until EOF or error. If the file does not exist, WriteFileAllFrom creates it with permissions fileperm (before umask) If the dir does not exist, WriteFileAllFrom creates it with permissions dirperm (before umask) otherwise WriteFileAllFrom truncates it before writing, without changing permissions.

func WriteRenameAll

func WriteRenameAll(filename string, data []byte) error

WriteRenameAll writes data to a temp file and rename to the new file named by filename. If the file does not exist, WriteRenameAll creates it with mode 0666 (before umask) If the dir does not exist, WriteRenameAll creates it with 0755 (before umask) otherwise WriteRenameAll truncates it before writing, without changing permissions.

func WriteRenameAllFrom

func WriteRenameAllFrom(filename string, r io.Reader) error

WriteRenameAllFrom writes data to a temp file from r until EOF or error, and rename to the new file named by filename. WriteRenameAllFrom is safer than WriteAllFrom as before Write finished, nobody can find the unfinished file. If the file does not exist, WriteRenameAllFrom creates it with mode 0666 (before umask) If the dir does not exist, WriteRenameAllFrom creates it with 0755 (before umask) otherwise WriteRenameAllFrom truncates it before writing, without changing permissions.

func WriteRenameFileAll

func WriteRenameFileAll(filename string, data []byte, dirperm os.FileMode) error

WriteRenameFileAll is the generalized open call; most users will use WriteRenameAll instead. WriteRenameFileAll is safer than WriteFileAll as before Write finished, nobody can find the unfinished file. It writes data to a temp file and rename to the new file named by filename. If the file does not exist, WriteRenameFileAll creates it with permissions fileperm If the dir does not exist, WriteRenameFileAll creates it with permissions dirperm (before umask); otherwise WriteRenameFileAll truncates it before writing, without changing permissions.

func WriteRenameFileAllFrom

func WriteRenameFileAllFrom(filename string, r io.Reader, dirperm os.FileMode) error

WriteRenameFileAllFrom is the generalized open call; most users will use WriteRenameAllFrom instead. WriteRenameFileAllFrom is safer than WriteRenameAllFrom as before Write finished, nobody can find the unfinished file. It writes data to a temp file and rename to the new file named by filename. If the file does not exist, WriteRenameFileAllFrom creates it with permissions fileperm If the dir does not exist, WriteRenameFileAllFrom creates it with permissions dirperm (before umask); otherwise WriteRenameFileAllFrom truncates it before writing, without changing permissions.

Types

type FileInfos

type FileInfos []os.FileInfo

func (FileInfos) Len

func (s FileInfos) Len() int

func (FileInfos) Less

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

func (FileInfos) Swap

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

type FileModeTimeDescSlice

type FileModeTimeDescSlice []string

sort filename by mode time in decrease order

func (FileModeTimeDescSlice) Len

func (s FileModeTimeDescSlice) Len() int

func (FileModeTimeDescSlice) Less

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

func (FileModeTimeDescSlice) Swap

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

type FileModeTimeSlice

type FileModeTimeSlice []string

sort filename by mode time in increase order

func (FileModeTimeSlice) Len

func (s FileModeTimeSlice) Len() int

func (FileModeTimeSlice) Less

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

func (FileModeTimeSlice) Swap

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

type RotateFile

type RotateFile struct {
	RotateMode           RotateMode
	FilePathPrefix       string // FilePath = FilePathPrefix + now.Format(filePathRotateLayout)
	FilePathRotateLayout string // Time layout to format rotate file

	RotateFileGlob string // file glob to clean

	// sets the symbolic link name that gets linked to the current file name being used.
	FileLinkPath string

	// Rotate files are rotated until RotateInterval expired before being removed
	// take effects if only RotateInterval is bigger than 0.
	RotateInterval time.Duration

	// Rotate files are rotated if they grow bigger then size bytes.
	// take effects if only RotateSize is bigger than 0.
	RotateSize int64

	// max age of a log file before it gets purged from the file system.
	// Remove rotated logs older than duration. The age is only checked if the file is
	// to be rotated.
	// take effects if only MaxAge is bigger than 0.
	MaxAge time.Duration

	// Rotate files are rotated MaxCount times before being removed
	// take effects if only MaxCount is bigger than 0.
	MaxCount int

	// Force File Rotate when start up
	ForceNewFileOnStartup bool

	// PreRotateHandler called before file rotate
	// name means file path rotated
	PreRotateHandler func(name string)

	// PostRotateHandler called after file rotate
	// name means file path rotated
	PostRotateHandler func(name string)
	// contains filtered or unexported fields
}

RotateFile logrotate reads everything about the log files it should be handling from the series of con‐ figuration files specified on the command line. Each configuration file can set global options (local definitions override global ones, and later definitions override earlier ones) and specify rotatefiles to rotate. A simple configuration file looks like this:

func NewRotateFile

func NewRotateFile(layout string) *RotateFile
Example
package main

import (
	"time"

	os_ "github.com/searKing/golang/go/os"
)

func main() {
	file := os_.NewRotateFile("log/test.2006-01-02-15-04-05.log")
	file.MaxCount = 5
	file.RotateInterval = 5 * time.Second
	file.MaxAge = time.Hour
	file.FileLinkPath = "log/s.log"
	for i := 0; i < 10000; i++ {
		time.Sleep(1 * time.Millisecond)
		file.WriteString(time.Now().String())
		//if err := file.Rotate(false); err != nil {
		//	fmt.Printf("%d, err: %v", i, err)
		//}
	}
}
Output:

func NewRotateFileWithStrftime

func NewRotateFileWithStrftime(strftimeLayout string) *RotateFile
Example
package main

import (
	"time"

	os_ "github.com/searKing/golang/go/os"
)

func main() {
	file := os_.NewRotateFileWithStrftime("log/test.%Y-%m-%d-%H-%M-%S.log")
	file.MaxCount = 5
	file.RotateInterval = 5 * time.Second
	file.MaxAge = time.Hour
	file.FileLinkPath = "log/s.log"
	for i := 0; i < 10000; i++ {
		time.Sleep(1 * time.Millisecond)
		file.WriteString(time.Now().String())
		//if err := file.Rotate(false); err != nil {
		//	fmt.Printf("%d, err: %v", i, err)
		//}
	}
}
Output:

func (*RotateFile) Close

func (f *RotateFile) Close() error

Close satisfies the io.Closer interface. You must call this method if you performed any writes to the object.

func (*RotateFile) Rotate

func (f *RotateFile) Rotate(forceRotate bool) error

Rotate forcefully rotates the file. If the generated file name clash because file already exists, a numeric suffix of the form ".1", ".2", ".3" and so forth are appended to the end of the log file

This method can be used in conjunction with a signal handler so to emulate servers that generate new log files when they receive a SIGHUP

func (*RotateFile) Write

func (f *RotateFile) Write(b []byte) (n int, err error)

func (*RotateFile) WriteAt

func (f *RotateFile) WriteAt(b []byte, off int64) (n int, err error)

WriteAt writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any. WriteAt returns a non-nil error when n != len(b).

If file was opened with the O_APPEND flag, WriteAt returns an error.

func (*RotateFile) WriteString

func (f *RotateFile) WriteString(s string) (n int, err error)

WriteString is like Write, but writes the contents of string s rather than a slice of bytes.

type RotateMode

type RotateMode int
const (
	// RotateModeNew create new rotate file directly
	RotateModeNew RotateMode = iota

	// RotateModeCopyRename Make a copy of the log file, but don't change the original at all. This option can be
	// used, for instance, to make a snapshot of the current log file, or when some other
	// utility needs to truncate or parse the file. When this option is used, the create
	// option will have no effect, as the old log file stays in place.
	RotateModeCopyRename RotateMode = iota

	// RotateModeCopyTruncate Truncate the original log file in place after creating a copy, instead of moving the
	// old log file and optionally creating a new one. It can be used when some program can‐
	// not be told to close its rotatefile and thus might continue writing (appending) to the
	// previous log file forever. Note that there is a very small time slice between copying
	// the file and truncating it, so some logging data might be lost. When this option is
	// used, the create option will have no effect, as the old log file stays in place.
	RotateModeCopyTruncate RotateMode = iota
)

type WalkFileInfo

type WalkFileInfo struct {
	Path     string
	FileInfo os.FileInfo
}

WalkFileInfo is a wrapper for sort of filepath.WalkFunc

type WalkFileInfos

type WalkFileInfos []WalkFileInfo

func (WalkFileInfos) Len

func (w WalkFileInfos) Len() int

func (WalkFileInfos) Less

func (w WalkFileInfos) Less(i, j int) bool

func (WalkFileInfos) Swap

func (w WalkFileInfos) Swap(i, j int)

Jump to

Keyboard shortcuts

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