template.go 7.6 KB

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