♻️ Refactor Go to err != nil, err == nil (#12385)

This commit is contained in:
Oleksandr Redko 2024-09-04 04:40:50 +03:00 committed by GitHub
parent 473a159ef2
commit b100721fee
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
147 changed files with 1661 additions and 1659 deletions

View file

@ -31,13 +31,13 @@ func AESEncrypt(str string) string {
buf := &bytes.Buffer{}
buf.Grow(4096)
_, err := hex.NewEncoder(buf).Write([]byte(str))
if nil != err {
if err != nil {
logging.LogErrorf("encrypt failed: %s", err)
return ""
}
data := buf.Bytes()
block, err := aes.NewCipher(SK)
if nil != err {
if err != nil {
logging.LogErrorf("encrypt failed: %s", err)
return ""
}
@ -57,13 +57,13 @@ func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
func AESDecrypt(cryptStr string) []byte {
crypt, err := hex.DecodeString(cryptStr)
if nil != err {
if err != nil {
logging.LogErrorf("decrypt failed: %s", err)
return nil
}
block, err := aes.NewCipher(SK)
if nil != err {
if err != nil {
return nil
}
cbc := cipher.NewCBCDecrypter(block, []byte("RandomInitVector"))

View file

@ -26,7 +26,7 @@ import (
func NeedWarnDiskUsage(dataSize int64) bool {
usage, err := disk.Usage(WorkspaceDir)
if nil != err {
if err != nil {
logging.LogErrorf("get disk usage failed: %s", err)
return false
}

View file

@ -37,7 +37,7 @@ import (
func GetFilePathsByExts(dirPath string, exts []string) (ret []string) {
filelock.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if nil != err {
if err != nil {
logging.LogErrorf("get file paths by ext failed: %s", err)
return err
}
@ -79,7 +79,7 @@ func GetMimeTypeByExt(filePath string) (ret string) {
ret = mime.TypeByExtension(filepath.Ext(filePath))
if "" == ret {
m, err := mimetype.DetectFile(filePath)
if nil != err {
if err != nil {
logging.LogErrorf("detect mime type of [%s] failed: %s", filePath, err)
return
}
@ -92,7 +92,7 @@ func GetMimeTypeByExt(filePath string) (ret string) {
func IsSymlinkPath(absPath string) bool {
fi, err := os.Lstat(absPath)
if nil != err {
if err != nil {
return false
}
return 0 != fi.Mode()&os.ModeSymlink
@ -104,7 +104,7 @@ func IsEmptyDir(p string) bool {
}
files, err := os.ReadDir(p)
if nil != err {
if err != nil {
return false
}
return 1 > len(files)
@ -124,7 +124,7 @@ func IsPathRegularDirOrSymlinkDir(path string) bool {
return false
}
if nil != err {
if err != nil {
return false
}
@ -276,7 +276,7 @@ func IsSubPath(absPath, toCheckPath string) bool {
func SizeOfDirectory(path string) (size int64, err error) {
err = filelock.Walk(path, func(_ string, info os.FileInfo, err error) error {
if nil != err {
if err != nil {
return err
}
if !info.IsDir() {
@ -287,7 +287,7 @@ func SizeOfDirectory(path string) (size int64, err error) {
}
return nil
})
if nil != err {
if err != nil {
logging.LogErrorf("size of dir [%s] failed: %s", path, err)
}
return
@ -295,7 +295,7 @@ func SizeOfDirectory(path string) (size int64, err error) {
func DataSize() (dataSize, assetsSize int64) {
filelock.Walk(DataDir, func(path string, info os.FileInfo, err error) error {
if nil != err {
if err != nil {
if os.IsNotExist(err) {
return nil
}

View file

@ -63,19 +63,19 @@ func loadFonts(currentLanguage string) (ret []*Font) {
for _, fontPath := range findfont.List() {
if strings.HasSuffix(strings.ToLower(fontPath), ".ttc") {
data, err := os.ReadFile(fontPath)
if nil != err {
if err != nil {
logging.LogErrorf("read font file [%s] failed: %s", fontPath, err)
continue
}
collection, err := ttc.ParseCollection(data)
if nil != err {
if err != nil {
//LogErrorf("parse font collection [%s] failed: %s", fontPath, err)
continue
}
for i := 0; i < collection.NumFonts(); i++ {
font, err := collection.Font(i)
if nil != err {
if err != nil {
//LogErrorf("get font [%s] failed: %s", fontPath, err)
continue
}
@ -86,18 +86,18 @@ func loadFonts(currentLanguage string) (ret []*Font) {
}
} else if strings.HasSuffix(strings.ToLower(fontPath), ".otf") || strings.HasSuffix(strings.ToLower(fontPath), ".ttf") {
fontFile, err := os.Open(fontPath)
if nil != err {
if err != nil {
//LogErrorf("open font file [%s] failed: %s", fontPath, err)
continue
}
font, err := sfnt.Parse(fontFile)
if nil != err {
if err != nil {
//LogErrorf("parse font [%s] failed: %s", fontPath, err)
continue
}
t, err := font.NameTable()
if nil != err {
if err != nil {
//LogErrorf("parse font name table [%s] failed: %s", fontPath, err)
return
}
@ -110,7 +110,7 @@ func loadFonts(currentLanguage string) (ret []*Font) {
if sfnt.PlatformLanguageID(1033) == e.LanguageID {
v, _, err := transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.IgnoreBOM).NewDecoder(), e.Value)
if nil != err {
if err != nil {
//LogErrorf("decode font family [%s] failed: %s", fontPath, err)
continue
}
@ -127,7 +127,7 @@ func loadFonts(currentLanguage string) (ret []*Font) {
}
v, _, err := transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.IgnoreBOM).NewDecoder(), e.Value)
if nil != err {
if err != nil {
//LogErrorf("decode font family [%s] failed: %s", fontPath, err)
continue
}

View file

@ -94,7 +94,7 @@ func NewStdLute() (ret *lute.Lute) {
func LinkTarget(htmlStr, linkBase string) (ret string) {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlStr))
if nil != err {
if err != nil {
logging.LogErrorf("parse HTML failed: %s", err)
return
}

View file

@ -146,7 +146,7 @@ func Convert2Float(s string) (float64, bool) {
}
s = buf.String()
ret, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
if nil != err {
if err != nil {
return 0, false
}
return ret, true

View file

@ -58,7 +58,7 @@ func IsLocalHostname(hostname string) bool {
}
func IsLocalHost(host string) bool {
if hostname, _, err := net.SplitHostPort(strings.TrimSpace(host)); nil != err {
if hostname, _, err := net.SplitHostPort(strings.TrimSpace(host)); err != nil {
return false
} else {
return IsLocalHostname(hostname)
@ -66,7 +66,7 @@ func IsLocalHost(host string) bool {
}
func IsLocalOrigin(origin string) bool {
if url, err := url.Parse(origin); nil == err {
if url, err := url.Parse(origin); err == nil {
return IsLocalHostname(url.Hostname())
}
return false
@ -74,7 +74,7 @@ func IsLocalOrigin(origin string) bool {
func IsOnline(checkURL string, skipTlsVerify bool) bool {
_, err := url.Parse(checkURL)
if nil != err {
if err != nil {
logging.LogWarnf("invalid check URL [%s]", checkURL)
return false
}
@ -94,7 +94,7 @@ func IsOnline(checkURL string, skipTlsVerify bool) bool {
func IsPortOpen(port string) bool {
timeout := time.Second
conn, err := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", port), timeout)
if nil != err {
if err != nil {
return false
}
if nil != conn {
@ -127,7 +127,7 @@ func isOnline(checkURL string, skipTlsVerify bool) (ret bool) {
}
}
ret = nil == err
ret = err == nil
if ret {
break
}
@ -153,7 +153,7 @@ func GetRemoteAddr(req *http.Request) string {
func JsonArg(c *gin.Context, result *gulu.Result) (arg map[string]interface{}, ok bool) {
arg = map[string]interface{}{}
if err := c.BindJSON(&arg); nil != err {
if err := c.BindJSON(&arg); err != nil {
result.Code = -1
result.Msg = "parses request failed"
return
@ -175,7 +175,7 @@ func InvalidIDPattern(idArg string, result *gulu.Result) bool {
func IsValidURL(str string) bool {
_, err := url.Parse(str)
return nil == err
return err == nil
}
func initHttpClient() {

View file

@ -79,15 +79,15 @@ func LoadAssetsTexts() {
start := time.Now()
data, err := filelock.ReadFile(assetsTextsPath)
if nil != err {
if err != nil {
logging.LogErrorf("read assets texts failed: %s", err)
return
}
assetsTextsLock.Lock()
if err = gulu.JSON.UnmarshalJSON(data, &assetsTexts); nil != err {
if err = gulu.JSON.UnmarshalJSON(data, &assetsTexts); err != nil {
logging.LogErrorf("unmarshal assets texts failed: %s", err)
if err = filelock.Remove(assetsTextsPath); nil != err {
if err = filelock.Remove(assetsTextsPath); err != nil {
logging.LogErrorf("removed corrupted assets texts failed: %s", err)
}
return
@ -110,7 +110,7 @@ func SaveAssetsTexts() {
assetsTextsLock.Lock()
data, err := gulu.JSON.MarshalIndentJSON(assetsTexts, "", " ")
if nil != err {
if err != nil {
logging.LogErrorf("marshal assets texts failed: %s", err)
return
}
@ -118,7 +118,7 @@ func SaveAssetsTexts() {
assetsPath := GetDataAssetsAbsPath()
assetsTextsPath := filepath.Join(assetsPath, "ocr-texts.json")
if err = filelock.WriteFile(assetsTextsPath, data); nil != err {
if err = filelock.WriteFile(assetsTextsPath, data); err != nil {
logging.LogErrorf("write assets texts failed: %s", err)
return
}
@ -192,7 +192,7 @@ func Tesseract(imgAbsPath string) (ret []map[string]interface{}) {
}
info, err := os.Stat(imgAbsPath)
if nil != err {
if err != nil {
return
}
@ -213,7 +213,7 @@ func Tesseract(imgAbsPath string) (ret []map[string]interface{}) {
return
}
if nil != err {
if err != nil {
logging.LogWarnf("tesseract [path=%s, size=%d] failed: %s", imgAbsPath, info.Size(), err)
return
}
@ -341,14 +341,14 @@ func getTesseractVer() (ret string) {
cmd := exec.Command(TesseractBin, "--version")
gulu.CmdAttr(cmd)
data, err := cmd.CombinedOutput()
if nil != err {
if err != nil {
if strings.Contains(err.Error(), "executable file not found") {
// macOS 端 Tesseract OCR 安装后不识别 https://github.com/siyuan-note/siyuan/issues/7107
TesseractBin = "/usr/local/bin/tesseract"
cmd = exec.Command(TesseractBin, "--version")
gulu.CmdAttr(cmd)
data, err = cmd.CombinedOutput()
if nil != err && strings.Contains(err.Error(), "executable file not found") {
if err != nil && strings.Contains(err.Error(), "executable file not found") {
TesseractBin = "/opt/homebrew/bin/tesseract"
cmd = exec.Command(TesseractBin, "--version")
gulu.CmdAttr(cmd)
@ -356,7 +356,7 @@ func getTesseractVer() (ret string) {
}
}
}
if nil != err {
if err != nil {
return
}
@ -380,7 +380,7 @@ func getTesseractLangs() (ret []string) {
cmd := exec.Command(TesseractBin, "--list-langs")
gulu.CmdAttr(cmd)
data, err := cmd.CombinedOutput()
if nil != err {
if err != nil {
return nil
}

View file

@ -50,7 +50,7 @@ func ChatGPT(msg string, contextMsgs []string, c *openai.Client, model string, m
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
resp, err := c.CreateChatCompletion(ctx, req)
if nil != err {
if err != nil {
PushErrMsg("Requesting failed, please check kernel log for more details", 3000)
logging.LogErrorf("create chat completion failed: %s", err)
stop = true
@ -86,7 +86,7 @@ func NewOpenAIClient(apiKey, apiProxy, apiBaseURL, apiUserAgent, apiVersion, api
transport := &http.Transport{}
if "" != apiProxy {
proxyUrl, err := url.Parse(apiProxy)
if nil != err {
if err != nil {
logging.LogErrorf("OpenAI API proxy failed: %v", err)
} else {
transport.Proxy = http.ProxyURL(proxyUrl)

View file

@ -25,7 +25,7 @@ import (
func GetOSPlatform() (plat string) {
plat, _, _, err := host.PlatformInformation()
if nil != err {
if err != nil {
logging.LogWarnf("get os platform failed: %s", err)
return "Unknown"
}

View file

@ -42,13 +42,13 @@ func ConvertPandoc(dir string, args ...string) (path string, err error) {
gulu.CmdAttr(pandoc)
path = filepath.Join("temp", "convert", "pandoc", dir)
absPath := filepath.Join(WorkspaceDir, path)
if err = os.MkdirAll(absPath, 0755); nil != err {
if err = os.MkdirAll(absPath, 0755); err != nil {
logging.LogErrorf("mkdir [%s] failed: [%s]", absPath, err)
return
}
pandoc.Dir = absPath
output, err := pandoc.CombinedOutput()
if nil != err {
if err != nil {
err = errors.Join(err, errors.New(string(output)))
logging.LogErrorf("pandoc convert output failed: %s", err)
return
@ -59,7 +59,7 @@ func ConvertPandoc(dir string, args ...string) (path string, err error) {
func Pandoc(from, to, o, content string) (err error) {
if "" == from || "" == to || "md" == to {
if err = gulu.File.WriteFileSafer(o, []byte(content), 0644); nil != err {
if err = gulu.File.WriteFileSafer(o, []byte(content), 0644); err != nil {
logging.LogErrorf("write export markdown file [%s] failed: %s", o, err)
}
return
@ -71,12 +71,12 @@ func Pandoc(from, to, o, content string) (err error) {
}
dir := filepath.Join(WorkspaceDir, "temp", "convert", "pandoc", gulu.Rand.String(7))
if err = os.MkdirAll(dir, 0755); nil != err {
if err = os.MkdirAll(dir, 0755); err != nil {
logging.LogErrorf("mkdir [%s] failed: [%s]", dir, err)
return
}
tmpPath := filepath.Join(dir, gulu.Rand.String(7))
if err = os.WriteFile(tmpPath, []byte(content), 0644); nil != err {
if err = os.WriteFile(tmpPath, []byte(content), 0644); err != nil {
logging.LogErrorf("write file failed: [%s]", err)
return
}
@ -93,7 +93,7 @@ func Pandoc(from, to, o, content string) (err error) {
pandoc := exec.Command(PandocBinPath, args...)
gulu.CmdAttr(pandoc)
output, err := pandoc.CombinedOutput()
if nil != err {
if err != nil {
logging.LogErrorf("pandoc convert output [%s], error [%s]", string(output), err)
return
}
@ -113,9 +113,9 @@ func InitPandoc() {
if confPath := filepath.Join(ConfDir, "conf.json"); gulu.File.IsExist(confPath) {
// Workspace built-in Pandoc is no longer initialized after customizing Pandoc path https://github.com/siyuan-note/siyuan/issues/8377
if data, err := os.ReadFile(confPath); nil == err {
if data, err := os.ReadFile(confPath); err == nil {
conf := map[string]interface{}{}
if err = gulu.JSON.UnmarshalJSON(data, &conf); nil == err && nil != conf["export"] {
if err = gulu.JSON.UnmarshalJSON(data, &conf); err == nil && nil != conf["export"] {
export := conf["export"].(map[string]interface{})
if customPandocBinPath := export["pandocBin"].(string); !strings.HasPrefix(customPandocBinPath, pandocDir) {
if pandocVer := getPandocVer(customPandocBinPath); "" != pandocVer {
@ -164,7 +164,7 @@ func InitPandoc() {
return
}
if err := gulu.Zip.Unzip(pandocZip, pandocDir); nil != err {
if err := gulu.Zip.Unzip(pandocZip, pandocDir); err != nil {
logging.LogErrorf("unzip pandoc failed: %s", err)
return
}
@ -184,7 +184,7 @@ func getPandocVer(binPath string) (ret string) {
cmd := exec.Command(binPath, "--version")
gulu.CmdAttr(cmd)
data, err := cmd.CombinedOutput()
if nil == err && strings.HasPrefix(string(data), "pandoc") {
if err == nil && strings.HasPrefix(string(data), "pandoc") {
parts := bytes.Split(data, []byte("\n"))
if 0 < len(parts) {
ret = strings.TrimPrefix(string(parts[0]), "pandoc")
@ -204,7 +204,7 @@ func IsValidPandocBin(binPath string) bool {
cmd := exec.Command(binPath, "--version")
gulu.CmdAttr(cmd)
data, err := cmd.CombinedOutput()
if nil == err && strings.HasPrefix(string(data), "pandoc") {
if err == nil && strings.HasPrefix(string(data), "pandoc") {
return true
}
return false

View file

@ -57,7 +57,7 @@ func GetLocalIPs() (ret []string) {
ret = []string{}
addrs, err := net.InterfaceAddrs()
if nil != err {
if err != nil {
logging.LogWarnf("get interface addresses failed: %s", err)
return
}

View file

@ -64,7 +64,7 @@ func NewCmdResult(cmdName string, cmdId float64, pushMode PushMode) *Result {
func (r *Result) Bytes() []byte {
ret, err := gulu.JSON.MarshalJSON(r)
if nil != err {
if err != nil {
logging.LogErrorf("marshal result [%+v] failed [%s]", r, err)
}
return ret

View file

@ -46,7 +46,7 @@ func GetRhyResult(force bool) (map[string]interface{}, error) {
request := httpclient.NewCloudRequest30s()
resp, err := request.SetSuccessResult(&cachedRhyResult).Get(GetCloudServer() + "/apis/siyuan/version?ver=" + Ver)
if nil != err {
if err != nil {
logging.LogErrorf("get version info failed: %s", err)
return nil, err
}

View file

@ -93,7 +93,7 @@ func RandomSleep(minMills, maxMills int) {
func GetDeviceID() string {
if ContainerStd == Container {
machineID, err := machineid.ID()
if nil != err {
if err != nil {
return gulu.Rand.String(12)
}
return machineID
@ -103,17 +103,17 @@ func GetDeviceID() string {
func GetDeviceName() string {
ret, err := os.Hostname()
if nil != err {
if err != nil {
return "unknown"
}
return ret
}
func SetNetworkProxy(proxyURL string) {
if err := os.Setenv("HTTPS_PROXY", proxyURL); nil != err {
if err := os.Setenv("HTTPS_PROXY", proxyURL); err != nil {
logging.LogErrorf("set env [HTTPS_PROXY] failed: %s", err)
}
if err := os.Setenv("HTTP_PROXY", proxyURL); nil != err {
if err := os.Setenv("HTTP_PROXY", proxyURL); err != nil {
logging.LogErrorf("set env [HTTP_PROXY] failed: %s", err)
}
@ -186,12 +186,12 @@ func checkFileSysStatus() {
}
dir := filepath.Join(DataDir, fileSysStatusCheckFile)
if err := os.RemoveAll(dir); nil != err {
if err := os.RemoveAll(dir); err != nil {
ReportFileSysFatalError(err)
return
}
if err := os.MkdirAll(dir, 0755); nil != err {
if err := os.MkdirAll(dir, 0755); err != nil {
ReportFileSysFatalError(err)
return
}
@ -200,12 +200,12 @@ func checkFileSysStatus() {
tmp := filepath.Join(dir, "check_consistency")
data := make([]byte, 1024*4)
_, err := rand.Read(data)
if nil != err {
if err != nil {
ReportFileSysFatalError(err)
return
}
if err = os.WriteFile(tmp, data, 0644); nil != err {
if err = os.WriteFile(tmp, data, 0644); err != nil {
ReportFileSysFatalError(err)
return
}
@ -214,7 +214,7 @@ func checkFileSysStatus() {
for j := 0; j < 32; j++ {
renamed := tmp + "_renamed"
if err = os.Rename(tmp, renamed); nil != err {
if err = os.Rename(tmp, renamed); err != nil {
ReportFileSysFatalError(err)
break
}
@ -222,23 +222,23 @@ func checkFileSysStatus() {
RandomSleep(500, 1000)
f, err := os.Open(renamed)
if nil != err {
if err != nil {
ReportFileSysFatalError(err)
return
}
if err = f.Close(); nil != err {
if err = f.Close(); err != nil {
ReportFileSysFatalError(err)
return
}
if err = os.Rename(renamed, tmp); nil != err {
if err = os.Rename(renamed, tmp); err != nil {
ReportFileSysFatalError(err)
return
}
entries, err := os.ReadDir(dir)
if nil != err {
if err != nil {
ReportFileSysFatalError(err)
return
}
@ -264,7 +264,7 @@ func checkFileSysStatus() {
}
}
if err = os.RemoveAll(tmp); nil != err {
if err = os.RemoveAll(tmp); err != nil {
ReportFileSysFatalError(err)
return
}
@ -343,33 +343,33 @@ func existAvailabilityStatus(workspaceAbsPath string) bool {
runtime.LockOSThread()
defer runtime.LockOSThread()
if err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED); nil != err {
if err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED); err != nil {
logging.LogWarnf("initialize ole failed: %s", err)
return false
}
defer ole.CoUninitialize()
dir, file := filepath.Split(checkAbsPath)
unknown, err := oleutil.CreateObject("Shell.Application")
if nil != err {
if err != nil {
logging.LogWarnf("create shell application failed: %s", err)
return false
}
shell, err := unknown.QueryInterface(ole.IID_IDispatch)
if nil != err {
if err != nil {
logging.LogWarnf("query shell interface failed: %s", err)
return false
}
defer shell.Release()
result, err := oleutil.CallMethod(shell, "NameSpace", dir)
if nil != err {
if err != nil {
logging.LogWarnf("call shell [NameSpace] failed: %s", err)
return false
}
folderObj := result.ToIDispatch()
result, err = oleutil.CallMethod(folderObj, "ParseName", file)
if nil != err {
if err != nil {
logging.LogWarnf("call shell [ParseName] failed: %s", err)
return false
}
@ -380,7 +380,7 @@ func existAvailabilityStatus(workspaceAbsPath string) bool {
}
result, err = oleutil.CallMethod(folderObj, "GetDetailsOf", fileObj, 303)
if nil != err {
if err != nil {
logging.LogWarnf("call shell [GetDetailsOf] failed: %s", err)
return false
}

View file

@ -42,7 +42,7 @@ type WorkspaceSession struct {
func (sd *SessionData) Save(c *gin.Context) error {
session := ginSessions.Default(c)
sessionDataBytes, err := gulu.JSON.MarshalJSON(sd)
if nil != err {
if err != nil {
return err
}
session.Set("data", string(sessionDataBytes))
@ -60,7 +60,7 @@ func GetSession(c *gin.Context) *SessionData {
}
err := gulu.JSON.UnmarshalJSON([]byte(sessionDataStr.(string)), ret)
if nil != err {
if err != nil {
return ret
}

View file

@ -53,7 +53,7 @@ func logf(a, b interface{}) float64 { return math.Log(cast.ToFloat64(a)) / math.
func parseTime(dateStr string) time.Time {
now := time.Now()
retTime, err := dateparse.ParseIn(dateStr, now.Location())
if nil != err {
if err != nil {
logging.LogWarnf("parse date [%s] failed [%s], return current time instead", dateStr, err)
return now
}

View file

@ -56,7 +56,7 @@ var (
func initEnvVars() {
RunInContainer = isRunningInDockerContainer()
var err error
if SiyuanAccessAuthCodeBypass, err = strconv.ParseBool(os.Getenv("SIYUAN_ACCESS_AUTH_CODE_BYPASS")); nil != err {
if SiyuanAccessAuthCodeBypass, err = strconv.ParseBool(os.Getenv("SIYUAN_ACCESS_AUTH_CODE_BYPASS")); err != nil {
SiyuanAccessAuthCodeBypass = false
}
}
@ -224,7 +224,7 @@ func initWorkspaceDir(workspaceArg string) {
logging.SetLogPath(filepath.Join(userHomeConfDir, "kernel.log"))
if !gulu.File.IsExist(workspaceConf) {
if err := os.MkdirAll(userHomeConfDir, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(userHomeConfDir, 0755); err != nil && !os.IsExist(err) {
logging.LogErrorf("create user home conf folder [%s] failed: %s", userHomeConfDir, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}
@ -256,7 +256,7 @@ func initWorkspaceDir(workspaceArg string) {
if !gulu.File.IsDir(WorkspaceDir) {
logging.LogWarnf("use the default workspace [%s] since the specified workspace [%s] is not a dir", defaultWorkspaceDir, WorkspaceDir)
if err := os.MkdirAll(defaultWorkspaceDir, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(defaultWorkspaceDir, 0755); err != nil && !os.IsExist(err) {
logging.LogErrorf("create default workspace folder [%s] failed: %s", defaultWorkspaceDir, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}
@ -264,7 +264,7 @@ func initWorkspaceDir(workspaceArg string) {
}
workspacePaths = append(workspacePaths, WorkspaceDir)
if err := WriteWorkspacePaths(workspacePaths); nil != err {
if err := WriteWorkspacePaths(workspacePaths); err != nil {
logging.LogErrorf("write workspace conf [%s] failed: %s", workspaceConf, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}
@ -276,7 +276,7 @@ func initWorkspaceDir(workspaceArg string) {
TempDir = filepath.Join(WorkspaceDir, "temp")
osTmpDir := filepath.Join(TempDir, "os")
os.RemoveAll(osTmpDir)
if err := os.MkdirAll(osTmpDir, 0755); nil != err {
if err := os.MkdirAll(osTmpDir, 0755); err != nil {
logging.LogErrorf("create os tmp dir [%s] failed: %s", osTmpDir, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}
@ -295,14 +295,14 @@ func ReadWorkspacePaths() (ret []string, err error) {
ret = []string{}
workspaceConf := filepath.Join(HomeDir, ".config", "siyuan", "workspace.json")
data, err := os.ReadFile(workspaceConf)
if nil != err {
if err != nil {
msg := fmt.Sprintf("read workspace conf [%s] failed: %s", workspaceConf, err)
logging.LogErrorf(msg)
err = errors.New(msg)
return
}
if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err {
if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil {
msg := fmt.Sprintf("unmarshal workspace conf [%s] failed: %s", workspaceConf, err)
logging.LogErrorf(msg)
err = errors.New(msg)
@ -325,14 +325,14 @@ func WriteWorkspacePaths(workspacePaths []string) (err error) {
workspacePaths = gulu.Str.RemoveDuplicatedElem(workspacePaths)
workspaceConf := filepath.Join(HomeDir, ".config", "siyuan", "workspace.json")
data, err := gulu.JSON.MarshalJSON(workspacePaths)
if nil != err {
if err != nil {
msg := fmt.Sprintf("marshal workspace conf [%s] failed: %s", workspaceConf, err)
logging.LogErrorf(msg)
err = errors.New(msg)
return
}
if err = filelock.WriteFile(workspaceConf, data); nil != err {
if err = filelock.WriteFile(workspaceConf, data); err != nil {
msg := fmt.Sprintf("write workspace conf [%s] failed: %s", workspaceConf, err)
logging.LogErrorf(msg)
err = errors.New(msg)
@ -364,44 +364,44 @@ const (
)
func initPathDir() {
if err := os.MkdirAll(ConfDir, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(ConfDir, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create conf folder [%s] failed: %s", ConfDir, err)
}
if err := os.MkdirAll(DataDir, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(DataDir, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data folder [%s] failed: %s", DataDir, err)
}
if err := os.MkdirAll(TempDir, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(TempDir, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create temp folder [%s] failed: %s", TempDir, err)
}
assets := filepath.Join(DataDir, "assets")
if err := os.MkdirAll(assets, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(assets, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data assets folder [%s] failed: %s", assets, err)
}
templates := filepath.Join(DataDir, "templates")
if err := os.MkdirAll(templates, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(templates, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data templates folder [%s] failed: %s", templates, err)
}
widgets := filepath.Join(DataDir, "widgets")
if err := os.MkdirAll(widgets, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(widgets, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data widgets folder [%s] failed: %s", widgets, err)
}
plugins := filepath.Join(DataDir, "plugins")
if err := os.MkdirAll(plugins, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(plugins, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data plugins folder [%s] failed: %s", widgets, err)
}
emojis := filepath.Join(DataDir, "emojis")
if err := os.MkdirAll(emojis, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(emojis, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data emojis folder [%s] failed: %s", widgets, err)
}
// Support directly access `data/public/*` contents via URL link https://github.com/siyuan-note/siyuan/issues/8593
public := filepath.Join(DataDir, "public")
if err := os.MkdirAll(public, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(public, 0755); err != nil && !os.IsExist(err) {
logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data public folder [%s] failed: %s", widgets, err)
}
}
@ -438,7 +438,7 @@ func GetDataAssetsAbsPath() (ret string) {
// 跟随符号链接 https://github.com/siyuan-note/siyuan/issues/5480
var err error
ret, err = filepath.EvalSymlinks(ret)
if nil != err {
if err != nil {
logging.LogErrorf("read assets link failed: %s", err)
}
}
@ -451,7 +451,7 @@ func tryLockWorkspace() {
if ok {
return
}
if nil != err {
if err != nil {
logging.LogErrorf("lock workspace [%s] failed: %s", WorkspaceDir, err)
} else {
logging.LogErrorf("lock workspace [%s] failed", WorkspaceDir)
@ -483,12 +483,12 @@ func UnlockWorkspace() {
return
}
if err := WorkspaceLock.Unlock(); nil != err {
if err := WorkspaceLock.Unlock(); err != nil {
logging.LogErrorf("unlock workspace [%s] failed: %s", WorkspaceDir, err)
return
}
if err := os.Remove(filepath.Join(WorkspaceDir, ".lock")); nil != err {
if err := os.Remove(filepath.Join(WorkspaceDir, ".lock")); err != nil {
logging.LogErrorf("remove workspace lock failed: %s", err)
return
}

View file

@ -46,14 +46,14 @@ func BootMobile(container, appDir, workspaceBaseDir, lang string) {
logging.SetLogPath(filepath.Join(userHomeConfDir, "kernel.log"))
if !gulu.File.IsExist(userHomeConfDir) {
if err := os.MkdirAll(userHomeConfDir, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(userHomeConfDir, 0755); err != nil && !os.IsExist(err) {
logging.LogErrorf("create user home conf folder [%s] failed: %s", userHomeConfDir, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}
}
defaultWorkspaceDir := filepath.Join(workspaceBaseDir, "siyuan")
if err := os.MkdirAll(defaultWorkspaceDir, 0755); nil != err && !os.IsExist(err) {
if err := os.MkdirAll(defaultWorkspaceDir, 0755); err != nil && !os.IsExist(err) {
logging.LogErrorf("create default workspace folder [%s] failed: %s", defaultWorkspaceDir, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}
@ -69,7 +69,7 @@ func BootMobile(container, appDir, workspaceBaseDir, lang string) {
func initWorkspaceDirMobile(workspaceBaseDir string) {
if gulu.File.IsDir(workspaceBaseDir) {
entries, err := os.ReadDir(workspaceBaseDir)
if nil != err {
if err != nil {
logging.LogErrorf("read workspace dir [%s] failed: %s", workspaceBaseDir, err)
} else {
// 旧版 iOS 端会在 workspaceBaseDir 下直接创建工作空间,这里需要将数据迁移到 workspaceBaseDir/siyuan/ 文件夹下
@ -96,7 +96,7 @@ func initWorkspaceDirMobile(workspaceBaseDir string) {
from := filepath.Join(workspaceBaseDir, entry.Name())
to := filepath.Join(workspaceBaseDir, "siyuan", entry.Name())
if err = os.Rename(from, to); nil != err {
if err = os.Rename(from, to); err != nil {
logging.LogErrorf("move workspace dir [%s] failed: %s", workspaceBaseDir, err)
} else {
logging.LogInfof("moved workspace dir [fomr=%s, to=%s]", from, to)
@ -136,7 +136,7 @@ func initWorkspaceDirMobile(workspaceBaseDir string) {
}
}
if err := WriteWorkspacePaths(workspacePaths); nil != err {
if err := WriteWorkspacePaths(workspacePaths); err != nil {
logging.LogErrorf("write workspace conf [%s] failed: %s", workspaceConf, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}
@ -148,7 +148,7 @@ func initWorkspaceDirMobile(workspaceBaseDir string) {
TempDir = filepath.Join(WorkspaceDir, "temp")
osTmpDir := filepath.Join(TempDir, "os")
os.RemoveAll(osTmpDir)
if err := os.MkdirAll(osTmpDir, 0755); nil != err {
if err := os.MkdirAll(osTmpDir, 0755); err != nil {
logging.LogErrorf("create os tmp dir [%s] failed: %s", osTmpDir, err)
os.Exit(logging.ExitCodeInitWorkspaceErr)
}