beancount-gs/script/file.go

100 lines
2.1 KiB
Go
Raw Normal View History

2021-11-17 09:59:06 +00:00
package script
import (
"io/ioutil"
"os"
)
func FileIfExist(filePath string) bool {
_, err := os.Stat(filePath)
if nil != err {
return false
}
if os.IsNotExist(err) {
return false
}
return true
}
2021-11-18 08:27:28 +00:00
func ReadFile(filePath string) ([]byte, error) {
2021-11-17 09:59:06 +00:00
content, err := ioutil.ReadFile(filePath)
if nil != err {
2021-11-21 14:37:13 +00:00
LogSystemError("Failed to read file (" + filePath + ")")
2021-11-18 08:27:28 +00:00
return content, err
2021-11-17 09:59:06 +00:00
}
2021-11-21 14:37:13 +00:00
LogSystemInfo("Success read file (" + filePath + ")")
2021-11-18 08:27:28 +00:00
return content, nil
2021-11-17 09:59:06 +00:00
}
2021-11-18 08:27:28 +00:00
func WriteFile(filePath string, content string) error {
2021-11-28 12:19:40 +00:00
content = "\r\n" + content
file, err := os.OpenFile(filePath, os.O_CREATE, 0644)
if err == nil {
_, err = file.WriteString(content)
if err != nil {
LogSystemError("Failed to write file (" + filePath + ")")
return err
}
2021-11-18 08:27:28 +00:00
}
2021-11-28 12:19:40 +00:00
defer file.Close()
2021-11-21 14:37:13 +00:00
LogSystemInfo("Success write file (" + filePath + ")")
2021-11-18 08:27:28 +00:00
return nil
}
2021-11-28 12:19:40 +00:00
func AppendFileInNewLine(filePath string, content string) error {
content = "\r\n" + content
file, err := os.OpenFile(filePath, os.O_APPEND, 0644)
if err == nil {
_, err = file.WriteString(content)
if err != nil {
LogSystemError("Failed to append file (" + filePath + ")")
return err
}
}
defer file.Close()
LogSystemInfo("Success append file (" + filePath + ")")
return nil
}
2021-11-18 08:27:28 +00:00
func CreateFile(filePath string) error {
2021-11-17 09:59:06 +00:00
f, err := os.Create(filePath)
if nil != err {
2021-11-21 14:37:13 +00:00
LogSystemError(filePath + " create failed")
2021-11-18 08:27:28 +00:00
return err
2021-11-17 09:59:06 +00:00
}
defer f.Close()
2021-11-21 14:37:13 +00:00
LogSystemInfo("Success create file " + filePath)
2021-11-18 08:27:28 +00:00
return nil
2021-11-17 09:59:06 +00:00
}
2021-11-23 15:33:14 +00:00
func CopyFile(sourceFilePath string, targetFilePath string) error {
if !FileIfExist(sourceFilePath) {
panic("File is not found, " + sourceFilePath)
}
if !FileIfExist(targetFilePath) {
err := CreateFile(targetFilePath)
if err != nil {
return err
}
}
bytes, err := ReadFile(sourceFilePath)
if err != nil {
return err
}
err = WriteFile(targetFilePath, string(bytes))
if err != nil {
return err
}
return nil
}
2021-11-18 08:27:28 +00:00
func MkDir(dirPath string) error {
2021-11-17 09:59:06 +00:00
err := os.MkdirAll(dirPath, os.ModePerm)
if nil != err {
2021-11-21 14:37:13 +00:00
LogSystemError("Failed mkdir " + dirPath)
2021-11-18 08:27:28 +00:00
return err
2021-11-17 09:59:06 +00:00
}
2021-11-21 14:37:13 +00:00
LogSystemInfo("Success mkdir " + dirPath)
2021-11-18 08:27:28 +00:00
return nil
2021-11-17 09:59:06 +00:00
}