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

template.go 7.2 kB

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