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

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