changelog_data.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2025 BackendServerTemplate Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package changelog
  5. import (
  6. "github.com/SongZihuan/BackendServerTemplate/tool/utils/cleanstringutils"
  7. "log"
  8. "os"
  9. "strings"
  10. "sync"
  11. )
  12. const FileChangelog = "./CHANGELOG.md"
  13. var lastChangeLog = ""
  14. var once sync.Once
  15. func GetLastChangLog() string {
  16. once.Do(func() {
  17. lastChangeLog = getLastChangLog()
  18. })
  19. return lastChangeLog
  20. }
  21. func getLastChangLog() string {
  22. log.Printf("generate: get %s data\n", FileChangelog)
  23. defer log.Printf("generate: get %s data finish\n", FileChangelog)
  24. dat, err := os.ReadFile(FileChangelog)
  25. if err != nil {
  26. log.Printf("generate: read file %s failed: %s\n", FileChangelog, err.Error())
  27. return ""
  28. }
  29. logSrc := strings.Split(cleanstringutils.GetString(string(dat)), "\n")
  30. res := new(strings.Builder)
  31. index := 0
  32. // 定位最新版本
  33. FindVersionCycle:
  34. for ; ; index++ {
  35. if index >= len(logSrc) {
  36. log.Printf("generate: read file %s failed: log title not found\n", FileChangelog)
  37. return ""
  38. }
  39. s := logSrc[index]
  40. if strings.HasPrefix(s, "## [") && !strings.HasPrefix(s, "## [未") {
  41. log.Printf("generate: read file %s title [index: %d]: %s\n", FileChangelog, index, s)
  42. res.WriteString(s + "\n")
  43. break FindVersionCycle
  44. }
  45. }
  46. GetVersionLogCycle:
  47. for index++; ; index++ { // 初始化的 index++ 是为了从标题哪一行向下走一行。因为对于上面的循环(FindVersionCycle)来说,break 后置语句(index++)也就不会执行,若本循环开头不执行(index++)则会导致本循环读取的第一条数据和 FindVersionCycle 循环读取的第一条数据为同一行(标题行)
  48. if index >= len(logSrc) {
  49. break GetVersionLogCycle
  50. }
  51. s := logSrc[index]
  52. if strings.HasPrefix(s, "## [") {
  53. log.Printf("generate: read file %s content end [index: %d]\n", FileChangelog, index)
  54. break GetVersionLogCycle
  55. }
  56. log.Printf("generate: read file %s content [index: %d]: %s\n", FileChangelog, index, s)
  57. res.WriteString(s + "\n")
  58. }
  59. return res.String()
  60. }