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.

repo.go 73KB

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