tree.go 8.0 KB

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