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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. "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. "contain": func(s []int64, id int64) bool {
  274. for i := 0; i < len(s); i++ {
  275. if s[i] == id {
  276. return true
  277. }
  278. }
  279. return false
  280. },
  281. "svg": func(icon string, size int) template.HTML {
  282. return template.HTML(fmt.Sprintf(`<svg class="svg %s" width="%d" height="%d" aria-hidden="true"><use xlink:href="%s/img/svg/icons.svg#%s" /></svg>`, icon, size, size, setting.StaticURLPrefix, icon))
  283. },
  284. }}
  285. }
  286. // NewTextFuncMap returns functions for injecting to text templates
  287. // It's a subset of those used for HTML and other templates
  288. func NewTextFuncMap() []texttmpl.FuncMap {
  289. return []texttmpl.FuncMap{map[string]interface{}{
  290. "GoVer": func() string {
  291. return strings.Title(runtime.Version())
  292. },
  293. "AppName": func() string {
  294. return setting.AppName
  295. },
  296. "AppSubUrl": func() string {
  297. return setting.AppSubURL
  298. },
  299. "AppUrl": func() string {
  300. return setting.AppURL
  301. },
  302. "AppVer": func() string {
  303. return setting.AppVer
  304. },
  305. "AppBuiltWith": func() string {
  306. return setting.AppBuiltWith
  307. },
  308. "AppDomain": func() string {
  309. return setting.Domain
  310. },
  311. "TimeSince": timeutil.TimeSince,
  312. "TimeSinceUnix": timeutil.TimeSinceUnix,
  313. "RawTimeSince": timeutil.RawTimeSince,
  314. "DateFmtLong": func(t time.Time) string {
  315. return t.Format(time.RFC1123Z)
  316. },
  317. "DateFmtShort": func(t time.Time) string {
  318. return t.Format("Jan 02, 2006")
  319. },
  320. "List": List,
  321. "SubStr": func(str string, start, length int) string {
  322. if len(str) == 0 {
  323. return ""
  324. }
  325. end := start + length
  326. if length == -1 {
  327. end = len(str)
  328. }
  329. if len(str) < end {
  330. return str
  331. }
  332. return str[start:end]
  333. },
  334. "EllipsisString": base.EllipsisString,
  335. "URLJoin": util.URLJoin,
  336. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  337. if len(values)%2 != 0 {
  338. return nil, errors.New("invalid dict call")
  339. }
  340. dict := make(map[string]interface{}, len(values)/2)
  341. for i := 0; i < len(values); i += 2 {
  342. key, ok := values[i].(string)
  343. if !ok {
  344. return nil, errors.New("dict keys must be strings")
  345. }
  346. dict[key] = values[i+1]
  347. }
  348. return dict, nil
  349. },
  350. "Printf": fmt.Sprintf,
  351. "Escape": Escape,
  352. "Sec2Time": models.SecToTime,
  353. "ParseDeadline": func(deadline string) []string {
  354. return strings.Split(deadline, "|")
  355. },
  356. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  357. if len(values) == 0 {
  358. return nil, errors.New("invalid dict call")
  359. }
  360. dict := make(map[string]interface{})
  361. for i := 0; i < len(values); i++ {
  362. switch key := values[i].(type) {
  363. case string:
  364. i++
  365. if i == len(values) {
  366. return nil, errors.New("specify the key for non array values")
  367. }
  368. dict[key] = values[i]
  369. case map[string]interface{}:
  370. m := values[i].(map[string]interface{})
  371. for i, v := range m {
  372. dict[i] = v
  373. }
  374. default:
  375. return nil, errors.New("dict values must be maps")
  376. }
  377. }
  378. return dict, nil
  379. },
  380. "percentage": func(n int, values ...int) float32 {
  381. var sum = 0
  382. for i := 0; i < len(values); i++ {
  383. sum += values[i]
  384. }
  385. return float32(n) * 100 / float32(sum)
  386. },
  387. }}
  388. }
  389. // Safe render raw as HTML
  390. func Safe(raw string) template.HTML {
  391. return template.HTML(raw)
  392. }
  393. // SafeJS renders raw as JS
  394. func SafeJS(raw string) template.JS {
  395. return template.JS(raw)
  396. }
  397. // Str2html render Markdown text to HTML
  398. func Str2html(raw string) template.HTML {
  399. return template.HTML(markup.Sanitize(raw))
  400. }
  401. // Escape escapes a HTML string
  402. func Escape(raw string) string {
  403. return html.EscapeString(raw)
  404. }
  405. // List traversings the list
  406. func List(l *list.List) chan interface{} {
  407. e := l.Front()
  408. c := make(chan interface{})
  409. go func() {
  410. for e != nil {
  411. c <- e.Value
  412. e = e.Next()
  413. }
  414. close(c)
  415. }()
  416. return c
  417. }
  418. // Sha1 returns sha1 sum of string
  419. func Sha1(str string) string {
  420. return base.EncodeSha1(str)
  421. }
  422. // ReplaceLeft replaces all prefixes 'oldS' in 's' with 'newS'.
  423. func ReplaceLeft(s, oldS, newS string) string {
  424. oldLen, newLen, i, n := len(oldS), len(newS), 0, 0
  425. for ; i < len(s) && strings.HasPrefix(s[i:], oldS); n++ {
  426. i += oldLen
  427. }
  428. // simple optimization
  429. if n == 0 {
  430. return s
  431. }
  432. // allocating space for the new string
  433. curLen := n*newLen + len(s[i:])
  434. replacement := make([]byte, curLen)
  435. j := 0
  436. for ; j < n*newLen; j += newLen {
  437. copy(replacement[j:j+newLen], newS)
  438. }
  439. copy(replacement[j:], s[i:])
  440. return string(replacement)
  441. }
  442. // RenderCommitMessage renders commit message with XSS-safe and special links.
  443. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  444. return RenderCommitMessageLink(msg, urlPrefix, "", metas)
  445. }
  446. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  447. // default url, handling for special links.
  448. func RenderCommitMessageLink(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  449. cleanMsg := template.HTMLEscapeString(msg)
  450. // we can safely assume that it will not return any error, since there
  451. // shouldn't be any special HTML.
  452. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, urlDefault, metas)
  453. if err != nil {
  454. log.Error("RenderCommitMessage: %v", err)
  455. return ""
  456. }
  457. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  458. if len(msgLines) == 0 {
  459. return template.HTML("")
  460. }
  461. return template.HTML(msgLines[0])
  462. }
  463. // RenderCommitMessageLinkSubject renders commit message as a XXS-safe link to
  464. // the provided default url, handling for special links without email to links.
  465. func RenderCommitMessageLinkSubject(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  466. msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
  467. lineEnd := strings.IndexByte(msgLine, '\n')
  468. if lineEnd > 0 {
  469. msgLine = msgLine[:lineEnd]
  470. }
  471. msgLine = strings.TrimRightFunc(msgLine, unicode.IsSpace)
  472. if len(msgLine) == 0 {
  473. return template.HTML("")
  474. }
  475. // we can safely assume that it will not return any error, since there
  476. // shouldn't be any special HTML.
  477. renderedMessage, err := markup.RenderCommitMessageSubject([]byte(template.HTMLEscapeString(msgLine)), urlPrefix, urlDefault, metas)
  478. if err != nil {
  479. log.Error("RenderCommitMessageSubject: %v", err)
  480. return template.HTML("")
  481. }
  482. return template.HTML(renderedMessage)
  483. }
  484. // RenderCommitBody extracts the body of a commit message without its title.
  485. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  486. msgLine := strings.TrimRightFunc(msg, unicode.IsSpace)
  487. lineEnd := strings.IndexByte(msgLine, '\n')
  488. if lineEnd > 0 {
  489. msgLine = msgLine[lineEnd+1:]
  490. } else {
  491. return template.HTML("")
  492. }
  493. msgLine = strings.TrimLeftFunc(msgLine, unicode.IsSpace)
  494. if len(msgLine) == 0 {
  495. return template.HTML("")
  496. }
  497. renderedMessage, err := markup.RenderCommitMessage([]byte(template.HTMLEscapeString(msgLine)), urlPrefix, "", metas)
  498. if err != nil {
  499. log.Error("RenderCommitMessage: %v", err)
  500. return ""
  501. }
  502. return template.HTML(renderedMessage)
  503. }
  504. // RenderNote renders the contents of a git-notes file as a commit message.
  505. func RenderNote(msg, urlPrefix string, metas map[string]string) template.HTML {
  506. cleanMsg := template.HTMLEscapeString(msg)
  507. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  508. if err != nil {
  509. log.Error("RenderNote: %v", err)
  510. return ""
  511. }
  512. return template.HTML(string(fullMessage))
  513. }
  514. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  515. func IsMultilineCommitMessage(msg string) bool {
  516. return strings.Count(strings.TrimSpace(msg), "\n") >= 1
  517. }
  518. // Actioner describes an action
  519. type Actioner interface {
  520. GetOpType() models.ActionType
  521. GetActUserName() string
  522. GetRepoUserName() string
  523. GetRepoName() string
  524. GetRepoPath() string
  525. GetRepoLink() string
  526. GetBranch() string
  527. GetContent() string
  528. GetCreate() time.Time
  529. GetIssueInfos() []string
  530. }
  531. // ActionIcon accepts an action operation type and returns an icon class name.
  532. func ActionIcon(opType models.ActionType) string {
  533. switch opType {
  534. case models.ActionCreateRepo, models.ActionTransferRepo:
  535. return "repo"
  536. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  537. return "git-commit"
  538. case models.ActionCreateIssue:
  539. return "issue-opened"
  540. case models.ActionCreatePullRequest:
  541. return "git-pull-request"
  542. case models.ActionCommentIssue, models.ActionCommentPull:
  543. return "comment-discussion"
  544. case models.ActionMergePullRequest:
  545. return "git-merge"
  546. case models.ActionCloseIssue, models.ActionClosePullRequest:
  547. return "issue-closed"
  548. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  549. return "issue-reopened"
  550. case models.ActionMirrorSyncPush, models.ActionMirrorSyncCreate, models.ActionMirrorSyncDelete:
  551. return "repo-clone"
  552. case models.ActionApprovePullRequest:
  553. return "eye"
  554. case models.ActionRejectPullRequest:
  555. return "x"
  556. default:
  557. return "invalid type"
  558. }
  559. }
  560. // ActionContent2Commits converts action content to push commits
  561. func ActionContent2Commits(act Actioner) *repository.PushCommits {
  562. push := repository.NewPushCommits()
  563. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  564. log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  565. }
  566. return push
  567. }
  568. // DiffTypeToStr returns diff type name
  569. func DiffTypeToStr(diffType int) string {
  570. diffTypes := map[int]string{
  571. 1: "add", 2: "modify", 3: "del", 4: "rename",
  572. }
  573. return diffTypes[diffType]
  574. }
  575. // DiffLineTypeToStr returns diff line type name
  576. func DiffLineTypeToStr(diffType int) string {
  577. switch diffType {
  578. case 2:
  579. return "add"
  580. case 3:
  581. return "del"
  582. case 4:
  583. return "tag"
  584. }
  585. return "same"
  586. }
  587. // Language specific rules for translating plural texts
  588. var trNLangRules = map[string]func(int64) int{
  589. "en-US": func(cnt int64) int {
  590. if cnt == 1 {
  591. return 0
  592. }
  593. return 1
  594. },
  595. "lv-LV": func(cnt int64) int {
  596. if cnt%10 == 1 && cnt%100 != 11 {
  597. return 0
  598. }
  599. return 1
  600. },
  601. "ru-RU": func(cnt int64) int {
  602. if cnt%10 == 1 && cnt%100 != 11 {
  603. return 0
  604. }
  605. return 1
  606. },
  607. "zh-CN": func(cnt int64) int {
  608. return 0
  609. },
  610. "zh-HK": func(cnt int64) int {
  611. return 0
  612. },
  613. "zh-TW": func(cnt int64) int {
  614. return 0
  615. },
  616. "fr-FR": func(cnt int64) int {
  617. if cnt > -2 && cnt < 2 {
  618. return 0
  619. }
  620. return 1
  621. },
  622. }
  623. // TrN returns key to be used for plural text translation
  624. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  625. var c int64
  626. if t, ok := cnt.(int); ok {
  627. c = int64(t)
  628. } else if t, ok := cnt.(int16); ok {
  629. c = int64(t)
  630. } else if t, ok := cnt.(int32); ok {
  631. c = int64(t)
  632. } else if t, ok := cnt.(int64); ok {
  633. c = t
  634. } else {
  635. return keyN
  636. }
  637. ruleFunc, ok := trNLangRules[lang]
  638. if !ok {
  639. ruleFunc = trNLangRules["en-US"]
  640. }
  641. if ruleFunc(c) == 0 {
  642. return key1
  643. }
  644. return keyN
  645. }
  646. // MigrationIcon returns a Font Awesome name matching the service an issue/comment was migrated from
  647. func MigrationIcon(hostname string) string {
  648. switch hostname {
  649. case "github.com":
  650. return "fa-github"
  651. default:
  652. return "fa-git-alt"
  653. }
  654. }
  655. func buildSubjectBodyTemplate(stpl *texttmpl.Template, btpl *template.Template, name string, content []byte) {
  656. // Split template into subject and body
  657. var subjectContent []byte
  658. bodyContent := content
  659. loc := mailSubjectSplit.FindIndex(content)
  660. if loc != nil {
  661. subjectContent = content[0:loc[0]]
  662. bodyContent = content[loc[1]:]
  663. }
  664. if _, err := stpl.New(name).
  665. Parse(string(subjectContent)); err != nil {
  666. log.Warn("Failed to parse template [%s/subject]: %v", name, err)
  667. }
  668. if _, err := btpl.New(name).
  669. Parse(string(bodyContent)); err != nil {
  670. log.Warn("Failed to parse template [%s/body]: %v", name, err)
  671. }
  672. }