template.go 7.9 KB

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