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

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