template.go 7.9 KB

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