github.com/Mericusta/go-stp@v0.6.8/file.go (about)

     1  package stp
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"io"
     7  	"io/fs"
     8  	"os"
     9  	"path"
    10  	"path/filepath"
    11  	"runtime"
    12  	"strings"
    13  )
    14  
    15  // ReadFileLineOneByOne 逐行读取文件内容,执行函数返回 true 则继续读取,返回 false 则结束读取
    16  func ReadFileLineOneByOne(filename string, f func(string) bool) error {
    17  	file, openError := os.Open(filename)
    18  	if openError != nil {
    19  		return openError
    20  	}
    21  	defer file.Close()
    22  
    23  	return ReadContentLineOneByOne(file, f)
    24  }
    25  
    26  // ReadContentLineOneByOne 逐行读取指定内容,执行函数返回 true 则继续读取,返回 false 则结束读取
    27  func ReadContentLineOneByOne(reader io.Reader, f func(string) bool) error {
    28  	scanner := bufio.NewScanner(reader)
    29  
    30  	for scanner.Scan() {
    31  		if !f(scanner.Text()) {
    32  			break
    33  		}
    34  	}
    35  
    36  	if scanner.Err() != nil {
    37  		return scanner.Err()
    38  	}
    39  
    40  	return nil
    41  }
    42  
    43  // IsExist 检查文件或文件夹是否存在
    44  func IsExist(path string) bool {
    45  	_, err := os.Stat(path)
    46  	return err == nil || os.IsExist(err)
    47  }
    48  
    49  // TraverseDirectorySpecificFileWithFunction 遍历文件夹获取所有绑定类型的文件
    50  func TraverseDirectorySpecificFileWithFunction(directory, syntax string, operate func(string, fs.DirEntry) error) error {
    51  	syntaxExt := fmt.Sprintf(".%v", syntax)
    52  	return filepath.WalkDir(directory, func(filePath string, d fs.DirEntry, err error) error {
    53  		if err != nil {
    54  			return err
    55  		}
    56  		if filePath != directory {
    57  			if d.IsDir() {
    58  				return err
    59  			}
    60  			if path.Ext(filePath) == syntaxExt {
    61  				err := operate(filePath, d)
    62  				return err
    63  			}
    64  		}
    65  		return nil
    66  	})
    67  }
    68  
    69  // CreateDir 创建文件夹
    70  func CreateDir(directoryPath string) error {
    71  	err := os.Mkdir(directoryPath, os.ModePerm)
    72  	if err != nil {
    73  		return err
    74  	}
    75  	return nil
    76  }
    77  
    78  // CreateFile 创建文件
    79  func CreateFile(filePath string) (*os.File, error) {
    80  	file, err := os.Create(filePath)
    81  	if err != nil {
    82  		return nil, err
    83  	}
    84  	return file, nil
    85  }
    86  
    87  // FormatFilePathWithOS 根据操作系统格式化路径
    88  func FormatFilePathWithOS(filePath string) string {
    89  	osLinux := "linux"
    90  	operationSystem := runtime.GOOS
    91  	beReplaced := "/"
    92  	toReplace := "\\"
    93  	if operationSystem == osLinux {
    94  		beReplaced, toReplace = toReplace, beReplaced
    95  	}
    96  	return strings.ReplaceAll(filePath, beReplaced, toReplace)
    97  }