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.

helper.go 12 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 templates
  5. import (
  6. "bytes"
  7. "container/list"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "html"
  12. "html/template"
  13. "mime"
  14. "net/url"
  15. "path/filepath"
  16. "runtime"
  17. "strings"
  18. "time"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/markup"
  23. "code.gitea.io/gitea/modules/setting"
  24. "golang.org/x/net/html/charset"
  25. "golang.org/x/text/transform"
  26. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  27. )
  28. // NewFuncMap returns functions for injecting to templates
  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. "AppName": func() string {
  38. return setting.AppName
  39. },
  40. "AppSubUrl": func() string {
  41. return setting.AppSubURL
  42. },
  43. "AppUrl": func() string {
  44. return setting.AppURL
  45. },
  46. "AppVer": func() string {
  47. return setting.AppVer
  48. },
  49. "AppBuiltWith": func() string {
  50. return setting.AppBuiltWith
  51. },
  52. "AppDomain": func() string {
  53. return setting.Domain
  54. },
  55. "DisableGravatar": func() bool {
  56. return setting.DisableGravatar
  57. },
  58. "ShowFooterTemplateLoadTime": func() bool {
  59. return setting.ShowFooterTemplateLoadTime
  60. },
  61. "LoadTimes": func(startTime time.Time) string {
  62. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  63. },
  64. "AvatarLink": base.AvatarLink,
  65. "Safe": Safe,
  66. "SafeJS": SafeJS,
  67. "Str2html": Str2html,
  68. "TimeSince": base.TimeSince,
  69. "TimeSinceUnix": base.TimeSinceUnix,
  70. "RawTimeSince": base.RawTimeSince,
  71. "FileSize": base.FileSize,
  72. "Subtract": base.Subtract,
  73. "Add": func(a, b int) int {
  74. return a + b
  75. },
  76. "ActionIcon": ActionIcon,
  77. "DateFmtLong": func(t time.Time) string {
  78. return t.Format(time.RFC1123Z)
  79. },
  80. "DateFmtShort": func(t time.Time) string {
  81. return t.Format("Jan 02, 2006")
  82. },
  83. "SizeFmt": func(s int64) string {
  84. return base.FileSize(s)
  85. },
  86. "List": List,
  87. "SubStr": func(str string, start, length int) string {
  88. if len(str) == 0 {
  89. return ""
  90. }
  91. end := start + length
  92. if length == -1 {
  93. end = len(str)
  94. }
  95. if len(str) < end {
  96. return str
  97. }
  98. return str[start:end]
  99. },
  100. "EllipsisString": base.EllipsisString,
  101. "DiffTypeToStr": DiffTypeToStr,
  102. "DiffLineTypeToStr": DiffLineTypeToStr,
  103. "Sha1": Sha1,
  104. "ShortSha": base.ShortSha,
  105. "MD5": base.EncodeMD5,
  106. "ActionContent2Commits": ActionContent2Commits,
  107. "PathEscape": url.PathEscape,
  108. "EscapePound": func(str string) string {
  109. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  110. },
  111. "RenderCommitMessage": RenderCommitMessage,
  112. "RenderCommitMessageLink": RenderCommitMessageLink,
  113. "RenderCommitBody": RenderCommitBody,
  114. "IsMultilineCommitMessage": IsMultilineCommitMessage,
  115. "ThemeColorMetaTag": func() string {
  116. return setting.UI.ThemeColorMetaTag
  117. },
  118. "MetaAuthor": func() string {
  119. return setting.UI.Meta.Author
  120. },
  121. "MetaDescription": func() string {
  122. return setting.UI.Meta.Description
  123. },
  124. "MetaKeywords": func() string {
  125. return setting.UI.Meta.Keywords
  126. },
  127. "FilenameIsImage": func(filename string) bool {
  128. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  129. return strings.HasPrefix(mimeType, "image/")
  130. },
  131. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  132. if ec != nil {
  133. def := ec.GetDefinitionForFilename(filename)
  134. if def.TabWidth > 0 {
  135. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  136. }
  137. }
  138. return "tab-size-8"
  139. },
  140. "SubJumpablePath": func(str string) []string {
  141. var path []string
  142. index := strings.LastIndex(str, "/")
  143. if index != -1 && index != len(str) {
  144. path = append(path, str[0:index+1])
  145. path = append(path, str[index+1:])
  146. } else {
  147. path = append(path, str)
  148. }
  149. return path
  150. },
  151. "JsonPrettyPrint": func(in string) string {
  152. var out bytes.Buffer
  153. err := json.Indent(&out, []byte(in), "", " ")
  154. if err != nil {
  155. return ""
  156. }
  157. return out.String()
  158. },
  159. "DisableGitHooks": func() bool {
  160. return setting.DisableGitHooks
  161. },
  162. "TrN": TrN,
  163. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  164. if len(values)%2 != 0 {
  165. return nil, errors.New("invalid dict call")
  166. }
  167. dict := make(map[string]interface{}, len(values)/2)
  168. for i := 0; i < len(values); i += 2 {
  169. key, ok := values[i].(string)
  170. if !ok {
  171. return nil, errors.New("dict keys must be strings")
  172. }
  173. dict[key] = values[i+1]
  174. }
  175. return dict, nil
  176. },
  177. "Printf": fmt.Sprintf,
  178. "Escape": Escape,
  179. "Sec2Time": models.SecToTime,
  180. }}
  181. }
  182. // Safe render raw as HTML
  183. func Safe(raw string) template.HTML {
  184. return template.HTML(raw)
  185. }
  186. // SafeJS renders raw as JS
  187. func SafeJS(raw string) template.JS {
  188. return template.JS(raw)
  189. }
  190. // Str2html render Markdown text to HTML
  191. func Str2html(raw string) template.HTML {
  192. return template.HTML(markup.Sanitize(raw))
  193. }
  194. // Escape escapes a HTML string
  195. func Escape(raw string) string {
  196. return html.EscapeString(raw)
  197. }
  198. // List traversings the list
  199. func List(l *list.List) chan interface{} {
  200. e := l.Front()
  201. c := make(chan interface{})
  202. go func() {
  203. for e != nil {
  204. c <- e.Value
  205. e = e.Next()
  206. }
  207. close(c)
  208. }()
  209. return c
  210. }
  211. // Sha1 returns sha1 sum of string
  212. func Sha1(str string) string {
  213. return base.EncodeSha1(str)
  214. }
  215. // ToUTF8WithErr converts content to UTF8 encoding
  216. func ToUTF8WithErr(content []byte) (string, error) {
  217. charsetLabel, err := base.DetectEncoding(content)
  218. if err != nil {
  219. return "", err
  220. } else if charsetLabel == "UTF-8" {
  221. return string(content), nil
  222. }
  223. encoding, _ := charset.Lookup(charsetLabel)
  224. if encoding == nil {
  225. return string(content), fmt.Errorf("Unknown encoding: %s", charsetLabel)
  226. }
  227. // If there is an error, we concatenate the nicely decoded part and the
  228. // original left over. This way we won't loose data.
  229. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  230. if err != nil {
  231. result = result + string(content[n:])
  232. }
  233. return result, err
  234. }
  235. // ToUTF8 converts content to UTF8 encoding and ignore error
  236. func ToUTF8(content string) string {
  237. res, _ := ToUTF8WithErr([]byte(content))
  238. return res
  239. }
  240. // ReplaceLeft replaces all prefixes 'old' in 's' with 'new'.
  241. func ReplaceLeft(s, old, new string) string {
  242. oldLen, newLen, i, n := len(old), len(new), 0, 0
  243. for ; i < len(s) && strings.HasPrefix(s[i:], old); n++ {
  244. i += oldLen
  245. }
  246. // simple optimization
  247. if n == 0 {
  248. return s
  249. }
  250. // allocating space for the new string
  251. curLen := n*newLen + len(s[i:])
  252. replacement := make([]byte, curLen, curLen)
  253. j := 0
  254. for ; j < n*newLen; j += newLen {
  255. copy(replacement[j:j+newLen], new)
  256. }
  257. copy(replacement[j:], s[i:])
  258. return string(replacement)
  259. }
  260. // RenderCommitMessage renders commit message with XSS-safe and special links.
  261. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  262. return RenderCommitMessageLink(msg, urlPrefix, "", metas)
  263. }
  264. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  265. // default url, handling for special links.
  266. func RenderCommitMessageLink(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  267. cleanMsg := template.HTMLEscapeString(msg)
  268. // we can safely assume that it will not return any error, since there
  269. // shouldn't be any special HTML.
  270. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, urlDefault, metas)
  271. if err != nil {
  272. log.Error(3, "RenderCommitMessage: %v", err)
  273. return ""
  274. }
  275. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  276. if len(msgLines) == 0 {
  277. return template.HTML("")
  278. }
  279. return template.HTML(msgLines[0])
  280. }
  281. // RenderCommitBody extracts the body of a commit message without its title.
  282. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  283. cleanMsg := template.HTMLEscapeString(msg)
  284. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  285. if err != nil {
  286. log.Error(3, "RenderCommitMessage: %v", err)
  287. return ""
  288. }
  289. body := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  290. if len(body) == 0 {
  291. return template.HTML("")
  292. }
  293. return template.HTML(strings.Join(body[1:], "\n"))
  294. }
  295. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  296. func IsMultilineCommitMessage(msg string) bool {
  297. return strings.Count(strings.TrimSpace(msg), "\n") > 1
  298. }
  299. // Actioner describes an action
  300. type Actioner interface {
  301. GetOpType() models.ActionType
  302. GetActUserName() string
  303. GetRepoUserName() string
  304. GetRepoName() string
  305. GetRepoPath() string
  306. GetRepoLink() string
  307. GetBranch() string
  308. GetContent() string
  309. GetCreate() time.Time
  310. GetIssueInfos() []string
  311. }
  312. // ActionIcon accepts an action operation type and returns an icon class name.
  313. func ActionIcon(opType models.ActionType) string {
  314. switch opType {
  315. case models.ActionCreateRepo, models.ActionTransferRepo:
  316. return "repo"
  317. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  318. return "git-commit"
  319. case models.ActionCreateIssue:
  320. return "issue-opened"
  321. case models.ActionCreatePullRequest:
  322. return "git-pull-request"
  323. case models.ActionCommentIssue:
  324. return "comment-discussion"
  325. case models.ActionMergePullRequest:
  326. return "git-merge"
  327. case models.ActionCloseIssue, models.ActionClosePullRequest:
  328. return "issue-closed"
  329. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  330. return "issue-reopened"
  331. default:
  332. return "invalid type"
  333. }
  334. }
  335. // ActionContent2Commits converts action content to push commits
  336. func ActionContent2Commits(act Actioner) *models.PushCommits {
  337. push := models.NewPushCommits()
  338. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  339. log.Error(4, "json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  340. }
  341. return push
  342. }
  343. // DiffTypeToStr returns diff type name
  344. func DiffTypeToStr(diffType int) string {
  345. diffTypes := map[int]string{
  346. 1: "add", 2: "modify", 3: "del", 4: "rename",
  347. }
  348. return diffTypes[diffType]
  349. }
  350. // DiffLineTypeToStr returns diff line type name
  351. func DiffLineTypeToStr(diffType int) string {
  352. switch diffType {
  353. case 2:
  354. return "add"
  355. case 3:
  356. return "del"
  357. case 4:
  358. return "tag"
  359. }
  360. return "same"
  361. }
  362. // Language specific rules for translating plural texts
  363. var trNLangRules = map[string]func(int64) int{
  364. "en-US": func(cnt int64) int {
  365. if cnt == 1 {
  366. return 0
  367. }
  368. return 1
  369. },
  370. "lv-LV": func(cnt int64) int {
  371. if cnt%10 == 1 && cnt%100 != 11 {
  372. return 0
  373. }
  374. return 1
  375. },
  376. "ru-RU": func(cnt int64) int {
  377. if cnt%10 == 1 && cnt%100 != 11 {
  378. return 0
  379. }
  380. return 1
  381. },
  382. "zh-CN": func(cnt int64) int {
  383. return 0
  384. },
  385. "zh-HK": func(cnt int64) int {
  386. return 0
  387. },
  388. "zh-TW": func(cnt int64) int {
  389. return 0
  390. },
  391. }
  392. // TrN returns key to be used for plural text translation
  393. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  394. var c int64
  395. if t, ok := cnt.(int); ok {
  396. c = int64(t)
  397. } else if t, ok := cnt.(int16); ok {
  398. c = int64(t)
  399. } else if t, ok := cnt.(int32); ok {
  400. c = int64(t)
  401. } else if t, ok := cnt.(int64); ok {
  402. c = t
  403. } else {
  404. return keyN
  405. }
  406. ruleFunc, ok := trNLangRules[lang]
  407. if !ok {
  408. ruleFunc = trNLangRules["en-US"]
  409. }
  410. if ruleFunc(c) == 0 {
  411. return key1
  412. }
  413. return keyN
  414. }