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

helper.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package templates
  6. import (
  7. "bytes"
  8. "container/list"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "html"
  13. "html/template"
  14. "mime"
  15. "net/url"
  16. "path/filepath"
  17. "regexp"
  18. "runtime"
  19. "strings"
  20. texttmpl "text/template"
  21. "time"
  22. "unicode"
  23. "code.gitea.io/gitea/models"
  24. "code.gitea.io/gitea/modules/base"
  25. "code.gitea.io/gitea/modules/emoji"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/markup"
  28. "code.gitea.io/gitea/modules/repository"
  29. "code.gitea.io/gitea/modules/setting"
  30. "code.gitea.io/gitea/modules/svg"
  31. "code.gitea.io/gitea/modules/timeutil"
  32. "code.gitea.io/gitea/modules/util"
  33. "code.gitea.io/gitea/services/gitdiff"
  34. mirror_service "code.gitea.io/gitea/services/mirror"
  35. "github.com/editorconfig/editorconfig-core-go/v2"
  36. )
  37. // Used from static.go && dynamic.go
  38. var mailSubjectSplit = regexp.MustCompile(`(?m)^-{3,}[\s]*$`)
  39. // NewFuncMap returns functions for injecting to templates
  40. func NewFuncMap() []template.FuncMap {
  41. return []template.FuncMap{map[string]interface{}{
  42. "GoVer": func() string {
  43. return strings.Title(runtime.Version())
  44. },
  45. "UseHTTPS": func() bool {
  46. return strings.HasPrefix(setting.AppURL, "https")
  47. },
  48. "AppName": func() string {
  49. return setting.AppName
  50. },
  51. "AppSubUrl": func() string {
  52. return setting.AppSubURL
  53. },
  54. "StaticUrlPrefix": func() string {
  55. return setting.StaticURLPrefix
  56. },
  57. "AppUrl": func() string {
  58. return setting.AppURL
  59. },
  60. "AppVer": func() string {
  61. return setting.AppVer
  62. },
  63. "AppBuiltWith": func() string {
  64. return setting.AppBuiltWith
  65. },
  66. "AppDomain": func() string {
  67. return setting.Domain
  68. },
  69. "DisableGravatar": func() bool {
  70. return setting.DisableGravatar
  71. },
  72. "DefaultShowFullName": func() bool {
  73. return setting.UI.DefaultShowFullName
  74. },
  75. "ShowFooterTemplateLoadTime": func() bool {
  76. return setting.ShowFooterTemplateLoadTime
  77. },
  78. "LoadTimes": func(startTime time.Time) string {
  79. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  80. },
  81. "AllowedReactions": func() []string {
  82. return setting.UI.Reactions
  83. },
  84. "AvatarLink": models.AvatarLink,
  85. "Safe": Safe,
  86. "SafeJS": SafeJS,
  87. "Str2html": Str2html,
  88. "TimeSince": timeutil.TimeSince,
  89. "TimeSinceUnix": timeutil.TimeSinceUnix,
  90. "RawTimeSince": timeutil.RawTimeSince,
  91. "FileSize": base.FileSize,
  92. "PrettyNumber": base.PrettyNumber,
  93. "Subtract": base.Subtract,
  94. "EntryIcon": base.EntryIcon,
  95. "MigrationIcon": MigrationIcon,
  96. "Add": func(a ...int) int {
  97. sum := 0
  98. for _, val := range a {
  99. sum += val
  100. }
  101. return sum
  102. },
  103. "Mul": func(a ...int) int {
  104. sum := 1
  105. for _, val := range a {
  106. sum *= val
  107. }
  108. return sum
  109. },
  110. "ActionIcon": ActionIcon,
  111. "DateFmtLong": func(t time.Time) string {
  112. return t.Format(time.RFC1123Z)
  113. },
  114. "DateFmtShort": func(t time.Time) string {
  115. return t.Format("Jan 02, 2006")
  116. },
  117. "SizeFmt": base.FileSize,
  118. "List": List,
  119. "SubStr": func(str string, start, length int) string {
  120. if len(str) == 0 {
  121. return ""
  122. }
  123. end := start + length
  124. if length == -1 {
  125. end = len(str)
  126. }
  127. if len(str) < end {
  128. return str
  129. }
  130. return str[start:end]
  131. },
  132. "EllipsisString": base.EllipsisString,
  133. "DiffTypeToStr": DiffTypeToStr,
  134. "DiffLineTypeToStr": DiffLineTypeToStr,
  135. "Sha1": Sha1,
  136. "ShortSha": base.ShortSha,
  137. "MD5": base.EncodeMD5,
  138. "ActionContent2Commits": ActionContent2Commits,
  139. "PathEscape": url.PathEscape,
  140. "EscapePound": func(str string) string {
  141. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  142. },
  143. "PathEscapeSegments": util.PathEscapeSegments,
  144. "URLJoin": util.URLJoin,
  145. "RenderCommitMessage": RenderCommitMessage,
  146. "RenderCommitMessageLink": RenderCommitMessageLink,
  147. "RenderCommitMessageLinkSubject": RenderCommitMessageLinkSubject,
  148. "RenderCommitBody": RenderCommitBody,
  149. "RenderEmoji": RenderEmoji,
  150. "RenderEmojiPlain": emoji.ReplaceAliases,
  151. "ReactionToEmoji": ReactionToEmoji,
  152. "RenderNote": RenderNote,
  153. "IsMultilineCommitMessage": IsMultilineCommitMessage,
  154. "ThemeColorMetaTag": func() string {
  155. return setting.UI.ThemeColorMetaTag
  156. },
  157. "MetaAuthor": func() string {
  158. return setting.UI.Meta.Author
  159. },
  160. "MetaDescription": func() string {
  161. return setting.UI.Meta.Description
  162. },
  163. "MetaKeywords": func() string {
  164. return setting.UI.Meta.Keywords
  165. },
  166. "UseServiceWorker": func() bool {
  167. return setting.UI.UseServiceWorker
  168. },
  169. "FilenameIsImage": func(filename string) bool {
  170. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  171. return strings.HasPrefix(mimeType, "image/")
  172. },
  173. "TabSizeClass": func(ec interface{}, filename string) string {
  174. var (
  175. value *editorconfig.Editorconfig
  176. ok bool
  177. )
  178. if ec != nil {
  179. if value, ok = ec.(*editorconfig.Editorconfig); !ok || value == nil {
  180. return "tab-size-8"
  181. }
  182. def, err := value.GetDefinitionForFilename(filename)
  183. if err != nil {
  184. log.Error("tab size class: getting definition for filename: %v", err)
  185. return "tab-size-8"
  186. }
  187. if def.TabWidth > 0 {
  188. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  189. }
  190. }
  191. return "tab-size-8"
  192. },
  193. "SubJumpablePath": func(str string) []string {
  194. var path []string
  195. index := strings.LastIndex(str, "/")
  196. if index != -1 && index != len(str) {
  197. path = append(path, str[0:index+1], str[index+1:])
  198. } else {
  199. path = append(path, str)
  200. }
  201. return path
  202. },
  203. "Json": func(in interface{}) string {
  204. out, err := json.Marshal(in)
  205. if err != nil {
  206. return ""
  207. }
  208. return string(out)
  209. },
  210. "JsonPrettyPrint": func(in string) string {
  211. var out bytes.Buffer
  212. err := json.Indent(&out, []byte(in), "", " ")
  213. if err != nil {
  214. return ""
  215. }
  216. return out.String()
  217. },
  218. "DisableGitHooks": func() bool {
  219. return setting.DisableGitHooks
  220. },
  221. "DisableImportLocal": func() bool {
  222. return !setting.ImportLocalPaths
  223. },
  224. "TrN": TrN,
  225. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  226. if len(values)%2 != 0 {
  227. return nil, errors.New("invalid dict call")
  228. }
  229. dict := make(map[string]interface{}, len(values)/2)
  230. for i := 0; i < len(values); i += 2 {
  231. key, ok := values[i].(string)
  232. if !ok {
  233. return nil, errors.New("dict keys must be strings")
  234. }
  235. dict[key] = values[i+1]
  236. }
  237. return dict, nil
  238. },
  239. "Printf": fmt.Sprintf,
  240. "Escape": Escape,
  241. "Sec2Time": models.SecToTime,
  242. "ParseDeadline": func(deadline string) []string {
  243. return strings.Split(deadline, "|")
  244. },
  245. "DefaultTheme": func() string {
  246. return setting.UI.DefaultTheme
  247. },
  248. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  249. if len(values) == 0 {
  250. return nil, errors.New("invalid dict call")
  251. }
  252. dict := make(map[string]interface{})
  253. for i := 0; i < len(values); i++ {
  254. switch key := values[i].(type) {
  255. case string:
  256. i++
  257. if i == len(values) {
  258. return nil, errors.New("specify the key for non array values")
  259. }
  260. dict[key] = values[i]
  261. case map[string]interface{}:
  262. m := values[i].(map[string]interface{})
  263. for i, v := range m {
  264. dict[i] = v
  265. }
  266. default:
  267. return nil, errors.New("dict values must be maps")
  268. }
  269. }
  270. return dict, nil
  271. },
  272. "percentage": func(n int, values ...int) float32 {
  273. var sum = 0
  274. for i := 0; i < len(values); i++ {
  275. sum += values[i]
  276. }
  277. return float32(n) * 100 / float32(sum)
  278. },
  279. "CommentMustAsDiff": gitdiff.CommentMustAsDiff,
  280. "MirrorAddress": mirror_service.Address,
  281. "MirrorFullAddress": mirror_service.AddressNoCredentials,
  282. "MirrorUserName": mirror_service.Username,
  283. "MirrorPassword": mirror_service.Password,
  284. "CommitType": func(commit interface{}) string {
  285. switch commit.(type) {
  286. case models.SignCommitWithStatuses:
  287. return "SignCommitWithStatuses"
  288. case models.SignCommit:
  289. return "SignCommit"
  290. case models.UserCommit:
  291. return "UserCommit"
  292. default:
  293. return ""
  294. }
  295. },
  296. "NotificationSettings": func() map[string]interface{} {
  297. return map[string]interface{}{
  298. "MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond),
  299. "TimeoutStep": int(setting.UI.Notification.TimeoutStep / time.Millisecond),
  300. "MaxTimeout": int(setting.UI.Notification.MaxTimeout / time.Millisecond),
  301. "EventSourceUpdateTime": int(setting.UI.Notification.EventSourceUpdateTime / time.Millisecond),
  302. }
  303. },
  304. "contain": func(s []int64, id int64) bool {
  305. for i := 0; i < len(s); i++ {
  306. if s[i] == id {
  307. return true
  308. }
  309. }
  310. return false
  311. },
  312. "svg": SVG,
  313. "SortArrow": func(normSort, revSort, urlSort string, isDefault bool) template.HTML {
  314. // if needed
  315. if len(normSort) == 0 || len(urlSort) == 0 {
  316. return ""
  317. }
  318. if len(urlSort) == 0 && isDefault {
  319. // if sort is sorted as default add arrow tho this table header
  320. if isDefault {
  321. return SVG("octicon-triangle-down", 16)
  322. }
  323. } else {
  324. // if sort arg is in url test if it correlates with column header sort arguments
  325. if urlSort == normSort {
  326. // the table is sorted with this header normal
  327. return SVG("octicon-triangle-down", 16)
  328. } else if urlSort == revSort {
  329. // the table is sorted with this header reverse
  330. return SVG("octicon-triangle-up", 16)
  331. }
  332. }
  333. // the table is NOT sorted with this header
  334. return ""
  335. },
  336. }}
  337. }
  338. // NewTextFuncMap returns functions for injecting to text templates
  339. // It's a subset of those used for HTML and other templates
  340. func NewTextFuncMap() []texttmpl.FuncMap {
  341. return []texttmpl.FuncMap{map[string]interface{}{
  342. "GoVer": func() string {
  343. return strings.Title(runtime.Version())
  344. },
  345. "AppName": func() string {
  346. return setting.AppName
  347. },
  348. "AppSubUrl": func() string {
  349. return setting.AppSubURL
  350. },
  351. "AppUrl": func() string {
  352. return setting.AppURL
  353. },
  354. "AppVer": func() string {
  355. return setting.AppVer
  356. },
  357. "AppBuiltWith": func() string {
  358. return setting.AppBuiltWith
  359. },
  360. "AppDomain": func() string {
  361. return setting.Domain
  362. },
  363. "TimeSince": timeutil.TimeSince,
  364. "TimeSinceUnix": timeutil.TimeSinceUnix,
  365. "RawTimeSince": timeutil.RawTimeSince,
  366. "DateFmtLong": func(t time.Time) string {
  367. return t.Format(time.RFC1123Z)
  368. },
  369. "DateFmtShort": func(t time.Time) string {
  370. return t.Format("Jan 02, 2006")
  371. },
  372. "List": List,
  373. "SubStr": func(str string, start, length int) string {
  374. if len(str) == 0 {
  375. return ""
  376. }
  377. end := start + length
  378. if length == -1 {
  379. end = len(str)
  380. }
  381. if len(str) < end {
  382. return str
  383. }
  384. return str[start:end]
  385. },
  386. "EllipsisString": base.EllipsisString,
  387. "URLJoin": util.URLJoin,
  388. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  389. if len(values)%2 != 0 {
  390. return nil, errors.New("invalid dict call")
  391. }
  392. dict := make(map[string]interface{}, len(values)/2)
  393. for i := 0; i < len(values); i += 2 {
  394. key, ok := values[i].(string)
  395. if !ok {
  396. return nil, errors.New("dict keys must be strings")
  397. }
  398. dict[key] = values[i+1]
  399. }
  400. return dict, nil
  401. },
  402. "Printf": fmt.Sprintf,
  403. "Escape": Escape,
  404. "Sec2Time": models.SecToTime,
  405. "ParseDeadline": func(deadline string) []string {
  406. return strings.Split(deadline, "|")
  407. },
  408. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  409. if len(values) == 0 {
  410. return nil, errors.New("invalid dict call")
  411. }
  412. dict := make(map[string]interface{})
  413. for i := 0; i < len(values); i++ {
  414. switch key := values[i].(type) {
  415. case string:
  416. i++
  417. if i == len(values) {
  418. return nil, errors.New("specify the key for non array values")
  419. }
  420. dict[key] = values[i]
  421. case map[string]interface{}:
  422. m := values[i].(map[string]interface{})
  423. for i, v := range m {
  424. dict[i] = v
  425. }
  426. default:
  427. return nil, errors.New("dict values must be maps")
  428. }
  429. }
  430. return dict, nil
  431. },
  432. "percentage": func(n int, values ...int) float32 {
  433. var sum = 0
  434. for i := 0; i < len(values); i++ {
  435. sum += values[i]
  436. }
  437. return float32(n) * 100 / float32(sum)
  438. },
  439. "Add": func(a ...int) int {
  440. sum := 0
  441. for _, val := range a {
  442. sum += val
  443. }
  444. return sum
  445. },
  446. "Mul": func(a ...int) int {
  447. sum := 1
  448. for _, val := range a {
  449. sum *= val
  450. }
  451. return sum
  452. },
  453. }}
  454. }
  455. var widthRe = regexp.MustCompile(`width="[0-9]+?"`)
  456. var heightRe = regexp.MustCompile(`height="[0-9]+?"`)
  457. // SVG render icons - arguments icon name (string), size (int), class (string)
  458. func SVG(icon string, others ...interface{}) template.HTML {
  459. var size = others[0].(int)
  460. class := ""
  461. if len(others) > 1 && others[1].(string) != "" {
  462. class = others[1].(string)
  463. }
  464. if svgStr, ok := svg.SVGs[icon]; ok {
  465. if size != 16 {
  466. svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size))
  467. svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size))
  468. }
  469. if class != "" {
  470. svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1)
  471. }
  472. return template.HTML(svgStr)
  473. }
  474. return template.HTML("")
  475. }
  476. // Safe render raw as HTML
  477. func Safe(raw string) template.HTML {
  478. return template.HTML(raw)
  479. }
  480. // SafeJS renders raw as JS
  481. func SafeJS(raw string) template.JS {
  482. return template.JS(raw)
  483. }
  484. // Str2html render Markdown text to HTML
  485. func Str2html(raw string) template.HTML {
  486. return template.HTML(markup.Sanitize(raw))
  487. }
  488. // Escape escapes a HTML string
  489. func Escape(raw string) string {
  490. return html.EscapeString(raw)
  491. }
  492. // List traversings the list
  493. func List(l *list.List) chan interface{} {
  494. e := l.Front()
  495. c := make(chan interface{})
  496. go func() {
  497. for e != nil {
  498. c <- e.Value
  499. e = e.Next()
  500. }
  501. close(c)
  502. }()
  503. return c
  504. }
  505. // Sha1 returns sha1 sum of string
  506. func Sha1(str string) string {
  507. return base.EncodeSha1(str)
  508. }
  509. // RenderCommitMessage renders commit message with XSS-safe and special links.
  510. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  511. return RenderCommitMessageLink(msg, urlPrefix, "", metas)
  512. }
  513. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  514. // default url, handling for special links.
  515. func RenderCommitMessageLink(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  516. cleanMsg := template.HTMLEscapeString(msg)
  517. // we can safely assume that it will not return any error, since there
  518. // shouldn't be any special HTML.
  519. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, urlDefault, metas)
  520. if err != nil {
  521. log.Error("RenderCommitMessage: %v", err)
  522. return ""
  523. }
  524. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  525. if len(msgLines) == 0 {
  526. return template.HTML("")
  527. }
  528. return template.HTML(msgLines[0])
  529. }
  530. // RenderCommitMessageLinkSubject renders commit message as a XXS-safe link to
  531. // the provided default url, handling for special links without email to links.
  532. func RenderCommitMessageLinkSubject(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  533. msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
  534. lineEnd := strings.IndexByte(msgLine, '\n')
  535. if lineEnd > 0 {
  536. msgLine = msgLine[:lineEnd]
  537. }
  538. msgLine = strings.TrimRightFunc(msgLine, unicode.IsSpace)
  539. if len(msgLine) == 0 {
  540. return template.HTML("")
  541. }
  542. // we can safely assume that it will not return any error, since there
  543. // shouldn't be any special HTML.
  544. renderedMessage, err := markup.RenderCommitMessageSubject([]byte(template.HTMLEscapeString(msgLine)), urlPrefix, urlDefault, metas)
  545. if err != nil {
  546. log.Error("RenderCommitMessageSubject: %v", err)
  547. return template.HTML("")
  548. }
  549. return template.HTML(renderedMessage)
  550. }
  551. // RenderCommitBody extracts the body of a commit message without its title.
  552. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  553. msgLine := strings.TrimRightFunc(msg, unicode.IsSpace)
  554. lineEnd := strings.IndexByte(msgLine, '\n')
  555. if lineEnd > 0 {
  556. msgLine = msgLine[lineEnd+1:]
  557. } else {
  558. return template.HTML("")
  559. }
  560. msgLine = strings.TrimLeftFunc(msgLine, unicode.IsSpace)
  561. if len(msgLine) == 0 {
  562. return template.HTML("")
  563. }
  564. renderedMessage, err := markup.RenderCommitMessage([]byte(template.HTMLEscapeString(msgLine)), urlPrefix, "", metas)
  565. if err != nil {
  566. log.Error("RenderCommitMessage: %v", err)
  567. return ""
  568. }
  569. return template.HTML(renderedMessage)
  570. }
  571. // RenderEmoji renders html text with emoji post processors
  572. func RenderEmoji(text string) template.HTML {
  573. renderedText, err := markup.RenderEmoji([]byte(template.HTMLEscapeString(text)))
  574. if err != nil {
  575. log.Error("RenderEmoji: %v", err)
  576. return template.HTML("")
  577. }
  578. return template.HTML(renderedText)
  579. }
  580. //ReactionToEmoji renders emoji for use in reactions
  581. func ReactionToEmoji(reaction string) template.HTML {
  582. val := emoji.FromCode(reaction)
  583. if val != nil {
  584. return template.HTML(val.Emoji)
  585. }
  586. val = emoji.FromAlias(reaction)
  587. if val != nil {
  588. return template.HTML(val.Emoji)
  589. }
  590. return template.HTML(fmt.Sprintf(`<img alt=":%s:" src="%s/img/emoji/%s.png"></img>`, reaction, setting.StaticURLPrefix, reaction))
  591. }
  592. // RenderNote renders the contents of a git-notes file as a commit message.
  593. func RenderNote(msg, urlPrefix string, metas map[string]string) template.HTML {
  594. cleanMsg := template.HTMLEscapeString(msg)
  595. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  596. if err != nil {
  597. log.Error("RenderNote: %v", err)
  598. return ""
  599. }
  600. return template.HTML(string(fullMessage))
  601. }
  602. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  603. func IsMultilineCommitMessage(msg string) bool {
  604. return strings.Count(strings.TrimSpace(msg), "\n") >= 1
  605. }
  606. // Actioner describes an action
  607. type Actioner interface {
  608. GetOpType() models.ActionType
  609. GetActUserName() string
  610. GetRepoUserName() string
  611. GetRepoName() string
  612. GetRepoPath() string
  613. GetRepoLink() string
  614. GetBranch() string
  615. GetContent() string
  616. GetCreate() time.Time
  617. GetIssueInfos() []string
  618. }
  619. // ActionIcon accepts an action operation type and returns an icon class name.
  620. func ActionIcon(opType models.ActionType) string {
  621. switch opType {
  622. case models.ActionCreateRepo, models.ActionTransferRepo:
  623. return "repo"
  624. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  625. return "git-commit"
  626. case models.ActionCreateIssue:
  627. return "issue-opened"
  628. case models.ActionCreatePullRequest:
  629. return "git-pull-request"
  630. case models.ActionCommentIssue, models.ActionCommentPull:
  631. return "comment-discussion"
  632. case models.ActionMergePullRequest:
  633. return "git-merge"
  634. case models.ActionCloseIssue, models.ActionClosePullRequest:
  635. return "issue-closed"
  636. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  637. return "issue-reopened"
  638. case models.ActionMirrorSyncPush, models.ActionMirrorSyncCreate, models.ActionMirrorSyncDelete:
  639. return "repo-clone"
  640. case models.ActionApprovePullRequest:
  641. return "check"
  642. case models.ActionRejectPullRequest:
  643. return "diff"
  644. case models.ActionPublishRelease:
  645. return "tag"
  646. default:
  647. return "question"
  648. }
  649. }
  650. // ActionContent2Commits converts action content to push commits
  651. func ActionContent2Commits(act Actioner) *repository.PushCommits {
  652. push := repository.NewPushCommits()
  653. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  654. log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  655. }
  656. return push
  657. }
  658. // DiffTypeToStr returns diff type name
  659. func DiffTypeToStr(diffType int) string {
  660. diffTypes := map[int]string{
  661. 1: "add", 2: "modify", 3: "del", 4: "rename",
  662. }
  663. return diffTypes[diffType]
  664. }
  665. // DiffLineTypeToStr returns diff line type name
  666. func DiffLineTypeToStr(diffType int) string {
  667. switch diffType {
  668. case 2:
  669. return "add"
  670. case 3:
  671. return "del"
  672. case 4:
  673. return "tag"
  674. }
  675. return "same"
  676. }
  677. // Language specific rules for translating plural texts
  678. var trNLangRules = map[string]func(int64) int{
  679. "en-US": func(cnt int64) int {
  680. if cnt == 1 {
  681. return 0
  682. }
  683. return 1
  684. },
  685. "lv-LV": func(cnt int64) int {
  686. if cnt%10 == 1 && cnt%100 != 11 {
  687. return 0
  688. }
  689. return 1
  690. },
  691. "ru-RU": func(cnt int64) int {
  692. if cnt%10 == 1 && cnt%100 != 11 {
  693. return 0
  694. }
  695. return 1
  696. },
  697. "zh-CN": func(cnt int64) int {
  698. return 0
  699. },
  700. "zh-HK": func(cnt int64) int {
  701. return 0
  702. },
  703. "zh-TW": func(cnt int64) int {
  704. return 0
  705. },
  706. "fr-FR": func(cnt int64) int {
  707. if cnt > -2 && cnt < 2 {
  708. return 0
  709. }
  710. return 1
  711. },
  712. }
  713. // TrN returns key to be used for plural text translation
  714. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  715. var c int64
  716. if t, ok := cnt.(int); ok {
  717. c = int64(t)
  718. } else if t, ok := cnt.(int16); ok {
  719. c = int64(t)
  720. } else if t, ok := cnt.(int32); ok {
  721. c = int64(t)
  722. } else if t, ok := cnt.(int64); ok {
  723. c = t
  724. } else {
  725. return keyN
  726. }
  727. ruleFunc, ok := trNLangRules[lang]
  728. if !ok {
  729. ruleFunc = trNLangRules["en-US"]
  730. }
  731. if ruleFunc(c) == 0 {
  732. return key1
  733. }
  734. return keyN
  735. }
  736. // MigrationIcon returns a Font Awesome name matching the service an issue/comment was migrated from
  737. func MigrationIcon(hostname string) string {
  738. switch hostname {
  739. case "github.com":
  740. return "fa-github"
  741. default:
  742. return "fa-git-alt"
  743. }
  744. }
  745. func buildSubjectBodyTemplate(stpl *texttmpl.Template, btpl *template.Template, name string, content []byte) {
  746. // Split template into subject and body
  747. var subjectContent []byte
  748. bodyContent := content
  749. loc := mailSubjectSplit.FindIndex(content)
  750. if loc != nil {
  751. subjectContent = content[0:loc[0]]
  752. bodyContent = content[loc[1]:]
  753. }
  754. if _, err := stpl.New(name).
  755. Parse(string(subjectContent)); err != nil {
  756. log.Warn("Failed to parse template [%s/subject]: %v", name, err)
  757. }
  758. if _, err := btpl.New(name).
  759. Parse(string(bodyContent)); err != nil {
  760. log.Warn("Failed to parse template [%s/body]: %v", name, err)
  761. }
  762. }