diff --git a/app/appearance/langs/en_US.json b/app/appearance/langs/en_US.json index d58e30469..edb0a8579 100644 --- a/app/appearance/langs/en_US.json +++ b/app/appearance/langs/en_US.json @@ -1381,7 +1381,7 @@ "88": "Finished parsing [%d] data files, remaining to be processed [%d]", "89": "[%d/%d] Created [%d] of data indexes of block-level elements [%s]", "90": "[%d/%d] Created [%d] of search indexes of block-level elements [%s]", - "91": "TODO", + "91": "Cleaning up unreferenced assets is complete. [%d] files have been deleted, freeing up a total of [%s] disk space", "92": "Parsing document tree [%s]", "93": "[%d/%d] Cleaned up the index related to document [%s]", "94": "Upload failed: %s", diff --git a/app/appearance/langs/es_ES.json b/app/appearance/langs/es_ES.json index c61e6ab57..bdd9e93e1 100644 --- a/app/appearance/langs/es_ES.json +++ b/app/appearance/langs/es_ES.json @@ -1381,7 +1381,7 @@ "88": "Se ha terminado de analizar [%d] archivos de datos, quedan por procesar [%d]", "89": "[%d/%d] Creado [%d] de índices de datos de elementos a nivel de bloque [%s]", "90": "[%d/%d] Creado [%d] de índices de búsqueda de elementos a nivel de bloque [%s]", - "91": "TODO", + "91": "Se completó la limpieza de archivos de recursos sin referencia, se eliminaron [%d] archivos y se liberó un total de [%s] espacio en disco.", "92": "Analizando el árbol del documento [%s]", "93": "[%d/%d] ha limpiado el índice relacionado con el documento [%s]", "94": "Carga fallida: %s", diff --git a/app/appearance/langs/fr_FR.json b/app/appearance/langs/fr_FR.json index 7a3baf109..36ca9b5b6 100644 --- a/app/appearance/langs/fr_FR.json +++ b/app/appearance/langs/fr_FR.json @@ -1381,7 +1381,7 @@ "88": "Fin de l'analyse des fichiers de données [%d], restant à traiter [%d]", "89": "[%d/%d] Créé [%d] d'index de données d'éléments de niveau bloc [%s]", "90": "[%d/%d] Création de [%d] index de recherche d'éléments de niveau bloc [%s]", - "91": "TODO", + "91": "Le nettoyage des fichiers de ressources non référencés est terminé, [%d] fichiers ont été supprimés et un total de [%s] espace disque a été libéré.", "92": "Analyse de l'arborescence du document [%s]", "93": "[%d/%d] a nettoyé l'index lié au document [%s]", "94": "Échec du téléchargement : %s", diff --git a/app/appearance/langs/ja_JP.json b/app/appearance/langs/ja_JP.json index f62c42002..ba338697e 100644 --- a/app/appearance/langs/ja_JP.json +++ b/app/appearance/langs/ja_JP.json @@ -1381,7 +1381,7 @@ "88": "[%d] 個のデータファイルの解析が完了し、処理待ちのデータファイルが [%d] 個残っています", "89": "[%d/%d] ブロックレベル要素 [%s] のデータインデックスを [%d] 個作成しました", "90": "[%d/%d] ブロックレベル要素 [%s] の検索インデックスを [%d] 個作成しました", - "91": "TODO", + "91": "参照されていないリソース ファイルのクリーンアップが完了し、[%d] ファイルが削除され、合計 [%s] 個のディスク領域が解放されました。", "92": "ドキュメントツリーを解析しています [%s]", "93": "[%d/%d] ドキュメント [%s] に関連するインデックスをクリーンアップしました", "94": "アップロードに失敗しました: %s", diff --git a/app/appearance/langs/zh_CHT.json b/app/appearance/langs/zh_CHT.json index 1b8417e63..a264cd55c 100644 --- a/app/appearance/langs/zh_CHT.json +++ b/app/appearance/langs/zh_CHT.json @@ -1381,7 +1381,7 @@ "88": "已完成解析 [%d] 個資料文件,剩餘待處理 [%d]", "89": "[%d/%d] 已經創建 [%d] 個塊級元素的資料索引 [%s]", "90": "[%d/%d] 已經創建 [%d] 個塊級元素的搜索索引 [%s]", - "91": "TODO", + "91": "清理未引用的資源文件完畢,已刪除 [%d] 個文件,共釋放 [%s] 磁碟空間", "92": "正在解析文檔樹 [%s]", "93": "[%d/%d] 已經清理文檔 [%s] 相關的索引", "94": "上傳失敗:%s", diff --git a/app/appearance/langs/zh_CN.json b/app/appearance/langs/zh_CN.json index 41863c11f..31d9807a1 100644 --- a/app/appearance/langs/zh_CN.json +++ b/app/appearance/langs/zh_CN.json @@ -1381,7 +1381,7 @@ "88": "已完成解析 [%d] 个数据文件,剩余待处理 [%d]", "89": "[%d/%d] 已经创建 [%d] 个块级元素的数据索引 [%s]", "90": "[%d/%d] 已经创建 [%d] 个块级元素的搜索索引 [%s]", - "91": "TODO", + "91": "清理未引用的资源文件完毕,已删除 [%d] 个文件,共释放 [%s] 磁盘空间", "92": "正在解析文档树 [%s]", "93": "[%d/%d] 已经清理文档 [%s] 相关的索引", "94": "上传失败:%s", diff --git a/app/src/protyle/util/resize.ts b/app/src/protyle/util/resize.ts index 354304a7c..e30f24a70 100644 --- a/app/src/protyle/util/resize.ts +++ b/app/src/protyle/util/resize.ts @@ -29,11 +29,8 @@ export const resize = (protyle: IProtyle) => { }); } protyle.wysiwyg.element.querySelectorAll(".code-block .protyle-linenumber__rows").forEach((item: HTMLElement) => { - const block = item.parentElement; - if ((window.siyuan.config.editor.codeSyntaxHighlightLineNum && block.parentElement.getAttribute("lineNumber") !== "false" && - window.siyuan.config.editor.codeLineWrap && block.parentElement.getAttribute("linewrap") !== "false") || - (block.parentElement.getAttribute("lineNumber") === "true" && block.parentElement.getAttribute("linewrap") === "true")) { - lineNumberRender(block); + if ((item.nextElementSibling as HTMLElement).style.wordBreak === "break-word") { + lineNumberRender(item.parentElement); } }); // 保持光标位置不变 https://ld246.com/article/1673704873983/comment/1673765814595#comments diff --git a/kernel/api/account.go b/kernel/api/account.go index 77d1dbb8c..9b2958838 100644 --- a/kernel/api/account.go +++ b/kernel/api/account.go @@ -30,7 +30,7 @@ func startFreeTrial(c *gin.Context) { defer c.JSON(http.StatusOK, ret) err := model.StartFreeTrial() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -48,7 +48,7 @@ func useActivationcode(c *gin.Context) { code := arg["data"].(string) err := model.UseActivationcode(code) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -73,7 +73,7 @@ func deactivateUser(c *gin.Context) { defer c.JSON(http.StatusOK, ret) err := model.DeactivateUser() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/archive.go b/kernel/api/archive.go index a886474e8..b64486be2 100644 --- a/kernel/api/archive.go +++ b/kernel/api/archive.go @@ -36,7 +36,7 @@ func zip(c *gin.Context) { entryPath := arg["path"].(string) entryAbsPath, err := util.GetAbsPathInWorkspace(entryPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -44,14 +44,14 @@ func zip(c *gin.Context) { zipFilePath := arg["zipPath"].(string) zipAbsFilePath, err := util.GetAbsPathInWorkspace(zipFilePath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } zipFile, err := gulu.Zip.Create(zipAbsFilePath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -63,13 +63,13 @@ func zip(c *gin.Context) { } else { err = zipFile.AddEntry(base, entryAbsPath) } - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } - if err = zipFile.Close(); nil != err { + if err = zipFile.Close(); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -87,7 +87,7 @@ func unzip(c *gin.Context) { zipFilePath := arg["zipPath"].(string) zipAbsFilePath, err := util.GetAbsPathInWorkspace(zipFilePath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -95,13 +95,13 @@ func unzip(c *gin.Context) { entryPath := arg["path"].(string) entryAbsPath, err := util.GetAbsPathInWorkspace(entryPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } - if err := gulu.Zip.Unzip(zipAbsFilePath, entryAbsPath); nil != err { + if err := gulu.Zip.Unzip(zipAbsFilePath, entryAbsPath); err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/asset.go b/kernel/api/asset.go index 76647e366..4dbac0c02 100644 --- a/kernel/api/asset.go +++ b/kernel/api/asset.go @@ -46,7 +46,7 @@ func statAsset(c *gin.Context) { if strings.HasPrefix(path, "assets/") { var err error p, err = model.GetAssetAbsPath(path) - if nil != err { + if err != nil { ret.Code = 1 return } @@ -62,13 +62,13 @@ func statAsset(c *gin.Context) { } info, err := os.Stat(p) - if nil != err { + if err != nil { ret.Code = 1 return } t, err := times.Stat(p) - if nil != err { + if err != nil { ret.Code = 1 return } @@ -160,7 +160,7 @@ func renameAsset(c *gin.Context) { oldPath := arg["oldPath"].(string) newName := arg["newName"].(string) newPath, err := model.RenameAsset(oldPath, newName) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -182,7 +182,7 @@ func getDocImageAssets(c *gin.Context) { id := arg["id"].(string) assets, err := model.DocImageAssets(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -203,12 +203,12 @@ func setFileAnnotation(c *gin.Context) { p = strings.ReplaceAll(p, "%23", "#") data := arg["data"].(string) writePath, err := resolveFileAnnotationAbsPath(p) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } - if err := filelock.WriteFile(writePath, []byte(data)); nil != err { + if err := filelock.WriteFile(writePath, []byte(data)); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -228,7 +228,7 @@ func getFileAnnotation(c *gin.Context) { p := arg["path"].(string) p = strings.ReplaceAll(p, "%23", "#") readPath, err := resolveFileAnnotationAbsPath(p) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -240,7 +240,7 @@ func getFileAnnotation(c *gin.Context) { } data, err := filelock.ReadFile(readPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -253,7 +253,7 @@ func getFileAnnotation(c *gin.Context) { func resolveFileAnnotationAbsPath(assetRelPath string) (ret string, err error) { filePath := strings.TrimSuffix(assetRelPath, ".sya") absPath, err := model.GetAssetAbsPath(filePath) - if nil != err { + if err != nil { return } dir := filepath.Dir(absPath) @@ -319,7 +319,7 @@ func resolveAssetPath(c *gin.Context) { path := arg["path"].(string) p, err := model.GetAssetAbsPath(path) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 3000} @@ -340,7 +340,7 @@ func uploadCloud(c *gin.Context) { rootID := arg["id"].(string) count, err := model.UploadAssets2Cloud(rootID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 3000} @@ -371,7 +371,7 @@ func insertLocalAssets(c *gin.Context) { } id := arg["id"].(string) succMap, err := model.InsertLocalAssets(id, assetPaths, isUpload) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/attr.go b/kernel/api/attr.go index 09beff328..c077dddb6 100644 --- a/kernel/api/attr.go +++ b/kernel/api/attr.go @@ -99,7 +99,7 @@ func setBlockAttrs(c *gin.Context) { } } err := model.SetBlockAttrs(id, nameValues) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -141,7 +141,7 @@ func batchSetBlockAttrs(c *gin.Context) { } err := model.BatchSetBlockAttrs(blockAttrs) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -164,7 +164,7 @@ func resetBlockAttrs(c *gin.Context) { nameValues[name] = value.(string) } err := model.ResetBlockAttrs(id, nameValues) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/av.go b/kernel/api/av.go index d7aa0c527..da8d97e60 100644 --- a/kernel/api/av.go +++ b/kernel/api/av.go @@ -38,7 +38,7 @@ func duplicateAttributeViewBlock(c *gin.Context) { avID := arg["avID"].(string) newAvID, newBlockID, err := model.DuplicateDatabaseBlock(avID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -88,7 +88,7 @@ func setDatabaseBlockView(c *gin.Context) { viewID := arg["viewID"].(string) err := model.SetDatabaseBlockView(blockID, viewID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -122,7 +122,7 @@ func getAttributeViewPrimaryKeyValues(c *gin.Context) { keyword = keywordArg.(string) } attributeViewName, databaseBlockIDs, rows, err := model.GetAttributeViewPrimaryKeyValues(id, keyword, page, pageSize) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -170,7 +170,7 @@ func appendAttributeViewDetachedBlocksWithValues(c *gin.Context) { } err := model.AppendAttributeViewDetachedBlocksWithValues(avID, values) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -206,7 +206,7 @@ func addAttributeViewBlocks(c *gin.Context) { srcs = append(srcs, src) } err := model.AddAttributeViewBlock(nil, srcs, avID, blockID, previousID, ignoreFillFilter) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -231,7 +231,7 @@ func removeAttributeViewBlocks(c *gin.Context) { } err := model.RemoveAttributeViewBlock(srcIDs, avID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -257,7 +257,7 @@ func addAttributeViewKey(c *gin.Context) { previousKeyID := arg["previousKeyID"].(string) err := model.AddAttributeViewKey(avID, keyID, keyName, keyType, keyIcon, previousKeyID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -279,7 +279,7 @@ func removeAttributeViewKey(c *gin.Context) { keyID := arg["keyID"].(string) err := model.RemoveAttributeViewKey(avID, keyID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -306,7 +306,7 @@ func sortAttributeViewViewKey(c *gin.Context) { previousKeyID := arg["previousKeyID"].(string) err := model.SortAttributeViewViewKey(avID, viewID, keyID, previousKeyID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -329,7 +329,7 @@ func sortAttributeViewKey(c *gin.Context) { previousKeyID := arg["previousKeyID"].(string) err := model.SortAttributeViewKey(avID, keyID, previousKeyID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -442,7 +442,7 @@ func renderSnapshotAttributeView(c *gin.Context) { index := arg["snapshot"].(string) id := arg["id"].(string) view, attrView, err := model.RenderRepoSnapshotAttributeView(index, id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -484,7 +484,7 @@ func renderHistoryAttributeView(c *gin.Context) { id := arg["id"].(string) created := arg["created"].(string) view, attrView, err := model.RenderHistoryAttributeView(id, created) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -548,7 +548,7 @@ func renderAttributeView(c *gin.Context) { } view, attrView, err := model.RenderAttributeView(id, viewID, query, page, pageSize) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/bazaar.go b/kernel/api/bazaar.go index eeaf0fc5f..38b0d3304 100644 --- a/kernel/api/bazaar.go +++ b/kernel/api/bazaar.go @@ -128,7 +128,7 @@ func installBazaarPlugin(c *gin.Context) { repoHash := arg["repoHash"].(string) packageName := arg["packageName"].(string) err := model.InstallBazaarPlugin(repoURL, repoHash, packageName) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return @@ -154,7 +154,7 @@ func uninstallBazaarPlugin(c *gin.Context) { frontend := arg["frontend"].(string) packageName := arg["packageName"].(string) err := model.UninstallBazaarPlugin(packageName, frontend) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -216,7 +216,7 @@ func installBazaarWidget(c *gin.Context) { repoHash := arg["repoHash"].(string) packageName := arg["packageName"].(string) err := model.InstallBazaarWidget(repoURL, repoHash, packageName) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return @@ -239,7 +239,7 @@ func uninstallBazaarWidget(c *gin.Context) { packageName := arg["packageName"].(string) err := model.UninstallBazaarWidget(packageName) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -301,7 +301,7 @@ func installBazaarIcon(c *gin.Context) { repoHash := arg["repoHash"].(string) packageName := arg["packageName"].(string) err := model.InstallBazaarIcon(repoURL, repoHash, packageName) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return @@ -325,7 +325,7 @@ func uninstallBazaarIcon(c *gin.Context) { packageName := arg["packageName"].(string) err := model.UninstallBazaarIcon(packageName) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -388,7 +388,7 @@ func installBazaarTemplate(c *gin.Context) { repoHash := arg["repoHash"].(string) packageName := arg["packageName"].(string) err := model.InstallBazaarTemplate(repoURL, repoHash, packageName) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return @@ -412,7 +412,7 @@ func uninstallBazaarTemplate(c *gin.Context) { packageName := arg["packageName"].(string) err := model.UninstallBazaarTemplate(packageName) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -479,7 +479,7 @@ func installBazaarTheme(c *gin.Context) { update = arg["update"].(bool) } err := model.InstallBazaarTheme(repoURL, repoHash, packageName, int(mode), update) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return @@ -507,7 +507,7 @@ func uninstallBazaarTheme(c *gin.Context) { packageName := arg["packageName"].(string) err := model.UninstallBazaarTheme(packageName) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/block.go b/kernel/api/block.go index e6e2a62a4..d6d584a76 100644 --- a/kernel/api/block.go +++ b/kernel/api/block.go @@ -97,7 +97,7 @@ func transferBlockRef(c *gin.Context) { } err := model.TransferBlockRef(fromID, toID, refIDs) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -122,7 +122,7 @@ func swapBlockRef(c *gin.Context) { defID := arg["defID"].(string) includeChildren := arg["includeChildren"].(bool) err := model.SwapBlockRef(refID, defID, includeChildren) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -170,7 +170,7 @@ func getHeadingDeleteTransaction(c *gin.Context) { id := arg["id"].(string) transaction, err := model.GetHeadingDeleteTransaction(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -193,7 +193,7 @@ func getHeadingLevelTransaction(c *gin.Context) { level := int(arg["level"].(float64)) transaction, err := model.GetHeadingLevelTransaction(id, level) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -215,7 +215,7 @@ func setBlockReminder(c *gin.Context) { id := arg["id"].(string) timed := arg["timed"].(string) // yyyyMMddHHmmss err := model.SetBlockReminder(id, timed) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -449,7 +449,7 @@ func getBlockBreadcrumb(c *gin.Context) { } blockPath, err := model.BuildBlockBreadcrumb(id, excludeTypes) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/block_op.go b/kernel/api/block_op.go index 24bb48fdb..e31d3d58e 100644 --- a/kernel/api/block_op.go +++ b/kernel/api/block_op.go @@ -99,7 +99,7 @@ func appendDailyNoteBlock(c *gin.Context) { luteEngine := util.NewLute() var err error data, err = dataBlockDOM(data, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "data block DOM failed: " + err.Error() return @@ -107,7 +107,7 @@ func appendDailyNoteBlock(c *gin.Context) { } p, _, err := model.CreateDailyNote(boxID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "create daily note failed: " + err.Error() return @@ -152,7 +152,7 @@ func prependDailyNoteBlock(c *gin.Context) { luteEngine := util.NewLute() var err error data, err = dataBlockDOM(data, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "data block DOM failed: " + err.Error() return @@ -160,7 +160,7 @@ func prependDailyNoteBlock(c *gin.Context) { } p, _, err := model.CreateDailyNote(boxID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "create daily note failed: " + err.Error() return @@ -380,7 +380,7 @@ func appendBlock(c *gin.Context) { luteEngine := util.NewLute() var err error data, err = dataBlockDOM(data, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "data block DOM failed: " + err.Error() return @@ -425,7 +425,7 @@ func prependBlock(c *gin.Context) { luteEngine := util.NewLute() var err error data, err = dataBlockDOM(data, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "data block DOM failed: " + err.Error() return @@ -486,7 +486,7 @@ func insertBlock(c *gin.Context) { luteEngine := util.NewLute() var err error data, err = dataBlockDOM(data, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "data block DOM failed: " + err.Error() return @@ -534,7 +534,7 @@ func updateBlock(c *gin.Context) { if "markdown" == dataType { var err error data, err = dataBlockDOM(data, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "data block DOM failed: " + err.Error() return @@ -548,7 +548,7 @@ func updateBlock(c *gin.Context) { } block, err := model.GetBlock(id, nil) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "get block failed: " + err.Error() return @@ -557,7 +557,7 @@ func updateBlock(c *gin.Context) { var transactions []*model.Transaction if "NodeDocument" == block.Type { oldTree, err := filesys.LoadTree(block.Box, block.Path, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "load tree failed: " + err.Error() return diff --git a/kernel/api/bookmark.go b/kernel/api/bookmark.go index 579b02003..dcafcd33a 100644 --- a/kernel/api/bookmark.go +++ b/kernel/api/bookmark.go @@ -42,7 +42,7 @@ func removeBookmark(c *gin.Context) { } bookmark := arg["bookmark"].(string) - if err := model.RemoveBookmark(bookmark); nil != err { + if err := model.RemoveBookmark(bookmark); err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -61,7 +61,7 @@ func renameBookmark(c *gin.Context) { oldBookmark := arg["oldBookmark"].(string) newBookmark := arg["newBookmark"].(string) - if err := model.RenameBookmark(oldBookmark, newBookmark); nil != err { + if err := model.RenameBookmark(oldBookmark, newBookmark); err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} diff --git a/kernel/api/broadcast.go b/kernel/api/broadcast.go index 976a323ba..d0534eb72 100644 --- a/kernel/api/broadcast.go +++ b/kernel/api/broadcast.go @@ -130,7 +130,7 @@ func subscribe(c *gin.Context, broadcastChannel *melody.Melody, channel string) map[string]interface{}{ "channel": channel, }, - ); nil != err { + ); err != nil { logging.LogErrorf("create broadcast channel failed: %s", err) return } @@ -175,7 +175,7 @@ func postMessage(c *gin.Context) { channel.Count = 0 } else { var broadcastChannel = _broadcastChannel.(*melody.Melody) - if err := broadcastChannel.Broadcast([]byte(message)); nil != err { + if err := broadcastChannel.Broadcast([]byte(message)); err != nil { logging.LogErrorf("broadcast message failed: %s", err) ret.Code = -2 diff --git a/kernel/api/export.go b/kernel/api/export.go index 444a1e09e..4295a070e 100644 --- a/kernel/api/export.go +++ b/kernel/api/export.go @@ -45,7 +45,7 @@ func exportAttributeView(c *gin.Context) { avID := arg["id"].(string) blockID := arg["blockID"].(string) zipPath, err := model.ExportAv2CSV(avID, blockID) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -221,7 +221,7 @@ func export2Liandi(c *gin.Context) { id := arg["id"].(string) err := model.Export2Liandi(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -239,7 +239,7 @@ func exportDataInFolder(c *gin.Context) { exportFolder := arg["folder"].(string) name, err := model.ExportDataInFolder(exportFolder) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -255,7 +255,7 @@ func exportData(c *gin.Context) { defer c.JSON(http.StatusOK, ret) zipPath, err := model.ExportData() - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -296,7 +296,7 @@ func exportResources(c *gin.Context) { } zipFilePath, err := model.ExportResources(resourcePaths, name) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -414,7 +414,7 @@ func exportDocx(c *gin.Context) { } fullPath, err := model.ExportDocx(id, savePath, removeAssets, merge) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -455,14 +455,14 @@ func exportTempContent(c *gin.Context) { content := arg["content"].(string) tmpExport := filepath.Join(util.TempDir, "export", "temp") - if err := os.MkdirAll(tmpExport, 0755); nil != err { + if err := os.MkdirAll(tmpExport, 0755); err != nil { ret.Code = 1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} return } p := filepath.Join(tmpExport, gulu.Rand.String(7)) - if err := os.WriteFile(p, []byte(content), 0644); nil != err { + if err := os.WriteFile(p, []byte(content), 0644); err != nil { ret.Code = 1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -563,7 +563,7 @@ func processPDF(c *gin.Context) { removeAssets := arg["removeAssets"].(bool) watermark := arg["watermark"].(bool) err := model.ProcessPDF(id, path, merge, removeAssets, watermark) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -592,7 +592,7 @@ func exportAsFile(c *gin.Context) { defer c.JSON(http.StatusOK, ret) form, err := c.MultipartForm() - if nil != err { + if err != nil { logging.LogErrorf("export as file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -601,7 +601,7 @@ func exportAsFile(c *gin.Context) { file := form.File["file"][0] reader, err := file.Open() - if nil != err { + if err != nil { logging.LogErrorf("export as file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -610,7 +610,7 @@ func exportAsFile(c *gin.Context) { defer reader.Close() data, err := io.ReadAll(reader) - if nil != err { + if err != nil { logging.LogErrorf("export as file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -620,7 +620,7 @@ func exportAsFile(c *gin.Context) { name := "file-" + file.Filename name = util.FilterFileName(name) tmpDir := filepath.Join(util.TempDir, "export") - if err = os.MkdirAll(tmpDir, 0755); nil != err { + if err = os.MkdirAll(tmpDir, 0755); err != nil { logging.LogErrorf("export as file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -629,7 +629,7 @@ func exportAsFile(c *gin.Context) { tmp := filepath.Join(tmpDir, name) err = os.WriteFile(tmp, data, 0644) - if nil != err { + if err != nil { logging.LogErrorf("export as file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() diff --git a/kernel/api/extension.go b/kernel/api/extension.go index fc9025d12..99a0ed7f7 100644 --- a/kernel/api/extension.go +++ b/kernel/api/extension.go @@ -53,7 +53,7 @@ func extensionCopy(c *gin.Context) { } } - if err := os.MkdirAll(assets, 0755); nil != err { + if err := os.MkdirAll(assets, 0755); err != nil { logging.LogErrorf("create assets folder [%s] failed: %s", assets, err) ret.Msg = err.Error() return @@ -62,15 +62,15 @@ func extensionCopy(c *gin.Context) { uploaded := map[string]string{} for originalName, file := range form.File { oName, err := url.PathUnescape(originalName) - if nil != err { + if err != nil { if strings.Contains(originalName, "%u") { originalName = strings.ReplaceAll(originalName, "%u", "\\u") originalName, err = strconv.Unquote("\"" + originalName + "\"") - if nil != err { + if err != nil { continue } oName, err = url.PathUnescape(originalName) - if nil != err { + if err != nil { continue } } else { @@ -84,14 +84,14 @@ func extensionCopy(c *gin.Context) { fName := path.Base(u.Path) f, err := file[0].Open() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() break } data, err := io.ReadAll(f) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() break @@ -113,7 +113,7 @@ func extensionCopy(c *gin.Context) { fName = util.FilterUploadFileName(fName) fName = fName + "-" + ast.NewNodeID() + ext writePath := filepath.Join(assets, fName) - if err = filelock.WriteFile(writePath, data); nil != err { + if err = filelock.WriteFile(writePath, data); err != nil { ret.Code = -1 ret.Msg = err.Error() break @@ -132,7 +132,7 @@ func extensionCopy(c *gin.Context) { href = strings.ReplaceAll(href, "https://ld246.com/article/", "https://ld246.com/article/raw/") href = strings.ReplaceAll(href, "https://liuyun.io/article/", "https://liuyun.io/article/raw/") resp, err := httpclient.NewCloudRequest30s().Get(href) - if nil != err { + if err != nil { logging.LogWarnf("get [%s] failed: %s", href, err) } else { bodyData, readErr := io.ReadAll(resp.Body) diff --git a/kernel/api/file.go b/kernel/api/file.go index 1a313ea24..c9f64a4ce 100644 --- a/kernel/api/file.go +++ b/kernel/api/file.go @@ -80,7 +80,7 @@ func globalCopyFiles(c *gin.Context) { destDir = filepath.Join(util.WorkspaceDir, destDir) for _, src := range srcs { dest := filepath.Join(destDir, filepath.Base(src)) - if err := filelock.Copy(src, dest); nil != err { + if err := filelock.Copy(src, dest); err != nil { logging.LogErrorf("copy file [%s] to [%s] failed: %s", src, dest, err) ret.Code = -1 ret.Msg = err.Error() @@ -100,7 +100,7 @@ func copyFile(c *gin.Context) { src := arg["src"].(string) src, err := model.GetAssetAbsPath(src) - if nil != err { + if err != nil { logging.LogErrorf("get asset [%s] abs path failed: %s", src, err) ret.Code = -1 ret.Msg = err.Error() @@ -109,7 +109,7 @@ func copyFile(c *gin.Context) { } info, err := os.Stat(src) - if nil != err { + if err != nil { logging.LogErrorf("stat [%s] failed: %s", src, err) ret.Code = -1 ret.Msg = err.Error() @@ -125,7 +125,7 @@ func copyFile(c *gin.Context) { } dest := arg["dest"].(string) - if err = filelock.Copy(src, dest); nil != err { + if err = filelock.Copy(src, dest); err != nil { logging.LogErrorf("copy file [%s] to [%s] failed: %s", src, dest, err) ret.Code = -1 ret.Msg = err.Error() @@ -145,7 +145,7 @@ func getFile(c *gin.Context) { filePath := arg["path"].(string) fileAbsPath, err := util.GetAbsPathInWorkspace(filePath) - if nil != err { + if err != nil { ret.Code = http.StatusForbidden ret.Msg = err.Error() c.JSON(http.StatusAccepted, ret) @@ -158,7 +158,7 @@ func getFile(c *gin.Context) { c.JSON(http.StatusAccepted, ret) return } - if nil != err { + if err != nil { logging.LogErrorf("stat [%s] failed: %s", fileAbsPath, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() @@ -192,7 +192,7 @@ func getFile(c *gin.Context) { } data, err := filelock.ReadFile(fileAbsPath) - if nil != err { + if err != nil { logging.LogErrorf("read file [%s] failed: %s", fileAbsPath, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() @@ -224,7 +224,7 @@ func readDir(c *gin.Context) { dirPath := arg["path"].(string) dirAbsPath, err := util.GetAbsPathInWorkspace(dirPath) - if nil != err { + if err != nil { ret.Code = http.StatusForbidden ret.Msg = err.Error() return @@ -235,7 +235,7 @@ func readDir(c *gin.Context) { ret.Msg = err.Error() return } - if nil != err { + if err != nil { logging.LogErrorf("stat [%s] failed: %s", dirAbsPath, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() @@ -249,7 +249,7 @@ func readDir(c *gin.Context) { } entries, err := os.ReadDir(dirAbsPath) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", dirAbsPath, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() @@ -260,7 +260,7 @@ func readDir(c *gin.Context) { for _, entry := range entries { path := filepath.Join(dirAbsPath, entry.Name()) info, err = os.Stat(path) - if nil != err { + if err != nil { logging.LogErrorf("stat [%s] failed: %s", path, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() @@ -289,7 +289,7 @@ func renameFile(c *gin.Context) { srcPath := arg["path"].(string) srcAbsPath, err := util.GetAbsPathInWorkspace(srcPath) - if nil != err { + if err != nil { ret.Code = http.StatusForbidden ret.Msg = err.Error() return @@ -302,7 +302,7 @@ func renameFile(c *gin.Context) { destPath := arg["newPath"].(string) destAbsPath, err := util.GetAbsPathInWorkspace(destPath) - if nil != err { + if err != nil { ret.Code = http.StatusForbidden ret.Msg = err.Error() c.JSON(http.StatusAccepted, ret) @@ -314,7 +314,7 @@ func renameFile(c *gin.Context) { return } - if err := filelock.Rename(srcAbsPath, destAbsPath); nil != err { + if err := filelock.Rename(srcAbsPath, destAbsPath); err != nil { logging.LogErrorf("rename file [%s] to [%s] failed: %s", srcAbsPath, destAbsPath, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() @@ -334,7 +334,7 @@ func removeFile(c *gin.Context) { filePath := arg["path"].(string) fileAbsPath, err := util.GetAbsPathInWorkspace(filePath) - if nil != err { + if err != nil { ret.Code = http.StatusForbidden ret.Msg = err.Error() return @@ -344,14 +344,14 @@ func removeFile(c *gin.Context) { ret.Code = http.StatusNotFound return } - if nil != err { + if err != nil { logging.LogErrorf("stat [%s] failed: %s", fileAbsPath, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() return } - if err = filelock.Remove(fileAbsPath); nil != err { + if err = filelock.Remove(fileAbsPath); err != nil { logging.LogErrorf("remove [%s] failed: %s", fileAbsPath, err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() @@ -366,7 +366,7 @@ func putFile(c *gin.Context) { var err error filePath := c.PostForm("path") fileAbsPath, err := util.GetAbsPathInWorkspace(filePath) - if nil != err { + if err != nil { ret.Code = http.StatusForbidden ret.Msg = err.Error() return @@ -377,7 +377,7 @@ func putFile(c *gin.Context) { if isDir { err = os.MkdirAll(fileAbsPath, 0755) - if nil != err { + if err != nil { logging.LogErrorf("make dir [%s] failed: %s", fileAbsPath, err) } } else { @@ -391,34 +391,34 @@ func putFile(c *gin.Context) { for { dir := filepath.Dir(fileAbsPath) - if err = os.MkdirAll(dir, 0755); nil != err { + if err = os.MkdirAll(dir, 0755); err != nil { logging.LogErrorf("put file [%s] make dir [%s] failed: %s", fileAbsPath, dir, err) break } var f multipart.File f, err = fileHeader.Open() - if nil != err { + if err != nil { logging.LogErrorf("open file failed: %s", err) break } var data []byte data, err = io.ReadAll(f) - if nil != err { + if err != nil { logging.LogErrorf("read file failed: %s", err) break } err = filelock.WriteFile(fileAbsPath, data) - if nil != err { + if err != nil { logging.LogErrorf("write file [%s] failed: %s", fileAbsPath, err) break } break } } - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -436,7 +436,7 @@ func putFile(c *gin.Context) { } modTime = millisecond2Time(modTimeInt) } - if err = os.Chtimes(fileAbsPath, modTime, modTime); nil != err { + if err = os.Chtimes(fileAbsPath, modTime, modTime); err != nil { logging.LogErrorf("change time failed: %s", err) ret.Code = http.StatusInternalServerError ret.Msg = err.Error() diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go index b00c78d14..405b7d20d 100644 --- a/kernel/api/filetree.go +++ b/kernel/api/filetree.go @@ -55,7 +55,7 @@ func listDocTree(c *gin.Context) { var doctree []*DocFile root := filepath.Join(util.WorkspaceDir, "data", notebook, p) dir, err := os.ReadDir(root) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -77,7 +77,7 @@ func listDocTree(c *gin.Context) { doctree = append(doctree, parent) subPath := filepath.Join(root, entry.Name()) - if err = walkDocTree(subPath, parent, &ids); nil != err { + if err = walkDocTree(subPath, parent, &ids); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -103,7 +103,7 @@ type DocFile struct { func walkDocTree(p string, docFile *DocFile, ids *map[string]bool) (err error) { dir, err := os.ReadDir(p) - if nil != err { + if err != nil { return } @@ -122,7 +122,7 @@ func walkDocTree(p string, docFile *DocFile, ids *map[string]bool) (err error) { docFile.Children = append(docFile.Children, parent) subPath := filepath.Join(p, entry.Name()) - if err = walkDocTree(subPath, parent, ids); nil != err { + if err = walkDocTree(subPath, parent, ids); err != nil { return } } else { @@ -190,7 +190,7 @@ func doc2Heading(c *gin.Context) { targetID := arg["targetID"].(string) after := arg["after"].(bool) srcTreeBox, srcTreePath, err := model.Doc2Heading(srcID, targetID, after) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -216,7 +216,7 @@ func heading2Doc(c *gin.Context) { targetNotebook := arg["targetNoteBook"].(string) targetPath := arg["targetPath"].(string) srcRootBlockID, targetPath, err := model.Heading2Doc(srcHeadingID, targetNotebook, targetPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -226,7 +226,7 @@ func heading2Doc(c *gin.Context) { model.WaitForWritingFiles() luteEngine := util.NewLute() tree, err := filesys.LoadTree(targetNotebook, targetPath, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -261,7 +261,7 @@ func li2Doc(c *gin.Context) { targetNotebook := arg["targetNoteBook"].(string) targetPath := arg["targetPath"].(string) srcRootBlockID, targetPath, err := model.ListItem2Doc(srcListItemID, targetNotebook, targetPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -271,7 +271,7 @@ func li2Doc(c *gin.Context) { model.WaitForWritingFiles() luteEngine := util.NewLute() tree, err := filesys.LoadTree(targetNotebook, targetPath, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -310,7 +310,7 @@ func getHPathByPath(c *gin.Context) { p := arg["path"].(string) hPath, err := model.GetHPathByPath(notebook, p) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -333,7 +333,7 @@ func getHPathsByPaths(c *gin.Context) { paths = append(paths, p.(string)) } hPath, err := model.GetHPathsByPaths(paths) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -356,7 +356,7 @@ func getHPathByID(c *gin.Context) { } hPath, err := model.GetHPathByID(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -379,7 +379,7 @@ func getPathByID(c *gin.Context) { } _path, err := model.GetPathByID(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -401,7 +401,7 @@ func getFullHPathByID(c *gin.Context) { id := arg["id"].(string) hPath, err := model.GetFullHPathByID(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -431,7 +431,7 @@ func getIDsByHPath(c *gin.Context) { p := arg["path"].(string) ids, err := model.GetIDsByHPath(p, notebook) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -462,7 +462,7 @@ func moveDocs(c *gin.Context) { callback := arg["callback"] err := model.MoveDocs(fromPaths, toNotebook, toPath, callback) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -523,7 +523,7 @@ func renameDoc(c *gin.Context) { title := arg["title"].(string) err := model.RenameDoc(notebook, p, title) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -542,7 +542,7 @@ func duplicateDoc(c *gin.Context) { id := arg["id"].(string) tree, err := model.LoadTreeByBlockID(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -584,7 +584,7 @@ func createDoc(c *gin.Context) { } tree, err := model.CreateDocByMd(notebook, p, title, md, sorts) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 7000} @@ -611,7 +611,7 @@ func createDailyNote(c *gin.Context) { notebook := arg["notebook"].(string) p, existed, err := model.CreateDailyNote(notebook) - if nil != err { + if err != nil { if model.ErrBoxNotFound == err { ret.Code = 1 } else { @@ -625,7 +625,7 @@ func createDailyNote(c *gin.Context) { box := model.Conf.Box(notebook) luteEngine := util.NewLute() tree, err := filesys.LoadTree(box.ID, p, luteEngine) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -707,7 +707,7 @@ func createDocWithMd(c *gin.Context) { } id, err := model.CreateWithMarkdown(notebook, hPath, markdown, parentID, id, withMath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -764,7 +764,7 @@ func getDocCreateSavePath(c *gin.Context) { } docCreateSavePath, err := model.RenderGoTemplate(docCreateSavePathTpl) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -818,7 +818,7 @@ func getRefCreateSavePath(c *gin.Context) { } refCreateSavePath, err := model.RenderGoTemplate(refCreateSavePathTpl) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -899,7 +899,7 @@ func listDocsByPath(c *gin.Context) { } files, totals, err := model.ListDocTree(notebook, p, sortMode, flashcard, showHidden, maxListCount) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -983,7 +983,7 @@ func getDoc(c *gin.Context) { return } - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return diff --git a/kernel/api/format.go b/kernel/api/format.go index 59dea607d..eb9d6d88d 100644 --- a/kernel/api/format.go +++ b/kernel/api/format.go @@ -36,7 +36,7 @@ func netAssets2LocalAssets(c *gin.Context) { id := arg["id"].(string) err := model.NetAssets2LocalAssets(id, false, "") - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -59,7 +59,7 @@ func netImg2LocalAssets(c *gin.Context) { url = urlArg.(string) } err := model.NetAssets2LocalAssets(id, true, url) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -78,7 +78,7 @@ func autoSpace(c *gin.Context) { id := arg["id"].(string) err := model.AutoSpace(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} diff --git a/kernel/api/graph.go b/kernel/api/graph.go index 5bf6e4249..9e015bdff 100644 --- a/kernel/api/graph.go +++ b/kernel/api/graph.go @@ -64,14 +64,14 @@ func getGraph(c *gin.Context) { query := arg["k"].(string) graphConf, err := gulu.JSON.MarshalJSON(arg["conf"]) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } global := conf.NewGlobalGraph() - if err = gulu.JSON.UnmarshalJSON(graphConf, global); nil != err { + if err = gulu.JSON.UnmarshalJSON(graphConf, global); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -110,14 +110,14 @@ func getLocalGraph(c *gin.Context) { id := arg["id"].(string) graphConf, err := gulu.JSON.MarshalJSON(arg["conf"]) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } local := conf.NewLocalGraph() - if err = gulu.JSON.UnmarshalJSON(graphConf, local); nil != err { + if err = gulu.JSON.UnmarshalJSON(graphConf, local); err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/history.go b/kernel/api/history.go index 303cf6556..220bbfec1 100644 --- a/kernel/api/history.go +++ b/kernel/api/history.go @@ -104,7 +104,7 @@ func getNotebookHistory(c *gin.Context) { defer c.JSON(http.StatusOK, ret) histories, err := model.GetNotebookHistory() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -122,14 +122,12 @@ func clearWorkspaceHistory(c *gin.Context) { msgId := util.PushMsg(model.Conf.Language(100), 1000*60*15) time.Sleep(3 * time.Second) err := model.ClearWorkspaceHistory() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } - util.PushClearMsg(msgId) - time.Sleep(500 * time.Millisecond) - util.PushMsg(model.Conf.Language(99), 1000*5) + util.PushUpdateMsg(msgId, model.Conf.Language(99), 1000*5) } func getDocHistoryContent(c *gin.Context) { @@ -148,7 +146,7 @@ func getDocHistoryContent(c *gin.Context) { keyword = k.(string) } id, rootID, content, isLargeDoc, err := model.GetDocHistoryContent(historyPath, keyword) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -174,7 +172,7 @@ func rollbackDocHistory(c *gin.Context) { notebook := arg["notebook"].(string) historyPath := arg["historyPath"].(string) err := model.RollbackDocHistory(notebook, historyPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -196,7 +194,7 @@ func rollbackAssetsHistory(c *gin.Context) { historyPath := arg["historyPath"].(string) err := model.RollbackAssetsHistory(historyPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -214,7 +212,7 @@ func rollbackNotebookHistory(c *gin.Context) { historyPath := arg["historyPath"].(string) err := model.RollbackNotebookHistory(historyPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/import.go b/kernel/api/import.go index bbfaadc0a..e5efdfd13 100644 --- a/kernel/api/import.go +++ b/kernel/api/import.go @@ -37,7 +37,7 @@ func importSY(c *gin.Context) { defer util.ClearPushProgress(100) form, err := c.MultipartForm() - if nil != err { + if err != nil { logging.LogErrorf("parse import .sy.zip failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -53,7 +53,7 @@ func importSY(c *gin.Context) { } file := files[0] reader, err := file.Open() - if nil != err { + if err != nil { logging.LogErrorf("read import .sy.zip failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -61,7 +61,7 @@ func importSY(c *gin.Context) { } importDir := filepath.Join(util.TempDir, "import") - if err = os.MkdirAll(importDir, 0755); nil != err { + if err = os.MkdirAll(importDir, 0755); err != nil { logging.LogErrorf("make import dir [%s] failed: %s", importDir, err) ret.Code = -1 ret.Msg = err.Error() @@ -70,13 +70,13 @@ func importSY(c *gin.Context) { writePath := filepath.Join(util.TempDir, "import", file.Filename) defer os.RemoveAll(writePath) writer, err := os.OpenFile(writePath, os.O_RDWR|os.O_CREATE, 0644) - if nil != err { + if err != nil { logging.LogErrorf("open import .sy.zip [%s] failed: %s", writePath, err) ret.Code = -1 ret.Msg = err.Error() return } - if _, err = io.Copy(writer, reader); nil != err { + if _, err = io.Copy(writer, reader); err != nil { logging.LogErrorf("write import .sy.zip failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -89,7 +89,7 @@ func importSY(c *gin.Context) { toPath := form.Value["toPath"][0] err = model.ImportSY(writePath, notebook, toPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -104,7 +104,7 @@ func importData(c *gin.Context) { defer util.ClearPushProgress(100) form, err := c.MultipartForm() - if nil != err { + if err != nil { logging.LogErrorf("import data failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -120,7 +120,7 @@ func importData(c *gin.Context) { tmpImport := filepath.Join(util.TempDir, "import") err = os.MkdirAll(tmpImport, 0755) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "create temp import dir failed" return @@ -128,7 +128,7 @@ func importData(c *gin.Context) { dataZipPath := filepath.Join(tmpImport, util.CurrentTimeSecondsStr()+".zip") defer os.RemoveAll(dataZipPath) dataZipFile, err := os.Create(dataZipPath) - if nil != err { + if err != nil { logging.LogErrorf("create temp file failed: %s", err) ret.Code = -1 ret.Msg = "create temp file failed" @@ -136,20 +136,20 @@ func importData(c *gin.Context) { } file := form.File["file"][0] fileReader, err := file.Open() - if nil != err { + if err != nil { logging.LogErrorf("open upload file failed: %s", err) ret.Code = -1 ret.Msg = "open file failed" return } _, err = io.Copy(dataZipFile, fileReader) - if nil != err { + if err != nil { logging.LogErrorf("read upload file failed: %s", err) ret.Code = -1 ret.Msg = "read file failed" return } - if err = dataZipFile.Close(); nil != err { + if err = dataZipFile.Close(); err != nil { logging.LogErrorf("close file failed: %s", err) ret.Code = -1 ret.Msg = "close file failed" @@ -158,7 +158,7 @@ func importData(c *gin.Context) { fileReader.Close() err = model.ImportData(dataZipPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -178,7 +178,7 @@ func importStdMd(c *gin.Context) { localPath := arg["localPath"].(string) toPath := arg["toPath"].(string) err := model.ImportFromLocalPath(notebook, localPath, toPath) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/inbox.go b/kernel/api/inbox.go index 0f0398087..051882076 100644 --- a/kernel/api/inbox.go +++ b/kernel/api/inbox.go @@ -41,7 +41,7 @@ func removeShorthands(c *gin.Context) { } err := model.RemoveCloudShorthands(ids) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return @@ -59,7 +59,7 @@ func getShorthand(c *gin.Context) { id := arg["id"].(string) data, err := model.GetCloudShorthand(id) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return @@ -78,7 +78,7 @@ func getShorthands(c *gin.Context) { page := int(arg["page"].(float64)) data, err := model.GetCloudShorthands(page) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return diff --git a/kernel/api/lute.go b/kernel/api/lute.go index 6a75e6664..12ec2f0ea 100644 --- a/kernel/api/lute.go +++ b/kernel/api/lute.go @@ -58,7 +58,7 @@ func html2BlockDOM(c *gin.Context) { dom := arg["dom"].(string) markdown, withMath, err := model.HTML2Markdown(dom) - if nil != err { + if err != nil { ret.Data = "Failed to convert" return } @@ -155,7 +155,7 @@ func html2BlockDOM(c *gin.Context) { name = name[0 : len(name)-len(ext)] name = name + "-" + ast.NewNodeID() + ext targetPath := filepath.Join(util.DataDir, "assets", name) - if err = filelock.Copy(localPath, targetPath); nil != err { + if err = filelock.Copy(localPath, targetPath); err != nil { logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", localPath, targetPath, err) return ast.WalkStop } diff --git a/kernel/api/network.go b/kernel/api/network.go index d298a7227..910bf17dd 100644 --- a/kernel/api/network.go +++ b/kernel/api/network.go @@ -61,7 +61,7 @@ func echo(c *gin.Context) { password, passwordSet = c.Request.URL.User.Password() - if form, err := c.MultipartForm(); nil != err || nil == form { + if form, err := c.MultipartForm(); err != nil || nil == form { multipartForm = nil } else { multipartForm = &MultipartForm{ @@ -75,11 +75,11 @@ func echo(c *gin.Context) { files[i].Filename = handler.Filename files[i].Header = handler.Header files[i].Size = handler.Size - if file, err := handler.Open(); nil != err { + if file, err := handler.Open(); err != nil { logging.LogWarnf("echo open form [%s] file [%s] error: %s", k, handler.Filename, err.Error()) } else { content := make([]byte, handler.Size) - if _, err := file.Read(content); nil != err { + if _, err := file.Read(content); err != nil { logging.LogWarnf("echo read form [%s] file [%s] error: %s", k, handler.Filename, err.Error()) } else { files[i].Content = base64.StdEncoding.EncodeToString(content) @@ -89,7 +89,7 @@ func echo(c *gin.Context) { } } - if data, err := c.GetRawData(); nil == err { + if data, err := c.GetRawData(); err == nil { rawData = base64.StdEncoding.EncodeToString(data) } else { logging.LogWarnf("echo get raw data error: %s", err.Error()) @@ -203,7 +203,7 @@ func forwardProxy(c *gin.Context) { case "base64": fallthrough case "base64-std": - if payload, err := base64.StdEncoding.DecodeString(arg["payload"].(string)); nil != err { + if payload, err := base64.StdEncoding.DecodeString(arg["payload"].(string)); err != nil { ret.Code = -2 ret.Msg = "decode base64-std payload failed: " + err.Error() return @@ -211,7 +211,7 @@ func forwardProxy(c *gin.Context) { request.SetBody(payload) } case "base64-url": - if payload, err := base64.URLEncoding.DecodeString(arg["payload"].(string)); nil != err { + if payload, err := base64.URLEncoding.DecodeString(arg["payload"].(string)); err != nil { ret.Code = -2 ret.Msg = "decode base64-url payload failed: " + err.Error() return @@ -221,7 +221,7 @@ func forwardProxy(c *gin.Context) { case "base32": fallthrough case "base32-std": - if payload, err := base32.StdEncoding.DecodeString(arg["payload"].(string)); nil != err { + if payload, err := base32.StdEncoding.DecodeString(arg["payload"].(string)); err != nil { ret.Code = -2 ret.Msg = "decode base32-std payload failed: " + err.Error() return @@ -229,7 +229,7 @@ func forwardProxy(c *gin.Context) { request.SetBody(payload) } case "base32-hex": - if payload, err := base32.HexEncoding.DecodeString(arg["payload"].(string)); nil != err { + if payload, err := base32.HexEncoding.DecodeString(arg["payload"].(string)); err != nil { ret.Code = -2 ret.Msg = "decode base32-hex payload failed: " + err.Error() return @@ -237,7 +237,7 @@ func forwardProxy(c *gin.Context) { request.SetBody(payload) } case "hex": - if payload, err := hex.DecodeString(arg["payload"].(string)); nil != err { + if payload, err := hex.DecodeString(arg["payload"].(string)); err != nil { ret.Code = -2 ret.Msg = "decode hex payload failed: " + err.Error() return @@ -251,14 +251,14 @@ func forwardProxy(c *gin.Context) { started := time.Now() resp, err := request.Send(method, destURL) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "forward request failed: " + err.Error() return } bodyData, err := io.ReadAll(resp.Body) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "read response body failed: " + err.Error() return diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go index 839f74adf..c00f4d274 100644 --- a/kernel/api/notebook.go +++ b/kernel/api/notebook.go @@ -75,7 +75,7 @@ func renameNotebook(c *gin.Context) { name := arg["name"].(string) err := model.RenameBox(notebook, name) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -112,7 +112,7 @@ func removeNotebook(c *gin.Context) { } err := model.RemoveBox(notebook) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -137,14 +137,14 @@ func createNotebook(c *gin.Context) { name := arg["name"].(string) id, err := model.CreateBox(name) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } existed, err := model.Mount(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -204,7 +204,7 @@ func openNotebook(c *gin.Context) { msgId := util.PushMsg(model.Conf.Language(45), 1000*60*15) defer util.PushClearMsg(msgId) existed, err := model.Mount(notebook) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -321,14 +321,14 @@ func setNotebookConf(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg["conf"]) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } boxConf := box.GetConf() - if err = gulu.JSON.UnmarshalJSON(param, boxConf); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, boxConf); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -377,7 +377,7 @@ func lsNotebooks(c *gin.Context) { // 兼容旧版接口,不能直接使用 util.JsonArg() arg := map[string]interface{}{} - if err := c.ShouldBindJSON(&arg); nil == err { + if err := c.ShouldBindJSON(&arg); err == nil { if arg["flashcard"] != nil { flashcard = arg["flashcard"].(bool) } @@ -389,7 +389,7 @@ func lsNotebooks(c *gin.Context) { } else { var err error notebooks, err = model.ListNotebooks() - if nil != err { + if err != nil { return } } diff --git a/kernel/api/outline.go b/kernel/api/outline.go index b8c59917d..ba1c3f3ea 100644 --- a/kernel/api/outline.go +++ b/kernel/api/outline.go @@ -40,7 +40,7 @@ func getDocOutline(c *gin.Context) { rootID := arg["id"].(string) headings, err := model.Outline(rootID) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return diff --git a/kernel/api/pandoc.go b/kernel/api/pandoc.go index d55a399ec..0b342d8cb 100644 --- a/kernel/api/pandoc.go +++ b/kernel/api/pandoc.go @@ -46,7 +46,7 @@ func pandoc(c *gin.Context) { } path, err := util.ConvertPandoc(dir, args...) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/petal.go b/kernel/api/petal.go index a4efd2a0a..7534da587 100644 --- a/kernel/api/petal.go +++ b/kernel/api/petal.go @@ -53,7 +53,7 @@ func setPetalEnabled(c *gin.Context) { enabled := arg["enabled"].(bool) frontend := arg["frontend"].(string) data, err := model.SetPetalEnabled(packageName, enabled, frontend) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/repo.go b/kernel/api/repo.go index 15757f79b..14cb0e34f 100644 --- a/kernel/api/repo.go +++ b/kernel/api/repo.go @@ -42,7 +42,7 @@ func getRepoFile(c *gin.Context) { id := arg["id"].(string) data, p, err := model.GetRepoFile(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -71,7 +71,7 @@ func openRepoSnapshotDoc(c *gin.Context) { id := arg["id"].(string) content, isProtyleDoc, updated, err := model.OpenRepoSnapshotDoc(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -96,7 +96,7 @@ func diffRepoSnapshots(c *gin.Context) { left := arg["left"].(string) right := arg["right"].(string) diff, err := model.DiffRepoSnapshots(left, right) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -117,7 +117,7 @@ func getCloudSpace(c *gin.Context) { defer c.JSON(http.StatusOK, ret) sync, backup, hSize, hAssetSize, hTotalSize, exchangeSize, hTrafficUploadSize, hTrafficDownloadSize, htrafficAPIGet, hTrafficAPIPut, err := model.GetCloudSpace() - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() util.PushErrMsg(err.Error(), 3000) @@ -162,7 +162,7 @@ func downloadCloudSnapshot(c *gin.Context) { id := arg["id"].(string) tag := arg["tag"].(string) - if err := model.DownloadCloudSnapshot(tag, id); nil != err { + if err := model.DownloadCloudSnapshot(tag, id); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -180,7 +180,7 @@ func uploadCloudSnapshot(c *gin.Context) { id := arg["id"].(string) tag := arg["tag"].(string) - if err := model.UploadCloudSnapshot(tag, id); nil != err { + if err := model.UploadCloudSnapshot(tag, id); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -198,7 +198,7 @@ func getRepoSnapshots(c *gin.Context) { page := arg["page"].(float64) snapshots, pageCount, totalCount, err := model.GetRepoSnapshots(int(page)) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -222,7 +222,7 @@ func getCloudRepoSnapshots(c *gin.Context) { page := int(arg["page"].(float64)) snapshots, pageCount, totalCount, err := model.GetCloudRepoSnapshots(page) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -240,7 +240,7 @@ func getCloudRepoTagSnapshots(c *gin.Context) { defer c.JSON(http.StatusOK, ret) snapshots, err := model.GetCloudRepoTagSnapshots() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -262,7 +262,7 @@ func removeCloudRepoTagSnapshot(c *gin.Context) { tag := arg["tag"].(string) err := model.RemoveCloudRepoTag(tag) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -274,7 +274,7 @@ func getRepoTagSnapshots(c *gin.Context) { defer c.JSON(http.StatusOK, ret) snapshots, err := model.GetTagSnapshots() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -296,7 +296,7 @@ func removeRepoTagSnapshot(c *gin.Context) { tag := arg["tag"].(string) err := model.RemoveTagSnapshot(tag) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -313,7 +313,7 @@ func createSnapshot(c *gin.Context) { } memo := arg["memo"].(string) - if err := model.IndexRepo(memo); nil != err { + if err := model.IndexRepo(memo); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(140), err) ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -332,7 +332,7 @@ func tagSnapshot(c *gin.Context) { id := arg["id"].(string) name := arg["name"].(string) - if err := model.TagSnapshot(id, name); nil != err { + if err := model.TagSnapshot(id, name); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(140), err) ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -351,7 +351,7 @@ func importRepoKey(c *gin.Context) { base64Key := arg["key"].(string) retKey, err := model.ImportRepoKey(base64Key) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(137), err) ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -373,7 +373,7 @@ func initRepoKeyFromPassphrase(c *gin.Context) { } pass := arg["pass"].(string) - if err := model.InitRepoKeyFromPassphrase(pass); nil != err { + if err := model.InitRepoKeyFromPassphrase(pass); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(137), err) ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -389,7 +389,7 @@ func initRepoKey(c *gin.Context) { ret := gulu.Ret.NewResult() defer c.JSON(http.StatusOK, ret) - if err := model.InitRepoKey(); nil != err { + if err := model.InitRepoKey(); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(137), err) ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -405,7 +405,7 @@ func resetRepo(c *gin.Context) { ret := gulu.Ret.NewResult() defer c.JSON(http.StatusOK, ret) - if err := model.ResetRepo(); nil != err { + if err := model.ResetRepo(); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(146), err.Error()) ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -417,7 +417,7 @@ func purgeRepo(c *gin.Context) { ret := gulu.Ret.NewResult() defer c.JSON(http.StatusOK, ret) - if err := model.PurgeRepo(); nil != err { + if err := model.PurgeRepo(); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(201), err.Error()) ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -429,7 +429,7 @@ func purgeCloudRepo(c *gin.Context) { ret := gulu.Ret.NewResult() defer c.JSON(http.StatusOK, ret) - if err := model.PurgeCloud(); nil != err { + if err := model.PurgeCloud(); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf(model.Conf.Language(201), err.Error()) ret.Data = map[string]interface{}{"closeTimeout": 5000} diff --git a/kernel/api/riff.go b/kernel/api/riff.go index 67a621687..58287b594 100644 --- a/kernel/api/riff.go +++ b/kernel/api/riff.go @@ -66,7 +66,7 @@ func batchSetRiffCardsDueTime(c *gin.Context) { } err := model.SetFlashcardsDueTime(cardDues) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() } @@ -178,7 +178,7 @@ func reviewRiffCard(c *gin.Context) { rating := int(arg["rating"].(float64)) reviewedCardIDs := getReviewedCards(arg) err := model.ReviewFlashcard(deckID, cardID, riff.Rating(rating), reviewedCardIDs) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -197,7 +197,7 @@ func skipReviewRiffCard(c *gin.Context) { deckID := arg["deckID"].(string) cardID := arg["cardID"].(string) err := model.SkipReviewFlashcard(deckID, cardID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -216,7 +216,7 @@ func getNotebookRiffDueCards(c *gin.Context) { notebookID := arg["notebook"].(string) reviewedCardIDs := getReviewedCards(arg) cards, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount, err := model.GetNotebookDueFlashcards(notebookID, reviewedCardIDs) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -242,7 +242,7 @@ func getTreeRiffDueCards(c *gin.Context) { rootID := arg["rootID"].(string) reviewedCardIDs := getReviewedCards(arg) cards, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount, err := model.GetTreeDueFlashcards(rootID, reviewedCardIDs) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -268,7 +268,7 @@ func getRiffDueCards(c *gin.Context) { deckID := arg["deckID"].(string) reviewedCardIDs := getReviewedCards(arg) cards, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount, err := model.GetDueFlashcards(deckID, reviewedCardIDs) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -381,7 +381,7 @@ func renameRiffDeck(c *gin.Context) { deckID := arg["deckID"].(string) name := arg["name"].(string) err := model.RenameDeck(deckID, name) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -399,7 +399,7 @@ func removeRiffDeck(c *gin.Context) { deckID := arg["deckID"].(string) err := model.RemoveDeck(deckID) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -417,7 +417,7 @@ func createRiffDeck(c *gin.Context) { name := arg["name"].(string) deck, err := model.CreateDeck(name) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/search.go b/kernel/api/search.go index bb4f16a43..2c16a4697 100644 --- a/kernel/api/search.go +++ b/kernel/api/search.go @@ -132,7 +132,7 @@ func findReplace(c *gin.Context) { } err := model.FindReplace(k, r, replaceTypes, ids, paths, boxes, types, method, orderBy, groupBy) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -211,7 +211,7 @@ func removeTemplate(c *gin.Context) { path := arg["path"].(string) err := model.RemoveTemplate(path) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -281,7 +281,7 @@ func updateEmbedBlock(c *gin.Context) { content := arg["content"].(string) err := model.UpdateEmbedBlock(id, content) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/setting.go b/kernel/api/setting.go index 901035007..a60c194a4 100644 --- a/kernel/api/setting.go +++ b/kernel/api/setting.go @@ -61,14 +61,14 @@ func setConfSnippet(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } snippet := &conf.Snpt{} - if err = gulu.JSON.UnmarshalJSON(param, snippet); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, snippet); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -142,14 +142,14 @@ func setBazaar(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } bazaar := &conf.Bazaar{} - if err = gulu.JSON.UnmarshalJSON(param, bazaar); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, bazaar); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -171,14 +171,14 @@ func setAI(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } ai := &conf.AI{} - if err = gulu.JSON.UnmarshalJSON(param, ai); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, ai); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -219,14 +219,14 @@ func setFlashcard(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } flashcard := &conf.Flashcard{} - if err = gulu.JSON.UnmarshalJSON(param, flashcard); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, flashcard); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -256,14 +256,14 @@ func setAccount(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } account := &conf.Account{} - if err = gulu.JSON.UnmarshalJSON(param, account); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, account); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -285,7 +285,7 @@ func setEditor(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -294,7 +294,7 @@ func setEditor(c *gin.Context) { oldGenerateHistoryInterval := model.Conf.Editor.GenerateHistoryInterval editor := conf.NewEditor() - if err = gulu.JSON.UnmarshalJSON(param, editor); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, editor); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -346,14 +346,14 @@ func setExport(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } export := &conf.Export{} - if err = gulu.JSON.UnmarshalJSON(param, export); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, export); err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -385,14 +385,14 @@ func setFiletree(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } fileTree := conf.NewFileTree() - if err = gulu.JSON.UnmarshalJSON(param, fileTree); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, fileTree); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -431,14 +431,14 @@ func setSearch(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } s := &conf.Search{} - if err = gulu.JSON.UnmarshalJSON(param, s); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, s); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -485,14 +485,14 @@ func setKeymap(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg["data"]) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } keymap := &conf.Keymap{} - if err = gulu.JSON.UnmarshalJSON(param, keymap); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, keymap); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -512,14 +512,14 @@ func setAppearance(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } appearance := &conf.Appearance{} - if err = gulu.JSON.UnmarshalJSON(param, appearance); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, appearance); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -544,14 +544,14 @@ func setPublish(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } publish := &conf.Publish{} - if err = gulu.JSON.UnmarshalJSON(param, publish); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, publish); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -627,7 +627,7 @@ func login2faCloudUser(c *gin.Context) { token := arg["token"].(string) code := arg["code"].(string) data, err := model.Login2fa(token, code) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/snippet.go b/kernel/api/snippet.go index b975d061b..460dffb41 100644 --- a/kernel/api/snippet.go +++ b/kernel/api/snippet.go @@ -49,7 +49,7 @@ func getSnippet(c *gin.Context) { } confSnippets, err := model.LoadSnippets() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "load snippets failed: " + err.Error() return @@ -108,7 +108,7 @@ func setSnippet(c *gin.Context) { } err := model.SetSnippet(snippets) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "set snippet failed: " + err.Error() return @@ -126,7 +126,7 @@ func removeSnippet(c *gin.Context) { id := arg["id"].(string) snippet, err := model.RemoveSnippet(id) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "remove snippet failed: " + err.Error() return diff --git a/kernel/api/sql.go b/kernel/api/sql.go index 9238894e0..d10cae8e5 100644 --- a/kernel/api/sql.go +++ b/kernel/api/sql.go @@ -45,7 +45,7 @@ func SQL(c *gin.Context) { stmt := arg["stmt"].(string) result, err := sql.Query(stmt, model.Conf.Search.Limit) - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() return diff --git a/kernel/api/storage.go b/kernel/api/storage.go index 930f052cc..9f26e4ebc 100644 --- a/kernel/api/storage.go +++ b/kernel/api/storage.go @@ -30,7 +30,7 @@ func getRecentDocs(c *gin.Context) { defer c.JSON(http.StatusOK, ret) data, err := model.GetRecentDocs() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -49,7 +49,7 @@ func removeCriterion(c *gin.Context) { name := arg["name"].(string) err := model.RemoveCriterion(name) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -66,21 +66,21 @@ func setCriterion(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg["criterion"]) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } criterion := &model.Criterion{} - if err = gulu.JSON.UnmarshalJSON(param, criterion); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, criterion); err != nil { ret.Code = -1 ret.Msg = err.Error() return } err = model.SetCriterion(criterion) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -111,7 +111,7 @@ func removeLocalStorageVals(c *gin.Context) { } err := model.RemoveLocalStorageVals(keys) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -136,7 +136,7 @@ func setLocalStorageVal(c *gin.Context) { key := arg["key"].(string) val := arg["val"].(interface{}) err := model.SetLocalStorageVal(key, val) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -160,7 +160,7 @@ func setLocalStorage(c *gin.Context) { val := arg["val"].(interface{}) err := model.SetLocalStorage(val) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/sync.go b/kernel/api/sync.go index 90be8ea18..847165f25 100644 --- a/kernel/api/sync.go +++ b/kernel/api/sync.go @@ -38,7 +38,7 @@ func importSyncProviderWebDAV(c *gin.Context) { defer c.JSON(200, ret) form, err := c.MultipartForm() - if nil != err { + if err != nil { logging.LogErrorf("read upload file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -54,7 +54,7 @@ func importSyncProviderWebDAV(c *gin.Context) { f := files[0] fh, err := f.Open() - if nil != err { + if err != nil { logging.LogErrorf("read upload file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -63,7 +63,7 @@ func importSyncProviderWebDAV(c *gin.Context) { data, err := io.ReadAll(fh) fh.Close() - if nil != err { + if err != nil { logging.LogErrorf("read upload file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -71,7 +71,7 @@ func importSyncProviderWebDAV(c *gin.Context) { } tmpDir := filepath.Join(util.TempDir, "import") - if err = os.MkdirAll(tmpDir, 0755); nil != err { + if err = os.MkdirAll(tmpDir, 0755); err != nil { logging.LogErrorf("import WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -79,14 +79,14 @@ func importSyncProviderWebDAV(c *gin.Context) { } tmp := filepath.Join(tmpDir, f.Filename) - if err = os.WriteFile(tmp, data, 0644); nil != err { + if err = os.WriteFile(tmp, data, 0644); err != nil { logging.LogErrorf("import WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() return } - if err = gulu.Zip.Unzip(tmp, tmpDir); nil != err { + if err = gulu.Zip.Unzip(tmp, tmpDir); err != nil { logging.LogErrorf("import WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -95,7 +95,7 @@ func importSyncProviderWebDAV(c *gin.Context) { tmp = filepath.Join(tmpDir, f.Filename[:len(f.Filename)-4]) data, err = os.ReadFile(tmp) - if nil != err { + if err != nil { logging.LogErrorf("import WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -105,7 +105,7 @@ func importSyncProviderWebDAV(c *gin.Context) { data = util.AESDecrypt(string(data)) data, _ = hex.DecodeString(string(data)) webdav := &conf.WebDAV{} - if err = gulu.JSON.UnmarshalJSON(data, webdav); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, webdav); err != nil { logging.LogErrorf("import WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -113,7 +113,7 @@ func importSyncProviderWebDAV(c *gin.Context) { } err = model.SetSyncProviderWebDAV(webdav) - if nil != err { + if err != nil { logging.LogErrorf("import WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -131,7 +131,7 @@ func exportSyncProviderWebDAV(c *gin.Context) { name := "siyuan-webdav-" + time.Now().Format("20060102150405") + ".json" tmpDir := filepath.Join(util.TempDir, "export") - if err := os.MkdirAll(tmpDir, 0755); nil != err { + if err := os.MkdirAll(tmpDir, 0755); err != nil { logging.LogErrorf("export WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -144,7 +144,7 @@ func exportSyncProviderWebDAV(c *gin.Context) { } data, err := gulu.JSON.MarshalJSON(model.Conf.Sync.WebDAV) - if nil != err { + if err != nil { logging.LogErrorf("export WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -153,7 +153,7 @@ func exportSyncProviderWebDAV(c *gin.Context) { dataStr := util.AESEncrypt(string(data)) tmp := filepath.Join(tmpDir, name) - if err = os.WriteFile(tmp, []byte(dataStr), 0644); nil != err { + if err = os.WriteFile(tmp, []byte(dataStr), 0644); err != nil { logging.LogErrorf("export WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -161,21 +161,21 @@ func exportSyncProviderWebDAV(c *gin.Context) { } zipFile, err := gulu.Zip.Create(tmp + ".zip") - if nil != err { + if err != nil { logging.LogErrorf("export WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() return } - if err = zipFile.AddEntry(name, tmp); nil != err { + if err = zipFile.AddEntry(name, tmp); err != nil { logging.LogErrorf("export WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() return } - if err = zipFile.Close(); nil != err { + if err = zipFile.Close(); err != nil { logging.LogErrorf("export WebDAV provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -194,7 +194,7 @@ func importSyncProviderS3(c *gin.Context) { defer c.JSON(200, ret) form, err := c.MultipartForm() - if nil != err { + if err != nil { logging.LogErrorf("read upload file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -210,7 +210,7 @@ func importSyncProviderS3(c *gin.Context) { f := files[0] fh, err := f.Open() - if nil != err { + if err != nil { logging.LogErrorf("read upload file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -219,7 +219,7 @@ func importSyncProviderS3(c *gin.Context) { data, err := io.ReadAll(fh) fh.Close() - if nil != err { + if err != nil { logging.LogErrorf("read upload file failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -227,7 +227,7 @@ func importSyncProviderS3(c *gin.Context) { } importDir := filepath.Join(util.TempDir, "import") - if err = os.MkdirAll(importDir, 0755); nil != err { + if err = os.MkdirAll(importDir, 0755); err != nil { logging.LogErrorf("import S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -235,7 +235,7 @@ func importSyncProviderS3(c *gin.Context) { } tmp := filepath.Join(importDir, f.Filename) - if err = os.WriteFile(tmp, data, 0644); nil != err { + if err = os.WriteFile(tmp, data, 0644); err != nil { logging.LogErrorf("import S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -243,7 +243,7 @@ func importSyncProviderS3(c *gin.Context) { } tmpDir := filepath.Join(importDir, "s3") - if err = gulu.Zip.Unzip(tmp, tmpDir); nil != err { + if err = gulu.Zip.Unzip(tmp, tmpDir); err != nil { logging.LogErrorf("import S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -251,7 +251,7 @@ func importSyncProviderS3(c *gin.Context) { } entries, err := os.ReadDir(tmpDir) - if nil != err { + if err != nil { logging.LogErrorf("import S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -267,7 +267,7 @@ func importSyncProviderS3(c *gin.Context) { tmp = filepath.Join(tmpDir, entries[0].Name()) data, err = os.ReadFile(tmp) - if nil != err { + if err != nil { logging.LogErrorf("import S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -277,7 +277,7 @@ func importSyncProviderS3(c *gin.Context) { data = util.AESDecrypt(string(data)) data, _ = hex.DecodeString(string(data)) s3 := &conf.S3{} - if err = gulu.JSON.UnmarshalJSON(data, s3); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, s3); err != nil { logging.LogErrorf("import S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -285,7 +285,7 @@ func importSyncProviderS3(c *gin.Context) { } err = model.SetSyncProviderS3(s3) - if nil != err { + if err != nil { logging.LogErrorf("import S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -303,7 +303,7 @@ func exportSyncProviderS3(c *gin.Context) { name := "siyuan-s3-" + time.Now().Format("20060102150405") + ".json" tmpDir := filepath.Join(util.TempDir, "export") - if err := os.MkdirAll(tmpDir, 0755); nil != err { + if err := os.MkdirAll(tmpDir, 0755); err != nil { logging.LogErrorf("export S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -316,7 +316,7 @@ func exportSyncProviderS3(c *gin.Context) { } data, err := gulu.JSON.MarshalJSON(model.Conf.Sync.S3) - if nil != err { + if err != nil { logging.LogErrorf("export S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -325,7 +325,7 @@ func exportSyncProviderS3(c *gin.Context) { dataStr := util.AESEncrypt(string(data)) tmp := filepath.Join(tmpDir, name) - if err = os.WriteFile(tmp, []byte(dataStr), 0644); nil != err { + if err = os.WriteFile(tmp, []byte(dataStr), 0644); err != nil { logging.LogErrorf("export S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -333,21 +333,21 @@ func exportSyncProviderS3(c *gin.Context) { } zipFile, err := gulu.Zip.Create(tmp + ".zip") - if nil != err { + if err != nil { logging.LogErrorf("export S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() return } - if err = zipFile.AddEntry(name, tmp); nil != err { + if err = zipFile.AddEntry(name, tmp); err != nil { logging.LogErrorf("export S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() return } - if err = zipFile.Close(); nil != err { + if err = zipFile.Close(); err != nil { logging.LogErrorf("export S3 provider failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -445,7 +445,7 @@ func listCloudSyncDir(c *gin.Context) { defer c.JSON(http.StatusOK, ret) syncDirs, hSize, err := model.ListCloudSyncDir() - if nil != err { + if err != nil { ret.Code = 1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -470,7 +470,7 @@ func removeCloudSyncDir(c *gin.Context) { name := arg["name"].(string) err := model.RemoveCloudSyncDir(name) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -491,7 +491,7 @@ func createCloudSyncDir(c *gin.Context) { name := arg["name"].(string) err := model.CreateCloudSyncDir(name) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -562,7 +562,7 @@ func setSyncProvider(c *gin.Context) { provider := int(arg["provider"].(float64)) err := model.SetSyncProvider(provider) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -581,7 +581,7 @@ func setSyncProviderS3(c *gin.Context) { s3Arg := arg["s3"].(interface{}) data, err := gulu.JSON.MarshalJSON(s3Arg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -589,7 +589,7 @@ func setSyncProviderS3(c *gin.Context) { } s3 := &conf.S3{} - if err = gulu.JSON.UnmarshalJSON(data, s3); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, s3); err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -597,7 +597,7 @@ func setSyncProviderS3(c *gin.Context) { } err = model.SetSyncProviderS3(s3) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -616,7 +616,7 @@ func setSyncProviderWebDAV(c *gin.Context) { webdavArg := arg["webdav"].(interface{}) data, err := gulu.JSON.MarshalJSON(webdavArg) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -624,7 +624,7 @@ func setSyncProviderWebDAV(c *gin.Context) { } webdav := &conf.WebDAV{} - if err = gulu.JSON.UnmarshalJSON(data, webdav); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, webdav); err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -632,7 +632,7 @@ func setSyncProviderWebDAV(c *gin.Context) { } err = model.SetSyncProviderWebDAV(webdav) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} diff --git a/kernel/api/system.go b/kernel/api/system.go index 312bcbea5..51af4472a 100644 --- a/kernel/api/system.go +++ b/kernel/api/system.go @@ -39,7 +39,7 @@ func getNetwork(c *gin.Context) { defer c.JSON(http.StatusOK, ret) maskedConf, err := model.GetMaskedConf() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "get conf failed: " + err.Error() return @@ -76,7 +76,7 @@ func getChangelog(c *gin.Context) { } contentData, err := os.ReadFile(changelogPath) - if nil != err { + if err != nil { logging.LogErrorf("read changelog failed: %s", err) return } @@ -97,7 +97,7 @@ func getEmojiConf(c *gin.Context) { builtConfPath := filepath.Join(util.AppearancePath, "emojis", "conf.json") data, err := os.ReadFile(builtConfPath) - if nil != err { + if err != nil { logging.LogErrorf("read emojis conf.json failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -105,7 +105,7 @@ func getEmojiConf(c *gin.Context) { } var conf []map[string]interface{} - if err = gulu.JSON.UnmarshalJSON(data, &conf); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &conf); err != nil { logging.LogErrorf("unmarshal emojis conf.json failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -124,7 +124,7 @@ func getEmojiConf(c *gin.Context) { if gulu.File.IsDir(customConfDir) { model.CustomEmojis = sync.Map{} customEmojis, err := os.ReadDir(customConfDir) - if nil != err { + if err != nil { logging.LogErrorf("read custom emojis failed: %s", err) } else { for _, customEmoji := range customEmojis { @@ -136,7 +136,7 @@ func getEmojiConf(c *gin.Context) { if customEmoji.IsDir() { // 子级 subCustomEmojis, err := os.ReadDir(filepath.Join(customConfDir, name)) - if nil != err { + if err != nil { logging.LogErrorf("read custom emojis failed: %s", err) continue } @@ -211,7 +211,7 @@ func getConf(c *gin.Context) { defer c.JSON(http.StatusOK, ret) maskedConf, err := model.GetMaskedConf() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "get conf failed: " + err.Error() return @@ -252,14 +252,14 @@ func setUILayout(c *gin.Context) { } param, err := gulu.JSON.MarshalJSON(arg["layout"]) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return } uiLayout := &conf.UILayout{} - if err = gulu.JSON.UnmarshalJSON(param, uiLayout); nil != err { + if err = gulu.JSON.UnmarshalJSON(param, uiLayout); err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/api/tag.go b/kernel/api/tag.go index 3767f8867..e844aed29 100644 --- a/kernel/api/tag.go +++ b/kernel/api/tag.go @@ -57,7 +57,7 @@ func renameTag(c *gin.Context) { oldLabel := arg["oldLabel"].(string) newLabel := arg["newLabel"].(string) - if err := model.RenameTag(oldLabel, newLabel); nil != err { + if err := model.RenameTag(oldLabel, newLabel); err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} @@ -75,7 +75,7 @@ func removeTag(c *gin.Context) { } label := arg["label"].(string) - if err := model.RemoveTag(label); nil != err { + if err := model.RemoveTag(label); err != nil { ret.Code = -1 ret.Msg = err.Error() ret.Data = map[string]interface{}{"closeTimeout": 5000} diff --git a/kernel/api/template.go b/kernel/api/template.go index 2913e3a9b..69f2db472 100644 --- a/kernel/api/template.go +++ b/kernel/api/template.go @@ -36,7 +36,7 @@ func renderSprig(c *gin.Context) { template := arg["template"].(string) content, err := model.RenderGoTemplate(template) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = util.EscapeHTML(err.Error()) return @@ -57,7 +57,7 @@ func docSaveAsTemplate(c *gin.Context) { name := arg["name"].(string) overwrite := arg["overwrite"].(bool) code, err := model.DocSaveAsTemplate(id, name, overwrite) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = util.EscapeHTML(err.Error()) return @@ -86,7 +86,7 @@ func renderTemplate(c *gin.Context) { } _, content, err := model.RenderTemplate(p, id, preview) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = util.EscapeHTML(err.Error()) return diff --git a/kernel/api/transaction.go b/kernel/api/transaction.go index 7f1f1dbcf..667e9aada 100644 --- a/kernel/api/transaction.go +++ b/kernel/api/transaction.go @@ -40,7 +40,7 @@ func performTransactions(c *gin.Context) { trans := arg["transactions"] data, err := gulu.JSON.MarshalJSON(trans) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = "parses request failed" return @@ -55,7 +55,7 @@ func performTransactions(c *gin.Context) { timestamp := int64(arg["reqId"].(float64)) var transactions []*model.Transaction - if err = gulu.JSON.UnmarshalJSON(data, &transactions); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &transactions); err != nil { ret.Code = -1 ret.Msg = "parses request failed" return diff --git a/kernel/api/workspace.go b/kernel/api/workspace.go index c126c3c33..be1d90eb3 100644 --- a/kernel/api/workspace.go +++ b/kernel/api/workspace.go @@ -57,7 +57,7 @@ func checkWorkspaceDir(c *gin.Context) { } entries, err := os.ReadDir(path) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf("read workspace dir [%s] failed: %s", path, err) } @@ -104,7 +104,7 @@ func createWorkspaceDir(c *gin.Context) { } if !gulu.File.IsExist(absPath) { - if err := os.MkdirAll(absPath, 0755); nil != err { + if err := os.MkdirAll(absPath, 0755); err != nil { ret.Code = -1 ret.Msg = fmt.Sprintf("create workspace dir [%s] failed: %s", absPath, err) return @@ -112,7 +112,7 @@ func createWorkspaceDir(c *gin.Context) { } workspacePaths, err := util.ReadWorkspacePaths() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -120,7 +120,7 @@ func createWorkspaceDir(c *gin.Context) { workspacePaths = append(workspacePaths, absPath) - if err = util.WriteWorkspacePaths(workspacePaths); nil != err { + if err = util.WriteWorkspacePaths(workspacePaths); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -147,7 +147,7 @@ func removeWorkspaceDir(c *gin.Context) { } workspacePaths, err := util.ReadWorkspacePaths() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -155,7 +155,7 @@ func removeWorkspaceDir(c *gin.Context) { workspacePaths = gulu.Str.RemoveElem(workspacePaths, path) - if err = util.WriteWorkspacePaths(workspacePaths); nil != err { + if err = util.WriteWorkspacePaths(workspacePaths); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -174,7 +174,7 @@ func removeWorkspaceDirPhysically(c *gin.Context) { path := arg["path"].(string) if gulu.File.IsDir(path) { err := os.RemoveAll(path) - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -202,7 +202,7 @@ func getMobileWorkspaces(c *gin.Context) { root := filepath.Dir(util.WorkspaceDir) dirs, err := os.ReadDir(root) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", root, err) ret.Code = -1 ret.Msg = err.Error() @@ -229,7 +229,7 @@ func getWorkspaces(c *gin.Context) { defer c.JSON(http.StatusOK, ret) workspacePaths, err := util.ReadWorkspacePaths() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -299,7 +299,7 @@ func setWorkspaceDir(c *gin.Context) { } workspacePaths, err := util.ReadWorkspacePaths() - if nil != err { + if err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -310,7 +310,7 @@ func setWorkspaceDir(c *gin.Context) { workspacePaths = gulu.Str.RemoveElem(workspacePaths, path) workspacePaths = append(workspacePaths, path) // 切换的工作空间固定放在最后一个 - if err = util.WriteWorkspacePaths(workspacePaths); nil != err { + if err = util.WriteWorkspacePaths(workspacePaths); err != nil { ret.Code = -1 ret.Msg = err.Error() return diff --git a/kernel/av/av.go b/kernel/av/av.go index c109deabc..012ee9c19 100644 --- a/kernel/av/av.go +++ b/kernel/av/av.go @@ -264,7 +264,7 @@ func GetAttributeViewName(avID string) (ret string, err error) { func GetAttributeViewNameByPath(avJSONPath string) (ret string, err error) { data, err := filelock.ReadFile(avJSONPath) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view [%s] failed: %s", avJSONPath, err) return } @@ -296,10 +296,10 @@ func ParseAttributeView(avID string) (ret *AttributeView, err error) { } ret = &AttributeView{} - if err = gulu.JSON.UnmarshalJSON(data, ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil { if strings.Contains(err.Error(), ".relation.contents of type av.Value") { mapAv := map[string]interface{}{} - if err = gulu.JSON.UnmarshalJSON(data, &mapAv); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &mapAv); err != nil { logging.LogErrorf("unmarshal attribute view [%s] failed: %s", avID, err) return } @@ -338,12 +338,12 @@ func ParseAttributeView(avID string) (ret *AttributeView, err error) { } data, err = gulu.JSON.MarshalJSON(mapAv) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view [%s] failed: %s", avID, err) return } - if err = gulu.JSON.UnmarshalJSON(data, ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil { logging.LogErrorf("unmarshal attribute view [%s] failed: %s", avID, err) return } @@ -524,13 +524,13 @@ func SaveAttributeView(av *AttributeView) (err error) { } else { data, err = gulu.JSON.MarshalIndentJSON(av, "", "\t") } - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view [%s] failed: %s", av.ID, err) return } avJSONPath := GetAttributeViewDataPath(av.ID) - if err = filelock.WriteFile(avJSONPath, data); nil != err { + if err = filelock.WriteFile(avJSONPath, data); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", av.ID, err) return } @@ -645,11 +645,11 @@ func (av *AttributeView) GetBlockKey() (ret *Key) { func (av *AttributeView) ShallowClone() (ret *AttributeView) { ret = &AttributeView{} data, err := gulu.JSON.MarshalJSON(av) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view [%s] failed: %s", av.ID, err) return nil } - if err = gulu.JSON.UnmarshalJSON(data, ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil { logging.LogErrorf("unmarshal attribute view [%s] failed: %s", av.ID, err) return nil } @@ -708,7 +708,7 @@ func GetAttributeViewDataPath(avID string) (ret string) { av := filepath.Join(util.DataDir, "storage", "av") ret = filepath.Join(av, avID+".json") if !gulu.File.IsDir(av) { - if err := os.MkdirAll(av, 0755); nil != err { + if err := os.MkdirAll(av, 0755); err != nil { logging.LogErrorf("create attribute view dir failed: %s", err) return } diff --git a/kernel/av/mirror.go b/kernel/av/mirror.go index 88786d6f5..95a0795a0 100644 --- a/kernel/av/mirror.go +++ b/kernel/av/mirror.go @@ -29,12 +29,12 @@ func GetBlockRels() (ret map[string][]string) { } data, err := filelock.ReadFile(blocks) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view blocks failed: %s", err) return } - if err = msgpack.Unmarshal(data, &ret); nil != err { + if err = msgpack.Unmarshal(data, &ret); err != nil { logging.LogErrorf("unmarshal attribute view blocks failed: %s", err) return } @@ -51,13 +51,13 @@ func IsMirror(avID string) bool { } data, err := filelock.ReadFile(blocks) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view blocks failed: %s", err) return false } avBlocks := map[string][]string{} - if err = msgpack.Unmarshal(data, &avBlocks); nil != err { + if err = msgpack.Unmarshal(data, &avBlocks); err != nil { logging.LogErrorf("unmarshal attribute view blocks failed: %s", err) return false } @@ -76,13 +76,13 @@ func RemoveBlockRel(avID, blockID string, existBlockTree func(string) bool) (ret } data, err := filelock.ReadFile(blocks) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view blocks failed: %s", err) return } avBlocks := map[string][]string{} - if err = msgpack.Unmarshal(data, &avBlocks); nil != err { + if err = msgpack.Unmarshal(data, &avBlocks); err != nil { logging.LogErrorf("unmarshal attribute view blocks failed: %s", err) return } @@ -104,11 +104,11 @@ func RemoveBlockRel(avID, blockID string, existBlockTree func(string) bool) (ret ret = len(newBlockIDs) != len(blockIDs) data, err = msgpack.Marshal(avBlocks) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view blocks failed: %s", err) return } - if err = filelock.WriteFile(blocks, data); nil != err { + if err = filelock.WriteFile(blocks, data); err != nil { logging.LogErrorf("write attribute view blocks failed: %s", err) return } @@ -122,18 +122,18 @@ func BatchUpsertBlockRel(nodes []*ast.Node) { avBlocks := map[string][]string{} blocks := filepath.Join(util.DataDir, "storage", "av", "blocks.msgpack") if !filelock.IsExist(blocks) { - if err := os.MkdirAll(filepath.Dir(blocks), 0755); nil != err { + if err := os.MkdirAll(filepath.Dir(blocks), 0755); err != nil { logging.LogErrorf("create attribute view dir failed: %s", err) return } } else { data, err := filelock.ReadFile(blocks) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view blocks failed: %s", err) return } - if err = msgpack.Unmarshal(data, &avBlocks); nil != err { + if err = msgpack.Unmarshal(data, &avBlocks); err != nil { logging.LogErrorf("unmarshal attribute view blocks failed: %s", err) return } @@ -155,11 +155,11 @@ func BatchUpsertBlockRel(nodes []*ast.Node) { } data, err := msgpack.Marshal(avBlocks) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view blocks failed: %s", err) return } - if err = filelock.WriteFile(blocks, data); nil != err { + if err = filelock.WriteFile(blocks, data); err != nil { logging.LogErrorf("write attribute view blocks failed: %s", err) return } @@ -172,18 +172,18 @@ func UpsertBlockRel(avID, blockID string) (ret bool) { avBlocks := map[string][]string{} blocks := filepath.Join(util.DataDir, "storage", "av", "blocks.msgpack") if !filelock.IsExist(blocks) { - if err := os.MkdirAll(filepath.Dir(blocks), 0755); nil != err { + if err := os.MkdirAll(filepath.Dir(blocks), 0755); err != nil { logging.LogErrorf("create attribute view dir failed: %s", err) return } } else { data, err := filelock.ReadFile(blocks) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view blocks failed: %s", err) return } - if err = msgpack.Unmarshal(data, &avBlocks); nil != err { + if err = msgpack.Unmarshal(data, &avBlocks); err != nil { logging.LogErrorf("unmarshal attribute view blocks failed: %s", err) return } @@ -197,11 +197,11 @@ func UpsertBlockRel(avID, blockID string) (ret bool) { ret = oldLen != len(blockIDs) && 0 != oldLen data, err := msgpack.Marshal(avBlocks) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view blocks failed: %s", err) return } - if err = filelock.WriteFile(blocks, data); nil != err { + if err = filelock.WriteFile(blocks, data); err != nil { logging.LogErrorf("write attribute view blocks failed: %s", err) return } diff --git a/kernel/av/relation.go b/kernel/av/relation.go index 7d6ccdab9..6ffb73626 100644 --- a/kernel/av/relation.go +++ b/kernel/av/relation.go @@ -26,13 +26,13 @@ func GetSrcAvIDs(destAvID string) []string { } data, err := filelock.ReadFile(relations) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view relations failed: %s", err) return nil } avRels := map[string][]string{} - if err = msgpack.Unmarshal(data, &avRels); nil != err { + if err = msgpack.Unmarshal(data, &avRels); err != nil { logging.LogErrorf("unmarshal attribute view relations failed: %s", err) return nil } @@ -57,13 +57,13 @@ func RemoveAvRel(srcAvID, destAvID string) { } data, err := filelock.ReadFile(relations) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view relations failed: %s", err) return } avRels := map[string][]string{} - if err = msgpack.Unmarshal(data, &avRels); nil != err { + if err = msgpack.Unmarshal(data, &avRels); err != nil { logging.LogErrorf("unmarshal attribute view relations failed: %s", err) return } @@ -82,11 +82,11 @@ func RemoveAvRel(srcAvID, destAvID string) { avRels[destAvID] = newAvIDs data, err = msgpack.Marshal(avRels) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view relations failed: %s", err) return } - if err = filelock.WriteFile(relations, data); nil != err { + if err = filelock.WriteFile(relations, data); err != nil { logging.LogErrorf("write attribute view relations failed: %s", err) return } @@ -99,18 +99,18 @@ func UpsertAvBackRel(srcAvID, destAvID string) { avRelations := map[string][]string{} relations := filepath.Join(util.DataDir, "storage", "av", "relations.msgpack") if !filelock.IsExist(relations) { - if err := os.MkdirAll(filepath.Dir(relations), 0755); nil != err { + if err := os.MkdirAll(filepath.Dir(relations), 0755); err != nil { logging.LogErrorf("create attribute view dir failed: %s", err) return } } else { data, err := filelock.ReadFile(relations) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view relations failed: %s", err) return } - if err = msgpack.Unmarshal(data, &avRelations); nil != err { + if err = msgpack.Unmarshal(data, &avRelations); err != nil { logging.LogErrorf("unmarshal attribute view relations failed: %s", err) return } @@ -122,11 +122,11 @@ func UpsertAvBackRel(srcAvID, destAvID string) { avRelations[destAvID] = srcAvIDs data, err := msgpack.Marshal(avRelations) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view relations failed: %s", err) return } - if err = filelock.WriteFile(relations, data); nil != err { + if err = filelock.WriteFile(relations, data); err != nil { logging.LogErrorf("write attribute view relations failed: %s", err) return } diff --git a/kernel/av/value.go b/kernel/av/value.go index 922226926..bc00f0ee8 100644 --- a/kernel/av/value.go +++ b/kernel/av/value.go @@ -181,7 +181,7 @@ func (value *Value) String(format bool) string { func (value *Value) ToJSONString() string { data, err := gulu.JSON.MarshalJSON(value) - if nil != err { + if err != nil { return "" } return string(data) @@ -189,11 +189,11 @@ func (value *Value) ToJSONString() string { func (value *Value) Clone() (ret *Value) { data, err := gulu.JSON.MarshalJSON(value) - if nil != err { + if err != nil { return } err = gulu.JSON.UnmarshalJSON(data, &ret) - if nil != err { + if err != nil { return } return diff --git a/kernel/bazaar/icon.go b/kernel/bazaar/icon.go index e3635da3a..d0dda33eb 100644 --- a/kernel/bazaar/icon.go +++ b/kernel/bazaar/icon.go @@ -43,7 +43,7 @@ func Icons() (icons []*Icon) { } stageIndex, err := getStageIndex("icons") - if nil != err { + if err != nil { return } bazaarIndex := getBazaarIndex() @@ -127,7 +127,7 @@ func InstalledIcons() (ret []*Icon) { } iconDirs, err := os.ReadDir(util.IconsPath) - if nil != err { + if err != nil { logging.LogWarnf("read icons folder failed: %s", err) return } @@ -193,7 +193,7 @@ func isBuiltInIcon(dirName string) bool { func InstallIcon(repoURL, repoHash, installPath string, systemID string) error { repoURLHash := repoURL + "@" + repoHash data, err := downloadPackage(repoURLHash, true, systemID) - if nil != err { + if err != nil { return err } return installPackage(data, installPath, repoURLHash) diff --git a/kernel/bazaar/package.go b/kernel/bazaar/package.go index 7eb3de138..e9f4df7a3 100644 --- a/kernel/bazaar/package.go +++ b/kernel/bazaar/package.go @@ -249,11 +249,11 @@ func PluginJSON(pluginDirName string) (ret *Plugin, err error) { return } data, err := filelock.ReadFile(p) - if nil != err { + if err != nil { logging.LogErrorf("read plugin.json [%s] failed: %s", p, err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("parse plugin.json [%s] failed: %s", p, err) return } @@ -269,11 +269,11 @@ func WidgetJSON(widgetDirName string) (ret *Widget, err error) { return } data, err := filelock.ReadFile(p) - if nil != err { + if err != nil { logging.LogErrorf("read widget.json [%s] failed: %s", p, err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("parse widget.json [%s] failed: %s", p, err) return } @@ -289,11 +289,11 @@ func IconJSON(iconDirName string) (ret *Icon, err error) { return } data, err := os.ReadFile(p) - if nil != err { + if err != nil { logging.LogErrorf("read icon.json [%s] failed: %s", p, err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("parse icon.json [%s] failed: %s", p, err) return } @@ -309,11 +309,11 @@ func TemplateJSON(templateDirName string) (ret *Template, err error) { return } data, err := filelock.ReadFile(p) - if nil != err { + if err != nil { logging.LogErrorf("read template.json [%s] failed: %s", p, err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("parse template.json [%s] failed: %s", p, err) return } @@ -329,13 +329,13 @@ func ThemeJSON(themeDirName string) (ret *Theme, err error) { return } data, err := os.ReadFile(p) - if nil != err { + if err != nil { logging.LogErrorf("read theme.json [%s] failed: %s", p, err) return } ret = &Theme{} - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("parse theme.json [%s] failed: %s", p, err) return } @@ -350,7 +350,7 @@ var stageIndexLock = sync.Mutex{} func getStageIndex(pkgType string) (ret *StageIndex, err error) { rhyRet, err := util.GetRhyResult(false) - if nil != err { + if err != nil { return } @@ -514,14 +514,14 @@ func GetPackageREADME(repoURL, repoHash, packageType string) (ret string) { readme := getPreferredReadme(repo.Package.Readme) data, err := downloadPackage(repoURLHash+"/"+readme, false, "") - if nil != err { + if err != nil { ret = fmt.Sprintf("Load bazaar package's README.md(%s) failed: %s", readme, err.Error()) if readme == repo.Package.Readme.Default || "" == strings.TrimSpace(repo.Package.Readme.Default) { return } readme = repo.Package.Readme.Default data, err = downloadPackage(repoURLHash+"/"+readme, false, "") - if nil != err { + if err != nil { ret += fmt.Sprintf("
Load bazaar package's README.md(%s) failed: %s", readme, err.Error()) return } @@ -579,7 +579,7 @@ func downloadPackage(repoURLHash string, pushProgress bool, systemID string) (da util.PushDownloadProgress(repoURL, progress) } }).Get(u) - if nil != err { + if err != nil { logging.LogErrorf("get bazaar package [%s] failed: %s", u, err) return nil, errors.New("get bazaar package failed, please check your network") } @@ -608,7 +608,7 @@ func incPackageDownloads(repoURLHash, systemID string) { } func uninstallPackage(installPath string) (err error) { - if err = os.RemoveAll(installPath); nil != err { + if err = os.RemoveAll(installPath); err != nil { logging.LogErrorf("remove [%s] failed: %s", installPath, err) return fmt.Errorf("remove community package [%s] failed", filepath.Base(installPath)) } @@ -618,7 +618,7 @@ func uninstallPackage(installPath string) (err error) { func installPackage(data []byte, installPath, repoURLHash string) (err error) { err = installPackage0(data, installPath) - if nil != err { + if err != nil { return } @@ -628,23 +628,23 @@ func installPackage(data []byte, installPath, repoURLHash string) (err error) { func installPackage0(data []byte, installPath string) (err error) { tmpPackage := filepath.Join(util.TempDir, "bazaar", "package") - if err = os.MkdirAll(tmpPackage, 0755); nil != err { + if err = os.MkdirAll(tmpPackage, 0755); err != nil { return } name := gulu.Rand.String(7) tmp := filepath.Join(tmpPackage, name+".zip") - if err = os.WriteFile(tmp, data, 0644); nil != err { + if err = os.WriteFile(tmp, data, 0644); err != nil { return } unzipPath := filepath.Join(tmpPackage, name) - if err = gulu.Zip.Unzip(tmp, unzipPath); nil != err { + if err = gulu.Zip.Unzip(tmp, unzipPath); err != nil { logging.LogErrorf("write file [%s] failed: %s", installPath, err) return } dirs, err := os.ReadDir(unzipPath) - if nil != err { + if err != nil { return } @@ -653,7 +653,7 @@ func installPackage0(data []byte, installPath string) (err error) { srcPath = filepath.Join(unzipPath, dirs[0].Name()) } - if err = filelock.Copy(srcPath, installPath); nil != err { + if err = filelock.Copy(srcPath, installPath); err != nil { return } return diff --git a/kernel/bazaar/plugin.go b/kernel/bazaar/plugin.go index 86d7decc3..5bf4bacad 100644 --- a/kernel/bazaar/plugin.go +++ b/kernel/bazaar/plugin.go @@ -45,7 +45,7 @@ func Plugins(frontend string) (plugins []*Plugin) { } stageIndex, err := getStageIndex("plugins") - if nil != err { + if err != nil { return } bazaarIndex := getBazaarIndex() @@ -131,7 +131,7 @@ func ParseInstalledPlugin(name, frontend string) (found bool, displayName string } pluginDirs, err := os.ReadDir(pluginsPath) - if nil != err { + if err != nil { logging.LogWarnf("read plugins folder failed: %s", err) return } @@ -166,7 +166,7 @@ func InstalledPlugins(frontend string, checkUpdate bool) (ret []*Plugin) { } pluginDirs, err := os.ReadDir(pluginsPath) - if nil != err { + if err != nil { logging.LogWarnf("read plugins folder failed: %s", err) return } @@ -228,7 +228,7 @@ func InstalledPlugins(frontend string, checkUpdate bool) (ret []*Plugin) { func InstallPlugin(repoURL, repoHash, installPath string, systemID string) error { repoURLHash := repoURL + "@" + repoHash data, err := downloadPackage(repoURLHash, true, systemID) - if nil != err { + if err != nil { return err } return installPackage(data, installPath, repoURLHash) diff --git a/kernel/bazaar/template.go b/kernel/bazaar/template.go index 46f28f9e7..2b61a3224 100644 --- a/kernel/bazaar/template.go +++ b/kernel/bazaar/template.go @@ -44,7 +44,7 @@ func Templates() (templates []*Template) { } stageIndex, err := getStageIndex("templates") - if nil != err { + if err != nil { return } bazaarIndex := getBazaarIndex() @@ -131,7 +131,7 @@ func InstalledTemplates() (ret []*Template) { } templateDirs, err := os.ReadDir(templatesPath) - if nil != err { + if err != nil { logging.LogWarnf("read templates folder failed: %s", err) return } @@ -190,7 +190,7 @@ func InstalledTemplates() (ret []*Template) { func InstallTemplate(repoURL, repoHash, installPath string, systemID string) error { repoURLHash := repoURL + "@" + repoHash data, err := downloadPackage(repoURLHash, true, systemID) - if nil != err { + if err != nil { return err } return installPackage(data, installPath, repoURLHash) @@ -206,7 +206,7 @@ func filterLegacyTemplates(templates []*Template) (ret []*Template) { if "" != theme.Updated { updated := theme.Updated[:len("2006-01-02T15:04:05")] t, err := time.Parse("2006-01-02T15:04:05", updated) - if nil != err { + if err != nil { logging.LogErrorf("convert update time [%s] failed: %s", updated, err) continue } diff --git a/kernel/bazaar/theme.go b/kernel/bazaar/theme.go index 2a6a0e5a1..5d29ceebd 100644 --- a/kernel/bazaar/theme.go +++ b/kernel/bazaar/theme.go @@ -45,7 +45,7 @@ func Themes() (ret []*Theme) { } stageIndex, err := getStageIndex("themes") - if nil != err { + if err != nil { return } bazaarIndex := getBazaarIndex() @@ -129,7 +129,7 @@ func InstalledThemes() (ret []*Theme) { } themeDirs, err := os.ReadDir(util.ThemesPath) - if nil != err { + if err != nil { logging.LogWarnf("read appearance themes folder failed: %s", err) return } @@ -195,7 +195,7 @@ func isBuiltInTheme(dirName string) bool { func InstallTheme(repoURL, repoHash, installPath string, systemID string) error { repoURLHash := repoURL + "@" + repoHash data, err := downloadPackage(repoURLHash, true, systemID) - if nil != err { + if err != nil { return err } return installPackage(data, installPath, repoURLHash) diff --git a/kernel/bazaar/widget.go b/kernel/bazaar/widget.go index cd4b504d7..6a4c17459 100644 --- a/kernel/bazaar/widget.go +++ b/kernel/bazaar/widget.go @@ -43,7 +43,7 @@ func Widgets() (widgets []*Widget) { } stageIndex, err := getStageIndex("widgets") - if nil != err { + if err != nil { return } bazaarIndex := getBazaarIndex() @@ -129,7 +129,7 @@ func InstalledWidgets() (ret []*Widget) { } widgetDirs, err := os.ReadDir(widgetsPath) - if nil != err { + if err != nil { logging.LogWarnf("read widgets folder failed: %s", err) return } @@ -188,7 +188,7 @@ func InstalledWidgets() (ret []*Widget) { func InstallWidget(repoURL, repoHash, installPath string, systemID string) error { repoURLHash := repoURL + "@" + repoHash data, err := downloadPackage(repoURLHash, true, systemID) - if nil != err { + if err != nil { return err } return installPackage(data, installPath, repoURLHash) diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go index e8b5bc4bb..9ca4df1b6 100644 --- a/kernel/conf/ai.go +++ b/kernel/conf/ai.go @@ -17,10 +17,11 @@ package conf import ( - "github.com/siyuan-note/siyuan/kernel/util" "os" "strconv" + "github.com/siyuan-note/siyuan/kernel/util" + "github.com/sashabaranov/go-openai" ) @@ -57,7 +58,7 @@ func NewAI() *AI { if timeout := os.Getenv("SIYUAN_OPENAI_API_TIMEOUT"); "" != timeout { timeoutInt, err := strconv.Atoi(timeout) - if nil == err { + if err == nil { openAI.APITimeout = timeoutInt } } @@ -68,21 +69,21 @@ func NewAI() *AI { if maxTokens := os.Getenv("SIYUAN_OPENAI_API_MAX_TOKENS"); "" != maxTokens { maxTokensInt, err := strconv.Atoi(maxTokens) - if nil == err { + if err == nil { openAI.APIMaxTokens = maxTokensInt } } if temperature := os.Getenv("SIYUAN_OPENAI_API_TEMPERATURE"); "" != temperature { temperatureFloat, err := strconv.ParseFloat(temperature, 64) - if nil == err { + if err == nil { openAI.APITemperature = temperatureFloat } } if maxContexts := os.Getenv("SIYUAN_OPENAI_API_MAX_CONTEXTS"); "" != maxContexts { maxContextsInt, err := strconv.Atoi(maxContexts) - if nil == err { + if err == nil { openAI.APIMaxContexts = maxContextsInt } } diff --git a/kernel/filesys/json_parser.go b/kernel/filesys/json_parser.go index cdf755331..cac8a8bb4 100644 --- a/kernel/filesys/json_parser.go +++ b/kernel/filesys/json_parser.go @@ -30,7 +30,7 @@ import ( func ParseJSONWithoutFix(jsonData []byte, options *parse.Options) (ret *parse.Tree, err error) { root := &ast.Node{} err = unmarshalJSON(jsonData, root) - if nil != err { + if err != nil { return } @@ -52,7 +52,7 @@ func ParseJSONWithoutFix(jsonData []byte, options *parse.Options) (ret *parse.Tr func ParseJSON(jsonData []byte, options *parse.Options) (ret *parse.Tree, needFix bool, err error) { root := &ast.Node{} err = unmarshalJSON(jsonData, root) - if nil != err { + if err != nil { return } diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.go index 029257b26..4ae68e886 100644 --- a/kernel/filesys/tree.go +++ b/kernel/filesys/tree.go @@ -58,7 +58,7 @@ func LoadTrees(ids []string) (ret map[string]*parse.Tree) { func LoadTree(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, err error) { filePath := filepath.Join(util.DataDir, boxID, p) data, err := filelock.ReadFile(filePath) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", p, err) return } @@ -135,11 +135,11 @@ func LoadTreeByData(data []byte, boxID, p string, luteEngine *lute.Lute) (ret *p func WriteTree(tree *parse.Tree) (err error) { data, filePath, err := prepareWriteTree(tree) - if nil != err { + if err != nil { return } - if err = filelock.WriteFile(filePath, data); nil != err { + if err = filelock.WriteFile(filePath, data); err != nil { msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err) logging.LogErrorf(msg) return errors.New(msg) @@ -172,13 +172,13 @@ func prepareWriteTree(tree *parse.Tree) (data []byte, filePath string, err error if !util.UseSingleLineSave { buf := bytes.Buffer{} buf.Grow(1024 * 1024 * 2) - if err = json.Indent(&buf, data, "", "\t"); nil != err { + if err = json.Indent(&buf, data, "", "\t"); err != nil { return } data = buf.Bytes() } - if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err { + if err = os.MkdirAll(filepath.Dir(filePath), 0755); err != nil { return } return @@ -193,7 +193,7 @@ func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (re var err error var needFix bool ret, needFix, err = ParseJSON(jsonData, luteEngine.ParseOptions) - if nil != err { + if err != nil { logging.LogErrorf("parse json [%s] to tree failed: %s", boxID+p, err) return } @@ -215,16 +215,16 @@ func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (re if !util.UseSingleLineSave { buf := bytes.Buffer{} buf.Grow(1024 * 1024 * 2) - if err = json.Indent(&buf, data, "", "\t"); nil != err { + if err = json.Indent(&buf, data, "", "\t"); err != nil { return } data = buf.Bytes() } - if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err { + if err = os.MkdirAll(filepath.Dir(filePath), 0755); err != nil { return } - if err = filelock.WriteFile(filePath, data); nil != err { + if err = filelock.WriteFile(filePath, data); err != nil { msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err) logging.LogErrorf(msg) } diff --git a/kernel/mobile/kernel.go b/kernel/mobile/kernel.go index 61d7c2552..900238fcf 100644 --- a/kernel/mobile/kernel.go +++ b/kernel/mobile/kernel.go @@ -91,7 +91,7 @@ func GetCurrentWorkspacePath() string { func GetAssetAbsPath(asset string) (ret string) { ret, err := model.GetAssetAbsPath(asset) - if nil != err { + if err != nil { logging.LogErrorf("get asset [%s] abs path failed: %s", asset, err) ret = asset } diff --git a/kernel/model/ai.go b/kernel/model/ai.go index a64348000..4b48ad171 100644 --- a/kernel/model/ai.go +++ b/kernel/model/ai.go @@ -61,7 +61,7 @@ func chatGPT(msg string, cloud bool) (ret string) { } ret, retCtxMsgs, err := chatGPTContinueWrite(msg, cachedContextMsg, cloud) - if nil != err { + if err != nil { return } cachedContextMsg = append(cachedContextMsg, retCtxMsgs...) @@ -74,7 +74,7 @@ func chatGPTWithAction(msg string, action string, cloud bool) (ret string) { msg = action + ":\n\n" + msg } ret, _, err := chatGPTContinueWrite(msg, nil, cloud) - if nil != err { + if err != nil { return } return diff --git a/kernel/model/appearance.go b/kernel/model/appearance.go index 597ce759e..bc1a5686d 100644 --- a/kernel/model/appearance.go +++ b/kernel/model/appearance.go @@ -34,7 +34,7 @@ import ( func InitAppearance() { util.SetBootDetails("Initializing appearance...") - if err := os.Mkdir(util.AppearancePath, 0755); nil != err && !os.IsExist(err) { + if err := os.Mkdir(util.AppearancePath, 0755); err != nil && !os.IsExist(err) { logging.LogErrorf("create appearance folder [%s] failed: %s", util.AppearancePath, err) util.ReportFileSysFatalError(err) return @@ -42,7 +42,7 @@ func InitAppearance() { unloadThemes() from := filepath.Join(util.WorkingDir, "appearance") - if err := filelock.Copy(from, util.AppearancePath); nil != err { + if err := filelock.Copy(from, util.AppearancePath); err != nil { logging.LogErrorf("copy appearance resources from [%s] to [%s] failed: %s", from, util.AppearancePath, err) util.ReportFileSysFatalError(err) return @@ -70,7 +70,7 @@ var themeWatchers = sync.Map{} // [string]*fsnotify.Watcher{} func closeThemeWatchers() { themeWatchers.Range(func(key, value interface{}) bool { - if err := value.(*fsnotify.Watcher).Close(); nil != err { + if err := value.(*fsnotify.Watcher).Close(); err != nil { logging.LogErrorf("close file watcher failed: %s", err) } return true @@ -83,7 +83,7 @@ func unloadThemes() { } themeDirs, err := os.ReadDir(util.ThemesPath) - if nil != err { + if err != nil { logging.LogErrorf("read appearance themes folder failed: %s", err) return } @@ -98,7 +98,7 @@ func unloadThemes() { func loadThemes() { themeDirs, err := os.ReadDir(util.ThemesPath) - if nil != err { + if err != nil { logging.LogErrorf("read appearance themes folder failed: %s", err) util.ReportFileSysFatalError(err) return @@ -143,7 +143,7 @@ func loadThemes() { func loadIcons() { iconDirs, err := os.ReadDir(util.IconsPath) - if nil != err { + if err != nil { logging.LogErrorf("read appearance icons folder failed: %s", err) util.ReportFileSysFatalError(err) return @@ -156,7 +156,7 @@ func loadIcons() { } name := iconDir.Name() iconConf, err := bazaar.IconJSON(name) - if nil != err || nil == iconConf { + if err != nil || nil == iconConf { continue } Conf.Appearance.Icons = append(Conf.Appearance.Icons, name) @@ -183,7 +183,7 @@ func watchTheme(folder string) { } var err error - if themeWatcher, err = fsnotify.NewWatcher(); nil != err { + if themeWatcher, err = fsnotify.NewWatcher(); err != nil { logging.LogErrorf("add theme file watcher for folder [%s] failed: %s", folder, err) return } diff --git a/kernel/model/asset_content.go b/kernel/model/asset_content.go index c5ec26b4c..628f72383 100644 --- a/kernel/model/asset_content.go +++ b/kernel/model/asset_content.go @@ -312,7 +312,7 @@ func IndexAssetContent(absPath string) { } info, err := os.Stat(absPath) - if nil != err { + if err != nil { logging.LogErrorf("stat [%s] failed: %s", absPath, err) return } @@ -385,7 +385,7 @@ func (searcher *AssetsSearcher) FullIndex() { var results []*AssetParseResult filelock.Walk(assetsDir, func(absPath string, info fs.FileInfo, err error) error { - if nil != err { + if err != nil { logging.LogErrorf("walk dir [%s] failed: %s", absPath, err) return err } @@ -502,7 +502,7 @@ type TxtAssetParser struct { func (parser *TxtAssetParser) Parse(absPath string) (ret *AssetParseResult) { info, err := os.Stat(absPath) - if nil != err { + if err != nil { logging.LogErrorf("stat file [%s] failed: %s", absPath, err) return } @@ -519,7 +519,7 @@ func (parser *TxtAssetParser) Parse(absPath string) (ret *AssetParseResult) { defer os.RemoveAll(tmp) data, err := os.ReadFile(tmp) - if nil != err { + if err != nil { logging.LogErrorf("read file [%s] failed: %s", absPath, err) return } @@ -544,7 +544,7 @@ func normalizeNonTxtAssetContent(content string) (ret string) { func copyTempAsset(absPath string) (ret string) { dir := filepath.Join(util.TempDir, "convert", "asset_content") - 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 } @@ -559,7 +559,7 @@ func copyTempAsset(absPath string) (ret string) { ext := filepath.Ext(absPath) ret = filepath.Join(dir, gulu.Rand.String(7)+ext) - if err := gulu.File.Copy(absPath, ret); nil != err { + if err := gulu.File.Copy(absPath, ret); err != nil { logging.LogErrorf("copy [src=%s, dest=%s] failed: %s", absPath, ret, err) return } @@ -585,14 +585,14 @@ func (parser *DocxAssetParser) Parse(absPath string) (ret *AssetParseResult) { defer os.RemoveAll(tmp) f, err := os.Open(tmp) - if nil != err { + if err != nil { logging.LogErrorf("open [%s] failed: [%s]", tmp, err) return } defer f.Close() data, _, err := docconv.ConvertDocx(f) - if nil != err { + if err != nil { logging.LogErrorf("convert [%s] failed: [%s]", tmp, err) return } @@ -623,14 +623,14 @@ func (parser *PptxAssetParser) Parse(absPath string) (ret *AssetParseResult) { defer os.RemoveAll(tmp) f, err := os.Open(tmp) - if nil != err { + if err != nil { logging.LogErrorf("open [%s] failed: [%s]", tmp, err) return } defer f.Close() data, _, err := docconv.ConvertPptx(f) - if nil != err { + if err != nil { logging.LogErrorf("convert [%s] failed: [%s]", tmp, err) return } @@ -661,7 +661,7 @@ func (parser *XlsxAssetParser) Parse(absPath string) (ret *AssetParseResult) { defer os.RemoveAll(tmp) x, err := excelize.OpenFile(tmp) - if nil != err { + if err != nil { logging.LogErrorf("open [%s] failed: [%s]", tmp, err) return } @@ -713,7 +713,7 @@ func (parser *PdfAssetParser) getTextPageWorker(id int, instance pdfium.Pdfium, doc, err := instance.OpenDocument(&requests.OpenDocument{ File: pd.data, }) - if nil != err { + if err != nil { instance.FPDF_CloseDocument(&requests.FPDF_CloseDocument{ Document: doc.Document, }) @@ -733,7 +733,7 @@ func (parser *PdfAssetParser) getTextPageWorker(id int, instance pdfium.Pdfium, }, } res, err := instance.GetPageText(req) - if nil != err { + if err != nil { instance.FPDF_CloseDocument(&requests.FPDF_CloseDocument{ Document: doc.Document, }) @@ -778,7 +778,7 @@ func (parser *PdfAssetParser) Parse(absPath string) (ret *AssetParseResult) { // PDF blob will be processed in-memory making sharing of PDF document data across worker goroutines possible pdfData, err := os.ReadFile(tmp) - if nil != err { + if err != nil { logging.LogErrorf("open [%s] failed: [%s]", tmp, err) return } @@ -795,7 +795,7 @@ func (parser *PdfAssetParser) Parse(absPath string) (ret *AssetParseResult) { MaxIdle: cores, MaxTotal: cores, }) - if nil != err { + if err != nil { logging.LogErrorf("convert [%s] failed: [%s]", tmp, err) return } @@ -803,20 +803,20 @@ func (parser *PdfAssetParser) Parse(absPath string) (ret *AssetParseResult) { // first get the number of PDF pages to convert into text instance, err := pool.GetInstance(time.Second * 30) - if nil != err { + if err != nil { logging.LogErrorf("convert [%s] failed: [%s]", tmp, err) return } doc, err := instance.OpenDocument(&requests.OpenDocument{ File: &pdfData, }) - if nil != err { + if err != nil { instance.Close() logging.LogErrorf("convert [%s] failed: [%s]", tmp, err) return } pc, err := instance.FPDF_GetPageCount(&requests.FPDF_GetPageCount{Document: doc.Document}) - if nil != err { + if err != nil { instance.FPDF_CloseDocument(&requests.FPDF_CloseDocument{ Document: doc.Document, }) @@ -854,7 +854,7 @@ func (parser *PdfAssetParser) Parse(absPath string) (ret *AssetParseResult) { results := make(chan *pdfTextResult, pc.PageCount) for i := 0; i < cores; i++ { inst, err := pool.GetInstance(time.Second * 30) - if nil != err { + if err != nil { close(pages) close(results) logging.LogErrorf("convert [%s] failed: [%s]", tmp, err) @@ -919,14 +919,14 @@ func (parser *EpubAssetParser) Parse(absPath string) (ret *AssetParseResult) { defer os.RemoveAll(tmp) f, err := os.Open(tmp) - if nil != err { + if err != nil { logging.LogErrorf("open [%s] failed: [%s]", tmp, err) return } defer f.Close() buf := bytes.Buffer{} - if err = epub.ToTxt(tmp, &buf); nil != err { + if err = epub.ToTxt(tmp, &buf); err != nil { logging.LogErrorf("convert [%s] failed: [%s]", tmp, err) return } diff --git a/kernel/model/assets.go b/kernel/model/assets.go index 06a9567e2..e91319331 100644 --- a/kernel/model/assets.go +++ b/kernel/model/assets.go @@ -54,7 +54,7 @@ import ( func DocImageAssets(rootID string) (ret []string, err error) { tree, err := LoadTreeByBlockID(rootID) - if nil != err { + if err != nil { return } @@ -77,7 +77,7 @@ func DocImageAssets(rootID string) (ret []string, err error) { func NetAssets2LocalAssets(rootID string, onlyImg bool, originalURL string) (err error) { tree, err := LoadTreeByBlockID(rootID) - if nil != err { + if err != nil { return } @@ -87,7 +87,7 @@ func NetAssets2LocalAssets(rootID string, onlyImg bool, originalURL string) (err docDirLocalPath := filepath.Join(util.DataDir, tree.Box, path.Dir(tree.Path)) assetsDirPath := getAssetsDir(filepath.Join(util.DataDir, tree.Box), docDirLocalPath) if !gulu.File.IsExist(assetsDirPath) { - if err = os.MkdirAll(assetsDirPath, 0755); nil != err { + if err = os.MkdirAll(assetsDirPath, 0755); err != nil { return } } @@ -127,7 +127,7 @@ func NetAssets2LocalAssets(rootID string, onlyImg bool, originalURL string) (err name = "network-asset-" + name name = util.AssetName(name) writePath := filepath.Join(assetsDirPath, name) - if err = filelock.Copy(u, writePath); nil != err { + if err = filelock.Copy(u, writePath); err != nil { logging.LogErrorf("copy [%s] to [%s] failed: %s", u, writePath, err) continue } @@ -223,7 +223,7 @@ func NetAssets2LocalAssets(rootID string, onlyImg bool, originalURL string) (err name = util.TruncateLenFileName(name) name = "network-asset-" + name + "-" + ast.NewNodeID() + ext writePath := filepath.Join(assetsDirPath, name) - if err = filelock.WriteFile(writePath, data); nil != err { + if err = filelock.WriteFile(writePath, data); err != nil { logging.LogErrorf("write downloaded network asset [%s] to local asset [%s] failed: %s", u, writePath, err) continue } @@ -237,7 +237,7 @@ func NetAssets2LocalAssets(rootID string, onlyImg bool, originalURL string) (err if 0 < files { util.PushUpdateMsg(msgId, Conf.Language(113), 7000) - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { return } util.PushUpdateMsg(msgId, fmt.Sprintf(Conf.Language(120), files), 5000) @@ -303,7 +303,7 @@ func GetAssetAbsPath(relativePath string) (ret string, err error) { relativePath = relativePath[:strings.Index(relativePath, "?")] } notebooks, err := ListNotebooks() - if nil != err { + if err != nil { err = errors.New(Conf.Language(0)) return } @@ -355,7 +355,7 @@ func UploadAssets2Cloud(rootID string) (count int, err error) { } tree, err := LoadTreeByBlockID(rootID) - if nil != err { + if err != nil { return } @@ -366,7 +366,7 @@ func UploadAssets2Cloud(rootID string) (count int, err error) { assets = append(assets, avAssets...) assets = gulu.Str.RemoveDuplicatedElem(assets) count, err = uploadAssets2Cloud(assets, bizTypeUploadAssets) - if nil != err { + if err != nil { return } return @@ -383,7 +383,7 @@ func uploadAssets2Cloud(assetPaths []string, bizType string) (count int, err err for _, assetPath := range assetPaths { var absPath string absPath, err = GetAssetAbsPath(assetPath) - if nil != err { + if err != nil { logging.LogWarnf("get asset [%s] abs path failed: %s", assetPath, err) return } @@ -486,17 +486,19 @@ func uploadAssets2Cloud(assetPaths []string, bizType string) (count int, err err } func RemoveUnusedAssets() (ret []string) { + ret = []string{} + var size int64 + msgId := util.PushMsg(Conf.Language(100), 30*1000) defer func() { - util.PushClearMsg(msgId) - util.PushMsg(Conf.Language(99), 3000) + msg := fmt.Sprintf(Conf.Language(91), len(ret), humanize.BytesCustomCeil(uint64(size), 2)) + util.PushUpdateMsg(msgId, msg, 7000) }() - ret = []string{} unusedAssets := UnusedAssets() historyDir, err := GetHistoryDir(HistoryOpClean) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } @@ -509,7 +511,7 @@ func RemoveUnusedAssets() (ret []string) { continue } - if err = filelock.Copy(p, historyPath); nil != err { + if err = filelock.Copy(p, historyPath); err != nil { return } @@ -522,7 +524,12 @@ func RemoveUnusedAssets() (ret []string) { for _, unusedAsset := range unusedAssets { if unusedAsset = filepath.Join(util.DataDir, unusedAsset); filelock.IsExist(unusedAsset) { - if err := filelock.Remove(unusedAsset); nil != err { + info, statErr := os.Stat(unusedAsset) + if statErr == nil { + size += info.Size() + } + + if err := filelock.Remove(unusedAsset); err != nil { logging.LogErrorf("remove unused asset [%s] failed: %s", unusedAsset, err) } } @@ -544,7 +551,7 @@ func RemoveUnusedAsset(p string) (ret string) { } historyDir, err := GetHistoryDir(HistoryOpClean) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } @@ -552,7 +559,7 @@ func RemoveUnusedAsset(p string) (ret string) { newP := strings.TrimPrefix(absPath, util.DataDir) historyPath := filepath.Join(historyDir, newP) if filelock.IsExist(absPath) { - if err = filelock.Copy(absPath, historyPath); nil != err { + if err = filelock.Copy(absPath, historyPath); err != nil { return } @@ -560,7 +567,7 @@ func RemoveUnusedAsset(p string) (ret string) { sql.BatchRemoveAssetsQueue([]string{hash}) } - if err = filelock.Remove(absPath); nil != err { + if err = filelock.Remove(absPath); err != nil { logging.LogErrorf("remove unused asset [%s] failed: %s", absPath, err) } ret = absPath @@ -591,14 +598,14 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) { newName = util.AssetName(newName + filepath.Ext(oldPath)) newPath = "assets/" + newName - if err = filelock.Copy(filepath.Join(util.DataDir, oldPath), filepath.Join(util.DataDir, newPath)); nil != err { + if err = filelock.Copy(filepath.Join(util.DataDir, oldPath), filepath.Join(util.DataDir, newPath)); err != nil { logging.LogErrorf("copy asset [%s] failed: %s", oldPath, err) return } if filelock.IsExist(filepath.Join(util.DataDir, oldPath+".sya")) { // Rename the .sya annotation file when renaming a PDF asset https://github.com/siyuan-note/siyuan/issues/9390 - if err = filelock.Copy(filepath.Join(util.DataDir, oldPath+".sya"), filepath.Join(util.DataDir, newPath+".sya")); nil != err { + if err = filelock.Copy(filepath.Join(util.DataDir, oldPath+".sya"), filepath.Join(util.DataDir, newPath+".sya")); err != nil { logging.LogErrorf("copy PDF annotation [%s] failed: %s", oldPath+".sya", err) return } @@ -607,7 +614,7 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) { oldName := path.Base(oldPath) notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } @@ -659,12 +666,12 @@ func UnusedAssets() (ret []string) { ret = []string{} assetsPathMap, err := allAssetAbsPaths() - if nil != err { + if err != nil { return } linkDestMap := map[string]bool{} notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } luteEngine := util.NewLute() @@ -815,11 +822,11 @@ func MissingAssets() (ret []string) { ret = []string{} assetsPathMap, err := allAssetAbsPaths() - if nil != err { + if err != nil { return } notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } luteEngine := util.NewLute() @@ -1188,7 +1195,7 @@ func getRemoteAssetsLinkDestsInTree(tree *parse.Tree, onlyImg bool) (nodes []*as // allAssetAbsPaths 返回 asset 相对路径(assets/xxx)到绝对路径(F:\SiYuan\data\assets\xxx)的映射。 func allAssetAbsPaths() (assetsAbsPathMap map[string]string, err error) { notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } @@ -1305,7 +1312,7 @@ func copyAssetsToDataAssets(rootPath string) { dataAssetsPath := filepath.Join(util.DataDir, "assets") for _, assetsDirPath := range assetsDirPaths { - if err := filelock.Copy(assetsDirPath, dataAssetsPath); nil != err { + if err := filelock.Copy(assetsDirPath, dataAssetsPath); err != nil { logging.LogErrorf("copy tree assets from [%s] to [%s] failed: %s", assetsDirPaths, dataAssetsPath, err) } } diff --git a/kernel/model/assets_watcher.go b/kernel/model/assets_watcher.go index 937860b8d..da67e2e22 100644 --- a/kernel/model/assets_watcher.go +++ b/kernel/model/assets_watcher.go @@ -49,7 +49,7 @@ func watchAssets() { } var err error - if assetsWatcher, err = fsnotify.NewWatcher(); nil != err { + if assetsWatcher, err = fsnotify.NewWatcher(); err != nil { logging.LogErrorf("add assets watcher for folder [%s] failed: %s", assetsDir, err) return } diff --git a/kernel/model/assets_watcher_darwin.go b/kernel/model/assets_watcher_darwin.go index 35d926895..f5d39e378 100644 --- a/kernel/model/assets_watcher_darwin.go +++ b/kernel/model/assets_watcher_darwin.go @@ -76,13 +76,13 @@ func watchAssets() { } }() - if err := assetsWatcher.Add(assetsDir); nil != err { + if err := assetsWatcher.Add(assetsDir); err != nil { logging.LogErrorf("add assets watcher for folder [%s] failed: %s", assetsDir, err) return } //logging.LogInfof("added file watcher [%s]", assetsDir) - if err := assetsWatcher.Start(10 * time.Second); nil != err { + if err := assetsWatcher.Start(10 * time.Second); err != nil { logging.LogErrorf("start assets watcher for folder [%s] failed: %s", assetsDir, err) return } diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go index dff46f334..62075a389 100644 --- a/kernel/model/attribute_view.go +++ b/kernel/model/attribute_view.go @@ -45,7 +45,7 @@ import ( func AppendAttributeViewDetachedBlocksWithValues(avID string, blocksValues [][]*av.Value) (err error) { attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } @@ -87,7 +87,7 @@ func AppendAttributeViewDetachedBlocksWithValues(avID string, blocksValues [][]* } } - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return } @@ -102,12 +102,12 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error) newAvID, newBlockID = ast.NewNodeID(), ast.NewNodeID() oldAv, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { return } data, err := filelock.ReadFile(oldAvPath) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view [%s] failed: %s", avID, err) return } @@ -116,7 +116,7 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error) av.UpsertBlockRel(newAvID, newBlockID) newAv := &av.AttributeView{} - if err = gulu.JSON.UnmarshalJSON(data, newAv); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, newAv); err != nil { logging.LogErrorf("unmarshal attribute view [%s] failed: %s", newAvID, err) return } @@ -132,13 +132,13 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error) } data, err = gulu.JSON.MarshalJSON(newAv) - if nil != err { + if err != nil { logging.LogErrorf("marshal attribute view [%s] failed: %s", newAvID, err) return } newAvPath := filepath.Join(storageAvDir, newAvID+".json") - if err = filelock.WriteFile(newAvPath, data); nil != err { + if err = filelock.WriteFile(newAvPath, data); err != nil { logging.LogErrorf("write attribute view [%s] failed: %s", newAvID, err) return } @@ -151,7 +151,7 @@ func GetAttributeViewKeysByAvID(avID string) (ret []*av.Key) { ret = []*av.Key{} attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } @@ -165,14 +165,14 @@ func GetAttributeViewKeysByAvID(avID string) (ret []*av.Key) { func SetDatabaseBlockView(blockID, viewID string) (err error) { node, tree, err := getNodeByBlockID(nil, blockID) - if nil != err { + if err != nil { return } attrs := parse.IAL2Map(node.KramdownIAL) attrs[av.NodeAttrView] = viewID err = setNodeAttrs(node, tree, attrs) - if nil != err { + if err != nil { logging.LogWarnf("set node [%s] attrs failed: %s", blockID, err) return } @@ -183,7 +183,7 @@ func GetAttributeViewPrimaryKeyValues(avID, keyword string, page, pageSize int) waitForSyncingStorages() attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } @@ -235,7 +235,7 @@ func GetAttributeViewFilterSort(avID, blockID string) (filters []*av.ViewFilter, waitForSyncingStorages() attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } @@ -243,7 +243,7 @@ func GetAttributeViewFilterSort(avID, blockID string) (filters []*av.ViewFilter, view, err := getAttrViewViewByBlockID(attrView, blockID) if nil == view { view, err = attrView.GetCurrentView(attrView.ViewID) - if nil != err { + if err != nil { logging.LogErrorf("get current view failed: %s", err) return } @@ -264,7 +264,7 @@ func SearchAttributeViewNonRelationKey(avID, keyword string) (ret []*av.Key) { ret = []*av.Key{} attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } @@ -284,7 +284,7 @@ func SearchAttributeViewRelationKey(avID, keyword string) (ret []*av.Key) { ret = []*av.Key{} attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } @@ -329,7 +329,7 @@ func SearchAttributeView(keyword string, excludeAvIDs []string) (ret []*SearchAt var avs []*result avDir := filepath.Join(util.DataDir, "storage", "av") entries, err := os.ReadDir(avDir) - if nil != err { + if err != nil { logging.LogErrorf("read directory [%s] failed: %s", avDir, err) return } @@ -485,7 +485,7 @@ func GetBlockAttributeViewKeys(blockID string) (ret []*BlockAttributeViewKeys) { avIDs := strings.Split(avs, ",") for _, avID := range avIDs { attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) unbindBlockAv(nil, avID, blockID) return @@ -710,17 +710,17 @@ func GetBlockAttributeViewKeys(blockID string) (ret []*BlockAttributeViewKeys) { func RenderRepoSnapshotAttributeView(indexID, avID string) (viewable av.Viewable, attrView *av.AttributeView, err error) { repo, err := newRepository() - if nil != err { + if err != nil { return } index, err := repo.GetIndex(indexID) - if nil != err { + if err != nil { return } files, err := repo.GetFiles(index) - if nil != err { + if err != nil { return } var avFile *entity.File @@ -741,7 +741,7 @@ func RenderRepoSnapshotAttributeView(indexID, avID string) (viewable av.Viewable } attrView = &av.AttributeView{} - if err = gulu.JSON.UnmarshalJSON(data, attrView); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, attrView); err != nil { logging.LogErrorf("unmarshal attribute view [%s] failed: %s", avID, err) return } @@ -761,7 +761,7 @@ func RenderHistoryAttributeView(avID, created string) (viewable av.Viewable, att dirPrefix := time.Unix(createdUnix, 0).Format("2006-01-02-150405") globPath := filepath.Join(util.HistoryDir, dirPrefix+"*") matches, err := filepath.Glob(globPath) - if nil != err { + if err != nil { logging.LogErrorf("glob [%s] failed: %s", globPath, err) return } @@ -784,7 +784,7 @@ func RenderHistoryAttributeView(avID, created string) (viewable av.Viewable, att } attrView = &av.AttributeView{} - if err = gulu.JSON.UnmarshalJSON(data, attrView); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, attrView); err != nil { logging.LogErrorf("unmarshal attribute view [%s] failed: %s", avID, err) return } @@ -799,14 +799,14 @@ func RenderAttributeView(avID, viewID, query string, page, pageSize int) (viewab if avJSONPath := av.GetAttributeViewDataPath(avID); !filelock.IsExist(avJSONPath) { attrView = av.NewAttributeView(avID) - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return } } attrView, err = av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } @@ -820,7 +820,7 @@ func renderAttributeView(attrView *av.AttributeView, viewID, query string, page, view, _, _ := av.NewTableViewWithBlockKey(ast.NewNodeID()) attrView.Views = append(attrView.Views, view) attrView.ViewID = view.ID - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", attrView.ID, err) return } @@ -831,7 +831,7 @@ func renderAttributeView(attrView *av.AttributeView, viewID, query string, page, view, _ = attrView.GetCurrentView(viewID) if nil != view && view.ID != attrView.ViewID { attrView.ViewID = view.ID - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", attrView.ID, err) return } @@ -973,7 +973,7 @@ func renderAttributeView(attrView *av.AttributeView, viewID, query string, page, func (tx *Transaction) doUnbindAttrViewBlock(operation *Operation) (ret *TxErr) { err := unbindAttributeViewBlock(operation, tx) - if nil != err { + if err != nil { return &TxErr{code: TxErrWriteAttributeView, id: operation.AvID} } return @@ -981,7 +981,7 @@ func (tx *Transaction) doUnbindAttrViewBlock(operation *Operation) (ret *TxErr) func unbindAttributeViewBlock(operation *Operation, tx *Transaction) (err error) { attrView, err := av.ParseAttributeView(operation.AvID) - if nil != err { + if err != nil { return } @@ -1051,7 +1051,7 @@ func unbindAttributeViewBlock(operation *Operation, tx *Transaction) (err error) func (tx *Transaction) doSetAttrViewColDate(operation *Operation) (ret *TxErr) { err := setAttributeViewColDate(operation) - if nil != err { + if err != nil { return &TxErr{code: TxErrWriteAttributeView, id: operation.AvID, msg: err.Error()} } return @@ -1059,7 +1059,7 @@ func (tx *Transaction) doSetAttrViewColDate(operation *Operation) (ret *TxErr) { func setAttributeViewColDate(operation *Operation) (err error) { attrView, err := av.ParseAttributeView(operation.AvID) - if nil != err { + if err != nil { return } @@ -1081,7 +1081,7 @@ func setAttributeViewColDate(operation *Operation) (err error) { func (tx *Transaction) doHideAttrViewName(operation *Operation) (ret *TxErr) { err := hideAttrViewName(operation) - if nil != err { + if err != nil { return &TxErr{code: TxErrWriteAttributeView, id: operation.AvID, msg: err.Error()} } return @@ -1089,7 +1089,7 @@ func (tx *Transaction) doHideAttrViewName(operation *Operation) (ret *TxErr) { func hideAttrViewName(operation *Operation) (err error) { attrView, err := av.ParseAttributeView(operation.AvID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", operation.AvID, err) return } @@ -1107,7 +1107,7 @@ func hideAttrViewName(operation *Operation) (err error) { func (tx *Transaction) doUpdateAttrViewColRollup(operation *Operation) (ret *TxErr) { err := updateAttributeViewColRollup(operation) - if nil != err { + if err != nil { return &TxErr{code: TxErrWriteAttributeView, id: operation.AvID, msg: err.Error()} } return @@ -1121,7 +1121,7 @@ func updateAttributeViewColRollup(operation *Operation) (err error) { // operation.Data 计算方式 attrView, err := av.ParseAttributeView(operation.AvID) - if nil != err { + if err != nil { return } @@ -1156,7 +1156,7 @@ func updateAttributeViewColRollup(operation *Operation) (err error) { func (tx *Transaction) doUpdateAttrViewColRelation(operation *Operation) (ret *TxErr) { err := updateAttributeViewColRelation(operation) - if nil != err { + if err != nil { return &TxErr{code: TxErrWriteAttributeView, id: operation.AvID, msg: err.Error()} } return @@ -1172,12 +1172,12 @@ func updateAttributeViewColRelation(operation *Operation) (err error) { // operation.Format 源 av 关联列名称 srcAv, err := av.ParseAttributeView(operation.AvID) - if nil != err { + if err != nil { return } destAv, err := av.ParseAttributeView(operation.ID) - if nil != err { + if err != nil { return } @@ -1210,7 +1210,7 @@ func updateAttributeViewColRelation(operation *Operation) (err error) { if !isOldSameAv { err = av.SaveAttributeView(oldDestAv) - if nil != err { + if err != nil { return } } @@ -1308,7 +1308,7 @@ func updateAttributeViewColRelation(operation *Operation) (err error) { } err = av.SaveAttributeView(srcAv) - if nil != err { + if err != nil { return } if !isSameAv { @@ -1326,7 +1326,7 @@ func updateAttributeViewColRelation(operation *Operation) (err error) { func (tx *Transaction) doSortAttrViewView(operation *Operation) (ret *TxErr) { avID := operation.AvID attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", operation.AvID, err) return &TxErr{code: TxErrWriteAttributeView, id: operation.AvID, msg: err.Error()} } @@ -1363,7 +1363,7 @@ func (tx *Transaction) doSortAttrViewView(operation *Operation) (ret *TxErr) { } attrView.Views = util.InsertElem(attrView.Views, previousIndex, view) - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: avID} } @@ -1374,7 +1374,7 @@ func (tx *Transaction) doRemoveAttrViewView(operation *Operation) (ret *TxErr) { var err error avID := operation.AvID attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrCodeBlockNotFound, id: avID} } @@ -1404,7 +1404,7 @@ func (tx *Transaction) doRemoveAttrViewView(operation *Operation) (ret *TxErr) { } attrView.ViewID = attrView.Views[index].ID - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: avID} } @@ -1427,7 +1427,7 @@ func (tx *Transaction) doRemoveAttrViewView(operation *Operation) (ret *TxErr) { } for _, tree := range trees { - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } } @@ -1477,7 +1477,7 @@ func (tx *Transaction) doDuplicateAttrViewView(operation *Operation) (ret *TxErr var err error avID := operation.AvID attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, id: avID} } @@ -1497,7 +1497,7 @@ func (tx *Transaction) doDuplicateAttrViewView(operation *Operation) (ret *TxErr attrs := parse.IAL2Map(node.KramdownIAL) attrs[av.NodeAttrView] = operation.ID err = setNodeAttrs(node, tree, attrs) - if nil != err { + if err != nil { logging.LogWarnf("set node [%s] attrs failed: %s", operation.BlockID, err) return } @@ -1543,7 +1543,7 @@ func (tx *Transaction) doDuplicateAttrViewView(operation *Operation) (ret *TxErr view.Table.PageSize = masterView.Table.PageSize view.Table.RowIDs = masterView.Table.RowIDs - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, msg: err.Error(), id: avID} } @@ -1554,7 +1554,7 @@ func (tx *Transaction) doAddAttrViewView(operation *Operation) (ret *TxErr) { var err error avID := operation.AvID attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, id: avID} } @@ -1579,7 +1579,7 @@ func (tx *Transaction) doAddAttrViewView(operation *Operation) (ret *TxErr) { attrs := parse.IAL2Map(node.KramdownIAL) attrs[av.NodeAttrView] = operation.ID err = setNodeAttrs(node, tree, attrs) - if nil != err { + if err != nil { logging.LogWarnf("set node [%s] attrs failed: %s", operation.BlockID, err) return } @@ -1595,7 +1595,7 @@ func (tx *Transaction) doAddAttrViewView(operation *Operation) (ret *TxErr) { view.Table.RowIDs = firstView.Table.RowIDs - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, msg: err.Error(), id: avID} } @@ -1606,7 +1606,7 @@ func (tx *Transaction) doSetAttrViewViewName(operation *Operation) (ret *TxErr) var err error avID := operation.AvID attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, id: avID} } @@ -1619,7 +1619,7 @@ func (tx *Transaction) doSetAttrViewViewName(operation *Operation) (ret *TxErr) } view.Name = strings.TrimSpace(operation.Data.(string)) - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, msg: err.Error(), id: avID} } @@ -1630,7 +1630,7 @@ func (tx *Transaction) doSetAttrViewViewIcon(operation *Operation) (ret *TxErr) var err error avID := operation.AvID attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, id: avID} } @@ -1643,7 +1643,7 @@ func (tx *Transaction) doSetAttrViewViewIcon(operation *Operation) (ret *TxErr) } view.Icon = operation.Data.(string) - if err = av.SaveAttributeView(attrView); nil != err { + if err = av.SaveAttributeView(attrView); err != nil { logging.LogErrorf("save attribute view [%s] failed: %s", avID, err) return &TxErr{code: TxErrWriteAttributeView, msg: err.Error(), id: avID} } @@ -1652,7 +1652,7 @@ func (tx *Transaction) doSetAttrViewViewIcon(operation *Operation) (ret *TxErr) func (tx *Transaction) doSetAttrViewName(operation *Operation) (ret *TxErr) { err := setAttributeViewName(operation) - if nil != err { + if err != nil { return &TxErr{code: TxErrWriteAttributeView, id: operation.AvID, msg: err.Error()} } return @@ -1663,7 +1663,7 @@ const attrAvNameTpl = ` semver.Compare("v"+pluginConf.Version, "v"+plugin.Version) } } @@ -237,7 +237,7 @@ func InstalledPlugins(frontend, keyword string) (plugins []*bazaar.Plugin) { func InstallBazaarPlugin(repoURL, repoHash, pluginName string) error { installPath := filepath.Join(util.DataDir, "plugins", pluginName) err := bazaar.InstallPlugin(repoURL, repoHash, installPath, Conf.System.ID) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(46), pluginName, err)) } return nil @@ -246,7 +246,7 @@ func InstallBazaarPlugin(repoURL, repoHash, pluginName string) error { func UninstallBazaarPlugin(pluginName, frontend string) error { installPath := filepath.Join(util.DataDir, "plugins", pluginName) err := bazaar.UninstallPlugin(installPath) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(47), err.Error())) } @@ -271,7 +271,7 @@ func BazaarWidgets(keyword string) (widgets []*bazaar.Widget) { for _, widget := range widgets { widget.Installed = util.IsPathRegularDirOrSymlinkDir(filepath.Join(util.DataDir, "widgets", widget.Name)) if widget.Installed { - if widgetConf, err := bazaar.WidgetJSON(widget.Name); nil == err && nil != widget { + if widgetConf, err := bazaar.WidgetJSON(widget.Name); err == nil && nil != widget { widget.Outdated = 0 > semver.Compare("v"+widgetConf.Version, "v"+widget.Version) } } @@ -299,7 +299,7 @@ func InstalledWidgets(keyword string) (widgets []*bazaar.Widget) { func InstallBazaarWidget(repoURL, repoHash, widgetName string) error { installPath := filepath.Join(util.DataDir, "widgets", widgetName) err := bazaar.InstallWidget(repoURL, repoHash, installPath, Conf.System.ID) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(46), widgetName, err)) } return nil @@ -308,7 +308,7 @@ func InstallBazaarWidget(repoURL, repoHash, widgetName string) error { func UninstallBazaarWidget(widgetName string) error { installPath := filepath.Join(util.DataDir, "widgets", widgetName) err := bazaar.UninstallWidget(installPath) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(47), err.Error())) } return nil @@ -321,7 +321,7 @@ func BazaarIcons(keyword string) (icons []*bazaar.Icon) { for _, icon := range icons { if installed == icon.Name { icon.Installed = true - if iconConf, err := bazaar.IconJSON(icon.Name); nil == err { + if iconConf, err := bazaar.IconJSON(icon.Name); err == nil { icon.Outdated = 0 > semver.Compare("v"+iconConf.Version, "v"+icon.Version) } } @@ -354,7 +354,7 @@ func InstalledIcons(keyword string) (icons []*bazaar.Icon) { func InstallBazaarIcon(repoURL, repoHash, iconName string) error { installPath := filepath.Join(util.IconsPath, iconName) err := bazaar.InstallIcon(repoURL, repoHash, installPath, Conf.System.ID) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(46), iconName, err)) } Conf.Appearance.Icon = iconName @@ -366,7 +366,7 @@ func InstallBazaarIcon(repoURL, repoHash, iconName string) error { func UninstallBazaarIcon(iconName string) error { installPath := filepath.Join(util.IconsPath, iconName) err := bazaar.UninstallIcon(installPath) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(47), err.Error())) } @@ -383,7 +383,7 @@ func BazaarThemes(keyword string) (ret []*bazaar.Theme) { for _, theme := range ret { if installed == theme.Name { theme.Installed = true - if themeConf, err := bazaar.ThemeJSON(theme.Name); nil == err { + if themeConf, err := bazaar.ThemeJSON(theme.Name); err == nil { theme.Outdated = 0 > semver.Compare("v"+themeConf.Version, "v"+theme.Version) } theme.Current = theme.Name == Conf.Appearance.ThemeDark || theme.Name == Conf.Appearance.ThemeLight @@ -418,7 +418,7 @@ func InstallBazaarTheme(repoURL, repoHash, themeName string, mode int, update bo installPath := filepath.Join(util.ThemesPath, themeName) err := bazaar.InstallTheme(repoURL, repoHash, installPath, Conf.System.ID) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(46), themeName, err)) } @@ -443,7 +443,7 @@ func UninstallBazaarTheme(themeName string) error { installPath := filepath.Join(util.ThemesPath, themeName) err := bazaar.UninstallTheme(installPath) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(47), err.Error())) } @@ -457,7 +457,7 @@ func BazaarTemplates(keyword string) (templates []*bazaar.Template) { for _, template := range templates { template.Installed = util.IsPathRegularDirOrSymlinkDir(filepath.Join(util.DataDir, "templates", template.Name)) if template.Installed { - if templateConf, err := bazaar.TemplateJSON(template.Name); nil == err && nil != templateConf { + if templateConf, err := bazaar.TemplateJSON(template.Name); err == nil && nil != templateConf { template.Outdated = 0 > semver.Compare("v"+templateConf.Version, "v"+template.Version) } } @@ -485,7 +485,7 @@ func InstalledTemplates(keyword string) (templates []*bazaar.Template) { func InstallBazaarTemplate(repoURL, repoHash, templateName string) error { installPath := filepath.Join(util.DataDir, "templates", templateName) err := bazaar.InstallTemplate(repoURL, repoHash, installPath, Conf.System.ID) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(46), templateName, err)) } return nil @@ -494,7 +494,7 @@ func InstallBazaarTemplate(repoURL, repoHash, templateName string) error { func UninstallBazaarTemplate(templateName string) error { installPath := filepath.Join(util.DataDir, "templates", templateName) err := bazaar.UninstallTemplate(installPath) - if nil != err { + if err != nil { return errors.New(fmt.Sprintf(Conf.Language(47), err.Error())) } return nil diff --git a/kernel/model/block.go b/kernel/model/block.go index 3b4787ba4..a2f987ef0 100644 --- a/kernel/model/block.go +++ b/kernel/model/block.go @@ -177,7 +177,7 @@ func GetBlockTreeInfos(ids []string) (ret map[string]*BlockTreeInfo) { func GetBlockSiblingID(id string) (parent, previous, next string) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -341,7 +341,7 @@ func TransferBlockRef(fromID, toID string, refIDs []string) (err error) { } } - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } } @@ -352,7 +352,7 @@ func TransferBlockRef(fromID, toID string, refIDs []string) (err error) { func SwapBlockRef(refID, defID string, includeChildren bool) (err error) { refTree, err := LoadTreeByBlockID(refID) - if nil != err { + if err != nil { return } refNode := treenode.GetNodeInTree(refTree, refID) @@ -363,7 +363,7 @@ func SwapBlockRef(refID, defID string, includeChildren bool) (err error) { refNode = refNode.Parent } defTree, err := LoadTreeByBlockID(defID) - if nil != err { + if err != nil { return } sameTree := defTree.ID == refTree.ID @@ -453,11 +453,11 @@ func SwapBlockRef(refID, defID string, includeChildren bool) (err error) { } refPivot.Unlink() - if err = indexWriteTreeUpsertQueue(refTree); nil != err { + if err = indexWriteTreeUpsertQueue(refTree); err != nil { return } if !sameTree { - if err = indexWriteTreeUpsertQueue(defTree); nil != err { + if err = indexWriteTreeUpsertQueue(defTree); err != nil { return } } @@ -468,7 +468,7 @@ func SwapBlockRef(refID, defID string, includeChildren bool) (err error) { func GetHeadingDeleteTransaction(id string) (transaction *Transaction, err error) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -511,7 +511,7 @@ func GetHeadingDeleteTransaction(id string) (transaction *Transaction, err error func GetHeadingChildrenIDs(id string) (ret []string) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } heading := treenode.GetNodeInTree(tree, id) @@ -529,7 +529,7 @@ func GetHeadingChildrenIDs(id string) (ret []string) { func GetHeadingChildrenDOM(id string) (ret string) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } heading := treenode.GetNodeInTree(tree, id) @@ -547,7 +547,7 @@ func GetHeadingChildrenDOM(id string) (ret string) { func GetHeadingLevelTransaction(id string, level int) (transaction *Transaction, err error) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -606,7 +606,7 @@ func GetBlockDOM(id string) (ret string) { } tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } node := treenode.GetNodeInTree(tree, id) @@ -621,7 +621,7 @@ func GetBlockKramdown(id string) (ret string) { } tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -650,7 +650,7 @@ func GetChildBlocks(id string) (ret []*ChildBlock) { } tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -702,7 +702,7 @@ func GetTailChildBlocks(id string, n int) (ret []*ChildBlock) { } tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -767,10 +767,10 @@ func getBlock(id string, tree *parse.Tree) (ret *Block, err error) { if nil == tree { tree, err = LoadTreeByBlockID(id) - if nil != err { + if err != nil { time.Sleep(1 * time.Second) tree, err = LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } } diff --git a/kernel/model/blockial.go b/kernel/model/blockial.go index 7a76d54c2..a1a32b3bd 100644 --- a/kernel/model/blockial.go +++ b/kernel/model/blockial.go @@ -55,7 +55,7 @@ func SetBlockReminder(id string, timed string) (err error) { attrs := GetBlockAttrs(id) // 获取属性是会等待树写入 tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -70,7 +70,7 @@ func SetBlockReminder(id string, timed string) (err error) { content := sql.NodeStaticContent(node, nil, false, false, false, GetBlockAttrsWithoutWaitWriting) content = gulu.Str.SubStr(content, 128) err = SetCloudBlockReminder(id, content, timedMills) - if nil != err { + if err != nil { return } @@ -88,7 +88,7 @@ func SetBlockReminder(id string, timed string) (err error) { node.SetIALAttr(attrName, timed) util.PushMsg(fmt.Sprintf(Conf.Language(101), time.UnixMilli(timedMills).Format("2006-01-02 15:04")), 5000) } - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } IncSync() @@ -144,7 +144,7 @@ func BatchSetBlockAttrs(blockAttrs []map[string]interface{}) (err error) { } for _, tree := range trees { - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } } @@ -162,7 +162,7 @@ func SetBlockAttrs(id string, nameValues map[string]string) (err error) { WaitForWritingFiles() tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return err } @@ -177,11 +177,11 @@ func SetBlockAttrs(id string, nameValues map[string]string) (err error) { func setNodeAttrs(node *ast.Node, tree *parse.Tree, nameValues map[string]string) (err error) { oldAttrs, err := setNodeAttrs0(node, nameValues) - if nil != err { + if err != nil { return } - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } @@ -201,11 +201,11 @@ func setNodeAttrs(node *ast.Node, tree *parse.Tree, nameValues map[string]string func setNodeAttrsWithTx(tx *Transaction, node *ast.Node, tree *parse.Tree, nameValues map[string]string) (err error) { oldAttrs, err := setNodeAttrs0(node, nameValues) - if nil != err { + if err != nil { return } - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return } @@ -250,7 +250,7 @@ func pushBroadcastAttrTransactions(oldAttrs map[string]string, node *ast.Node) { func ResetBlockAttrs(id string, nameValues map[string]string) (err error) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return err } @@ -280,7 +280,7 @@ func ResetBlockAttrs(id string, nameValues map[string]string) (err error) { updateRefTextRenameDoc(tree) } - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } IncSync() @@ -335,7 +335,7 @@ func getBlockAttrs(id string) (ret map[string]string) { ret = map[string]string{} tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go index c0bee39fb..b1231844e 100644 --- a/kernel/model/blockinfo.go +++ b/kernel/model/blockinfo.go @@ -55,7 +55,7 @@ func GetDocInfo(blockID string) (ret *BlockInfo) { WaitForWritingFiles() tree, err := LoadTreeByBlockID(blockID) - if nil != err { + if err != nil { logging.LogErrorf("load tree by root id [%s] failed: %s", blockID, err) return } @@ -111,7 +111,7 @@ func GetDocInfo(blockID string) (ret *BlockInfo) { var subFileCount int boxLocalPath := filepath.Join(util.DataDir, tree.Box) subFiles, err := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy"))) - if nil == err { + if err == nil { for _, subFile := range subFiles { if strings.HasSuffix(subFile.Name(), ".sy") { subFileCount++ @@ -130,7 +130,7 @@ func GetBlockRefText(id string) string { } tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return "" } diff --git a/kernel/model/bookmark.go b/kernel/model/bookmark.go index b1c7142f1..17b10c751 100644 --- a/kernel/model/bookmark.go +++ b/kernel/model/bookmark.go @@ -66,7 +66,7 @@ func RemoveBookmark(bookmark string) (err error) { } util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title")))) - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { util.ClearPushProgress(100) return } @@ -124,7 +124,7 @@ func RenameBookmark(oldBookmark, newBookmark string) (err error) { } util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title")))) - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { util.ClearPushProgress(100) return } @@ -180,7 +180,7 @@ func BuildBookmark() (ret *Bookmarks) { } else { // Improve bookmark panel rendering https://github.com/siyuan-note/siyuan/issues/9361 tree, err := LoadTreeByBlockID(block.ID) - if nil != err { + if err != nil { logging.LogErrorf("parse block [%s] failed: %s", block.ID, err) } else { n := treenode.GetNodeInTree(tree, block.ID) diff --git a/kernel/model/box.go b/kernel/model/box.go index 69600fd5f..1c0b4fa1f 100644 --- a/kernel/model/box.go +++ b/kernel/model/box.go @@ -89,7 +89,7 @@ func StatJob() { func ListNotebooks() (ret []*Box, err error) { ret = []*Box{} dirs, err := os.ReadDir(util.DataDir) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", util.DataDir, err) return ret, err } @@ -185,12 +185,12 @@ func (box *Box) GetConf() (ret *conf.BoxConf) { } data, err := filelock.ReadFile(confPath) - if nil != err { + if err != nil { logging.LogErrorf("read box conf [%s] failed: %s", confPath, err) return } - if err = gulu.JSON.UnmarshalJSON(data, ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil { logging.LogErrorf("parse box conf [%s] failed: %s", confPath, err) return } @@ -200,13 +200,13 @@ func (box *Box) GetConf() (ret *conf.BoxConf) { func (box *Box) SaveConf(conf *conf.BoxConf) { confPath := filepath.Join(util.DataDir, box.ID, ".siyuan/conf.json") newData, err := gulu.JSON.MarshalIndentJSON(conf, "", " ") - if nil != err { + if err != nil { logging.LogErrorf("marshal box conf [%s] failed: %s", confPath, err) return } oldData, err := filelock.ReadFile(confPath) - if nil != err { + if err != nil { box.saveConf0(newData) return } @@ -220,10 +220,10 @@ func (box *Box) SaveConf(conf *conf.BoxConf) { func (box *Box) saveConf0(data []byte) { confPath := filepath.Join(util.DataDir, box.ID, ".siyuan/conf.json") - if err := os.MkdirAll(filepath.Join(util.DataDir, box.ID, ".siyuan"), 0755); nil != err { + if err := os.MkdirAll(filepath.Join(util.DataDir, box.ID, ".siyuan"), 0755); err != nil { logging.LogErrorf("save box conf [%s] failed: %s", confPath, err) } - if err := filelock.WriteFile(confPath, data); nil != err { + if err := filelock.WriteFile(confPath, data); err != nil { logging.LogErrorf("write box conf [%s] failed: %s", confPath, err) util.ReportFileSysFatalError(err) return @@ -243,7 +243,7 @@ func (box *Box) Ls(p string) (ret []*FileInfo, totals int, err error) { } entries, err := os.ReadDir(filepath.Join(util.DataDir, box.ID, p)) - if nil != err { + if err != nil { return } @@ -287,7 +287,7 @@ func (box *Box) Ls(p string) (ret []*FileInfo, totals int, err error) { func (box *Box) Stat(p string) (ret *FileInfo) { absPath := filepath.Join(util.DataDir, box.ID, p) info, err := os.Stat(absPath) - if nil != err { + if err != nil { if !os.IsNotExist(err) { logging.LogErrorf("stat [%s] failed: %s", absPath, err) } @@ -307,7 +307,7 @@ func (box *Box) Exist(p string) bool { } func (box *Box) Mkdir(path string) error { - if err := os.Mkdir(filepath.Join(util.DataDir, box.ID, path), 0755); nil != err { + if err := os.Mkdir(filepath.Join(util.DataDir, box.ID, path), 0755); err != nil { msg := fmt.Sprintf(Conf.Language(6), box.Name, path, err) logging.LogErrorf("mkdir [path=%s] in box [%s] failed: %s", path, box.ID, err) return errors.New(msg) @@ -317,7 +317,7 @@ func (box *Box) Mkdir(path string) error { } func (box *Box) MkdirAll(path string) error { - if err := os.MkdirAll(filepath.Join(util.DataDir, box.ID, path), 0755); nil != err { + if err := os.MkdirAll(filepath.Join(util.DataDir, box.ID, path), 0755); err != nil { msg := fmt.Sprintf(Conf.Language(6), box.Name, path, err) logging.LogErrorf("mkdir all [path=%s] in box [%s] failed: %s", path, box.ID, err) return errors.New(msg) @@ -331,7 +331,7 @@ func (box *Box) Move(oldPath, newPath string) error { fromPath := filepath.Join(boxLocalPath, oldPath) toPath := filepath.Join(boxLocalPath, newPath) - if err := filelock.Rename(fromPath, toPath); nil != err { + if err := filelock.Rename(fromPath, toPath); err != nil { msg := fmt.Sprintf(Conf.Language(5), box.Name, fromPath, err) logging.LogErrorf("move [path=%s] in box [%s] failed: %s", fromPath, box.Name, err) return errors.New(msg) @@ -350,7 +350,7 @@ func (box *Box) Move(oldPath, newPath string) error { func (box *Box) Remove(path string) error { boxLocalPath := filepath.Join(util.DataDir, box.ID) filePath := filepath.Join(boxLocalPath, path) - if err := filelock.Remove(filePath); nil != err { + if err := filelock.Remove(filePath); err != nil { msg := fmt.Sprintf(Conf.Language(7), box.Name, path, err) logging.LogErrorf("remove [path=%s] in box [%s] failed: %s", path, box.ID, err) return errors.New(msg) @@ -361,7 +361,7 @@ func (box *Box) Remove(path string) error { func (box *Box) ListFiles(path string) (ret []*FileInfo) { fis, _, err := box.Ls(path) - if nil != err { + if err != nil { return } box.listFiles(&fis, &ret) @@ -372,7 +372,7 @@ func (box *Box) listFiles(files, ret *[]*FileInfo) { for _, file := range *files { if file.isdir { fis, _, err := box.Ls(file.path) - if nil == err { + if err == nil { box.listFiles(&fis, ret) } *ret = append(*ret, file) @@ -412,7 +412,7 @@ func (box *Box) renameSubTrees(tree *parse.Tree) { } subTree, err := filesys.LoadTree(box.ID, subFile.path, luteEngine) // LoadTree 会重新构造 HPath - if nil != err { + if err != nil { continue } @@ -521,7 +521,7 @@ func fullReindex() { WaitForWritingFiles() - if err := sql.InitDatabase(true); nil != err { + if err := sql.InitDatabase(true); err != nil { os.Exit(logging.ExitCodeReadOnlyDatabase) return } diff --git a/kernel/model/cloud_service.go b/kernel/model/cloud_service.go index e0c66cc39..da7bae761 100644 --- a/kernel/model/cloud_service.go +++ b/kernel/model/cloud_service.go @@ -64,7 +64,7 @@ func CloudChatGPT(msg string, contextMsgs []string) (ret string, stop bool, err SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). SetBody(payload). Post(util.GetCloudServer() + "/apis/siyuan/ai/chatGPT") - if nil != err { + if err != nil { logging.LogErrorf("chat gpt failed: %s", err) err = ErrFailedToConnectCloudServer return @@ -109,7 +109,7 @@ func StartFreeTrial() (err error) { SetSuccessResult(requestResult). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/user/startFreeTrial") - if nil != err { + if err != nil { logging.LogErrorf("start free trial failed: %s", err) return ErrFailedToConnectCloudServer } @@ -130,7 +130,7 @@ func DeactivateUser() (err error) { SetSuccessResult(requestResult). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/user/deactivate") - if nil != err { + if err != nil { logging.LogErrorf("deactivate user failed: %s", err) return ErrFailedToConnectCloudServer } @@ -156,7 +156,7 @@ func SetCloudBlockReminder(id, data string, timed int64) (err error) { SetBody(payload). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/calendar/setBlockReminder") - if nil != err { + if err != nil { logging.LogErrorf("set block reminder failed: %s", err) return ErrFailedToConnectCloudServer } @@ -188,7 +188,7 @@ func LoadUploadToken() (err error) { SetSuccessResult(requestResult). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/upload/token") - if nil != err { + if err != nil { logging.LogErrorf("get upload token failed: %s", err) return ErrFailedToConnectCloudServer } @@ -288,11 +288,11 @@ func refreshAnnouncement() { var existingAnnouncements, newAnnouncements []*Announcement if gulu.File.IsExist(announcementConf) { data, err := os.ReadFile(announcementConf) - if nil != err { + if err != nil { logging.LogErrorf("read announcement conf failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &existingAnnouncements); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &existingAnnouncements); err != nil { logging.LogErrorf("unmarshal announcement conf failed: %s", err) os.Remove(announcementConf) return @@ -316,11 +316,11 @@ func refreshAnnouncement() { } data, err := gulu.JSON.MarshalJSON(existingAnnouncements) - if nil != err { + if err != nil { logging.LogErrorf("marshal announcement conf failed: %s", err) return } - if err = os.WriteFile(announcementConf, data, 0644); nil != err { + if err = os.WriteFile(announcementConf, data, 0644); err != nil { logging.LogErrorf("write announcement conf failed: %s", err) return } @@ -342,7 +342,7 @@ func RefreshUser(token string) { var tokenExpireTime int64 tokenExpireTime, err := strconv.ParseInt(Conf.GetUser().UserTokenExpireTime+"000", 10, 64) - if nil != err { + if err != nil { logging.LogErrorf("convert token expire time [%s] failed: %s", Conf.GetUser().UserTokenExpireTime, err) util.PushErrMsg(Conf.Language(19), 5000) return @@ -366,7 +366,7 @@ Net: var tokenExpireTime int64 tokenExpireTime, err = strconv.ParseInt(Conf.GetUser().UserTokenExpireTime+"000", 10, 64) - if nil != err { + if err != nil { logging.LogErrorf("convert token expire time [%s] failed: %s", Conf.GetUser().UserTokenExpireTime, err) util.PushErrMsg(Conf.Language(19), 5000) return @@ -398,7 +398,7 @@ func loadUserFromConf() *conf.User { data := util.AESDecrypt(Conf.UserData) data, _ = hex.DecodeString(string(data)) user := &conf.User{} - if err := gulu.JSON.UnmarshalJSON(data, &user); nil == err { + if err := gulu.JSON.UnmarshalJSON(data, &user); err == nil { return user } return nil @@ -415,7 +415,7 @@ func RemoveCloudShorthands(ids []string) (err error) { SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). SetBody(body). Post(util.GetCloudServer() + "/apis/siyuan/inbox/removeCloudShorthands") - if nil != err { + if err != nil { logging.LogErrorf("remove cloud shorthands failed: %s", err) err = ErrFailedToConnectCloudServer return @@ -442,7 +442,7 @@ func GetCloudShorthand(id string) (ret map[string]interface{}, err error) { SetSuccessResult(&result). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/inbox/getCloudShorthand?id=" + id) - if nil != err { + if err != nil { logging.LogErrorf("get cloud shorthand failed: %s", err) err = ErrFailedToConnectCloudServer return @@ -482,7 +482,7 @@ func GetCloudShorthands(page int) (result map[string]interface{}, err error) { SetSuccessResult(&result). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/inbox/getCloudShorthands?p=" + strconv.Itoa(page)) - if nil != err { + if err != nil { logging.LogErrorf("get cloud shorthands failed: %s", err) err = ErrFailedToConnectCloudServer return @@ -538,7 +538,7 @@ func getUser(token string) (*conf.User, error) { SetSuccessResult(&result). SetBody(map[string]string{"token": token}). Post(util.GetCloudServer() + "/apis/siyuan/user") - if nil != err { + if err != nil { logging.LogErrorf("get community user failed: %s", err) return nil, errors.New(Conf.Language(18)) } @@ -559,7 +559,7 @@ func getUser(token string) (*conf.User, error) { dataStr := result["data"].(string) data := util.AESDecrypt(dataStr) user := &conf.User{} - if err = gulu.JSON.UnmarshalJSON(data, &user); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &user); err != nil { logging.LogErrorf("get community user failed: %s", err) return nil, errors.New(Conf.Language(18)) } @@ -576,7 +576,7 @@ func UseActivationcode(code string) (err error) { SetBody(map[string]string{"data": code}). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/useActivationcode") - if nil != err { + if err != nil { logging.LogErrorf("check activation code failed: %s", err) return ErrFailedToConnectCloudServer } @@ -601,7 +601,7 @@ func CheckActivationcode(code string) (retCode int, msg string) { SetBody(map[string]string{"data": code}). SetCookies(&http.Cookie{Name: "symphony", Value: Conf.GetUser().UserToken}). Post(util.GetCloudServer() + "/apis/siyuan/checkActivationcode") - if nil != err { + if err != nil { logging.LogErrorf("check activation code failed: %s", err) msg = ErrFailedToConnectCloudServer.Error() return @@ -629,7 +629,7 @@ func Login(userName, password, captcha string, cloudRegion int) (ret *gulu.Resul SetSuccessResult(&result). SetBody(map[string]string{"userName": userName, "userPassword": password, "captcha": captcha}). Post(util.GetCloudServer() + "/apis/siyuan/login") - if nil != err { + if err != nil { logging.LogErrorf("login failed: %s", err) ret = gulu.Ret.NewResult() ret.Code = -1 @@ -667,7 +667,7 @@ func Login2fa(token, code string) (map[string]interface{}, error) { SetBody(map[string]string{"twofactorAuthCode": code}). SetHeader("token", token). Post(util.GetCloudServer() + "/apis/siyuan/login/2fa") - if nil != err { + if err != nil { logging.LogErrorf("login 2fa failed: %s", err) return nil, errors.New(Conf.Language(18)) } diff --git a/kernel/model/conf.go b/kernel/model/conf.go index bc6286db2..fe3eee0e4 100644 --- a/kernel/model/conf.go +++ b/kernel/model/conf.go @@ -116,7 +116,7 @@ func InitConf() { Conf = &AppConf{LogLevel: "debug", m: &sync.Mutex{}} confPath := filepath.Join(util.ConfDir, "conf.json") if gulu.File.IsExist(confPath) { - if data, err := os.ReadFile(confPath); nil != err { + if data, err := os.ReadFile(confPath); err != nil { logging.LogErrorf("load conf [%s] failed: %s", confPath, err) } else { if err = gulu.JSON.UnmarshalJSON(data, Conf); err != nil { @@ -146,10 +146,10 @@ func InitConf() { if "" == Conf.Lang { // 未指定外观语言时使用系统语言 - if userLang, err := locale.Detect(); nil == err { + if userLang, err := locale.Detect(); err == nil { var supportLangs []language.Tag for lang := range util.Langs { - if tag, err := language.Parse(lang); nil == err { + if tag, err := language.Parse(lang); err == nil { supportLangs = append(supportLangs, tag) } else { logging.LogErrorf("load language [%s] failed: %s", lang, err) @@ -367,7 +367,7 @@ func InitConf() { } if timingEnv := os.Getenv("SIYUAN_SYNC_INDEX_TIMING"); "" != timingEnv { val, err := strconv.Atoi(timingEnv) - if nil == err { + if err == nil { Conf.Repo.SyncIndexTiming = int64(val) } } @@ -504,7 +504,7 @@ func InitConf() { func initLang() { p := filepath.Join(util.WorkingDir, "appearance", "langs") dir, err := os.Open(p) - if nil != err { + if err != nil { logging.LogErrorf("open language configuration folder [%s] failed: %s", p, err) util.ReportFileSysFatalError(err) return @@ -512,7 +512,7 @@ func initLang() { defer dir.Close() langNames, err := dir.Readdirnames(-1) - if nil != err { + if err != nil { logging.LogErrorf("list language configuration folder [%s] failed: %s", p, err) util.ReportFileSysFatalError(err) return @@ -521,12 +521,12 @@ func initLang() { for _, langName := range langNames { jsonPath := filepath.Join(p, langName) data, err := os.ReadFile(jsonPath) - if nil != err { + if err != nil { logging.LogErrorf("read language configuration [%s] failed: %s", jsonPath, err) continue } langMap := map[string]interface{}{} - if err := gulu.JSON.UnmarshalJSON(data, &langMap); nil != err { + if err := gulu.JSON.UnmarshalJSON(data, &langMap); err != nil { logging.LogErrorf("parse language configuration failed [%s] failed: %s", jsonPath, err) continue } @@ -639,7 +639,7 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int) { // 将当前工作空间放到工作空间列表的最后一个 // Open the last workspace by default https://github.com/siyuan-note/siyuan/issues/10570 workspacePaths, err := util.ReadWorkspacePaths() - if nil != err { + if err != nil { logging.LogErrorf("read workspace paths failed: %s", err) } else { workspacePaths = gulu.Str.RemoveElem(workspacePaths, util.WorkspaceDir) @@ -697,7 +697,7 @@ func (conf *AppConf) Save() { newData, _ := gulu.JSON.MarshalIndentJSON(Conf, "", " ") confPath := filepath.Join(util.ConfDir, "conf.json") oldData, err := filelock.ReadFile(confPath) - if nil != err { + if err != nil { conf.save0(newData) return } @@ -711,7 +711,7 @@ func (conf *AppConf) Save() { func (conf *AppConf) save0(data []byte) { confPath := filepath.Join(util.ConfDir, "conf.json") - if err := filelock.WriteFile(confPath, data); nil != err { + if err := filelock.WriteFile(confPath, data); err != nil { logging.LogErrorf("write conf [%s] failed: %s", confPath, err) util.ReportFileSysFatalError(err) return @@ -758,7 +758,7 @@ func (conf *AppConf) BoxNames(boxIDs []string) (ret map[string]string) { func (conf *AppConf) GetBoxes() (ret []*Box) { ret = []*Box{} notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } @@ -775,7 +775,7 @@ func (conf *AppConf) GetBoxes() (ret []*Box) { func (conf *AppConf) GetOpenedBoxes() (ret []*Box) { ret = []*Box{} notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } @@ -790,7 +790,7 @@ func (conf *AppConf) GetOpenedBoxes() (ret []*Box) { func (conf *AppConf) GetClosedBoxes() (ret []*Box) { ret = []*Box{} notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } @@ -829,7 +829,7 @@ func InitBoxes() { } var dbSize string - if dbFile, err := os.Stat(util.DBPath); nil == err { + if dbFile, err := os.Stat(util.DBPath); err == nil { dbSize = humanize.BytesCustomCeil(uint64(dbFile.Size()), 2) } logging.LogInfof("database size [%s], tree/block count [%d/%d]", dbSize, treenode.CountTrees(), treenode.CountBlocks()) @@ -862,12 +862,12 @@ const ( func GetMaskedConf() (ret *AppConf, err error) { // 脱敏处理 data, err := gulu.JSON.MarshalIndentJSON(Conf, "", " ") - if nil != err { + if err != nil { logging.LogErrorf("marshal conf failed: %s", err) return } ret = &AppConf{} - if err = gulu.JSON.UnmarshalJSON(data, ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil { logging.LogErrorf("unmarshal conf failed: %s", err) return } @@ -906,20 +906,20 @@ func clearPortJSON() { if gulu.File.IsExist(portJSON) { data, err = os.ReadFile(portJSON) - if nil != err { + if err != nil { logging.LogWarnf("read port.json failed: %s", err) } else { - if err = gulu.JSON.UnmarshalJSON(data, &pidPorts); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &pidPorts); err != nil { logging.LogWarnf("unmarshal port.json failed: %s", err) } } } delete(pidPorts, pid) - if data, err = gulu.JSON.MarshalIndentJSON(pidPorts, "", " "); nil != err { + if data, err = gulu.JSON.MarshalIndentJSON(pidPorts, "", " "); err != nil { logging.LogWarnf("marshal port.json failed: %s", err) } else { - if err = os.WriteFile(portJSON, data, 0644); nil != err { + if err = os.WriteFile(portJSON, data, 0644); err != nil { logging.LogWarnf("write port.json failed: %s", err) } } @@ -929,7 +929,7 @@ func clearCorruptedNotebooks() { // 数据同步时展开文档树操作可能导致数据丢失 https://github.com/siyuan-note/siyuan/issues/7129 dirs, err := os.ReadDir(util.DataDir) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", util.DataDir, err) return } @@ -970,13 +970,13 @@ func clearWorkspaceTemp() { if gulu.File.IsDir(install) { monthAgo := time.Now().Add(-time.Hour * 24 * 7) entries, err := os.ReadDir(install) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", install, err) } else { for _, entry := range entries { info, _ := entry.Info() if nil != info && !info.IsDir() && info.ModTime().Before(monthAgo) { - if err = os.RemoveAll(filepath.Join(install, entry.Name())); nil != err { + if err = os.RemoveAll(filepath.Join(install, entry.Name())); err != nil { logging.LogErrorf("remove old install pkg [%s] failed: %s", filepath.Join(install, entry.Name()), err) } } @@ -985,11 +985,11 @@ func clearWorkspaceTemp() { } tmps, err := filepath.Glob(filepath.Join(util.TempDir, "*.tmp")) - if nil != err { + if err != nil { logging.LogErrorf("glob temp files failed: %s", err) } for _, tmp := range tmps { - if err = os.RemoveAll(tmp); nil != err { + if err = os.RemoveAll(tmp); err != nil { logging.LogErrorf("remove temp file [%s] failed: %s", tmp, err) } else { logging.LogInfof("removed temp file [%s]", tmp) @@ -997,11 +997,11 @@ func clearWorkspaceTemp() { } tmps, err = filepath.Glob(filepath.Join(util.DataDir, ".siyuan", "*.tmp")) - if nil != err { + if err != nil { logging.LogErrorf("glob temp files failed: %s", err) } for _, tmp := range tmps { - if err = os.RemoveAll(tmp); nil != err { + if err = os.RemoveAll(tmp); err != nil { logging.LogErrorf("remove temp file [%s] failed: %s", tmp, err) } else { logging.LogInfof("removed temp file [%s]", tmp) @@ -1022,7 +1022,7 @@ func closeUserGuide() { defer logging.Recover() dirs, err := os.ReadDir(util.DataDir) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", util.DataDir, err) return } diff --git a/kernel/model/emojis_watcher.go b/kernel/model/emojis_watcher.go index b7d856370..9eda8c42c 100644 --- a/kernel/model/emojis_watcher.go +++ b/kernel/model/emojis_watcher.go @@ -48,7 +48,7 @@ func watchEmojis() { } var err error - if emojisWatcher, err = fsnotify.NewWatcher(); nil != err { + if emojisWatcher, err = fsnotify.NewWatcher(); err != nil { logging.LogErrorf("add emojis watcher for folder [%s] failed: %s", emojisDir, err) return } diff --git a/kernel/model/emojis_watcher_darwin.go b/kernel/model/emojis_watcher_darwin.go index 1f64bec3e..652b3c917 100644 --- a/kernel/model/emojis_watcher_darwin.go +++ b/kernel/model/emojis_watcher_darwin.go @@ -62,13 +62,13 @@ func watchEmojis() { } }() - if err := emojisWatcher.Add(emojisDir); nil != err { + if err := emojisWatcher.Add(emojisDir); err != nil { logging.LogErrorf("add emojis watcher for folder [%s] failed: %s", emojisDir, err) return } //logging.LogInfof("added file watcher [%s]", emojisDir) - if err := emojisWatcher.Start(10 * time.Second); nil != err { + if err := emojisWatcher.Start(10 * time.Second); err != nil { logging.LogErrorf("start emojis watcher for folder [%s] failed: %s", emojisDir, err) return } diff --git a/kernel/model/export.go b/kernel/model/export.go index a97050f3a..deeb440da 100644 --- a/kernel/model/export.go +++ b/kernel/model/export.go @@ -61,7 +61,7 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) { // Database block supports export as CSV https://github.com/siyuan-note/siyuan/issues/10072 attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { return } @@ -71,7 +71,7 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) { } viewID := node.IALAttr(av.NodeAttrView) view, err := attrView.GetCurrentView(viewID) - if nil != err { + if err != nil { return } @@ -83,19 +83,19 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) { table.SortRows(attrView) exportFolder := filepath.Join(util.TempDir, "export", "csv", name) - if err = os.MkdirAll(exportFolder, 0755); nil != err { + if err = os.MkdirAll(exportFolder, 0755); err != nil { logging.LogErrorf("mkdir [%s] failed: %s", exportFolder, err) return } csvPath := filepath.Join(exportFolder, name+".csv") f, err := os.OpenFile(csvPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) - if nil != err { + if err != nil { logging.LogErrorf("open [%s] failed: %s", csvPath, err) return } - if _, err = f.WriteString("\xEF\xBB\xBF"); nil != err { // 写入 UTF-8 BOM,避免使用 Microsoft Excel 打开乱码 + if _, err = f.WriteString("\xEF\xBB\xBF"); err != nil { // 写入 UTF-8 BOM,避免使用 Microsoft Excel 打开乱码 logging.LogErrorf("write UTF-8 BOM to [%s] failed: %s", csvPath, err) f.Close() return @@ -106,7 +106,7 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) { for _, col := range table.Columns { header = append(header, col.Name) } - if err = writer.Write(header); nil != err { + if err = writer.Write(header); err != nil { logging.LogErrorf("write csv header [%s] failed: %s", header, err) f.Close() return @@ -164,7 +164,7 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) { rowVal = append(rowVal, val) } - if err = writer.Write(rowVal); nil != err { + if err = writer.Write(rowVal); err != nil { logging.LogErrorf("write csv row [%s] failed: %s", rowVal, err) f.Close() return @@ -175,19 +175,19 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) { zipPath = exportFolder + ".db.zip" zip, err := gulu.Zip.Create(zipPath) - if nil != err { + if err != nil { logging.LogErrorf("create export .db.zip [%s] failed: %s", exportFolder, err) f.Close() return } - if err = zip.AddDirectory("", exportFolder); nil != err { + if err = zip.AddDirectory("", exportFolder); err != nil { logging.LogErrorf("create export .db.zip [%s] failed: %s", exportFolder, err) f.Close() return } - if err = zip.Close(); nil != err { + if err = zip.Close(); err != nil { logging.LogErrorf("close export .db.zip failed: %s", err) f.Close() return @@ -204,7 +204,7 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) { func Export2Liandi(id string) (err error) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree by block id [%s] failed: %s", id, err) return } @@ -221,7 +221,7 @@ func Export2Liandi(id string) (err error) { assets = append(assets, avAssets...) assets = gulu.Str.RemoveDuplicatedElem(assets) _, err = uploadAssets2Cloud(assets, bizTypeExport2Liandi) - if nil != err { + if err != nil { return } @@ -309,7 +309,7 @@ func Export2Liandi(id string) (err error) { articleId = result.Data.(string) tree, _ = LoadTreeByBlockID(id) // 这里必须重新加载,因为前面导出时已经修改了树结构 tree.Root.SetIALAttr(liandiArticleIdAttrName, articleId) - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { return } } @@ -322,7 +322,7 @@ func Export2Liandi(id string) (err error) { func ExportSystemLog() (zipPath string) { exportFolder := filepath.Join(util.TempDir, "export", "system-log") os.RemoveAll(exportFolder) - if err := os.MkdirAll(exportFolder, 0755); nil != err { + if err := os.MkdirAll(exportFolder, 0755); err != nil { logging.LogErrorf("create export temp folder failed: %s", err) return } @@ -330,7 +330,7 @@ func ExportSystemLog() (zipPath string) { appLog := filepath.Join(util.HomeDir, ".config", "siyuan", "app.log") if gulu.File.IsExist(appLog) { to := filepath.Join(exportFolder, "app.log") - if err := filelock.Copy(appLog, to); nil != err { + if err := filelock.Copy(appLog, to); err != nil { logging.LogErrorf("copy app log from [%s] to [%s] failed: %s", err, appLog, to) } } @@ -338,7 +338,7 @@ func ExportSystemLog() (zipPath string) { kernelLog := filepath.Join(util.HomeDir, ".config", "siyuan", "kernel.log") if gulu.File.IsExist(kernelLog) { to := filepath.Join(exportFolder, "kernel.log") - if err := filelock.Copy(kernelLog, to); nil != err { + if err := filelock.Copy(kernelLog, to); err != nil { logging.LogErrorf("copy kernel log from [%s] to [%s] failed: %s", err, kernelLog, to) } } @@ -346,7 +346,7 @@ func ExportSystemLog() (zipPath string) { siyuanLog := filepath.Join(util.TempDir, "siyuan.log") if gulu.File.IsExist(siyuanLog) { to := filepath.Join(exportFolder, "siyuan.log") - if err := filelock.Copy(siyuanLog, to); nil != err { + if err := filelock.Copy(siyuanLog, to); err != nil { logging.LogErrorf("copy kernel log from [%s] to [%s] failed: %s", err, siyuanLog, to) } } @@ -354,24 +354,24 @@ func ExportSystemLog() (zipPath string) { mobileLog := filepath.Join(util.TempDir, "mobile.log") if gulu.File.IsExist(mobileLog) { to := filepath.Join(exportFolder, "mobile.log") - if err := filelock.Copy(mobileLog, to); nil != err { + if err := filelock.Copy(mobileLog, to); err != nil { logging.LogErrorf("copy mobile log from [%s] to [%s] failed: %s", err, mobileLog, to) } } zipPath = exportFolder + ".zip" zip, err := gulu.Zip.Create(zipPath) - if nil != err { + if err != nil { logging.LogErrorf("create export log zip [%s] failed: %s", exportFolder, err) return "" } - if err = zip.AddDirectory("log", exportFolder); nil != err { + if err = zip.AddDirectory("log", exportFolder); err != nil { logging.LogErrorf("create export log zip [%s] failed: %s", exportFolder, err) return "" } - if err = zip.Close(); nil != err { + if err = zip.Close(); err != nil { logging.LogErrorf("close export log zip failed: %s", err) } @@ -414,12 +414,12 @@ func ExportDataInFolder(exportFolder string) (name string, err error) { defer util.ClearPushProgress(100) zipPath, err := ExportData() - if nil != err { + if err != nil { return } name = filepath.Base(zipPath) name, err = url.PathUnescape(name) - if nil != err { + if err != nil { logging.LogErrorf("url unescape [%s] failed: %s", name, err) return } @@ -427,7 +427,7 @@ func ExportDataInFolder(exportFolder string) (name string, err error) { targetZipPath := filepath.Join(exportFolder, name) zipAbsPath := filepath.Join(util.TempDir, "export", name) err = filelock.Copy(zipAbsPath, targetZipPath) - if nil != err { + if err != nil { logging.LogErrorf("copy export zip from [%s] to [%s] failed: %s", zipAbsPath, targetZipPath, err) return } @@ -444,7 +444,7 @@ func ExportData() (zipPath string, err error) { name := util.FilterFileName(filepath.Base(util.WorkspaceDir)) + "-" + util.CurrentTimeSecondsStr() exportFolder := filepath.Join(util.TempDir, "export", name) zipPath, err = exportData(exportFolder) - if nil != err { + if err != nil { return } zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath)) @@ -455,13 +455,13 @@ func exportData(exportFolder string) (zipPath string, err error) { WaitForWritingFiles() baseFolderName := "data-" + util.CurrentTimeSecondsStr() - if err = os.MkdirAll(exportFolder, 0755); nil != err { + if err = os.MkdirAll(exportFolder, 0755); err != nil { logging.LogErrorf("create export temp folder failed: %s", err) return } data := filepath.Join(util.WorkspaceDir, "data") - if err = filelock.Copy(data, exportFolder); nil != err { + if err = filelock.Copy(data, exportFolder); err != nil { logging.LogErrorf("copy data dir from [%s] to [%s] failed: %s", data, baseFolderName, err) err = errors.New(fmt.Sprintf(Conf.Language(14), err.Error())) return @@ -469,7 +469,7 @@ func exportData(exportFolder string) (zipPath string, err error) { zipPath = exportFolder + ".zip" zip, err := gulu.Zip.Create(zipPath) - if nil != err { + if err != nil { logging.LogErrorf("create export data zip [%s] failed: %s", exportFolder, err) return } @@ -479,12 +479,12 @@ func exportData(exportFolder string) (zipPath string, err error) { util.PushEndlessProgress(msg) } - if err = zip.AddDirectory(baseFolderName, exportFolder, zipCallback); nil != err { + if err = zip.AddDirectory(baseFolderName, exportFolder, zipCallback); err != nil { logging.LogErrorf("create export data zip [%s] failed: %s", exportFolder, err) return } - if err = zip.Close(); nil != err { + if err = zip.Close(); err != nil { logging.LogErrorf("close export data zip failed: %s", err) } @@ -497,7 +497,7 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st // 用于导出的临时文件夹完整路径 exportFolderPath := filepath.Join(util.TempDir, "export", mainName) - if err = os.MkdirAll(exportFolderPath, 0755); nil != err { + if err = os.MkdirAll(exportFolderPath, 0755); err != nil { logging.LogErrorf("create export temp folder failed: %s", err) return } @@ -507,7 +507,7 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st resourceFullPath := filepath.Join(util.WorkspaceDir, resourcePath) // 资源完整路径 resourceBaseName := filepath.Base(resourceFullPath) // 资源名称 resourceCopyPath := filepath.Join(exportFolderPath, resourceBaseName) // 资源副本完整路径 - if err = filelock.Copy(resourceFullPath, resourceCopyPath); nil != err { + if err = filelock.Copy(resourceFullPath, resourceCopyPath); err != nil { logging.LogErrorf("copy resource will be exported from [%s] to [%s] failed: %s", resourcePath, resourceCopyPath, err) err = fmt.Errorf(Conf.Language(14), err.Error()) return @@ -516,17 +516,17 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st zipFilePath := exportFolderPath + ".zip" // 导出的 *.zip 文件完整路径 zip, err := gulu.Zip.Create(zipFilePath) - if nil != err { + if err != nil { logging.LogErrorf("create export zip [%s] failed: %s", zipFilePath, err) return } - if err = zip.AddDirectory(mainName, exportFolderPath); nil != err { + if err = zip.AddDirectory(mainName, exportFolderPath); err != nil { logging.LogErrorf("create export zip [%s] failed: %s", exportFolderPath, err) return } - if err = zip.Close(); nil != err { + if err = zip.Close(); err != nil { logging.LogErrorf("close export zip failed: %s", err) } @@ -570,7 +570,7 @@ func ExportDocx(id, savePath string, removeAssets, merge bool) (fullPath string, } tmpDir := filepath.Join(util.TempDir, "export", gulu.Rand.String(7)) - if err = os.MkdirAll(tmpDir, 0755); nil != err { + if err = os.MkdirAll(tmpDir, 0755); err != nil { return } defer os.Remove(tmpDir) @@ -601,7 +601,7 @@ func ExportDocx(id, savePath string, removeAssets, merge bool) (fullPath string, gulu.CmdAttr(pandoc) pandoc.Stdin = bytes.NewBufferString(content) output, err := pandoc.CombinedOutput() - if nil != err { + if err != nil { logging.LogErrorf("export docx failed: %s", gulu.Str.FromBytes(output)) msg := fmt.Sprintf(Conf.Language(14), gulu.Str.FromBytes(output)) err = errors.New(msg) @@ -610,14 +610,14 @@ func ExportDocx(id, savePath string, removeAssets, merge bool) (fullPath string, fullPath = filepath.Join(savePath, name+".docx") fullPath = util.GetUniqueFilename(fullPath) - if err = filelock.Copy(tmpDocxPath, fullPath); nil != err { + if err = filelock.Copy(tmpDocxPath, fullPath); err != nil { logging.LogErrorf("export docx failed: %s", err) err = errors.New(fmt.Sprintf(Conf.Language(14), err)) return } if tmpAssets := filepath.Join(tmpDir, "assets"); !removeAssets && gulu.File.IsDir(tmpAssets) { - if err = filelock.Copy(tmpAssets, filepath.Join(savePath, "assets")); nil != err { + if err = filelock.Copy(tmpAssets, filepath.Join(savePath, "assets")); err != nil { logging.LogErrorf("export docx failed: %s", err) err = errors.New(fmt.Sprintf(Conf.Language(14), err)) return @@ -652,7 +652,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom string name = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614 savePath = strings.TrimSpace(savePath) - if err := os.MkdirAll(savePath, 0755); nil != err { + if err := os.MkdirAll(savePath, 0755); err != nil { logging.LogErrorf("mkdir [%s] failed: %s", savePath, err) return } @@ -665,12 +665,12 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom string } srcAbsPath, err := GetAssetAbsPath(asset) - if nil != err { + if err != nil { logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err) continue } targetAbsPath := filepath.Join(savePath, asset) - if err = filelock.Copy(srcAbsPath, targetAbsPath); nil != err { + if err = filelock.Copy(srcAbsPath, targetAbsPath); err != nil { logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err) } } @@ -680,7 +680,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom string for _, src := range srcs { from := filepath.Join(util.WorkingDir, src) to := filepath.Join(savePath, src) - if err := filelock.Copy(from, to); nil != err { + if err := filelock.Copy(from, to); err != nil { logging.LogWarnf("copy stage from [%s] to [%s] failed: %s", from, savePath, err) return } @@ -705,7 +705,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom string for _, src := range srcs { from := filepath.Join(appearancePath, src) to := filepath.Join(savePath, "appearance", src) - if err := filelock.Copy(from, to); nil != err { + if err := filelock.Copy(from, to); err != nil { logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err) return } @@ -716,7 +716,7 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom string for _, emoji := range emojis { from := filepath.Join(util.DataDir, emoji) to := filepath.Join(savePath, emoji) - if err := filelock.Copy(from, to); nil != err { + if err := filelock.Copy(from, to); err != nil { logging.LogErrorf("copy emojis from [%s] to [%s] failed: %s", from, savePath, err) return } @@ -802,7 +802,7 @@ func ExportHTML(id, savePath string, pdf, image, keepFold, merge bool) (name, do name = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614 if "" != savePath { - if err := os.MkdirAll(savePath, 0755); nil != err { + if err := os.MkdirAll(savePath, 0755); err != nil { logging.LogErrorf("mkdir [%s] failed: %s", savePath, err) return } @@ -814,12 +814,12 @@ func ExportHTML(id, savePath string, pdf, image, keepFold, merge bool) (name, do } srcAbsPath, err := GetAssetAbsPath(asset) - if nil != err { + if err != nil { logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err) continue } targetAbsPath := filepath.Join(savePath, asset) - if err = filelock.Copy(srcAbsPath, targetAbsPath); nil != err { + if err = filelock.Copy(srcAbsPath, targetAbsPath); err != nil { logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err) } } @@ -831,7 +831,7 @@ func ExportHTML(id, savePath string, pdf, image, keepFold, merge bool) (name, do for _, src := range srcs { from := filepath.Join(util.WorkingDir, src) to := filepath.Join(savePath, src) - if err := filelock.Copy(from, to); nil != err { + if err := filelock.Copy(from, to); err != nil { logging.LogErrorf("copy stage from [%s] to [%s] failed: %s", from, savePath, err) return } @@ -855,7 +855,7 @@ func ExportHTML(id, savePath string, pdf, image, keepFold, merge bool) (name, do for _, src := range srcs { from := filepath.Join(appearancePath, src) to := filepath.Join(savePath, "appearance", src) - if err := filelock.Copy(from, to); nil != err { + if err := filelock.Copy(from, to); err != nil { logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err) return } @@ -866,7 +866,7 @@ func ExportHTML(id, savePath string, pdf, image, keepFold, merge bool) (name, do for _, emoji := range emojis { from := filepath.Join(util.DataDir, emoji) to := filepath.Join(savePath, emoji) - if err := filelock.Copy(from, to); nil != err { + if err := filelock.Copy(from, to); err != nil { logging.LogErrorf("copy emojis from [%s] to [%s] failed: %s", from, savePath, err) return } @@ -1055,7 +1055,7 @@ func processPDFWatermark(pdfCtx *pdfcpu.Context, watermark bool) { fontPath := filepath.Join(util.AppearancePath, "fonts", "LxgwWenKai-Lite-1.311", "LXGWWenKaiLite-Regular.ttf") err := api.InstallFonts([]string{fontPath}) - if nil != err { + if err != nil { logging.LogErrorf("install font [%s] failed: %s", fontPath, err) } } @@ -1073,14 +1073,14 @@ func processPDFWatermark(pdfCtx *pdfcpu.Context, watermark bool) { wm, err = pdfcpu.ParsePDFWatermarkDetails(str, desc, false, pdfcpu.POINTS) } - if nil != err { + if err != nil { logging.LogErrorf("parse watermark failed: %s", err) return } wm.OnTop = true // Export PDF and add watermarks no longer covered by images https://github.com/siyuan-note/siyuan/issues/10818 err = pdfCtx.AddWatermarks(nil, wm) - if nil != err { + if err != nil { logging.LogErrorf("add watermark failed: %s", err) return } @@ -1088,7 +1088,7 @@ func processPDFWatermark(pdfCtx *pdfcpu.Context, watermark bool) { func processPDFBookmarks(pdfCtx *pdfcpu.Context, headings []*ast.Node) { links, err := api.ListToCLinks(pdfCtx) - if nil != err { + if err != nil { return } @@ -1148,7 +1148,7 @@ func processPDFBookmarks(pdfCtx *pdfcpu.Context, headings []*ast.Node) { } err = pdfCtx.AddBookmarks(topBms) - if nil != err { + if err != nil { logging.LogErrorf("add bookmark failed: %s", err) return } @@ -1342,7 +1342,7 @@ func processPDFLinkEmbedAssets(pdfCtx *pdfcpu.Context, assetDests []string, remo func ExportStdMarkdown(id string) string { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree by block id [%s] failed: %s", id, err) return "" } @@ -1503,7 +1503,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) ( box := Conf.Box(boxID) exportFolder := filepath.Join(util.TempDir, "export", baseFolderName) - if err := os.MkdirAll(exportFolder, 0755); nil != err { + if err := os.MkdirAll(exportFolder, 0755); err != nil { logging.LogErrorf("create export temp folder failed: %s", err) return } @@ -1518,7 +1518,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) ( id := docIAL["id"] tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { continue } trees[tree.ID] = tree @@ -1649,7 +1649,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) ( } attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return ast.WalkContinue } @@ -1749,7 +1749,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) ( zipPath = exportFolder + ".sy.zip" zip, err := gulu.Zip.Create(zipPath) - if nil != err { + if err != nil { logging.LogErrorf("create export .sy.zip [%s] failed: %s", exportFolder, err) return "" } @@ -1759,12 +1759,12 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) ( util.PushEndlessProgress(msg) } - if err = zip.AddDirectory(baseFolderName, exportFolder, zipCallback); nil != err { + if err = zip.AddDirectory(baseFolderName, exportFolder, zipCallback); err != nil { logging.LogErrorf("create export .sy.zip [%s] failed: %s", exportFolder, err) return "" } - if err = zip.Close(); nil != err { + if err = zip.Close(); err != nil { logging.LogErrorf("close export .sy.zip failed: %s", err) } @@ -1819,7 +1819,7 @@ func ExportMarkdownContent(id string) (hPath, exportedMd string) { func exportMarkdownContent(id string, exportRefMode int, defBlockIDs []string) (hPath, exportedMd string) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree by block id [%s] failed: %s", id, err) return } @@ -2196,14 +2196,14 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool, } attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return ast.WalkContinue } viewID := n.IALAttr(av.NodeAttrView) view, err := attrView.GetCurrentView(viewID) - if nil != err { + if err != nil { logging.LogErrorf("get attribute view [%s] failed: %s", avID, err) return ast.WalkContinue } @@ -2389,7 +2389,7 @@ func resolveFootnotesDefs(refFootnotes *[]*refAsFootnotes, rootID string, blockR var rendered []string for _, foot := range *refFootnotes { t, err := LoadTreeByBlockID(foot.defID) - if nil != err { + if err != nil { continue } defNode := treenode.GetNodeInTree(t, foot.defID) @@ -2515,7 +2515,7 @@ func collectFootnotesDefs(id string, refFootnotes *[]*refAsFootnotes, treeCache t := (*treeCache)[b.RootID] if nil == t { var err error - if t, err = LoadTreeByBlockID(b.ID); nil != err { + if t, err = LoadTreeByBlockID(b.ID); err != nil { return } (*treeCache)[t.ID] = t @@ -2602,7 +2602,7 @@ func exportRefTrees0(tree *parse.Tree, retTrees *map[string]*parse.Tree) { return ast.WalkSkipChildren } defTree, err := LoadTreeByBlockID(defBlock.RootID) - if nil != err { + if err != nil { return ast.WalkSkipChildren } @@ -2647,18 +2647,18 @@ func exportRefTrees0(tree *parse.Tree, retTrees *map[string]*parse.Tree) { func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode int) ast.WalkStatus { p := refID[:strings.LastIndex(refID, "/")] absPath, err := GetAssetAbsPath(p) - if nil != err { + if err != nil { logging.LogWarnf("get assets abs path by rel path [%s] failed: %s", p, err) return ast.WalkSkipChildren } sya := absPath + ".sya" syaData, err := os.ReadFile(sya) - if nil != err { + if err != nil { logging.LogErrorf("read file [%s] failed: %s", sya, err) return ast.WalkSkipChildren } syaJSON := map[string]interface{}{} - if err = gulu.JSON.UnmarshalJSON(syaData, &syaJSON); nil != err { + if err = gulu.JSON.UnmarshalJSON(syaData, &syaJSON); err != nil { logging.LogErrorf("unmarshal file [%s] failed: %s", sya, err) return ast.WalkSkipChildren } @@ -2705,7 +2705,7 @@ func exportPandocConvertZip(exportNotebook bool, boxID, baseFolderName string, d exportFolder := filepath.Join(util.TempDir, "export", baseFolderName+ext) os.RemoveAll(exportFolder) - if err := os.MkdirAll(exportFolder, 0755); nil != err { + if err := os.MkdirAll(exportFolder, 0755); err != nil { logging.LogErrorf("create export temp folder failed: %s", err) return } @@ -2726,7 +2726,7 @@ func exportPandocConvertZip(exportNotebook bool, boxID, baseFolderName string, d } id := docIAL["id"] tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { continue } ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus { @@ -2772,7 +2772,7 @@ func exportPandocConvertZip(exportNotebook bool, boxID, baseFolderName string, d writePath = filepath.Join(exportFolder, p) } writeFolder := filepath.Dir(writePath) - if err := os.MkdirAll(writeFolder, 0755); nil != err { + if err := os.MkdirAll(writeFolder, 0755); err != nil { logging.LogErrorf("create export temp folder [%s] failed: %s", writeFolder, err) continue } @@ -2792,14 +2792,14 @@ func exportPandocConvertZip(exportNotebook bool, boxID, baseFolderName string, d } srcPath, err := GetAssetAbsPath(asset) - if nil != err { + if err != nil { logging.LogWarnf("get asset [%s] abs path failed: %s", asset, err) continue } destPath := filepath.Join(writeFolder, asset) err = filelock.Copy(srcPath, destPath) - if nil != err { + if err != nil { logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, err) continue } @@ -2807,7 +2807,7 @@ func exportPandocConvertZip(exportNotebook bool, boxID, baseFolderName string, d // 调用 Pandoc 进行格式转换 err := util.Pandoc(pandocFrom, pandocTo, writePath, md) - if nil != err { + if err != nil { logging.LogErrorf("pandoc failed: %s", err) continue } @@ -2815,14 +2815,14 @@ func exportPandocConvertZip(exportNotebook bool, boxID, baseFolderName string, d zipPath = exportFolder + ".zip" zip, err := gulu.Zip.Create(zipPath) - if nil != err { + if err != nil { logging.LogErrorf("create export markdown zip [%s] failed: %s", exportFolder, err) return "" } // 导出 Markdown zip 包内不带文件夹 https://github.com/siyuan-note/siyuan/issues/6869 entries, err := os.ReadDir(exportFolder) - if nil != err { + if err != nil { logging.LogErrorf("read export markdown folder [%s] failed: %s", exportFolder, err) return "" } @@ -2833,13 +2833,13 @@ func exportPandocConvertZip(exportNotebook bool, boxID, baseFolderName string, d } else { err = zip.AddEntry(entry.Name(), entryPath) } - if nil != err { + if err != nil { logging.LogErrorf("add entry [%s] to zip failed: %s", entry.Name(), err) return "" } } - if err = zip.Close(); nil != err { + if err = zip.Close(); err != nil { logging.LogErrorf("close export markdown zip failed: %s", err) } diff --git a/kernel/model/export_merge.go b/kernel/model/export_merge.go index b54a10202..1956518fb 100644 --- a/kernel/model/export_merge.go +++ b/kernel/model/export_merge.go @@ -27,7 +27,7 @@ import ( func mergeSubDocs(rootTree *parse.Tree) (ret *parse.Tree, err error) { ret = rootTree rootBlock := &Block{Box: rootTree.Box, ID: rootTree.ID, Path: rootTree.Path, HPath: rootTree.HPath} - if err = buildBlockChildren(rootBlock); nil != err { + if err = buildBlockChildren(rootBlock); err != nil { return } @@ -53,7 +53,7 @@ func mergeSubDocs(rootTree *parse.Tree) (ret *parse.Tree, err error) { for { i := 0 - if err = walkBlock(insertPoint, rootBlock, i); nil != err { + if err = walkBlock(insertPoint, rootBlock, i); err != nil { return } if nil == rootBlock.Children { @@ -67,7 +67,7 @@ func walkBlock(insertPoint *ast.Node, block *Block, level int) (err error) { level++ for i := len(block.Children) - 1; i >= 0; i-- { c := block.Children[i] - if err = walkBlock(insertPoint, c, level); nil != err { + if err = walkBlock(insertPoint, c, level); err != nil { return } @@ -87,7 +87,7 @@ func walkBlock(insertPoint *ast.Node, block *Block, level int) (err error) { func loadTreeNodes(box string, p string, level int) (ret []*ast.Node, err error) { luteEngine := NewLute() tree, err := filesys.LoadTree(box, p, luteEngine) - if nil != err { + if err != nil { return } @@ -112,7 +112,7 @@ func loadTreeNodes(box string, p string, level int) (ret []*ast.Node, err error) func buildBlockChildren(block *Block) (err error) { files, _, err := ListDocTree(block.Box, block.Path, util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount) - if nil != err { + if err != nil { return } @@ -122,7 +122,7 @@ func buildBlockChildren(block *Block) (err error) { } for _, c := range block.Children { - if err = buildBlockChildren(c); nil != err { + if err = buildBlockChildren(c); err != nil { return } } diff --git a/kernel/model/file.go b/kernel/model/file.go index b74a2a0fe..ac7977c31 100644 --- a/kernel/model/file.go +++ b/kernel/model/file.go @@ -94,7 +94,7 @@ func (box *Box) docFromFileInfo(fileInfo *FileInfo, ial map[string]string) (ret mTime := t if updated := ial["updated"]; "" != updated { - if updatedTime, err := time.ParseInLocation("20060102150405", updated, time.Local); nil == err { + if updatedTime, err := time.ParseInLocation("20060102150405", updated, time.Local); err == nil { mTime = updatedTime } } @@ -122,7 +122,7 @@ func (box *Box) docIAL(p string) (ret map[string]string) { box.moveCorruptedData(filePath) return nil } - if nil != err { + if err != nil { logging.LogErrorf("read file [%s] failed: %s", p, err) return nil } @@ -271,7 +271,7 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo var files []*FileInfo start := time.Now() files, totals, err = box.Ls(listPath) - if nil != err { + if err != nil { return } elapsed := time.Now().Sub(start).Milliseconds() @@ -300,7 +300,7 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo doc := box.docFromFileInfo(parentDocFile, ial) subFiles, err := os.ReadDir(filepath.Join(boxLocalPath, file.path)) - if nil == err { + if err == nil { for _, subFile := range subFiles { subDocFilePath := path.Join(file.path, subFile.Name()) if subIAL := box.docIAL(subDocFilePath); "true" == subIAL["custom-hidden"] { @@ -602,7 +602,7 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes map[s inputIndex := index tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { if ErrBlockNotFound == err { if 0 == mode { err = ErrTreeNotFound // 初始化打开文档时如果找不到则关闭编辑器 @@ -1055,7 +1055,7 @@ func loadNodesByMode(node *ast.Node, inputIndex, mode, size int, isDoc, isHeadin } func writeTreeUpsertQueue(tree *parse.Tree) (err error) { - if err = filesys.WriteTree(tree); nil != err { + if err = filesys.WriteTree(tree); err != nil { return } sql.UpsertTreeQueue(tree) @@ -1063,7 +1063,7 @@ func writeTreeUpsertQueue(tree *parse.Tree) (err error) { } func writeTreeIndexQueue(tree *parse.Tree) (err error) { - if err = filesys.WriteTree(tree); nil != err { + if err = filesys.WriteTree(tree); err != nil { return } sql.IndexTreeQueue(tree) @@ -1081,7 +1081,7 @@ func indexWriteTreeUpsertQueue(tree *parse.Tree) (err error) { } func renameWriteJSONQueue(tree *parse.Tree) (err error) { - if err = filesys.WriteTree(tree); nil != err { + if err = filesys.WriteTree(tree); err != nil { return } sql.RenameTreeQueue(tree) @@ -1140,7 +1140,7 @@ func CreateDocByMd(boxID, p, title, md string, sorts []string) (tree *parse.Tree luteEngine := util.NewLute() dom := luteEngine.Md2BlockDOM(md, false) tree, err = createDoc(box.ID, p, title, dom) - if nil != err { + if err != nil { return } @@ -1188,7 +1188,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) { } hPath, err := RenderGoTemplate(boxConf.DailyNoteSavePath) - if nil != err { + if err != nil { return } @@ -1208,7 +1208,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) { date := time.Now().Format("20060102") if tree.Root.IALAttr("custom-dailynote-"+date) == "" { tree.Root.SetIALAttr("custom-dailynote-"+date, date) - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } } @@ -1216,7 +1216,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) { } id, err := createDocsByHPath(box.ID, hPath, "", "", "") - if nil != err { + if err != nil { return } @@ -1237,7 +1237,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) { if "" != templateDom { var tree *parse.Tree tree, err = LoadTreeByBlockID(id) - if nil == err { + if err == nil { tree.Root.FirstChild.Unlink() luteEngine := util.NewLute() @@ -1259,7 +1259,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) { } tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr()) - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } } @@ -1269,14 +1269,14 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) { WaitForWritingFiles() tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree by block id [%s] failed: %v", id, err) return } p = tree.Path date := time.Now().Format("20060102") tree.Root.SetIALAttr("custom-dailynote-"+date, date) - if err = indexWriteTreeUpsertQueue(tree); nil != err { + if err = indexWriteTreeUpsertQueue(tree); err != nil { return } @@ -1291,7 +1291,7 @@ func GetHPathByPath(boxID, p string) (hPath string, err error) { luteEngine := util.NewLute() tree, err := filesys.LoadTree(boxID, p, luteEngine) - if nil != err { + if err != nil { return } hPath = tree.HPath @@ -1320,7 +1320,7 @@ func GetHPathsByPaths(paths []string) (hPaths []string, err error) { func GetHPathByID(id string) (hPath string, err error) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } hPath = tree.HPath @@ -1329,7 +1329,7 @@ func GetHPathByID(id string) (hPath string, err error) { func GetPathByID(id string) (path string, err error) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -1339,7 +1339,7 @@ func GetPathByID(id string) (path string, err error) { func GetFullHPathByID(id string) (hPath string, err error) { tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -1422,7 +1422,7 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback interface{}) } _, err = moveDoc(fromBox, fromPath, toBox, toPath, luteEngine, callback) - if nil != err { + if err != nil { return } } @@ -1434,7 +1434,7 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback interface{}) func countSubDocs(box, p string) (ret int) { p = strings.TrimSuffix(p, ".sy") _ = filepath.Walk(filepath.Join(util.DataDir, box, p), func(path string, info os.FileInfo, err error) error { - if nil != err { + if err != nil { return err } if info.IsDir() { @@ -1464,7 +1464,7 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin } tree, err := filesys.LoadTree(fromBox.ID, fromPath, luteEngine) - if nil != err { + if err != nil { err = ErrBlockNotFound return } @@ -1480,7 +1480,7 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin } else { toTree, err = filesys.LoadTree(toBox.ID, toPath, luteEngine) } - if nil != err { + if err != nil { err = ErrBlockNotFound return } @@ -1490,11 +1490,11 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin } if isSameBox { - if err = fromBox.MkdirAll(toFolder); nil != err { + if err = fromBox.MkdirAll(toFolder); err != nil { return } } else { - if err = toBox.MkdirAll(toFolder); nil != err { + if err = toBox.MkdirAll(toFolder); err != nil { return } } @@ -1505,7 +1505,7 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin newFolder := path.Join(toFolder, tree.ID) if isSameBox { - if err = fromBox.Move(fromFolder, newFolder); nil != err { + if err = fromBox.Move(fromFolder, newFolder); err != nil { return } } else { @@ -1514,7 +1514,7 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin if filelock.IsExist(absToPath) { filelock.Remove(absToPath) } - if err = filelock.Rename(absFromPath, absToPath); nil != err { + if err = filelock.Rename(absFromPath, absToPath); err != nil { msg := fmt.Sprintf(Conf.Language(5), fromBox.Name, fromPath, err) logging.LogErrorf("move [path=%s] in box [%s] failed: %s", fromPath, fromBox.ID, err) err = errors.New(msg) @@ -1526,12 +1526,12 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin newPath = path.Join(toFolder, tree.ID+".sy") if isSameBox { - if err = fromBox.Move(fromPath, newPath); nil != err { + if err = fromBox.Move(fromPath, newPath); err != nil { return } tree, err = filesys.LoadTree(fromBox.ID, newPath, luteEngine) - if nil != err { + if err != nil { return } @@ -1539,7 +1539,7 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin } else { absFromPath := filepath.Join(util.DataDir, fromBox.ID, fromPath) absToPath := filepath.Join(util.DataDir, toBox.ID, newPath) - if err = filelock.Rename(absFromPath, absToPath); nil != err { + if err = filelock.Rename(absFromPath, absToPath); err != nil { msg := fmt.Sprintf(Conf.Language(5), fromBox.Name, fromPath, err) logging.LogErrorf("move [path=%s] in box [%s] failed: %s", fromPath, fromBox.ID, err) err = errors.New(msg) @@ -1547,7 +1547,7 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin } tree, err = filesys.LoadTree(toBox.ID, newPath, luteEngine) - if nil != err { + if err != nil { return } @@ -1624,14 +1624,14 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) { } historyDir, err := GetHistoryDir(HistoryOpDelete) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } historyPath := filepath.Join(historyDir, box.ID, p) absPath := filepath.Join(util.DataDir, box.ID, p) - if err = filelock.Copy(absPath, historyPath); nil != err { + if err = filelock.Copy(absPath, historyPath); err != nil { logging.LogErrorf("backup [path=%s] to history [%s] failed: %s", absPath, historyPath, err) return } @@ -1655,7 +1655,7 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) { if existChildren { absChildrenDir := filepath.Join(util.DataDir, tree.Box, childrenDir) historyPath = filepath.Join(historyDir, tree.Box, childrenDir) - if err = filelock.Copy(absChildrenDir, historyPath); nil != err { + if err = filelock.Copy(absChildrenDir, historyPath); err != nil { logging.LogErrorf("backup [path=%s] to history [%s] failed: %s", absChildrenDir, historyPath, err) return } @@ -1676,13 +1676,13 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) { } if existChildren { - if err = box.Remove(childrenDir); nil != err { + if err = box.Remove(childrenDir); err != nil { logging.LogErrorf("remove children dir [%s%s] failed: %s", box.ID, childrenDir, err) return } logging.LogInfof("removed children dir [%s%s]", box.ID, childrenDir) } - if err = box.Remove(p); nil != err { + if err = box.Remove(p); err != nil { logging.LogErrorf("remove [%s%s] failed: %s", box.ID, p, err) return } @@ -1692,7 +1692,7 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) { RemoveRecentDoc(removeIDs) if "/" != dir { others, err := os.ReadDir(filepath.Join(util.DataDir, box.ID, dir)) - if nil == err && 1 > len(others) { + if err == nil && 1 > len(others) { box.Remove(dir) } } @@ -1723,7 +1723,7 @@ func RenameDoc(boxID, p, title string) (err error) { WaitForWritingFiles() luteEngine := util.NewLute() tree, err := filesys.LoadTree(box.ID, p, luteEngine) - if nil != err { + if err != nil { return } @@ -1745,7 +1745,7 @@ func RenameDoc(boxID, p, title string) (err error) { tree.HPath = path.Join(path.Dir(tree.HPath), title) tree.Root.SetIALAttr("title", title) tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr()) - if err = renameWriteJSONQueue(tree); nil != err { + if err = renameWriteJSONQueue(tree); err != nil { return } @@ -1818,7 +1818,7 @@ func createDoc(boxID, p, title, dom string) (tree *parse.Tree, err error) { } if !box.Exist(folder) { - if err = box.MkdirAll(folder); nil != err { + if err = box.MkdirAll(folder); err != nil { return } } @@ -1900,12 +1900,12 @@ func moveSorts(rootID, fromBox, toBox string) { fromFullSortIDs := map[string]int{} if filelock.IsExist(fromConfPath) { data, err := filelock.ReadFile(fromConfPath) - if nil != err { + if err != nil { logging.LogErrorf("read sort conf failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &fromFullSortIDs); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &fromFullSortIDs); err != nil { logging.LogErrorf("unmarshal sort conf failed: %s", err) } } @@ -1917,12 +1917,12 @@ func moveSorts(rootID, fromBox, toBox string) { toFullSortIDs := map[string]int{} if filelock.IsExist(toConfPath) { data, err := filelock.ReadFile(toConfPath) - if nil != err { + if err != nil { logging.LogErrorf("read sort conf failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &toFullSortIDs); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &toFullSortIDs); err != nil { logging.LogErrorf("unmarshal sort conf failed: %s", err) return } @@ -1933,11 +1933,11 @@ func moveSorts(rootID, fromBox, toBox string) { } data, err := gulu.JSON.MarshalJSON(toFullSortIDs) - if nil != err { + if err != nil { logging.LogErrorf("marshal sort conf failed: %s", err) return } - if err = filelock.WriteFile(toConfPath, data); nil != err { + if err = filelock.WriteFile(toConfPath, data); err != nil { logging.LogErrorf("write sort conf failed: %s", err) return } @@ -1964,7 +1964,7 @@ func ChangeFileTreeSort(boxID string, paths []string) { parentPath := path.Dir(p) absParentPath := filepath.Join(util.DataDir, boxID, parentPath) files, err := os.ReadDir(absParentPath) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", absParentPath, err) } @@ -1984,7 +1984,7 @@ func ChangeFileTreeSort(boxID string, paths []string) { } confDir := filepath.Join(util.DataDir, box.ID, ".siyuan") - if err = os.MkdirAll(confDir, 0755); nil != err { + if err = os.MkdirAll(confDir, 0755); err != nil { logging.LogErrorf("create conf dir failed: %s", err) return } @@ -1993,12 +1993,12 @@ func ChangeFileTreeSort(boxID string, paths []string) { var data []byte if filelock.IsExist(confPath) { data, err = filelock.ReadFile(confPath) - if nil != err { + if err != nil { logging.LogErrorf("read sort conf failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); err != nil { logging.LogErrorf("unmarshal sort conf failed: %s", err) } } @@ -2008,11 +2008,11 @@ func ChangeFileTreeSort(boxID string, paths []string) { } data, err = gulu.JSON.MarshalJSON(fullSortIDs) - if nil != err { + if err != nil { logging.LogErrorf("marshal sort conf failed: %s", err) return } - if err = filelock.WriteFile(confPath, data); nil != err { + if err = filelock.WriteFile(confPath, data); err != nil { logging.LogErrorf("write sort conf failed: %s", err) return } @@ -2027,13 +2027,13 @@ func (box *Box) fillSort(files *[]*File) { } data, err := filelock.ReadFile(confPath) - if nil != err { + if err != nil { logging.LogErrorf("read sort conf failed: %s", err) return } fullSortIDs := map[string]int{} - if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); err != nil { logging.LogErrorf("unmarshal sort conf failed: %s", err) return } @@ -2051,13 +2051,13 @@ func (box *Box) removeSort(ids []string) { } data, err := filelock.ReadFile(confPath) - if nil != err { + if err != nil { logging.LogErrorf("read sort conf failed: %s", err) return } fullSortIDs := map[string]int{} - if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); err != nil { logging.LogErrorf("unmarshal sort conf failed: %s", err) return } @@ -2067,11 +2067,11 @@ func (box *Box) removeSort(ids []string) { } data, err = gulu.JSON.MarshalJSON(fullSortIDs) - if nil != err { + if err != nil { logging.LogErrorf("marshal sort conf failed: %s", err) return } - if err = filelock.WriteFile(confPath, data); nil != err { + if err = filelock.WriteFile(confPath, data); err != nil { logging.LogErrorf("write sort conf failed: %s", err) return } @@ -2079,7 +2079,7 @@ func (box *Box) removeSort(ids []string) { func (box *Box) addMinSort(parentPath, id string) { docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeUnassigned, false, false, 1) - if nil != err { + if err != nil { logging.LogErrorf("list doc tree failed: %s", err) return } @@ -2090,7 +2090,7 @@ func (box *Box) addMinSort(parentPath, id string) { } confDir := filepath.Join(util.DataDir, box.ID, ".siyuan") - if err = os.MkdirAll(confDir, 0755); nil != err { + if err = os.MkdirAll(confDir, 0755); err != nil { logging.LogErrorf("create conf dir failed: %s", err) return } @@ -2099,12 +2099,12 @@ func (box *Box) addMinSort(parentPath, id string) { var data []byte if filelock.IsExist(confPath) { data, err = filelock.ReadFile(confPath) - if nil != err { + if err != nil { logging.LogErrorf("read sort conf failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &fullSortIDs); err != nil { logging.LogErrorf("unmarshal sort conf failed: %s", err) } } @@ -2112,11 +2112,11 @@ func (box *Box) addMinSort(parentPath, id string) { fullSortIDs[id] = sortVal data, err = gulu.JSON.MarshalJSON(fullSortIDs) - if nil != err { + if err != nil { logging.LogErrorf("marshal sort conf failed: %s", err) return } - if err = filelock.WriteFile(confPath, data); nil != err { + if err = filelock.WriteFile(confPath, data); err != nil { logging.LogErrorf("write sort conf failed: %s", err) return } diff --git a/kernel/model/flashcard.go b/kernel/model/flashcard.go index 08e7ceb53..23c221f8e 100644 --- a/kernel/model/flashcard.go +++ b/kernel/model/flashcard.go @@ -106,7 +106,7 @@ func SetFlashcardsDueTime(cardDues []*SetFlashcardDueTime) (err error) { card.SetDue(due) } - if err = deck.Save(); nil != err { + if err = deck.Save(); err != nil { logging.LogErrorf("save deck [%s] failed: %s", builtinDeckID, err) } return @@ -270,7 +270,7 @@ func GetNotebookFlashcards(boxID string, page, pageSize int) (blocks []*Block, t blocks = []*Block{} entries, err := os.ReadDir(filepath.Join(util.DataDir, boxID)) - if nil != err { + if err != nil { logging.LogErrorf("read dir failed: %s", err) return } @@ -467,12 +467,12 @@ func ReviewFlashcard(deckID, cardID string, rating riff.Rating, reviewedCardIDs } log := deck.Review(cardID, rating) - if err = deck.Save(); nil != err { + if err = deck.Save(); err != nil { logging.LogErrorf("save deck [%s] failed: %s", deckID, err) return } - if err = deck.SaveLog(log); nil != err { + if err = deck.SaveLog(log); err != nil { logging.LogErrorf("save review log [%s] failed: %s", deckID, err) return } @@ -538,7 +538,7 @@ func GetNotebookDueFlashcards(boxID string, reviewedCardIDs []string) (ret []*Fl waitForSyncingStorages() entries, err := os.ReadDir(filepath.Join(util.DataDir, boxID)) - if nil != err { + if err != nil { logging.LogErrorf("read dir failed: %s", err) return } @@ -734,7 +734,7 @@ func (tx *Transaction) doRemoveFlashcards(operation *Operation) (ret *TxErr) { deckID := operation.DeckID blockIDs := operation.BlockIDs - if err := tx.removeBlocksDeckAttr(blockIDs, deckID); nil != err { + if err := tx.removeBlocksDeckAttr(blockIDs, deckID); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: deckID} } @@ -803,7 +803,7 @@ func (tx *Transaction) removeBlocksDeckAttr(blockIDs []string, deckID string) (e node.SetIALAttr("custom-riff-decks", val) } - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return } @@ -829,7 +829,7 @@ func removeFlashcardsByBlockIDs(blockIDs []string, deck *riff.Deck) { deck.RemoveCard(card.ID()) } err := deck.Save() - if nil != err { + if err != nil { logging.LogErrorf("save deck [%s] failed: %s", deck.ID, err) } } @@ -899,7 +899,7 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) { val = strings.TrimSuffix(val, ",") node.SetIALAttr("custom-riff-decks", val) - if err := tx.writeTree(tree); nil != err { + if err := tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: deckID} } @@ -924,7 +924,7 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) { deck.AddCard(cardID, blockID) } - if err := deck.Save(); nil != err { + if err := deck.Save(); err != nil { logging.LogErrorf("save deck [%s] failed: %s", deckID, err) return } @@ -933,7 +933,7 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) { func LoadFlashcards() { riffSavePath := getRiffDir() - if err := os.MkdirAll(riffSavePath, 0755); nil != err { + if err := os.MkdirAll(riffSavePath, 0755); err != nil { logging.LogErrorf("create riff dir [%s] failed: %s", riffSavePath, err) return } @@ -941,7 +941,7 @@ func LoadFlashcards() { Decks = map[string]*riff.Deck{} entries, err := os.ReadDir(riffSavePath) - if nil != err { + if err != nil { logging.LogErrorf("read riff dir failed: %s", err) return } @@ -978,7 +978,7 @@ func RenameDeck(deckID, name string) (err error) { deck := Decks[deckID] deck.Name = name err = deck.Save() - if nil != err { + if err != nil { logging.LogErrorf("save deck [%s] failed: %s", deckID, err) return } @@ -994,14 +994,14 @@ func RemoveDeck(deckID string) (err error) { riffSavePath := getRiffDir() deckPath := filepath.Join(riffSavePath, deckID+".deck") if filelock.IsExist(deckPath) { - if err = filelock.Remove(deckPath); nil != err { + if err = filelock.Remove(deckPath); err != nil { return } } cardsPath := filepath.Join(riffSavePath, deckID+".cards") if filelock.IsExist(cardsPath) { - if err = filelock.Remove(cardsPath); nil != err { + if err = filelock.Remove(cardsPath); err != nil { return } } @@ -1027,14 +1027,14 @@ func createDeck(name string) (deck *riff.Deck, err error) { func createDeck0(name string, deckID string) (deck *riff.Deck, err error) { riffSavePath := getRiffDir() deck, err = riff.LoadDeck(riffSavePath, deckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights) - if nil != err { + if err != nil { logging.LogErrorf("load deck [%s] failed: %s", deckID, err) return } deck.Name = name Decks[deckID] = deck err = deck.Save() - if nil != err { + if err != nil { logging.LogErrorf("save deck [%s] failed: %s", deckID, err) return } diff --git a/kernel/model/format.go b/kernel/model/format.go index de4408ddc..856ca9242 100644 --- a/kernel/model/format.go +++ b/kernel/model/format.go @@ -25,7 +25,7 @@ import ( func AutoSpace(rootID string) (err error) { tree, err := LoadTreeByBlockID(rootID) - if nil != err { + if err != nil { return } @@ -69,7 +69,7 @@ func AutoSpace(rootID string) (err error) { newTree.HPath = tree.HPath newTree.Box = tree.Box err = writeTreeUpsertQueue(newTree) - if nil != err { + if err != nil { return } logging.LogInfof("formatted tree [%s]", rootID) diff --git a/kernel/model/graph.go b/kernel/model/graph.go index 4d26100f6..86283185e 100644 --- a/kernel/model/graph.go +++ b/kernel/model/graph.go @@ -64,7 +64,7 @@ func BuildTreeGraph(id, query string) (boxID string, nodes []*GraphNode, links [ links = []*GraphLink{} tree, err := LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } node := treenode.GetNodeInTree(tree, id) diff --git a/kernel/model/heading.go b/kernel/model/heading.go index 365d97dfc..fd33c12db 100644 --- a/kernel/model/heading.go +++ b/kernel/model/heading.go @@ -36,7 +36,7 @@ import ( func (tx *Transaction) doFoldHeading(operation *Operation) (ret *TxErr) { headingID := operation.ID tree, err := tx.loadTree(headingID) - if nil != err { + if err != nil { return &TxErr{code: TxErrCodeBlockNotFound, id: headingID} } @@ -59,7 +59,7 @@ func (tx *Transaction) doFoldHeading(operation *Operation) (ret *TxErr) { }) } heading.SetIALAttr("fold", "1") - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: headingID} } IncSync() @@ -77,7 +77,7 @@ func (tx *Transaction) doUnfoldHeading(operation *Operation) (ret *TxErr) { headingID := operation.ID tree, err := tx.loadTree(headingID) - if nil != err { + if err != nil { return &TxErr{code: TxErrCodeBlockNotFound, id: headingID} } @@ -100,7 +100,7 @@ func (tx *Transaction) doUnfoldHeading(operation *Operation) (ret *TxErr) { } heading.RemoveIALAttr("fold") heading.RemoveIALAttr("heading-fold") - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: headingID} } IncSync() @@ -272,7 +272,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath string) (srcRootBlockID, srcRootBlockID = srcTree.Root.ID headingBlock, err := getBlock(srcHeadingID, srcTree) - if nil != err { + if err != nil { return } if nil == headingBlock { @@ -308,7 +308,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath string) (srcRootBlockID, newTargetPath = path.Join(toFolder, srcHeadingID+".sy") if !box.Exist(toFolder) { - if err = box.MkdirAll(toFolder); nil != err { + if err = box.MkdirAll(toFolder); err != nil { return } } @@ -358,7 +358,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath string) (srcRootBlockID, srcTree.Root.AppendChild(treenode.NewParagraph()) } treenode.RemoveBlockTreesByRootID(srcTree.ID) - if err = indexWriteTreeUpsertQueue(srcTree); nil != err { + if err = indexWriteTreeUpsertQueue(srcTree); err != nil { return "", "", err } @@ -366,7 +366,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath string) (srcRootBlockID, newTree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr()) newTree.Root.Spec = "1" box.addMinSort(path.Dir(newTargetPath), newTree.ID) - if err = indexWriteTreeUpsertQueue(newTree); nil != err { + if err = indexWriteTreeUpsertQueue(newTree); err != nil { return "", "", err } IncSync() diff --git a/kernel/model/history.go b/kernel/model/history.go index 60ec0db7e..cb9857690 100644 --- a/kernel/model/history.go +++ b/kernel/model/history.go @@ -97,7 +97,7 @@ func ChangeHistoryTick(minutes int) { func ClearWorkspaceHistory() (err error) { historyDir := util.HistoryDir if gulu.File.IsDir(historyDir) { - if err = os.RemoveAll(historyDir); nil != err { + if err = os.RemoveAll(historyDir); err != nil { logging.LogErrorf("remove workspace history dir [%s] failed: %s", historyDir, err) return } @@ -109,7 +109,7 @@ func ClearWorkspaceHistory() (err error) { // 以下部分是老版本的清理逻辑,暂时保留 notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } @@ -120,7 +120,7 @@ func ClearWorkspaceHistory() (err error) { continue } - if err = os.RemoveAll(historyDir); nil != err { + if err = os.RemoveAll(historyDir); err != nil { logging.LogErrorf("remove notebook history dir [%s] failed: %s", historyDir, err) return } @@ -129,7 +129,7 @@ func ClearWorkspaceHistory() (err error) { historyDir = filepath.Join(util.DataDir, ".siyuan", "history") if gulu.File.IsDir(historyDir) { - if err = os.RemoveAll(historyDir); nil != err { + if err = os.RemoveAll(historyDir); err != nil { logging.LogErrorf("remove data history dir [%s] failed: %s", historyDir, err) return } @@ -137,7 +137,7 @@ func ClearWorkspaceHistory() (err error) { } historyDir = filepath.Join(util.DataDir, "assets", ".siyuan", "history") if gulu.File.IsDir(historyDir) { - if err = os.RemoveAll(historyDir); nil != err { + if err = os.RemoveAll(historyDir); err != nil { logging.LogErrorf("remove assets history dir [%s] failed: %s", historyDir, err) return } @@ -153,7 +153,7 @@ func GetDocHistoryContent(historyPath, keyword string) (id, rootID, content stri } data, err := filelock.ReadFile(historyPath) - if nil != err { + if err != nil { logging.LogErrorf("read file [%s] failed: %s", historyPath, err) return } @@ -161,7 +161,7 @@ func GetDocHistoryContent(historyPath, keyword string) (id, rootID, content stri luteEngine := NewLute() historyTree, err := filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions) - if nil != err { + if err != nil { logging.LogErrorf("parse tree from file [%s] failed, remove it", historyPath) os.RemoveAll(historyPath) return @@ -234,17 +234,17 @@ func RollbackDocHistory(boxID, historyPath string) (err error) { workingDoc := treenode.GetBlockTree(id) if nil != workingDoc { - if err = filelock.Remove(filepath.Join(util.DataDir, boxID, workingDoc.Path)); nil != err { + if err = filelock.Remove(filepath.Join(util.DataDir, boxID, workingDoc.Path)); err != nil { return } } destPath, parentHPath, err = getRollbackDockPath(boxID, historyPath) - if nil != err { + if err != nil { return } - if err = filelock.CopyNewtimes(srcPath, destPath); nil != err { + if err = filelock.CopyNewtimes(srcPath, destPath); err != nil { return } @@ -317,7 +317,7 @@ func getRollbackDockPath(boxID, historyPath string) (destPath, parentHPath strin // 父路径如果是文档,则恢复到父路径下 parentDir := strings.TrimSuffix(parentWorkingDoc.Path, ".sy") parentDir = filepath.Join(util.DataDir, boxID, parentDir) - if err = os.MkdirAll(parentDir, 0755); nil != err { + if err = os.MkdirAll(parentDir, 0755); err != nil { return } destPath = filepath.Join(parentDir, baseName) @@ -339,7 +339,7 @@ func RollbackAssetsHistory(historyPath string) (err error) { from := historyPath to := filepath.Join(util.DataDir, "assets", filepath.Base(historyPath)) - if err = filelock.CopyNewtimes(from, to); nil != err { + if err = filelock.CopyNewtimes(from, to); err != nil { logging.LogErrorf("copy file [%s] to [%s] failed: %s", from, to, err) return } @@ -357,7 +357,7 @@ func RollbackNotebookHistory(historyPath string) (err error) { from := historyPath to := filepath.Join(util.DataDir, filepath.Base(historyPath)) - if err = filelock.CopyNewtimes(from, to); nil != err { + if err = filelock.CopyNewtimes(from, to); err != nil { logging.LogErrorf("copy file [%s] to [%s] failed: %s", from, to, err) return } @@ -395,14 +395,14 @@ func FullTextSearchHistory(query, box, op string, typ, page int) (ret []string, countStmt := strings.ReplaceAll(stmt, "SELECT DISTINCT created", "SELECT COUNT(DISTINCT created) AS total") stmt += " ORDER BY created DESC LIMIT " + strconv.Itoa(fileHistoryPageSize) + " OFFSET " + strconv.Itoa(offset) result, err := sql.QueryHistory(stmt) - if nil != err { + if err != nil { return } for _, row := range result { ret = append(ret, row["created"].(string)) } result, err = sql.QueryHistory(countStmt) - if nil != err { + if err != nil { return } if 1 > len(ret) { @@ -472,7 +472,7 @@ func GetNotebookHistory() (ret []*History, err error) { } historyNotebookConfs, err := filepath.Glob(historyDir + "/*-delete/*/.siyuan/conf.json") - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", historyDir, err) return } @@ -495,7 +495,7 @@ func GetNotebookHistory() (ret []*History, err error) { logging.LogErrorf("read notebook conf [%s] failed: %s", historyNotebookConf, readErr) continue } - if err = json.Unmarshal(data, &c); nil != err { + if err = json.Unmarshal(data, &c); err != nil { logging.LogErrorf("parse notebook conf [%s] failed: %s", historyNotebookConf, err) continue } @@ -523,19 +523,19 @@ func generateAssetsHistory() { } historyDir, err := GetHistoryDir(HistoryOpUpdate) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } for _, file := range assets { historyPath := filepath.Join(historyDir, "assets", strings.TrimPrefix(file, filepath.Join(util.DataDir, "assets"))) - if err = os.MkdirAll(filepath.Dir(historyPath), 0755); nil != err { + if err = os.MkdirAll(filepath.Dir(historyPath), 0755); err != nil { logging.LogErrorf("generate history failed: %s", err) return } - if err = filelock.Copy(file, historyPath); nil != err { + if err = filelock.Copy(file, historyPath); err != nil { logging.LogErrorf("copy file [%s] to [%s] failed: %s", file, historyPath, err) return } @@ -552,7 +552,7 @@ func (box *Box) generateDocHistory0() { } historyDir, err := GetHistoryDir(HistoryOpUpdate) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } @@ -560,7 +560,7 @@ func (box *Box) generateDocHistory0() { luteEngine := util.NewLute() for _, file := range files { historyPath := filepath.Join(historyDir, box.ID, strings.TrimPrefix(file, filepath.Join(util.DataDir, box.ID))) - if err = os.MkdirAll(filepath.Dir(historyPath), 0755); nil != err { + if err = os.MkdirAll(filepath.Dir(historyPath), 0755); err != nil { logging.LogErrorf("generate history failed: %s", err) return } @@ -605,7 +605,7 @@ func clearOutdatedHistoryDir(historyDir string) { } dirs, err := os.ReadDir(historyDir) - if nil != err { + if err != nil { logging.LogErrorf("clear history [%s] failed: %s", historyDir, err) return } @@ -615,7 +615,7 @@ func clearOutdatedHistoryDir(historyDir string) { var removes []string for _, dir := range dirs { dirInfo, err := dir.Info() - if nil != err { + if err != nil { logging.LogErrorf("read history dir [%s] failed: %s", dir.Name(), err) continue } @@ -624,7 +624,7 @@ func clearOutdatedHistoryDir(historyDir string) { } } for _, dir := range removes { - if err = os.RemoveAll(dir); nil != err { + if err = os.RemoveAll(dir); err != nil { logging.LogWarnf("remove history dir [%s] failed: %s", dir, err) continue } @@ -692,13 +692,13 @@ const ( func generateOpTypeHistory(tree *parse.Tree, opType string) { historyDir, err := GetHistoryDir(opType) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } historyPath := filepath.Join(historyDir, tree.Box, tree.Path) - if err = os.MkdirAll(filepath.Dir(historyPath), 0755); nil != err { + if err = os.MkdirAll(filepath.Dir(historyPath), 0755); err != nil { logging.LogErrorf("generate history failed: %s", err) return } @@ -723,7 +723,7 @@ func GetHistoryDir(suffix string) (ret string, err error) { func getHistoryDir(suffix string, t time.Time) (ret string, err error) { ret = filepath.Join(util.HistoryDir, t.Format("2006-01-02-150405")+"-"+suffix) - if err = os.MkdirAll(ret, 0755); nil != err { + if err = os.MkdirAll(ret, 0755); err != nil { logging.LogErrorf("make history dir failed: %s", err) return } @@ -737,7 +737,7 @@ func ReindexHistory() { func fullReindexHistory() { historyDirs, err := os.ReadDir(util.HistoryDir) - if nil != err { + if err != nil { logging.LogErrorf("read history dir [%s] failed: %s", util.HistoryDir, err) return } diff --git a/kernel/model/import.go b/kernel/model/import.go index a845070a0..cdfc183a6 100644 --- a/kernel/model/import.go +++ b/kernel/model/import.go @@ -109,14 +109,14 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { baseName = strings.TrimSuffix(baseName, ext) unzipPath := filepath.Join(filepath.Dir(zipPath), baseName+"-"+gulu.Rand.String(7)) err = gulu.Zip.Unzip(zipPath, unzipPath) - if nil != err { + if err != nil { return } defer os.RemoveAll(unzipPath) var syPaths []string filelock.Walk(unzipPath, func(path string, info fs.FileInfo, err error) error { - if nil != err { + if err != nil { return err } @@ -127,7 +127,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { }) entries, err := os.ReadDir(unzipPath) - if nil != err { + if err != nil { logging.LogErrorf("read unzip dir [%s] failed: %s", unzipPath, err) return } @@ -264,7 +264,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { } } - if err = os.Rename(oldPath, newPath); nil != err { + if err = os.Rename(oldPath, newPath); err != nil { logging.LogErrorf("rename av file from [%s] to [%s] failed: %s", oldPath, newPath, err) return } @@ -381,18 +381,18 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { if !util.UseSingleLineSave { buf := bytes.Buffer{} buf.Grow(1024 * 1024 * 2) - if err = json.Indent(&buf, data, "", "\t"); nil != err { + if err = json.Indent(&buf, data, "", "\t"); err != nil { return } data = buf.Bytes() } - if err = os.WriteFile(syPath, data, 0644); nil != err { + if err = os.WriteFile(syPath, data, 0644); err != nil { logging.LogErrorf("write .sy [%s] failed: %s", syPath, err) return } newSyPath := filepath.Join(filepath.Dir(syPath), tree.ID+".sy") - if err = filelock.Rename(syPath, newSyPath); nil != err { + if err = filelock.Rename(syPath, newSyPath); err != nil { logging.LogErrorf("rename .sy from [%s] to [%s] failed: %s", syPath, newSyPath, err) return } @@ -449,7 +449,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { // 重命名文件路径 renamePaths := map[string]string{} filelock.Walk(unzipRootPath, func(path string, info fs.FileInfo, err error) error { - if nil != err { + if err != nil { return err } @@ -492,7 +492,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { }) for i, oldPath := range oldPaths { newPath := renamePaths[oldPath] - if err = filelock.Rename(oldPath, newPath); nil != err { + if err = filelock.Rename(oldPath, newPath); err != nil { logging.LogErrorf("rename path from [%s] to [%s] failed: %s", oldPath, renamePaths[oldPath], err) return errors.New("rename path failed") } @@ -532,7 +532,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { dataAssets := filepath.Join(util.DataDir, "assets") for _, assets := range assetsDirs { if gulu.File.IsDir(assets) { - if err = filelock.Copy(assets, dataAssets); nil != err { + if err = filelock.Copy(assets, dataAssets); err != nil { logging.LogErrorf("copy assets from [%s] to [%s] failed: %s", assets, dataAssets, err) return } @@ -553,7 +553,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { } targetDir := filepath.Join(util.DataDir, boxID, baseTargetPath) - if err = os.MkdirAll(targetDir, 0755); nil != err { + if err = os.MkdirAll(targetDir, 0755); err != nil { return } @@ -576,7 +576,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { return nil }) - if err = filelock.Copy(unzipRootPath, targetDir); nil != err { + if err = filelock.Copy(unzipRootPath, targetDir); err != nil { logging.LogErrorf("copy data dir from [%s] to [%s] failed: %s", unzipRootPath, util.DataDir, err) err = errors.New("copy data failed") return @@ -588,7 +588,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) { p := strings.TrimPrefix(absPath, boxAbsPath) p = filepath.ToSlash(p) tree, err := filesys.LoadTree(boxID, p, luteEngine) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", treePath, err) continue } @@ -613,13 +613,13 @@ func ImportData(zipPath string) (err error) { baseName = strings.TrimSuffix(baseName, ext) unzipPath := filepath.Join(filepath.Dir(zipPath), baseName) err = gulu.Zip.Unzip(zipPath, unzipPath) - if nil != err { + if err != nil { return } defer os.RemoveAll(unzipPath) files, err := filepath.Glob(filepath.Join(unzipPath, "*/*.sy")) - if nil != err { + if err != nil { logging.LogErrorf("check data.zip failed: %s", err) return errors.New("check data.zip failed") } @@ -627,7 +627,7 @@ func ImportData(zipPath string) (err error) { return errors.New(Conf.Language(198)) } dirs, err := os.ReadDir(unzipPath) - if nil != err { + if err != nil { logging.LogErrorf("check data.zip failed: %s", err) return errors.New("check data.zip failed") } @@ -636,7 +636,7 @@ func ImportData(zipPath string) (err error) { } tmpDataPath := filepath.Join(unzipPath, dirs[0].Name()) - if err = filelock.Copy(tmpDataPath, util.DataDir); nil != err { + if err = filelock.Copy(tmpDataPath, util.DataDir); err != nil { logging.LogErrorf("copy data dir from [%s] to [%s] failed: %s", tmpDataPath, util.DataDir, err) err = errors.New("copy data failed") return @@ -827,7 +827,7 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) { name = filepath.Base(fullPath) name = util.AssetName(name) assetTargetPath := filepath.Join(assetDirPath, name) - if err = filelock.Copy(fullPath, assetTargetPath); nil != err { + if err = filelock.Copy(fullPath, assetTargetPath); err != nil { logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", fullPath, assetTargetPath, err) return ast.WalkContinue } @@ -864,7 +864,7 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) { targetPath = path.Join(targetPath, id+".sy") var data []byte data, err = os.ReadFile(localPath) - if nil != err { + if err != nil { return err } tree := parseStdMd(data) @@ -927,7 +927,7 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) { name := filepath.Base(absolutePath) name = util.AssetName(name) assetTargetPath := filepath.Join(assetDirPath, name) - if err = filelock.Copy(absolutePath, assetTargetPath); nil != err { + if err = filelock.Copy(absolutePath, assetTargetPath); err != nil { logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", absolutePath, assetTargetPath, err) return ast.WalkContinue } @@ -1053,7 +1053,7 @@ func processBase64Img(n *ast.Node, dest string, assetDirPath string, err error) tmpFile.Close() assetTargetPath := filepath.Join(assetDirPath, name) - if err = filelock.Copy(tmp, assetTargetPath); nil != err { + if err = filelock.Copy(tmp, assetTargetPath); err != nil { logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", tmp, assetTargetPath, err) return } diff --git a/kernel/model/index.go b/kernel/model/index.go index b32fae6d8..fd0053097 100644 --- a/kernel/model/index.go +++ b/kernel/model/index.go @@ -83,7 +83,7 @@ func RemoveIndexes(paths []string) { func listSyFiles(dir string) (ret []string) { dirPath := filepath.Join(util.DataDir, dir) err := filelock.Walk(dirPath, func(path string, d fs.FileInfo, err error) error { - if nil != err { + if err != nil { logging.LogWarnf("walk dir [%s] failed: %s", dirPath, err) return err } @@ -98,7 +98,7 @@ func listSyFiles(dir string) (ret []string) { } return nil }) - if nil != err { + if err != nil { logging.LogWarnf("walk dir [%s] failed: %s", dirPath, err) } return @@ -169,7 +169,7 @@ func index(boxID string) { i := treeCount lock.Unlock() tree, err := filesys.LoadTree(box.ID, file.path, luteEngine) - if nil != err { + if err != nil { logging.LogErrorf("read box [%s] tree [%s] failed: %s", box.ID, file.path, err) return } diff --git a/kernel/model/index_fix.go b/kernel/model/index_fix.go index d5e76354b..967a57db2 100644 --- a/kernel/model/index_fix.go +++ b/kernel/model/index_fix.go @@ -269,7 +269,7 @@ func recreateTree(tree *parse.Tree, absPath string) { treenode.RemoveBlockTreesByRootID(tree.ID) resetTree(tree, "", true) - if err := filesys.WriteTree(tree); nil != err { + if err := filesys.WriteTree(tree); err != nil { logging.LogWarnf("write tree [%s] failed: %s", tree.Path, err) return } @@ -284,7 +284,7 @@ func recreateTree(tree *parse.Tree, absPath string) { } } - if err := filelock.Remove(absPath); nil != err { + if err := filelock.Remove(absPath); err != nil { logging.LogWarnf("remove [%s] failed: %s", absPath, err) return } @@ -369,7 +369,7 @@ func fixDatabaseIndexByBlockTree() { util.PushStatusBar(fmt.Sprintf(Conf.Language(58), 4, 5)) rootUpdatedMap := treenode.GetRootUpdated() dbRootUpdatedMap, err := sql.GetRootUpdated() - if nil == err { + if err == nil { reindexTreeByUpdated(rootUpdatedMap, dbRootUpdatedMap) } } @@ -445,7 +445,7 @@ func reindexTreeByUpdated(rootUpdatedMap, dbRootUpdatedMap map[string]string) { func reindexTreeByPath(box, p string, i, size int, luteEngine *lute.Lute) { tree, err := filesys.LoadTree(box, p, luteEngine) - if nil != err { + if err != nil { return } @@ -460,7 +460,7 @@ func reindexTree(rootID string, i, size int, luteEngine *lute.Lute) { } tree, err := filesys.LoadTree(root.BoxID, root.Path, luteEngine) - if nil != err { + if err != nil { if os.IsNotExist(err) { // 文件系统上没有找到该 .sy 文件,则订正块树 treenode.RemoveBlockTreesByRootID(rootID) diff --git a/kernel/model/listitem.go b/kernel/model/listitem.go index 9c8325372..db82b02f2 100644 --- a/kernel/model/listitem.go +++ b/kernel/model/listitem.go @@ -60,7 +60,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath string) (srcRootBlockID newTargetPath = path.Join(toFolder, srcListItemID+".sy") if !box.Exist(toFolder) { - if err = box.MkdirAll(toFolder); nil != err { + if err = box.MkdirAll(toFolder); err != nil { return } } @@ -97,7 +97,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath string) (srcRootBlockID srcTree.Root.AppendChild(treenode.NewParagraph()) } treenode.RemoveBlockTreesByRootID(srcTree.ID) - if err = indexWriteTreeUpsertQueue(srcTree); nil != err { + if err = indexWriteTreeUpsertQueue(srcTree); err != nil { return "", "", err } @@ -105,7 +105,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath string) (srcRootBlockID newTree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr()) newTree.Root.Spec = "1" box.addMinSort(path.Dir(newTargetPath), newTree.ID) - if err = indexWriteTreeUpsertQueue(newTree); nil != err { + if err = indexWriteTreeUpsertQueue(newTree); err != nil { return "", "", err } IncSync() diff --git a/kernel/model/mount.go b/kernel/model/mount.go index 1ec00f178..7c83fcdf1 100644 --- a/kernel/model/mount.go +++ b/kernel/model/mount.go @@ -52,7 +52,7 @@ func CreateBox(name string) (id string, err error) { id = ast.NewNodeID() boxLocalPath := filepath.Join(util.DataDir, id) err = os.MkdirAll(boxLocalPath, 0755) - if nil != err { + if err != nil { return } @@ -121,13 +121,13 @@ func RemoveBox(boxID string) (err error) { if !isUserGuide { var historyDir string historyDir, err = GetHistoryDir(HistoryOpDelete) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } p := strings.TrimPrefix(localPath, util.DataDir) historyPath := filepath.Join(historyDir, p) - if err = filelock.Copy(localPath, historyPath); nil != err { + if err = filelock.Copy(localPath, historyPath); err != nil { logging.LogErrorf("gen sync history failed: %s", err) return } @@ -136,7 +136,7 @@ func RemoveBox(boxID string) (err error) { } unmount0(boxID) - if err = filelock.Remove(localPath); nil != err { + if err = filelock.Remove(localPath); err != nil { return } IncSync() @@ -191,18 +191,18 @@ func Mount(boxID string) (alreadyMount bool, err error) { reMountGuide = true } - if err = filelock.Remove(localPath); nil != err { + if err = filelock.Remove(localPath); err != nil { return } p := filepath.Join(util.WorkingDir, "guide", boxID) - if err = filelock.Copy(p, localPath); nil != err { + if err = filelock.Copy(p, localPath); err != nil { return } avDirPath := filepath.Join(util.WorkingDir, "guide", boxID, "storage", "av") if filelock.IsExist(avDirPath) { - if err = filelock.Copy(avDirPath, filepath.Join(util.DataDir, "storage", "av")); nil != err { + if err = filelock.Copy(avDirPath, filepath.Join(util.DataDir, "storage", "av")); err != nil { return } } diff --git a/kernel/model/outline.go b/kernel/model/outline.go index b72eea267..f68a1ee9e 100644 --- a/kernel/model/outline.go +++ b/kernel/model/outline.go @@ -32,7 +32,7 @@ func (tx *Transaction) doMoveOutlineHeading(operation *Operation) (ret *TxErr) { parentID := operation.ParentID tree, err := tx.loadTree(headingID) - if nil != err { + if err != nil { return &TxErr{code: TxErrCodeBlockNotFound, id: headingID} } operation.RetData = tree.Root.ID @@ -201,7 +201,7 @@ func (tx *Transaction) doMoveOutlineHeading(operation *Operation) (ret *TxErr) { } } - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return } return diff --git a/kernel/model/path.go b/kernel/model/path.go index ee2f51915..efd518f28 100644 --- a/kernel/model/path.go +++ b/kernel/model/path.go @@ -49,7 +49,7 @@ func createDocsByHPath(boxID, hPath, content, parentID, id string) (retID string if nil != preferredParent && preferredParent.ID == parentID { // 如果父文档存在且 ID 一致,则直接在父文档下创建 p := strings.TrimSuffix(preferredParent.Path, ".sy") + "/" + id + ".sy" - if _, err = createDoc(boxID, p, name, content); nil != err { + if _, err = createDoc(boxID, p, name, content); err != nil { logging.LogErrorf("create doc [%s] failed: %s", p, err) } return @@ -101,18 +101,18 @@ func createDocsByHPath(boxID, hPath, content, parentID, id string) (retID string pathBuilder.WriteString(rootID) docP := pathBuilder.String() + ".sy" if isNotLast { - if _, err = createDoc(boxID, docP, part, ""); nil != err { + if _, err = createDoc(boxID, docP, part, ""); err != nil { return } } else { - if _, err = createDoc(boxID, docP, part, content); nil != err { + if _, err = createDoc(boxID, docP, part, content); err != nil { return } } if isNotLast { dirPath := filepath.Join(util.DataDir, boxID, pathBuilder.String()) - if err = os.MkdirAll(dirPath, 0755); nil != err { + if err = os.MkdirAll(dirPath, 0755); err != nil { logging.LogErrorf("mkdir [%s] failed: %s", dirPath, err) return } diff --git a/kernel/model/plugin.go b/kernel/model/plugin.go index 1a6635de6..1a1a71828 100644 --- a/kernel/model/plugin.go +++ b/kernel/model/plugin.go @@ -113,7 +113,7 @@ func loadCode(petal *Petal) { } data, err := filelock.ReadFile(jsPath) - if nil != err { + if err != nil { logging.LogErrorf("read plugin [%s] js failed: %s", petal.Name, err) return } @@ -122,7 +122,7 @@ func loadCode(petal *Petal) { cssPath := filepath.Join(pluginDir, "index.css") if filelock.IsExist(cssPath) { data, err = filelock.ReadFile(cssPath) - if nil != err { + if err != nil { logging.LogErrorf("read plugin [%s] css failed: %s", petal.Name, err) } else { petal.CSS = string(data) @@ -167,11 +167,11 @@ func loadCode(petal *Petal) { } data, err = filelock.ReadFile(filepath.Join(i18nDir, preferredLang)) - if nil != err { + if err != nil { logging.LogErrorf("read plugin [%s] i18n failed: %s", petal.Name, err) } else { petal.I18n = map[string]interface{}{} - if err = gulu.JSON.UnmarshalJSON(data, &petal.I18n); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &petal.I18n); err != nil { logging.LogErrorf("unmarshal plugin [%s] i18n failed: %s", petal.Name, err) } } @@ -188,11 +188,11 @@ func savePetals(petals []*Petal) { petalDir := filepath.Join(util.DataDir, "storage", "petal") confPath := filepath.Join(petalDir, "petals.json") data, err := gulu.JSON.MarshalIndentJSON(petals, "", "\t") - if nil != err { + if err != nil { logging.LogErrorf("marshal petals failed: %s", err) return } - if err = filelock.WriteFile(confPath, data); nil != err { + if err = filelock.WriteFile(confPath, data); err != nil { logging.LogErrorf("write petals [%s] failed: %s", confPath, err) return } @@ -204,7 +204,7 @@ func getPetals() (ret []*Petal) { ret = []*Petal{} petalDir := filepath.Join(util.DataDir, "storage", "petal") - if err := os.MkdirAll(petalDir, 0755); nil != err { + if err := os.MkdirAll(petalDir, 0755); err != nil { logging.LogErrorf("create petal dir [%s] failed: %s", petalDir, err) return } @@ -212,11 +212,11 @@ func getPetals() (ret []*Petal) { confPath := filepath.Join(petalDir, "petals.json") if !filelock.IsExist(confPath) { data, err := gulu.JSON.MarshalIndentJSON(ret, "", "\t") - if nil != err { + if err != nil { logging.LogErrorf("marshal petals failed: %s", err) return } - if err = filelock.WriteFile(confPath, data); nil != err { + if err = filelock.WriteFile(confPath, data); err != nil { logging.LogErrorf("write petals [%s] failed: %s", confPath, err) return } @@ -224,12 +224,12 @@ func getPetals() (ret []*Petal) { } data, err := filelock.ReadFile(confPath) - if nil != err { + if err != nil { logging.LogErrorf("read petal file [%s] failed: %s", confPath, err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("unmarshal petals failed: %s", err) return } diff --git a/kernel/model/process.go b/kernel/model/process.go index ac618231f..6cb37bb5d 100644 --- a/kernel/model/process.go +++ b/kernel/model/process.go @@ -87,13 +87,13 @@ var uiProcNames = []string{"siyuan", "electron"} func getAttachedUIProcCount() (ret int) { util.UIProcessIDs.Range(func(uiProcIDArg, _ interface{}) bool { uiProcID, err := strconv.Atoi(uiProcIDArg.(string)) - if nil != err { + if err != nil { logging.LogErrorf("invalid UI proc ID [%s]: %s", uiProcIDArg, err) return true } proc, err := goPS.FindProcess(uiProcID) - if nil != err { + if err != nil { logging.LogErrorf("find UI proc [%d] failed: %s", uiProcID, err) return true } diff --git a/kernel/model/render.go b/kernel/model/render.go index 2b164d6e0..0bd31f488 100644 --- a/kernel/model/render.go +++ b/kernel/model/render.go @@ -282,7 +282,7 @@ func renderBlockMarkdownR(id string, rendered *[]string) (ret []*ast.Node) { var err error var t *parse.Tree - if t, err = LoadTreeByBlockID(b.ID); nil != err { + if t, err = LoadTreeByBlockID(b.ID); err != nil { return } node := treenode.GetNodeInTree(t, b.ID) diff --git a/kernel/model/repository.go b/kernel/model/repository.go index 4e32bb298..ce521281b 100644 --- a/kernel/model/repository.go +++ b/kernel/model/repository.go @@ -65,12 +65,12 @@ func GetRepoFile(fileID string) (ret []byte, p string, err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } file, err := repo.GetFile(fileID) - if nil != err { + if err != nil { return } @@ -86,17 +86,17 @@ func OpenRepoSnapshotDoc(fileID string) (content string, isProtyleDoc bool, upda } repo, err := newRepository() - if nil != err { + if err != nil { return } file, err := repo.GetFile(fileID) - if nil != err { + if err != nil { return } data, err := repo.OpenFile(file) - if nil != err { + if err != nil { return } @@ -106,7 +106,7 @@ func OpenRepoSnapshotDoc(fileID string) (content string, isProtyleDoc bool, upda luteEngine := NewLute() var snapshotTree *parse.Tree isProtyleDoc, snapshotTree, err = parseTreeInSnapshot(data, luteEngine) - if nil != err { + if err != nil { logging.LogErrorf("parse tree from snapshot file [%s] failed", fileID) return } @@ -204,12 +204,12 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } diff, err := repo.DiffIndex(left, right) - if nil != err { + if err != nil { return } @@ -300,7 +300,7 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) { func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lute) (title string, err error) { file, err := repo.GetFile(fileID) - if nil != err { + if err != nil { logging.LogErrorf("get file [%s] failed: %s", fileID, err) return } @@ -309,14 +309,14 @@ func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lut if strings.HasSuffix(file.Path, ".sy") { var data []byte data, err = repo.OpenFile(file) - if nil != err { + if err != nil { logging.LogErrorf("open file [%s] failed: %s", fileID, err) return } var tree *parse.Tree tree, err = filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions) - if nil != err { + if err != nil { logging.LogErrorf("parse file [%s] failed: %s", fileID, err) return } @@ -329,7 +329,7 @@ func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lut func parseTreeInSnapshot(data []byte, luteEngine *lute.Lute) (isProtyleDoc bool, tree *parse.Tree, err error) { isProtyleDoc = 1024*1024*1 <= len(data) tree, err = filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions) - if nil != err { + if err != nil { return } return @@ -353,12 +353,12 @@ func GetRepoSnapshots(page int) (ret []*Snapshot, pageCount, totalCount int, err } repo, err := newRepository() - if nil != err { + if err != nil { return } logs, pageCount, totalCount, err := repo.GetIndexLogs(page, 32) - if nil != err { + if err != nil { if dejavu.ErrNotFoundIndex == err { logs = []*dejavu.Log{} err = nil @@ -435,7 +435,7 @@ func ImportRepoKey(base64Key string) (retKey string, err error) { } key, err := base64.StdEncoding.DecodeString(retKey) - if nil != err { + if err != nil { logging.LogErrorf("import data repo key failed: %s", err) return "", errors.New(Conf.Language(157)) } @@ -446,10 +446,10 @@ func ImportRepoKey(base64Key string) (retKey string, err error) { Conf.Repo.Key = key Conf.Save() - if err = os.RemoveAll(Conf.Repo.GetSaveDir()); nil != err { + if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil { return } - if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); nil != err { + if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil { return } @@ -462,11 +462,11 @@ func ResetRepo() (err error) { msgId := util.PushMsg(Conf.Language(144), 1000*60) repo, err := newRepository() - if nil != err { + if err != nil { return } - if err = repo.Reset(); nil != err { + if err = repo.Reset(); err != nil { logging.LogErrorf("reset data repo failed: %s", err) return } @@ -490,12 +490,12 @@ func PurgeCloud() (err error) { defer util.PushClearProgress() repo, err := newRepository() - if nil != err { + if err != nil { return } stat, err := repo.PurgeCloud() - if nil != err { + if err != nil { return } @@ -503,7 +503,7 @@ func PurgeCloud() (err error) { deletedObjects := stat.Objects deletedSize := humanize.BytesCustomCeil(uint64(stat.Size), 2) msg = fmt.Sprintf(Conf.Language(232), deletedIndexes, deletedObjects, deletedSize) - util.PushMsg(msg, 5000) + util.PushMsg(msg, 7000) return } @@ -513,12 +513,12 @@ func PurgeRepo() (err error) { defer util.PushClearProgress() repo, err := newRepository() - if nil != err { + if err != nil { return } stat, err := repo.Purge() - if nil != err { + if err != nil { return } @@ -526,7 +526,7 @@ func PurgeRepo() (err error) { deletedObjects := stat.Objects deletedSize := humanize.BytesCustomCeil(uint64(stat.Size), 2) msg = fmt.Sprintf(Conf.Language(203), deletedIndexes, deletedObjects, deletedSize) - util.PushMsg(msg, 5000) + util.PushMsg(msg, 7000) return } @@ -538,10 +538,10 @@ func InitRepoKeyFromPassphrase(passphrase string) (err error) { } util.PushMsg(Conf.Language(136), 3000) - if err = os.RemoveAll(Conf.Repo.GetSaveDir()); nil != err { + if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil { return } - if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); nil != err { + if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil { return } @@ -554,7 +554,7 @@ func InitRepoKeyFromPassphrase(passphrase string) (err error) { } else { salt := fmt.Sprintf("%x", sha256.Sum256([]byte(passphrase)))[:16] key, err = encryption.KDF(passphrase, salt) - if nil != err { + if err != nil { logging.LogErrorf("init data repo key failed: %s", err) return } @@ -570,29 +570,29 @@ func InitRepoKeyFromPassphrase(passphrase string) (err error) { func InitRepoKey() (err error) { util.PushMsg(Conf.Language(136), 3000) - if err = os.RemoveAll(Conf.Repo.GetSaveDir()); nil != err { + if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil { return } - if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); nil != err { + if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil { return } randomBytes := make([]byte, 16) _, err = rand.Read(randomBytes) - if nil != err { + if err != nil { return } password := string(randomBytes) randomBytes = make([]byte, 16) _, err = rand.Read(randomBytes) - if nil != err { + if err != nil { logging.LogErrorf("init data repo key failed: %s", err) return } salt := string(randomBytes) key, err := encryption.KDF(password, salt) - if nil != err { + if err != nil { logging.LogErrorf("init data repo key failed: %s", err) return } @@ -624,7 +624,7 @@ func checkoutRepo(id string) { } repo, err := newRepository() - if nil != err { + if err != nil { logging.LogErrorf("new repository failed: %s", err) util.PushErrMsg(Conf.Language(141), 7000) return @@ -643,7 +643,7 @@ func checkoutRepo(id string) { Conf.Save() _, _, err = repo.Checkout(id, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress}) - if nil != err { + if err != nil { logging.LogErrorf("checkout repository failed: %s", err) util.PushClearProgress() util.PushErrMsg(Conf.Language(141), 7000) @@ -674,7 +674,7 @@ func DownloadCloudSnapshot(tag, id string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } @@ -700,7 +700,7 @@ func DownloadCloudSnapshot(tag, id string) (err error) { } else { downloadFileCount, downloadChunkCount, downloadBytes, err = repo.DownloadTagIndex(tag, id, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress}) } - if nil != err { + if err != nil { return } msg := fmt.Sprintf(Conf.Language(153), downloadFileCount, downloadChunkCount, humanize.BytesCustomCeil(uint64(downloadBytes), 2)) @@ -716,7 +716,7 @@ func UploadCloudSnapshot(tag, id string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } @@ -736,7 +736,7 @@ func UploadCloudSnapshot(tag, id string) (err error) { util.PushEndlessProgress(Conf.Language(116)) defer util.PushClearProgress() uploadFileCount, uploadChunkCount, uploadBytes, err := repo.UploadTagIndex(tag, id, map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress}) - if nil != err { + if err != nil { if errors.Is(err, dejavu.ErrCloudBackupCountExceeded) { err = fmt.Errorf(Conf.Language(84), Conf.Language(154)) return @@ -762,7 +762,7 @@ func RemoveCloudRepoTag(tag string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } @@ -780,7 +780,7 @@ func RemoveCloudRepoTag(tag string) (err error) { } err = repo.RemoveCloudRepoTag(tag) - if nil != err { + if err != nil { return } return @@ -794,7 +794,7 @@ func GetCloudRepoTagSnapshots() (ret []*dejavu.Log, err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } @@ -812,7 +812,7 @@ func GetCloudRepoTagSnapshots() (ret []*dejavu.Log, err error) { } logs, err := repo.GetCloudRepoTagLogs(map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}) - if nil != err { + if err != nil { return } ret = logs @@ -830,7 +830,7 @@ func GetCloudRepoSnapshots(page int) (ret []*dejavu.Log, pageCount, totalCount i } repo, err := newRepository() - if nil != err { + if err != nil { return } @@ -852,7 +852,7 @@ func GetCloudRepoSnapshots(page int) (ret []*dejavu.Log, pageCount, totalCount i } logs, pageCount, totalCount, err := repo.GetCloudRepoLogs(page) - if nil != err { + if err != nil { return } ret = logs @@ -870,12 +870,12 @@ func GetTagSnapshots() (ret []*Snapshot, err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } logs, err := repo.GetTagLogs() - if nil != err { + if err != nil { return } ret = buildSnapshots(logs) @@ -892,7 +892,7 @@ func RemoveTagSnapshot(tag string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } @@ -919,16 +919,16 @@ func TagSnapshot(id, name string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } index, err := repo.GetIndex(id) - if nil != err { + if err != nil { return } - if err = repo.AddTag(index.ID, name); nil != err { + if err = repo.AddTag(index.ID, name); err != nil { msg := fmt.Sprintf("Add tag to data snapshot [%s] failed: %s", index.ID, err) util.PushStatusBar(msg) return @@ -950,7 +950,7 @@ func IndexRepo(memo string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } @@ -962,7 +962,7 @@ func IndexRepo(memo string) (err error) { index, err := repo.Index(memo, map[string]interface{}{ eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress, }) - if nil != err { + if err != nil { util.PushStatusBar("Index data repo failed: " + html.EscapeString(err.Error())) return } @@ -1011,7 +1011,7 @@ func syncRepoDownload() (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { planSyncAfter(fixSyncInterval) msg := fmt.Sprintf("sync repo failed: %s", err) @@ -1024,7 +1024,7 @@ func syncRepoDownload() (err error) { logging.LogInfof("downloading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "d", true) start := time.Now() _, _, err = indexRepoBeforeCloudSync(repo) - if nil != err { + if err != nil { planSyncAfter(fixSyncInterval) logging.LogErrorf("sync data repo download failed: %s", err) @@ -1039,7 +1039,7 @@ func syncRepoDownload() (err error) { syncContext := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar} mergeResult, trafficStat, err := repo.SyncDownload(syncContext) elapsed := time.Since(start) - if nil != err { + if err != nil { planSyncAfter(fixSyncInterval) logging.LogErrorf("sync data repo download failed: %s", err) @@ -1082,7 +1082,7 @@ func syncRepoUpload() (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { planSyncAfter(fixSyncInterval) msg := fmt.Sprintf("sync repo failed: %s", err) @@ -1095,7 +1095,7 @@ func syncRepoUpload() (err error) { logging.LogInfof("uploading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "u", true) start := time.Now() _, _, err = indexRepoBeforeCloudSync(repo) - if nil != err { + if err != nil { planSyncAfter(fixSyncInterval) logging.LogErrorf("sync data repo upload failed: %s", err) @@ -1110,7 +1110,7 @@ func syncRepoUpload() (err error) { syncContext := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar} trafficStat, err := repo.SyncUpload(syncContext) elapsed := time.Since(start) - if nil != err { + if err != nil { planSyncAfter(fixSyncInterval) logging.LogErrorf("sync data repo upload failed: %s", err) @@ -1156,7 +1156,7 @@ func bootSyncRepo() (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { autoSyncErrCount++ planSyncAfter(fixSyncInterval) @@ -1171,7 +1171,7 @@ func bootSyncRepo() (err error) { start := time.Now() _, _, err = indexRepoBeforeCloudSync(repo) - if nil != err { + if err != nil { autoSyncErrCount++ planSyncAfter(fixSyncInterval) @@ -1217,7 +1217,7 @@ func bootSyncRepo() (err error) { elapsed := time.Since(start) logging.LogInfof("boot get sync cloud files elapsed [%.2fs]", elapsed.Seconds()) - if nil != err { + if err != nil { autoSyncErrCount++ planSyncAfter(fixSyncInterval) @@ -1243,7 +1243,7 @@ func bootSyncRepo() (err error) { go func() { _, syncErr := syncRepo(false, false) isBootSyncing.Store(false) - if nil != err { + if err != nil { logging.LogErrorf("boot background sync repo failed: %s", syncErr) return } @@ -1267,7 +1267,7 @@ func syncRepo(exit, byHand bool) (dataChanged bool, err error) { } repo, err := newRepository() - if nil != err { + if err != nil { autoSyncErrCount++ planSyncAfter(fixSyncInterval) @@ -1281,7 +1281,7 @@ func syncRepo(exit, byHand bool) (dataChanged bool, err error) { logging.LogInfof("syncing data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "a", byHand) start := time.Now() beforeIndex, afterIndex, err := indexRepoBeforeCloudSync(repo) - if nil != err { + if err != nil { autoSyncErrCount++ planSyncAfter(fixSyncInterval) @@ -1302,7 +1302,7 @@ func syncRepo(exit, byHand bool) (dataChanged bool, err error) { syncContext := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar} mergeResult, trafficStat, err := repo.Sync(syncContext) elapsed := time.Since(start) - if nil != err { + if err != nil { autoSyncErrCount++ planSyncAfter(fixSyncInterval) @@ -1610,7 +1610,7 @@ func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entit afterIndex, err = repo.Index("[Sync] Cloud sync", map[string]interface{}{ eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar, }) - if nil != err { + if err != nil { logging.LogErrorf("index data repo before cloud sync failed: %s", err) return } @@ -1619,7 +1619,7 @@ func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entit if nil == beforeIndex || beforeIndex.ID != afterIndex.ID { // 对新创建的快照需要更新备注,加入耗时统计 afterIndex.Memo = fmt.Sprintf("[Sync] Cloud sync, completed in %.2fs", elapsed.Seconds()) - if err = repo.PutIndex(afterIndex); nil != err { + if err = repo.PutIndex(afterIndex); err != nil { util.PushStatusBar("Save data snapshot for cloud sync failed") logging.LogErrorf("put index into data repo before cloud sync failed: %s", err) return @@ -1651,7 +1651,7 @@ func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entit func newRepository() (ret *dejavu.Repo, err error) { cloudConf, err := buildCloudConf() - if nil != err { + if err != nil { return } @@ -1680,7 +1680,7 @@ func newRepository() (ret *dejavu.Repo, err error) { ignoreLines := getSyncIgnoreLines() ignoreLines = append(ignoreLines, "/.siyuan/conf.json") // 忽略旧版同步配置 ret, err = dejavu.NewRepo(util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir, Conf.System.ID, Conf.System.Name, Conf.System.OS, Conf.Repo.Key, ignoreLines, cloudRepo) - if nil != err { + if err != nil { logging.LogErrorf("init data repo failed: %s", err) return } @@ -1978,7 +1978,7 @@ type Sync struct { func GetCloudSpace() (s *Sync, b *Backup, hSize, hAssetSize, hTotalSize, hExchangeSize, hTrafficUploadSize, hTrafficDownloadSize, hTrafficAPIGet, hTrafficAPIPut string, err error) { stat, err := getCloudSpace() - if nil != err { + if err != nil { err = errors.New(Conf.Language(30) + " " + err.Error()) return } @@ -2027,12 +2027,12 @@ func GetCloudSpace() (s *Sync, b *Backup, hSize, hAssetSize, hTotalSize, hExchan func getCloudSpace() (stat *cloud.Stat, err error) { repo, err := newRepository() - if nil != err { + if err != nil { return } stat, err = repo.GetCloudRepoStat() - if nil != err { + if err != nil { logging.LogErrorf("get cloud repo stat failed: %s", err) return } diff --git a/kernel/model/search.go b/kernel/model/search.go index bebd9d3f7..19e152109 100644 --- a/kernel/model/search.go +++ b/kernel/model/search.go @@ -56,7 +56,7 @@ func ListInvalidBlockRefs(page, pageSize int) (ret []*Block, matchedBlockCount, blockMap := map[string]bool{} var invalidBlockIDs []string notebooks, err := ListNotebooks() - if nil != err { + if err != nil { return } luteEngine := util.NewLute() @@ -469,7 +469,7 @@ func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids cachedTrees := map[string]*parse.Tree{} historyDir, err := getHistoryDir(HistoryOpReplace, time.Now()) - if nil != err { + if err != nil { logging.LogErrorf("get history dir failed: %s", err) return } @@ -499,7 +499,7 @@ func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids } historyPath := filepath.Join(historyDir, tree.Box, tree.Path) - if err = os.MkdirAll(filepath.Dir(historyPath), 0755); nil != err { + if err = os.MkdirAll(filepath.Dir(historyPath), 0755); err != nil { logging.LogErrorf("generate history failed: %s", err) return } @@ -773,7 +773,7 @@ func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids unlink.Unlink() } - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { return } } @@ -1069,7 +1069,7 @@ func buildOrderBy(query string, method, orderBy int) string { func buildTypeFilter(types map[string]bool) string { s := conf.NewSearch() - if err := copier.Copy(s, Conf.Search); nil != err { + if err := copier.Copy(s, Conf.Search); err != nil { logging.LogErrorf("copy search conf failed: %s", err) } if nil != types { @@ -1141,7 +1141,7 @@ func searchBySQL(stmt string, beforeLen, page, pageSize int) (ret []*Block, matc func removeLimitClause(stmt string) string { parsedStmt, err := sqlparser.Parse(stmt) - if nil != err { + if err != nil { return stmt } @@ -1728,17 +1728,17 @@ func getSearchIgnoreLines() (ret []string) { searchIgnorePath := filepath.Join(util.DataDir, ".siyuan", "searchignore") err := os.MkdirAll(filepath.Dir(searchIgnorePath), 0755) - if nil != err { + if err != nil { return } if !gulu.File.IsExist(searchIgnorePath) { - if err = gulu.File.WriteFileSafer(searchIgnorePath, nil, 0644); nil != err { + if err = gulu.File.WriteFileSafer(searchIgnorePath, nil, 0644); err != nil { logging.LogErrorf("create searchignore [%s] failed: %s", searchIgnorePath, err) return } } data, err := os.ReadFile(searchIgnorePath) - if nil != err { + if err != nil { logging.LogErrorf("read searchignore [%s] failed: %s", searchIgnorePath, err) return } @@ -1778,17 +1778,17 @@ func getRefSearchIgnoreLines() (ret []string) { searchIgnorePath := filepath.Join(util.DataDir, ".siyuan", "refsearchignore") err := os.MkdirAll(filepath.Dir(searchIgnorePath), 0755) - if nil != err { + if err != nil { return } if !gulu.File.IsExist(searchIgnorePath) { - if err = gulu.File.WriteFileSafer(searchIgnorePath, nil, 0644); nil != err { + if err = gulu.File.WriteFileSafer(searchIgnorePath, nil, 0644); err != nil { logging.LogErrorf("create refsearchignore [%s] failed: %s", searchIgnorePath, err) return } } data, err := os.ReadFile(searchIgnorePath) - if nil != err { + if err != nil { logging.LogErrorf("read refsearchignore [%s] failed: %s", searchIgnorePath, err) return } diff --git a/kernel/model/session.go b/kernel/model/session.go index 4a78cee7d..461d83983 100644 --- a/kernel/model/session.go +++ b/kernel/model/session.go @@ -47,7 +47,7 @@ func LogoutAuth(c *gin.Context) { session := util.GetSession(c) util.RemoveWorkspaceSession(session) - if err := session.Save(c); nil != err { + if err := session.Save(c); err != nil { logging.LogErrorf("saves session failed: " + err.Error()) ret.Code = -1 ret.Msg = "save session failed" @@ -102,7 +102,7 @@ func LoginAuth(c *gin.Context) { ret.Code = 1 // 需要渲染验证码 } - if err := session.Save(c); nil != err { + if err := session.Save(c); err != nil { logging.LogErrorf("save session failed: " + err.Error()) c.Status(http.StatusInternalServerError) return @@ -114,7 +114,7 @@ func LoginAuth(c *gin.Context) { util.WrongAuthCount = 0 workspaceSession.Captcha = gulu.Rand.String(7) logging.LogInfof("auth success [ip=%s]", util.GetRemoteAddr(c.Request)) - if err := session.Save(c); nil != err { + if err := session.Save(c); err != nil { logging.LogErrorf("save session failed: " + err.Error()) c.Status(http.StatusInternalServerError) return @@ -128,7 +128,7 @@ func GetCaptcha(c *gin.Context) { options.CurveNumber = 0 options.BackgroundColor = color.White }) - if nil != err { + if err != nil { logging.LogErrorf("generates captcha failed: " + err.Error()) c.Status(http.StatusInternalServerError) return @@ -137,13 +137,13 @@ func GetCaptcha(c *gin.Context) { session := util.GetSession(c) workspaceSession := util.GetWorkspaceSession(session) workspaceSession.Captcha = img.Text - if err = session.Save(c); nil != err { + if err = session.Save(c); err != nil { logging.LogErrorf("save session failed: " + err.Error()) c.Status(http.StatusInternalServerError) return } - if err = img.WriteImage(c.Writer); nil != err { + if err = img.WriteImage(c.Writer); err != nil { logging.LogErrorf("writes captcha image failed: " + err.Error()) c.Status(http.StatusInternalServerError) return @@ -369,7 +369,7 @@ func Timing(c *gin.Context) { timing := 15 * 1000 if timingEnv := os.Getenv("SIYUAN_PERFORMANCE_TIMING"); "" != timingEnv { val, err := strconv.Atoi(timingEnv) - if nil == err { + if err == nil { timing = val } } diff --git a/kernel/model/snippet.go b/kernel/model/snippet.go index b5dc24421..98449bd45 100644 --- a/kernel/model/snippet.go +++ b/kernel/model/snippet.go @@ -36,7 +36,7 @@ func RemoveSnippet(id string) (ret *conf.Snippet, err error) { defer snippetsLock.Unlock() snippets, err := loadSnippets() - if nil != err { + if err != nil { return } @@ -73,12 +73,12 @@ func loadSnippets() (ret []*conf.Snippet, err error) { } data, err := filelock.ReadFile(confPath) - if nil != err { + if err != nil { logging.LogErrorf("load js snippets failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("unmarshal js snippets failed: %s", err) return } @@ -98,12 +98,12 @@ func loadSnippets() (ret []*conf.Snippet, err error) { func writeSnippetsConf(snippets []*conf.Snippet) (err error) { data, err := gulu.JSON.MarshalIndentJSON(snippets, "", " ") - if nil != err { + if err != nil { logging.LogErrorf("marshal snippets failed: %s", err) return } - if err = os.MkdirAll(util.SnippetsPath, 0755); nil != err { + if err = os.MkdirAll(util.SnippetsPath, 0755); err != nil { return } diff --git a/kernel/model/storage.go b/kernel/model/storage.go index d0836a5a8..b69d20744 100644 --- a/kernel/model/storage.go +++ b/kernel/model/storage.go @@ -44,7 +44,7 @@ func RemoveRecentDoc(ids []string) { defer recentDocLock.Unlock() recentDocs, err := getRecentDocs() - if nil != err { + if err != nil { return } @@ -57,7 +57,7 @@ func RemoveRecentDoc(ids []string) { } err = setRecentDocs(recentDocs) - if nil != err { + if err != nil { return } return @@ -74,7 +74,7 @@ func setRecentDocByTree(tree *parse.Tree) { defer recentDocLock.Unlock() recentDocs, err := getRecentDocs() - if nil != err { + if err != nil { return } @@ -102,20 +102,20 @@ func GetRecentDocs() (ret []*RecentDoc, err error) { func setRecentDocs(recentDocs []*RecentDoc) (err error) { dirPath := filepath.Join(util.DataDir, "storage") - if err = os.MkdirAll(dirPath, 0755); nil != err { + if err = os.MkdirAll(dirPath, 0755); err != nil { logging.LogErrorf("create storage [recent-doc] dir failed: %s", err) return } data, err := gulu.JSON.MarshalIndentJSON(recentDocs, "", " ") - if nil != err { + if err != nil { logging.LogErrorf("marshal storage [recent-doc] failed: %s", err) return } lsPath := filepath.Join(dirPath, "recent-doc.json") err = filelock.WriteFile(lsPath, data) - if nil != err { + if err != nil { logging.LogErrorf("write storage [recent-doc] failed: %s", err) return } @@ -130,12 +130,12 @@ func getRecentDocs() (ret []*RecentDoc, err error) { } data, err := filelock.ReadFile(dataPath) - if nil != err { + if err != nil { logging.LogErrorf("read storage [recent-doc] failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &tmp); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &tmp); err != nil { logging.LogErrorf("unmarshal storage [recent-doc] failed: %s", err) return } @@ -227,7 +227,7 @@ func RemoveCriterion(name string) (err error) { defer criteriaLock.Unlock() criteria, err := getCriteria() - if nil != err { + if err != nil { return } @@ -251,7 +251,7 @@ func SetCriterion(criterion *Criterion) (err error) { defer criteriaLock.Unlock() criteria, err := getCriteria() - if nil != err { + if err != nil { return } @@ -280,20 +280,20 @@ func GetCriteria() (ret []*Criterion) { func setCriteria(criteria []*Criterion) (err error) { dirPath := filepath.Join(util.DataDir, "storage") - if err = os.MkdirAll(dirPath, 0755); nil != err { + if err = os.MkdirAll(dirPath, 0755); err != nil { logging.LogErrorf("create storage [criteria] dir failed: %s", err) return } data, err := gulu.JSON.MarshalIndentJSON(criteria, "", " ") - if nil != err { + if err != nil { logging.LogErrorf("marshal storage [criteria] failed: %s", err) return } lsPath := filepath.Join(dirPath, "criteria.json") err = filelock.WriteFile(lsPath, data) - if nil != err { + if err != nil { logging.LogErrorf("write storage [criteria] failed: %s", err) return } @@ -308,12 +308,12 @@ func getCriteria() (ret []*Criterion, err error) { } data, err := filelock.ReadFile(dataPath) - if nil != err { + if err != nil { logging.LogErrorf("read storage [criteria] failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("unmarshal storage [criteria] failed: %s", err) return } @@ -360,20 +360,20 @@ func setLocalStorage(val interface{}) (err error) { } dirPath := filepath.Join(util.DataDir, "storage") - if err = os.MkdirAll(dirPath, 0755); nil != err { + if err = os.MkdirAll(dirPath, 0755); err != nil { logging.LogErrorf("create storage [local] dir failed: %s", err) return } data, err := gulu.JSON.MarshalIndentJSON(val, "", " ") - if nil != err { + if err != nil { logging.LogErrorf("marshal storage [local] failed: %s", err) return } lsPath := filepath.Join(dirPath, "local.json") err = filelock.WriteFile(lsPath, data) - if nil != err { + if err != nil { logging.LogErrorf("write storage [local] failed: %s", err) return } @@ -389,12 +389,12 @@ func getLocalStorage() (ret map[string]interface{}) { } data, err := filelock.ReadFile(lsPath) - if nil != err { + if err != nil { logging.LogErrorf("read storage [local] failed: %s", err) return } - if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil { logging.LogErrorf("unmarshal storage [local] failed: %s", err) return } diff --git a/kernel/model/sync.go b/kernel/model/sync.go index be2a14b03..3268d4fdc 100644 --- a/kernel/model/sync.go +++ b/kernel/model/sync.go @@ -65,7 +65,7 @@ func SyncDataDownload() { err := syncRepoDownload() code := 1 - if nil != err { + if err != nil { code = 2 } util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil) @@ -92,7 +92,7 @@ func SyncDataUpload() { err := syncRepoUpload() code := 1 - if nil != err { + if err != nil { code = 2 } util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil) @@ -151,7 +151,7 @@ func BootSyncData() { util.BroadcastByType("main", "syncing", 0, Conf.Language(81), nil) err := bootSyncRepo() code := 1 - if nil != err { + if err != nil { code = 2 } util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil) @@ -202,7 +202,7 @@ func syncData(exit, byHand bool) { dataChanged, err := syncRepo(exit, byHand) code := 1 - if nil != err { + if err != nil { code = 2 } util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil) @@ -474,12 +474,12 @@ func CreateCloudSyncDir(name string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } err = repo.CreateCloudRepo(name) - if nil != err { + if err != nil { err = errors.New(formatRepoErrorMsg(err)) return } @@ -499,12 +499,12 @@ func RemoveCloudSyncDir(name string) (err error) { } repo, err := newRepository() - if nil != err { + if err != nil { return } err = repo.RemoveCloudRepo(name) - if nil != err { + if err != nil { err = errors.New(formatRepoErrorMsg(err)) return } @@ -525,12 +525,12 @@ func ListCloudSyncDir() (syncDirs []*Sync, hSize string, err error) { var size int64 repo, err := newRepository() - if nil != err { + if err != nil { return } dirs, size, err = repo.GetCloudRepos() - if nil != err { + if err != nil { err = errors.New(formatRepoErrorMsg(err)) return } @@ -606,17 +606,17 @@ func formatRepoErrorMsg(err error) string { func getSyncIgnoreLines() (ret []string) { ignore := filepath.Join(util.DataDir, ".siyuan", "syncignore") err := os.MkdirAll(filepath.Dir(ignore), 0755) - if nil != err { + if err != nil { return } if !gulu.File.IsExist(ignore) { - if err = gulu.File.WriteFileSafer(ignore, nil, 0644); nil != err { + if err = gulu.File.WriteFileSafer(ignore, nil, 0644); err != nil { logging.LogErrorf("create syncignore [%s] failed: %s", ignore, err) return } } data, err := os.ReadFile(ignore) - if nil != err { + if err != nil { logging.LogErrorf("read syncignore [%s] failed: %s", ignore, err) return } @@ -831,7 +831,7 @@ func dialSyncWebSocket() (c *websocket.Conn, err error) { "x-siyuan-repo": []string{Conf.Sync.CloudName}, } c, _, err = websocket.DefaultDialer.Dial(endpoint, header) - if nil == err { + if err == nil { closedSyncWebSocket.Store(false) } return diff --git a/kernel/model/tag.go b/kernel/model/tag.go index 0b8fbf09b..1f598fdb7 100644 --- a/kernel/model/tag.go +++ b/kernel/model/tag.go @@ -93,7 +93,7 @@ func RemoveTag(label string) (err error) { n.Unlink() } util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title")))) - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { util.ClearPushProgress(100) return } @@ -176,7 +176,7 @@ func RenameTag(oldLabel, newLabel string) (err error) { } } util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title")))) - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { util.ClearPushProgress(100) return } diff --git a/kernel/model/template.go b/kernel/model/template.go index f19f8ba36..2015711d8 100644 --- a/kernel/model/template.go +++ b/kernel/model/template.go @@ -46,14 +46,14 @@ func RenderGoTemplate(templateContent string) (ret string, err error) { sql.SQLTemplateFuncs(&tplFuncMap) tmpl = tmpl.Funcs(tplFuncMap) tpl, err := tmpl.Parse(templateContent) - if nil != err { + if err != nil { return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error())) } buf := &bytes.Buffer{} buf.Grow(4096) err = tpl.Execute(buf, nil) - if nil != err { + if err != nil { return "", errors.New(fmt.Sprintf(Conf.Language(44), err.Error())) } ret = buf.String() @@ -62,7 +62,7 @@ func RenderGoTemplate(templateContent string) (ret string, err error) { func RemoveTemplate(p string) (err error) { err = filelock.Remove(p) - if nil != err { + if err != nil { logging.LogErrorf("remove template failed: %s", err) } return @@ -77,7 +77,7 @@ func SearchTemplate(keyword string) (ret []*Block) { } groups, err := os.ReadDir(templates) - if nil != err { + if err != nil { logging.LogErrorf("read templates failed: %s", err) return } @@ -195,7 +195,7 @@ func DocSaveAsTemplate(id, name string, overwrite bool) (code int, err error) { func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, err error) { tree, err = LoadTreeByBlockID(id) - if nil != err { + if err != nil { return } @@ -206,7 +206,7 @@ func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, e } block := sql.BuildBlockFromNode(node, tree) md, err := os.ReadFile(p) - if nil != err { + if err != nil { return } @@ -228,14 +228,14 @@ func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, e sql.SQLTemplateFuncs(&tplFuncMap) goTpl = goTpl.Funcs(tplFuncMap) tpl, err := goTpl.Funcs(tplFuncMap).Parse(gulu.Str.FromBytes(md)) - if nil != err { + if err != nil { err = errors.New(fmt.Sprintf(Conf.Language(44), err.Error())) return } buf := &bytes.Buffer{} buf.Grow(4096) - if err = tpl.Execute(buf, dataModel); nil != err { + if err = tpl.Execute(buf, dataModel); err != nil { err = errors.New(fmt.Sprintf(Conf.Language(44), err.Error())) return } diff --git a/kernel/model/theme.go b/kernel/model/theme.go index fdccbdb15..b18982d7c 100644 --- a/kernel/model/theme.go +++ b/kernel/model/theme.go @@ -109,7 +109,7 @@ func getThemeStyleVar(theme string) (ret map[string]string) { ret = map[string]string{} data, err := os.ReadFile(filepath.Join(util.ThemesPath, theme, "theme.css")) - if nil != err { + if err != nil { logging.LogErrorf("read theme [%s] css file failed: %s", theme, err) return } diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go index 46b1ccace..5ec9002bb 100644 --- a/kernel/model/transaction.go +++ b/kernel/model/transaction.go @@ -155,7 +155,7 @@ func performTx(tx *Transaction) (ret *TxErr) { //defer pprof.StopCPUProfile() var err error - if err = tx.begin(); nil != err { + if err = tx.begin(); err != nil { if strings.Contains(err.Error(), "database is closed") { return } @@ -302,7 +302,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) { var err error id := operation.ID srcTree, err := tx.loadTree(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", id, err) return &TxErr{code: TxErrCodeBlockNotFound, id: id} } @@ -335,7 +335,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) { var targetTree *parse.Tree targetTree, err = tx.loadTree(targetPreviousID) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", targetPreviousID, err) return &TxErr{code: TxErrCodeBlockNotFound, id: targetPreviousID} } @@ -374,11 +374,11 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) { refreshUpdated(srcNode) refreshUpdated(srcTree.Root) - if err = tx.writeTree(srcTree); nil != err { + if err = tx.writeTree(srcTree); err != nil { return } if !isSameTree { - if err = tx.writeTree(targetTree); nil != err { + if err = tx.writeTree(targetTree); err != nil { return } } @@ -390,7 +390,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) { } targetTree, err := tx.loadTree(targetParentID) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", targetParentID, err) return &TxErr{code: TxErrCodeBlockNotFound, id: targetParentID} } @@ -452,11 +452,11 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) { refreshUpdated(srcNode) refreshUpdated(srcTree.Root) - if err = tx.writeTree(srcTree); nil != err { + if err = tx.writeTree(srcTree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: id} } if !isSameTree { - if err = tx.writeTree(targetTree); nil != err { + if err = tx.writeTree(targetTree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: id} } } @@ -482,7 +482,7 @@ func (tx *Transaction) doPrependInsert(operation *Operation) (ret *TxErr) { return } tree, err := tx.loadTree(block.ID) - if nil != err { + if err != nil { msg := fmt.Sprintf("load tree [%s] failed: %s", block.ID, err) logging.LogErrorf(msg) return &TxErr{code: TxErrCodeBlockNotFound, id: block.ID} @@ -542,7 +542,7 @@ func (tx *Transaction) doPrependInsert(operation *Operation) (ret *TxErr) { } createdUpdated(insertedNode) tx.nodes[insertedNode.ID] = insertedNode - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: block.ID} } @@ -566,7 +566,7 @@ func (tx *Transaction) doAppendInsert(operation *Operation) (ret *TxErr) { return } tree, err := tx.loadTree(block.ID) - if nil != err { + if err != nil { msg := fmt.Sprintf("load tree [%s] failed: %s", block.ID, err) logging.LogErrorf(msg) return &TxErr{code: TxErrCodeBlockNotFound, id: block.ID} @@ -631,7 +631,7 @@ func (tx *Transaction) doAppendInsert(operation *Operation) (ret *TxErr) { createdUpdated(insertedNode) tx.nodes[insertedNode.ID] = insertedNode - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: block.ID} } @@ -650,7 +650,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) { var err error id := operation.ID srcTree, err := tx.loadTree(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", id, err) return &TxErr{code: TxErrCodeBlockNotFound, id: id} } @@ -688,7 +688,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) { } targetTree, err := tx.loadTree(targetRootID) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", targetRootID, err) return &TxErr{code: TxErrCodeBlockNotFound, id: targetRootID} } @@ -719,12 +719,12 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) { srcEmptyList.Unlink() } - if err = tx.writeTree(srcTree); nil != err { + if err = tx.writeTree(srcTree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: id} } if !isSameTree { - if err = tx.writeTree(targetTree); nil != err { + if err = tx.writeTree(targetTree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: id} } } @@ -737,7 +737,7 @@ func (tx *Transaction) doDelete(operation *Operation) (ret *TxErr) { var err error id := operation.ID tree, err := tx.loadTree(id) - if nil != err { + if err != nil { if errors.Is(err, ErrBlockNotFound) { // move 以后这里会空,算作正常情况 return @@ -768,7 +768,7 @@ func (tx *Transaction) doDelete(operation *Operation) (ret *TxErr) { treenode.RemoveBlockTree(node.ID) delete(tx.nodes, node.ID) - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return } @@ -824,7 +824,7 @@ func syncDelete2Block(node *ast.Node) { } attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { return ast.WalkContinue } @@ -919,7 +919,7 @@ func (tx *Transaction) doInsert(operation *Operation) (ret *TxErr) { } tree, err := tx.loadTree(block.ID) - if nil != err { + if err != nil { msg := fmt.Sprintf("load tree [%s] failed: %s", block.ID, err) logging.LogErrorf(msg) return &TxErr{code: TxErrCodeBlockNotFound, id: block.ID} @@ -953,7 +953,7 @@ func (tx *Transaction) doInsert(operation *Operation) (ret *TxErr) { // 只有全局 assets 才移动到相对 assets targetP := filepath.Join(assets, filepath.Base(assetPath)) - if e = filelock.Rename(assetPath, targetP); nil != err { + if e = filelock.Rename(assetPath, targetP); err != nil { logging.LogErrorf("copy path of asset from [%s] to [%s] failed: %s", assetPath, targetP, err) return ast.WalkContinue } @@ -1048,7 +1048,7 @@ func (tx *Transaction) doInsert(operation *Operation) (ret *TxErr) { createdUpdated(insertedNode) tx.nodes[insertedNode.ID] = insertedNode - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: block.ID} } @@ -1078,7 +1078,7 @@ func (tx *Transaction) doInsert(operation *Operation) (ret *TxErr) { func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) { id := operation.ID tree, err := tx.loadTree(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", id, err) return &TxErr{code: TxErrCodeBlockNotFound, id: id} } @@ -1151,7 +1151,7 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) { createdUpdated(updatedNode) tx.nodes[updatedNode.ID] = updatedNode - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: id} } @@ -1185,7 +1185,7 @@ func upsertAvBlockRel(node *ast.Node) { func (tx *Transaction) doUpdateUpdated(operation *Operation) (ret *TxErr) { id := operation.ID tree, err := tx.loadTree(id) - if nil != err { + if err != nil { if errors.Is(err, ErrBlockNotFound) { logging.LogWarnf("not found block [%s]", id) return @@ -1204,7 +1204,7 @@ func (tx *Transaction) doUpdateUpdated(operation *Operation) (ret *TxErr) { node.SetIALAttr("updated", operation.Data.(string)) createdUpdated(node) tx.nodes[node.ID] = node - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: id} } return @@ -1221,7 +1221,7 @@ func (tx *Transaction) doCreate(operation *Operation) (ret *TxErr) { func (tx *Transaction) doSetAttrs(operation *Operation) (ret *TxErr) { id := operation.ID tree, err := tx.loadTree(id) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", id, err) return &TxErr{code: TxErrCodeBlockNotFound, id: id} } @@ -1233,7 +1233,7 @@ func (tx *Transaction) doSetAttrs(operation *Operation) (ret *TxErr) { } attrs := map[string]string{} - if err = gulu.JSON.UnmarshalJSON([]byte(operation.Data.(string)), &attrs); nil != err { + if err = gulu.JSON.UnmarshalJSON([]byte(operation.Data.(string)), &attrs); err != nil { logging.LogErrorf("unmarshal attrs failed: %s", err) return &TxErr{code: TxErrCodeBlockNotFound, id: id} } @@ -1259,7 +1259,7 @@ func (tx *Transaction) doSetAttrs(operation *Operation) (ret *TxErr) { } } - if err = tx.writeTree(tree); nil != err { + if err = tx.writeTree(tree); err != nil { return } cache.PutBlockIAL(id, parse.IAL2Map(node.KramdownIAL)) @@ -1366,7 +1366,7 @@ func (tx *Transaction) begin() (err error) { func (tx *Transaction) commit() (err error) { for _, tree := range tx.trees { - if err = writeTreeUpsertQueue(tree); nil != err { + if err = writeTreeUpsertQueue(tree); err != nil { return } @@ -1404,7 +1404,7 @@ func (tx *Transaction) loadTree(id string) (ret *parse.Tree, err error) { } ret, err = filesys.LoadTree(box, p, tx.luteEngine) - if nil != err { + if err != nil { return } tx.trees[rootID] = ret @@ -1466,7 +1466,7 @@ func refreshDynamicRefTexts(updatedDefNodes map[string]*ast.Node, updatedTrees m if !ok { var err error refTree, err = LoadTreeByBlockID(refTreeID) - if nil != err { + if err != nil { continue } } diff --git a/kernel/model/tree.go b/kernel/model/tree.go index 8a0766074..98ee9f81d 100644 --- a/kernel/model/tree.go +++ b/kernel/model/tree.go @@ -153,13 +153,13 @@ func pagedPaths(localPath string, pageSize int) (ret map[int][]string) { func loadTree(localPath string, luteEngine *lute.Lute) (ret *parse.Tree, err error) { data, err := filelock.ReadFile(localPath) - if nil != err { + if err != nil { logging.LogErrorf("get data [path=%s] failed: %s", localPath, err) return } ret, err = filesys.ParseJSONWithoutFix(data, luteEngine.ParseOptions) - if nil != err { + if err != nil { logging.LogErrorf("parse json to tree [%s] failed: %s", localPath, err) return } @@ -284,7 +284,7 @@ func searchTreeInFilesystem(rootID string) { } tree, err := filesys.LoadTree(boxID, treePath, util.NewLute()) - if nil != err { + if err != nil { logging.LogErrorf("load tree [%s] failed: %s", treePath, err) return } diff --git a/kernel/model/updater.go b/kernel/model/updater.go index dd1c3af48..f902b49d6 100644 --- a/kernel/model/updater.go +++ b/kernel/model/updater.go @@ -60,7 +60,7 @@ func getNewVerInstallPkgPath() string { } downloadPkgURLs, checksum, err := getUpdatePkg() - if nil != err || 1 > len(downloadPkgURLs) || "" == checksum { + if err != nil || 1 > len(downloadPkgURLs) || "" == checksum { return "" } @@ -88,7 +88,7 @@ func checkDownloadInstallPkg() { defer checkDownloadInstallPkgLock.Unlock() downloadPkgURLs, checksum, err := getUpdatePkg() - if nil != err || 1 > len(downloadPkgURLs) || "" == checksum { + if err != nil || 1 > len(downloadPkgURLs) || "" == checksum { return } @@ -96,7 +96,7 @@ func checkDownloadInstallPkg() { succ := false for _, downloadPkgURL := range downloadPkgURLs { err = downloadInstallPkg(downloadPkgURL, checksum) - if nil == err { + if err == nil { succ = true break @@ -110,7 +110,7 @@ func checkDownloadInstallPkg() { func getUpdatePkg() (downloadPkgURLs []string, checksum string, err error) { defer logging.Recover() result, err := util.GetRhyResult(false) - if nil != err { + if err != nil { return } @@ -170,7 +170,7 @@ func downloadInstallPkg(pkgURL, checksum string) (err error) { } err = os.MkdirAll(filepath.Join(util.TempDir, "install"), 0755) - if nil != err { + if err != nil { logging.LogErrorf("create temp install dir failed: %s", err) return } @@ -183,7 +183,7 @@ func downloadInstallPkg(pkgURL, checksum string) (err error) { util.PushStatusBar(fmt.Sprintf(Conf.Language(133), progress)) } _, err = client.R().SetOutputFile(savePath).SetDownloadCallbackWithInterval(callback, 1*time.Second).Get(pkgURL) - if nil != err { + if err != nil { logging.LogErrorf("download install package [%s] failed: %s", pkgURL, err) return } @@ -200,7 +200,7 @@ func downloadInstallPkg(pkgURL, checksum string) (err error) { func sha256Hash(filename string) (ret string, err error) { file, err := os.Open(filename) - if nil != err { + if err != nil { return } defer file.Close() @@ -229,7 +229,7 @@ type Announcement struct { func GetAnnouncements() (ret []*Announcement) { result, err := util.GetRhyResult(false) - if nil != err { + if err != nil { logging.LogErrorf("get announcement failed: %s", err) return } @@ -261,7 +261,7 @@ func CheckUpdate(showMsg bool) { } result, err := util.GetRhyResult(showMsg) - if nil != err { + if err != nil { return } diff --git a/kernel/model/upload.go b/kernel/model/upload.go index ad57efe60..97bf73373 100644 --- a/kernel/model/upload.go +++ b/kernel/model/upload.go @@ -46,7 +46,7 @@ func InsertLocalAssets(id string, assetPaths []string, isUpload bool) (succMap m docDirLocalPath := filepath.Join(util.DataDir, bt.BoxID, path.Dir(bt.Path)) assetsDirPath := getAssetsDir(filepath.Join(util.DataDir, bt.BoxID), docDirLocalPath) if !gulu.File.IsExist(assetsDirPath) { - if err = os.MkdirAll(assetsDirPath, 0755); nil != err { + if err = os.MkdirAll(assetsDirPath, 0755); err != nil { return } } @@ -91,11 +91,11 @@ func InsertLocalAssets(id string, assetPaths []string, isUpload bool) (succMap m fName = fName[0 : len(fName)-len(ext)] fName = fName + "-" + ast.NewNodeID() + ext writePath := filepath.Join(assetsDirPath, fName) - if _, err = f.Seek(0, io.SeekStart); nil != err { + if _, err = f.Seek(0, io.SeekStart); err != nil { f.Close() return } - if err = filelock.WriteFileByReader(writePath, f); nil != err { + if err = filelock.WriteFileByReader(writePath, f); err != nil { f.Close() return } @@ -112,7 +112,7 @@ func Upload(c *gin.Context) { defer c.JSON(200, ret) form, err := c.MultipartForm() - if nil != err { + if err != nil { logging.LogErrorf("insert asset failed: %s", err) ret.Code = -1 ret.Msg = err.Error() @@ -137,7 +137,7 @@ func Upload(c *gin.Context) { assetsDirPath = filepath.Join(util.DataDir, relAssetsDirPath) } if !gulu.File.IsExist(assetsDirPath) { - if err = os.MkdirAll(assetsDirPath, 0755); nil != err { + if err = os.MkdirAll(assetsDirPath, 0755); err != nil { ret.Code = -1 ret.Msg = err.Error() return @@ -206,7 +206,7 @@ func Upload(c *gin.Context) { writePath := filepath.Join(assetsDirPath, fName) tmpDir := filepath.Join(util.TempDir, "convert", "zip", gulu.Rand.String(7)) if needUnzip2Dir { - if err = os.MkdirAll(tmpDir, 0755); nil != err { + if err = os.MkdirAll(tmpDir, 0755); err != nil { errFiles = append(errFiles, fName) ret.Msg = err.Error() f.Close() @@ -215,14 +215,14 @@ func Upload(c *gin.Context) { writePath = filepath.Join(tmpDir, fName) } - if _, err = f.Seek(0, io.SeekStart); nil != err { + if _, err = f.Seek(0, io.SeekStart); err != nil { logging.LogErrorf("seek failed: %s", err) errFiles = append(errFiles, fName) ret.Msg = err.Error() f.Close() break } - if err = filelock.WriteFileByReader(writePath, f); nil != err { + if err = filelock.WriteFileByReader(writePath, f); err != nil { logging.LogErrorf("write file failed: %s", err) errFiles = append(errFiles, fName) ret.Msg = err.Error() @@ -241,7 +241,7 @@ func Upload(c *gin.Context) { fName += ext fName = util.AssetName(fName) tmpDir2 := filepath.Join(util.TempDir, "convert", "zip", gulu.Rand.String(7)) - if err = gulu.Zip.Unzip(writePath, tmpDir2); nil != err { + if err = gulu.Zip.Unzip(writePath, tmpDir2); err != nil { errFiles = append(errFiles, fName) ret.Msg = err.Error() break diff --git a/kernel/model/widget.go b/kernel/model/widget.go index f8baed072..5ca7d6043 100644 --- a/kernel/model/widget.go +++ b/kernel/model/widget.go @@ -30,7 +30,7 @@ func SearchWidget(keyword string) (ret []*Block) { ret = []*Block{} widgetsDir := filepath.Join(util.DataDir, "widgets") entries, err := os.ReadDir(widgetsDir) - if nil != err { + if err != nil { logging.LogErrorf("read dir [%s] failed: %s", widgetsDir, err) return } diff --git a/kernel/search/mark.go b/kernel/search/mark.go index d8fecb225..f363a7a60 100644 --- a/kernel/search/mark.go +++ b/kernel/search/mark.go @@ -18,11 +18,12 @@ package search import ( "fmt" - "github.com/88250/gulu" "regexp" "strings" "unicode/utf8" + "github.com/88250/gulu" + "github.com/88250/lute/lex" "github.com/siyuan-note/siyuan/kernel/util" ) @@ -113,7 +114,7 @@ func EncloseHighlighting(text string, keywords []string, openMark, closeMark str re += ")" ret = text - if reg, err := regexp.Compile(re); nil == err { + if reg, err := regexp.Compile(re); err == nil { ret = reg.ReplaceAllStringFunc(text, func(s string) string { return openMark + s + closeMark }) } diff --git a/kernel/server/port.go b/kernel/server/port.go index b982bb922..5ea29b904 100644 --- a/kernel/server/port.go +++ b/kernel/server/port.go @@ -38,7 +38,7 @@ func killRunningKernel() { defer logging.LogInfof("check running kernel elapsed [%dms]", time.Since(now).Milliseconds()) processes, err := goPS.Processes() - if nil != err { + if err != nil { logging.LogErrorf("get processes failed: %s", err) killByPort(util.FixedPort) return @@ -102,7 +102,7 @@ func pidByPort(port string) (ret string) { cmd := exec.Command("cmd", "/c", "netstat -ano | findstr "+port) gulu.CmdAttr(cmd) data, err := cmd.CombinedOutput() - if nil != err { + if err != nil { logging.LogErrorf("netstat failed: %s", err) return } @@ -122,7 +122,7 @@ func pidByPort(port string) (ret string) { cmd := exec.Command("lsof", "-Fp", "-i", ":"+port) gulu.CmdAttr(cmd) data, err := cmd.CombinedOutput() - if nil != err { + if err != nil { logging.LogErrorf("lsof failed: %s", err) return } diff --git a/kernel/server/proxy/publish.go b/kernel/server/proxy/publish.go index 6490d5052..52506270e 100644 --- a/kernel/server/proxy/publish.go +++ b/kernel/server/proxy/publish.go @@ -90,7 +90,7 @@ func initPublishListener() (err error) { } _, Port, err = net.SplitHostPort(listener.Addr().String()) - if nil != err { + if err != nil { logging.LogErrorf("split host and port failed: %s", err) return } @@ -110,7 +110,7 @@ func closePublishListener() (err error) { func startPublishReverseProxyService() { logging.LogInfof("publish service [%s:%s] is running", Host, Port) // 服务进行时一直阻塞 - if err := http.Serve(listener, proxy); nil != err { + if err := http.Serve(listener, proxy); err != nil { if listener != nil { logging.LogErrorf("boot publish service failed: %s", err) } diff --git a/kernel/server/serve.go b/kernel/server/serve.go index 376748cf0..8b04502ad 100644 --- a/kernel/server/serve.go +++ b/kernel/server/serve.go @@ -96,7 +96,7 @@ func Serve(fastMode bool) { } ln, err := net.Listen("tcp", host+":"+util.ServerPort) - if nil != err { + if err != nil { if !fastMode { logging.LogErrorf("boot kernel failed: %s", err) os.Exit(logging.ExitCodeUnavailablePort) @@ -107,7 +107,7 @@ func Serve(fastMode bool) { } _, port, err := net.SplitHostPort(ln.Addr().String()) - if nil != err { + if err != nil { if !fastMode { logging.LogErrorf("boot kernel failed: %s", err) os.Exit(logging.ExitCodeUnavailablePort) @@ -136,7 +136,7 @@ func Serve(fastMode bool) { // 反代服务器启动失败不影响核心服务器启动 }() - if err = http.Serve(ln, ginServer.Handler()); nil != err { + if err = http.Serve(ln, ginServer.Handler()); err != nil { if !fastMode { logging.LogErrorf("boot kernel failed: %s", err) os.Exit(logging.ExitCodeUnavailablePort) @@ -152,20 +152,20 @@ func rewritePortJSON(pid, port string) { if gulu.File.IsExist(portJSON) { data, err = os.ReadFile(portJSON) - if nil != err { + if err != nil { logging.LogWarnf("read port.json failed: %s", err) } else { - if err = gulu.JSON.UnmarshalJSON(data, &pidPorts); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &pidPorts); err != nil { logging.LogWarnf("unmarshal port.json failed: %s", err) } } } pidPorts[pid] = port - if data, err = gulu.JSON.MarshalIndentJSON(pidPorts, "", " "); nil != err { + if data, err = gulu.JSON.MarshalIndentJSON(pidPorts, "", " "); err != nil { logging.LogWarnf("marshal port.json failed: %s", err) } else { - if err = os.WriteFile(portJSON, data, 0644); nil != err { + if err = os.WriteFile(portJSON, data, 0644); err != nil { logging.LogWarnf("write port.json failed: %s", err) } } @@ -204,7 +204,7 @@ func serveSnippets(ginServer *gin.Engine) { ext := filepath.Ext(filePath) name := strings.TrimSuffix(filePath, ext) confSnippets, err := model.LoadSnippets() - if nil != err { + if err != nil { logging.LogErrorf("load snippets failed: %s", err) c.Status(http.StatusNotFound) return @@ -278,13 +278,13 @@ func serveAppearance(ginServer *gin.Engine) { enUSFilePath := filepath.Join(appearancePath, "langs", "en_US.json") enUSData, err := os.ReadFile(enUSFilePath) - if nil != err { + if err != nil { logging.LogErrorf("read en_US.json [%s] failed: %s", enUSFilePath, err) util.ReportFileSysFatalError(err) return } enUSMap := map[string]interface{}{} - if err = gulu.JSON.UnmarshalJSON(enUSData, &enUSMap); nil != err { + if err = gulu.JSON.UnmarshalJSON(enUSData, &enUSMap); err != nil { logging.LogErrorf("unmarshal en_US.json [%s] failed: %s", enUSFilePath, err) util.ReportFileSysFatalError(err) return @@ -292,13 +292,13 @@ func serveAppearance(ginServer *gin.Engine) { for { data, err := os.ReadFile(filePath) - if nil != err { + if err != nil { c.JSON(200, enUSMap) return } langMap := map[string]interface{}{} - if err = gulu.JSON.UnmarshalJSON(data, &langMap); nil != err { + if err = gulu.JSON.UnmarshalJSON(data, &langMap); err != nil { logging.LogErrorf("unmarshal json [%s] failed: %s", filePath, err) c.JSON(200, enUSMap) return @@ -327,14 +327,14 @@ func serveCheckAuth(ginServer *gin.Engine) { func serveAuthPage(c *gin.Context) { data, err := os.ReadFile(filepath.Join(util.WorkingDir, "stage/auth.html")) - if nil != err { + if err != nil { logging.LogErrorf("load auth page failed: %s", err) c.Status(500) return } tpl, err := template.New("auth").Parse(string(data)) - if nil != err { + if err != nil { logging.LogErrorf("parse auth page failed: %s", err) c.Status(500) return @@ -378,7 +378,7 @@ func serveAuthPage(c *gin.Context) { "workspaceDir": util.WorkspaceDir, } buf := &bytes.Buffer{} - if err = tpl.Execute(buf, model); nil != err { + if err = tpl.Execute(buf, model); err != nil { logging.LogErrorf("execute auth page failed: %s", err) c.Status(500) return @@ -394,7 +394,7 @@ func serveAssets(ginServer *gin.Engine) { requestPath := context.Param("path") relativePath := path.Join("assets", requestPath) p, err := model.GetAssetAbsPath(relativePath) - if nil != err { + if err != nil { if strings.Contains(strings.TrimPrefix(requestPath, "/"), "/") { // 再使用编码过的路径解析一次 https://github.com/siyuan-note/siyuan/issues/11823 dest := url.PathEscape(strings.TrimPrefix(requestPath, "/")) @@ -403,7 +403,7 @@ func serveAssets(ginServer *gin.Engine) { p, err = model.GetAssetAbsPath(relativePath) } - if nil != err { + if err != nil { context.Status(http.StatusNotFound) return } @@ -450,7 +450,7 @@ func serveWebSocket(ginServer *gin.Engine) { util.WebSocketServer.Config.MaxMessageSize = 1024 * 1024 * 8 ginServer.GET("/ws", func(c *gin.Context) { - if err := util.WebSocketServer.HandleRequest(c.Writer, c.Request); nil != err { + if err := util.WebSocketServer.HandleRequest(c.Writer, c.Request); err != nil { logging.LogErrorf("handle command failed: %s", err) } }) @@ -465,7 +465,7 @@ func serveWebSocket(ginServer *gin.Engine) { if "" != model.Conf.AccessAuthCode { session, err := cookieStore.Get(s.Request, "siyuan") - if nil != err { + if err != nil { authOk = false logging.LogErrorf("get cookie failed: %s", err) } else { @@ -475,7 +475,7 @@ func serveWebSocket(ginServer *gin.Engine) { } else { sess := &util.SessionData{} err = gulu.JSON.UnmarshalJSON([]byte(val.(string)), sess) - if nil != err { + if err != nil { authOk = false logging.LogErrorf("unmarshal cookie failed: %s", err) } else { @@ -534,7 +534,7 @@ func serveWebSocket(ginServer *gin.Engine) { start := time.Now() logging.LogTracef("request [%s]", shortReqMsg(msg)) request := map[string]interface{}{} - if err := gulu.JSON.UnmarshalJSON(msg, &request); nil != err { + if err := gulu.JSON.UnmarshalJSON(msg, &request); err != nil { result := util.NewResult() result.Code = -1 result.Msg = "Bad Request" diff --git a/kernel/sql/asset.go b/kernel/sql/asset.go index 049be5d29..6e933d5df 100644 --- a/kernel/sql/asset.go +++ b/kernel/sql/asset.go @@ -73,7 +73,7 @@ func docTitleImgAsset(root *ast.Node, boxLocalPath, docDirLocalPath string) *Ass var err error if lp := assetLocalPath(p, boxLocalPath, docDirLocalPath); "" != lp { hash, err = util.GetEtag(lp) - if nil != err { + if err != nil { logging.LogErrorf("calc asset [%s] hash failed: %s", lp, err) return nil } @@ -106,7 +106,7 @@ func QueryAssetByHash(hash string) (ret *Asset) { sqlStmt := "SELECT * FROM assets WHERE hash = ?" row := queryRow(sqlStmt, hash) var asset Asset - if err := row.Scan(&asset.ID, &asset.BlockID, &asset.RootID, &asset.Box, &asset.DocPath, &asset.Path, &asset.Name, &asset.Title, &asset.Hash); nil != err { + if err := row.Scan(&asset.ID, &asset.BlockID, &asset.RootID, &asset.Box, &asset.DocPath, &asset.Path, &asset.Name, &asset.Title, &asset.Hash); err != nil { if sql.ErrNoRows != err { logging.LogErrorf("query scan field failed: %s", err) } @@ -118,7 +118,7 @@ func QueryAssetByHash(hash string) (ret *Asset) { func scanAssetRows(rows *sql.Rows) (ret *Asset) { var asset Asset - if err := rows.Scan(&asset.ID, &asset.BlockID, &asset.RootID, &asset.Box, &asset.DocPath, &asset.Path, &asset.Name, &asset.Title, &asset.Hash); nil != err { + if err := rows.Scan(&asset.ID, &asset.BlockID, &asset.RootID, &asset.Box, &asset.DocPath, &asset.Path, &asset.Name, &asset.Title, &asset.Hash); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } diff --git a/kernel/sql/asset_content.go b/kernel/sql/asset_content.go index 19ceab244..1c1331319 100644 --- a/kernel/sql/asset_content.go +++ b/kernel/sql/asset_content.go @@ -51,13 +51,13 @@ func insertAssetContents(tx *sql.Tx, assetContents []*AssetContent, context map[ continue } - if err = insertAssetContents0(tx, bulk, context); nil != err { + if err = insertAssetContents0(tx, bulk, context); err != nil { return } bulk = []*AssetContent{} } if 0 < len(bulk) { - if err = insertAssetContents0(tx, bulk, context); nil != err { + if err = insertAssetContents0(tx, bulk, context); err != nil { return } } @@ -79,7 +79,7 @@ func insertAssetContents0(tx *sql.Tx, bulk []*AssetContent, context map[string]i } stmt := fmt.Sprintf(AssetContentsFTSCaseInsensitiveInsert, strings.Join(valueStrings, ",")) - if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err { + if err = prepareExecInsertTx(tx, stmt, valueArgs); err != nil { return } @@ -89,7 +89,7 @@ func insertAssetContents0(tx *sql.Tx, bulk []*AssetContent, context map[string]i func deleteAssetContentsByPath(tx *sql.Tx, path string, context map[string]interface{}) (err error) { stmt := "DELETE FROM asset_contents_fts_case_insensitive WHERE path = ?" - if err = execStmtTx(tx, stmt, path); nil != err { + if err = execStmtTx(tx, stmt, path); err != nil { return } return diff --git a/kernel/sql/asset_content_query.go b/kernel/sql/asset_content_query.go index 22c14af82..9b78f3f2e 100644 --- a/kernel/sql/asset_content_query.go +++ b/kernel/sql/asset_content_query.go @@ -33,7 +33,7 @@ func QueryAssetContentNoLimit(stmt string) (ret []map[string]interface{}, err er func queryAssetContentRawStmt(stmt string, limit int) (ret []map[string]interface{}, err error) { rows, err := queryAssetContent(stmt) - if nil != err { + if err != nil { if strings.Contains(err.Error(), "syntax error") { return } @@ -42,7 +42,7 @@ func queryAssetContentRawStmt(stmt string, limit int) (ret []map[string]interfac defer rows.Close() cols, err := rows.Columns() - if nil != err || nil == cols { + if err != nil || nil == cols { return } @@ -55,7 +55,7 @@ func queryAssetContentRawStmt(stmt string, limit int) (ret []map[string]interfac columnPointers[i] = &columns[i] } - if err = rows.Scan(columnPointers...); nil != err { + if err = rows.Scan(columnPointers...); err != nil { return } @@ -76,7 +76,7 @@ func queryAssetContentRawStmt(stmt string, limit int) (ret []map[string]interfac func SelectAssetContentsRawStmt(stmt string, page, limit int) (ret []*AssetContent) { parsedStmt, err := sqlparser.Parse(stmt) - if nil != err { + if err != nil { return selectAssetContentsRawStmt(stmt, limit) } @@ -122,7 +122,7 @@ func SelectAssetContentsRawStmt(stmt string, page, limit int) (ret []*AssetConte stmt = strings.ReplaceAll(stmt, "\\\\*", "\\*") stmt = strings.ReplaceAll(stmt, "from dual", "") rows, err := queryAssetContent(stmt) - if nil != err { + if err != nil { if strings.Contains(err.Error(), "syntax error") { return } @@ -144,7 +144,7 @@ func SelectAssetContentsRawStmtNoParse(stmt string, limit int) (ret []*AssetCont func selectAssetContentsRawStmt(stmt string, limit int) (ret []*AssetContent) { rows, err := queryAssetContent(stmt) - if nil != err { + if err != nil { if strings.Contains(err.Error(), "syntax error") { return } @@ -172,7 +172,7 @@ func selectAssetContentsRawStmt(stmt string, limit int) (ret []*AssetContent) { func scanAssetContentRows(rows *sql.Rows) (ret *AssetContent) { var ac AssetContent - if err := rows.Scan(&ac.ID, &ac.Name, &ac.Ext, &ac.Path, &ac.Size, &ac.Updated, &ac.Content); nil != err { + if err := rows.Scan(&ac.ID, &ac.Name, &ac.Ext, &ac.Path, &ac.Size, &ac.Updated, &ac.Content); err != nil { logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack()) return } diff --git a/kernel/sql/av.go b/kernel/sql/av.go index 13e4dba25..fa185f0fd 100644 --- a/kernel/sql/av.go +++ b/kernel/sql/av.go @@ -408,7 +408,7 @@ func RenderTemplateCol(ial map[string]string, rowValues []*av.KeyValues, tplCont SQLTemplateFuncs(&tplFuncMap) goTpl = goTpl.Funcs(tplFuncMap) tpl, err := goTpl.Parse(tplContent) - if nil != err { + if err != nil { logging.LogWarnf("parse template [%s] failed: %s", tplContent, err) return } @@ -489,7 +489,7 @@ func RenderTemplateCol(ial map[string]string, rowValues []*av.KeyValues, tplCont } } - if err = tpl.Execute(buf, dataModel); nil != err { + if err = tpl.Execute(buf, dataModel); err != nil { logging.LogWarnf("execute template [%s] failed: %s", tplContent, err) return } @@ -575,7 +575,7 @@ func getAttributeViewContent(avID string, } attrView, err := av.ParseAttributeView(avID) - if nil != err { + if err != nil { logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err) return } diff --git a/kernel/sql/block.go b/kernel/sql/block.go index 93b32d64e..c28b7ce51 100644 --- a/kernel/sql/block.go +++ b/kernel/sql/block.go @@ -57,16 +57,16 @@ type Block struct { func updateRootContent(tx *sql.Tx, content, updated, id string) (err error) { stmt := "UPDATE blocks SET content = ?, fcontent = ?, updated = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, content, content, updated, id); nil != err { + if err = execStmtTx(tx, stmt, content, content, updated, id); err != nil { return } stmt = "UPDATE blocks_fts SET content = ?, fcontent = ?, updated = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, content, content, updated, id); nil != err { + if err = execStmtTx(tx, stmt, content, content, updated, id); err != nil { return } if !caseSensitive { stmt = "UPDATE blocks_fts_case_insensitive SET content = ?, fcontent = ?, updated = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, content, content, updated, id); nil != err { + if err = execStmtTx(tx, stmt, content, content, updated, id); err != nil { return } } @@ -77,18 +77,18 @@ func updateRootContent(tx *sql.Tx, content, updated, id string) (err error) { func updateBlockContent(tx *sql.Tx, block *Block) (err error) { stmt := "UPDATE blocks SET content = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, block.Content, block.ID); nil != err { + if err = execStmtTx(tx, stmt, block.Content, block.ID); err != nil { tx.Rollback() return } stmt = "UPDATE blocks_fts SET content = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, block.Content, block.ID); nil != err { + if err = execStmtTx(tx, stmt, block.Content, block.ID); err != nil { tx.Rollback() return } if !caseSensitive { stmt = "UPDATE blocks_fts_case_insensitive SET content = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, block.Content, block.ID); nil != err { + if err = execStmtTx(tx, stmt, block.Content, block.ID); err != nil { tx.Rollback() return } @@ -117,18 +117,18 @@ func indexNode(tx *sql.Tx, id string) (err error) { content := NodeStaticContent(node, nil, true, indexAssetPath, true, nil) stmt := "UPDATE blocks SET content = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, content, id); nil != err { + if err = execStmtTx(tx, stmt, content, id); err != nil { tx.Rollback() return } stmt = "UPDATE blocks_fts SET content = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, content, id); nil != err { + if err = execStmtTx(tx, stmt, content, id); err != nil { tx.Rollback() return } if !caseSensitive { stmt = "UPDATE blocks_fts_case_insensitive SET content = ? WHERE id = ?" - if err = execStmtTx(tx, stmt, content, id); nil != err { + if err = execStmtTx(tx, stmt, content, id); err != nil { tx.Rollback() return } diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go index 565bc79c9..e6d461f0b 100644 --- a/kernel/sql/block_query.go +++ b/kernel/sql/block_query.go @@ -36,7 +36,7 @@ import ( func QueryEmptyContentEmbedBlocks() (ret []*Block) { stmt := "SELECT * FROM blocks WHERE type = 'query_embed' AND content = ''" rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", stmt, err) return } @@ -52,7 +52,7 @@ func QueryEmptyContentEmbedBlocks() (ret []*Block) { func queryBlockHashes(rootID string) (ret map[string]string) { stmt := "SELECT id, hash FROM blocks WHERE root_id = ?" rows, err := query(stmt, rootID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", stmt, err) return } @@ -60,7 +60,7 @@ func queryBlockHashes(rootID string) (ret map[string]string) { ret = map[string]string{} for rows.Next() { var id, hash string - if err = rows.Scan(&id, &hash); nil != err { + if err = rows.Scan(&id, &hash); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -72,7 +72,7 @@ func queryBlockHashes(rootID string) (ret map[string]string) { func QueryRootBlockByCondition(condition string) (ret []*Block) { sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition + " ORDER BY box DESC,lv ASC LIMIT 128" rows, err := query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -80,7 +80,7 @@ func QueryRootBlockByCondition(condition string) (ret []*Block) { for rows.Next() { var block Block var sepCount int - if err = rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated, &sepCount); nil != err { + if err = rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated, &sepCount); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -109,7 +109,7 @@ func queryBlockChildrenIDs(id string) (ret []string) { func queryBlockIDByParentID(parentID string) (ret []string) { sqlStmt := "SELECT id FROM blocks WHERE parent_id = ?" rows, err := query(sqlStmt, parentID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -128,7 +128,7 @@ func QueryRecentUpdatedBlocks() (ret []*Block) { sqlStmt = "SELECT * FROM blocks WHERE type = 'd' ORDER BY updated DESC LIMIT 16" } rows, err := query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -151,7 +151,7 @@ func QueryBlockByNameOrAlias(rootID, text string) (ret *Block) { func QueryBlockAliases(rootID string) (ret []string) { sqlStmt := "SELECT alias FROM blocks WHERE root_id = ? AND alias != ''" rows, err := query(sqlStmt, rootID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -191,7 +191,7 @@ func queryNames(searchIgnoreLines []string) (ret []string) { sqlStmt += buf.String() sqlStmt += " LIMIT ?" rows, err := query(sqlStmt, 10240) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -231,7 +231,7 @@ func queryAliases(searchIgnoreLines []string) (ret []string) { sqlStmt += buf.String() sqlStmt += " LIMIT ?" rows, err := query(sqlStmt, 10240) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -269,7 +269,7 @@ func queryDocIDsByTitle(title string, excludeIDs []string) (ret []string) { sqlStmt = "SELECT id FROM blocks WHERE type = 'd' AND content = ? AND id NOT IN " + notIn + " LIMIT ?" } rows, err := query(sqlStmt, title, 32) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -298,7 +298,7 @@ func queryDocTitles(searchIgnoreLines []string) (ret []string) { } sqlStmt += buf.String() rows, err := query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -330,7 +330,7 @@ func queryDocTitles(searchIgnoreLines []string) (ret []string) { func QueryBlockNamesByRootID(rootID string) (ret []string) { sqlStmt := "SELECT DISTINCT name FROM blocks WHERE root_id = ? AND name != ''" rows, err := query(sqlStmt, rootID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -346,7 +346,7 @@ func QueryBlockNamesByRootID(rootID string) (ret []string) { func QueryBookmarkBlocksByKeyword(bookmark string) (ret []*Block) { sqlStmt := "SELECT * FROM blocks WHERE ial LIKE ?" rows, err := query(sqlStmt, "%bookmark=%") - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -362,7 +362,7 @@ func QueryBookmarkBlocksByKeyword(bookmark string) (ret []*Block) { func QueryBookmarkBlocks() (ret []*Block) { sqlStmt := "SELECT * FROM blocks WHERE ial LIKE ?" rows, err := query(sqlStmt, "%bookmark=%") - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -379,7 +379,7 @@ func QueryBookmarkLabels() (ret []string) { ret = []string{} sqlStmt := "SELECT * FROM blocks WHERE ial LIKE ?" rows, err := query(sqlStmt, "%bookmark=%") - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -410,7 +410,7 @@ func Query(stmt string, limit int) (ret []map[string]interface{}, err error) { // 考虑到 UNION 的使用场景不多,这里还是以支持 || 操作符为主 p := sqlparser2.NewParser(strings.NewReader(stmt)) parsedStmt2, err := p.ParseStatement() - if nil != err { + if err != nil { if !strings.Contains(stmt, "||") { // 这个解析器无法处理 || 连接字符串操作符 parsedStmt, err2 := sqlparser.Parse(stmt) @@ -451,7 +451,7 @@ func Query(stmt string, limit int) (ret []map[string]interface{}, err error) { ret = []map[string]interface{}{} rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogWarnf("sql query [%s] failed: %s", stmt, err) return } @@ -469,7 +469,7 @@ func Query(stmt string, limit int) (ret []map[string]interface{}, err error) { columnPointers[i] = &columns[i] } - if err = rows.Scan(columnPointers...); nil != err { + if err = rows.Scan(columnPointers...); err != nil { return } @@ -510,7 +510,7 @@ func getLimitClause(parsedStmt sqlparser.Statement, limit int) (ret *sqlparser.L func queryRawStmt(stmt string, limit int) (ret []map[string]interface{}, err error) { rows, err := query(stmt) - if nil != err { + if err != nil { if strings.Contains(err.Error(), "syntax error") { return } @@ -519,7 +519,7 @@ func queryRawStmt(stmt string, limit int) (ret []map[string]interface{}, err err defer rows.Close() cols, err := rows.Columns() - if nil != err || nil == cols { + if err != nil || nil == cols { return } @@ -532,7 +532,7 @@ func queryRawStmt(stmt string, limit int) (ret []map[string]interface{}, err err columnPointers[i] = &columns[i] } - if err = rows.Scan(columnPointers...); nil != err { + if err = rows.Scan(columnPointers...); err != nil { return } @@ -557,7 +557,7 @@ func SelectBlocksRawStmtNoParse(stmt string, limit int) (ret []*Block) { func SelectBlocksRawStmt(stmt string, page, limit int) (ret []*Block) { parsedStmt, err := sqlparser.Parse(stmt) - if nil != err { + if err != nil { return selectBlocksRawStmt(stmt, limit) } @@ -603,7 +603,7 @@ func SelectBlocksRawStmt(stmt string, page, limit int) (ret []*Block) { stmt = strings.ReplaceAll(stmt, "\\\\*", "\\*") stmt = strings.ReplaceAll(stmt, "from dual", "") rows, err := query(stmt) - if nil != err { + if err != nil { if strings.Contains(err.Error(), "syntax error") { return } @@ -621,7 +621,7 @@ func SelectBlocksRawStmt(stmt string, page, limit int) (ret []*Block) { func selectBlocksRawStmt(stmt string, limit int) (ret []*Block) { rows, err := query(stmt) - if nil != err { + if err != nil { if strings.Contains(err.Error(), "syntax error") { return } @@ -649,7 +649,7 @@ func selectBlocksRawStmt(stmt string, limit int) (ret []*Block) { func scanBlockRows(rows *sql.Rows) (ret *Block) { var block Block - if err := rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); nil != err { + if err := rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil { logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack()) return } @@ -660,7 +660,7 @@ func scanBlockRows(rows *sql.Rows) (ret *Block) { func scanBlockRow(row *sql.Row) (ret *Block) { var block Block - if err := row.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); nil != err { + if err := row.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil { if sql.ErrNoRows != err { logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack()) } @@ -684,7 +684,7 @@ func GetChildBlocks(parentID, condition string) (ret []*Block) { sqlStmt += " AND " + condition } rows, err := query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -704,7 +704,7 @@ func GetAllChildBlocks(rootIDs []string, condition string) (ret []*Block) { sqlStmt += " AND " + condition } rows, err := query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } @@ -732,7 +732,7 @@ func GetBlock(id string) (ret *Block) { func GetRootUpdated() (ret map[string]string, err error) { rows, err := query("SELECT root_id, updated FROM `blocks` WHERE type = 'd'") - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -749,7 +749,7 @@ func GetRootUpdated() (ret map[string]string, err error) { func GetDuplicatedRootIDs(blocksTable string) (ret []string) { rows, err := query("SELECT DISTINCT root_id FROM `" + blocksTable + "` GROUP BY id HAVING COUNT(*) > 1") - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -765,7 +765,7 @@ func GetDuplicatedRootIDs(blocksTable string) (ret []string) { func GetAllRootBlocks() (ret []*Block) { stmt := "SELECT * FROM blocks WHERE type = 'd'" rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", stmt, err) return } @@ -811,7 +811,7 @@ func GetBlocks(ids []string) (ret []*Block) { stmtBuilder.WriteString(")") sqlStmt := stmtBuilder.String() rows, err := query(sqlStmt, args...) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } diff --git a/kernel/sql/block_ref.go b/kernel/sql/block_ref.go index 1016ceb2c..667264855 100644 --- a/kernel/sql/block_ref.go +++ b/kernel/sql/block_ref.go @@ -38,10 +38,10 @@ type Ref struct { } func upsertRefs(tx *sql.Tx, tree *parse.Tree) (err error) { - if err = deleteRefsByPath(tx, tree.Box, tree.Path); nil != err { + if err = deleteRefsByPath(tx, tree.Box, tree.Path); err != nil { return } - if err = deleteFileAnnotationRefsByPath(tx, tree.Box, tree.Path); nil != err { + if err = deleteFileAnnotationRefsByPath(tx, tree.Box, tree.Path); err != nil { return } err = insertRefs(tx, tree) @@ -49,10 +49,10 @@ func upsertRefs(tx *sql.Tx, tree *parse.Tree) (err error) { } func deleteRefs(tx *sql.Tx, tree *parse.Tree) (err error) { - if err = deleteRefsByPath(tx, tree.Box, tree.Path); nil != err { + if err = deleteRefsByPath(tx, tree.Box, tree.Path); err != nil { return } - if err = deleteFileAnnotationRefsByPath(tx, tree.Box, tree.Path); nil != err { + if err = deleteFileAnnotationRefsByPath(tx, tree.Box, tree.Path); err != nil { return } return @@ -60,10 +60,10 @@ func deleteRefs(tx *sql.Tx, tree *parse.Tree) (err error) { func insertRefs(tx *sql.Tx, tree *parse.Tree) (err error) { refs, fileAnnotationRefs := refsFromTree(tree) - if err = insertBlockRefs(tx, refs); nil != err { + if err = insertBlockRefs(tx, refs); err != nil { return } - if err = insertFileAnnotationRefs(tx, fileAnnotationRefs); nil != err { + if err = insertFileAnnotationRefs(tx, fileAnnotationRefs); err != nil { return } return err diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.go index 2dcdc2dfc..91777fdd3 100644 --- a/kernel/sql/block_ref_query.go +++ b/kernel/sql/block_ref_query.go @@ -31,7 +31,7 @@ import ( func GetRefDuplicatedDefRootIDs() (ret []string) { rows, err := query("SELECT DISTINCT def_block_root_id FROM `refs` GROUP BY def_block_id, def_block_root_id, block_id HAVING COUNT(*) > 1") - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -75,7 +75,7 @@ func queryRefTexts(refSearchIgnoreLines []string) (ret []string) { sqlStmt += buf.String() sqlStmt += " LIMIT 10240" rows, err := query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", sqlStmt, err) return } @@ -101,7 +101,7 @@ func QueryRefCount(defIDs []string) (ret map[string]int) { ids := strings.Join(defIDs, "','") ids = "('" + ids + "')" rows, err := query("SELECT def_block_id, COUNT(*) AS ref_cnt FROM refs WHERE def_block_id IN " + ids + " GROUP BY def_block_id") - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -109,7 +109,7 @@ func QueryRefCount(defIDs []string) (ret map[string]int) { for rows.Next() { var id string var cnt int - if err = rows.Scan(&id, &cnt); nil != err { + if err = rows.Scan(&id, &cnt); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -121,7 +121,7 @@ func QueryRefCount(defIDs []string) (ret map[string]int) { func QueryRootChildrenRefCount(defRootID string) (ret map[string]int) { ret = map[string]int{} rows, err := query("SELECT def_block_id, COUNT(*) AS ref_cnt FROM refs WHERE def_block_root_id = ? GROUP BY def_block_id", defRootID) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -129,7 +129,7 @@ func QueryRootChildrenRefCount(defRootID string) (ret map[string]int) { for rows.Next() { var id string var cnt int - if err = rows.Scan(&id, &cnt); nil != err { + if err = rows.Scan(&id, &cnt); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -142,7 +142,7 @@ func QueryRootBlockRefCount() (ret map[string]int) { ret = map[string]int{} rows, err := query("SELECT def_block_root_id, COUNT(*) AS ref_cnt FROM refs GROUP BY def_block_root_id") - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -150,7 +150,7 @@ func QueryRootBlockRefCount() (ret map[string]int) { for rows.Next() { var id string var cnt int - if err = rows.Scan(&id, &cnt); nil != err { + if err = rows.Scan(&id, &cnt); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -161,7 +161,7 @@ func QueryRootBlockRefCount() (ret map[string]int) { func QueryDefRootBlocksByRefRootID(refRootID string) (ret []*Block) { rows, err := query("SELECT * FROM blocks WHERE id IN (SELECT DISTINCT def_block_root_id FROM refs WHERE root_id = ?)", refRootID) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -179,7 +179,7 @@ func QueryRefRootBlocksByDefRootIDs(defRootIDs []string) (ret map[string][]*Bloc stmt := "SELECT r.def_block_root_id, b.* FROM refs AS r, blocks AS b ON r.def_block_root_id IN ('" + strings.Join(defRootIDs, "','") + "')" + " AND b.id = r.root_id" rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -187,7 +187,7 @@ func QueryRefRootBlocksByDefRootIDs(defRootIDs []string) (ret map[string][]*Bloc for rows.Next() { var block Block var defRootID string - if err := rows.Scan(&defRootID, &block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); nil != err { + if err := rows.Scan(&defRootID, &block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil { logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack()) return } @@ -261,14 +261,14 @@ func queryDefIDsByDefText(keyword string, excludeIDs []string) (ret []string) { q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content = ? AND def_block_id NOT IN " + notIn } rows, err := query(q, keyword) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } defer rows.Close() for rows.Next() { var id string - if err = rows.Scan(&id); nil != err { + if err = rows.Scan(&id); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -281,14 +281,14 @@ func queryDefIDsByNameAlias(keyword string, excludeIDs []string) (ret []string) ret = []string{} notIn := "('" + strings.Join(excludeIDs, "','") + "')" rows, err := query("SELECT DISTINCT(id), name, alias FROM blocks WHERE (name = ? OR alias LIKE ?) AND id NOT IN "+notIn, keyword, "%"+keyword+"%") - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } defer rows.Close() for rows.Next() { var id, name, alias string - if err = rows.Scan(&id, &name, &alias); nil != err { + if err = rows.Scan(&id, &name, &alias); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -318,14 +318,14 @@ func queryDefIDsByNameAlias(keyword string, excludeIDs []string) (ret []string) func QueryChildDefIDsByRootDefID(rootDefID string) (ret []string) { ret = []string{} rows, err := query("SELECT DISTINCT(def_block_id) FROM refs WHERE def_block_root_id = ?", rootDefID) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } defer rows.Close() for rows.Next() { var id string - if err = rows.Scan(&id); nil != err { + if err = rows.Scan(&id); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -343,14 +343,14 @@ func QueryRefIDsByDefID(defID string, containChildren bool) (refIDs, refTexts [] } else { rows, err = query("SELECT block_id, content FROM refs WHERE def_block_id = ?", defID) } - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } defer rows.Close() for rows.Next() { var id, content string - if err = rows.Scan(&id, &content); nil != err { + if err = rows.Scan(&id, &content); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -376,7 +376,7 @@ func QueryRefsRecent(onlyDoc bool, typeFilter string, ignoreLines []string) (ret } stmt += " GROUP BY r.def_block_id ORDER BY r.id DESC LIMIT 32" rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -410,7 +410,7 @@ func QueryRefsByDefID(defBlockID string, containChildren bool) (ret []*Ref) { rows, err = query("SELECT * FROM refs WHERE def_block_id = ?", defBlockID) } } - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -425,7 +425,7 @@ func QueryRefsByDefID(defBlockID string, containChildren bool) (ret []*Ref) { func QueryRefsByDefIDRefID(defBlockID, refBlockID string) (ret []*Ref) { stmt := "SELECT * FROM refs WHERE def_block_id = ? AND block_id = ?" rows, err := query(stmt, defBlockID, refBlockID) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -445,7 +445,7 @@ func DefRefs(condition string) (ret []map[*Block]*Block) { } rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -455,7 +455,7 @@ func DefRefs(condition string) (ret []map[*Block]*Block) { var ref Block var rel string if err = rows.Scan(&ref.ID, &ref.ParentID, &ref.RootID, &ref.Hash, &ref.Box, &ref.Path, &ref.HPath, &ref.Name, &ref.Alias, &ref.Memo, &ref.Tag, &ref.Content, &ref.FContent, &ref.Markdown, &ref.Length, &ref.Type, &ref.SubType, &ref.IAL, &ref.Sort, &ref.Created, &ref.Updated, - &rel); nil != err { + &rel); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -463,7 +463,7 @@ func DefRefs(condition string) (ret []map[*Block]*Block) { } rows, err = query("SELECT def.* FROM blocks AS def, refs AS r WHERE def.id = r.def_block_id") - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -490,7 +490,7 @@ func DefRefs(condition string) (ret []map[*Block]*Block) { func scanRefRows(rows *sql.Rows) (ret *Ref) { var ref Ref - if err := rows.Scan(&ref.ID, &ref.DefBlockID, &ref.DefBlockParentID, &ref.DefBlockRootID, &ref.DefBlockPath, &ref.BlockID, &ref.RootID, &ref.Box, &ref.Path, &ref.Content, &ref.Markdown, &ref.Type); nil != err { + if err := rows.Scan(&ref.ID, &ref.DefBlockID, &ref.DefBlockParentID, &ref.DefBlockRootID, &ref.DefBlockPath, &ref.BlockID, &ref.RootID, &ref.Box, &ref.Path, &ref.Content, &ref.Markdown, &ref.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } diff --git a/kernel/sql/cache.go b/kernel/sql/cache.go index 6c106585b..3e18c19fe 100644 --- a/kernel/sql/cache.go +++ b/kernel/sql/cache.go @@ -53,7 +53,7 @@ func putBlockCache(block *Block) { } cloned := &Block{} - if err := copier.Copy(cloned, block); nil != err { + if err := copier.Copy(cloned, block); err != nil { logging.LogErrorf("clone block failed: %v", err) return } diff --git a/kernel/sql/database.go b/kernel/sql/database.go index 870d4dc49..dbc29a22e 100644 --- a/kernel/sql/database.go +++ b/kernel/sql/database.go @@ -96,7 +96,7 @@ func InitDatabase(forceRebuild bool) (err error) { closeDatabase() if gulu.File.IsExist(util.DBPath) { - if err = removeDatabaseFile(); nil != err { + if err = removeDatabaseFile(); err != nil { logging.LogErrorf("remove database file [%s] failed: %s", util.DBPath, err) util.PushClearProgress() err = nil @@ -112,111 +112,111 @@ func InitDatabase(forceRebuild bool) (err error) { func initDBTables() { _, err := db.Exec("DROP TABLE IF EXISTS stat") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [stat] failed: %s", err) } _, err = db.Exec("CREATE TABLE stat (key, value)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [stat] failed: %s", err) } setDatabaseVer() _, err = db.Exec("DROP TABLE IF EXISTS blocks") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [blocks] failed: %s", err) } _, err = db.Exec("CREATE TABLE blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [blocks] failed: %s", err) } _, err = db.Exec("CREATE INDEX idx_blocks_id ON blocks(id)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create index [idx_blocks_id] failed: %s", err) } _, err = db.Exec("CREATE INDEX idx_blocks_parent_id ON blocks(parent_id)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create index [idx_blocks_parent_id] failed: %s", err) } _, err = db.Exec("CREATE INDEX idx_blocks_root_id ON blocks(root_id)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create index [idx_blocks_root_id] failed: %s", err) } _, err = db.Exec("DROP TABLE IF EXISTS blocks_fts") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [blocks_fts] failed: %s", err) } _, err = db.Exec("CREATE VIRTUAL TABLE blocks_fts USING fts5(id UNINDEXED, parent_id UNINDEXED, root_id UNINDEXED, hash UNINDEXED, box UNINDEXED, path UNINDEXED, hpath, name, alias, memo, tag, content, fcontent, markdown UNINDEXED, length UNINDEXED, type UNINDEXED, subtype UNINDEXED, ial, sort UNINDEXED, created UNINDEXED, updated UNINDEXED, tokenize=\"siyuan\")") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [blocks_fts] failed: %s", err) } _, err = db.Exec("DROP TABLE IF EXISTS blocks_fts_case_insensitive") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [blocks_fts_case_insensitive] failed: %s", err) } _, err = db.Exec("CREATE VIRTUAL TABLE blocks_fts_case_insensitive USING fts5(id UNINDEXED, parent_id UNINDEXED, root_id UNINDEXED, hash UNINDEXED, box UNINDEXED, path UNINDEXED, hpath, name, alias, memo, tag, content, fcontent, markdown UNINDEXED, length UNINDEXED, type UNINDEXED, subtype UNINDEXED, ial, sort UNINDEXED, created UNINDEXED, updated UNINDEXED, tokenize=\"siyuan case_insensitive\")") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [blocks_fts_case_insensitive] failed: %s", err) } _, err = db.Exec("DROP TABLE IF EXISTS spans") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [spans] failed: %s", err) } _, err = db.Exec("CREATE TABLE spans (id, block_id, root_id, box, path, content, markdown, type, ial)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [spans] failed: %s", err) } _, err = db.Exec("CREATE INDEX idx_spans_root_id ON spans(root_id)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create index [idx_spans_root_id] failed: %s", err) } _, err = db.Exec("DROP TABLE IF EXISTS assets") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [assets] failed: %s", err) } _, err = db.Exec("CREATE TABLE assets (id, block_id, root_id, box, docpath, path, name, title, hash)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [assets] failed: %s", err) } _, err = db.Exec("CREATE INDEX idx_assets_root_id ON assets(root_id)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create index [idx_assets_root_id] failed: %s", err) } _, err = db.Exec("DROP TABLE IF EXISTS attributes") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [attributes] failed: %s", err) } _, err = db.Exec("CREATE TABLE attributes (id, name, value, type, block_id, root_id, box, path)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [attributes] failed: %s", err) } _, err = db.Exec("CREATE INDEX idx_attributes_root_id ON attributes(root_id)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create index [idx_attributes_root_id] failed: %s", err) } _, err = db.Exec("DROP TABLE IF EXISTS refs") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [refs] failed: %s", err) } _, err = db.Exec("CREATE TABLE refs (id, def_block_id, def_block_parent_id, def_block_root_id, def_block_path, block_id, root_id, box, path, content, markdown, type)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [refs] failed: %s", err) } _, err = db.Exec("DROP TABLE IF EXISTS file_annotation_refs") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [refs] failed: %s", err) } _, err = db.Exec("CREATE TABLE file_annotation_refs (id, file_path, annotation_id, block_id, root_id, box, path, content, type)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [refs] failed: %s", err) } } @@ -237,7 +237,7 @@ func initDBConnection() { "&_case_sensitive_like=OFF" var err error db, err = sql.Open("sqlite3_extended", dsn) - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create database failed: %s", err) } db.SetMaxIdleConns(20) @@ -258,7 +258,7 @@ func InitHistoryDatabase(forceRebuild bool) { } historyDB.Close() - if err := os.RemoveAll(util.HistoryDBPath); nil != err { + if err := os.RemoveAll(util.HistoryDBPath); err != nil { logging.LogErrorf("remove history database file [%s] failed: %s", util.HistoryDBPath, err) return } @@ -284,7 +284,7 @@ func initHistoryDBConnection() { "&_case_sensitive_like=OFF" var err error historyDB, err = sql.Open("sqlite3_extended", dsn) - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create history database failed: %s", err) } historyDB.SetMaxIdleConns(3) @@ -295,7 +295,7 @@ func initHistoryDBConnection() { func initHistoryDBTables() { historyDB.Exec("DROP TABLE histories_fts_case_insensitive") _, err := historyDB.Exec("CREATE VIRTUAL TABLE histories_fts_case_insensitive USING fts5(id UNINDEXED, type UNINDEXED, op UNINDEXED, title, content, path UNINDEXED, created UNINDEXED, tokenize=\"siyuan case_insensitive\")") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [histories_fts_case_insensitive] failed: %s", err) } } @@ -313,7 +313,7 @@ func InitAssetContentDatabase(forceRebuild bool) { } assetContentDB.Close() - if err := os.RemoveAll(util.AssetContentDBPath); nil != err { + if err := os.RemoveAll(util.AssetContentDBPath); err != nil { logging.LogErrorf("remove assets database file [%s] failed: %s", util.AssetContentDBPath, err) return } @@ -339,7 +339,7 @@ func initAssetContentDBConnection() { "&_case_sensitive_like=OFF" var err error assetContentDB, err = sql.Open("sqlite3_extended", dsn) - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create assets database failed: %s", err) } assetContentDB.SetMaxIdleConns(3) @@ -350,7 +350,7 @@ func initAssetContentDBConnection() { func initAssetContentDBTables() { assetContentDB.Exec("DROP TABLE asset_contents_fts_case_insensitive") _, err := assetContentDB.Exec("CREATE VIRTUAL TABLE asset_contents_fts_case_insensitive USING fts5(id UNINDEXED, name, ext, path, size UNINDEXED, updated UNINDEXED, content, tokenize=\"siyuan case_insensitive\")") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [asset_contents_fts_case_insensitive] failed: %s", err) } } @@ -718,7 +718,7 @@ func buildSpanFromNode(n *ast.Node, tree *parse.Tree, rootID, boxID, p string) ( } case ast.NodeInlineHTML, ast.NodeHTMLBlock, ast.NodeIFrame, ast.NodeWidget, ast.NodeAudio, ast.NodeVideo: nodes, err := html.ParseFragment(bytes.NewReader(n.Tokens), &html.Node{Type: html.ElementNode}) - if nil != err { + if err != nil { logging.LogErrorf("parse HTML failed: %s", err) walkStatus = ast.WalkContinue return @@ -954,22 +954,22 @@ func heading(node *ast.Node) *ast.Node { } func deleteByBoxTx(tx *sql.Tx, box string) (err error) { - if err = deleteBlocksByBoxTx(tx, box); nil != err { + if err = deleteBlocksByBoxTx(tx, box); err != nil { return } - if err = deleteSpansByBoxTx(tx, box); nil != err { + if err = deleteSpansByBoxTx(tx, box); err != nil { return } - if err = deleteAssetsByBoxTx(tx, box); nil != err { + if err = deleteAssetsByBoxTx(tx, box); err != nil { return } - if err = deleteAttributesByBoxTx(tx, box); nil != err { + if err = deleteAttributesByBoxTx(tx, box); err != nil { return } - if err = deleteBlockRefsByBoxTx(tx, box); nil != err { + if err = deleteBlockRefsByBoxTx(tx, box); err != nil { return } - if err = deleteFileAnnotationRefsByBoxTx(tx, box); nil != err { + if err = deleteFileAnnotationRefsByBoxTx(tx, box); err != nil { return } return @@ -989,13 +989,13 @@ func deleteBlocksByIDs(tx *sql.Tx, ids []string) (err error) { var rowIDs []string stmt := "SELECT ROWID FROM blocks WHERE id IN (" + strings.Join(ftsIDs, ",") + ")" rows, err := tx.Query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("query block rowIDs failed: %s", err) return } for rows.Next() { var rowID int64 - if err = rows.Scan(&rowID); nil != err { + if err = rows.Scan(&rowID); err != nil { logging.LogErrorf("scan block rowID failed: %s", err) rows.Close() return @@ -1009,18 +1009,18 @@ func deleteBlocksByIDs(tx *sql.Tx, ids []string) (err error) { } stmt = "DELETE FROM blocks WHERE ROWID IN (" + strings.Join(rowIDs, ",") + ")" - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } stmt = "DELETE FROM blocks_fts WHERE ROWID IN (" + strings.Join(rowIDs, ",") + ")" - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } if !caseSensitive { stmt = "DELETE FROM blocks_fts_case_insensitive WHERE ROWID IN (" + strings.Join(rowIDs, ",") + ")" - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } } @@ -1029,16 +1029,16 @@ func deleteBlocksByIDs(tx *sql.Tx, ids []string) (err error) { func deleteBlocksByBoxTx(tx *sql.Tx, box string) (err error) { stmt := "DELETE FROM blocks WHERE box = ?" - if err = execStmtTx(tx, stmt, box); nil != err { + if err = execStmtTx(tx, stmt, box); err != nil { return } stmt = "DELETE FROM blocks_fts WHERE box = ?" - if err = execStmtTx(tx, stmt, box); nil != err { + if err = execStmtTx(tx, stmt, box); err != nil { return } if !caseSensitive { stmt = "DELETE FROM blocks_fts_case_insensitive WHERE box = ?" - if err = execStmtTx(tx, stmt, box); nil != err { + if err = execStmtTx(tx, stmt, box); err != nil { return } } @@ -1096,7 +1096,7 @@ func deleteRefsByPathTx(tx *sql.Tx, box, path string) (err error) { } func deleteRefsByBoxTx(tx *sql.Tx, box string) (err error) { - if err = deleteFileAnnotationRefsByBoxTx(tx, box); nil != err { + if err = deleteFileAnnotationRefsByBoxTx(tx, box); err != nil { return } return deleteBlockRefsByBoxTx(tx, box) @@ -1128,37 +1128,37 @@ func deleteFileAnnotationRefsByBoxTx(tx *sql.Tx, box string) (err error) { func deleteByRootID(tx *sql.Tx, rootID string, context map[string]interface{}) (err error) { stmt := "DELETE FROM blocks WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } stmt = "DELETE FROM blocks_fts WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } if !caseSensitive { stmt = "DELETE FROM blocks_fts_case_insensitive WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } } stmt = "DELETE FROM spans WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } stmt = "DELETE FROM assets WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } stmt = "DELETE FROM refs WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } stmt = "DELETE FROM file_annotation_refs WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } stmt = "DELETE FROM attributes WHERE root_id = ?" - if err = execStmtTx(tx, stmt, rootID); nil != err { + if err = execStmtTx(tx, stmt, rootID); err != nil { return } ClearCache() @@ -1174,37 +1174,37 @@ func batchDeleteByRootIDs(tx *sql.Tx, rootIDs []string, context map[string]inter ids := strings.Join(rootIDs, "','") ids = "('" + ids + "')" stmt := "DELETE FROM blocks WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } stmt = "DELETE FROM blocks_fts WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } if !caseSensitive { stmt = "DELETE FROM blocks_fts_case_insensitive WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } } stmt = "DELETE FROM spans WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } stmt = "DELETE FROM assets WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } stmt = "DELETE FROM refs WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } stmt = "DELETE FROM file_annotation_refs WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } stmt = "DELETE FROM attributes WHERE root_id IN " + ids - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } ClearCache() @@ -1214,37 +1214,37 @@ func batchDeleteByRootIDs(tx *sql.Tx, rootIDs []string, context map[string]inter func batchDeleteByPathPrefix(tx *sql.Tx, boxID, pathPrefix string) (err error) { stmt := "DELETE FROM blocks WHERE box = ? AND path LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } stmt = "DELETE FROM blocks_fts WHERE box = ? AND path LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } if !caseSensitive { stmt = "DELETE FROM blocks_fts_case_insensitive WHERE box = ? AND path LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } } stmt = "DELETE FROM spans WHERE box = ? AND path LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } stmt = "DELETE FROM assets WHERE box = ? AND docpath LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } stmt = "DELETE FROM refs WHERE box = ? AND path LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } stmt = "DELETE FROM file_annotation_refs WHERE box = ? AND path LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } stmt = "DELETE FROM attributes WHERE box = ? AND path LIKE ?" - if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); nil != err { + if err = execStmtTx(tx, stmt, boxID, pathPrefix+"%"); err != nil { return } ClearCache() @@ -1253,16 +1253,16 @@ func batchDeleteByPathPrefix(tx *sql.Tx, boxID, pathPrefix string) (err error) { func batchUpdateHPath(tx *sql.Tx, rootID, newHPath string, context map[string]interface{}) (err error) { stmt := "UPDATE blocks SET hpath = ? WHERE root_id = ?" - if err = execStmtTx(tx, stmt, newHPath, rootID); nil != err { + if err = execStmtTx(tx, stmt, newHPath, rootID); err != nil { return } stmt = "UPDATE blocks_fts SET hpath = ? WHERE root_id = ?" - if err = execStmtTx(tx, stmt, newHPath, rootID); nil != err { + if err = execStmtTx(tx, stmt, newHPath, rootID); err != nil { return } if !caseSensitive { stmt = "UPDATE blocks_fts_case_insensitive SET hpath = ? WHERE root_id = ?" - if err = execStmtTx(tx, stmt, newHPath, rootID); nil != err { + if err = execStmtTx(tx, stmt, newHPath, rootID); err != nil { return } } @@ -1273,15 +1273,15 @@ func batchUpdateHPath(tx *sql.Tx, rootID, newHPath string, context map[string]in } func CloseDatabase() { - if err := closeDatabase(); nil != err { + if err := closeDatabase(); err != nil { logging.LogErrorf("close database failed: %s", err) return } - if err := historyDB.Close(); nil != err { + if err := historyDB.Close(); err != nil { logging.LogErrorf("close history database failed: %s", err) return } - if err := assetContentDB.Close(); nil != err { + if err := assetContentDB.Close(); err != nil { logging.LogErrorf("close asset content database failed: %s", err) return } @@ -1307,7 +1307,7 @@ func query(query string, args ...interface{}) (*sql.Rows, error) { } func beginTx() (tx *sql.Tx, err error) { - if tx, err = db.Begin(); nil != err { + if tx, err = db.Begin(); err != nil { logging.LogErrorf("begin tx failed: %s\n %s", err, logging.ShortStack()) if strings.Contains(err.Error(), "database is locked") { os.Exit(logging.ExitCodeReadOnlyDatabase) @@ -1322,14 +1322,14 @@ func commitTx(tx *sql.Tx) (err error) { return errors.New("tx is nil") } - if err = tx.Commit(); nil != err { + if err = tx.Commit(); err != nil { logging.LogErrorf("commit tx failed: %s\n %s", err, logging.ShortStack()) } return } func beginHistoryTx() (tx *sql.Tx, err error) { - if tx, err = historyDB.Begin(); nil != err { + if tx, err = historyDB.Begin(); err != nil { logging.LogErrorf("begin history tx failed: %s\n %s", err, logging.ShortStack()) if strings.Contains(err.Error(), "database is locked") { os.Exit(logging.ExitCodeReadOnlyDatabase) @@ -1344,14 +1344,14 @@ func commitHistoryTx(tx *sql.Tx) (err error) { return errors.New("tx is nil") } - if err = tx.Commit(); nil != err { + if err = tx.Commit(); err != nil { logging.LogErrorf("commit tx failed: %s\n %s", err, logging.ShortStack()) } return } func beginAssetContentTx() (tx *sql.Tx, err error) { - if tx, err = assetContentDB.Begin(); nil != err { + if tx, err = assetContentDB.Begin(); err != nil { logging.LogErrorf("begin asset content tx failed: %s\n %s", err, logging.ShortStack()) if strings.Contains(err.Error(), "database is locked") { os.Exit(logging.ExitCodeReadOnlyDatabase) @@ -1366,7 +1366,7 @@ func commitAssetContentTx(tx *sql.Tx) (err error) { return errors.New("tx is nil") } - if err = tx.Commit(); nil != err { + if err = tx.Commit(); err != nil { logging.LogErrorf("commit tx failed: %s\n %s", err, logging.ShortStack()) } return @@ -1374,10 +1374,10 @@ func commitAssetContentTx(tx *sql.Tx) (err error) { func prepareExecInsertTx(tx *sql.Tx, stmtSQL string, args []interface{}) (err error) { stmt, err := tx.Prepare(stmtSQL) - if nil != err { + if err != nil { return } - if _, err = stmt.Exec(args...); nil != err { + if _, err = stmt.Exec(args...); err != nil { logging.LogErrorf("exec database stmt [%s] failed: %s", stmtSQL, err) return } @@ -1385,7 +1385,7 @@ func prepareExecInsertTx(tx *sql.Tx, stmtSQL string, args []interface{}) (err er } func execStmtTx(tx *sql.Tx, stmt string, args ...interface{}) (err error) { - if _, err = tx.Exec(stmt, args...); nil != err { + if _, err = tx.Exec(stmt, args...); err != nil { if strings.Contains(err.Error(), "database disk image is malformed") { tx.Rollback() closeDatabase() @@ -1446,15 +1446,15 @@ func ialAttr(ial, name string) (ret string) { func removeDatabaseFile() (err error) { err = os.RemoveAll(util.DBPath) - if nil != err { + if err != nil { return } err = os.RemoveAll(util.DBPath + "-shm") - if nil != err { + if err != nil { return } err = os.RemoveAll(util.DBPath + "-wal") - if nil != err { + if err != nil { return } return diff --git a/kernel/sql/file_annotation_ref.go b/kernel/sql/file_annotation_ref.go index 604ebcfe5..8c1df8375 100644 --- a/kernel/sql/file_annotation_ref.go +++ b/kernel/sql/file_annotation_ref.go @@ -35,14 +35,14 @@ type FileAnnotationRef struct { func QueryRefIDsByAnnotationID(annotationID string) (refIDs, refTexts []string) { refIDs = []string{} rows, err := query("SELECT block_id, content FROM file_annotation_refs WHERE annotation_id = ?", annotationID) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } defer rows.Close() for rows.Next() { var id, content string - if err = rows.Scan(&id, &content); nil != err { + if err = rows.Scan(&id, &content); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } diff --git a/kernel/sql/history.go b/kernel/sql/history.go index 5a1dd2760..3ccc02841 100644 --- a/kernel/sql/history.go +++ b/kernel/sql/history.go @@ -39,7 +39,7 @@ type History struct { func QueryHistory(stmt string) (ret []map[string]interface{}, err error) { ret = []map[string]interface{}{} rows, err := queryHistory(stmt) - if nil != err { + if err != nil { logging.LogWarnf("sql query [%s] failed: %s", stmt, err) return } @@ -57,7 +57,7 @@ func QueryHistory(stmt string) (ret []map[string]interface{}, err error) { columnPointers[i] = &columns[i] } - if err = rows.Scan(columnPointers...); nil != err { + if err = rows.Scan(columnPointers...); err != nil { return } @@ -73,7 +73,7 @@ func QueryHistory(stmt string) (ret []map[string]interface{}, err error) { func SelectHistoriesRawStmt(stmt string) (ret []*History) { rows, err := historyDB.Query(stmt) - if nil != err { + if err != nil { logging.LogWarnf("sql query [%s] failed: %s", stmt, err) return } @@ -88,7 +88,7 @@ func SelectHistoriesRawStmt(stmt string) (ret []*History) { func scanHistoryRows(rows *sql.Rows) (ret *History) { var history History - if err := rows.Scan(&history.ID, &history.Type, &history.Op, &history.Title, &history.Content, &history.Path, &history.Created); nil != err { + if err := rows.Scan(&history.ID, &history.Type, &history.Op, &history.Title, &history.Content, &history.Path, &history.Created); err != nil { logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack()) return } @@ -106,7 +106,7 @@ func queryHistory(query string, args ...interface{}) (*sql.Rows, error) { func deleteOutdatedHistories(tx *sql.Tx, before int64, context map[string]interface{}) (err error) { stmt := "DELETE FROM histories_fts_case_insensitive WHERE CAST(created AS INTEGER) < ?" - if err = execStmtTx(tx, stmt, before); nil != err { + if err = execStmtTx(tx, stmt, before); err != nil { return } return @@ -129,13 +129,13 @@ func insertHistories(tx *sql.Tx, histories []*History, context map[string]interf continue } - if err = insertHistories0(tx, bulk, context); nil != err { + if err = insertHistories0(tx, bulk, context); err != nil { return } bulk = []*History{} } if 0 < len(bulk) { - if err = insertHistories0(tx, bulk, context); nil != err { + if err = insertHistories0(tx, bulk, context); err != nil { return } } @@ -157,7 +157,7 @@ func insertHistories0(tx *sql.Tx, bulk []*History, context map[string]interface{ } stmt := fmt.Sprintf(HistoriesFTSCaseInsensitiveInsert, strings.Join(valueStrings, ",")) - if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err { + if err = prepareExecInsertTx(tx, stmt, valueArgs); err != nil { return } diff --git a/kernel/sql/queue.go b/kernel/sql/queue.go index 27d544798..cd4a10103 100644 --- a/kernel/sql/queue.go +++ b/kernel/sql/queue.go @@ -136,20 +136,20 @@ func FlushQueue() { } tx, err := beginTx() - if nil != err { + if err != nil { return } groupOpsCurrent[op.action]++ context["current"] = groupOpsCurrent[op.action] context["total"] = groupOpsTotal[op.action] - if err = execOp(op, tx, context); nil != err { + if err = execOp(op, tx, context); err != nil { tx.Rollback() logging.LogErrorf("queue operation [%s] failed: %s", op.action, err) continue } - if err = commitTx(tx); nil != err { + if err = commitTx(tx); err != nil { logging.LogErrorf("commit tx failed: %s", err) continue } @@ -188,7 +188,7 @@ func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]interface{}) (e err = batchDeleteByRootIDs(tx, op.removeTreeIDs, context) case "rename": err = batchUpdateHPath(tx, op.renameTree.ID, op.renameTree.HPath, context) - if nil != err { + if err != nil { break } err = updateRootContent(tx, path.Base(op.renameTree.HPath), op.renameTree.Root.IALAttr("updated"), op.renameTree.ID) diff --git a/kernel/sql/queue_asset_content.go b/kernel/sql/queue_asset_content.go index 67eb955dd..5140db724 100644 --- a/kernel/sql/queue_asset_content.go +++ b/kernel/sql/queue_asset_content.go @@ -72,7 +72,7 @@ func FlushAssetContentQueue() { } tx, err := beginAssetContentTx() - if nil != err { + if err != nil { return } @@ -80,14 +80,14 @@ func FlushAssetContentQueue() { context["current"] = groupOpsCurrent[op.action] context["total"] = groupOpsTotal[op.action] - if err = execAssetContentOp(op, tx, context); nil != err { + if err = execAssetContentOp(op, tx, context); err != nil { tx.Rollback() logging.LogErrorf("queue operation failed: %s", err) eventbus.Publish(util.EvtSQLAssetContentRebuild) return } - if err = commitAssetContentTx(tx); nil != err { + if err = commitAssetContentTx(tx); err != nil { logging.LogErrorf("commit tx failed: %s", err) return } diff --git a/kernel/sql/queue_history.go b/kernel/sql/queue_history.go index b9643210a..493ea9470 100644 --- a/kernel/sql/queue_history.go +++ b/kernel/sql/queue_history.go @@ -72,7 +72,7 @@ func FlushHistoryQueue() { } tx, err := beginHistoryTx() - if nil != err { + if err != nil { return } @@ -80,14 +80,14 @@ func FlushHistoryQueue() { context["current"] = groupOpsCurrent[op.action] context["total"] = groupOpsTotal[op.action] - if err = execHistoryOp(op, tx, context); nil != err { + if err = execHistoryOp(op, tx, context); err != nil { tx.Rollback() logging.LogErrorf("queue operation failed: %s", err) eventbus.Publish(util.EvtSQLHistoryRebuild) return } - if err = commitHistoryTx(tx); nil != err { + if err = commitHistoryTx(tx); err != nil { logging.LogErrorf("commit tx failed: %s", err) return } diff --git a/kernel/sql/span.go b/kernel/sql/span.go index 84f6b86c1..773a8494d 100644 --- a/kernel/sql/span.go +++ b/kernel/sql/span.go @@ -39,7 +39,7 @@ type Span struct { func SelectSpansRawStmt(stmt string, limit int) (ret []*Span) { parsedStmt, err := sqlparser.Parse(stmt) - if nil != err { + if err != nil { //logging.LogErrorf("select [%s] failed: %s", stmt, err) return } @@ -65,7 +65,7 @@ func SelectSpansRawStmt(stmt string, limit int) (ret []*Span) { stmt = strings.ReplaceAll(stmt, "\\\\*", "\\*") stmt = strings.ReplaceAll(stmt, "from dual", "") rows, err := query(stmt) - if nil != err { + if err != nil { if strings.Contains(err.Error(), "syntax error") { return } @@ -83,7 +83,7 @@ func SelectSpansRawStmt(stmt string, limit int) (ret []*Span) { func QueryTagSpansByLabel(label string) (ret []*Span) { stmt := "SELECT * FROM spans WHERE type LIKE '%tag%' AND content LIKE '%" + label + "%' GROUP BY block_id" rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -99,7 +99,7 @@ func QueryTagSpansByKeyword(keyword string, limit int) (ret []*Span) { stmt := "SELECT * FROM spans WHERE type LIKE '%tag%' AND content LIKE '%" + keyword + "%' GROUP BY markdown" stmt += " LIMIT " + strconv.Itoa(limit) rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -117,7 +117,7 @@ func QueryTagSpans(p string) (ret []*Span) { stmt += " AND path = '" + p + "'" } rows, err := query(stmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query failed: %s", err) return } @@ -131,7 +131,7 @@ func QueryTagSpans(p string) (ret []*Span) { func scanSpanRows(rows *sql.Rows) (ret *Span) { var span Span - if err := rows.Scan(&span.ID, &span.BlockID, &span.RootID, &span.Box, &span.Path, &span.Content, &span.Markdown, &span.Type, &span.IAL); nil != err { + if err := rows.Scan(&span.ID, &span.BlockID, &span.RootID, &span.Box, &span.Path, &span.Content, &span.Markdown, &span.Type, &span.IAL); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } diff --git a/kernel/sql/stat.go b/kernel/sql/stat.go index 6d808f048..0f03f5357 100644 --- a/kernel/sql/stat.go +++ b/kernel/sql/stat.go @@ -33,7 +33,7 @@ func getDatabaseVer() (ret string) { key := "siyuan_database_ver" stmt := "SELECT value FROM stat WHERE `key` = ?" row := db.QueryRow(stmt, key) - if err := row.Scan(&ret); nil != err { + if err := row.Scan(&ret); err != nil { if !strings.Contains(err.Error(), "no such table") { logging.LogErrorf("query database version failed: %s", err) } @@ -44,10 +44,10 @@ func getDatabaseVer() (ret string) { func setDatabaseVer() { key := "siyuan_database_ver" tx, err := beginTx() - if nil != err { + if err != nil { return } - if err = putStat(tx, key, util.DatabaseVer); nil != err { + if err = putStat(tx, key, util.DatabaseVer); err != nil { return } commitTx(tx) @@ -55,7 +55,7 @@ func setDatabaseVer() { func putStat(tx *sql.Tx, key, value string) (err error) { stmt := "DELETE FROM stat WHERE `key` = '" + key + "'" - if err = execStmtTx(tx, stmt); nil != err { + if err = execStmtTx(tx, stmt); err != nil { return } diff --git a/kernel/sql/upsert.go b/kernel/sql/upsert.go index 8e81b0e41..7fed62fe1 100644 --- a/kernel/sql/upsert.go +++ b/kernel/sql/upsert.go @@ -69,13 +69,13 @@ func insertBlocks(tx *sql.Tx, blocks []*Block, context map[string]interface{}) ( continue } - if err = insertBlocks0(tx, bulk, context); nil != err { + if err = insertBlocks0(tx, bulk, context); err != nil { return } bulk = []*Block{} } if 0 < len(bulk) { - if err = insertBlocks0(tx, bulk, context); nil != err { + if err = insertBlocks0(tx, bulk, context); err != nil { return } } @@ -115,7 +115,7 @@ func insertBlocks0(tx *sql.Tx, bulk []*Block, context map[string]interface{}) (e } stmt := fmt.Sprintf(BlocksInsert, strings.Join(valueStrings, ",")) - if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err { + if err = prepareExecInsertTx(tx, stmt, valueArgs); err != nil { return } hashBuf.WriteString("blocks") @@ -124,13 +124,13 @@ func insertBlocks0(tx *sql.Tx, bulk []*Block, context map[string]interface{}) (e //eventbus.Publish(eventbus.EvtSQLInsertBlocks, context, current, total, len(bulk), evtHash) stmt = fmt.Sprintf(BlocksFTSInsert, strings.Join(valueStrings, ",")) - if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err { + if err = prepareExecInsertTx(tx, stmt, valueArgs); err != nil { return } if !caseSensitive { stmt = fmt.Sprintf(BlocksFTSCaseInsensitiveInsert, strings.Join(valueStrings, ",")) - if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err { + if err = prepareExecInsertTx(tx, stmt, valueArgs); err != nil { return } } @@ -152,13 +152,13 @@ func insertAttributes(tx *sql.Tx, attributes []*Attribute) (err error) { continue } - if err = insertAttribute0(tx, bulk); nil != err { + if err = insertAttribute0(tx, bulk); err != nil { return } bulk = []*Attribute{} } if 0 < len(bulk) { - if err = insertAttribute0(tx, bulk); nil != err { + if err = insertAttribute0(tx, bulk); err != nil { return } } @@ -200,13 +200,13 @@ func insertAssets(tx *sql.Tx, assets []*Asset) (err error) { continue } - if err = insertAsset0(tx, bulk); nil != err { + if err = insertAsset0(tx, bulk); err != nil { return } bulk = []*Asset{} } if 0 < len(bulk) { - if err = insertAsset0(tx, bulk); nil != err { + if err = insertAsset0(tx, bulk); err != nil { return } } @@ -249,13 +249,13 @@ func insertSpans(tx *sql.Tx, spans []*Span) (err error) { continue } - if err = insertSpans0(tx, bulk); nil != err { + if err = insertSpans0(tx, bulk); err != nil { return } bulk = []*Span{} } if 0 < len(bulk) { - if err = insertSpans0(tx, bulk); nil != err { + if err = insertSpans0(tx, bulk); err != nil { return } } @@ -298,13 +298,13 @@ func insertBlockRefs(tx *sql.Tx, refs []*Ref) (err error) { continue } - if err = insertRefs0(tx, bulk); nil != err { + if err = insertRefs0(tx, bulk); err != nil { return } bulk = []*Ref{} } if 0 < len(bulk) { - if err = insertRefs0(tx, bulk); nil != err { + if err = insertRefs0(tx, bulk); err != nil { return } } @@ -352,13 +352,13 @@ func insertFileAnnotationRefs(tx *sql.Tx, refs []*FileAnnotationRef) (err error) continue } - if err = insertFileAnnotationRefs0(tx, bulk); nil != err { + if err = insertFileAnnotationRefs0(tx, bulk); err != nil { return } bulk = []*FileAnnotationRef{} } if 0 < len(bulk) { - if err = insertFileAnnotationRefs0(tx, bulk); nil != err { + if err = insertFileAnnotationRefs0(tx, bulk); err != nil { return } } @@ -425,28 +425,28 @@ func upsertTree(tx *sql.Tx, tree *parse.Tree, context map[string]interface{}) (e toRemoves = append(toRemoves, b.ID) } - if err = deleteBlocksByIDs(tx, toRemoves); nil != err { + if err = deleteBlocksByIDs(tx, toRemoves); err != nil { return } - if err = deleteSpansByRootID(tx, tree.ID); nil != err { + if err = deleteSpansByRootID(tx, tree.ID); err != nil { return } - if err = deleteAssetsByRootID(tx, tree.ID); nil != err { + if err = deleteAssetsByRootID(tx, tree.ID); err != nil { return } - if err = deleteAttributesByRootID(tx, tree.ID); nil != err { + if err = deleteAttributesByRootID(tx, tree.ID); err != nil { return } - if err = deleteRefsByPathTx(tx, tree.Box, tree.Path); nil != err { + if err = deleteRefsByPathTx(tx, tree.Box, tree.Path); err != nil { return } - if err = deleteFileAnnotationRefsByPathTx(tx, tree.Box, tree.Path); nil != err { + if err = deleteFileAnnotationRefsByPathTx(tx, tree.Box, tree.Path); err != nil { return } refs, fileAnnotationRefs := refsFromTree(tree) - if err = insertTree0(tx, tree, context, blocks, spans, assets, attributes, refs, fileAnnotationRefs); nil != err { + if err = insertTree0(tx, tree, context, blocks, spans, assets, attributes, refs, fileAnnotationRefs); err != nil { return } return err @@ -463,30 +463,30 @@ func insertTree0(tx *sql.Tx, tree *parse.Tree, context map[string]interface{}, } } - if err = insertBlocks(tx, blocks, context); nil != err { + if err = insertBlocks(tx, blocks, context); err != nil { return } - if err = insertBlockRefs(tx, refs); nil != err { + if err = insertBlockRefs(tx, refs); err != nil { return } - if err = insertFileAnnotationRefs(tx, fileAnnotationRefs); nil != err { + if err = insertFileAnnotationRefs(tx, fileAnnotationRefs); err != nil { return } if 0 < len(spans) { // 移除文档标签,否则会重复添加 https://github.com/siyuan-note/siyuan/issues/3723 - if err = deleteSpansByRootID(tx, tree.Root.ID); nil != err { + if err = deleteSpansByRootID(tx, tree.Root.ID); err != nil { return } - if err = insertSpans(tx, spans); nil != err { + if err = insertSpans(tx, spans); err != nil { return } } - if err = insertAssets(tx, assets); nil != err { + if err = insertAssets(tx, assets); err != nil { return } - if err = insertAttributes(tx, attributes); nil != err { + if err = insertAttributes(tx, attributes); err != nil { return } return @@ -511,17 +511,17 @@ func getIndexIgnoreLines() (ret []string) { IndexIgnoreCached = true indexIgnorePath := filepath.Join(util.DataDir, ".siyuan", "indexignore") err := os.MkdirAll(filepath.Dir(indexIgnorePath), 0755) - if nil != err { + if err != nil { return } if !gulu.File.IsExist(indexIgnorePath) { - if err = gulu.File.WriteFileSafer(indexIgnorePath, nil, 0644); nil != err { + if err = gulu.File.WriteFileSafer(indexIgnorePath, nil, 0644); err != nil { logging.LogErrorf("create indexignore [%s] failed: %s", indexIgnorePath, err) return } } data, err := os.ReadFile(indexIgnorePath) - if nil != err { + if err != nil { logging.LogErrorf("read indexignore [%s] failed: %s", indexIgnorePath, err) return } diff --git a/kernel/treenode/av.go b/kernel/treenode/av.go index d07721c1a..5bd3bebfe 100644 --- a/kernel/treenode/av.go +++ b/kernel/treenode/av.go @@ -37,13 +37,13 @@ func GetMirrorAttrViewBlockIDs(avID string) (ret []string) { } data, err := filelock.ReadFile(blocks) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view blocks failed: %s", err) return } avBlocks := map[string][]string{} - if err = msgpack.Unmarshal(data, &avBlocks); nil != err { + if err = msgpack.Unmarshal(data, &avBlocks); err != nil { logging.LogErrorf("unmarshal attribute view blocks failed: %s", err) return } @@ -73,13 +73,13 @@ func BatchGetMirrorAttrViewBlocks(avIDs []string) (ret []*AvBlock) { } data, err := filelock.ReadFile(blocks) - if nil != err { + if err != nil { logging.LogErrorf("read attribute view blocks failed: %s", err) return } avBlocks := map[string][]string{} - if err = msgpack.Unmarshal(data, &avBlocks); nil != err { + if err = msgpack.Unmarshal(data, &avBlocks); err != nil { logging.LogErrorf("unmarshal attribute view blocks failed: %s", err) return } diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go index b681b8437..0030d0fbb 100644 --- a/kernel/treenode/blocktree.go +++ b/kernel/treenode/blocktree.go @@ -63,7 +63,7 @@ func initDatabase(forceRebuild bool) (err error) { closeDatabase() if gulu.File.IsExist(util.BlockTreeDBPath) { - if err = removeDatabaseFile(); nil != err { + if err = removeDatabaseFile(); err != nil { logging.LogErrorf("remove database file [%s] failed: %s", util.BlockTreeDBPath, err) err = nil } @@ -78,16 +78,16 @@ func initDatabase(forceRebuild bool) (err error) { func initDBTables() { _, err := db.Exec("DROP TABLE IF EXISTS blocktrees") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "drop table [blocks] failed: %s", err) } _, err = db.Exec("CREATE TABLE blocktrees (id, root_id, parent_id, box_id, path, hpath, updated, type)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create table [blocktrees] failed: %s", err) } _, err = db.Exec("CREATE INDEX idx_blocktrees_id ON blocktrees(id)") - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create index [idx_blocktrees_id] failed: %s", err) } } @@ -108,7 +108,7 @@ func initDBConnection() { "&_case_sensitive_like=OFF" var err error db, err = sql.Open("sqlite3_extended", dsn) - if nil != err { + if err != nil { logging.LogFatalf(logging.ExitCodeReadOnlyDatabase, "create database failed: %s", err) } db.SetMaxIdleConns(7) @@ -125,7 +125,7 @@ func closeDatabase() { return } - if err := db.Close(); nil != err { + if err := db.Close(); err != nil { logging.LogErrorf("close database failed: %s", err) } debug.FreeOSMemory() @@ -135,15 +135,15 @@ func closeDatabase() { func removeDatabaseFile() (err error) { err = os.RemoveAll(util.BlockTreeDBPath) - if nil != err { + if err != nil { return } err = os.RemoveAll(util.BlockTreeDBPath + "-shm") - if nil != err { + if err != nil { return } err = os.RemoveAll(util.BlockTreeDBPath + "-wal") - if nil != err { + if err != nil { return } return @@ -152,14 +152,14 @@ func removeDatabaseFile() (err error) { func GetBlockTreesByType(typ string) (ret []*BlockTree) { sqlStmt := "SELECT * FROM blocktrees WHERE type = ?" rows, err := db.Query(sqlStmt, typ) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var block BlockTree - if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); nil != err { + if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -172,7 +172,7 @@ func GetBlockTreeByPath(path string) (ret *BlockTree) { ret = &BlockTree{} sqlStmt := "SELECT * FROM blocktrees WHERE path = ?" err := db.QueryRow(sqlStmt, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type) - if nil != err { + if err != nil { ret = nil if errors.Is(err, sql.ErrNoRows) { return @@ -186,7 +186,7 @@ func GetBlockTreeByPath(path string) (ret *BlockTree) { func CountTrees() (ret int) { sqlStmt := "SELECT COUNT(*) FROM blocktrees WHERE type = 'd'" err := db.QueryRow(sqlStmt).Scan(&ret) - if nil != err { + if err != nil { if errors.Is(err, sql.ErrNoRows) { return 0 } @@ -198,7 +198,7 @@ func CountTrees() (ret int) { func CountBlocks() (ret int) { sqlStmt := "SELECT COUNT(*) FROM blocktrees" err := db.QueryRow(sqlStmt).Scan(&ret) - if nil != err { + if err != nil { if errors.Is(err, sql.ErrNoRows) { return 0 } @@ -211,7 +211,7 @@ func GetBlockTreeRootByPath(boxID, path string) (ret *BlockTree) { ret = &BlockTree{} sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND path = ? AND type = 'd'" err := db.QueryRow(sqlStmt, boxID, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type) - if nil != err { + if err != nil { ret = nil if errors.Is(err, sql.ErrNoRows) { return @@ -227,7 +227,7 @@ func GetBlockTreeRootByHPath(boxID, hPath string) (ret *BlockTree) { hPath = gulu.Str.RemoveInvisible(hPath) sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND hpath = ? AND type = 'd'" err := db.QueryRow(sqlStmt, boxID, hPath).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type) - if nil != err { + if err != nil { ret = nil if errors.Is(err, sql.ErrNoRows) { return @@ -242,14 +242,14 @@ func GetBlockTreeRootsByHPath(boxID, hPath string) (ret []*BlockTree) { hPath = gulu.Str.RemoveInvisible(hPath) sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND hpath = ? AND type = 'd'" rows, err := db.Query(sqlStmt, boxID, hPath) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var block BlockTree - if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); nil != err { + if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -263,14 +263,14 @@ func GetBlockTreeRootByHPathPreferredParentID(boxID, hPath, preferredParentID st var roots []*BlockTree sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND hpath = ? AND parent_id = ? AND type = 'd'" rows, err := db.Query(sqlStmt, boxID, hPath, preferredParentID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var block BlockTree - if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); nil != err { + if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -299,7 +299,7 @@ func ExistBlockTree(id string) bool { sqlStmt := "SELECT COUNT(*) FROM blocktrees WHERE id = ?" var count int err := db.QueryRow(sqlStmt, id).Scan(&count) - if nil != err { + if err != nil { if errors.Is(err, sql.ErrNoRows) { return false } @@ -321,14 +321,14 @@ func ExistBlockTrees(ids []string) (ret map[string]bool) { sqlStmt := "SELECT id FROM blocktrees WHERE id IN ('" + strings.Join(ids, "','") + "')" rows, err := db.Query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var id string - if err = rows.Scan(&id); nil != err { + if err = rows.Scan(&id); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -345,14 +345,14 @@ func GetBlockTrees(ids []string) (ret map[string]*BlockTree) { sqlStmt := "SELECT * FROM blocktrees WHERE id IN ('" + strings.Join(ids, "','") + "')" rows, err := db.Query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var block BlockTree - if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); nil != err { + if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -369,7 +369,7 @@ func GetBlockTree(id string) (ret *BlockTree) { ret = &BlockTree{} sqlStmt := "SELECT * FROM blocktrees WHERE id = ?" err := db.QueryRow(sqlStmt, id).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type) - if nil != err { + if err != nil { ret = nil if errors.Is(err, sql.ErrNoRows) { return @@ -388,7 +388,7 @@ func SetBlockTreePath(tree *parse.Tree) { func RemoveBlockTreesByRootID(rootID string) { sqlStmt := "DELETE FROM blocktrees WHERE root_id = ?" _, err := db.Exec(sqlStmt, rootID) - if nil != err { + if err != nil { logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err) return } @@ -397,14 +397,14 @@ func RemoveBlockTreesByRootID(rootID string) { func GetBlockTreesByPathPrefix(pathPrefix string) (ret []*BlockTree) { sqlStmt := "SELECT * FROM blocktrees WHERE path LIKE ?" rows, err := db.Query(sqlStmt, pathPrefix+"%") - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var block BlockTree - if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); nil != err { + if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -416,14 +416,14 @@ func GetBlockTreesByPathPrefix(pathPrefix string) (ret []*BlockTree) { func GetBlockTreesByRootID(rootID string) (ret []*BlockTree) { sqlStmt := "SELECT * FROM blocktrees WHERE root_id = ?" rows, err := db.Query(sqlStmt, rootID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var block BlockTree - if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); nil != err { + if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -435,7 +435,7 @@ func GetBlockTreesByRootID(rootID string) (ret []*BlockTree) { func RemoveBlockTreesByPathPrefix(pathPrefix string) { sqlStmt := "DELETE FROM blocktrees WHERE path LIKE ?" _, err := db.Exec(sqlStmt, pathPrefix+"%") - if nil != err { + if err != nil { logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err) return } @@ -444,14 +444,14 @@ func RemoveBlockTreesByPathPrefix(pathPrefix string) { func GetBlockTreesByBoxID(boxID string) (ret []*BlockTree) { sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ?" rows, err := db.Query(sqlStmt, boxID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var block BlockTree - if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); nil != err { + if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -463,14 +463,14 @@ func GetBlockTreesByBoxID(boxID string) (ret []*BlockTree) { func RemoveBlockTreesByBoxID(boxID string) (ids []string) { sqlStmt := "SELECT id FROM blocktrees WHERE box_id = ?" rows, err := db.Query(sqlStmt, boxID) - if nil != err { + if err != nil { logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err) return } defer rows.Close() for rows.Next() { var id string - if err = rows.Scan(&id); nil != err { + if err = rows.Scan(&id); err != nil { logging.LogErrorf("query scan field failed: %s", err) return } @@ -479,7 +479,7 @@ func RemoveBlockTreesByBoxID(boxID string) (ids []string) { sqlStmt = "DELETE FROM blocktrees WHERE box_id = ?" _, err = db.Exec(sqlStmt, boxID) - if nil != err { + if err != nil { logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err) return } @@ -489,7 +489,7 @@ func RemoveBlockTreesByBoxID(boxID string) (ids []string) { func RemoveBlockTree(id string) { sqlStmt := "DELETE FROM blocktrees WHERE id = ?" _, err := db.Exec(sqlStmt, id) - if nil != err { + if err != nil { logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err) return } @@ -512,7 +512,7 @@ func IndexBlockTree(tree *parse.Tree) { defer indexBlockTreeLock.Unlock() tx, err := db.Begin() - if nil != err { + if err != nil { logging.LogErrorf("begin transaction failed: %s", err) return } @@ -523,13 +523,13 @@ func IndexBlockTree(tree *parse.Tree) { if nil != n.Parent { parentID = n.Parent.ID } - if _, err = tx.Exec(sqlStmt, n.ID, tree.ID, parentID, tree.Box, tree.Path, tree.HPath, n.IALAttr("updated"), TypeAbbr(n.Type.String())); nil != err { + if _, err = tx.Exec(sqlStmt, n.ID, tree.ID, parentID, tree.Box, tree.Path, tree.HPath, n.IALAttr("updated"), TypeAbbr(n.Type.String())); err != nil { tx.Rollback() logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err) return } } - if err = tx.Commit(); nil != err { + if err = tx.Commit(); err != nil { logging.LogErrorf("commit transaction failed: %s", err) } } @@ -573,7 +573,7 @@ func UpsertBlockTree(tree *parse.Tree) { defer indexBlockTreeLock.Unlock() tx, err := db.Begin() - if nil != err { + if err != nil { logging.LogErrorf("begin transaction failed: %s", err) return } @@ -581,7 +581,7 @@ func UpsertBlockTree(tree *parse.Tree) { sqlStmt := "DELETE FROM blocktrees WHERE id IN (" + ids.String() + ")" _, err = tx.Exec(sqlStmt) - if nil != err { + if err != nil { tx.Rollback() logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err) return @@ -592,20 +592,20 @@ func UpsertBlockTree(tree *parse.Tree) { if nil != n.Parent { parentID = n.Parent.ID } - if _, err = tx.Exec(sqlStmt, n.ID, tree.ID, parentID, tree.Box, tree.Path, tree.HPath, n.IALAttr("updated"), TypeAbbr(n.Type.String())); nil != err { + if _, err = tx.Exec(sqlStmt, n.ID, tree.ID, parentID, tree.Box, tree.Path, tree.HPath, n.IALAttr("updated"), TypeAbbr(n.Type.String())); err != nil { tx.Rollback() logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err) return } } - if err = tx.Commit(); nil != err { + if err = tx.Commit(); err != nil { logging.LogErrorf("commit transaction failed: %s", err) } } func InitBlockTree(force bool) { err := initDatabase(force) - if nil != err { + if err != nil { logging.LogErrorf("init database failed: %s", err) os.Exit(logging.ExitCodeReadOnlyDatabase) return diff --git a/kernel/treenode/blocktree_fix.go b/kernel/treenode/blocktree_fix.go index f9a5eabcc..191e04061 100644 --- a/kernel/treenode/blocktree_fix.go +++ b/kernel/treenode/blocktree_fix.go @@ -37,14 +37,14 @@ func getRedundantPaths(boxID string, paths []string) (ret []string) { btPathsMap := map[string]bool{} sqlStmt := "SELECT path FROM blocktrees WHERE box_id = ?" rows, err := db.Query(sqlStmt, boxID) - if nil != err { + if err != nil { logging.LogErrorf("query block tree failed: %s", err) return } defer rows.Close() for rows.Next() { var path string - if err = rows.Scan(&path); nil != err { + if err = rows.Scan(&path); err != nil { logging.LogErrorf("scan block tree failed: %s", err) return } @@ -63,7 +63,7 @@ func getRedundantPaths(boxID string, paths []string) (ret []string) { func removeBlockTreesByPath(boxID, path string) { sqlStmt := "DELETE FROM blocktrees WHERE box_id = ? AND path = ?" _, err := db.Exec(sqlStmt, boxID, path) - if nil != err { + if err != nil { logging.LogErrorf("delete block tree failed: %s", err) } } @@ -77,14 +77,14 @@ func GetNotExistPaths(boxID string, paths []string) (ret []string) { btPathsMap := map[string]bool{} sqlStmt := "SELECT path FROM blocktrees WHERE box_id = ?" rows, err := db.Query(sqlStmt, boxID) - if nil != err { + if err != nil { logging.LogErrorf("query block tree failed: %s", err) return } defer rows.Close() for rows.Next() { var path string - if err = rows.Scan(&path); nil != err { + if err = rows.Scan(&path); err != nil { logging.LogErrorf("scan block tree failed: %s", err) return } @@ -104,14 +104,14 @@ func GetRootUpdated() (ret map[string]string) { ret = map[string]string{} sqlStmt := "SELECT root_id, updated FROM blocktrees WHERE root_id = id AND type = 'd'" rows, err := db.Query(sqlStmt) - if nil != err { + if err != nil { logging.LogErrorf("query block tree failed: %s", err) return } defer rows.Close() for rows.Next() { var rootID, updated string - if err = rows.Scan(&rootID, &updated); nil != err { + if err = rows.Scan(&rootID, &updated); err != nil { logging.LogErrorf("scan block tree failed: %s", err) return } diff --git a/kernel/treenode/node.go b/kernel/treenode/node.go index f6d71385a..98ce2a879 100644 --- a/kernel/treenode/node.go +++ b/kernel/treenode/node.go @@ -46,7 +46,7 @@ func GetEmbedBlockRef(embedNode *ast.Node) (blockRefID string) { stmt := scriptNode.TokensStr() parsedStmt, err := sqlparser.Parse(stmt) - if nil != err { + if err != nil { return } @@ -116,7 +116,7 @@ func IsEmbedBlockRef(n *ast.Node) bool { func FormatNode(node *ast.Node, luteEngine *lute.Lute) string { markdown, err := lute.FormatNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions) - if nil != err { + if err != nil { root := TreeRoot(node) logging.LogFatalf(logging.ExitCodeFatal, "format node [%s] in tree [%s] failed: %s", node.ID, root.ID, err) } @@ -125,7 +125,7 @@ func FormatNode(node *ast.Node, luteEngine *lute.Lute) string { func ExportNodeStdMd(node *ast.Node, luteEngine *lute.Lute) string { markdown, err := lute.ProtyleExportMdNodeSync(node, luteEngine.ParseOptions, luteEngine.RenderOptions) - if nil != err { + if err != nil { root := TreeRoot(node) logging.LogFatalf(logging.ExitCodeFatal, "export markdown for node [%s] in tree [%s] failed: %s", node.ID, root.ID, err) } diff --git a/kernel/util/crypt.go b/kernel/util/crypt.go index fec1eab17..b61117ee4 100644 --- a/kernel/util/crypt.go +++ b/kernel/util/crypt.go @@ -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")) diff --git a/kernel/util/disk.go b/kernel/util/disk.go index 9feb8390b..39882ed67 100644 --- a/kernel/util/disk.go +++ b/kernel/util/disk.go @@ -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 } diff --git a/kernel/util/file.go b/kernel/util/file.go index 4758ee385..3aab9852d 100644 --- a/kernel/util/file.go +++ b/kernel/util/file.go @@ -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 } diff --git a/kernel/util/font.go b/kernel/util/font.go index 3d621177d..44da3b481 100644 --- a/kernel/util/font.go +++ b/kernel/util/font.go @@ -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 } diff --git a/kernel/util/lute.go b/kernel/util/lute.go index bfc9ea87c..6a099be74 100644 --- a/kernel/util/lute.go +++ b/kernel/util/lute.go @@ -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 } diff --git a/kernel/util/misc.go b/kernel/util/misc.go index f5bdd8ee2..a5ab4a8a7 100644 --- a/kernel/util/misc.go +++ b/kernel/util/misc.go @@ -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 diff --git a/kernel/util/net.go b/kernel/util/net.go index 549670ca1..94d6f91ae 100644 --- a/kernel/util/net.go +++ b/kernel/util/net.go @@ -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() { diff --git a/kernel/util/ocr.go b/kernel/util/ocr.go index 2edb9bb3f..83ecd96fc 100644 --- a/kernel/util/ocr.go +++ b/kernel/util/ocr.go @@ -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 } diff --git a/kernel/util/openai.go b/kernel/util/openai.go index 16ab27a2e..bb248ee86 100644 --- a/kernel/util/openai.go +++ b/kernel/util/openai.go @@ -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) diff --git a/kernel/util/os.go b/kernel/util/os.go index b761f82e1..ca135a5c9 100644 --- a/kernel/util/os.go +++ b/kernel/util/os.go @@ -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" } diff --git a/kernel/util/pandoc.go b/kernel/util/pandoc.go index 164ca054a..7bd290b4b 100644 --- a/kernel/util/pandoc.go +++ b/kernel/util/pandoc.go @@ -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 diff --git a/kernel/util/path.go b/kernel/util/path.go index 6d0848f84..ecee45d9c 100644 --- a/kernel/util/path.go +++ b/kernel/util/path.go @@ -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 } diff --git a/kernel/util/result.go b/kernel/util/result.go index 814c60013..3ed4ac394 100644 --- a/kernel/util/result.go +++ b/kernel/util/result.go @@ -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 diff --git a/kernel/util/rhy.go b/kernel/util/rhy.go index 066d2f398..76e9a4bc6 100644 --- a/kernel/util/rhy.go +++ b/kernel/util/rhy.go @@ -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 } diff --git a/kernel/util/runtime.go b/kernel/util/runtime.go index 09a15aede..b96bb34ee 100644 --- a/kernel/util/runtime.go +++ b/kernel/util/runtime.go @@ -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 } diff --git a/kernel/util/session.go b/kernel/util/session.go index 2d6865adc..070742d9a 100644 --- a/kernel/util/session.go +++ b/kernel/util/session.go @@ -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 } diff --git a/kernel/util/template.go b/kernel/util/template.go index 00e4328fe..2f133364b 100644 --- a/kernel/util/template.go +++ b/kernel/util/template.go @@ -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 } diff --git a/kernel/util/working.go b/kernel/util/working.go index f8aa05873..9e62a0b45 100644 --- a/kernel/util/working.go +++ b/kernel/util/working.go @@ -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 } diff --git a/kernel/util/working_mobile.go b/kernel/util/working_mobile.go index 85fc5cbaf..518ec7d09 100644 --- a/kernel/util/working_mobile.go +++ b/kernel/util/working_mobile.go @@ -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) }