tree.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // SiYuan - Build Your Eternal Digital Garden
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package filesys
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "os"
  23. "path/filepath"
  24. "strings"
  25. "time"
  26. "github.com/88250/lute"
  27. "github.com/88250/lute/parse"
  28. "github.com/88250/protyle"
  29. "github.com/siyuan-note/filelock"
  30. "github.com/siyuan-note/logging"
  31. "github.com/siyuan-note/siyuan/kernel/cache"
  32. "github.com/siyuan-note/siyuan/kernel/treenode"
  33. "github.com/siyuan-note/siyuan/kernel/util"
  34. )
  35. func LoadTree(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, err error) {
  36. filePath := filepath.Join(util.DataDir, boxID, p)
  37. data, err := filelock.LockFileRead(filePath)
  38. if nil != err {
  39. return
  40. }
  41. ret = parseJSON2Tree(boxID, p, data, luteEngine)
  42. if nil == ret {
  43. ret = recoverParseJSON2Tree(boxID, p, filePath, luteEngine)
  44. if nil == ret {
  45. return nil, errors.New("parse tree failed")
  46. }
  47. }
  48. ret.Path = p
  49. ret.Root.Path = p
  50. parts := strings.Split(p, "/")
  51. parts = parts[1 : len(parts)-1] // 去掉开头的斜杆和结尾的自己
  52. if 1 > len(parts) {
  53. ret.HPath = "/" + ret.Root.IALAttr("title")
  54. ret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)
  55. return
  56. }
  57. // 构造 HPath
  58. hPathBuilder := bytes.Buffer{}
  59. hPathBuilder.WriteString("/")
  60. for i, _ := range parts {
  61. var parentPath string
  62. if 0 < i {
  63. parentPath = strings.Join(parts[:i+1], "/")
  64. } else {
  65. parentPath = parts[0]
  66. }
  67. parentPath += ".sy"
  68. parentPath = filepath.Join(util.DataDir, boxID, parentPath)
  69. parentData, readErr := filelock.LockFileRead(parentPath)
  70. if nil != readErr {
  71. logging.LogWarnf("read parent tree data [%s] failed: %s", parentPath, readErr)
  72. hPathBuilder.WriteString("Untitled/")
  73. continue
  74. }
  75. parentTree, parseErr := protyle.ParseJSONWithoutFix(luteEngine, parentData)
  76. if nil != parseErr {
  77. logging.LogWarnf("parse parent tree [%s] failed: %s", parentPath, parseErr)
  78. hPathBuilder.WriteString("Untitled/")
  79. continue
  80. }
  81. hPathBuilder.WriteString(parentTree.Root.IALAttr("title"))
  82. hPathBuilder.WriteString("/")
  83. }
  84. hPathBuilder.WriteString(ret.Root.IALAttr("title"))
  85. ret.HPath = hPathBuilder.String()
  86. ret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)
  87. return
  88. }
  89. func WriteTree(tree *parse.Tree) (err error) {
  90. luteEngine := util.NewLute() // 不关注用户的自定义解析渲染选项
  91. if nil == tree.Root.FirstChild {
  92. newP := protyle.NewParagraph()
  93. tree.Root.AppendChild(newP)
  94. tree.Root.SetIALAttr("updated", util.TimeFromID(newP.ID))
  95. }
  96. renderer := protyle.NewJSONRenderer(tree, luteEngine.RenderOptions)
  97. output := renderer.Render()
  98. // .sy 文档数据使用格式化好的 JSON 而非单行 JSON
  99. buf := bytes.Buffer{}
  100. buf.Grow(4096)
  101. if err = json.Indent(&buf, output, "", "\t"); nil != err {
  102. return
  103. }
  104. output = buf.Bytes()
  105. filePath := filepath.Join(util.DataDir, tree.Box, tree.Path)
  106. if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err {
  107. return
  108. }
  109. if err = filelock.LockFileWrite(filePath, output); nil != err {
  110. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  111. logging.LogErrorf(msg)
  112. return errors.New(msg)
  113. }
  114. docIAL := parse.IAL2MapUnEsc(tree.Root.KramdownIAL)
  115. cache.PutDocIAL(tree.Path, docIAL)
  116. return
  117. }
  118. func recoverParseJSON2Tree(boxID, p, filePath string, luteEngine *lute.Lute) (ret *parse.Tree) {
  119. // 尝试从临时文件恢复
  120. tmp := util.LatestTmpFile(filePath)
  121. if "" == tmp {
  122. logging.LogWarnf("recover tree [%s] not found tmp", filePath)
  123. return
  124. }
  125. stat, err := os.Stat(filePath)
  126. if nil != err {
  127. logging.LogErrorf("stat tmp [%s] failed: %s", tmp, err)
  128. return
  129. }
  130. if stat.ModTime().Before(time.Now().Add(-time.Hour * 24)) {
  131. logging.LogWarnf("tmp [%s] is too old, remove it", tmp)
  132. os.RemoveAll(tmp)
  133. return
  134. }
  135. data, err := filelock.NoLockFileRead(tmp)
  136. if nil != err {
  137. logging.LogErrorf("recover tree read from tmp [%s] failed: %s", tmp, err)
  138. return
  139. }
  140. if err = filelock.NoLockFileWrite(filePath, data); nil != err {
  141. logging.LogErrorf("recover tree write [%s] from tmp [%s] failed: %s", filePath, tmp, err)
  142. return
  143. }
  144. ret = parseJSON2Tree(boxID, p, data, luteEngine)
  145. if nil == ret {
  146. logging.LogErrorf("recover tree from tmp [%s] parse failed, remove it", tmp)
  147. os.RemoveAll(tmp)
  148. return
  149. }
  150. logging.LogInfof("recovered tree [%s] from [%s]", filePath, tmp)
  151. os.RemoveAll(tmp)
  152. return
  153. }
  154. func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (ret *parse.Tree) {
  155. var err error
  156. var needFix bool
  157. ret, needFix, err = protyle.ParseJSON(luteEngine, jsonData)
  158. if nil != err {
  159. logging.LogErrorf("parse json [%s] to tree failed: %s", boxID+p, err)
  160. return
  161. }
  162. ret.Box = boxID
  163. ret.Path = p
  164. if needFix {
  165. renderer := protyle.NewJSONRenderer(ret, luteEngine.RenderOptions)
  166. output := renderer.Render()
  167. buf := bytes.Buffer{}
  168. buf.Grow(4096)
  169. if err = json.Indent(&buf, output, "", "\t"); nil != err {
  170. return
  171. }
  172. output = buf.Bytes()
  173. filePath := filepath.Join(util.DataDir, ret.Box, ret.Path)
  174. if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err {
  175. return
  176. }
  177. if err = filelock.LockFileWrite(filePath, output); nil != err {
  178. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  179. logging.LogErrorf(msg)
  180. }
  181. }
  182. return
  183. }