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

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
5 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. "runtime"
  18. "strings"
  19. "time"
  20. "code.gitea.io/gitea/models"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/markup"
  24. "code.gitea.io/gitea/modules/setting"
  25. "code.gitea.io/gitea/modules/timeutil"
  26. "code.gitea.io/gitea/modules/util"
  27. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  28. )
  29. // NewFuncMap returns functions for injecting to templates
  30. func NewFuncMap() []template.FuncMap {
  31. return []template.FuncMap{map[string]interface{}{
  32. "GoVer": func() string {
  33. return strings.Title(runtime.Version())
  34. },
  35. "UseHTTPS": func() bool {
  36. return strings.HasPrefix(setting.AppURL, "https")
  37. },
  38. "AppName": func() string {
  39. return setting.AppName
  40. },
  41. "AppSubUrl": func() string {
  42. return setting.AppSubURL
  43. },
  44. "AppUrl": func() string {
  45. return setting.AppURL
  46. },
  47. "AppVer": func() string {
  48. return setting.AppVer
  49. },
  50. "AppBuiltWith": func() string {
  51. return setting.AppBuiltWith
  52. },
  53. "AppDomain": func() string {
  54. return setting.Domain
  55. },
  56. "DisableGravatar": func() bool {
  57. return setting.DisableGravatar
  58. },
  59. "DefaultShowFullName": func() bool {
  60. return setting.UI.DefaultShowFullName
  61. },
  62. "ShowFooterTemplateLoadTime": func() bool {
  63. return setting.ShowFooterTemplateLoadTime
  64. },
  65. "LoadTimes": func(startTime time.Time) string {
  66. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  67. },
  68. "AvatarLink": base.AvatarLink,
  69. "Safe": Safe,
  70. "SafeJS": SafeJS,
  71. "Str2html": Str2html,
  72. "TimeSince": timeutil.TimeSince,
  73. "TimeSinceUnix": timeutil.TimeSinceUnix,
  74. "RawTimeSince": timeutil.RawTimeSince,
  75. "FileSize": base.FileSize,
  76. "Subtract": base.Subtract,
  77. "EntryIcon": base.EntryIcon,
  78. "MigrationIcon": MigrationIcon,
  79. "Add": func(a, b int) int {
  80. return a + b
  81. },
  82. "ActionIcon": ActionIcon,
  83. "DateFmtLong": func(t time.Time) string {
  84. return t.Format(time.RFC1123Z)
  85. },
  86. "DateFmtShort": func(t time.Time) string {
  87. return t.Format("Jan 02, 2006")
  88. },
  89. "SizeFmt": base.FileSize,
  90. "List": List,
  91. "SubStr": func(str string, start, length int) string {
  92. if len(str) == 0 {
  93. return ""
  94. }
  95. end := start + length
  96. if length == -1 {
  97. end = len(str)
  98. }
  99. if len(str) < end {
  100. return str
  101. }
  102. return str[start:end]
  103. },
  104. "EllipsisString": base.EllipsisString,
  105. "DiffTypeToStr": DiffTypeToStr,
  106. "DiffLineTypeToStr": DiffLineTypeToStr,
  107. "Sha1": Sha1,
  108. "ShortSha": base.ShortSha,
  109. "MD5": base.EncodeMD5,
  110. "ActionContent2Commits": ActionContent2Commits,
  111. "PathEscape": url.PathEscape,
  112. "EscapePound": func(str string) string {
  113. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  114. },
  115. "PathEscapeSegments": util.PathEscapeSegments,
  116. "URLJoin": util.URLJoin,
  117. "RenderCommitMessage": RenderCommitMessage,
  118. "RenderCommitMessageLink": RenderCommitMessageLink,
  119. "RenderCommitBody": RenderCommitBody,
  120. "RenderNote": RenderNote,
  121. "IsMultilineCommitMessage": IsMultilineCommitMessage,
  122. "ThemeColorMetaTag": func() string {
  123. return setting.UI.ThemeColorMetaTag
  124. },
  125. "MetaAuthor": func() string {
  126. return setting.UI.Meta.Author
  127. },
  128. "MetaDescription": func() string {
  129. return setting.UI.Meta.Description
  130. },
  131. "MetaKeywords": func() string {
  132. return setting.UI.Meta.Keywords
  133. },
  134. "FilenameIsImage": func(filename string) bool {
  135. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  136. return strings.HasPrefix(mimeType, "image/")
  137. },
  138. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  139. if ec != nil {
  140. def := ec.GetDefinitionForFilename(filename)
  141. if def.TabWidth > 0 {
  142. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  143. }
  144. }
  145. return "tab-size-8"
  146. },
  147. "SubJumpablePath": func(str string) []string {
  148. var path []string
  149. index := strings.LastIndex(str, "/")
  150. if index != -1 && index != len(str) {
  151. path = append(path, str[0:index+1], str[index+1:])
  152. } else {
  153. path = append(path, str)
  154. }
  155. return path
  156. },
  157. "JsonPrettyPrint": func(in string) string {
  158. var out bytes.Buffer
  159. err := json.Indent(&out, []byte(in), "", " ")
  160. if err != nil {
  161. return ""
  162. }
  163. return out.String()
  164. },
  165. "DisableGitHooks": func() bool {
  166. return setting.DisableGitHooks
  167. },
  168. "DisableImportLocal": func() bool {
  169. return !setting.ImportLocalPaths
  170. },
  171. "TrN": TrN,
  172. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  173. if len(values)%2 != 0 {
  174. return nil, errors.New("invalid dict call")
  175. }
  176. dict := make(map[string]interface{}, len(values)/2)
  177. for i := 0; i < len(values); i += 2 {
  178. key, ok := values[i].(string)
  179. if !ok {
  180. return nil, errors.New("dict keys must be strings")
  181. }
  182. dict[key] = values[i+1]
  183. }
  184. return dict, nil
  185. },
  186. "Printf": fmt.Sprintf,
  187. "Escape": Escape,
  188. "Sec2Time": models.SecToTime,
  189. "ParseDeadline": func(deadline string) []string {
  190. return strings.Split(deadline, "|")
  191. },
  192. "DefaultTheme": func() string {
  193. return setting.UI.DefaultTheme
  194. },
  195. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  196. if len(values) == 0 {
  197. return nil, errors.New("invalid dict call")
  198. }
  199. dict := make(map[string]interface{})
  200. for i := 0; i < len(values); i++ {
  201. switch key := values[i].(type) {
  202. case string:
  203. i++
  204. if i == len(values) {
  205. return nil, errors.New("specify the key for non array values")
  206. }
  207. dict[key] = values[i]
  208. case map[string]interface{}:
  209. m := values[i].(map[string]interface{})
  210. for i, v := range m {
  211. dict[i] = v
  212. }
  213. default:
  214. return nil, errors.New("dict values must be maps")
  215. }
  216. }
  217. return dict, nil
  218. },
  219. "percentage": func(n int, values ...int) float32 {
  220. var sum = 0
  221. for i := 0; i < len(values); i++ {
  222. sum += values[i]
  223. }
  224. return float32(n) * 100 / float32(sum)
  225. },
  226. }}
  227. }
  228. // Safe render raw as HTML
  229. func Safe(raw string) template.HTML {
  230. return template.HTML(raw)
  231. }
  232. // SafeJS renders raw as JS
  233. func SafeJS(raw string) template.JS {
  234. return template.JS(raw)
  235. }
  236. // Str2html render Markdown text to HTML
  237. func Str2html(raw string) template.HTML {
  238. return template.HTML(markup.Sanitize(raw))
  239. }
  240. // Escape escapes a HTML string
  241. func Escape(raw string) string {
  242. return html.EscapeString(raw)
  243. }
  244. // List traversings the list
  245. func List(l *list.List) chan interface{} {
  246. e := l.Front()
  247. c := make(chan interface{})
  248. go func() {
  249. for e != nil {
  250. c <- e.Value
  251. e = e.Next()
  252. }
  253. close(c)
  254. }()
  255. return c
  256. }
  257. // Sha1 returns sha1 sum of string
  258. func Sha1(str string) string {
  259. return base.EncodeSha1(str)
  260. }
  261. // ReplaceLeft replaces all prefixes 'oldS' in 's' with 'newS'.
  262. func ReplaceLeft(s, oldS, newS string) string {
  263. oldLen, newLen, i, n := len(oldS), len(newS), 0, 0
  264. for ; i < len(s) && strings.HasPrefix(s[i:], oldS); n++ {
  265. i += oldLen
  266. }
  267. // simple optimization
  268. if n == 0 {
  269. return s
  270. }
  271. // allocating space for the new string
  272. curLen := n*newLen + len(s[i:])
  273. replacement := make([]byte, curLen)
  274. j := 0
  275. for ; j < n*newLen; j += newLen {
  276. copy(replacement[j:j+newLen], newS)
  277. }
  278. copy(replacement[j:], s[i:])
  279. return string(replacement)
  280. }
  281. // RenderCommitMessage renders commit message with XSS-safe and special links.
  282. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  283. return RenderCommitMessageLink(msg, urlPrefix, "", metas)
  284. }
  285. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  286. // default url, handling for special links.
  287. func RenderCommitMessageLink(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  288. cleanMsg := template.HTMLEscapeString(msg)
  289. // we can safely assume that it will not return any error, since there
  290. // shouldn't be any special HTML.
  291. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, urlDefault, metas)
  292. if err != nil {
  293. log.Error("RenderCommitMessage: %v", err)
  294. return ""
  295. }
  296. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  297. if len(msgLines) == 0 {
  298. return template.HTML("")
  299. }
  300. return template.HTML(msgLines[0])
  301. }
  302. // RenderCommitBody extracts the body of a commit message without its title.
  303. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  304. cleanMsg := template.HTMLEscapeString(msg)
  305. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  306. if err != nil {
  307. log.Error("RenderCommitMessage: %v", err)
  308. return ""
  309. }
  310. body := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  311. if len(body) == 0 {
  312. return template.HTML("")
  313. }
  314. return template.HTML(strings.Join(body[1:], "\n"))
  315. }
  316. // RenderNote renders the contents of a git-notes file as a commit message.
  317. func RenderNote(msg, urlPrefix string, metas map[string]string) template.HTML {
  318. cleanMsg := template.HTMLEscapeString(msg)
  319. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  320. if err != nil {
  321. log.Error("RenderNote: %v", err)
  322. return ""
  323. }
  324. return template.HTML(string(fullMessage))
  325. }
  326. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  327. func IsMultilineCommitMessage(msg string) bool {
  328. return strings.Count(strings.TrimSpace(msg), "\n") >= 1
  329. }
  330. // Actioner describes an action
  331. type Actioner interface {
  332. GetOpType() models.ActionType
  333. GetActUserName() string
  334. GetRepoUserName() string
  335. GetRepoName() string
  336. GetRepoPath() string
  337. GetRepoLink() string
  338. GetBranch() string
  339. GetContent() string
  340. GetCreate() time.Time
  341. GetIssueInfos() []string
  342. }
  343. // ActionIcon accepts an action operation type and returns an icon class name.
  344. func ActionIcon(opType models.ActionType) string {
  345. switch opType {
  346. case models.ActionCreateRepo, models.ActionTransferRepo:
  347. return "repo"
  348. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  349. return "git-commit"
  350. case models.ActionCreateIssue:
  351. return "issue-opened"
  352. case models.ActionCreatePullRequest:
  353. return "git-pull-request"
  354. case models.ActionCommentIssue:
  355. return "comment-discussion"
  356. case models.ActionMergePullRequest:
  357. return "git-merge"
  358. case models.ActionCloseIssue, models.ActionClosePullRequest:
  359. return "issue-closed"
  360. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  361. return "issue-reopened"
  362. case models.ActionMirrorSyncPush, models.ActionMirrorSyncCreate, models.ActionMirrorSyncDelete:
  363. return "repo-clone"
  364. default:
  365. return "invalid type"
  366. }
  367. }
  368. // ActionContent2Commits converts action content to push commits
  369. func ActionContent2Commits(act Actioner) *models.PushCommits {
  370. push := models.NewPushCommits()
  371. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  372. log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  373. }
  374. return push
  375. }
  376. // DiffTypeToStr returns diff type name
  377. func DiffTypeToStr(diffType int) string {
  378. diffTypes := map[int]string{
  379. 1: "add", 2: "modify", 3: "del", 4: "rename",
  380. }
  381. return diffTypes[diffType]
  382. }
  383. // DiffLineTypeToStr returns diff line type name
  384. func DiffLineTypeToStr(diffType int) string {
  385. switch diffType {
  386. case 2:
  387. return "add"
  388. case 3:
  389. return "del"
  390. case 4:
  391. return "tag"
  392. }
  393. return "same"
  394. }
  395. // Language specific rules for translating plural texts
  396. var trNLangRules = map[string]func(int64) int{
  397. "en-US": func(cnt int64) int {
  398. if cnt == 1 {
  399. return 0
  400. }
  401. return 1
  402. },
  403. "lv-LV": func(cnt int64) int {
  404. if cnt%10 == 1 && cnt%100 != 11 {
  405. return 0
  406. }
  407. return 1
  408. },
  409. "ru-RU": func(cnt int64) int {
  410. if cnt%10 == 1 && cnt%100 != 11 {
  411. return 0
  412. }
  413. return 1
  414. },
  415. "zh-CN": func(cnt int64) int {
  416. return 0
  417. },
  418. "zh-HK": func(cnt int64) int {
  419. return 0
  420. },
  421. "zh-TW": func(cnt int64) int {
  422. return 0
  423. },
  424. "fr-FR": func(cnt int64) int {
  425. if cnt > -2 && cnt < 2 {
  426. return 0
  427. }
  428. return 1
  429. },
  430. }
  431. // TrN returns key to be used for plural text translation
  432. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  433. var c int64
  434. if t, ok := cnt.(int); ok {
  435. c = int64(t)
  436. } else if t, ok := cnt.(int16); ok {
  437. c = int64(t)
  438. } else if t, ok := cnt.(int32); ok {
  439. c = int64(t)
  440. } else if t, ok := cnt.(int64); ok {
  441. c = t
  442. } else {
  443. return keyN
  444. }
  445. ruleFunc, ok := trNLangRules[lang]
  446. if !ok {
  447. ruleFunc = trNLangRules["en-US"]
  448. }
  449. if ruleFunc(c) == 0 {
  450. return key1
  451. }
  452. return keyN
  453. }
  454. // MigrationIcon returns a Font Awesome name matching the service an issue/comment was migrated from
  455. func MigrationIcon(hostname string) string {
  456. switch hostname {
  457. case "github.com":
  458. return "fa-github"
  459. default:
  460. return "fa-git-alt"
  461. }
  462. }