You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 72 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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>
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
8 years ago
10 years ago
11 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
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
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
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
9 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 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>
8 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 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
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
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
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
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
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
9 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431
  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. }
  373. return &RepoUnit{
  374. Type: tp,
  375. Config: new(UnitConfig),
  376. }
  377. }
  378. // GetUnit returns a RepoUnit object
  379. func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) {
  380. if err := repo.getUnits(x); err != nil {
  381. return nil, err
  382. }
  383. for _, unit := range repo.Units {
  384. if unit.Type == tp {
  385. return unit, nil
  386. }
  387. }
  388. return nil, ErrUnitNotExist
  389. }
  390. func (repo *Repository) getOwner(e Engine) (err error) {
  391. if repo.Owner != nil {
  392. return nil
  393. }
  394. repo.Owner, err = getUserByID(e, repo.OwnerID)
  395. return err
  396. }
  397. // GetOwner returns the repository owner
  398. func (repo *Repository) GetOwner() error {
  399. return repo.getOwner(x)
  400. }
  401. func (repo *Repository) mustOwner(e Engine) *User {
  402. if err := repo.getOwner(e); err != nil {
  403. return &User{
  404. Name: "error",
  405. FullName: err.Error(),
  406. }
  407. }
  408. return repo.Owner
  409. }
  410. // ComposeMetas composes a map of metas for rendering external issue tracker URL.
  411. func (repo *Repository) ComposeMetas() map[string]string {
  412. unit, err := repo.GetUnit(UnitTypeExternalTracker)
  413. if err != nil {
  414. return nil
  415. }
  416. if repo.ExternalMetas == nil {
  417. repo.ExternalMetas = map[string]string{
  418. "format": unit.ExternalTrackerConfig().ExternalTrackerFormat,
  419. "user": repo.MustOwner().Name,
  420. "repo": repo.Name,
  421. }
  422. switch unit.ExternalTrackerConfig().ExternalTrackerStyle {
  423. case markup.IssueNameStyleAlphanumeric:
  424. repo.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
  425. default:
  426. repo.ExternalMetas["style"] = markup.IssueNameStyleNumeric
  427. }
  428. }
  429. return repo.ExternalMetas
  430. }
  431. // DeleteWiki removes the actual and local copy of repository wiki.
  432. func (repo *Repository) DeleteWiki() error {
  433. return repo.deleteWiki(x)
  434. }
  435. func (repo *Repository) deleteWiki(e Engine) error {
  436. wikiPaths := []string{repo.WikiPath(), repo.LocalWikiPath()}
  437. for _, wikiPath := range wikiPaths {
  438. removeAllWithNotice(e, "Delete repository wiki", wikiPath)
  439. }
  440. _, err := e.Where("repo_id = ?", repo.ID).And("type = ?", UnitTypeWiki).Delete(new(RepoUnit))
  441. return err
  442. }
  443. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  444. if err = repo.getOwner(e); err != nil {
  445. return nil, err
  446. }
  447. accesses := make([]*Access, 0, 10)
  448. if err = e.
  449. Where("repo_id = ? AND mode >= ?", repo.ID, AccessModeWrite).
  450. Find(&accesses); err != nil {
  451. return nil, err
  452. }
  453. // Leave a seat for owner itself to append later, but if owner is an organization
  454. // and just waste 1 unit is cheaper than re-allocate memory once.
  455. users := make([]*User, 0, len(accesses)+1)
  456. if len(accesses) > 0 {
  457. userIDs := make([]int64, len(accesses))
  458. for i := 0; i < len(accesses); i++ {
  459. userIDs[i] = accesses[i].UserID
  460. }
  461. if err = e.In("id", userIDs).Find(&users); err != nil {
  462. return nil, err
  463. }
  464. }
  465. if !repo.Owner.IsOrganization() {
  466. users = append(users, repo.Owner)
  467. }
  468. return users, nil
  469. }
  470. // GetAssignees returns all users that have write access and can be assigned to issues
  471. // of the repository,
  472. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  473. return repo.getAssignees(x)
  474. }
  475. // GetAssigneeByID returns the user that has write access of repository by given ID.
  476. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  477. return GetAssigneeByID(repo, userID)
  478. }
  479. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  480. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  481. return GetMilestoneByRepoID(repo.ID, milestoneID)
  482. }
  483. // IssueStats returns number of open and closed repository issues by given filter mode.
  484. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  485. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  486. }
  487. // GetMirror sets the repository mirror, returns an error upon failure
  488. func (repo *Repository) GetMirror() (err error) {
  489. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  490. return err
  491. }
  492. // GetBaseRepo populates repo.BaseRepo for a fork repository and
  493. // returns an error on failure (NOTE: no error is returned for
  494. // non-fork repositories, and BaseRepo will be left untouched)
  495. func (repo *Repository) GetBaseRepo() (err error) {
  496. if !repo.IsFork {
  497. return nil
  498. }
  499. repo.BaseRepo, err = GetRepositoryByID(repo.ForkID)
  500. return err
  501. }
  502. func (repo *Repository) repoPath(e Engine) string {
  503. return RepoPath(repo.mustOwner(e).Name, repo.Name)
  504. }
  505. // RepoPath returns the repository path
  506. func (repo *Repository) RepoPath() string {
  507. return repo.repoPath(x)
  508. }
  509. // GitConfigPath returns the path to a repository's git config/ directory
  510. func GitConfigPath(repoPath string) string {
  511. return filepath.Join(repoPath, "config")
  512. }
  513. // GitConfigPath returns the repository git config path
  514. func (repo *Repository) GitConfigPath() string {
  515. return GitConfigPath(repo.RepoPath())
  516. }
  517. // RelLink returns the repository relative link
  518. func (repo *Repository) RelLink() string {
  519. return "/" + repo.FullName()
  520. }
  521. // Link returns the repository link
  522. func (repo *Repository) Link() string {
  523. return setting.AppSubURL + "/" + repo.FullName()
  524. }
  525. // ComposeCompareURL returns the repository comparison URL
  526. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  527. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  528. }
  529. // HasAccess returns true when user has access to this repository
  530. func (repo *Repository) HasAccess(u *User) bool {
  531. has, _ := HasAccess(u.ID, repo, AccessModeRead)
  532. return has
  533. }
  534. // UpdateDefaultBranch updates the default branch
  535. func (repo *Repository) UpdateDefaultBranch() error {
  536. _, err := x.ID(repo.ID).Cols("default_branch").Update(repo)
  537. return err
  538. }
  539. // IsOwnedBy returns true when user owns this repository
  540. func (repo *Repository) IsOwnedBy(userID int64) bool {
  541. return repo.OwnerID == userID
  542. }
  543. func (repo *Repository) updateSize(e Engine) error {
  544. repoInfoSize, err := git.GetRepoSize(repo.RepoPath())
  545. if err != nil {
  546. return fmt.Errorf("UpdateSize: %v", err)
  547. }
  548. repo.Size = repoInfoSize.Size + repoInfoSize.SizePack
  549. _, err = e.ID(repo.ID).Cols("size").Update(repo)
  550. return err
  551. }
  552. // UpdateSize updates the repository size, calculating it using git.GetRepoSize
  553. func (repo *Repository) UpdateSize() error {
  554. return repo.updateSize(x)
  555. }
  556. // CanBeForked returns true if repository meets the requirements of being forked.
  557. func (repo *Repository) CanBeForked() bool {
  558. return !repo.IsBare && repo.UnitEnabled(UnitTypeCode)
  559. }
  560. // CanUserFork returns true if specified user can fork repository.
  561. func (repo *Repository) CanUserFork(user *User) (bool, error) {
  562. if user == nil {
  563. return false, nil
  564. }
  565. if repo.OwnerID != user.ID && !user.HasForkedRepo(repo.ID) {
  566. return true, nil
  567. }
  568. if err := user.GetOwnedOrganizations(); err != nil {
  569. return false, err
  570. }
  571. for _, org := range user.OwnedOrgs {
  572. if repo.OwnerID != org.ID && !org.HasForkedRepo(repo.ID) {
  573. return true, nil
  574. }
  575. }
  576. return false, nil
  577. }
  578. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  579. func (repo *Repository) CanEnablePulls() bool {
  580. return !repo.IsMirror && !repo.IsBare
  581. }
  582. // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  583. func (repo *Repository) AllowsPulls() bool {
  584. return repo.CanEnablePulls() && repo.UnitEnabled(UnitTypePullRequests)
  585. }
  586. // CanEnableEditor returns true if repository meets the requirements of web editor.
  587. func (repo *Repository) CanEnableEditor() bool {
  588. return !repo.IsMirror
  589. }
  590. // GetWriters returns all users that have write access to the repository.
  591. func (repo *Repository) GetWriters() (_ []*User, err error) {
  592. return repo.getUsersWithAccessMode(x, AccessModeWrite)
  593. }
  594. // getUsersWithAccessMode returns users that have at least given access mode to the repository.
  595. func (repo *Repository) getUsersWithAccessMode(e Engine, mode AccessMode) (_ []*User, err error) {
  596. if err = repo.getOwner(e); err != nil {
  597. return nil, err
  598. }
  599. accesses := make([]*Access, 0, 10)
  600. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  601. return nil, err
  602. }
  603. // Leave a seat for owner itself to append later, but if owner is an organization
  604. // and just waste 1 unit is cheaper than re-allocate memory once.
  605. users := make([]*User, 0, len(accesses)+1)
  606. if len(accesses) > 0 {
  607. userIDs := make([]int64, len(accesses))
  608. for i := 0; i < len(accesses); i++ {
  609. userIDs[i] = accesses[i].UserID
  610. }
  611. if err = e.In("id", userIDs).Find(&users); err != nil {
  612. return nil, err
  613. }
  614. }
  615. if !repo.Owner.IsOrganization() {
  616. users = append(users, repo.Owner)
  617. }
  618. return users, nil
  619. }
  620. // NextIssueIndex returns the next issue index
  621. // FIXME: should have a mutex to prevent producing same index for two issues that are created
  622. // closely enough.
  623. func (repo *Repository) NextIssueIndex() int64 {
  624. return int64(repo.NumIssues+repo.NumPulls) + 1
  625. }
  626. var (
  627. descPattern = regexp.MustCompile(`https?://\S+`)
  628. )
  629. // DescriptionHTML does special handles to description and return HTML string.
  630. func (repo *Repository) DescriptionHTML() template.HTML {
  631. sanitize := func(s string) string {
  632. return fmt.Sprintf(`<a href="%[1]s" target="_blank" rel="noopener">%[1]s</a>`, s)
  633. }
  634. return template.HTML(descPattern.ReplaceAllStringFunc(markup.Sanitize(repo.Description), sanitize))
  635. }
  636. // LocalCopyPath returns the local repository copy path.
  637. func LocalCopyPath() string {
  638. if filepath.IsAbs(setting.Repository.Local.LocalCopyPath) {
  639. return setting.Repository.Local.LocalCopyPath
  640. }
  641. return path.Join(setting.AppDataPath, setting.Repository.Local.LocalCopyPath)
  642. }
  643. // LocalCopyPath returns the local repository copy path for the given repo.
  644. func (repo *Repository) LocalCopyPath() string {
  645. return path.Join(LocalCopyPath(), com.ToStr(repo.ID))
  646. }
  647. // UpdateLocalCopyBranch pulls latest changes of given branch from repoPath to localPath.
  648. // It creates a new clone if local copy does not exist.
  649. // This function checks out target branch by default, it is safe to assume subsequent
  650. // operations are operating against target branch when caller has confidence for no race condition.
  651. func UpdateLocalCopyBranch(repoPath, localPath, branch string) error {
  652. if !com.IsExist(localPath) {
  653. if err := git.Clone(repoPath, localPath, git.CloneRepoOptions{
  654. Timeout: time.Duration(setting.Git.Timeout.Clone) * time.Second,
  655. Branch: branch,
  656. }); err != nil {
  657. return fmt.Errorf("git clone %s: %v", branch, err)
  658. }
  659. } else {
  660. if err := git.Checkout(localPath, git.CheckoutOptions{
  661. Branch: branch,
  662. }); err != nil {
  663. return fmt.Errorf("git checkout %s: %v", branch, err)
  664. }
  665. _, err := git.NewCommand("fetch", "origin").RunInDir(localPath)
  666. if err != nil {
  667. return fmt.Errorf("git fetch origin: %v", err)
  668. }
  669. if len(branch) > 0 {
  670. if err := git.ResetHEAD(localPath, true, "origin/"+branch); err != nil {
  671. return fmt.Errorf("git reset --hard origin/%s: %v", branch, err)
  672. }
  673. }
  674. }
  675. return nil
  676. }
  677. // UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
  678. func (repo *Repository) UpdateLocalCopyBranch(branch string) error {
  679. return UpdateLocalCopyBranch(repo.RepoPath(), repo.LocalCopyPath(), branch)
  680. }
  681. // PatchPath returns corresponding patch file path of repository by given issue ID.
  682. func (repo *Repository) PatchPath(index int64) (string, error) {
  683. if err := repo.GetOwner(); err != nil {
  684. return "", err
  685. }
  686. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  687. }
  688. // SavePatch saves patch data to corresponding location by given issue ID.
  689. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  690. patchPath, err := repo.PatchPath(index)
  691. if err != nil {
  692. return fmt.Errorf("PatchPath: %v", err)
  693. }
  694. dir := filepath.Dir(patchPath)
  695. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  696. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  697. }
  698. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  699. return fmt.Errorf("WriteFile: %v", err)
  700. }
  701. return nil
  702. }
  703. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  704. has, err := e.Get(&Repository{
  705. OwnerID: u.ID,
  706. LowerName: strings.ToLower(repoName),
  707. })
  708. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  709. }
  710. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  711. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  712. return isRepositoryExist(x, u, repoName)
  713. }
  714. // CloneLink represents different types of clone URLs of repository.
  715. type CloneLink struct {
  716. SSH string
  717. HTTPS string
  718. Git string
  719. }
  720. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  721. func ComposeHTTPSCloneURL(owner, repo string) string {
  722. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, owner, repo)
  723. }
  724. func (repo *Repository) cloneLink(isWiki bool) *CloneLink {
  725. repoName := repo.Name
  726. if isWiki {
  727. repoName += ".wiki"
  728. }
  729. sshUser := setting.RunUser
  730. if setting.SSH.StartBuiltinServer {
  731. sshUser = setting.SSH.BuiltinServerUser
  732. }
  733. repo.Owner = repo.MustOwner()
  734. cl := new(CloneLink)
  735. if setting.SSH.Port != 22 {
  736. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", sshUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  737. } else if setting.Repository.UseCompatSSHURI {
  738. cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  739. } else {
  740. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  741. }
  742. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  743. return cl
  744. }
  745. // CloneLink returns clone URLs of repository.
  746. func (repo *Repository) CloneLink() (cl *CloneLink) {
  747. return repo.cloneLink(false)
  748. }
  749. // MigrateRepoOptions contains the repository migrate options
  750. type MigrateRepoOptions struct {
  751. Name string
  752. Description string
  753. IsPrivate bool
  754. IsMirror bool
  755. RemoteAddr string
  756. }
  757. /*
  758. GitHub, GitLab, Gogs: *.wiki.git
  759. BitBucket: *.git/wiki
  760. */
  761. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  762. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  763. // Otherwise, it returns an empty string.
  764. func wikiRemoteURL(remote string) string {
  765. remote = strings.TrimSuffix(remote, ".git")
  766. for _, suffix := range commonWikiURLSuffixes {
  767. wikiURL := remote + suffix
  768. if git.IsRepoURLAccessible(wikiURL) {
  769. return wikiURL
  770. }
  771. }
  772. return ""
  773. }
  774. // MigrateRepository migrates a existing repository from other project hosting.
  775. func MigrateRepository(doer, u *User, opts MigrateRepoOptions) (*Repository, error) {
  776. repo, err := CreateRepository(doer, u, CreateRepoOptions{
  777. Name: opts.Name,
  778. Description: opts.Description,
  779. IsPrivate: opts.IsPrivate,
  780. IsMirror: opts.IsMirror,
  781. })
  782. if err != nil {
  783. return nil, err
  784. }
  785. repoPath := RepoPath(u.Name, opts.Name)
  786. wikiPath := WikiPath(u.Name, opts.Name)
  787. if u.IsOrganization() {
  788. t, err := u.GetOwnerTeam()
  789. if err != nil {
  790. return nil, err
  791. }
  792. repo.NumWatches = t.NumMembers
  793. } else {
  794. repo.NumWatches = 1
  795. }
  796. migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second
  797. if err := os.RemoveAll(repoPath); err != nil {
  798. return repo, fmt.Errorf("Failed to remove %s: %v", repoPath, err)
  799. }
  800. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{
  801. Mirror: true,
  802. Quiet: true,
  803. Timeout: migrateTimeout,
  804. }); err != nil {
  805. return repo, fmt.Errorf("Clone: %v", err)
  806. }
  807. wikiRemotePath := wikiRemoteURL(opts.RemoteAddr)
  808. if len(wikiRemotePath) > 0 {
  809. if err := os.RemoveAll(wikiPath); err != nil {
  810. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  811. }
  812. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{
  813. Mirror: true,
  814. Quiet: true,
  815. Timeout: migrateTimeout,
  816. Branch: "master",
  817. }); err != nil {
  818. log.Warn("Clone wiki: %v", err)
  819. if err := os.RemoveAll(wikiPath); err != nil {
  820. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  821. }
  822. }
  823. }
  824. // Check if repository is empty.
  825. _, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
  826. if err != nil {
  827. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  828. repo.IsBare = true
  829. } else {
  830. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  831. }
  832. }
  833. if !repo.IsBare {
  834. // Try to get HEAD branch and set it as default branch.
  835. gitRepo, err := git.OpenRepository(repoPath)
  836. if err != nil {
  837. return repo, fmt.Errorf("OpenRepository: %v", err)
  838. }
  839. headBranch, err := gitRepo.GetHEADBranch()
  840. if err != nil {
  841. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  842. }
  843. if headBranch != nil {
  844. repo.DefaultBranch = headBranch.Name
  845. }
  846. if err = SyncReleasesWithTags(repo, gitRepo); err != nil {
  847. log.Error(4, "Failed to synchronize tags to releases for repository: %v", err)
  848. }
  849. UpdateRepoIndexer(repo)
  850. }
  851. if err = repo.UpdateSize(); err != nil {
  852. log.Error(4, "Failed to update size for repository: %v", err)
  853. }
  854. if opts.IsMirror {
  855. if _, err = x.InsertOne(&Mirror{
  856. RepoID: repo.ID,
  857. Interval: setting.Mirror.DefaultInterval,
  858. EnablePrune: true,
  859. NextUpdateUnix: util.TimeStampNow().AddDuration(setting.Mirror.DefaultInterval),
  860. }); err != nil {
  861. return repo, fmt.Errorf("InsertOne: %v", err)
  862. }
  863. repo.IsMirror = true
  864. return repo, UpdateRepository(repo, false)
  865. }
  866. return CleanUpMigrateInfo(repo)
  867. }
  868. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  869. // This also removes possible user credentials.
  870. func cleanUpMigrateGitConfig(configPath string) error {
  871. cfg, err := ini.Load(configPath)
  872. if err != nil {
  873. return fmt.Errorf("open config file: %v", err)
  874. }
  875. cfg.DeleteSection("remote \"origin\"")
  876. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  877. return fmt.Errorf("save config file: %v", err)
  878. }
  879. return nil
  880. }
  881. // createDelegateHooks creates all the hooks scripts for the repo
  882. func createDelegateHooks(repoPath string) (err error) {
  883. var (
  884. hookNames = []string{"pre-receive", "update", "post-receive"}
  885. hookTpls = []string{
  886. 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),
  887. 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),
  888. 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),
  889. }
  890. giteaHookTpls = []string{
  891. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  892. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  893. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  894. }
  895. )
  896. hookDir := filepath.Join(repoPath, "hooks")
  897. for i, hookName := range hookNames {
  898. oldHookPath := filepath.Join(hookDir, hookName)
  899. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  900. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  901. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  902. }
  903. // WARNING: This will override all old server-side hooks
  904. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  905. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  906. }
  907. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  908. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  909. }
  910. }
  911. return nil
  912. }
  913. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.
  914. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  915. repoPath := repo.RepoPath()
  916. if err := createDelegateHooks(repoPath); err != nil {
  917. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  918. }
  919. if repo.HasWiki() {
  920. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  921. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  922. }
  923. }
  924. if err := cleanUpMigrateGitConfig(repo.GitConfigPath()); err != nil {
  925. return repo, fmt.Errorf("cleanUpMigrateGitConfig: %v", err)
  926. }
  927. if repo.HasWiki() {
  928. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  929. return repo, fmt.Errorf("cleanUpMigrateGitConfig (wiki): %v", err)
  930. }
  931. }
  932. return repo, UpdateRepository(repo, false)
  933. }
  934. // initRepoCommit temporarily changes with work directory.
  935. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  936. var stderr string
  937. if _, stderr, err = process.GetManager().ExecDir(-1,
  938. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  939. "git", "add", "--all"); err != nil {
  940. return fmt.Errorf("git add: %s", stderr)
  941. }
  942. if _, stderr, err = process.GetManager().ExecDir(-1,
  943. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  944. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  945. "-m", "Initial commit"); err != nil {
  946. return fmt.Errorf("git commit: %s", stderr)
  947. }
  948. if _, stderr, err = process.GetManager().ExecDir(-1,
  949. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  950. "git", "push", "origin", "master"); err != nil {
  951. return fmt.Errorf("git push: %s", stderr)
  952. }
  953. return nil
  954. }
  955. // CreateRepoOptions contains the create repository options
  956. type CreateRepoOptions struct {
  957. Name string
  958. Description string
  959. Gitignores string
  960. License string
  961. Readme string
  962. IsPrivate bool
  963. IsMirror bool
  964. AutoInit bool
  965. }
  966. func getRepoInitFile(tp, name string) ([]byte, error) {
  967. cleanedName := strings.TrimLeft(name, "./")
  968. relPath := path.Join("options", tp, cleanedName)
  969. // Use custom file when available.
  970. customPath := path.Join(setting.CustomPath, relPath)
  971. if com.IsFile(customPath) {
  972. return ioutil.ReadFile(customPath)
  973. }
  974. switch tp {
  975. case "readme":
  976. return options.Readme(cleanedName)
  977. case "gitignore":
  978. return options.Gitignore(cleanedName)
  979. case "license":
  980. return options.License(cleanedName)
  981. case "label":
  982. return options.Labels(cleanedName)
  983. default:
  984. return []byte{}, fmt.Errorf("Invalid init file type")
  985. }
  986. }
  987. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  988. // Clone to temporary path and do the init commit.
  989. _, stderr, err := process.GetManager().Exec(
  990. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  991. "git", "clone", repoPath, tmpDir,
  992. )
  993. if err != nil {
  994. return fmt.Errorf("git clone: %v - %s", err, stderr)
  995. }
  996. // README
  997. data, err := getRepoInitFile("readme", opts.Readme)
  998. if err != nil {
  999. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  1000. }
  1001. cloneLink := repo.CloneLink()
  1002. match := map[string]string{
  1003. "Name": repo.Name,
  1004. "Description": repo.Description,
  1005. "CloneURL.SSH": cloneLink.SSH,
  1006. "CloneURL.HTTPS": cloneLink.HTTPS,
  1007. }
  1008. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  1009. []byte(com.Expand(string(data), match)), 0644); err != nil {
  1010. return fmt.Errorf("write README.md: %v", err)
  1011. }
  1012. // .gitignore
  1013. if len(opts.Gitignores) > 0 {
  1014. var buf bytes.Buffer
  1015. names := strings.Split(opts.Gitignores, ",")
  1016. for _, name := range names {
  1017. data, err = getRepoInitFile("gitignore", name)
  1018. if err != nil {
  1019. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  1020. }
  1021. buf.WriteString("# ---> " + name + "\n")
  1022. buf.Write(data)
  1023. buf.WriteString("\n")
  1024. }
  1025. if buf.Len() > 0 {
  1026. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  1027. return fmt.Errorf("write .gitignore: %v", err)
  1028. }
  1029. }
  1030. }
  1031. // LICENSE
  1032. if len(opts.License) > 0 {
  1033. data, err = getRepoInitFile("license", opts.License)
  1034. if err != nil {
  1035. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  1036. }
  1037. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  1038. return fmt.Errorf("write LICENSE: %v", err)
  1039. }
  1040. }
  1041. return nil
  1042. }
  1043. // InitRepository initializes README and .gitignore if needed.
  1044. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  1045. // Somehow the directory could exist.
  1046. if com.IsExist(repoPath) {
  1047. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  1048. }
  1049. // Init bare new repository.
  1050. if err = git.InitRepository(repoPath, true); err != nil {
  1051. return fmt.Errorf("InitRepository: %v", err)
  1052. } else if err = createDelegateHooks(repoPath); err != nil {
  1053. return fmt.Errorf("createDelegateHooks: %v", err)
  1054. }
  1055. tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  1056. // Initialize repository according to user's choice.
  1057. if opts.AutoInit {
  1058. if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
  1059. return fmt.Errorf("Failed to create dir %s: %v", tmpDir, err)
  1060. }
  1061. defer os.RemoveAll(tmpDir)
  1062. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  1063. return fmt.Errorf("prepareRepoCommit: %v", err)
  1064. }
  1065. // Apply changes and commit.
  1066. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  1067. return fmt.Errorf("initRepoCommit: %v", err)
  1068. }
  1069. }
  1070. // Re-fetch the repository from database before updating it (else it would
  1071. // override changes that were done earlier with sql)
  1072. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  1073. return fmt.Errorf("getRepositoryByID: %v", err)
  1074. }
  1075. if !opts.AutoInit {
  1076. repo.IsBare = true
  1077. }
  1078. repo.DefaultBranch = "master"
  1079. if err = updateRepository(e, repo, false); err != nil {
  1080. return fmt.Errorf("updateRepository: %v", err)
  1081. }
  1082. return nil
  1083. }
  1084. var (
  1085. reservedRepoNames = []string{".", ".."}
  1086. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  1087. )
  1088. // IsUsableRepoName returns true when repository is usable
  1089. func IsUsableRepoName(name string) error {
  1090. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  1091. }
  1092. func createRepository(e *xorm.Session, doer, u *User, repo *Repository) (err error) {
  1093. if err = IsUsableRepoName(repo.Name); err != nil {
  1094. return err
  1095. }
  1096. has, err := isRepositoryExist(e, u, repo.Name)
  1097. if err != nil {
  1098. return fmt.Errorf("IsRepositoryExist: %v", err)
  1099. } else if has {
  1100. return ErrRepoAlreadyExist{u.Name, repo.Name}
  1101. }
  1102. if _, err = e.Insert(repo); err != nil {
  1103. return err
  1104. }
  1105. if err = deleteRepoRedirect(e, u.ID, repo.Name); err != nil {
  1106. return err
  1107. }
  1108. // insert units for repo
  1109. var units = make([]RepoUnit, 0, len(defaultRepoUnits))
  1110. for _, tp := range defaultRepoUnits {
  1111. if tp == UnitTypeIssues {
  1112. units = append(units, RepoUnit{
  1113. RepoID: repo.ID,
  1114. Type: tp,
  1115. Config: &IssuesConfig{EnableTimetracker: setting.Service.DefaultEnableTimetracking, AllowOnlyContributorsToTrackTime: setting.Service.DefaultAllowOnlyContributorsToTrackTime},
  1116. })
  1117. } else {
  1118. units = append(units, RepoUnit{
  1119. RepoID: repo.ID,
  1120. Type: tp,
  1121. })
  1122. }
  1123. }
  1124. if _, err = e.Insert(&units); err != nil {
  1125. return err
  1126. }
  1127. u.NumRepos++
  1128. // Remember visibility preference.
  1129. u.LastRepoVisibility = repo.IsPrivate
  1130. if err = updateUser(e, u); err != nil {
  1131. return fmt.Errorf("updateUser: %v", err)
  1132. }
  1133. // Give access to all members in owner team.
  1134. if u.IsOrganization() {
  1135. t, err := u.getOwnerTeam(e)
  1136. if err != nil {
  1137. return fmt.Errorf("getOwnerTeam: %v", err)
  1138. } else if err = t.addRepository(e, repo); err != nil {
  1139. return fmt.Errorf("addRepository: %v", err)
  1140. } else if err = prepareWebhooks(e, repo, HookEventRepository, &api.RepositoryPayload{
  1141. Action: api.HookRepoCreated,
  1142. Repository: repo.APIFormat(AccessModeOwner),
  1143. Organization: u.APIFormat(),
  1144. Sender: doer.APIFormat(),
  1145. }); err != nil {
  1146. return fmt.Errorf("prepareWebhooks: %v", err)
  1147. }
  1148. go HookQueue.Add(repo.ID)
  1149. } else {
  1150. // Organization automatically called this in addRepository method.
  1151. if err = repo.recalculateAccesses(e); err != nil {
  1152. return fmt.Errorf("recalculateAccesses: %v", err)
  1153. }
  1154. }
  1155. if err = watchRepo(e, doer.ID, repo.ID, true); err != nil {
  1156. return fmt.Errorf("watchRepo: %v", err)
  1157. } else if err = newRepoAction(e, u, repo); err != nil {
  1158. return fmt.Errorf("newRepoAction: %v", err)
  1159. }
  1160. return nil
  1161. }
  1162. // CreateRepository creates a repository for the user/organization u.
  1163. func CreateRepository(doer, u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  1164. if !u.CanCreateRepo() {
  1165. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  1166. }
  1167. repo := &Repository{
  1168. OwnerID: u.ID,
  1169. Owner: u,
  1170. Name: opts.Name,
  1171. LowerName: strings.ToLower(opts.Name),
  1172. Description: opts.Description,
  1173. IsPrivate: opts.IsPrivate,
  1174. }
  1175. sess := x.NewSession()
  1176. defer sess.Close()
  1177. if err = sess.Begin(); err != nil {
  1178. return nil, err
  1179. }
  1180. if err = createRepository(sess, doer, u, repo); err != nil {
  1181. return nil, err
  1182. }
  1183. // No need for init mirror.
  1184. if !opts.IsMirror {
  1185. repoPath := RepoPath(u.Name, repo.Name)
  1186. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  1187. if err2 := os.RemoveAll(repoPath); err2 != nil {
  1188. log.Error(4, "initRepository: %v", err)
  1189. return nil, fmt.Errorf(
  1190. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  1191. }
  1192. return nil, fmt.Errorf("initRepository: %v", err)
  1193. }
  1194. _, stderr, err := process.GetManager().ExecDir(-1,
  1195. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  1196. "git", "update-server-info")
  1197. if err != nil {
  1198. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  1199. }
  1200. }
  1201. return repo, sess.Commit()
  1202. }
  1203. func countRepositories(userID int64, private bool) int64 {
  1204. sess := x.Where("id > 0")
  1205. if userID > 0 {
  1206. sess.And("owner_id = ?", userID)
  1207. }
  1208. if !private {
  1209. sess.And("is_private=?", false)
  1210. }
  1211. count, err := sess.Count(new(Repository))
  1212. if err != nil {
  1213. log.Error(4, "countRepositories: %v", err)
  1214. }
  1215. return count
  1216. }
  1217. // CountRepositories returns number of repositories.
  1218. // Argument private only takes effect when it is false,
  1219. // set it true to count all repositories.
  1220. func CountRepositories(private bool) int64 {
  1221. return countRepositories(-1, private)
  1222. }
  1223. // CountUserRepositories returns number of repositories user owns.
  1224. // Argument private only takes effect when it is false,
  1225. // set it true to count all repositories.
  1226. func CountUserRepositories(userID int64, private bool) int64 {
  1227. return countRepositories(userID, private)
  1228. }
  1229. // RepoPath returns repository path by given user and repository name.
  1230. func RepoPath(userName, repoName string) string {
  1231. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1232. }
  1233. // TransferOwnership transfers all corresponding setting from old user to new one.
  1234. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1235. newOwner, err := GetUserByName(newOwnerName)
  1236. if err != nil {
  1237. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1238. }
  1239. // Check if new owner has repository with same name.
  1240. has, err := IsRepositoryExist(newOwner, repo.Name)
  1241. if err != nil {
  1242. return fmt.Errorf("IsRepositoryExist: %v", err)
  1243. } else if has {
  1244. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1245. }
  1246. sess := x.NewSession()
  1247. defer sess.Close()
  1248. if err = sess.Begin(); err != nil {
  1249. return fmt.Errorf("sess.Begin: %v", err)
  1250. }
  1251. owner := repo.Owner
  1252. // Note: we have to set value here to make sure recalculate accesses is based on
  1253. // new owner.
  1254. repo.OwnerID = newOwner.ID
  1255. repo.Owner = newOwner
  1256. // Update repository.
  1257. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1258. return fmt.Errorf("update owner: %v", err)
  1259. }
  1260. // Remove redundant collaborators.
  1261. collaborators, err := repo.getCollaborators(sess)
  1262. if err != nil {
  1263. return fmt.Errorf("getCollaborators: %v", err)
  1264. }
  1265. // Dummy object.
  1266. collaboration := &Collaboration{RepoID: repo.ID}
  1267. for _, c := range collaborators {
  1268. if c.ID != newOwner.ID {
  1269. isMember, err := newOwner.IsOrgMember(c.ID)
  1270. if err != nil {
  1271. return fmt.Errorf("IsOrgMember: %v", err)
  1272. } else if !isMember {
  1273. continue
  1274. }
  1275. }
  1276. collaboration.UserID = c.ID
  1277. if _, err = sess.Delete(collaboration); err != nil {
  1278. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1279. }
  1280. }
  1281. // Remove old team-repository relations.
  1282. if owner.IsOrganization() {
  1283. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1284. return fmt.Errorf("removeOrgRepo: %v", err)
  1285. }
  1286. }
  1287. if newOwner.IsOrganization() {
  1288. t, err := newOwner.getOwnerTeam(sess)
  1289. if err != nil {
  1290. return fmt.Errorf("getOwnerTeam: %v", err)
  1291. } else if err = t.addRepository(sess, repo); err != nil {
  1292. return fmt.Errorf("add to owner team: %v", err)
  1293. }
  1294. } else {
  1295. // Organization called this in addRepository method.
  1296. if err = repo.recalculateAccesses(sess); err != nil {
  1297. return fmt.Errorf("recalculateAccesses: %v", err)
  1298. }
  1299. }
  1300. // Update repository count.
  1301. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1302. return fmt.Errorf("increase new owner repository count: %v", err)
  1303. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1304. return fmt.Errorf("decrease old owner repository count: %v", err)
  1305. }
  1306. if err = watchRepo(sess, doer.ID, repo.ID, true); err != nil {
  1307. return fmt.Errorf("watchRepo: %v", err)
  1308. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1309. return fmt.Errorf("transferRepoAction: %v", err)
  1310. }
  1311. // Rename remote repository to new path and delete local copy.
  1312. dir := UserPath(newOwner.Name)
  1313. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  1314. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  1315. }
  1316. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1317. return fmt.Errorf("rename repository directory: %v", err)
  1318. }
  1319. RemoveAllWithNotice("Delete repository local copy", repo.LocalCopyPath())
  1320. // Rename remote wiki repository to new path and delete local copy.
  1321. wikiPath := WikiPath(owner.Name, repo.Name)
  1322. if com.IsExist(wikiPath) {
  1323. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1324. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1325. return fmt.Errorf("rename repository wiki: %v", err)
  1326. }
  1327. }
  1328. return sess.Commit()
  1329. }
  1330. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1331. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1332. oldRepoName = strings.ToLower(oldRepoName)
  1333. newRepoName = strings.ToLower(newRepoName)
  1334. if err = IsUsableRepoName(newRepoName); err != nil {
  1335. return err
  1336. }
  1337. has, err := IsRepositoryExist(u, newRepoName)
  1338. if err != nil {
  1339. return fmt.Errorf("IsRepositoryExist: %v", err)
  1340. } else if has {
  1341. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1342. }
  1343. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1344. if err != nil {
  1345. return fmt.Errorf("GetRepositoryByName: %v", err)
  1346. }
  1347. // Change repository directory name.
  1348. if err = os.Rename(repo.RepoPath(), RepoPath(u.Name, newRepoName)); err != nil {
  1349. return fmt.Errorf("rename repository directory: %v", err)
  1350. }
  1351. wikiPath := repo.WikiPath()
  1352. if com.IsExist(wikiPath) {
  1353. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1354. return fmt.Errorf("rename repository wiki: %v", err)
  1355. }
  1356. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1357. }
  1358. return nil
  1359. }
  1360. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1361. repos := make([]*Repository, 0, 10)
  1362. return repos, e.
  1363. Where("fork_id=?", forkID).
  1364. Find(&repos)
  1365. }
  1366. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1367. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1368. return getRepositoriesByForkID(x, forkID)
  1369. }
  1370. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1371. repo.LowerName = strings.ToLower(repo.Name)
  1372. if len(repo.Description) > 255 {
  1373. repo.Description = repo.Description[:255]
  1374. }
  1375. if len(repo.Website) > 255 {
  1376. repo.Website = repo.Website[:255]
  1377. }
  1378. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1379. return fmt.Errorf("update: %v", err)
  1380. }
  1381. if visibilityChanged {
  1382. if err = repo.getOwner(e); err != nil {
  1383. return fmt.Errorf("getOwner: %v", err)
  1384. }
  1385. if repo.Owner.IsOrganization() {
  1386. // Organization repository need to recalculate access table when visibility is changed.
  1387. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1388. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1389. }
  1390. }
  1391. // If repo has become private, we need to set its actions to private.
  1392. if repo.IsPrivate {
  1393. _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{
  1394. IsPrivate: true,
  1395. })
  1396. if err != nil {
  1397. return err
  1398. }
  1399. }
  1400. // Create/Remove git-daemon-export-ok for git-daemon...
  1401. daemonExportFile := path.Join(repo.RepoPath(), `git-daemon-export-ok`)
  1402. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1403. if err = os.Remove(daemonExportFile); err != nil {
  1404. log.Error(4, "Failed to remove %s: %v", daemonExportFile, err)
  1405. }
  1406. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1407. if f, err := os.Create(daemonExportFile); err != nil {
  1408. log.Error(4, "Failed to create %s: %v", daemonExportFile, err)
  1409. } else {
  1410. f.Close()
  1411. }
  1412. }
  1413. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1414. if err != nil {
  1415. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1416. }
  1417. for i := range forkRepos {
  1418. forkRepos[i].IsPrivate = repo.IsPrivate
  1419. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1420. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1421. }
  1422. }
  1423. if err = repo.updateSize(e); err != nil {
  1424. log.Error(4, "Failed to update size for repository: %v", err)
  1425. }
  1426. }
  1427. return nil
  1428. }
  1429. // UpdateRepository updates a repository
  1430. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1431. sess := x.NewSession()
  1432. defer sess.Close()
  1433. if err = sess.Begin(); err != nil {
  1434. return err
  1435. }
  1436. if err = updateRepository(sess, repo, visibilityChanged); err != nil {
  1437. return fmt.Errorf("updateRepository: %v", err)
  1438. }
  1439. return sess.Commit()
  1440. }
  1441. // UpdateRepositoryUnits updates a repository's units
  1442. func UpdateRepositoryUnits(repo *Repository, units []RepoUnit) (err error) {
  1443. sess := x.NewSession()
  1444. defer sess.Close()
  1445. if err = sess.Begin(); err != nil {
  1446. return err
  1447. }
  1448. if _, err = sess.Where("repo_id = ?", repo.ID).Delete(new(RepoUnit)); err != nil {
  1449. return err
  1450. }
  1451. if _, err = sess.Insert(units); err != nil {
  1452. return err
  1453. }
  1454. return sess.Commit()
  1455. }
  1456. // DeleteRepository deletes a repository for a user or organization.
  1457. func DeleteRepository(doer *User, uid, repoID int64) error {
  1458. // In case is a organization.
  1459. org, err := GetUserByID(uid)
  1460. if err != nil {
  1461. return err
  1462. }
  1463. if org.IsOrganization() {
  1464. if err = org.GetTeams(); err != nil {
  1465. return err
  1466. }
  1467. }
  1468. sess := x.NewSession()
  1469. defer sess.Close()
  1470. if err = sess.Begin(); err != nil {
  1471. return err
  1472. }
  1473. repo := &Repository{ID: repoID, OwnerID: uid}
  1474. has, err := sess.Get(repo)
  1475. if err != nil {
  1476. return err
  1477. } else if !has {
  1478. return ErrRepoNotExist{repoID, uid, "", ""}
  1479. }
  1480. if cnt, err := sess.ID(repoID).Delete(&Repository{}); err != nil {
  1481. return err
  1482. } else if cnt != 1 {
  1483. return ErrRepoNotExist{repoID, uid, "", ""}
  1484. }
  1485. if org.IsOrganization() {
  1486. for _, t := range org.Teams {
  1487. if !t.hasRepository(sess, repoID) {
  1488. continue
  1489. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1490. return err
  1491. }
  1492. }
  1493. }
  1494. if err = deleteBeans(sess,
  1495. &Access{RepoID: repo.ID},
  1496. &Action{RepoID: repo.ID},
  1497. &Watch{RepoID: repoID},
  1498. &Star{RepoID: repoID},
  1499. &Mirror{RepoID: repoID},
  1500. &Milestone{RepoID: repoID},
  1501. &Release{RepoID: repoID},
  1502. &Collaboration{RepoID: repoID},
  1503. &PullRequest{BaseRepoID: repoID},
  1504. &RepoUnit{RepoID: repoID},
  1505. &RepoRedirect{RedirectRepoID: repoID},
  1506. ); err != nil {
  1507. return fmt.Errorf("deleteBeans: %v", err)
  1508. }
  1509. // Delete comments and attachments.
  1510. issueIDs := make([]int64, 0, 25)
  1511. attachmentPaths := make([]string, 0, len(issueIDs))
  1512. if err = sess.
  1513. Table("issue").
  1514. Cols("id").
  1515. Where("repo_id=?", repoID).
  1516. Find(&issueIDs); err != nil {
  1517. return err
  1518. }
  1519. if len(issueIDs) > 0 {
  1520. if _, err = sess.In("issue_id", issueIDs).Delete(&Comment{}); err != nil {
  1521. return err
  1522. }
  1523. if _, err = sess.In("issue_id", issueIDs).Delete(&IssueUser{}); err != nil {
  1524. return err
  1525. }
  1526. attachments := make([]*Attachment, 0, 5)
  1527. if err = sess.
  1528. In("issue_id", issueIDs).
  1529. Find(&attachments); err != nil {
  1530. return err
  1531. }
  1532. for j := range attachments {
  1533. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1534. }
  1535. if _, err = sess.In("issue_id", issueIDs).Delete(&Attachment{}); err != nil {
  1536. return err
  1537. }
  1538. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1539. return err
  1540. }
  1541. }
  1542. if _, err = sess.Where("repo_id = ?", repoID).Delete(new(RepoUnit)); err != nil {
  1543. return err
  1544. }
  1545. if repo.IsFork {
  1546. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1547. return fmt.Errorf("decrease fork count: %v", err)
  1548. }
  1549. }
  1550. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1551. return err
  1552. }
  1553. // FIXME: Remove repository files should be executed after transaction succeed.
  1554. repoPath := repo.repoPath(sess)
  1555. removeAllWithNotice(sess, "Delete repository files", repoPath)
  1556. repo.deleteWiki(sess)
  1557. // Remove attachment files.
  1558. for i := range attachmentPaths {
  1559. removeAllWithNotice(sess, "Delete attachment", attachmentPaths[i])
  1560. }
  1561. // Remove LFS objects
  1562. var lfsObjects []*LFSMetaObject
  1563. if err = sess.Where("repository_id=?", repoID).Find(&lfsObjects); err != nil {
  1564. return err
  1565. }
  1566. for _, v := range lfsObjects {
  1567. count, err := sess.Count(&LFSMetaObject{Oid: v.Oid})
  1568. if err != nil {
  1569. return err
  1570. }
  1571. if count > 1 {
  1572. continue
  1573. }
  1574. oidPath := filepath.Join(v.Oid[0:2], v.Oid[2:4], v.Oid[4:len(v.Oid)])
  1575. err = os.Remove(filepath.Join(setting.LFS.ContentPath, oidPath))
  1576. if err != nil {
  1577. return err
  1578. }
  1579. }
  1580. if _, err := sess.Delete(&LFSMetaObject{RepositoryID: repoID}); err != nil {
  1581. return err
  1582. }
  1583. if repo.NumForks > 0 {
  1584. if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1585. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1586. }
  1587. }
  1588. if err = sess.Commit(); err != nil {
  1589. return fmt.Errorf("Commit: %v", err)
  1590. }
  1591. if org.IsOrganization() {
  1592. if err = PrepareWebhooks(repo, HookEventRepository, &api.RepositoryPayload{
  1593. Action: api.HookRepoDeleted,
  1594. Repository: repo.APIFormat(AccessModeOwner),
  1595. Organization: org.APIFormat(),
  1596. Sender: doer.APIFormat(),
  1597. }); err != nil {
  1598. return err
  1599. }
  1600. go HookQueue.Add(repo.ID)
  1601. }
  1602. DeleteRepoFromIndexer(repo)
  1603. return nil
  1604. }
  1605. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
  1606. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
  1607. var repo Repository
  1608. has, err := x.Select("repository.*").
  1609. Join("INNER", "user", "`user`.id = repository.owner_id").
  1610. Where("repository.lower_name = ?", strings.ToLower(repoName)).
  1611. And("`user`.lower_name = ?", strings.ToLower(ownerName)).
  1612. Get(&repo)
  1613. if err != nil {
  1614. return nil, err
  1615. } else if !has {
  1616. return nil, ErrRepoNotExist{0, 0, ownerName, repoName}
  1617. }
  1618. return &repo, nil
  1619. }
  1620. // GetRepositoryByName returns the repository by given name under user if exists.
  1621. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1622. repo := &Repository{
  1623. OwnerID: ownerID,
  1624. LowerName: strings.ToLower(name),
  1625. }
  1626. has, err := x.Get(repo)
  1627. if err != nil {
  1628. return nil, err
  1629. } else if !has {
  1630. return nil, ErrRepoNotExist{0, ownerID, "", name}
  1631. }
  1632. return repo, err
  1633. }
  1634. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1635. repo := new(Repository)
  1636. has, err := e.ID(id).Get(repo)
  1637. if err != nil {
  1638. return nil, err
  1639. } else if !has {
  1640. return nil, ErrRepoNotExist{id, 0, "", ""}
  1641. }
  1642. return repo, nil
  1643. }
  1644. // GetRepositoryByID returns the repository by given id if exists.
  1645. func GetRepositoryByID(id int64) (*Repository, error) {
  1646. return getRepositoryByID(x, id)
  1647. }
  1648. // GetUserRepositories returns a list of repositories of given user.
  1649. func GetUserRepositories(userID int64, private bool, page, pageSize int, orderBy string) ([]*Repository, error) {
  1650. if len(orderBy) == 0 {
  1651. orderBy = "updated_unix DESC"
  1652. }
  1653. sess := x.
  1654. Where("owner_id = ?", userID).
  1655. OrderBy(orderBy)
  1656. if !private {
  1657. sess.And("is_private=?", false)
  1658. }
  1659. if page <= 0 {
  1660. page = 1
  1661. }
  1662. sess.Limit(pageSize, (page-1)*pageSize)
  1663. repos := make([]*Repository, 0, pageSize)
  1664. return repos, sess.Find(&repos)
  1665. }
  1666. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
  1667. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1668. repos := make([]*Repository, 0, 10)
  1669. return repos, x.
  1670. Where("owner_id = ?", userID).
  1671. And("is_mirror = ?", true).
  1672. Find(&repos)
  1673. }
  1674. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1675. return e.Count(&Repository{OwnerID: u.ID})
  1676. }
  1677. func getPublicRepositoryCount(e Engine, u *User) (int64, error) {
  1678. return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
  1679. }
  1680. func getPrivateRepositoryCount(e Engine, u *User) (int64, error) {
  1681. return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
  1682. }
  1683. // GetRepositoryCount returns the total number of repositories of user.
  1684. func GetRepositoryCount(u *User) (int64, error) {
  1685. return getRepositoryCount(x, u)
  1686. }
  1687. // GetPublicRepositoryCount returns the total number of public repositories of user.
  1688. func GetPublicRepositoryCount(u *User) (int64, error) {
  1689. return getPublicRepositoryCount(x, u)
  1690. }
  1691. // GetPrivateRepositoryCount returns the total number of private repositories of user.
  1692. func GetPrivateRepositoryCount(u *User) (int64, error) {
  1693. return getPrivateRepositoryCount(x, u)
  1694. }
  1695. // DeleteRepositoryArchives deletes all repositories' archives.
  1696. func DeleteRepositoryArchives() error {
  1697. return x.
  1698. Where("id > 0").
  1699. Iterate(new(Repository),
  1700. func(idx int, bean interface{}) error {
  1701. repo := bean.(*Repository)
  1702. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1703. })
  1704. }
  1705. // DeleteOldRepositoryArchives deletes old repository archives.
  1706. func DeleteOldRepositoryArchives() {
  1707. if !taskStatusTable.StartIfNotRunning(archiveCleanup) {
  1708. return
  1709. }
  1710. defer taskStatusTable.Stop(archiveCleanup)
  1711. log.Trace("Doing: ArchiveCleanup")
  1712. if err := x.Where("id > 0").Iterate(new(Repository), deleteOldRepositoryArchives); err != nil {
  1713. log.Error(4, "ArchiveClean: %v", err)
  1714. }
  1715. }
  1716. func deleteOldRepositoryArchives(idx int, bean interface{}) error {
  1717. repo := bean.(*Repository)
  1718. basePath := filepath.Join(repo.RepoPath(), "archives")
  1719. for _, ty := range []string{"zip", "targz"} {
  1720. path := filepath.Join(basePath, ty)
  1721. file, err := os.Open(path)
  1722. if err != nil {
  1723. if !os.IsNotExist(err) {
  1724. log.Warn("Unable to open directory %s: %v", path, err)
  1725. return err
  1726. }
  1727. // If the directory doesn't exist, that's okay.
  1728. continue
  1729. }
  1730. files, err := file.Readdir(0)
  1731. file.Close()
  1732. if err != nil {
  1733. log.Warn("Unable to read directory %s: %v", path, err)
  1734. return err
  1735. }
  1736. minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
  1737. for _, info := range files {
  1738. if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
  1739. toDelete := filepath.Join(path, info.Name())
  1740. // This is a best-effort purge, so we do not check error codes to confirm removal.
  1741. if err = os.Remove(toDelete); err != nil {
  1742. log.Trace("Unable to delete %s, but proceeding: %v", toDelete, err)
  1743. }
  1744. }
  1745. }
  1746. }
  1747. return nil
  1748. }
  1749. func gatherMissingRepoRecords() ([]*Repository, error) {
  1750. repos := make([]*Repository, 0, 10)
  1751. if err := x.
  1752. Where("id > 0").
  1753. Iterate(new(Repository),
  1754. func(idx int, bean interface{}) error {
  1755. repo := bean.(*Repository)
  1756. if !com.IsDir(repo.RepoPath()) {
  1757. repos = append(repos, repo)
  1758. }
  1759. return nil
  1760. }); err != nil {
  1761. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1762. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1763. }
  1764. }
  1765. return repos, nil
  1766. }
  1767. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1768. func DeleteMissingRepositories(doer *User) error {
  1769. repos, err := gatherMissingRepoRecords()
  1770. if err != nil {
  1771. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1772. }
  1773. if len(repos) == 0 {
  1774. return nil
  1775. }
  1776. for _, repo := range repos {
  1777. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1778. if err := DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  1779. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1780. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1781. }
  1782. }
  1783. }
  1784. return nil
  1785. }
  1786. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1787. func ReinitMissingRepositories() error {
  1788. repos, err := gatherMissingRepoRecords()
  1789. if err != nil {
  1790. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1791. }
  1792. if len(repos) == 0 {
  1793. return nil
  1794. }
  1795. for _, repo := range repos {
  1796. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1797. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1798. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1799. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1800. }
  1801. }
  1802. }
  1803. return nil
  1804. }
  1805. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1806. // to make sure the binary and custom conf path are up-to-date.
  1807. func SyncRepositoryHooks() error {
  1808. return x.Where("id > 0").Iterate(new(Repository),
  1809. func(idx int, bean interface{}) error {
  1810. if err := createDelegateHooks(bean.(*Repository).RepoPath()); err != nil {
  1811. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1812. }
  1813. if bean.(*Repository).HasWiki() {
  1814. if err := createDelegateHooks(bean.(*Repository).WikiPath()); err != nil {
  1815. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1816. }
  1817. }
  1818. return nil
  1819. })
  1820. }
  1821. // Prevent duplicate running tasks.
  1822. var taskStatusTable = sync.NewStatusTable()
  1823. const (
  1824. mirrorUpdate = "mirror_update"
  1825. gitFsck = "git_fsck"
  1826. checkRepos = "check_repos"
  1827. archiveCleanup = "archive_cleanup"
  1828. )
  1829. // GitFsck calls 'git fsck' to check repository health.
  1830. func GitFsck() {
  1831. if !taskStatusTable.StartIfNotRunning(gitFsck) {
  1832. return
  1833. }
  1834. defer taskStatusTable.Stop(gitFsck)
  1835. log.Trace("Doing: GitFsck")
  1836. if err := x.
  1837. Where("id>0").BufferSize(setting.IterateBufferSize).
  1838. Iterate(new(Repository),
  1839. func(idx int, bean interface{}) error {
  1840. repo := bean.(*Repository)
  1841. repoPath := repo.RepoPath()
  1842. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1843. desc := fmt.Sprintf("Failed to health check repository (%s): %v", repoPath, err)
  1844. log.Warn(desc)
  1845. if err = CreateRepositoryNotice(desc); err != nil {
  1846. log.Error(4, "CreateRepositoryNotice: %v", err)
  1847. }
  1848. }
  1849. return nil
  1850. }); err != nil {
  1851. log.Error(4, "GitFsck: %v", err)
  1852. }
  1853. }
  1854. // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
  1855. func GitGcRepos() error {
  1856. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1857. return x.
  1858. Where("id > 0").BufferSize(setting.IterateBufferSize).
  1859. Iterate(new(Repository),
  1860. func(idx int, bean interface{}) error {
  1861. repo := bean.(*Repository)
  1862. if err := repo.GetOwner(); err != nil {
  1863. return err
  1864. }
  1865. _, stderr, err := process.GetManager().ExecDir(
  1866. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1867. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1868. "git", args...)
  1869. if err != nil {
  1870. return fmt.Errorf("%v: %v", err, stderr)
  1871. }
  1872. return nil
  1873. })
  1874. }
  1875. type repoChecker struct {
  1876. querySQL, correctSQL string
  1877. desc string
  1878. }
  1879. func repoStatsCheck(checker *repoChecker) {
  1880. results, err := x.Query(checker.querySQL)
  1881. if err != nil {
  1882. log.Error(4, "Select %s: %v", checker.desc, err)
  1883. return
  1884. }
  1885. for _, result := range results {
  1886. id := com.StrTo(result["id"]).MustInt64()
  1887. log.Trace("Updating %s: %d", checker.desc, id)
  1888. _, err = x.Exec(checker.correctSQL, id, id)
  1889. if err != nil {
  1890. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1891. }
  1892. }
  1893. }
  1894. // CheckRepoStats checks the repository stats
  1895. func CheckRepoStats() {
  1896. if !taskStatusTable.StartIfNotRunning(checkRepos) {
  1897. return
  1898. }
  1899. defer taskStatusTable.Stop(checkRepos)
  1900. log.Trace("Doing: CheckRepoStats")
  1901. checkers := []*repoChecker{
  1902. // Repository.NumWatches
  1903. {
  1904. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1905. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1906. "repository count 'num_watches'",
  1907. },
  1908. // Repository.NumStars
  1909. {
  1910. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1911. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1912. "repository count 'num_stars'",
  1913. },
  1914. // Label.NumIssues
  1915. {
  1916. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1917. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1918. "label count 'num_issues'",
  1919. },
  1920. // User.NumRepos
  1921. {
  1922. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1923. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1924. "user count 'num_repos'",
  1925. },
  1926. // Issue.NumComments
  1927. {
  1928. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1929. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1930. "issue count 'num_comments'",
  1931. },
  1932. }
  1933. for i := range checkers {
  1934. repoStatsCheck(checkers[i])
  1935. }
  1936. // ***** START: Repository.NumClosedIssues *****
  1937. desc := "repository count 'num_closed_issues'"
  1938. 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)
  1939. if err != nil {
  1940. log.Error(4, "Select %s: %v", desc, err)
  1941. } else {
  1942. for _, result := range results {
  1943. id := com.StrTo(result["id"]).MustInt64()
  1944. log.Trace("Updating %s: %d", desc, id)
  1945. _, 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)
  1946. if err != nil {
  1947. log.Error(4, "Update %s[%d]: %v", desc, id, err)
  1948. }
  1949. }
  1950. }
  1951. // ***** END: Repository.NumClosedIssues *****
  1952. // FIXME: use checker when stop supporting old fork repo format.
  1953. // ***** START: Repository.NumForks *****
  1954. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1955. if err != nil {
  1956. log.Error(4, "Select repository count 'num_forks': %v", err)
  1957. } else {
  1958. for _, result := range results {
  1959. id := com.StrTo(result["id"]).MustInt64()
  1960. log.Trace("Updating repository count 'num_forks': %d", id)
  1961. repo, err := GetRepositoryByID(id)
  1962. if err != nil {
  1963. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1964. continue
  1965. }
  1966. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1967. if err != nil {
  1968. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1969. continue
  1970. }
  1971. repo.NumForks = int(parseCountResult(rawResult))
  1972. if err = UpdateRepository(repo, false); err != nil {
  1973. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1974. continue
  1975. }
  1976. }
  1977. }
  1978. // ***** END: Repository.NumForks *****
  1979. }
  1980. // ___________ __
  1981. // \_ _____/__________| | __
  1982. // | __)/ _ \_ __ \ |/ /
  1983. // | \( <_> ) | \/ <
  1984. // \___ / \____/|__| |__|_ \
  1985. // \/ \/
  1986. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1987. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1988. repo := new(Repository)
  1989. has, _ := x.
  1990. Where("owner_id=? AND fork_id=?", ownerID, repoID).
  1991. Get(repo)
  1992. return repo, has
  1993. }
  1994. // ForkRepository forks a repository
  1995. func ForkRepository(doer, u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1996. forkedRepo, err := oldRepo.GetUserFork(u.ID)
  1997. if err != nil {
  1998. return nil, err
  1999. }
  2000. if forkedRepo != nil {
  2001. return nil, ErrRepoAlreadyExist{
  2002. Uname: u.Name,
  2003. Name: forkedRepo.Name,
  2004. }
  2005. }
  2006. repo := &Repository{
  2007. OwnerID: u.ID,
  2008. Owner: u,
  2009. Name: name,
  2010. LowerName: strings.ToLower(name),
  2011. Description: desc,
  2012. DefaultBranch: oldRepo.DefaultBranch,
  2013. IsPrivate: oldRepo.IsPrivate,
  2014. IsFork: true,
  2015. ForkID: oldRepo.ID,
  2016. }
  2017. sess := x.NewSession()
  2018. defer sess.Close()
  2019. if err = sess.Begin(); err != nil {
  2020. return nil, err
  2021. }
  2022. if err = createRepository(sess, doer, u, repo); err != nil {
  2023. return nil, err
  2024. }
  2025. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  2026. return nil, err
  2027. }
  2028. repoPath := RepoPath(u.Name, repo.Name)
  2029. _, stderr, err := process.GetManager().ExecTimeout(10*time.Minute,
  2030. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  2031. "git", "clone", "--bare", oldRepo.RepoPath(), repoPath)
  2032. if err != nil {
  2033. return nil, fmt.Errorf("git clone: %v", stderr)
  2034. }
  2035. _, stderr, err = process.GetManager().ExecDir(-1,
  2036. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  2037. "git", "update-server-info")
  2038. if err != nil {
  2039. return nil, fmt.Errorf("git update-server-info: %v", stderr)
  2040. }
  2041. if err = createDelegateHooks(repoPath); err != nil {
  2042. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2043. }
  2044. //Commit repo to get Fork ID
  2045. err = sess.Commit()
  2046. if err != nil {
  2047. return nil, err
  2048. }
  2049. if err = repo.UpdateSize(); err != nil {
  2050. log.Error(4, "Failed to update size for repository: %v", err)
  2051. }
  2052. // Copy LFS meta objects in new session
  2053. sess2 := x.NewSession()
  2054. defer sess2.Close()
  2055. if err = sess2.Begin(); err != nil {
  2056. return nil, err
  2057. }
  2058. var lfsObjects []*LFSMetaObject
  2059. if err = sess2.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
  2060. return nil, err
  2061. }
  2062. for _, v := range lfsObjects {
  2063. v.ID = 0
  2064. v.RepositoryID = repo.ID
  2065. if _, err = sess2.Insert(v); err != nil {
  2066. return nil, err
  2067. }
  2068. }
  2069. return repo, sess2.Commit()
  2070. }
  2071. // GetForks returns all the forks of the repository
  2072. func (repo *Repository) GetForks() ([]*Repository, error) {
  2073. forks := make([]*Repository, 0, repo.NumForks)
  2074. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2075. }
  2076. // GetUserFork return user forked repository from this repository, if not forked return nil
  2077. func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
  2078. var forkedRepo Repository
  2079. has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
  2080. if err != nil {
  2081. return nil, err
  2082. }
  2083. if !has {
  2084. return nil, nil
  2085. }
  2086. return &forkedRepo, nil
  2087. }