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

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