tree.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. "github.com/88250/lute"
  26. "github.com/88250/lute/parse"
  27. "github.com/88250/lute/render"
  28. jsoniter "github.com/json-iterator/go"
  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.ReadFile(filePath)
  38. if nil != err {
  39. return
  40. }
  41. ret = parseJSON2Tree(boxID, p, data, luteEngine)
  42. if nil == ret {
  43. return nil, errors.New("parse tree failed")
  44. }
  45. ret.Path = p
  46. ret.Root.Path = p
  47. parts := strings.Split(p, "/")
  48. parts = parts[1 : len(parts)-1] // 去掉开头的斜杆和结尾的自己
  49. if 1 > len(parts) {
  50. ret.HPath = "/" + ret.Root.IALAttr("title")
  51. ret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)
  52. return
  53. }
  54. // 构造 HPath
  55. hPathBuilder := bytes.Buffer{}
  56. hPathBuilder.WriteString("/")
  57. for i, _ := range parts {
  58. var parentAbsPath string
  59. if 0 < i {
  60. parentAbsPath = strings.Join(parts[:i+1], "/")
  61. } else {
  62. parentAbsPath = parts[0]
  63. }
  64. parentAbsPath += ".sy"
  65. parentPath := parentAbsPath
  66. parentAbsPath = filepath.Join(util.DataDir, boxID, parentAbsPath)
  67. parentData, readErr := filelock.ReadFile(parentAbsPath)
  68. if nil != readErr {
  69. if os.IsNotExist(readErr) {
  70. parentTree := treenode.NewTree(boxID, parentPath, hPathBuilder.String()+"Untitled", "Untitled")
  71. if writeErr := WriteTree(parentTree); nil != writeErr {
  72. logging.LogErrorf("rebuild parent tree [%s] failed: %s", parentAbsPath, writeErr)
  73. } else {
  74. logging.LogInfof("rebuilt parent tree [%s]", parentAbsPath)
  75. }
  76. } else {
  77. logging.LogWarnf("read parent tree data [%s] failed: %s", parentAbsPath, readErr)
  78. }
  79. hPathBuilder.WriteString("Untitled/")
  80. continue
  81. }
  82. ial := ReadDocIAL(parentData)
  83. if 1 > len(ial) {
  84. logging.LogWarnf("tree [%s] is corrupted", filePath)
  85. }
  86. title := ial["title"]
  87. if "" == title {
  88. title = "Untitled"
  89. }
  90. hPathBuilder.WriteString(title)
  91. hPathBuilder.WriteString("/")
  92. }
  93. hPathBuilder.WriteString(ret.Root.IALAttr("title"))
  94. ret.HPath = hPathBuilder.String()
  95. ret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)
  96. return
  97. }
  98. func WriteTreeWithoutChangeTime(tree *parse.Tree) (err error) {
  99. data, filePath, err := prepareWriteTree(tree)
  100. if nil != err {
  101. return
  102. }
  103. if err = filelock.WriteFileWithoutChangeTime(filePath, data); nil != err {
  104. if errors.Is(err, filelock.ErrUnableAccessFile) {
  105. return
  106. }
  107. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  108. logging.LogErrorf(msg)
  109. return errors.New(msg)
  110. }
  111. afterWriteTree(tree)
  112. return
  113. }
  114. func WriteTree(tree *parse.Tree) (err error) {
  115. data, filePath, err := prepareWriteTree(tree)
  116. if nil != err {
  117. return
  118. }
  119. if err = filelock.WriteFile(filePath, data); nil != err {
  120. if errors.Is(err, filelock.ErrUnableAccessFile) {
  121. return
  122. }
  123. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  124. logging.LogErrorf(msg)
  125. return errors.New(msg)
  126. }
  127. afterWriteTree(tree)
  128. return
  129. }
  130. func prepareWriteTree(tree *parse.Tree) (data []byte, filePath string, err error) {
  131. luteEngine := util.NewLute() // 不关注用户的自定义解析渲染选项
  132. if nil == tree.Root.FirstChild {
  133. newP := treenode.NewParagraph()
  134. tree.Root.AppendChild(newP)
  135. tree.Root.SetIALAttr("updated", util.TimeFromID(newP.ID))
  136. treenode.IndexBlockTree(tree)
  137. }
  138. filePath = filepath.Join(util.DataDir, tree.Box, tree.Path)
  139. if oldSpec := tree.Root.Spec; "" == oldSpec {
  140. parse.NestedInlines2FlattedSpans(tree)
  141. tree.Root.Spec = "1"
  142. logging.LogInfof("migrated tree [%s] from spec [%s] to [%s]", filePath, oldSpec, tree.Root.Spec)
  143. }
  144. renderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions)
  145. data = renderer.Render()
  146. // .sy 文档数据使用格式化好的 JSON 而非单行 JSON
  147. buf := bytes.Buffer{}
  148. buf.Grow(4096)
  149. if err = json.Indent(&buf, data, "", "\t"); nil != err {
  150. return
  151. }
  152. data = buf.Bytes()
  153. if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err {
  154. return
  155. }
  156. return
  157. }
  158. func afterWriteTree(tree *parse.Tree) {
  159. docIAL := parse.IAL2MapUnEsc(tree.Root.KramdownIAL)
  160. cache.PutDocIAL(tree.Path, docIAL)
  161. }
  162. func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (ret *parse.Tree) {
  163. var err error
  164. var needFix bool
  165. ret, needFix, err = ParseJSON(jsonData, luteEngine.ParseOptions)
  166. if nil != err {
  167. logging.LogErrorf("parse json [%s] to tree failed: %s", boxID+p, err)
  168. return
  169. }
  170. ret.Box = boxID
  171. ret.Path = p
  172. filePath := filepath.Join(util.DataDir, ret.Box, ret.Path)
  173. if oldSpec := ret.Root.Spec; "" == oldSpec {
  174. parse.NestedInlines2FlattedSpans(ret)
  175. ret.Root.Spec = "1"
  176. needFix = true
  177. logging.LogInfof("migrated tree [%s] from spec [%s] to [%s]", filePath, oldSpec, ret.Root.Spec)
  178. }
  179. if needFix {
  180. renderer := render.NewJSONRenderer(ret, luteEngine.RenderOptions)
  181. output := renderer.Render()
  182. buf := bytes.Buffer{}
  183. buf.Grow(4096)
  184. if err = json.Indent(&buf, output, "", "\t"); nil != err {
  185. return
  186. }
  187. output = buf.Bytes()
  188. if err = os.MkdirAll(filepath.Dir(filePath), 0755); nil != err {
  189. return
  190. }
  191. if err = filelock.WriteFile(filePath, output); nil != err {
  192. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  193. logging.LogErrorf(msg)
  194. }
  195. }
  196. return
  197. }
  198. func ReadDocIAL(data []byte) (ret map[string]string) {
  199. ret = map[string]string{}
  200. val := jsoniter.Get(data, "Properties")
  201. if nil == val || val.ValueType() == jsoniter.InvalidValue {
  202. return
  203. }
  204. val.ToVal(&ret)
  205. return
  206. }