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

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