template.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, 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. // NewFuncMap 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. // Safe render raw as HTML
  119. func Safe(raw string) template.HTML {
  120. return template.HTML(raw)
  121. }
  122. // Str2HTML render Markdown text to HTML
  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. // List traversings the list
  131. func List(l *list.List) chan interface{} {
  132. e := l.Front()
  133. c := make(chan interface{})
  134. go func() {
  135. for e != nil {
  136. c <- e.Value
  137. e = e.Next()
  138. }
  139. close(c)
  140. }()
  141. return c
  142. }
  143. // Sha1 returns sha1 sum of string
  144. func Sha1(str string) string {
  145. return tool.SHA1(str)
  146. }
  147. // ToUTF8WithErr converts content to UTF8 encoding
  148. func ToUTF8WithErr(content []byte) (error, string) {
  149. charsetLabel, err := tool.DetectEncoding(content)
  150. if err != nil {
  151. return err, ""
  152. } else if charsetLabel == "UTF-8" {
  153. return nil, string(content)
  154. }
  155. encoding, _ := charset.Lookup(charsetLabel)
  156. if encoding == nil {
  157. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  158. }
  159. // If there is an error, we concatenate the nicely decoded part and the
  160. // original left over. This way we won't loose data.
  161. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  162. if err != nil {
  163. result = result + string(content[n:])
  164. }
  165. return err, result
  166. }
  167. // ToUTF8 converts content to UTF8 encoding and ignore error
  168. func ToUTF8(content string) string {
  169. _, res := ToUTF8WithErr([]byte(content))
  170. return res
  171. }
  172. // ReplaceLeft replaces all prefixes 'old' in 's' with 'new'.
  173. // FIXME: Unused function
  174. func ReplaceLeft(s, old, new string) string {
  175. oldLen, newLen, i, n := len(old), len(new), 0, 0
  176. for ; i < len(s) && strings.HasPrefix(s[i:], old); n++ {
  177. i += oldLen
  178. }
  179. // simple optimization
  180. if n == 0 {
  181. return s
  182. }
  183. // allocating space for the new string
  184. curLen := n*newLen + len(s[i:])
  185. replacement := make([]byte, curLen, curLen)
  186. j := 0
  187. for ; j < n*newLen; j += newLen {
  188. copy(replacement[j:j+newLen], new)
  189. }
  190. copy(replacement[j:], s[i:])
  191. return string(replacement)
  192. }
  193. // RenderCommitMessage renders commit message with special links.
  194. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  195. cleanMsg := template.HTMLEscapeString(msg)
  196. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  197. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  198. numLines := len(msgLines)
  199. if numLines == 0 {
  200. return ""
  201. } else if !full {
  202. return msgLines[0]
  203. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  204. // First line is a header, standalone or followed by empty line
  205. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  206. if numLines >= 2 {
  207. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  208. } else {
  209. fullMessage = header
  210. }
  211. } else {
  212. // Non-standard git message, there is no header line
  213. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  214. }
  215. return fullMessage
  216. }
  217. // Actioner describes an action
  218. type Actioner interface {
  219. GetOpType() int
  220. GetActUserName() string
  221. GetRepoUserName() string
  222. GetRepoName() string
  223. GetRepoPath() string
  224. GetRepoLink() string
  225. GetBranch() string
  226. GetContent() string
  227. GetCreate() time.Time
  228. GetIssueInfos() []string
  229. }
  230. // ActionIcon accepts a int that represents action operation type
  231. // and returns a icon class name.
  232. func ActionIcon(opType int) string {
  233. switch opType {
  234. case 1, 8: // Create and transfer repository
  235. return "rocket"
  236. case 5: // Push repository
  237. return "repo-push"
  238. case 6: // Create issue
  239. return "issue-opened"
  240. case 7: // New pull request
  241. return "git-pull-request"
  242. case 9: // Push tag
  243. return "tag"
  244. case 10: // Comment issue
  245. return "comment-discussion"
  246. case 11: // Merge pull request
  247. return "git-merge"
  248. case 12, 14: // Close issue or pull request
  249. return "issue-closed"
  250. case 13, 15: // Reopen issue or pull request
  251. return "issue-reopened"
  252. case 16: // Create branch
  253. return "git-branch"
  254. case 17, 18: // Delete branch or tag
  255. return "alert"
  256. case 19: // Fork a repository
  257. return "repo-forked"
  258. case 20, 21, 22: // Mirror sync
  259. return "repo-clone"
  260. default:
  261. return "invalid type"
  262. }
  263. }
  264. // ActionContent2Commits converts action content to push commits
  265. func ActionContent2Commits(act Actioner) *models.PushCommits {
  266. push := models.NewPushCommits()
  267. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  268. raven.CaptureErrorAndWait(err, nil)
  269. log.Error(4, "Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  270. }
  271. return push
  272. }
  273. // EscapePound returns new replacer
  274. func EscapePound(str string) string {
  275. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  276. }
  277. // DiffTypeToStr returns diff type name
  278. func DiffTypeToStr(diffType int) string {
  279. diffTypes := map[int]string{
  280. 1: "add", 2: "modify", 3: "del", 4: "rename",
  281. }
  282. return diffTypes[diffType]
  283. }
  284. // DiffLineTypeToStr returns diff line type name
  285. func DiffLineTypeToStr(diffType int) string {
  286. switch diffType {
  287. case 2:
  288. return "add"
  289. case 3:
  290. return "del"
  291. case 4:
  292. return "tag"
  293. }
  294. return "same"
  295. }