template.go 7.8 KB

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