You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

template.go 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. "encoding/json"
  8. "fmt"
  9. "html/template"
  10. "runtime"
  11. "strings"
  12. "time"
  13. "golang.org/x/net/html/charset"
  14. "golang.org/x/text/transform"
  15. "github.com/gogits/gogs/models"
  16. "github.com/gogits/gogs/modules/base"
  17. "github.com/gogits/gogs/modules/markdown"
  18. "github.com/gogits/gogs/modules/setting"
  19. )
  20. var Funcs template.FuncMap = map[string]interface{}{
  21. "GoVer": func() string {
  22. return strings.Title(runtime.Version())
  23. },
  24. "UseHTTPS": func() bool {
  25. return strings.HasPrefix(setting.AppUrl, "https")
  26. },
  27. "AppName": func() string {
  28. return setting.AppName
  29. },
  30. "AppSubUrl": func() string {
  31. return setting.AppSubUrl
  32. },
  33. "AppUrl": func() string {
  34. return setting.AppUrl
  35. },
  36. "AppVer": func() string {
  37. return setting.AppVer
  38. },
  39. "AppDomain": func() string {
  40. return setting.Domain
  41. },
  42. "DisableGravatar": func() bool {
  43. return setting.DisableGravatar
  44. },
  45. "LoadTimes": func(startTime time.Time) string {
  46. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  47. },
  48. "AvatarLink": base.AvatarLink,
  49. "Safe": Safe,
  50. "Str2html": Str2html,
  51. "TimeSince": base.TimeSince,
  52. "RawTimeSince": base.RawTimeSince,
  53. "FileSize": base.FileSize,
  54. "Subtract": base.Subtract,
  55. "Add": func(a, b int) int {
  56. return a + b
  57. },
  58. "ActionIcon": ActionIcon,
  59. "DateFmtLong": func(t time.Time) string {
  60. return t.Format(time.RFC1123Z)
  61. },
  62. "DateFmtShort": func(t time.Time) string {
  63. return t.Format("Jan 02, 2006")
  64. },
  65. "List": List,
  66. "Mail2Domain": func(mail string) string {
  67. if !strings.Contains(mail, "@") {
  68. return "try.gogs.io"
  69. }
  70. return strings.SplitN(mail, "@", 2)[1]
  71. },
  72. "SubStr": func(str string, start, length int) string {
  73. if len(str) == 0 {
  74. return ""
  75. }
  76. end := start + length
  77. if length == -1 {
  78. end = len(str)
  79. }
  80. if len(str) < end {
  81. return str
  82. }
  83. return str[start:end]
  84. },
  85. "DiffTypeToStr": DiffTypeToStr,
  86. "DiffLineTypeToStr": DiffLineTypeToStr,
  87. "Sha1": Sha1,
  88. "ShortSha": base.ShortSha,
  89. "MD5": base.EncodeMD5,
  90. "ActionContent2Commits": ActionContent2Commits,
  91. "ToUtf8": ToUtf8,
  92. "EscapePound": func(str string) string {
  93. return strings.Replace(strings.Replace(str, "%", "%25", -1), "#", "%23", -1)
  94. },
  95. "RenderCommitMessage": RenderCommitMessage,
  96. "ThemeColorMetaTag": func() string {
  97. return setting.ThemeColorMetaTag
  98. },
  99. }
  100. func Safe(raw string) template.HTML {
  101. return template.HTML(raw)
  102. }
  103. func Str2html(raw string) template.HTML {
  104. return template.HTML(markdown.Sanitizer.Sanitize(raw))
  105. }
  106. func Range(l int) []int {
  107. return make([]int, l)
  108. }
  109. func List(l *list.List) chan interface{} {
  110. e := l.Front()
  111. c := make(chan interface{})
  112. go func() {
  113. for e != nil {
  114. c <- e.Value
  115. e = e.Next()
  116. }
  117. close(c)
  118. }()
  119. return c
  120. }
  121. func Sha1(str string) string {
  122. return base.EncodeSha1(str)
  123. }
  124. func ToUtf8WithErr(content []byte) (error, string) {
  125. charsetLabel, err := base.DetectEncoding(content)
  126. if err != nil {
  127. return err, ""
  128. } else if charsetLabel == "UTF-8" {
  129. return nil, string(content)
  130. }
  131. encoding, _ := charset.Lookup(charsetLabel)
  132. if encoding == nil {
  133. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  134. }
  135. // If there is an error, we concatenate the nicely decoded part and the
  136. // original left over. This way we won't loose data.
  137. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  138. if err != nil {
  139. result = result + string(content[n:])
  140. }
  141. return err, result
  142. }
  143. func ToUtf8(content string) string {
  144. _, res := ToUtf8WithErr([]byte(content))
  145. return res
  146. }
  147. // Replaces all prefixes 'old' in 's' with 'new'.
  148. func ReplaceLeft(s, old, new string) string {
  149. old_len, new_len, i, n := len(old), len(new), 0, 0
  150. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  151. i += old_len
  152. }
  153. // simple optimization
  154. if n == 0 {
  155. return s
  156. }
  157. // allocating space for the new string
  158. newLen := n*new_len + len(s[i:])
  159. replacement := make([]byte, newLen, newLen)
  160. j := 0
  161. for ; j < n*new_len; j += new_len {
  162. copy(replacement[j:j+new_len], new)
  163. }
  164. copy(replacement[j:], s[i:])
  165. return string(replacement)
  166. }
  167. // RenderCommitMessage renders commit message with XSS-safe and special links.
  168. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) template.HTML {
  169. cleanMsg := template.HTMLEscapeString(msg)
  170. fullMessage := string(markdown.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  171. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  172. numLines := len(msgLines)
  173. if numLines == 0 {
  174. return template.HTML("")
  175. } else if !full {
  176. return template.HTML(msgLines[0])
  177. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  178. // First line is a header, standalone or followed by empty line
  179. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  180. if numLines >= 2 {
  181. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  182. } else {
  183. fullMessage = header
  184. }
  185. } else {
  186. // Non-standard git message, there is no header line
  187. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  188. }
  189. return template.HTML(fullMessage)
  190. }
  191. type Actioner interface {
  192. GetOpType() int
  193. GetActUserName() string
  194. GetActEmail() string
  195. GetRepoUserName() string
  196. GetRepoName() string
  197. GetRepoPath() string
  198. GetRepoLink() string
  199. GetBranch() string
  200. GetContent() string
  201. GetCreate() time.Time
  202. GetIssueInfos() []string
  203. }
  204. // ActionIcon accepts a int that represents action operation type
  205. // and returns a icon class name.
  206. func ActionIcon(opType int) string {
  207. switch opType {
  208. case 1, 8: // Create and transfer repository
  209. return "repo"
  210. case 5, 9: // Commit repository
  211. return "git-commit"
  212. case 6: // Create issue
  213. return "issue-opened"
  214. case 7: // New pull request
  215. return "git-pull-request"
  216. case 10: // Comment issue
  217. return "comment"
  218. case 11: // Merge pull request
  219. return "git-merge"
  220. case 12, 14: // Close issue or pull request
  221. return "issue-closed"
  222. case 13, 15: // Reopen issue or pull request
  223. return "issue-reopened"
  224. default:
  225. return "invalid type"
  226. }
  227. }
  228. func ActionContent2Commits(act Actioner) *models.PushCommits {
  229. push := models.NewPushCommits()
  230. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  231. return nil
  232. }
  233. return push
  234. }
  235. func DiffTypeToStr(diffType int) string {
  236. diffTypes := map[int]string{
  237. 1: "add", 2: "modify", 3: "del", 4: "rename",
  238. }
  239. return diffTypes[diffType]
  240. }
  241. func DiffLineTypeToStr(diffType int) string {
  242. switch diffType {
  243. case 2:
  244. return "add"
  245. case 3:
  246. return "del"
  247. case 4:
  248. return "tag"
  249. }
  250. return "same"
  251. }