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.

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