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.

2436 lines
70 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 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
10 years ago
10 years ago
10 years ago
7 years ago
9 years ago
10 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
9 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea 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 models
  6. import (
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "html/template"
  11. "io/ioutil"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "sort"
  18. "strings"
  19. "time"
  20. "code.gitea.io/git"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/markup"
  23. "code.gitea.io/gitea/modules/options"
  24. "code.gitea.io/gitea/modules/process"
  25. "code.gitea.io/gitea/modules/setting"
  26. "code.gitea.io/gitea/modules/sync"
  27. "code.gitea.io/gitea/modules/util"
  28. api "code.gitea.io/sdk/gitea"
  29. "github.com/Unknwon/cae/zip"
  30. "github.com/Unknwon/com"
  31. "github.com/go-xorm/xorm"
  32. "github.com/mcuadros/go-version"
  33. "gopkg.in/ini.v1"
  34. )
  35. var repoWorkingPool = sync.NewExclusivePool()
  36. var (
  37. // ErrMirrorNotExist mirror does not exist error
  38. ErrMirrorNotExist = errors.New("Mirror does not exist")
  39. // ErrNameEmpty name is empty error
  40. ErrNameEmpty = errors.New("Name is empty")
  41. )
  42. var (
  43. // Gitignores contains the gitiginore files
  44. Gitignores []string
  45. // Licenses contains the license files
  46. Licenses []string
  47. // Readmes contains the readme files
  48. Readmes []string
  49. // LabelTemplates contains the label template files
  50. LabelTemplates []string
  51. // ItemsPerPage maximum items per page in forks, watchers and stars of a repo
  52. ItemsPerPage = 40
  53. )
  54. // LoadRepoConfig loads the repository config
  55. func LoadRepoConfig() {
  56. // Load .gitignore and license files and readme templates.
  57. types := []string{"gitignore", "license", "readme", "label"}
  58. typeFiles := make([][]string, 4)
  59. for i, t := range types {
  60. files, err := options.Dir(t)
  61. if err != nil {
  62. log.Fatal(4, "Failed to get %s files: %v", t, err)
  63. }
  64. customPath := path.Join(setting.CustomPath, "options", t)
  65. if com.IsDir(customPath) {
  66. customFiles, err := com.StatDir(customPath)
  67. if err != nil {
  68. log.Fatal(4, "Failed to get custom %s files: %v", t, err)
  69. }
  70. for _, f := range customFiles {
  71. if !com.IsSliceContainsStr(files, f) {
  72. files = append(files, f)
  73. }
  74. }
  75. }
  76. typeFiles[i] = files
  77. }
  78. Gitignores = typeFiles[0]
  79. Licenses = typeFiles[1]
  80. Readmes = typeFiles[2]
  81. LabelTemplates = typeFiles[3]
  82. sort.Strings(Gitignores)
  83. sort.Strings(Licenses)
  84. sort.Strings(Readmes)
  85. sort.Strings(LabelTemplates)
  86. // Filter out invalid names and promote preferred licenses.
  87. sortedLicenses := make([]string, 0, len(Licenses))
  88. for _, name := range setting.Repository.PreferredLicenses {
  89. if com.IsSliceContainsStr(Licenses, name) {
  90. sortedLicenses = append(sortedLicenses, name)
  91. }
  92. }
  93. for _, name := range Licenses {
  94. if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) {
  95. sortedLicenses = append(sortedLicenses, name)
  96. }
  97. }
  98. Licenses = sortedLicenses
  99. }
  100. // NewRepoContext creates a new repository context
  101. func NewRepoContext() {
  102. zip.Verbose = false
  103. // Check Git installation.
  104. if _, err := exec.LookPath("git"); err != nil {
  105. log.Fatal(4, "Failed to test 'git' command: %v (forgotten install?)", err)
  106. }
  107. // Check Git version.
  108. var err error
  109. setting.Git.Version, err = git.BinVersion()
  110. if err != nil {
  111. log.Fatal(4, "Failed to get Git version: %v", err)
  112. }
  113. log.Info("Git Version: %s", setting.Git.Version)
  114. if version.Compare("1.7.1", setting.Git.Version, ">") {
  115. log.Fatal(4, "Gitea requires Git version greater or equal to 1.7.1")
  116. }
  117. // Git requires setting user.name and user.email in order to commit changes.
  118. for configKey, defaultValue := range map[string]string{"user.name": "Gitea", "user.email": "gitea@fake.local"} {
  119. if stdout, stderr, err := process.GetManager().Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  120. // ExitError indicates this config is not set
  121. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  122. if _, stderr, gerr := process.GetManager().Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  123. log.Fatal(4, "Failed to set git %s(%s): %s", configKey, gerr, stderr)
  124. }
  125. log.Info("Git config %s set to %s", configKey, defaultValue)
  126. } else {
  127. log.Fatal(4, "Failed to get git %s(%s): %s", configKey, err, stderr)
  128. }
  129. }
  130. }
  131. // Set git some configurations.
  132. if _, stderr, err := process.GetManager().Exec("NewRepoContext(git config --global core.quotepath false)",
  133. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  134. log.Fatal(4, "Failed to execute 'git config --global core.quotepath false': %s", stderr)
  135. }
  136. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
  137. }
  138. // Repository represents a git repository.
  139. type Repository struct {
  140. ID int64 `xorm:"pk autoincr"`
  141. OwnerID int64 `xorm:"UNIQUE(s)"`
  142. Owner *User `xorm:"-"`
  143. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  144. Name string `xorm:"INDEX NOT NULL"`
  145. Description string
  146. Website string
  147. DefaultBranch string
  148. NumWatches int
  149. NumStars int
  150. NumForks int
  151. NumIssues int
  152. NumClosedIssues int
  153. NumOpenIssues int `xorm:"-"`
  154. NumPulls int
  155. NumClosedPulls int
  156. NumOpenPulls int `xorm:"-"`
  157. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  158. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  159. NumOpenMilestones int `xorm:"-"`
  160. NumReleases int `xorm:"-"`
  161. IsPrivate bool `xorm:"INDEX"`
  162. IsBare bool `xorm:"INDEX"`
  163. IsMirror bool `xorm:"INDEX"`
  164. *Mirror `xorm:"-"`
  165. ExternalMetas map[string]string `xorm:"-"`
  166. Units []*RepoUnit `xorm:"-"`
  167. IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"`
  168. ForkID int64 `xorm:"INDEX"`
  169. BaseRepo *Repository `xorm:"-"`
  170. Size int64 `xorm:"NOT NULL DEFAULT 0"`
  171. IndexerStatus *RepoIndexerStatus `xorm:"-"`
  172. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  173. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  174. }
  175. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  176. func (repo *Repository) AfterLoad() {
  177. // FIXME: use models migration to solve all at once.
  178. if len(repo.DefaultBranch) == 0 {
  179. repo.DefaultBranch = "master"
  180. }
  181. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  182. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  183. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  184. }
  185. // MustOwner always returns a valid *User object to avoid
  186. // conceptually impossible error handling.
  187. // It creates a fake object that contains error details
  188. // when error occurs.
  189. func (repo *Repository) MustOwner() *User {
  190. return repo.mustOwner(x)
  191. }
  192. // FullName returns the repository full name
  193. func (repo *Repository) FullName() string {
  194. return repo.MustOwner().Name + "/" + repo.Name
  195. }
  196. // HTMLURL returns the repository HTML URL
  197. func (repo *Repository) HTMLURL() string {
  198. return setting.AppURL + repo.FullName()
  199. }
  200. // APIURL returns the repository API URL
  201. func (repo *Repository) APIURL() string {
  202. return setting.AppURL + path.Join("api/v1/repos", repo.FullName())
  203. }
  204. // APIFormat converts a Repository to api.Repository
  205. func (repo *Repository) APIFormat(mode AccessMode) *api.Repository {
  206. return repo.innerAPIFormat(mode, false)
  207. }
  208. // GetCommitsCountCacheKey returns cache key used for commits count caching.
  209. func (repo *Repository) GetCommitsCountCacheKey(contextName string, isRef bool) string {
  210. var prefix string
  211. if isRef {
  212. prefix = "ref"
  213. } else {
  214. prefix = "commit"
  215. }
  216. return fmt.Sprintf("commits-count-%d-%s-%s", repo.ID, prefix, contextName)
  217. }
  218. func (repo *Repository) innerAPIFormat(mode AccessMode, isParent bool) *api.Repository {
  219. var parent *api.Repository
  220. cloneLink := repo.CloneLink()
  221. permission := &api.Permission{
  222. Admin: mode >= AccessModeAdmin,
  223. Push: mode >= AccessModeWrite,
  224. Pull: mode >= AccessModeRead,
  225. }
  226. if !isParent {
  227. err := repo.GetBaseRepo()
  228. if err != nil {
  229. log.Error(4, "APIFormat: %v", err)
  230. }
  231. if repo.BaseRepo != nil {
  232. parent = repo.BaseRepo.innerAPIFormat(mode, true)
  233. }
  234. }
  235. return &api.Repository{
  236. ID: repo.ID,
  237. Owner: repo.Owner.APIFormat(),
  238. Name: repo.Name,
  239. FullName: repo.FullName(),
  240. Description: repo.Description,
  241. Private: repo.IsPrivate,
  242. Empty: repo.IsBare,
  243. Size: int(repo.Size / 1024),
  244. Fork: repo.IsFork,
  245. Parent: parent,
  246. Mirror: repo.IsMirror,
  247. HTMLURL: repo.HTMLURL(),
  248. SSHURL: cloneLink.SSH,
  249. CloneURL: cloneLink.HTTPS,
  250. Website: repo.Website,
  251. Stars: repo.NumStars,
  252. Forks: repo.NumForks,
  253. Watchers: repo.NumWatches,
  254. OpenIssues: repo.NumOpenIssues,
  255. DefaultBranch: repo.DefaultBranch,
  256. Created: repo.CreatedUnix.AsTime(),
  257. Updated: repo.UpdatedUnix.AsTime(),
  258. Permissions: permission,
  259. }
  260. }
  261. func (repo *Repository) getUnits(e Engine) (err error) {
  262. if repo.Units != nil {
  263. return nil
  264. }
  265. repo.Units, err = getUnitsByRepoID(e, repo.ID)
  266. return err
  267. }
  268. // CheckUnitUser check whether user could visit the unit of this repository
  269. func (repo *Repository) CheckUnitUser(userID int64, isAdmin bool, unitType UnitType) bool {
  270. if err := repo.getUnitsByUserID(x, userID, isAdmin); err != nil {
  271. return false
  272. }
  273. for _, unit := range repo.Units {
  274. if unit.Type == unitType {
  275. return true
  276. }
  277. }
  278. return false
  279. }
  280. // LoadUnitsByUserID loads units according userID's permissions
  281. func (repo *Repository) LoadUnitsByUserID(userID int64, isAdmin bool) error {
  282. return repo.getUnitsByUserID(x, userID, isAdmin)
  283. }
  284. func (repo *Repository) getUnitsByUserID(e Engine, userID int64, isAdmin bool) (err error) {
  285. if repo.Units != nil {
  286. return nil
  287. }
  288. if err = repo.getUnits(e); err != nil {
  289. return err
  290. } else if err = repo.getOwner(e); err != nil {
  291. return err
  292. }
  293. if !repo.Owner.IsOrganization() || userID == 0 || isAdmin || !repo.IsPrivate {
  294. return nil
  295. }
  296. // Collaborators will not be limited
  297. if isCollaborator, err := repo.isCollaborator(e, userID); err != nil {
  298. return err
  299. } else if isCollaborator {
  300. return nil
  301. }
  302. teams, err := getUserTeams(e, repo.OwnerID, userID)
  303. if err != nil {
  304. return err
  305. }
  306. var allTypes = make(map[UnitType]struct{}, len(allRepUnitTypes))
  307. for _, team := range teams {
  308. // Administrators can not be limited
  309. if team.Authorize >= AccessModeAdmin {
  310. return nil
  311. }
  312. for _, unitType := range team.UnitTypes {
  313. allTypes[unitType] = struct{}{}
  314. }
  315. }
  316. // unique
  317. var newRepoUnits = make([]*RepoUnit, 0, len(repo.Units))
  318. for _, u := range repo.Units {
  319. if _, ok := allTypes[u.Type]; ok {
  320. newRepoUnits = append(newRepoUnits, u)
  321. }
  322. }
  323. repo.Units = newRepoUnits
  324. return nil
  325. }
  326. // UnitEnabled if this repository has the given unit enabled
  327. func (repo *Repository) UnitEnabled(tp UnitType) bool {
  328. if err := repo.getUnits(x); err != nil {
  329. log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error())
  330. }
  331. for _, unit := range repo.Units {
  332. if unit.Type == tp {
  333. return true
  334. }
  335. }
  336. return false
  337. }
  338. // AnyUnitEnabled if this repository has the any of the given units enabled
  339. func (repo *Repository) AnyUnitEnabled(tps ...UnitType) bool {
  340. if err := repo.getUnits(x); err != nil {
  341. log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error())
  342. }
  343. for _, unit := range repo.Units {
  344. for _, tp := range tps {
  345. if unit.Type == tp {
  346. return true
  347. }
  348. }
  349. }
  350. return false
  351. }
  352. var (
  353. // ErrUnitNotExist organization does not exist
  354. ErrUnitNotExist = errors.New("Unit does not exist")
  355. )
  356. // MustGetUnit always returns a RepoUnit object
  357. func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit {
  358. ru, err := repo.GetUnit(tp)
  359. if err == nil {
  360. return ru
  361. }
  362. if tp == UnitTypeExternalWiki {
  363. return &RepoUnit{
  364. Type: tp,
  365. Config: new(ExternalWikiConfig),
  366. }
  367. } else if tp == UnitTypeExternalTracker {
  368. return &RepoUnit{
  369. Type: tp,
  370. Config: new(ExternalTrackerConfig),
  371. }
  372. } else if tp == UnitTypePullRequests {
  373. return &RepoUnit{
  374. Type: tp,
  375. Config: new(PullRequestsConfig),
  376. }
  377. }
  378. return &RepoUnit{
  379. Type: tp,
  380. Config: new(UnitConfig),
  381. }
  382. }
  383. // GetUnit returns a RepoUnit object
  384. func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) {
  385. if err := repo.getUnits(x); err != nil {
  386. return nil, err
  387. }
  388. for _, unit := range repo.Units {
  389. if unit.Type == tp {
  390. return unit, nil
  391. }
  392. }
  393. return nil, ErrUnitNotExist
  394. }
  395. func (repo *Repository) getOwner(e Engine) (err error) {
  396. if repo.Owner != nil {
  397. return nil
  398. }
  399. repo.Owner, err = getUserByID(e, repo.OwnerID)
  400. return err
  401. }
  402. // GetOwner returns the repository owner
  403. func (repo *Repository) GetOwner() error {
  404. return repo.getOwner(x)
  405. }
  406. func (repo *Repository) mustOwner(e Engine) *User {
  407. if err := repo.getOwner(e); err != nil {
  408. return &User{
  409. Name: "error",
  410. FullName: err.Error(),
  411. }
  412. }
  413. return repo.Owner
  414. }
  415. // ComposeMetas composes a map of metas for rendering external issue tracker URL.
  416. func (repo *Repository) ComposeMetas() map[string]string {
  417. unit, err := repo.GetUnit(UnitTypeExternalTracker)
  418. if err != nil {
  419. return nil
  420. }
  421. if repo.ExternalMetas == nil {
  422. repo.ExternalMetas = map[string]string{
  423. "format": unit.ExternalTrackerConfig().ExternalTrackerFormat,
  424. "user": repo.MustOwner().Name,
  425. "repo": repo.Name,
  426. }
  427. switch unit.ExternalTrackerConfig().ExternalTrackerStyle {
  428. case markup.IssueNameStyleAlphanumeric:
  429. repo.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
  430. default:
  431. repo.ExternalMetas["style"] = markup.IssueNameStyleNumeric
  432. }
  433. }
  434. return repo.ExternalMetas
  435. }
  436. // DeleteWiki removes the actual and local copy of repository wiki.
  437. func (repo *Repository) DeleteWiki() error {
  438. return repo.deleteWiki(x)
  439. }
  440. func (repo *Repository) deleteWiki(e Engine) error {
  441. wikiPaths := []string{repo.WikiPath(), repo.LocalWikiPath()}
  442. for _, wikiPath := range wikiPaths {
  443. removeAllWithNotice(e, "Delete repository wiki", wikiPath)
  444. }
  445. _, err := e.Where("repo_id = ?", repo.ID).And("type = ?", UnitTypeWiki).Delete(new(RepoUnit))
  446. return err
  447. }
  448. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  449. if err = repo.getOwner(e); err != nil {
  450. return nil, err
  451. }
  452. accesses := make([]*Access, 0, 10)
  453. if err = e.
  454. Where("repo_id = ? AND mode >= ?", repo.ID, AccessModeWrite).
  455. Find(&accesses); err != nil {
  456. return nil, err
  457. }
  458. // Leave a seat for owner itself to append later, but if owner is an organization
  459. // and just waste 1 unit is cheaper than re-allocate memory once.
  460. users := make([]*User, 0, len(accesses)+1)
  461. if len(accesses) > 0 {
  462. userIDs := make([]int64, len(accesses))
  463. for i := 0; i < len(accesses); i++ {
  464. userIDs[i] = accesses[i].UserID
  465. }
  466. if err = e.In("id", userIDs).Find(&users); err != nil {
  467. return nil, err
  468. }
  469. }
  470. if !repo.Owner.IsOrganization() {
  471. users = append(users, repo.Owner)
  472. }
  473. return users, nil
  474. }
  475. // GetAssignees returns all users that have write access and can be assigned to issues
  476. // of the repository,
  477. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  478. return repo.getAssignees(x)
  479. }
  480. // GetAssigneeByID returns the user that has write access of repository by given ID.
  481. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  482. return GetAssigneeByID(repo, userID)
  483. }
  484. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  485. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  486. return GetMilestoneByRepoID(repo.ID, milestoneID)
  487. }
  488. // IssueStats returns number of open and closed repository issues by given filter mode.
  489. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  490. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  491. }
  492. // GetMirror sets the repository mirror, returns an error upon failure
  493. func (repo *Repository) GetMirror() (err error) {
  494. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  495. return err
  496. }
  497. // GetBaseRepo populates repo.BaseRepo for a fork repository and
  498. // returns an error on failure (NOTE: no error is returned for
  499. // non-fork repositories, and BaseRepo will be left untouched)
  500. func (repo *Repository) GetBaseRepo() (err error) {
  501. if !repo.IsFork {
  502. return nil
  503. }
  504. repo.BaseRepo, err = GetRepositoryByID(repo.ForkID)
  505. return err
  506. }
  507. func (repo *Repository) repoPath(e Engine) string {
  508. return RepoPath(repo.mustOwner(e).Name, repo.Name)
  509. }
  510. // RepoPath returns the repository path
  511. func (repo *Repository) RepoPath() string {
  512. return repo.repoPath(x)
  513. }
  514. // GitConfigPath returns the path to a repository's git config/ directory
  515. func GitConfigPath(repoPath string) string {
  516. return filepath.Join(repoPath, "config")
  517. }
  518. // GitConfigPath returns the repository git config path
  519. func (repo *Repository) GitConfigPath() string {
  520. return GitConfigPath(repo.RepoPath())
  521. }
  522. // RelLink returns the repository relative link
  523. func (repo *Repository) RelLink() string {
  524. return "/" + repo.FullName()
  525. }
  526. // Link returns the repository link
  527. func (repo *Repository) Link() string {
  528. return setting.AppSubURL + "/" + repo.FullName()
  529. }
  530. // ComposeCompareURL returns the repository comparison URL
  531. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  532. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  533. }
  534. // HasAccess returns true when user has access to this repository
  535. func (repo *Repository) HasAccess(u *User) bool {
  536. has, _ := HasAccess(u.ID, repo, AccessModeRead)
  537. return has
  538. }
  539. // UpdateDefaultBranch updates the default branch
  540. func (repo *Repository) UpdateDefaultBranch() error {
  541. _, err := x.ID(repo.ID).Cols("default_branch").Update(repo)
  542. return err
  543. }
  544. // IsOwnedBy returns true when user owns this repository
  545. func (repo *Repository) IsOwnedBy(userID int64) bool {
  546. return repo.OwnerID == userID
  547. }
  548. func (repo *Repository) updateSize(e Engine) error {
  549. repoInfoSize, err := git.GetRepoSize(repo.RepoPath())
  550. if err != nil {
  551. return fmt.Errorf("UpdateSize: %v", err)
  552. }
  553. repo.Size = repoInfoSize.Size + repoInfoSize.SizePack
  554. _, err = e.ID(repo.ID).Cols("size").Update(repo)
  555. return err
  556. }
  557. // UpdateSize updates the repository size, calculating it using git.GetRepoSize
  558. func (repo *Repository) UpdateSize() error {
  559. return repo.updateSize(x)
  560. }
  561. // CanBeForked returns true if repository meets the requirements of being forked.
  562. func (repo *Repository) CanBeForked() bool {
  563. return !repo.IsBare && repo.UnitEnabled(UnitTypeCode)
  564. }
  565. // CanUserFork returns true if specified user can fork repository.
  566. func (repo *Repository) CanUserFork(user *User) (bool, error) {
  567. if user == nil {
  568. return false, nil
  569. }
  570. if repo.OwnerID != user.ID && !user.HasForkedRepo(repo.ID) {
  571. return true, nil
  572. }
  573. if err := user.GetOwnedOrganizations(); err != nil {
  574. return false, err
  575. }
  576. for _, org := range user.OwnedOrgs {
  577. if repo.OwnerID != org.ID && !org.HasForkedRepo(repo.ID) {
  578. return true, nil
  579. }
  580. }
  581. return false, nil
  582. }
  583. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  584. func (repo *Repository) CanEnablePulls() bool {
  585. return !repo.IsMirror && !repo.IsBare
  586. }
  587. // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  588. func (repo *Repository) AllowsPulls() bool {
  589. return repo.CanEnablePulls() && repo.UnitEnabled(UnitTypePullRequests)
  590. }
  591. // CanEnableEditor returns true if repository meets the requirements of web editor.
  592. func (repo *Repository) CanEnableEditor() bool {
  593. return !repo.IsMirror
  594. }
  595. // GetWriters returns all users that have write access to the repository.
  596. func (repo *Repository) GetWriters() (_ []*User, err error) {
  597. return repo.getUsersWithAccessMode(x, AccessModeWrite)
  598. }
  599. // getUsersWithAccessMode returns users that have at least given access mode to the repository.
  600. func (repo *Repository) getUsersWithAccessMode(e Engine, mode AccessMode) (_ []*User, err error) {
  601. if err = repo.getOwner(e); err != nil {
  602. return nil, err
  603. }
  604. accesses := make([]*Access, 0, 10)
  605. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  606. return nil, err
  607. }
  608. // Leave a seat for owner itself to append later, but if owner is an organization
  609. // and just waste 1 unit is cheaper than re-allocate memory once.
  610. users := make([]*User, 0, len(accesses)+1)
  611. if len(accesses) > 0 {
  612. userIDs := make([]int64, len(accesses))
  613. for i := 0; i < len(accesses); i++ {
  614. userIDs[i] = accesses[i].UserID
  615. }
  616. if err = e.In("id", userIDs).Find(&users); err != nil {
  617. return nil, err
  618. }
  619. }
  620. if !repo.Owner.IsOrganization() {
  621. users = append(users, repo.Owner)
  622. }
  623. return users, nil
  624. }
  625. // NextIssueIndex returns the next issue index
  626. // FIXME: should have a mutex to prevent producing same index for two issues that are created
  627. // closely enough.
  628. func (repo *Repository) NextIssueIndex() int64 {
  629. return int64(repo.NumIssues+repo.NumPulls) + 1
  630. }
  631. var (
  632. descPattern = regexp.MustCompile(`https?://\S+`)
  633. )
  634. // DescriptionHTML does special handles to description and return HTML string.
  635. func (repo *Repository) DescriptionHTML() template.HTML {
  636. sanitize := func(s string) string {
  637. return fmt.Sprintf(`<a href="%[1]s" target="_blank" rel="noopener">%[1]s</a>`, s)
  638. }
  639. return template.HTML(descPattern.ReplaceAllStringFunc(markup.Sanitize(repo.Description), sanitize))
  640. }
  641. // LocalCopyPath returns the local repository copy path.
  642. func LocalCopyPath() string {
  643. if filepath.IsAbs(setting.Repository.Local.LocalCopyPath) {
  644. return setting.Repository.Local.LocalCopyPath
  645. }
  646. return path.Join(setting.AppDataPath, setting.Repository.Local.LocalCopyPath)
  647. }
  648. // LocalCopyPath returns the local repository copy path for the given repo.
  649. func (repo *Repository) LocalCopyPath() string {
  650. return path.Join(LocalCopyPath(), com.ToStr(repo.ID))
  651. }
  652. // UpdateLocalCopyBranch pulls latest changes of given branch from repoPath to localPath.
  653. // It creates a new clone if local copy does not exist.
  654. // This function checks out target branch by default, it is safe to assume subsequent
  655. // operations are operating against target branch when caller has confidence for no race condition.
  656. func UpdateLocalCopyBranch(repoPath, localPath, branch string) error {
  657. if !com.IsExist(localPath) {
  658. if err := git.Clone(repoPath, localPath, git.CloneRepoOptions{
  659. Timeout: time.Duration(setting.Git.Timeout.Clone) * time.Second,
  660. Branch: branch,
  661. }); err != nil {
  662. return fmt.Errorf("git clone %s: %v", branch, err)
  663. }
  664. } else {
  665. if err := git.Checkout(localPath, git.CheckoutOptions{
  666. Branch: branch,
  667. }); err != nil {
  668. return fmt.Errorf("git checkout %s: %v", branch, err)
  669. }
  670. _, err := git.NewCommand("fetch", "origin").RunInDir(localPath)
  671. if err != nil {
  672. return fmt.Errorf("git fetch origin: %v", err)
  673. }
  674. if len(branch) > 0 {
  675. if err := git.ResetHEAD(localPath, true, "origin/"+branch); err != nil {
  676. return fmt.Errorf("git reset --hard origin/%s: %v", branch, err)
  677. }
  678. }
  679. }
  680. return nil
  681. }
  682. // UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
  683. func (repo *Repository) UpdateLocalCopyBranch(branch string) error {
  684. return UpdateLocalCopyBranch(repo.RepoPath(), repo.LocalCopyPath(), branch)
  685. }
  686. // PatchPath returns corresponding patch file path of repository by given issue ID.
  687. func (repo *Repository) PatchPath(index int64) (string, error) {
  688. if err := repo.GetOwner(); err != nil {
  689. return "", err
  690. }
  691. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  692. }
  693. // SavePatch saves patch data to corresponding location by given issue ID.
  694. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  695. patchPath, err := repo.PatchPath(index)
  696. if err != nil {
  697. return fmt.Errorf("PatchPath: %v", err)
  698. }
  699. dir := filepath.Dir(patchPath)
  700. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  701. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  702. }
  703. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  704. return fmt.Errorf("WriteFile: %v", err)
  705. }
  706. return nil
  707. }
  708. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  709. has, err := e.Get(&Repository{
  710. OwnerID: u.ID,
  711. LowerName: strings.ToLower(repoName),
  712. })
  713. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  714. }
  715. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  716. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  717. return isRepositoryExist(x, u, repoName)
  718. }
  719. // CloneLink represents different types of clone URLs of repository.
  720. type CloneLink struct {
  721. SSH string
  722. HTTPS string
  723. Git string
  724. }
  725. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  726. func ComposeHTTPSCloneURL(owner, repo string) string {
  727. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, owner, repo)
  728. }
  729. func (repo *Repository) cloneLink(isWiki bool) *CloneLink {
  730. repoName := repo.Name
  731. if isWiki {
  732. repoName += ".wiki"
  733. }
  734. sshUser := setting.RunUser
  735. if setting.SSH.StartBuiltinServer {
  736. sshUser = setting.SSH.BuiltinServerUser
  737. }
  738. repo.Owner = repo.MustOwner()
  739. cl := new(CloneLink)
  740. if setting.SSH.Port != 22 {
  741. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", sshUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  742. } else if setting.Repository.UseCompatSSHURI {
  743. cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  744. } else {
  745. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  746. }
  747. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  748. return cl
  749. }
  750. // CloneLink returns clone URLs of repository.
  751. func (repo *Repository) CloneLink() (cl *CloneLink) {
  752. return repo.cloneLink(false)
  753. }
  754. // MigrateRepoOptions contains the repository migrate options
  755. type MigrateRepoOptions struct {
  756. Name string
  757. Description string
  758. IsPrivate bool
  759. IsMirror bool
  760. RemoteAddr string
  761. }
  762. /*
  763. GitHub, GitLab, Gogs: *.wiki.git
  764. BitBucket: *.git/wiki
  765. */
  766. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  767. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  768. // Otherwise, it returns an empty string.
  769. func wikiRemoteURL(remote string) string {
  770. remote = strings.TrimSuffix(remote, ".git")
  771. for _, suffix := range commonWikiURLSuffixes {
  772. wikiURL := remote + suffix
  773. if git.IsRepoURLAccessible(wikiURL) {
  774. return wikiURL
  775. }
  776. }
  777. return ""
  778. }
  779. // MigrateRepository migrates a existing repository from other project hosting.
  780. func MigrateRepository(doer, u *User, opts MigrateRepoOptions) (*Repository, error) {
  781. repo, err := CreateRepository(doer, u, CreateRepoOptions{
  782. Name: opts.Name,
  783. Description: opts.Description,
  784. IsPrivate: opts.IsPrivate,
  785. IsMirror: opts.IsMirror,
  786. })
  787. if err != nil {
  788. return nil, err
  789. }
  790. repoPath := RepoPath(u.Name, opts.Name)
  791. wikiPath := WikiPath(u.Name, opts.Name)
  792. if u.IsOrganization() {
  793. t, err := u.GetOwnerTeam()
  794. if err != nil {
  795. return nil, err
  796. }
  797. repo.NumWatches = t.NumMembers
  798. } else {
  799. repo.NumWatches = 1
  800. }
  801. migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second
  802. if err := os.RemoveAll(repoPath); err != nil {
  803. return repo, fmt.Errorf("Failed to remove %s: %v", repoPath, err)
  804. }
  805. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{
  806. Mirror: true,
  807. Quiet: true,
  808. Timeout: migrateTimeout,
  809. }); err != nil {
  810. return repo, fmt.Errorf("Clone: %v", err)
  811. }
  812. wikiRemotePath := wikiRemoteURL(opts.RemoteAddr)
  813. if len(wikiRemotePath) > 0 {
  814. if err := os.RemoveAll(wikiPath); err != nil {
  815. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  816. }
  817. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{
  818. Mirror: true,
  819. Quiet: true,
  820. Timeout: migrateTimeout,
  821. Branch: "master",
  822. }); err != nil {
  823. log.Warn("Clone wiki: %v", err)
  824. if err := os.RemoveAll(wikiPath); err != nil {
  825. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  826. }
  827. }
  828. }
  829. // Check if repository is empty.
  830. _, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
  831. if err != nil {
  832. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  833. repo.IsBare = true
  834. } else {
  835. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  836. }
  837. }
  838. if !repo.IsBare {
  839. // Try to get HEAD branch and set it as default branch.
  840. gitRepo, err := git.OpenRepository(repoPath)
  841. if err != nil {
  842. return repo, fmt.Errorf("OpenRepository: %v", err)
  843. }
  844. headBranch, err := gitRepo.GetHEADBranch()
  845. if err != nil {
  846. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  847. }
  848. if headBranch != nil {
  849. repo.DefaultBranch = headBranch.Name
  850. }
  851. if err = SyncReleasesWithTags(repo, gitRepo); err != nil {
  852. log.Error(4, "Failed to synchronize tags to releases for repository: %v", err)
  853. }
  854. UpdateRepoIndexer(repo)
  855. }
  856. if err = repo.UpdateSize(); err != nil {
  857. log.Error(4, "Failed to update size for repository: %v", err)
  858. }
  859. if opts.IsMirror {
  860. if _, err = x.InsertOne(&Mirror{
  861. RepoID: repo.ID,
  862. Interval: setting.Mirror.DefaultInterval,
  863. EnablePrune: true,
  864. NextUpdateUnix: util.TimeStampNow().AddDuration(setting.Mirror.DefaultInterval),
  865. }); err != nil {
  866. return repo, fmt.Errorf("InsertOne: %v", err)
  867. }
  868. repo.IsMirror = true
  869. return repo, UpdateRepository(repo, false)
  870. }
  871. return CleanUpMigrateInfo(repo)
  872. }
  873. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  874. // This also removes possible user credentials.
  875. func cleanUpMigrateGitConfig(configPath string) error {
  876. cfg, err := ini.Load(configPath)
  877. if err != nil {
  878. return fmt.Errorf("open config file: %v", err)
  879. }
  880. cfg.DeleteSection("remote \"origin\"")
  881. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  882. return fmt.Errorf("save config file: %v", err)
  883. }
  884. return nil
  885. }
  886. // createDelegateHooks creates all the hooks scripts for the repo
  887. func createDelegateHooks(repoPath string) (err error) {
  888. var (
  889. hookNames = []string{"pre-receive", "update", "post-receive"}
  890. hookTpls = []string{
  891. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  892. fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  893. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  894. }
  895. giteaHookTpls = []string{
  896. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  897. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  898. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  899. }
  900. )
  901. hookDir := filepath.Join(repoPath, "hooks")
  902. for i, hookName := range hookNames {
  903. oldHookPath := filepath.Join(hookDir, hookName)
  904. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  905. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  906. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  907. }
  908. // WARNING: This will override all old server-side hooks
  909. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  910. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  911. }
  912. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  913. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  914. }
  915. }
  916. return nil
  917. }
  918. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.
  919. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  920. repoPath := repo.RepoPath()
  921. if err := createDelegateHooks(repoPath); err != nil {
  922. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  923. }
  924. if repo.HasWiki() {
  925. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  926. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  927. }
  928. }
  929. if err := cleanUpMigrateGitConfig(repo.GitConfigPath()); err != nil {
  930. return repo, fmt.Errorf("cleanUpMigrateGitConfig: %v", err)
  931. }
  932. if repo.HasWiki() {
  933. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  934. return repo, fmt.Errorf("cleanUpMigrateGitConfig (wiki): %v", err)
  935. }
  936. }
  937. return repo, UpdateRepository(repo, false)
  938. }
  939. // initRepoCommit temporarily changes with work directory.
  940. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  941. var stderr string
  942. if _, stderr, err = process.GetManager().ExecDir(-1,
  943. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  944. "git", "add", "--all"); err != nil {
  945. return fmt.Errorf("git add: %s", stderr)
  946. }
  947. if _, stderr, err = process.GetManager().ExecDir(-1,
  948. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  949. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  950. "-m", "Initial commit"); err != nil {
  951. return fmt.Errorf("git commit: %s", stderr)
  952. }
  953. if _, stderr, err = process.GetManager().ExecDir(-1,
  954. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  955. "git", "push", "origin", "master"); err != nil {
  956. return fmt.Errorf("git push: %s", stderr)
  957. }
  958. return nil
  959. }
  960. // CreateRepoOptions contains the create repository options
  961. type CreateRepoOptions struct {
  962. Name string
  963. Description string
  964. Gitignores string
  965. License string
  966. Readme string
  967. IsPrivate bool
  968. IsMirror bool
  969. AutoInit bool
  970. }
  971. func getRepoInitFile(tp, name string) ([]byte, error) {
  972. cleanedName := strings.TrimLeft(name, "./")
  973. relPath := path.Join("options", tp, cleanedName)
  974. // Use custom file when available.
  975. customPath := path.Join(setting.CustomPath, relPath)
  976. if com.IsFile(customPath) {
  977. return ioutil.ReadFile(customPath)
  978. }
  979. switch tp {
  980. case "readme":
  981. return options.Readme(cleanedName)
  982. case "gitignore":
  983. return options.Gitignore(cleanedName)
  984. case "license":
  985. return options.License(cleanedName)
  986. case "label":
  987. return options.Labels(cleanedName)
  988. default:
  989. return []byte{}, fmt.Errorf("Invalid init file type")
  990. }
  991. }
  992. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  993. // Clone to temporary path and do the init commit.
  994. _, stderr, err := process.GetManager().Exec(
  995. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  996. "git", "clone", repoPath, tmpDir,
  997. )
  998. if err != nil {
  999. return fmt.Errorf("git clone: %v - %s", err, stderr)
  1000. }
  1001. // README
  1002. data, err := getRepoInitFile("readme", opts.Readme)
  1003. if err != nil {
  1004. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  1005. }
  1006. cloneLink := repo.CloneLink()
  1007. match := map[string]string{
  1008. "Name": repo.Name,
  1009. "Description": repo.Description,
  1010. "CloneURL.SSH": cloneLink.SSH,
  1011. "CloneURL.HTTPS": cloneLink.HTTPS,
  1012. }
  1013. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  1014. []byte(com.Expand(string(data), match)), 0644); err != nil {
  1015. return fmt.Errorf("write README.md: %v", err)
  1016. }
  1017. // .gitignore
  1018. if len(opts.Gitignores) > 0 {
  1019. var buf bytes.Buffer
  1020. names := strings.Split(opts.Gitignores, ",")
  1021. for _, name := range names {
  1022. data, err = getRepoInitFile("gitignore", name)
  1023. if err != nil {
  1024. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  1025. }
  1026. buf.WriteString("# ---> " + name + "\n")
  1027. buf.Write(data)
  1028. buf.WriteString("\n")
  1029. }
  1030. if buf.Len() > 0 {
  1031. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  1032. return fmt.Errorf("write .gitignore: %v", err)
  1033. }
  1034. }
  1035. }
  1036. // LICENSE
  1037. if len(opts.License) > 0 {
  1038. data, err = getRepoInitFile("license", opts.License)
  1039. if err != nil {
  1040. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  1041. }
  1042. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  1043. return fmt.Errorf("write LICENSE: %v", err)
  1044. }
  1045. }
  1046. return nil
  1047. }
  1048. // InitRepository initializes README and .gitignore if needed.
  1049. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  1050. // Somehow the directory could exist.
  1051. if com.IsExist(repoPath) {
  1052. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  1053. }
  1054. // Init bare new repository.
  1055. if err = git.InitRepository(repoPath, true); err != nil {
  1056. return fmt.Errorf("InitRepository: %v", err)
  1057. } else if err = createDelegateHooks(repoPath); err != nil {
  1058. return fmt.Errorf("createDelegateHooks: %v", err)
  1059. }
  1060. tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  1061. // Initialize repository according to user's choice.
  1062. if opts.AutoInit {
  1063. if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
  1064. return fmt.Errorf("Failed to create dir %s: %v", tmpDir, err)
  1065. }
  1066. defer os.RemoveAll(tmpDir)
  1067. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  1068. return fmt.Errorf("prepareRepoCommit: %v", err)
  1069. }
  1070. // Apply changes and commit.
  1071. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  1072. return fmt.Errorf("initRepoCommit: %v", err)
  1073. }
  1074. }
  1075. // Re-fetch the repository from database before updating it (else it would
  1076. // override changes that were done earlier with sql)
  1077. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  1078. return fmt.Errorf("getRepositoryByID: %v", err)
  1079. }
  1080. if !opts.AutoInit {
  1081. repo.IsBare = true
  1082. }
  1083. repo.DefaultBranch = "master"
  1084. if err = updateRepository(e, repo, false); err != nil {
  1085. return fmt.Errorf("updateRepository: %v", err)
  1086. }
  1087. return nil
  1088. }
  1089. var (
  1090. reservedRepoNames = []string{".", ".."}
  1091. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  1092. )
  1093. // IsUsableRepoName returns true when repository is usable
  1094. func IsUsableRepoName(name string) error {
  1095. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  1096. }
  1097. func createRepository(e *xorm.Session, doer, u *User, repo *Repository) (err error) {
  1098. if err = IsUsableRepoName(repo.Name); err != nil {
  1099. return err
  1100. }
  1101. has, err := isRepositoryExist(e, u, repo.Name)
  1102. if err != nil {
  1103. return fmt.Errorf("IsRepositoryExist: %v", err)
  1104. } else if has {
  1105. return ErrRepoAlreadyExist{u.Name, repo.Name}
  1106. }
  1107. if _, err = e.Insert(repo); err != nil {
  1108. return err
  1109. }
  1110. if err = deleteRepoRedirect(e, u.ID, repo.Name); err != nil {
  1111. return err
  1112. }
  1113. // insert units for repo
  1114. var units = make([]RepoUnit, 0, len(defaultRepoUnits))
  1115. for _, tp := range defaultRepoUnits {
  1116. if tp == UnitTypeIssues {
  1117. units = append(units, RepoUnit{
  1118. RepoID: repo.ID,
  1119. Type: tp,
  1120. Config: &IssuesConfig{EnableTimetracker: setting.Service.DefaultEnableTimetracking, AllowOnlyContributorsToTrackTime: setting.Service.DefaultAllowOnlyContributorsToTrackTime},
  1121. })
  1122. } else {
  1123. units = append(units, RepoUnit{
  1124. RepoID: repo.ID,
  1125. Type: tp,
  1126. })
  1127. }
  1128. }
  1129. if _, err = e.Insert(&units); err != nil {
  1130. return err
  1131. }
  1132. u.NumRepos++
  1133. // Remember visibility preference.
  1134. u.LastRepoVisibility = repo.IsPrivate
  1135. if err = updateUser(e, u); err != nil {
  1136. return fmt.Errorf("updateUser: %v", err)
  1137. }
  1138. // Give access to all members in owner team.
  1139. if u.IsOrganization() {
  1140. t, err := u.getOwnerTeam(e)
  1141. if err != nil {
  1142. return fmt.Errorf("getOwnerTeam: %v", err)
  1143. } else if err = t.addRepository(e, repo); err != nil {
  1144. return fmt.Errorf("addRepository: %v", err)
  1145. } else if err = prepareWebhooks(e, repo, HookEventRepository, &api.RepositoryPayload{
  1146. Action: api.HookRepoCreated,
  1147. Repository: repo.APIFormat(AccessModeOwner),
  1148. Organization: u.APIFormat(),
  1149. Sender: doer.APIFormat(),
  1150. }); err != nil {
  1151. return fmt.Errorf("prepareWebhooks: %v", err)
  1152. }
  1153. go HookQueue.Add(repo.ID)
  1154. } else {
  1155. // Organization automatically called this in addRepository method.
  1156. if err = repo.recalculateAccesses(e); err != nil {
  1157. return fmt.Errorf("recalculateAccesses: %v", err)
  1158. }
  1159. }
  1160. if err = watchRepo(e, doer.ID, repo.ID, true); err != nil {
  1161. return fmt.Errorf("watchRepo: %v", err)
  1162. } else if err = newRepoAction(e, u, repo); err != nil {
  1163. return fmt.Errorf("newRepoAction: %v", err)
  1164. }
  1165. return nil
  1166. }
  1167. // CreateRepository creates a repository for the user/organization u.
  1168. func CreateRepository(doer, u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  1169. if !u.CanCreateRepo() {
  1170. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  1171. }
  1172. repo := &Repository{
  1173. OwnerID: u.ID,
  1174. Owner: u,
  1175. Name: opts.Name,
  1176. LowerName: strings.ToLower(opts.Name),
  1177. Description: opts.Description,
  1178. IsPrivate: opts.IsPrivate,
  1179. }
  1180. sess := x.NewSession()
  1181. defer sess.Close()
  1182. if err = sess.Begin(); err != nil {
  1183. return nil, err
  1184. }
  1185. if err = createRepository(sess, doer, u, repo); err != nil {
  1186. return nil, err
  1187. }
  1188. // No need for init mirror.
  1189. if !opts.IsMirror {
  1190. repoPath := RepoPath(u.Name, repo.Name)
  1191. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  1192. if err2 := os.RemoveAll(repoPath); err2 != nil {
  1193. log.Error(4, "initRepository: %v", err)
  1194. return nil, fmt.Errorf(
  1195. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  1196. }
  1197. return nil, fmt.Errorf("initRepository: %v", err)
  1198. }
  1199. _, stderr, err := process.GetManager().ExecDir(-1,
  1200. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  1201. "git", "update-server-info")
  1202. if err != nil {
  1203. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  1204. }
  1205. }
  1206. return repo, sess.Commit()
  1207. }
  1208. func countRepositories(userID int64, private bool) int64 {
  1209. sess := x.Where("id > 0")
  1210. if userID > 0 {
  1211. sess.And("owner_id = ?", userID)
  1212. }
  1213. if !private {
  1214. sess.And("is_private=?", false)
  1215. }
  1216. count, err := sess.Count(new(Repository))
  1217. if err != nil {
  1218. log.Error(4, "countRepositories: %v", err)
  1219. }
  1220. return count
  1221. }
  1222. // CountRepositories returns number of repositories.
  1223. // Argument private only takes effect when it is false,
  1224. // set it true to count all repositories.
  1225. func CountRepositories(private bool) int64 {
  1226. return countRepositories(-1, private)
  1227. }
  1228. // CountUserRepositories returns number of repositories user owns.
  1229. // Argument private only takes effect when it is false,
  1230. // set it true to count all repositories.
  1231. func CountUserRepositories(userID int64, private bool) int64 {
  1232. return countRepositories(userID, private)
  1233. }
  1234. // RepoPath returns repository path by given user and repository name.
  1235. func RepoPath(userName, repoName string) string {
  1236. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1237. }
  1238. // TransferOwnership transfers all corresponding setting from old user to new one.
  1239. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1240. newOwner, err := GetUserByName(newOwnerName)
  1241. if err != nil {
  1242. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1243. }
  1244. // Check if new owner has repository with same name.
  1245. has, err := IsRepositoryExist(newOwner, repo.Name)
  1246. if err != nil {
  1247. return fmt.Errorf("IsRepositoryExist: %v", err)
  1248. } else if has {
  1249. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1250. }
  1251. sess := x.NewSession()
  1252. defer sess.Close()
  1253. if err = sess.Begin(); err != nil {
  1254. return fmt.Errorf("sess.Begin: %v", err)
  1255. }
  1256. owner := repo.Owner
  1257. // Note: we have to set value here to make sure recalculate accesses is based on
  1258. // new owner.
  1259. repo.OwnerID = newOwner.ID
  1260. repo.Owner = newOwner
  1261. // Update repository.
  1262. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1263. return fmt.Errorf("update owner: %v", err)
  1264. }
  1265. // Remove redundant collaborators.
  1266. collaborators, err := repo.getCollaborators(sess)
  1267. if err != nil {
  1268. return fmt.Errorf("getCollaborators: %v", err)
  1269. }
  1270. // Dummy object.
  1271. collaboration := &Collaboration{RepoID: repo.ID}
  1272. for _, c := range collaborators {
  1273. if c.ID != newOwner.ID {
  1274. isMember, err := newOwner.IsOrgMember(c.ID)
  1275. if err != nil {
  1276. return fmt.Errorf("IsOrgMember: %v", err)
  1277. } else if !isMember {
  1278. continue
  1279. }
  1280. }
  1281. collaboration.UserID = c.ID
  1282. if _, err = sess.Delete(collaboration); err != nil {
  1283. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1284. }
  1285. }
  1286. // Remove old team-repository relations.
  1287. if owner.IsOrganization() {
  1288. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1289. return fmt.Errorf("removeOrgRepo: %v", err)
  1290. }
  1291. }
  1292. if newOwner.IsOrganization() {
  1293. t, err := newOwner.getOwnerTeam(sess)
  1294. if err != nil {
  1295. return fmt.Errorf("getOwnerTeam: %v", err)
  1296. } else if err = t.addRepository(sess, repo); err != nil {
  1297. return fmt.Errorf("add to owner team: %v", err)
  1298. }
  1299. } else {
  1300. // Organization called this in addRepository method.
  1301. if err = repo.recalculateAccesses(sess); err != nil {
  1302. return fmt.Errorf("recalculateAccesses: %v", err)
  1303. }
  1304. }
  1305. // Update repository count.
  1306. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1307. return fmt.Errorf("increase new owner repository count: %v", err)
  1308. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1309. return fmt.Errorf("decrease old owner repository count: %v", err)
  1310. }
  1311. if err = watchRepo(sess, doer.ID, repo.ID, true); err != nil {
  1312. return fmt.Errorf("watchRepo: %v", err)
  1313. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1314. return fmt.Errorf("transferRepoAction: %v", err)
  1315. }
  1316. // Rename remote repository to new path and delete local copy.
  1317. dir := UserPath(newOwner.Name)
  1318. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  1319. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  1320. }
  1321. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1322. return fmt.Errorf("rename repository directory: %v", err)
  1323. }
  1324. RemoveAllWithNotice("Delete repository local copy", repo.LocalCopyPath())
  1325. // Rename remote wiki repository to new path and delete local copy.
  1326. wikiPath := WikiPath(owner.Name, repo.Name)
  1327. if com.IsExist(wikiPath) {
  1328. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1329. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1330. return fmt.Errorf("rename repository wiki: %v", err)
  1331. }
  1332. }
  1333. return sess.Commit()
  1334. }
  1335. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1336. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1337. oldRepoName = strings.ToLower(oldRepoName)
  1338. newRepoName = strings.ToLower(newRepoName)
  1339. if err = IsUsableRepoName(newRepoName); err != nil {
  1340. return err
  1341. }
  1342. has, err := IsRepositoryExist(u, newRepoName)
  1343. if err != nil {
  1344. return fmt.Errorf("IsRepositoryExist: %v", err)
  1345. } else if has {
  1346. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1347. }
  1348. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1349. if err != nil {
  1350. return fmt.Errorf("GetRepositoryByName: %v", err)
  1351. }
  1352. // Change repository directory name.
  1353. if err = os.Rename(repo.RepoPath(), RepoPath(u.Name, newRepoName)); err != nil {
  1354. return fmt.Errorf("rename repository directory: %v", err)
  1355. }
  1356. wikiPath := repo.WikiPath()
  1357. if com.IsExist(wikiPath) {
  1358. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1359. return fmt.Errorf("rename repository wiki: %v", err)
  1360. }
  1361. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1362. }
  1363. return nil
  1364. }
  1365. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1366. repos := make([]*Repository, 0, 10)
  1367. return repos, e.
  1368. Where("fork_id=?", forkID).
  1369. Find(&repos)
  1370. }
  1371. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1372. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1373. return getRepositoriesByForkID(x, forkID)
  1374. }
  1375. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1376. repo.LowerName = strings.ToLower(repo.Name)
  1377. if len(repo.Description) > 255 {
  1378. repo.Description = repo.Description[:255]
  1379. }
  1380. if len(repo.Website) > 255 {
  1381. repo.Website = repo.Website[:255]
  1382. }
  1383. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1384. return fmt.Errorf("update: %v", err)
  1385. }
  1386. if visibilityChanged {
  1387. if err = repo.getOwner(e); err != nil {
  1388. return fmt.Errorf("getOwner: %v", err)
  1389. }
  1390. if repo.Owner.IsOrganization() {
  1391. // Organization repository need to recalculate access table when visibility is changed.
  1392. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1393. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1394. }
  1395. }
  1396. // If repo has become private, we need to set its actions to private.
  1397. if repo.IsPrivate {
  1398. _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{
  1399. IsPrivate: true,
  1400. })
  1401. if err != nil {
  1402. return err
  1403. }
  1404. }
  1405. // Create/Remove git-daemon-export-ok for git-daemon...
  1406. daemonExportFile := path.Join(repo.RepoPath(), `git-daemon-export-ok`)
  1407. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1408. if err = os.Remove(daemonExportFile); err != nil {
  1409. log.Error(4, "Failed to remove %s: %v", daemonExportFile, err)
  1410. }
  1411. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1412. if f, err := os.Create(daemonExportFile); err != nil {
  1413. log.Error(4, "Failed to create %s: %v", daemonExportFile, err)
  1414. } else {
  1415. f.Close()
  1416. }
  1417. }
  1418. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1419. if err != nil {
  1420. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1421. }
  1422. for i := range forkRepos {
  1423. forkRepos[i].IsPrivate = repo.IsPrivate
  1424. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1425. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1426. }
  1427. }
  1428. if err = repo.updateSize(e); err != nil {
  1429. log.Error(4, "Failed to update size for repository: %v", err)
  1430. }
  1431. }
  1432. return nil
  1433. }
  1434. // UpdateRepository updates a repository
  1435. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1436. sess := x.NewSession()
  1437. defer sess.Close()
  1438. if err = sess.Begin(); err != nil {
  1439. return err
  1440. }
  1441. if err = updateRepository(sess, repo, visibilityChanged); err != nil {
  1442. return fmt.Errorf("updateRepository: %v", err)
  1443. }
  1444. return sess.Commit()
  1445. }
  1446. // UpdateRepositoryUnits updates a repository's units
  1447. func UpdateRepositoryUnits(repo *Repository, units []RepoUnit) (err error) {
  1448. sess := x.NewSession()
  1449. defer sess.Close()
  1450. if err = sess.Begin(); err != nil {
  1451. return err
  1452. }
  1453. if _, err = sess.Where("repo_id = ?", repo.ID).Delete(new(RepoUnit)); err != nil {
  1454. return err
  1455. }
  1456. if _, err = sess.Insert(units); err != nil {
  1457. return err
  1458. }
  1459. return sess.Commit()
  1460. }
  1461. // DeleteRepository deletes a repository for a user or organization.
  1462. func DeleteRepository(doer *User, uid, repoID int64) error {
  1463. // In case is a organization.
  1464. org, err := GetUserByID(uid)
  1465. if err != nil {
  1466. return err
  1467. }
  1468. if org.IsOrganization() {
  1469. if err = org.GetTeams(); err != nil {
  1470. return err
  1471. }
  1472. }
  1473. sess := x.NewSession()
  1474. defer sess.Close()
  1475. if err = sess.Begin(); err != nil {
  1476. return err
  1477. }
  1478. repo := &Repository{ID: repoID, OwnerID: uid}
  1479. has, err := sess.Get(repo)
  1480. if err != nil {
  1481. return err
  1482. } else if !has {
  1483. return ErrRepoNotExist{repoID, uid, "", ""}
  1484. }
  1485. if cnt, err := sess.ID(repoID).Delete(&Repository{}); err != nil {
  1486. return err
  1487. } else if cnt != 1 {
  1488. return ErrRepoNotExist{repoID, uid, "", ""}
  1489. }
  1490. if org.IsOrganization() {
  1491. for _, t := range org.Teams {
  1492. if !t.hasRepository(sess, repoID) {
  1493. continue
  1494. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1495. return err
  1496. }
  1497. }
  1498. }
  1499. if err = deleteBeans(sess,
  1500. &Access{RepoID: repo.ID},
  1501. &Action{RepoID: repo.ID},
  1502. &Watch{RepoID: repoID},
  1503. &Star{RepoID: repoID},
  1504. &Mirror{RepoID: repoID},
  1505. &Milestone{RepoID: repoID},
  1506. &Release{RepoID: repoID},
  1507. &Collaboration{RepoID: repoID},
  1508. &PullRequest{BaseRepoID: repoID},
  1509. &RepoUnit{RepoID: repoID},
  1510. &RepoRedirect{RedirectRepoID: repoID},
  1511. ); err != nil {
  1512. return fmt.Errorf("deleteBeans: %v", err)
  1513. }
  1514. // Delete comments and attachments.
  1515. issueIDs := make([]int64, 0, 25)
  1516. attachmentPaths := make([]string, 0, len(issueIDs))
  1517. if err = sess.
  1518. Table("issue").
  1519. Cols("id").
  1520. Where("repo_id=?", repoID).
  1521. Find(&issueIDs); err != nil {
  1522. return err
  1523. }
  1524. if len(issueIDs) > 0 {
  1525. if _, err = sess.In("issue_id", issueIDs).Delete(&Comment{}); err != nil {
  1526. return err
  1527. }
  1528. if _, err = sess.In("issue_id", issueIDs).Delete(&IssueUser{}); err != nil {
  1529. return err
  1530. }
  1531. attachments := make([]*Attachment, 0, 5)
  1532. if err = sess.
  1533. In("issue_id", issueIDs).
  1534. Find(&attachments); err != nil {
  1535. return err
  1536. }
  1537. for j := range attachments {
  1538. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1539. }
  1540. if _, err = sess.In("issue_id", issueIDs).Delete(&Attachment{}); err != nil {
  1541. return err
  1542. }
  1543. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1544. return err
  1545. }
  1546. }
  1547. if _, err = sess.Where("repo_id = ?", repoID).Delete(new(RepoUnit)); err != nil {
  1548. return err
  1549. }
  1550. if repo.IsFork {
  1551. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1552. return fmt.Errorf("decrease fork count: %v", err)
  1553. }
  1554. }
  1555. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1556. return err
  1557. }
  1558. // FIXME: Remove repository files should be executed after transaction succeed.
  1559. repoPath := repo.repoPath(sess)
  1560. removeAllWithNotice(sess, "Delete repository files", repoPath)
  1561. repo.deleteWiki(sess)
  1562. // Remove attachment files.
  1563. for i := range attachmentPaths {
  1564. removeAllWithNotice(sess, "Delete attachment", attachmentPaths[i])
  1565. }
  1566. // Remove LFS objects
  1567. var lfsObjects []*LFSMetaObject
  1568. if err = sess.Where("repository_id=?", repoID).Find(&lfsObjects); err != nil {
  1569. return err
  1570. }
  1571. for _, v := range lfsObjects {
  1572. count, err := sess.Count(&LFSMetaObject{Oid: v.Oid})
  1573. if err != nil {
  1574. return err
  1575. }
  1576. if count > 1 {
  1577. continue
  1578. }
  1579. oidPath := filepath.Join(v.Oid[0:2], v.Oid[2:4], v.Oid[4:len(v.Oid)])
  1580. err = os.Remove(filepath.Join(setting.LFS.ContentPath, oidPath))
  1581. if err != nil {
  1582. return err
  1583. }
  1584. }
  1585. if _, err := sess.Delete(&LFSMetaObject{RepositoryID: repoID}); err != nil {
  1586. return err
  1587. }
  1588. if repo.NumForks > 0 {
  1589. if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1590. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1591. }
  1592. }
  1593. if err = sess.Commit(); err != nil {
  1594. return fmt.Errorf("Commit: %v", err)
  1595. }
  1596. if org.IsOrganization() {
  1597. if err = PrepareWebhooks(repo, HookEventRepository, &api.RepositoryPayload{
  1598. Action: api.HookRepoDeleted,
  1599. Repository: repo.APIFormat(AccessModeOwner),
  1600. Organization: org.APIFormat(),
  1601. Sender: doer.APIFormat(),
  1602. }); err != nil {
  1603. return err
  1604. }
  1605. go HookQueue.Add(repo.ID)
  1606. }
  1607. DeleteRepoFromIndexer(repo)
  1608. return nil
  1609. }
  1610. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
  1611. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
  1612. var repo Repository
  1613. has, err := x.Select("repository.*").
  1614. Join("INNER", "user", "`user`.id = repository.owner_id").
  1615. Where("repository.lower_name = ?", strings.ToLower(repoName)).
  1616. And("`user`.lower_name = ?", strings.ToLower(ownerName)).
  1617. Get(&repo)
  1618. if err != nil {
  1619. return nil, err
  1620. } else if !has {
  1621. return nil, ErrRepoNotExist{0, 0, ownerName, repoName}
  1622. }
  1623. return &repo, nil
  1624. }
  1625. // GetRepositoryByName returns the repository by given name under user if exists.
  1626. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1627. repo := &Repository{
  1628. OwnerID: ownerID,
  1629. LowerName: strings.ToLower(name),
  1630. }
  1631. has, err := x.Get(repo)
  1632. if err != nil {
  1633. return nil, err
  1634. } else if !has {
  1635. return nil, ErrRepoNotExist{0, ownerID, "", name}
  1636. }
  1637. return repo, err
  1638. }
  1639. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1640. repo := new(Repository)
  1641. has, err := e.ID(id).Get(repo)
  1642. if err != nil {
  1643. return nil, err
  1644. } else if !has {
  1645. return nil, ErrRepoNotExist{id, 0, "", ""}
  1646. }
  1647. return repo, nil
  1648. }
  1649. // GetRepositoryByID returns the repository by given id if exists.
  1650. func GetRepositoryByID(id int64) (*Repository, error) {
  1651. return getRepositoryByID(x, id)
  1652. }
  1653. // GetUserRepositories returns a list of repositories of given user.
  1654. func GetUserRepositories(userID int64, private bool, page, pageSize int, orderBy string) ([]*Repository, error) {
  1655. if len(orderBy) == 0 {
  1656. orderBy = "updated_unix DESC"
  1657. }
  1658. sess := x.
  1659. Where("owner_id = ?", userID).
  1660. OrderBy(orderBy)
  1661. if !private {
  1662. sess.And("is_private=?", false)
  1663. }
  1664. if page <= 0 {
  1665. page = 1
  1666. }
  1667. sess.Limit(pageSize, (page-1)*pageSize)
  1668. repos := make([]*Repository, 0, pageSize)
  1669. return repos, sess.Find(&repos)
  1670. }
  1671. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
  1672. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1673. repos := make([]*Repository, 0, 10)
  1674. return repos, x.
  1675. Where("owner_id = ?", userID).
  1676. And("is_mirror = ?", true).
  1677. Find(&repos)
  1678. }
  1679. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1680. return e.Count(&Repository{OwnerID: u.ID})
  1681. }
  1682. func getPublicRepositoryCount(e Engine, u *User) (int64, error) {
  1683. return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
  1684. }
  1685. func getPrivateRepositoryCount(e Engine, u *User) (int64, error) {
  1686. return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
  1687. }
  1688. // GetRepositoryCount returns the total number of repositories of user.
  1689. func GetRepositoryCount(u *User) (int64, error) {
  1690. return getRepositoryCount(x, u)
  1691. }
  1692. // GetPublicRepositoryCount returns the total number of public repositories of user.
  1693. func GetPublicRepositoryCount(u *User) (int64, error) {
  1694. return getPublicRepositoryCount(x, u)
  1695. }
  1696. // GetPrivateRepositoryCount returns the total number of private repositories of user.
  1697. func GetPrivateRepositoryCount(u *User) (int64, error) {
  1698. return getPrivateRepositoryCount(x, u)
  1699. }
  1700. // DeleteRepositoryArchives deletes all repositories' archives.
  1701. func DeleteRepositoryArchives() error {
  1702. return x.
  1703. Where("id > 0").
  1704. Iterate(new(Repository),
  1705. func(idx int, bean interface{}) error {
  1706. repo := bean.(*Repository)
  1707. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1708. })
  1709. }
  1710. // DeleteOldRepositoryArchives deletes old repository archives.
  1711. func DeleteOldRepositoryArchives() {
  1712. if !taskStatusTable.StartIfNotRunning(archiveCleanup) {
  1713. return
  1714. }
  1715. defer taskStatusTable.Stop(archiveCleanup)
  1716. log.Trace("Doing: ArchiveCleanup")
  1717. if err := x.Where("id > 0").Iterate(new(Repository), deleteOldRepositoryArchives); err != nil {
  1718. log.Error(4, "ArchiveClean: %v", err)
  1719. }
  1720. }
  1721. func deleteOldRepositoryArchives(idx int, bean interface{}) error {
  1722. repo := bean.(*Repository)
  1723. basePath := filepath.Join(repo.RepoPath(), "archives")
  1724. for _, ty := range []string{"zip", "targz"} {
  1725. path := filepath.Join(basePath, ty)
  1726. file, err := os.Open(path)
  1727. if err != nil {
  1728. if !os.IsNotExist(err) {
  1729. log.Warn("Unable to open directory %s: %v", path, err)
  1730. return err
  1731. }
  1732. // If the directory doesn't exist, that's okay.
  1733. continue
  1734. }
  1735. files, err := file.Readdir(0)
  1736. file.Close()
  1737. if err != nil {
  1738. log.Warn("Unable to read directory %s: %v", path, err)
  1739. return err
  1740. }
  1741. minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
  1742. for _, info := range files {
  1743. if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
  1744. toDelete := filepath.Join(path, info.Name())
  1745. // This is a best-effort purge, so we do not check error codes to confirm removal.
  1746. if err = os.Remove(toDelete); err != nil {
  1747. log.Trace("Unable to delete %s, but proceeding: %v", toDelete, err)
  1748. }
  1749. }
  1750. }
  1751. }
  1752. return nil
  1753. }
  1754. func gatherMissingRepoRecords() ([]*Repository, error) {
  1755. repos := make([]*Repository, 0, 10)
  1756. if err := x.
  1757. Where("id > 0").
  1758. Iterate(new(Repository),
  1759. func(idx int, bean interface{}) error {
  1760. repo := bean.(*Repository)
  1761. if !com.IsDir(repo.RepoPath()) {
  1762. repos = append(repos, repo)
  1763. }
  1764. return nil
  1765. }); err != nil {
  1766. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1767. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1768. }
  1769. }
  1770. return repos, nil
  1771. }
  1772. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1773. func DeleteMissingRepositories(doer *User) error {
  1774. repos, err := gatherMissingRepoRecords()
  1775. if err != nil {
  1776. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1777. }
  1778. if len(repos) == 0 {
  1779. return nil
  1780. }
  1781. for _, repo := range repos {
  1782. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1783. if err := DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  1784. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1785. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1786. }
  1787. }
  1788. }
  1789. return nil
  1790. }
  1791. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1792. func ReinitMissingRepositories() error {
  1793. repos, err := gatherMissingRepoRecords()
  1794. if err != nil {
  1795. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1796. }
  1797. if len(repos) == 0 {
  1798. return nil
  1799. }
  1800. for _, repo := range repos {
  1801. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1802. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1803. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1804. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1805. }
  1806. }
  1807. }
  1808. return nil
  1809. }
  1810. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1811. // to make sure the binary and custom conf path are up-to-date.
  1812. func SyncRepositoryHooks() error {
  1813. return x.Where("id > 0").Iterate(new(Repository),
  1814. func(idx int, bean interface{}) error {
  1815. if err := createDelegateHooks(bean.(*Repository).RepoPath()); err != nil {
  1816. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1817. }
  1818. if bean.(*Repository).HasWiki() {
  1819. if err := createDelegateHooks(bean.(*Repository).WikiPath()); err != nil {
  1820. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1821. }
  1822. }
  1823. return nil
  1824. })
  1825. }
  1826. // Prevent duplicate running tasks.
  1827. var taskStatusTable = sync.NewStatusTable()
  1828. const (
  1829. mirrorUpdate = "mirror_update"
  1830. gitFsck = "git_fsck"
  1831. checkRepos = "check_repos"
  1832. archiveCleanup = "archive_cleanup"
  1833. )
  1834. // GitFsck calls 'git fsck' to check repository health.
  1835. func GitFsck() {
  1836. if !taskStatusTable.StartIfNotRunning(gitFsck) {
  1837. return
  1838. }
  1839. defer taskStatusTable.Stop(gitFsck)
  1840. log.Trace("Doing: GitFsck")
  1841. if err := x.
  1842. Where("id>0").BufferSize(setting.IterateBufferSize).
  1843. Iterate(new(Repository),
  1844. func(idx int, bean interface{}) error {
  1845. repo := bean.(*Repository)
  1846. repoPath := repo.RepoPath()
  1847. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1848. desc := fmt.Sprintf("Failed to health check repository (%s): %v", repoPath, err)
  1849. log.Warn(desc)
  1850. if err = CreateRepositoryNotice(desc); err != nil {
  1851. log.Error(4, "CreateRepositoryNotice: %v", err)
  1852. }
  1853. }
  1854. return nil
  1855. }); err != nil {
  1856. log.Error(4, "GitFsck: %v", err)
  1857. }
  1858. }
  1859. // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
  1860. func GitGcRepos() error {
  1861. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1862. return x.
  1863. Where("id > 0").BufferSize(setting.IterateBufferSize).
  1864. Iterate(new(Repository),
  1865. func(idx int, bean interface{}) error {
  1866. repo := bean.(*Repository)
  1867. if err := repo.GetOwner(); err != nil {
  1868. return err
  1869. }
  1870. _, stderr, err := process.GetManager().ExecDir(
  1871. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1872. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1873. "git", args...)
  1874. if err != nil {
  1875. return fmt.Errorf("%v: %v", err, stderr)
  1876. }
  1877. return nil
  1878. })
  1879. }
  1880. type repoChecker struct {
  1881. querySQL, correctSQL string
  1882. desc string
  1883. }
  1884. func repoStatsCheck(checker *repoChecker) {
  1885. results, err := x.Query(checker.querySQL)
  1886. if err != nil {
  1887. log.Error(4, "Select %s: %v", checker.desc, err)
  1888. return
  1889. }
  1890. for _, result := range results {
  1891. id := com.StrTo(result["id"]).MustInt64()
  1892. log.Trace("Updating %s: %d", checker.desc, id)
  1893. _, err = x.Exec(checker.correctSQL, id, id)
  1894. if err != nil {
  1895. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1896. }
  1897. }
  1898. }
  1899. // CheckRepoStats checks the repository stats
  1900. func CheckRepoStats() {
  1901. if !taskStatusTable.StartIfNotRunning(checkRepos) {
  1902. return
  1903. }
  1904. defer taskStatusTable.Stop(checkRepos)
  1905. log.Trace("Doing: CheckRepoStats")
  1906. checkers := []*repoChecker{
  1907. // Repository.NumWatches
  1908. {
  1909. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1910. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1911. "repository count 'num_watches'",
  1912. },
  1913. // Repository.NumStars
  1914. {
  1915. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1916. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1917. "repository count 'num_stars'",
  1918. },
  1919. // Label.NumIssues
  1920. {
  1921. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1922. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1923. "label count 'num_issues'",
  1924. },
  1925. // User.NumRepos
  1926. {
  1927. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1928. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1929. "user count 'num_repos'",
  1930. },
  1931. // Issue.NumComments
  1932. {
  1933. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1934. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1935. "issue count 'num_comments'",
  1936. },
  1937. }
  1938. for i := range checkers {
  1939. repoStatsCheck(checkers[i])
  1940. }
  1941. // ***** START: Repository.NumClosedIssues *****
  1942. desc := "repository count 'num_closed_issues'"
  1943. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false)
  1944. if err != nil {
  1945. log.Error(4, "Select %s: %v", desc, err)
  1946. } else {
  1947. for _, result := range results {
  1948. id := com.StrTo(result["id"]).MustInt64()
  1949. log.Trace("Updating %s: %d", desc, id)
  1950. _, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id)
  1951. if err != nil {
  1952. log.Error(4, "Update %s[%d]: %v", desc, id, err)
  1953. }
  1954. }
  1955. }
  1956. // ***** END: Repository.NumClosedIssues *****
  1957. // FIXME: use checker when stop supporting old fork repo format.
  1958. // ***** START: Repository.NumForks *****
  1959. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1960. if err != nil {
  1961. log.Error(4, "Select repository count 'num_forks': %v", err)
  1962. } else {
  1963. for _, result := range results {
  1964. id := com.StrTo(result["id"]).MustInt64()
  1965. log.Trace("Updating repository count 'num_forks': %d", id)
  1966. repo, err := GetRepositoryByID(id)
  1967. if err != nil {
  1968. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1969. continue
  1970. }
  1971. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1972. if err != nil {
  1973. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1974. continue
  1975. }
  1976. repo.NumForks = int(parseCountResult(rawResult))
  1977. if err = UpdateRepository(repo, false); err != nil {
  1978. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1979. continue
  1980. }
  1981. }
  1982. }
  1983. // ***** END: Repository.NumForks *****
  1984. }
  1985. // ___________ __
  1986. // \_ _____/__________| | __
  1987. // | __)/ _ \_ __ \ |/ /
  1988. // | \( <_> ) | \/ <
  1989. // \___ / \____/|__| |__|_ \
  1990. // \/ \/
  1991. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1992. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1993. repo := new(Repository)
  1994. has, _ := x.
  1995. Where("owner_id=? AND fork_id=?", ownerID, repoID).
  1996. Get(repo)
  1997. return repo, has
  1998. }
  1999. // ForkRepository forks a repository
  2000. func ForkRepository(doer, u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  2001. forkedRepo, err := oldRepo.GetUserFork(u.ID)
  2002. if err != nil {
  2003. return nil, err
  2004. }
  2005. if forkedRepo != nil {
  2006. return nil, ErrRepoAlreadyExist{
  2007. Uname: u.Name,
  2008. Name: forkedRepo.Name,
  2009. }
  2010. }
  2011. repo := &Repository{
  2012. OwnerID: u.ID,
  2013. Owner: u,
  2014. Name: name,
  2015. LowerName: strings.ToLower(name),
  2016. Description: desc,
  2017. DefaultBranch: oldRepo.DefaultBranch,
  2018. IsPrivate: oldRepo.IsPrivate,
  2019. IsFork: true,
  2020. ForkID: oldRepo.ID,
  2021. }
  2022. sess := x.NewSession()
  2023. defer sess.Close()
  2024. if err = sess.Begin(); err != nil {
  2025. return nil, err
  2026. }
  2027. if err = createRepository(sess, doer, u, repo); err != nil {
  2028. return nil, err
  2029. }
  2030. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  2031. return nil, err
  2032. }
  2033. repoPath := RepoPath(u.Name, repo.Name)
  2034. _, stderr, err := process.GetManager().ExecTimeout(10*time.Minute,
  2035. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  2036. "git", "clone", "--bare", oldRepo.RepoPath(), repoPath)
  2037. if err != nil {
  2038. return nil, fmt.Errorf("git clone: %v", stderr)
  2039. }
  2040. _, stderr, err = process.GetManager().ExecDir(-1,
  2041. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  2042. "git", "update-server-info")
  2043. if err != nil {
  2044. return nil, fmt.Errorf("git update-server-info: %v", stderr)
  2045. }
  2046. if err = createDelegateHooks(repoPath); err != nil {
  2047. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2048. }
  2049. //Commit repo to get Fork ID
  2050. err = sess.Commit()
  2051. if err != nil {
  2052. return nil, err
  2053. }
  2054. if err = repo.UpdateSize(); err != nil {
  2055. log.Error(4, "Failed to update size for repository: %v", err)
  2056. }
  2057. // Copy LFS meta objects in new session
  2058. sess2 := x.NewSession()
  2059. defer sess2.Close()
  2060. if err = sess2.Begin(); err != nil {
  2061. return nil, err
  2062. }
  2063. var lfsObjects []*LFSMetaObject
  2064. if err = sess2.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
  2065. return nil, err
  2066. }
  2067. for _, v := range lfsObjects {
  2068. v.ID = 0
  2069. v.RepositoryID = repo.ID
  2070. if _, err = sess2.Insert(v); err != nil {
  2071. return nil, err
  2072. }
  2073. }
  2074. return repo, sess2.Commit()
  2075. }
  2076. // GetForks returns all the forks of the repository
  2077. func (repo *Repository) GetForks() ([]*Repository, error) {
  2078. forks := make([]*Repository, 0, repo.NumForks)
  2079. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2080. }
  2081. // GetUserFork return user forked repository from this repository, if not forked return nil
  2082. func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
  2083. var forkedRepo Repository
  2084. has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
  2085. if err != nil {
  2086. return nil, err
  2087. }
  2088. if !has {
  2089. return nil, nil
  2090. }
  2091. return &forkedRepo, nil
  2092. }