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 19KB

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