template.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // Copyright 2014 The Gogs 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 and LICENSE.gogs file.
  4. package template
  5. import (
  6. "fmt"
  7. "html/template"
  8. "mime"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/editorconfig/editorconfig-core-go/v2"
  14. jsoniter "github.com/json-iterator/go"
  15. "github.com/microcosm-cc/bluemonday"
  16. "golang.org/x/net/html/charset"
  17. "golang.org/x/text/transform"
  18. log "unknwon.dev/clog/v2"
  19. "github.com/gogs/git-module"
  20. "github.com/SongZihuan/huan-gogs/internal/conf"
  21. "github.com/SongZihuan/huan-gogs/internal/cryptoutil"
  22. "github.com/SongZihuan/huan-gogs/internal/database"
  23. "github.com/SongZihuan/huan-gogs/internal/gitutil"
  24. "github.com/SongZihuan/huan-gogs/internal/markup"
  25. "github.com/SongZihuan/huan-gogs/internal/strutil"
  26. "github.com/SongZihuan/huan-gogs/internal/tool"
  27. )
  28. var (
  29. funcMap []template.FuncMap
  30. funcMapOnce sync.Once
  31. )
  32. // FuncMap returns a list of user-defined template functions.
  33. func FuncMap() []template.FuncMap {
  34. funcMapOnce.Do(func() {
  35. funcMap = []template.FuncMap{map[string]any{
  36. "BuildCommit": func() string {
  37. return conf.BuildCommit
  38. },
  39. "Year": func() int {
  40. return time.Now().Year()
  41. },
  42. "UseHTTPS": func() bool {
  43. return conf.Server.URL.Scheme == "https"
  44. },
  45. "AppName": func() string {
  46. return conf.App.BrandName
  47. },
  48. "AppSubURL": func() string {
  49. return conf.Server.Subpath
  50. },
  51. "AppURL": func() string {
  52. return conf.Server.ExternalURL
  53. },
  54. "AppVer": func() string {
  55. return conf.App.Version
  56. },
  57. "AppDomain": func() string {
  58. return conf.Server.Domain
  59. },
  60. "DisableGravatar": func() bool {
  61. return conf.Picture.DisableGravatar
  62. },
  63. "LoadTimes": func(startTime time.Time) string {
  64. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  65. },
  66. "AvatarLink": tool.AvatarLink,
  67. "AppendAvatarSize": tool.AppendAvatarSize,
  68. "Safe": Safe,
  69. "Sanitize": bluemonday.UGCPolicy().Sanitize,
  70. "Str2HTML": Str2HTML,
  71. "NewLine2br": NewLine2br,
  72. "TimeSince": tool.TimeSince,
  73. "RawTimeSince": tool.RawTimeSince,
  74. "FileSize": tool.FileSize,
  75. "Subtract": tool.Subtract,
  76. "Add": func(a, b int) int {
  77. return a + b
  78. },
  79. "ActionIcon": ActionIcon,
  80. "DateFmtLong": func(t time.Time) string {
  81. return t.Format(time.RFC1123Z)
  82. },
  83. "DateFmtShort": func(t time.Time) string {
  84. return t.Format("Jan 02, 2006")
  85. },
  86. "SubStr": func(str string, start, length int) string {
  87. if str == "" {
  88. return ""
  89. }
  90. end := start + length
  91. if length == -1 {
  92. end = len(str)
  93. }
  94. if len(str) < end {
  95. return str
  96. }
  97. return str[start:end]
  98. },
  99. "Join": strings.Join,
  100. "EllipsisString": strutil.Ellipsis,
  101. "DiffFileTypeToStr": DiffFileTypeToStr,
  102. "DiffLineTypeToStr": DiffLineTypeToStr,
  103. "Sha1": Sha1,
  104. "ShortSHA1": tool.ShortSHA1,
  105. "ActionContent2Commits": ActionContent2Commits,
  106. "EscapePound": EscapePound,
  107. "RenderCommitMessage": RenderCommitMessage,
  108. "ThemeColorMetaTag": func() string {
  109. return conf.UI.ThemeColorMetaTag
  110. },
  111. "FilenameIsImage": func(filename string) bool {
  112. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  113. return strings.HasPrefix(mimeType, "image/")
  114. },
  115. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  116. if ec != nil {
  117. def, err := ec.GetDefinitionForFilename(filename)
  118. if err == nil && def.TabWidth > 0 {
  119. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  120. }
  121. }
  122. return "tab-size-8"
  123. },
  124. "InferSubmoduleURL": gitutil.InferSubmoduleURL,
  125. }}
  126. })
  127. return funcMap
  128. }
  129. func Safe(raw string) template.HTML {
  130. return template.HTML(raw)
  131. }
  132. func Str2HTML(raw string) template.HTML {
  133. return template.HTML(markup.Sanitize(raw))
  134. }
  135. // NewLine2br simply replaces "\n" to "<br>".
  136. func NewLine2br(raw string) string {
  137. return strings.ReplaceAll(raw, "\n", "<br>")
  138. }
  139. func Sha1(str string) string {
  140. return cryptoutil.SHA1(str)
  141. }
  142. func ToUTF8WithErr(content []byte) (error, string) {
  143. charsetLabel, err := tool.DetectEncoding(content)
  144. if err != nil {
  145. return err, ""
  146. } else if charsetLabel == "UTF-8" {
  147. return nil, string(content)
  148. }
  149. encoding, _ := charset.Lookup(charsetLabel)
  150. if encoding == nil {
  151. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  152. }
  153. // If there is an error, we concatenate the nicely decoded part and the
  154. // original left over. This way we won't loose data.
  155. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  156. if err != nil {
  157. result = result + string(content[n:])
  158. }
  159. return err, result
  160. }
  161. // RenderCommitMessage renders commit message with special links.
  162. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  163. cleanMsg := template.HTMLEscapeString(msg)
  164. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  165. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  166. numLines := len(msgLines)
  167. if numLines == 0 {
  168. return ""
  169. } else if !full {
  170. return msgLines[0]
  171. } else if numLines == 1 || (numLines >= 2 && msgLines[1] == "") {
  172. // First line is a header, standalone or followed by empty line
  173. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  174. if numLines >= 2 {
  175. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  176. } else {
  177. fullMessage = header
  178. }
  179. } else {
  180. // Non-standard git message, there is no header line
  181. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  182. }
  183. return fullMessage
  184. }
  185. type Actioner interface {
  186. GetOpType() int
  187. GetActUserName() string
  188. GetRepoUserName() string
  189. GetRepoName() string
  190. GetRepoPath() string
  191. GetRepoLink() string
  192. GetBranch() string
  193. GetContent() string
  194. GetCreate() time.Time
  195. GetIssueInfos() []string
  196. }
  197. // ActionIcon accepts a int that represents action operation type
  198. // and returns a icon class name.
  199. func ActionIcon(opType int) string {
  200. switch opType {
  201. case 1, 8: // Create and transfer repository
  202. return "repo"
  203. case 5: // Commit repository
  204. return "git-commit"
  205. case 6: // Create issue
  206. return "issue-opened"
  207. case 7: // New pull request
  208. return "git-pull-request"
  209. case 9: // Push tag
  210. return "tag"
  211. case 10: // Comment issue
  212. return "comment-discussion"
  213. case 11: // Merge pull request
  214. return "git-merge"
  215. case 12, 14: // Close issue or pull request
  216. return "issue-closed"
  217. case 13, 15: // Reopen issue or pull request
  218. return "issue-reopened"
  219. case 16: // Create branch
  220. return "git-branch"
  221. case 17, 18: // Delete branch or tag
  222. return "alert"
  223. case 19: // Fork a repository
  224. return "repo-forked"
  225. case 20, 21, 22: // Mirror sync
  226. return "repo-clone"
  227. default:
  228. return "invalid type"
  229. }
  230. }
  231. func ActionContent2Commits(act Actioner) *database.PushCommits {
  232. push := database.NewPushCommits()
  233. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  234. log.Error("Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  235. }
  236. return push
  237. }
  238. // TODO(unknwon): Use url.Escape.
  239. func EscapePound(str string) string {
  240. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  241. }
  242. func DiffFileTypeToStr(typ git.DiffFileType) string {
  243. return map[git.DiffFileType]string{
  244. git.DiffFileAdd: "add",
  245. git.DiffFileChange: "modify",
  246. git.DiffFileDelete: "del",
  247. git.DiffFileRename: "rename",
  248. }[typ]
  249. }
  250. func DiffLineTypeToStr(typ git.DiffLineType) string {
  251. switch typ {
  252. case git.DiffLineAdd:
  253. return "add"
  254. case git.DiffLineDelete:
  255. return "del"
  256. case git.DiffLineSection:
  257. return "tag"
  258. }
  259. return "same"
  260. }