tree.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // SiYuan - Refactor your thinking
  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. "github.com/88250/lute"
  23. "github.com/88250/lute/parse"
  24. "github.com/88250/lute/render"
  25. jsoniter "github.com/json-iterator/go"
  26. "github.com/siyuan-note/filelock"
  27. "github.com/siyuan-note/logging"
  28. "github.com/siyuan-note/siyuan/kernel/cache"
  29. "github.com/siyuan-note/siyuan/kernel/treenode"
  30. "github.com/siyuan-note/siyuan/kernel/util"
  31. "os"
  32. "path/filepath"
  33. "strings"
  34. "sync"
  35. )
  36. func LoadTrees(ids []string) (ret map[string]*parse.Tree) {
  37. ret = map[string]*parse.Tree{}
  38. bts := treenode.GetBlockTrees(ids)
  39. luteEngine := util.NewLute()
  40. var boxIDs []string
  41. var paths []string
  42. seen := make(map[string]bool)
  43. for _, bt := range bts {
  44. key := bt.BoxID + bt.Path
  45. if !seen[key] {
  46. seen[key] = true
  47. boxIDs = append(boxIDs, bt.BoxID)
  48. paths = append(paths, bt.Path)
  49. }
  50. }
  51. trees, errs := BatchLoadTrees(boxIDs, paths, luteEngine)
  52. for i := range trees {
  53. tree := trees[i]
  54. err := errs[i]
  55. if err != nil || tree == nil {
  56. logging.LogErrorf("load tree failed: %s", err)
  57. continue
  58. }
  59. ret[tree.ID] = tree
  60. }
  61. return
  62. }
  63. func LoadTree(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, err error) {
  64. filePath := filepath.Join(util.DataDir, boxID, p)
  65. data, err := filelock.ReadFile(filePath)
  66. if err != nil {
  67. logging.LogErrorf("load tree [%s] failed: %s", p, err)
  68. return
  69. }
  70. ret, err = LoadTreeByData(data, boxID, p, luteEngine)
  71. return
  72. }
  73. func BatchLoadTrees(boxIDs, paths []string, luteEngine *lute.Lute) ([]*parse.Tree, []error) {
  74. var wg sync.WaitGroup
  75. results := make([]*parse.Tree, len(paths))
  76. errors := make([]error, len(paths))
  77. for i := range paths {
  78. wg.Add(1)
  79. go func(i int) {
  80. defer wg.Done()
  81. boxID := boxIDs[i]
  82. path := paths[i]
  83. tree, err := LoadTree(boxID, path, luteEngine)
  84. results[i] = tree
  85. errors[i] = err
  86. }(i)
  87. }
  88. wg.Wait()
  89. return results, errors
  90. }
  91. func LoadTreeByData(data []byte, boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, err error) {
  92. ret = parseJSON2Tree(boxID, p, data, luteEngine)
  93. if nil == ret {
  94. logging.LogErrorf("parse tree [%s] failed", p)
  95. err = errors.New("parse tree failed")
  96. return
  97. }
  98. ret.Path = p
  99. ret.Root.Path = p
  100. parts := strings.Split(p, "/")
  101. parts = parts[1 : len(parts)-1] // 去掉开头的斜杆和结尾的自己
  102. if 1 > len(parts) {
  103. ret.HPath = "/" + ret.Root.IALAttr("title")
  104. ret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)
  105. return
  106. }
  107. // 构造 HPath
  108. hPathBuilder := bytes.Buffer{}
  109. hPathBuilder.WriteString("/")
  110. for i, _ := range parts {
  111. var parentAbsPath string
  112. if 0 < i {
  113. parentAbsPath = strings.Join(parts[:i+1], "/")
  114. } else {
  115. parentAbsPath = parts[0]
  116. }
  117. parentAbsPath += ".sy"
  118. parentPath := parentAbsPath
  119. parentAbsPath = filepath.Join(util.DataDir, boxID, parentAbsPath)
  120. parentData, readErr := filelock.ReadFile(parentAbsPath)
  121. if nil != readErr {
  122. if os.IsNotExist(readErr) {
  123. // 子文档缺失父文档时自动补全 https://github.com/siyuan-note/siyuan/issues/7376
  124. parentTree := treenode.NewTree(boxID, parentPath, hPathBuilder.String()+"Untitled", "Untitled")
  125. if _, writeErr := WriteTree(parentTree); nil != writeErr {
  126. logging.LogErrorf("rebuild parent tree [%s] failed: %s", parentAbsPath, writeErr)
  127. } else {
  128. logging.LogInfof("rebuilt parent tree [%s]", parentAbsPath)
  129. treenode.UpsertBlockTree(parentTree)
  130. }
  131. } else {
  132. logging.LogWarnf("read parent tree data [%s] failed: %s", parentAbsPath, readErr)
  133. }
  134. hPathBuilder.WriteString("Untitled/")
  135. continue
  136. }
  137. ial := ReadDocIAL(parentData)
  138. if 1 > len(ial) {
  139. logging.LogWarnf("tree [%s] is corrupted", filepath.Join(boxID, p))
  140. }
  141. title := ial["title"]
  142. if "" == title {
  143. title = "Untitled"
  144. }
  145. hPathBuilder.WriteString(title)
  146. hPathBuilder.WriteString("/")
  147. }
  148. hPathBuilder.WriteString(ret.Root.IALAttr("title"))
  149. ret.HPath = hPathBuilder.String()
  150. ret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)
  151. return
  152. }
  153. func WriteTree(tree *parse.Tree) (size uint64, err error) {
  154. data, filePath, err := prepareWriteTree(tree)
  155. if err != nil {
  156. return
  157. }
  158. size = uint64(len(data))
  159. if err = filelock.WriteFile(filePath, data); err != nil {
  160. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  161. logging.LogErrorf(msg)
  162. err = errors.New(msg)
  163. return
  164. }
  165. afterWriteTree(tree)
  166. return
  167. }
  168. func prepareWriteTree(tree *parse.Tree) (data []byte, filePath string, err error) {
  169. luteEngine := util.NewLute() // 不关注用户的自定义解析渲染选项
  170. if nil == tree.Root.FirstChild {
  171. newP := treenode.NewParagraph()
  172. tree.Root.AppendChild(newP)
  173. tree.Root.SetIALAttr("updated", util.TimeFromID(newP.ID))
  174. treenode.UpsertBlockTree(tree)
  175. }
  176. filePath = filepath.Join(util.DataDir, tree.Box, tree.Path)
  177. if oldSpec := tree.Root.Spec; "" == oldSpec {
  178. parse.NestedInlines2FlattedSpans(tree, false)
  179. tree.Root.Spec = "1"
  180. logging.LogInfof("migrated tree [%s] from spec [%s] to [%s]", filePath, oldSpec, tree.Root.Spec)
  181. }
  182. tree.Root.SetIALAttr("type", "doc")
  183. renderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions)
  184. data = renderer.Render()
  185. if !util.UseSingleLineSave {
  186. buf := bytes.Buffer{}
  187. buf.Grow(1024 * 1024 * 2)
  188. if err = json.Indent(&buf, data, "", "\t"); err != nil {
  189. return
  190. }
  191. data = buf.Bytes()
  192. }
  193. if err = os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
  194. return
  195. }
  196. return
  197. }
  198. func afterWriteTree(tree *parse.Tree) {
  199. docIAL := parse.IAL2MapUnEsc(tree.Root.KramdownIAL)
  200. cache.PutDocIAL(tree.Path, docIAL)
  201. }
  202. func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (ret *parse.Tree) {
  203. var err error
  204. var needFix bool
  205. ret, needFix, err = ParseJSON(jsonData, luteEngine.ParseOptions)
  206. if err != nil {
  207. logging.LogErrorf("parse json [%s] to tree failed: %s", boxID+p, err)
  208. return
  209. }
  210. ret.Box = boxID
  211. ret.Path = p
  212. filePath := filepath.Join(util.DataDir, ret.Box, ret.Path)
  213. if oldSpec := ret.Root.Spec; "" == oldSpec {
  214. parse.NestedInlines2FlattedSpans(ret, false)
  215. ret.Root.Spec = "1"
  216. needFix = true
  217. logging.LogInfof("migrated tree [%s] from spec [%s] to [%s]", filePath, oldSpec, ret.Root.Spec)
  218. }
  219. if needFix {
  220. renderer := render.NewJSONRenderer(ret, luteEngine.RenderOptions)
  221. data := renderer.Render()
  222. if !util.UseSingleLineSave {
  223. buf := bytes.Buffer{}
  224. buf.Grow(1024 * 1024 * 2)
  225. if err = json.Indent(&buf, data, "", "\t"); err != nil {
  226. return
  227. }
  228. data = buf.Bytes()
  229. }
  230. if err = os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
  231. return
  232. }
  233. if err = filelock.WriteFile(filePath, data); err != nil {
  234. msg := fmt.Sprintf("write data [%s] failed: %s", filePath, err)
  235. logging.LogErrorf(msg)
  236. }
  237. }
  238. return
  239. }
  240. func ReadDocIAL(data []byte) (ret map[string]string) {
  241. ret = map[string]string{}
  242. val := jsoniter.Get(data, "Properties")
  243. if nil == val || val.ValueType() == jsoniter.InvalidValue {
  244. return
  245. }
  246. val.ToVal(&ret)
  247. return
  248. }