tree.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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/lute/render"
  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 := parse.ParseJSONWithoutFix(parentData, luteEngine.ParseOptions)
  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 := parse.NewParagraph()
  93. tree.Root.AppendChild(newP)
  94. tree.Root.SetIALAttr("updated", util.TimeFromID(newP.ID))
  95. treenode.ReindexBlockTree(tree)
  96. }
  97. if oldSpec := tree.Root.Spec; "" == oldSpec {
  98. treenode.NestedInlines2FlattedSpans(tree)
  99. tree.Root.Spec = "1"
  100. logging.LogInfof("migrated tree [%s] from spec [%s] to [%s]", tree.Root.ID, oldSpec, tree.Root.Spec)
  101. }
  102. renderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions)
  103. output := renderer.Render()
  104. // .sy 文档数据使用格式化好的 JSON 而非单行 JSON
  105. buf := bytes.Buffer{}
  106. buf.Grow(4096)
  107. if err = json.Indent(&buf, output, "", "\t"); nil != err {
  108. return
  109. }
  110. output = buf.Bytes()
  111. filePath := filepath.Join(util.DataDir, tree.Box, tree.Path)
  112. if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err {
  113. return
  114. }
  115. if err = filelock.LockFileWrite(filePath, output); nil != err {
  116. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  117. logging.LogErrorf(msg)
  118. return errors.New(msg)
  119. }
  120. docIAL := parse.IAL2MapUnEsc(tree.Root.KramdownIAL)
  121. cache.PutDocIAL(tree.Path, docIAL)
  122. return
  123. }
  124. func recoverParseJSON2Tree(boxID, p, filePath string, luteEngine *lute.Lute) (ret *parse.Tree) {
  125. // 尝试从临时文件恢复
  126. tmp := util.LatestTmpFile(filePath)
  127. if "" == tmp {
  128. logging.LogWarnf("recover tree [%s] not found tmp", filePath)
  129. return
  130. }
  131. stat, err := os.Stat(filePath)
  132. if nil != err {
  133. logging.LogErrorf("stat tmp [%s] failed: %s", tmp, err)
  134. return
  135. }
  136. if stat.ModTime().Before(time.Now().Add(-time.Hour * 24)) {
  137. logging.LogWarnf("tmp [%s] is too old, remove it", tmp)
  138. os.RemoveAll(tmp)
  139. return
  140. }
  141. data, err := filelock.NoLockFileRead(tmp)
  142. if nil != err {
  143. logging.LogErrorf("recover tree read from tmp [%s] failed: %s", tmp, err)
  144. return
  145. }
  146. if err = filelock.NoLockFileWrite(filePath, data); nil != err {
  147. logging.LogErrorf("recover tree write [%s] from tmp [%s] failed: %s", filePath, tmp, err)
  148. return
  149. }
  150. ret = parseJSON2Tree(boxID, p, data, luteEngine)
  151. if nil == ret {
  152. logging.LogErrorf("recover tree from tmp [%s] parse failed, remove it", tmp)
  153. os.RemoveAll(tmp)
  154. return
  155. }
  156. logging.LogInfof("recovered tree [%s] from [%s]", filePath, tmp)
  157. os.RemoveAll(tmp)
  158. return
  159. }
  160. func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (ret *parse.Tree) {
  161. var err error
  162. var needFix bool
  163. ret, needFix, err = parse.ParseJSON(jsonData, luteEngine.ParseOptions)
  164. if nil != err {
  165. logging.LogErrorf("parse json [%s] to tree failed: %s", boxID+p, err)
  166. return
  167. }
  168. ret.Box = boxID
  169. ret.Path = p
  170. if oldSpec := ret.Root.Spec; "" == oldSpec {
  171. treenode.NestedInlines2FlattedSpans(ret)
  172. ret.Root.Spec = "1"
  173. needFix = true
  174. logging.LogInfof("migrated tree [%s] from spec [%s] to [%s]", ret.Root.ID, oldSpec, ret.Root.Spec)
  175. }
  176. if needFix {
  177. renderer := render.NewJSONRenderer(ret, luteEngine.RenderOptions)
  178. output := renderer.Render()
  179. buf := bytes.Buffer{}
  180. buf.Grow(4096)
  181. if err = json.Indent(&buf, output, "", "\t"); nil != err {
  182. return
  183. }
  184. output = buf.Bytes()
  185. filePath := filepath.Join(util.DataDir, ret.Box, ret.Path)
  186. if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err {
  187. return
  188. }
  189. if err = filelock.LockFileWrite(filePath, output); nil != err {
  190. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  191. logging.LogErrorf(msg)
  192. }
  193. }
  194. return
  195. }