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

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