tree.go 7.7 KB

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