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.

2473 lines
72 KiB

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