gitea源码

meta.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package markdown
  4. import (
  5. "bytes"
  6. "errors"
  7. "unicode"
  8. "unicode/utf8"
  9. "gopkg.in/yaml.v3"
  10. )
  11. func isYAMLSeparator(line []byte) bool {
  12. idx := 0
  13. for ; idx < len(line); idx++ {
  14. if line[idx] >= utf8.RuneSelf {
  15. r, sz := utf8.DecodeRune(line[idx:])
  16. if !unicode.IsSpace(r) {
  17. return false
  18. }
  19. idx += sz
  20. continue
  21. }
  22. if line[idx] != ' ' {
  23. break
  24. }
  25. }
  26. dashCount := 0
  27. for ; idx < len(line); idx++ {
  28. if line[idx] != '-' {
  29. break
  30. }
  31. dashCount++
  32. }
  33. if dashCount < 3 {
  34. return false
  35. }
  36. for ; idx < len(line); idx++ {
  37. if line[idx] >= utf8.RuneSelf {
  38. r, sz := utf8.DecodeRune(line[idx:])
  39. if !unicode.IsSpace(r) {
  40. return false
  41. }
  42. idx += sz
  43. continue
  44. }
  45. if line[idx] != ' ' {
  46. return false
  47. }
  48. }
  49. return true
  50. }
  51. // ExtractMetadata consumes a markdown file, parses YAML frontmatter,
  52. // and returns the frontmatter metadata separated from the markdown content
  53. func ExtractMetadata(contents string, out any) (string, error) {
  54. body, err := ExtractMetadataBytes([]byte(contents), out)
  55. return string(body), err
  56. }
  57. // ExtractMetadata consumes a markdown file, parses YAML frontmatter,
  58. // and returns the frontmatter metadata separated from the markdown content
  59. func ExtractMetadataBytes(contents []byte, out any) ([]byte, error) {
  60. var front, body []byte
  61. start, end := 0, len(contents)
  62. idx := bytes.IndexByte(contents[start:], '\n')
  63. if idx >= 0 {
  64. end = start + idx
  65. }
  66. line := contents[start:end]
  67. if !isYAMLSeparator(line) {
  68. return contents, errors.New("frontmatter must start with a separator line")
  69. }
  70. frontMatterStart := end + 1
  71. for start = frontMatterStart; start < len(contents); start = end + 1 {
  72. end = len(contents)
  73. idx := bytes.IndexByte(contents[start:], '\n')
  74. if idx >= 0 {
  75. end = start + idx
  76. }
  77. line := contents[start:end]
  78. if isYAMLSeparator(line) {
  79. front = contents[frontMatterStart:start]
  80. if end+1 < len(contents) {
  81. body = contents[end+1:]
  82. }
  83. break
  84. }
  85. }
  86. if len(front) == 0 {
  87. return contents, errors.New("could not determine metadata")
  88. }
  89. if err := yaml.Unmarshal(front, out); err != nil {
  90. return contents, err
  91. }
  92. return body, nil
  93. }