A fork of Gitea (see branch `mj`) adding Majority Judgment Polls 𐄷 over Issues and Merge Requests. https://git.mieuxvoter.fr
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.

688 lines
18 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
Use templates for issue e-mail subject and body (#8329) * Add template capability for issue mail subject * Remove test string * Fix trim subject length * Add comment to template and run make fmt * Add information for the template * Rename defaultMailSubject() to fallbackMailSubject() * General rewrite of the mail template code * Fix .Doer name * Use text/template for subject instead of html * Fix subject Re: prefix * Fix mail tests * Fix static templates * [skip ci] Updated translations via Crowdin * Expose db.SetMaxOpenConns and allow non MySQL dbs to set conn pool params (#8528) * Expose db.SetMaxOpenConns and allow other dbs to set their connection params * Add note about port exhaustion Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Prevent .code-view from overriding font on icon fonts (#8614) * Correct some outdated statements in the contributing guidelines (#8612) * More information for drone-cli in CONTRIBUTING.md * Increases the version of drone-cli to 1.2.0 * Adds a note for the Docker Toolbox on Windows Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Fix the url for the blog repository (now on gitea.com) Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Remove TrN due to lack of lang context * Redo templates to match previous code * Fix extra character in template * Unify PR & Issue tempaltes, fix format * Remove default subject * Add template tests * Fix template * Remove replaced function * Provide User as models.User for better consistency * Add docs * Fix doc inaccuracies, improve examples * Change mail footer to math AppName * Add test for mail subject/body template separation * Add support for code review comments * Update docs/content/doc/advanced/mail-templates-us.md Co-Authored-By: 6543 <24977596+6543@users.noreply.github.com>
3 years ago
8 years ago
9 years ago
Use templates for issue e-mail subject and body (#8329) * Add template capability for issue mail subject * Remove test string * Fix trim subject length * Add comment to template and run make fmt * Add information for the template * Rename defaultMailSubject() to fallbackMailSubject() * General rewrite of the mail template code * Fix .Doer name * Use text/template for subject instead of html * Fix subject Re: prefix * Fix mail tests * Fix static templates * [skip ci] Updated translations via Crowdin * Expose db.SetMaxOpenConns and allow non MySQL dbs to set conn pool params (#8528) * Expose db.SetMaxOpenConns and allow other dbs to set their connection params * Add note about port exhaustion Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Prevent .code-view from overriding font on icon fonts (#8614) * Correct some outdated statements in the contributing guidelines (#8612) * More information for drone-cli in CONTRIBUTING.md * Increases the version of drone-cli to 1.2.0 * Adds a note for the Docker Toolbox on Windows Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Fix the url for the blog repository (now on gitea.com) Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Remove TrN due to lack of lang context * Redo templates to match previous code * Fix extra character in template * Unify PR & Issue tempaltes, fix format * Remove default subject * Add template tests * Fix template * Remove replaced function * Provide User as models.User for better consistency * Add docs * Fix doc inaccuracies, improve examples * Change mail footer to math AppName * Add test for mail subject/body template separation * Add support for code review comments * Update docs/content/doc/advanced/mail-templates-us.md Co-Authored-By: 6543 <24977596+6543@users.noreply.github.com>
3 years ago
9 years ago
8 years ago
9 years ago
Use templates for issue e-mail subject and body (#8329) * Add template capability for issue mail subject * Remove test string * Fix trim subject length * Add comment to template and run make fmt * Add information for the template * Rename defaultMailSubject() to fallbackMailSubject() * General rewrite of the mail template code * Fix .Doer name * Use text/template for subject instead of html * Fix subject Re: prefix * Fix mail tests * Fix static templates * [skip ci] Updated translations via Crowdin * Expose db.SetMaxOpenConns and allow non MySQL dbs to set conn pool params (#8528) * Expose db.SetMaxOpenConns and allow other dbs to set their connection params * Add note about port exhaustion Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Prevent .code-view from overriding font on icon fonts (#8614) * Correct some outdated statements in the contributing guidelines (#8612) * More information for drone-cli in CONTRIBUTING.md * Increases the version of drone-cli to 1.2.0 * Adds a note for the Docker Toolbox on Windows Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Fix the url for the blog repository (now on gitea.com) Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Remove TrN due to lack of lang context * Redo templates to match previous code * Fix extra character in template * Unify PR & Issue tempaltes, fix format * Remove default subject * Add template tests * Fix template * Remove replaced function * Provide User as models.User for better consistency * Add docs * Fix doc inaccuracies, improve examples * Change mail footer to math AppName * Add test for mail subject/body template separation * Add support for code review comments * Update docs/content/doc/advanced/mail-templates-us.md Co-Authored-By: 6543 <24977596+6543@users.noreply.github.com>
3 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>
4 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
4 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>
4 years ago
Add Octicon SVG spritemap (#10107) * Add octicon SVG sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Static prefix Signed-off-by: jolheiser <john.olheiser@gmail.com> * SVG for all repo icons Signed-off-by: jolheiser <john.olheiser@gmail.com> * make vendor Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap out octicons Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move octicons to top of less imports Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix JS Signed-off-by: jolheiser <john.olheiser@gmail.com> * Definitely not a search/replace Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed regex Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move to more generic calls and webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * make svg -> make webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg-sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed a test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg from makefile Signed-off-by: jolheiser <john.olheiser@gmail.com> * Suggestions Signed-off-by: jolheiser <john.olheiser@gmail.com> * Attempt to fix test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert timetracking test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap .octicon for .svg in less Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add aria-hidden Signed-off-by: jolheiser <john.olheiser@gmail.com> * Replace mega-octicon Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix webpack globbing on Windows Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert Co-Authored-By: silverwind <me@silverwind.io> * Fix octions from upstream Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix Vue and missed JS function Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add JS helper and PWA Signed-off-by: jolheiser <john.olheiser@gmail.com> * Preload SVG Signed-off-by: jolheiser <john.olheiser@gmail.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: techknowlogick <matti@mdranta.net>
3 years ago
Add Octicon SVG spritemap (#10107) * Add octicon SVG sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Static prefix Signed-off-by: jolheiser <john.olheiser@gmail.com> * SVG for all repo icons Signed-off-by: jolheiser <john.olheiser@gmail.com> * make vendor Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap out octicons Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move octicons to top of less imports Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix JS Signed-off-by: jolheiser <john.olheiser@gmail.com> * Definitely not a search/replace Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed regex Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move to more generic calls and webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * make svg -> make webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg-sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed a test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg from makefile Signed-off-by: jolheiser <john.olheiser@gmail.com> * Suggestions Signed-off-by: jolheiser <john.olheiser@gmail.com> * Attempt to fix test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert timetracking test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap .octicon for .svg in less Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add aria-hidden Signed-off-by: jolheiser <john.olheiser@gmail.com> * Replace mega-octicon Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix webpack globbing on Windows Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert Co-Authored-By: silverwind <me@silverwind.io> * Fix octions from upstream Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix Vue and missed JS function Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add JS helper and PWA Signed-off-by: jolheiser <john.olheiser@gmail.com> * Preload SVG Signed-off-by: jolheiser <john.olheiser@gmail.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: techknowlogick <matti@mdranta.net>
3 years ago
7 years ago
Use templates for issue e-mail subject and body (#8329) * Add template capability for issue mail subject * Remove test string * Fix trim subject length * Add comment to template and run make fmt * Add information for the template * Rename defaultMailSubject() to fallbackMailSubject() * General rewrite of the mail template code * Fix .Doer name * Use text/template for subject instead of html * Fix subject Re: prefix * Fix mail tests * Fix static templates * [skip ci] Updated translations via Crowdin * Expose db.SetMaxOpenConns and allow non MySQL dbs to set conn pool params (#8528) * Expose db.SetMaxOpenConns and allow other dbs to set their connection params * Add note about port exhaustion Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Prevent .code-view from overriding font on icon fonts (#8614) * Correct some outdated statements in the contributing guidelines (#8612) * More information for drone-cli in CONTRIBUTING.md * Increases the version of drone-cli to 1.2.0 * Adds a note for the Docker Toolbox on Windows Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Fix the url for the blog repository (now on gitea.com) Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Remove TrN due to lack of lang context * Redo templates to match previous code * Fix extra character in template * Unify PR & Issue tempaltes, fix format * Remove default subject * Add template tests * Fix template * Remove replaced function * Provide User as models.User for better consistency * Add docs * Fix doc inaccuracies, improve examples * Change mail footer to math AppName * Add test for mail subject/body template separation * Add support for code review comments * Update docs/content/doc/advanced/mail-templates-us.md Co-Authored-By: 6543 <24977596+6543@users.noreply.github.com>
3 years ago
9 years ago
9 years ago
9 years ago
8 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
4 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
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 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
4 years ago
9 years ago
9 years ago
9 years ago
Use templates for issue e-mail subject and body (#8329) * Add template capability for issue mail subject * Remove test string * Fix trim subject length * Add comment to template and run make fmt * Add information for the template * Rename defaultMailSubject() to fallbackMailSubject() * General rewrite of the mail template code * Fix .Doer name * Use text/template for subject instead of html * Fix subject Re: prefix * Fix mail tests * Fix static templates * [skip ci] Updated translations via Crowdin * Expose db.SetMaxOpenConns and allow non MySQL dbs to set conn pool params (#8528) * Expose db.SetMaxOpenConns and allow other dbs to set their connection params * Add note about port exhaustion Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Prevent .code-view from overriding font on icon fonts (#8614) * Correct some outdated statements in the contributing guidelines (#8612) * More information for drone-cli in CONTRIBUTING.md * Increases the version of drone-cli to 1.2.0 * Adds a note for the Docker Toolbox on Windows Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Fix the url for the blog repository (now on gitea.com) Signed-off-by: LukBukkit <luk.bukkit@gmail.com> * Remove TrN due to lack of lang context * Redo templates to match previous code * Fix extra character in template * Unify PR & Issue tempaltes, fix format * Remove default subject * Add template tests * Fix template * Remove replaced function * Provide User as models.User for better consistency * Add docs * Fix doc inaccuracies, improve examples * Change mail footer to math AppName * Add test for mail subject/body template separation * Add support for code review comments * Update docs/content/doc/advanced/mail-templates-us.md Co-Authored-By: 6543 <24977596+6543@users.noreply.github.com>
3 years ago
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package templates
  6. import (
  7. "bytes"
  8. "container/list"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "html"
  13. "html/template"
  14. "mime"
  15. "net/url"
  16. "path/filepath"
  17. "regexp"
  18. "runtime"
  19. "strings"
  20. texttmpl "text/template"
  21. "time"
  22. "unicode"
  23. "code.gitea.io/gitea/models"
  24. "code.gitea.io/gitea/modules/base"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/markup"
  27. "code.gitea.io/gitea/modules/repository"
  28. "code.gitea.io/gitea/modules/setting"
  29. "code.gitea.io/gitea/modules/timeutil"
  30. "code.gitea.io/gitea/modules/util"
  31. "code.gitea.io/gitea/services/gitdiff"
  32. mirror_service "code.gitea.io/gitea/services/mirror"
  33. "github.com/editorconfig/editorconfig-core-go/v2"
  34. )
  35. // Used from static.go && dynamic.go
  36. var mailSubjectSplit = regexp.MustCompile(`(?m)^-{3,}[\s]*$`)
  37. // NewFuncMap returns functions for injecting to templates
  38. func NewFuncMap() []template.FuncMap {
  39. return []template.FuncMap{map[string]interface{}{
  40. "GoVer": func() string {
  41. return strings.Title(runtime.Version())
  42. },
  43. "UseHTTPS": func() bool {
  44. return strings.HasPrefix(setting.AppURL, "https")
  45. },
  46. "AppName": func() string {
  47. return setting.AppName
  48. },
  49. "AppSubUrl": func() string {
  50. return setting.AppSubURL
  51. },
  52. "StaticUrlPrefix": func() string {
  53. return setting.StaticURLPrefix
  54. },
  55. "AppUrl": func() string {
  56. return setting.AppURL
  57. },
  58. "AppVer": func() string {
  59. return setting.AppVer
  60. },
  61. "AppBuiltWith": func() string {
  62. return setting.AppBuiltWith
  63. },
  64. "AppDomain": func() string {
  65. return setting.Domain
  66. },
  67. "DisableGravatar": func() bool {
  68. return setting.DisableGravatar
  69. },
  70. "DefaultShowFullName": func() bool {
  71. return setting.UI.DefaultShowFullName
  72. },
  73. "ShowFooterTemplateLoadTime": func() bool {
  74. return setting.ShowFooterTemplateLoadTime
  75. },
  76. "LoadTimes": func(startTime time.Time) string {
  77. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  78. },
  79. "AllowedReactions": func() []string {
  80. return setting.UI.Reactions
  81. },
  82. "AvatarLink": base.AvatarLink,
  83. "Safe": Safe,
  84. "SafeJS": SafeJS,
  85. "Str2html": Str2html,
  86. "TimeSince": timeutil.TimeSince,
  87. "TimeSinceUnix": timeutil.TimeSinceUnix,
  88. "RawTimeSince": timeutil.RawTimeSince,
  89. "FileSize": base.FileSize,
  90. "PrettyNumber": base.PrettyNumber,
  91. "Subtract": base.Subtract,
  92. "EntryIcon": base.EntryIcon,
  93. "MigrationIcon": MigrationIcon,
  94. "Add": func(a, b int) int {
  95. return a + b
  96. },
  97. "ActionIcon": ActionIcon,
  98. "DateFmtLong": func(t time.Time) string {
  99. return t.Format(time.RFC1123Z)
  100. },
  101. "DateFmtShort": func(t time.Time) string {
  102. return t.Format("Jan 02, 2006")
  103. },
  104. "SizeFmt": base.FileSize,
  105. "List": List,
  106. "SubStr": func(str string, start, length int) string {
  107. if len(str) == 0 {
  108. return ""
  109. }
  110. end := start + length
  111. if length == -1 {
  112. end = len(str)
  113. }
  114. if len(str) < end {
  115. return str
  116. }
  117. return str[start:end]
  118. },
  119. "EllipsisString": base.EllipsisString,
  120. "DiffTypeToStr": DiffTypeToStr,
  121. "DiffLineTypeToStr": DiffLineTypeToStr,
  122. "Sha1": Sha1,
  123. "ShortSha": base.ShortSha,
  124. "MD5": base.EncodeMD5,
  125. "ActionContent2Commits": ActionContent2Commits,
  126. "PathEscape": url.PathEscape,
  127. "EscapePound": func(str string) string {
  128. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  129. },
  130. "PathEscapeSegments": util.PathEscapeSegments,
  131. "URLJoin": util.URLJoin,
  132. "RenderCommitMessage": RenderCommitMessage,
  133. "RenderCommitMessageLink": RenderCommitMessageLink,
  134. "RenderCommitMessageLinkSubject": RenderCommitMessageLinkSubject,
  135. "RenderCommitBody": RenderCommitBody,
  136. "RenderNote": RenderNote,
  137. "IsMultilineCommitMessage": IsMultilineCommitMessage,
  138. "ThemeColorMetaTag": func() string {
  139. return setting.UI.ThemeColorMetaTag
  140. },
  141. "MetaAuthor": func() string {
  142. return setting.UI.Meta.Author
  143. },
  144. "MetaDescription": func() string {
  145. return setting.UI.Meta.Description
  146. },
  147. "MetaKeywords": func() string {
  148. return setting.UI.Meta.Keywords
  149. },
  150. "UseServiceWorker": func() bool {
  151. return setting.UI.UseServiceWorker
  152. },
  153. "FilenameIsImage": func(filename string) bool {
  154. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  155. return strings.HasPrefix(mimeType, "image/")
  156. },
  157. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  158. if ec != nil {
  159. def, err := ec.GetDefinitionForFilename(filename)
  160. if err != nil {
  161. log.Error("tab size class: getting definition for filename: %v", err)
  162. return "tab-size-8"
  163. }
  164. if def.TabWidth > 0 {
  165. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  166. }
  167. }
  168. return "tab-size-8"
  169. },
  170. "SubJumpablePath": func(str string) []string {
  171. var path []string
  172. index := strings.LastIndex(str, "/")
  173. if index != -1 && index != len(str) {
  174. path = append(path, str[0:index+1], str[index+1:])
  175. } else {
  176. path = append(path, str)
  177. }
  178. return path
  179. },
  180. "Json": func(in interface{}) string {
  181. out, err := json.Marshal(in)
  182. if err != nil {
  183. return ""
  184. }
  185. return string(out)
  186. },
  187. "JsonPrettyPrint": func(in string) string {
  188. var out bytes.Buffer
  189. err := json.Indent(&out, []byte(in), "", " ")
  190. if err != nil {
  191. return ""
  192. }
  193. return out.String()
  194. },
  195. "DisableGitHooks": func() bool {
  196. return setting.DisableGitHooks
  197. },
  198. "DisableImportLocal": func() bool {
  199. return !setting.ImportLocalPaths
  200. },
  201. "TrN": TrN,
  202. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  203. if len(values)%2 != 0 {
  204. return nil, errors.New("invalid dict call")
  205. }
  206. dict := make(map[string]interface{}, len(values)/2)
  207. for i := 0; i < len(values); i += 2 {
  208. key, ok := values[i].(string)
  209. if !ok {
  210. return nil, errors.New("dict keys must be strings")
  211. }
  212. dict[key] = values[i+1]
  213. }
  214. return dict, nil
  215. },
  216. "Printf": fmt.Sprintf,
  217. "Escape": Escape,
  218. "Sec2Time": models.SecToTime,
  219. "ParseDeadline": func(deadline string) []string {
  220. return strings.Split(deadline, "|")
  221. },
  222. "DefaultTheme": func() string {
  223. return setting.UI.DefaultTheme
  224. },
  225. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  226. if len(values) == 0 {
  227. return nil, errors.New("invalid dict call")
  228. }
  229. dict := make(map[string]interface{})
  230. for i := 0; i < len(values); i++ {
  231. switch key := values[i].(type) {
  232. case string:
  233. i++
  234. if i == len(values) {
  235. return nil, errors.New("specify the key for non array values")
  236. }
  237. dict[key] = values[i]
  238. case map[string]interface{}:
  239. m := values[i].(map[string]interface{})
  240. for i, v := range m {
  241. dict[i] = v
  242. }
  243. default:
  244. return nil, errors.New("dict values must be maps")
  245. }
  246. }
  247. return dict, nil
  248. },
  249. "percentage": func(n int, values ...int) float32 {
  250. var sum = 0
  251. for i := 0; i < len(values); i++ {
  252. sum += values[i]
  253. }
  254. return float32(n) * 100 / float32(sum)
  255. },
  256. "CommentMustAsDiff": gitdiff.CommentMustAsDiff,
  257. "MirrorAddress": mirror_service.Address,
  258. "MirrorFullAddress": mirror_service.AddressNoCredentials,
  259. "MirrorUserName": mirror_service.Username,
  260. "MirrorPassword": mirror_service.Password,
  261. "CommitType": func(commit interface{}) string {
  262. switch commit.(type) {
  263. case models.SignCommitWithStatuses:
  264. return "SignCommitWithStatuses"
  265. case models.SignCommit:
  266. return "SignCommit"
  267. case models.UserCommit:
  268. return "UserCommit"
  269. default:
  270. return ""
  271. }
  272. },
  273. "contain": func(s []int64, id int64) bool {
  274. for i := 0; i < len(s); i++ {
  275. if s[i] == id {
  276. return true
  277. }
  278. }
  279. return false
  280. },
  281. "svg": func(icon string, size int) template.HTML {
  282. return template.HTML(fmt.Sprintf(`<svg class="svg %s" width="%d" height="%d" aria-hidden="true"><use xlink:href="#%s" /></svg>`, icon, size, size, icon))
  283. },
  284. }}
  285. }
  286. // NewTextFuncMap returns functions for injecting to text templates
  287. // It's a subset of those used for HTML and other templates
  288. func NewTextFuncMap() []texttmpl.FuncMap {
  289. return []texttmpl.FuncMap{map[string]interface{}{
  290. "GoVer": func() string {
  291. return strings.Title(runtime.Version())
  292. },
  293. "AppName": func() string {
  294. return setting.AppName
  295. },
  296. "AppSubUrl": func() string {
  297. return setting.AppSubURL
  298. },
  299. "AppUrl": func() string {
  300. return setting.AppURL
  301. },
  302. "AppVer": func() string {
  303. return setting.AppVer
  304. },
  305. "AppBuiltWith": func() string {
  306. return setting.AppBuiltWith
  307. },
  308. "AppDomain": func() string {
  309. return setting.Domain
  310. },
  311. "TimeSince": timeutil.TimeSince,
  312. "TimeSinceUnix": timeutil.TimeSinceUnix,
  313. "RawTimeSince": timeutil.RawTimeSince,
  314. "DateFmtLong": func(t time.Time) string {
  315. return t.Format(time.RFC1123Z)
  316. },
  317. "DateFmtShort": func(t time.Time) string {
  318. return t.Format("Jan 02, 2006")
  319. },
  320. "List": List,
  321. "SubStr": func(str string, start, length int) string {
  322. if len(str) == 0 {
  323. return ""
  324. }
  325. end := start + length
  326. if length == -1 {
  327. end = len(str)
  328. }
  329. if len(str) < end {
  330. return str
  331. }
  332. return str[start:end]
  333. },
  334. "EllipsisString": base.EllipsisString,
  335. "URLJoin": util.URLJoin,
  336. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  337. if len(values)%2 != 0 {
  338. return nil, errors.New("invalid dict call")
  339. }
  340. dict := make(map[string]interface{}, len(values)/2)
  341. for i := 0; i < len(values); i += 2 {
  342. key, ok := values[i].(string)
  343. if !ok {
  344. return nil, errors.New("dict keys must be strings")
  345. }
  346. dict[key] = values[i+1]
  347. }
  348. return dict, nil
  349. },
  350. "Printf": fmt.Sprintf,
  351. "Escape": Escape,
  352. "Sec2Time": models.SecToTime,
  353. "ParseDeadline": func(deadline string) []string {
  354. return strings.Split(deadline, "|")
  355. },
  356. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  357. if len(values) == 0 {
  358. return nil, errors.New("invalid dict call")
  359. }
  360. dict := make(map[string]interface{})
  361. for i := 0; i < len(values); i++ {
  362. switch key := values[i].(type) {
  363. case string:
  364. i++
  365. if i == len(values) {
  366. return nil, errors.New("specify the key for non array values")
  367. }
  368. dict[key] = values[i]
  369. case map[string]interface{}:
  370. m := values[i].(map[string]interface{})
  371. for i, v := range m {
  372. dict[i] = v
  373. }
  374. default:
  375. return nil, errors.New("dict values must be maps")
  376. }
  377. }
  378. return dict, nil
  379. },
  380. "percentage": func(n int, values ...int) float32 {
  381. var sum = 0
  382. for i := 0; i < len(values); i++ {
  383. sum += values[i]
  384. }
  385. return float32(n) * 100 / float32(sum)
  386. },
  387. }}
  388. }
  389. // Safe render raw as HTML
  390. func Safe(raw string) template.HTML {
  391. return template.HTML(raw)
  392. }
  393. // SafeJS renders raw as JS
  394. func SafeJS(raw string) template.JS {
  395. return template.JS(raw)
  396. }
  397. // Str2html render Markdown text to HTML
  398. func Str2html(raw string) template.HTML {
  399. return template.HTML(markup.Sanitize(raw))
  400. }
  401. // Escape escapes a HTML string
  402. func Escape(raw string) string {
  403. return html.EscapeString(raw)
  404. }
  405. // List traversings the list
  406. func List(l *list.List) chan interface{} {
  407. e := l.Front()
  408. c := make(chan interface{})
  409. go func() {
  410. for e != nil {
  411. c <- e.Value
  412. e = e.Next()
  413. }
  414. close(c)
  415. }()
  416. return c
  417. }
  418. // Sha1 returns sha1 sum of string
  419. func Sha1(str string) string {
  420. return base.EncodeSha1(str)
  421. }
  422. // 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) *repository.PushCommits {
  542. push := repository.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. }