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.

2519 lines
73 KiB

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