snippet.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 model
  17. import (
  18. "path/filepath"
  19. "sync"
  20. "github.com/88250/gulu"
  21. "github.com/siyuan-note/filelock"
  22. "github.com/siyuan-note/logging"
  23. "github.com/siyuan-note/siyuan/kernel/conf"
  24. "github.com/siyuan-note/siyuan/kernel/util"
  25. )
  26. var snippetsLock = sync.Mutex{}
  27. func SetSnippet(name, typ, content string, enabled bool) (err error) {
  28. snippetsLock.Lock()
  29. defer snippetsLock.Unlock()
  30. snippets, err := loadSnippets()
  31. if nil != err {
  32. return
  33. }
  34. snippet := &conf.Snippet{Name: name, Type: typ, Content: content, Enabled: enabled}
  35. snippets = append(snippets, snippet)
  36. err = writeSnippetsConf(snippets)
  37. return
  38. }
  39. func LoadSnippets() (ret []*conf.Snippet, err error) {
  40. snippetsLock.Lock()
  41. defer snippetsLock.Unlock()
  42. return loadSnippets()
  43. }
  44. func loadSnippets() (ret []*conf.Snippet, err error) {
  45. ret = []*conf.Snippet{}
  46. confPath := filepath.Join(util.DataDir, "snippets/conf.json")
  47. if !gulu.File.IsExist(confPath) {
  48. return
  49. }
  50. data, err := filelock.ReadFile(confPath)
  51. if nil != err {
  52. logging.LogErrorf("load js snippets failed: %s", err)
  53. return
  54. }
  55. if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err {
  56. logging.LogErrorf("unmarshal js snippets failed: %s", err)
  57. return
  58. }
  59. return
  60. }
  61. func writeSnippetsConf(snippets []*conf.Snippet) (err error) {
  62. data, err := gulu.JSON.MarshalIndentJSON(snippets, "", " ")
  63. if nil != err {
  64. logging.LogErrorf("marshal snippets failed: %s", err)
  65. return
  66. }
  67. confPath := filepath.Join(util.DataDir, "snippets/conf.json")
  68. err = filelock.WriteFile(confPath, data)
  69. return
  70. }