template.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package template
  7. import (
  8. "container/list"
  9. "fmt"
  10. "gitote/gitote/models"
  11. "gitote/gitote/pkg/markup"
  12. "gitote/gitote/pkg/setting"
  13. "gitote/gitote/pkg/tool"
  14. "html/template"
  15. "mime"
  16. "path/filepath"
  17. "runtime"
  18. "strings"
  19. "time"
  20. raven "github.com/getsentry/raven-go"
  21. "github.com/json-iterator/go"
  22. "github.com/microcosm-cc/bluemonday"
  23. "golang.org/x/net/html/charset"
  24. "golang.org/x/text/transform"
  25. log "gopkg.in/clog.v1"
  26. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  27. )
  28. // TODO: only initialize map once and save to a local variable to reduce copies.
  29. func NewFuncMap() []template.FuncMap {
  30. return []template.FuncMap{map[string]interface{}{
  31. "GoVer": func() string {
  32. return strings.Title(runtime.Version())
  33. },
  34. "UseHTTPS": func() bool {
  35. return strings.HasPrefix(setting.AppURL, "https")
  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. "APIVer": func() string {
  47. return setting.APIVer
  48. },
  49. "AppDomain": func() string {
  50. return setting.Domain
  51. },
  52. "DisableGravatar": func() bool {
  53. return setting.DisableGravatar
  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,
  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. "IssueDesc": tool.IssueDesc,
  99. "MD5": tool.MD5,
  100. "ActionContent2Commits": ActionContent2Commits,
  101. "EscapePound": EscapePound,
  102. "RenderCommitMessage": RenderCommitMessage,
  103. "FilenameIsImage": func(filename string) bool {
  104. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  105. return strings.HasPrefix(mimeType, "image/")
  106. },
  107. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  108. if ec != nil {
  109. def := ec.GetDefinitionForFilename(filename)
  110. if def.TabWidth > 0 {
  111. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  112. }
  113. }
  114. return "tab-size-8"
  115. },
  116. }}
  117. }
  118. func Safe(raw string) template.HTML {
  119. return template.HTML(raw)
  120. }
  121. func Str2HTML(raw string) template.HTML {
  122. return template.HTML(markup.Sanitize(raw))
  123. }
  124. // NewLine2br simply replaces "\n" to "<br>".
  125. func NewLine2br(raw string) string {
  126. return strings.Replace(raw, "\n", "<br>", -1)
  127. }
  128. func List(l *list.List) chan interface{} {
  129. e := l.Front()
  130. c := make(chan interface{})
  131. go func() {
  132. for e != nil {
  133. c <- e.Value
  134. e = e.Next()
  135. }
  136. close(c)
  137. }()
  138. return c
  139. }
  140. func Sha1(str string) string {
  141. return tool.SHA1(str)
  142. }
  143. func ToUTF8WithErr(content []byte) (error, string) {
  144. charsetLabel, err := tool.DetectEncoding(content)
  145. if err != nil {
  146. return err, ""
  147. } else if charsetLabel == "UTF-8" {
  148. return nil, string(content)
  149. }
  150. encoding, _ := charset.Lookup(charsetLabel)
  151. if encoding == nil {
  152. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  153. }
  154. // If there is an error, we concatenate the nicely decoded part and the
  155. // original left over. This way we won't loose data.
  156. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  157. if err != nil {
  158. result = result + string(content[n:])
  159. }
  160. return err, result
  161. }
  162. // FIXME: Unused function
  163. func ToUTF8(content string) string {
  164. _, res := ToUTF8WithErr([]byte(content))
  165. return res
  166. }
  167. // Replaces all prefixes 'old' in 's' with 'new'.
  168. // FIXME: Unused function
  169. func ReplaceLeft(s, old, new string) string {
  170. old_len, new_len, i, n := len(old), len(new), 0, 0
  171. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  172. i += old_len
  173. }
  174. // simple optimization
  175. if n == 0 {
  176. return s
  177. }
  178. // allocating space for the new string
  179. newLen := n*new_len + len(s[i:])
  180. replacement := make([]byte, newLen, newLen)
  181. j := 0
  182. for ; j < n*new_len; j += new_len {
  183. copy(replacement[j:j+new_len], new)
  184. }
  185. copy(replacement[j:], s[i:])
  186. return string(replacement)
  187. }
  188. // RenderCommitMessage renders commit message with special links.
  189. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  190. cleanMsg := template.HTMLEscapeString(msg)
  191. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  192. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  193. numLines := len(msgLines)
  194. if numLines == 0 {
  195. return ""
  196. } else if !full {
  197. return msgLines[0]
  198. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  199. // First line is a header, standalone or followed by empty line
  200. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  201. if numLines >= 2 {
  202. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  203. } else {
  204. fullMessage = header
  205. }
  206. } else {
  207. // Non-standard git message, there is no header line
  208. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  209. }
  210. return fullMessage
  211. }
  212. type Actioner interface {
  213. GetOpType() int
  214. GetActUserName() string
  215. GetRepoUserName() string
  216. GetRepoName() string
  217. GetRepoPath() string
  218. GetRepoLink() string
  219. GetBranch() string
  220. GetContent() string
  221. GetCreate() time.Time
  222. GetIssueInfos() []string
  223. }
  224. // ActionIcon accepts a int that represents action operation type
  225. // and returns a icon class name.
  226. func ActionIcon(opType int) string {
  227. switch opType {
  228. case 1, 8: // Create and transfer repository
  229. return "rocket"
  230. case 5: // Push repository
  231. return "repo-push"
  232. case 6: // Create issue
  233. return "issue-opened"
  234. case 7: // New pull request
  235. return "git-pull-request"
  236. case 9: // Push tag
  237. return "tag"
  238. case 10: // Comment issue
  239. return "comment-discussion"
  240. case 11: // Merge pull request
  241. return "git-merge"
  242. case 12, 14: // Close issue or pull request
  243. return "issue-closed"
  244. case 13, 15: // Reopen issue or pull request
  245. return "issue-reopened"
  246. case 16: // Create branch
  247. return "git-branch"
  248. case 17, 18: // Delete branch or tag
  249. return "alert"
  250. case 19: // Fork a repository
  251. return "repo-forked"
  252. case 20, 21, 22: // Mirror sync
  253. return "repo-clone"
  254. default:
  255. return "invalid type"
  256. }
  257. }
  258. func ActionContent2Commits(act Actioner) *models.PushCommits {
  259. push := models.NewPushCommits()
  260. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  261. raven.CaptureErrorAndWait(err, nil)
  262. log.Error(4, "Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  263. }
  264. return push
  265. }
  266. func EscapePound(str string) string {
  267. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  268. }
  269. func DiffTypeToStr(diffType int) string {
  270. diffTypes := map[int]string{
  271. 1: "add", 2: "modify", 3: "del", 4: "rename",
  272. }
  273. return diffTypes[diffType]
  274. }
  275. func DiffLineTypeToStr(diffType int) string {
  276. switch diffType {
  277. case 2:
  278. return "add"
  279. case 3:
  280. return "del"
  281. case 4:
  282. return "tag"
  283. }
  284. return "same"
  285. }