2020-10-13 22:06:00 -06:00
// Copyright 2020 The Gitea Authors. All rights reserved.
2022-11-27 11:20:29 -07:00
// SPDX-License-Identifier: MIT
2020-10-13 22:06:00 -06:00
package migrations
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"code.gitea.io/gitea/modules/log"
2021-11-16 08:25:33 -07:00
base "code.gitea.io/gitea/modules/migration"
2020-10-13 22:06:00 -06:00
"code.gitea.io/gitea/modules/structs"
gitea_sdk "code.gitea.io/sdk/gitea"
)
var (
_ base . Downloader = & GiteaDownloader { }
_ base . DownloaderFactory = & GiteaDownloaderFactory { }
)
func init ( ) {
RegisterDownloaderFactory ( & GiteaDownloaderFactory { } )
}
// GiteaDownloaderFactory defines a gitea downloader factory
2022-01-20 10:46:10 -07:00
type GiteaDownloaderFactory struct { }
2020-10-13 22:06:00 -06:00
// New returns a Downloader related to this factory according MigrateOptions
func ( f * GiteaDownloaderFactory ) New ( ctx context . Context , opts base . MigrateOptions ) ( base . Downloader , error ) {
u , err := url . Parse ( opts . CloneAddr )
if err != nil {
return nil , err
}
baseURL := u . Scheme + "://" + u . Host
repoNameSpace := strings . TrimPrefix ( u . Path , "/" )
repoNameSpace = strings . TrimSuffix ( repoNameSpace , ".git" )
path := strings . Split ( repoNameSpace , "/" )
if len ( path ) < 2 {
2020-10-27 15:34:56 -06:00
return nil , fmt . Errorf ( "invalid path: %s" , repoNameSpace )
2020-10-13 22:06:00 -06:00
}
repoPath := strings . Join ( path [ len ( path ) - 2 : ] , "/" )
if len ( path ) > 2 {
subPath := strings . Join ( path [ : len ( path ) - 2 ] , "/" )
baseURL += "/" + subPath
}
log . Trace ( "Create gitea downloader. BaseURL: %s RepoName: %s" , baseURL , repoNameSpace )
return NewGiteaDownloader ( ctx , baseURL , repoPath , opts . AuthUsername , opts . AuthPassword , opts . AuthToken )
}
// GitServiceType returns the type of git service
func ( f * GiteaDownloaderFactory ) GitServiceType ( ) structs . GitServiceType {
return structs . GiteaService
}
// GiteaDownloader implements a Downloader interface to get repository information's
type GiteaDownloader struct {
2021-01-21 12:33:58 -07:00
base . NullDownloader
2020-10-13 22:06:00 -06:00
ctx context . Context
client * gitea_sdk . Client
2022-09-04 04:47:56 -06:00
baseURL string
2020-10-13 22:06:00 -06:00
repoOwner string
repoName string
pagination bool
maxPerPage int
}
// NewGiteaDownloader creates a gitea Downloader via gitea API
2022-08-30 20:15:45 -06:00
//
// Use either a username/password or personal token. token is preferred
// Note: Public access only allows very basic access
2020-10-13 22:06:00 -06:00
func NewGiteaDownloader ( ctx context . Context , baseURL , repoPath , username , password , token string ) ( * GiteaDownloader , error ) {
giteaClient , err := gitea_sdk . NewClient (
baseURL ,
gitea_sdk . SetToken ( token ) ,
gitea_sdk . SetBasicAuth ( username , password ) ,
gitea_sdk . SetContext ( ctx ) ,
2021-11-20 02:34:05 -07:00
gitea_sdk . SetHTTPClient ( NewMigrationHTTPClient ( ) ) ,
2020-10-13 22:06:00 -06:00
)
if err != nil {
2020-10-27 15:34:56 -06:00
log . Error ( fmt . Sprintf ( "Failed to create NewGiteaDownloader for: %s. Error: %v" , baseURL , err ) )
2020-10-13 22:06:00 -06:00
return nil , err
}
path := strings . Split ( repoPath , "/" )
paginationSupport := true
2021-01-21 12:33:58 -07:00
if err = giteaClient . CheckServerVersionConstraint ( ">=1.12" ) ; err != nil {
2020-10-13 22:06:00 -06:00
paginationSupport = false
}
// set small maxPerPage since we can only guess
// (default would be 50 but this can differ)
maxPerPage := 10
2020-10-21 23:46:18 -06:00
// gitea instances >=1.13 can tell us what maximum they have
apiConf , _ , err := giteaClient . GetGlobalAPISettings ( )
if err != nil {
log . Info ( "Unable to get global API settings. Ignoring these." )
log . Debug ( "giteaClient.GetGlobalAPISettings. Error: %v" , err )
}
if apiConf != nil {
2020-10-13 22:06:00 -06:00
maxPerPage = apiConf . MaxResponseItems
}
return & GiteaDownloader {
ctx : ctx ,
client : giteaClient ,
2022-09-04 04:47:56 -06:00
baseURL : baseURL ,
2020-10-13 22:06:00 -06:00
repoOwner : path [ 0 ] ,
repoName : path [ 1 ] ,
pagination : paginationSupport ,
maxPerPage : maxPerPage ,
} , nil
}
// SetContext set context
func ( g * GiteaDownloader ) SetContext ( ctx context . Context ) {
g . ctx = ctx
}
2022-09-04 04:47:56 -06:00
// String implements Stringer
func ( g * GiteaDownloader ) String ( ) string {
return fmt . Sprintf ( "migration from gitea server %s %s/%s" , g . baseURL , g . repoOwner , g . repoName )
}
Rewrite logger system (#24726)
## ⚠️ Breaking
The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.
Although many legacy options still work, it's encouraged to upgrade to
the new options.
The SMTP logger is deleted because SMTP is not suitable to collect logs.
If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.
## Description
Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)
Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)
There is a new document (with examples): `logging-config.en-us.md`
This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.
## The old problems
The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.
## The new design
See `logger.go` for documents.
## Screenshot
<details>
![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)
![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)
![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)
</details>
## TODO
* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)
---------
Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-21 16:35:11 -06:00
func ( g * GiteaDownloader ) LogString ( ) string {
2022-09-04 04:47:56 -06:00
if g == nil {
Rewrite logger system (#24726)
## ⚠️ Breaking
The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.
Although many legacy options still work, it's encouraged to upgrade to
the new options.
The SMTP logger is deleted because SMTP is not suitable to collect logs.
If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.
## Description
Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)
Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)
There is a new document (with examples): `logging-config.en-us.md`
This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.
## The old problems
The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.
## The new design
See `logger.go` for documents.
## Screenshot
<details>
![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)
![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)
![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)
</details>
## TODO
* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)
---------
Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-21 16:35:11 -06:00
return "<GiteaDownloader nil>"
2022-09-04 04:47:56 -06:00
}
Rewrite logger system (#24726)
## ⚠️ Breaking
The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.
Although many legacy options still work, it's encouraged to upgrade to
the new options.
The SMTP logger is deleted because SMTP is not suitable to collect logs.
If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.
## Description
Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)
Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)
There is a new document (with examples): `logging-config.en-us.md`
This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.
## The old problems
The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.
## The new design
See `logger.go` for documents.
## Screenshot
<details>
![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)
![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)
![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)
</details>
## TODO
* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)
---------
Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-21 16:35:11 -06:00
return fmt . Sprintf ( "<GiteaDownloader %s %s/%s>" , g . baseURL , g . repoOwner , g . repoName )
2022-09-04 04:47:56 -06:00
}
2020-10-13 22:06:00 -06:00
// GetRepoInfo returns a repository information
func ( g * GiteaDownloader ) GetRepoInfo ( ) ( * base . Repository , error ) {
if g == nil {
return nil , errors . New ( "error: GiteaDownloader is nil" )
}
repo , _ , err := g . client . GetRepo ( g . repoOwner , g . repoName )
if err != nil {
return nil , err
}
return & base . Repository {
Name : repo . Name ,
Owner : repo . Owner . UserName ,
IsPrivate : repo . Private ,
Description : repo . Description ,
CloneURL : repo . CloneURL ,
OriginalURL : repo . HTMLURL ,
DefaultBranch : repo . DefaultBranch ,
} , nil
}
// GetTopics return gitea topics
func ( g * GiteaDownloader ) GetTopics ( ) ( [ ] string , error ) {
topics , _ , err := g . client . ListRepoTopics ( g . repoOwner , g . repoName , gitea_sdk . ListRepoTopicsOptions { } )
return topics , err
}
// GetMilestones returns milestones
func ( g * GiteaDownloader ) GetMilestones ( ) ( [ ] * base . Milestone , error ) {
2022-01-20 10:46:10 -07:00
milestones := make ( [ ] * base . Milestone , 0 , g . maxPerPage )
2020-10-13 22:06:00 -06:00
for i := 1 ; ; i ++ {
// make sure gitea can shutdown gracefully
select {
case <- g . ctx . Done ( ) :
return nil , nil
default :
}
ms , _ , err := g . client . ListRepoMilestones ( g . repoOwner , g . repoName , gitea_sdk . ListMilestoneOption {
ListOptions : gitea_sdk . ListOptions {
PageSize : g . maxPerPage ,
Page : i ,
} ,
State : gitea_sdk . StateAll ,
} )
if err != nil {
return nil , err
}
for i := range ms {
// old gitea instances dont have this information
2021-08-17 18:47:18 -06:00
createdAT := time . Time { }
2020-10-13 22:06:00 -06:00
var updatedAT * time . Time
if ms [ i ] . Closed != nil {
createdAT = * ms [ i ] . Closed
updatedAT = ms [ i ] . Closed
}
// new gitea instances (>=1.13) do
if ! ms [ i ] . Created . IsZero ( ) {
createdAT = ms [ i ] . Created
}
if ms [ i ] . Updated != nil && ! ms [ i ] . Updated . IsZero ( ) {
updatedAT = ms [ i ] . Updated
}
milestones = append ( milestones , & base . Milestone {
Title : ms [ i ] . Title ,
Description : ms [ i ] . Description ,
Deadline : ms [ i ] . Deadline ,
Created : createdAT ,
Updated : updatedAT ,
Closed : ms [ i ] . Closed ,
State : string ( ms [ i ] . State ) ,
} )
}
if ! g . pagination || len ( ms ) < g . maxPerPage {
break
}
}
return milestones , nil
}
func ( g * GiteaDownloader ) convertGiteaLabel ( label * gitea_sdk . Label ) * base . Label {
return & base . Label {
Name : label . Name ,
Color : label . Color ,
Description : label . Description ,
}
}
// GetLabels returns labels
func ( g * GiteaDownloader ) GetLabels ( ) ( [ ] * base . Label , error ) {
2022-01-20 10:46:10 -07:00
labels := make ( [ ] * base . Label , 0 , g . maxPerPage )
2020-10-13 22:06:00 -06:00
for i := 1 ; ; i ++ {
// make sure gitea can shutdown gracefully
select {
case <- g . ctx . Done ( ) :
return nil , nil
default :
}
ls , _ , err := g . client . ListRepoLabels ( g . repoOwner , g . repoName , gitea_sdk . ListLabelsOptions { ListOptions : gitea_sdk . ListOptions {
PageSize : g . maxPerPage ,
Page : i ,
} } )
if err != nil {
return nil , err
}
for i := range ls {
labels = append ( labels , g . convertGiteaLabel ( ls [ i ] ) )
}
if ! g . pagination || len ( ls ) < g . maxPerPage {
break
}
}
return labels , nil
}
func ( g * GiteaDownloader ) convertGiteaRelease ( rel * gitea_sdk . Release ) * base . Release {
r := & base . Release {
TagName : rel . TagName ,
TargetCommitish : rel . Target ,
Name : rel . Title ,
Body : rel . Note ,
Draft : rel . IsDraft ,
Prerelease : rel . IsPrerelease ,
PublisherID : rel . Publisher . ID ,
PublisherName : rel . Publisher . UserName ,
PublisherEmail : rel . Publisher . Email ,
Published : rel . PublishedAt ,
Created : rel . CreatedAt ,
}
2021-11-20 02:34:05 -07:00
httpClient := NewMigrationHTTPClient ( )
2021-08-18 07:10:39 -06:00
2020-10-13 22:06:00 -06:00
for _ , asset := range rel . Attachments {
size := int ( asset . Size )
dlCount := int ( asset . DownloadCount )
2020-12-26 20:34:19 -07:00
r . Assets = append ( r . Assets , & base . ReleaseAsset {
2020-10-13 22:06:00 -06:00
ID : asset . ID ,
Name : asset . Name ,
Size : & size ,
DownloadCount : & dlCount ,
Created : asset . Created ,
DownloadURL : & asset . DownloadURL ,
2020-12-26 20:34:19 -07:00
DownloadFunc : func ( ) ( io . ReadCloser , error ) {
asset , _ , err := g . client . GetReleaseAttachment ( g . repoOwner , g . repoName , rel . ID , asset . ID )
if err != nil {
return nil , err
}
2022-09-04 04:47:56 -06:00
if ! hasBaseURL ( asset . DownloadURL , g . baseURL ) {
WarnAndNotice ( "Unexpected AssetURL for assetID[%d] in %s: %s" , asset . ID , g , asset . DownloadURL )
return io . NopCloser ( strings . NewReader ( asset . DownloadURL ) ) , nil
}
2020-12-26 20:34:19 -07:00
// FIXME: for a private download?
2021-08-18 07:10:39 -06:00
req , err := http . NewRequest ( "GET" , asset . DownloadURL , nil )
if err != nil {
return nil , err
}
resp , err := httpClient . Do ( req )
2020-12-26 20:34:19 -07:00
if err != nil {
return nil , err
}
// resp.Body is closed by the uploader
return resp . Body , nil
} ,
2020-10-13 22:06:00 -06:00
} )
}
return r
}
// GetReleases returns releases
func ( g * GiteaDownloader ) GetReleases ( ) ( [ ] * base . Release , error ) {
2022-01-20 10:46:10 -07:00
releases := make ( [ ] * base . Release , 0 , g . maxPerPage )
2020-10-13 22:06:00 -06:00
for i := 1 ; ; i ++ {
// make sure gitea can shutdown gracefully
select {
case <- g . ctx . Done ( ) :
return nil , nil
default :
}
rl , _ , err := g . client . ListReleases ( g . repoOwner , g . repoName , gitea_sdk . ListReleasesOptions { ListOptions : gitea_sdk . ListOptions {
PageSize : g . maxPerPage ,
Page : i ,
} } )
if err != nil {
return nil , err
}
for i := range rl {
releases = append ( releases , g . convertGiteaRelease ( rl [ i ] ) )
}
if ! g . pagination || len ( rl ) < g . maxPerPage {
break
}
}
return releases , nil
}
func ( g * GiteaDownloader ) getIssueReactions ( index int64 ) ( [ ] * base . Reaction , error ) {
var reactions [ ] * base . Reaction
if err := g . client . CheckServerVersionConstraint ( ">=1.11" ) ; err != nil {
log . Info ( "GiteaDownloader: instance to old, skip getIssueReactions" )
return reactions , nil
}
rl , _ , err := g . client . GetIssueReactions ( g . repoOwner , g . repoName , index )
if err != nil {
return nil , err
}
for _ , reaction := range rl {
reactions = append ( reactions , & base . Reaction {
UserID : reaction . User . ID ,
UserName : reaction . User . UserName ,
Content : reaction . Reaction ,
} )
}
return reactions , nil
}
func ( g * GiteaDownloader ) getCommentReactions ( commentID int64 ) ( [ ] * base . Reaction , error ) {
var reactions [ ] * base . Reaction
if err := g . client . CheckServerVersionConstraint ( ">=1.11" ) ; err != nil {
log . Info ( "GiteaDownloader: instance to old, skip getCommentReactions" )
return reactions , nil
}
rl , _ , err := g . client . GetIssueCommentReactions ( g . repoOwner , g . repoName , commentID )
if err != nil {
return nil , err
}
for i := range rl {
reactions = append ( reactions , & base . Reaction {
UserID : rl [ i ] . User . ID ,
UserName : rl [ i ] . User . UserName ,
Content : rl [ i ] . Reaction ,
} )
}
return reactions , nil
}
// GetIssues returns issues according start and limit
func ( g * GiteaDownloader ) GetIssues ( page , perPage int ) ( [ ] * base . Issue , bool , error ) {
if perPage > g . maxPerPage {
perPage = g . maxPerPage
}
2022-01-20 10:46:10 -07:00
allIssues := make ( [ ] * base . Issue , 0 , perPage )
2020-10-13 22:06:00 -06:00
issues , _ , err := g . client . ListRepoIssues ( g . repoOwner , g . repoName , gitea_sdk . ListIssueOption {
ListOptions : gitea_sdk . ListOptions { Page : page , PageSize : perPage } ,
State : gitea_sdk . StateAll ,
Type : gitea_sdk . IssueTypeIssue ,
} )
if err != nil {
2022-10-24 13:29:17 -06:00
return nil , false , fmt . Errorf ( "error while listing issues: %w" , err )
2020-10-13 22:06:00 -06:00
}
for _ , issue := range issues {
2022-01-20 10:46:10 -07:00
labels := make ( [ ] * base . Label , 0 , len ( issue . Labels ) )
2020-10-13 22:06:00 -06:00
for i := range issue . Labels {
labels = append ( labels , g . convertGiteaLabel ( issue . Labels [ i ] ) )
}
var milestone string
if issue . Milestone != nil {
milestone = issue . Milestone . Title
}
reactions , err := g . getIssueReactions ( issue . Index )
if err != nil {
2022-09-04 04:47:56 -06:00
WarnAndNotice ( "Unable to load reactions during migrating issue #%d in %s. Error: %v" , issue . Index , g , err )
2020-10-13 22:06:00 -06:00
}
var assignees [ ] string
for i := range issue . Assignees {
assignees = append ( assignees , issue . Assignees [ i ] . UserName )
}
allIssues = append ( allIssues , & base . Issue {
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
Title : issue . Title ,
Number : issue . Index ,
PosterID : issue . Poster . ID ,
PosterName : issue . Poster . UserName ,
PosterEmail : issue . Poster . Email ,
Content : issue . Body ,
Milestone : milestone ,
State : string ( issue . State ) ,
Created : issue . Created ,
Updated : issue . Updated ,
Closed : issue . Closed ,
Reactions : reactions ,
Labels : labels ,
Assignees : assignees ,
IsLocked : issue . IsLocked ,
ForeignIndex : issue . Index ,
2020-10-13 22:06:00 -06:00
} )
}
isEnd := len ( issues ) < perPage
if ! g . pagination {
isEnd = len ( issues ) == 0
}
return allIssues , isEnd , nil
}
// GetComments returns comments according issueNumber
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
func ( g * GiteaDownloader ) GetComments ( commentable base . Commentable ) ( [ ] * base . Comment , bool , error ) {
2022-01-20 10:46:10 -07:00
allComments := make ( [ ] * base . Comment , 0 , g . maxPerPage )
2020-10-13 22:06:00 -06:00
2021-09-06 10:00:50 -06:00
for i := 1 ; ; i ++ {
// make sure gitea can shutdown gracefully
select {
case <- g . ctx . Done ( ) :
return nil , false , nil
default :
}
2020-10-13 22:06:00 -06:00
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
comments , _ , err := g . client . ListIssueComments ( g . repoOwner , g . repoName , commentable . GetForeignIndex ( ) , gitea_sdk . ListIssueCommentOptions { ListOptions : gitea_sdk . ListOptions {
2021-09-06 10:00:50 -06:00
PageSize : g . maxPerPage ,
Page : i ,
} } )
2020-10-13 22:06:00 -06:00
if err != nil {
2022-10-24 13:29:17 -06:00
return nil , false , fmt . Errorf ( "error while listing comments for issue #%d. Error: %w" , commentable . GetForeignIndex ( ) , err )
2021-09-06 10:00:50 -06:00
}
for _ , comment := range comments {
reactions , err := g . getCommentReactions ( comment . ID )
if err != nil {
2022-09-04 04:47:56 -06:00
WarnAndNotice ( "Unable to load comment reactions during migrating issue #%d for comment %d in %s. Error: %v" , commentable . GetForeignIndex ( ) , comment . ID , g , err )
2020-10-29 15:41:49 -06:00
}
2021-09-06 10:00:50 -06:00
allComments = append ( allComments , & base . Comment {
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
IssueIndex : commentable . GetLocalIndex ( ) ,
2022-03-06 12:00:41 -07:00
Index : comment . ID ,
2021-09-06 10:00:50 -06:00
PosterID : comment . Poster . ID ,
PosterName : comment . Poster . UserName ,
PosterEmail : comment . Poster . Email ,
Content : comment . Body ,
Created : comment . Created ,
Updated : comment . Updated ,
Reactions : reactions ,
} )
2020-10-13 22:06:00 -06:00
}
2021-09-06 10:00:50 -06:00
if ! g . pagination || len ( comments ) < g . maxPerPage {
break
}
2020-10-13 22:06:00 -06:00
}
2021-06-30 01:23:49 -06:00
return allComments , true , nil
2020-10-13 22:06:00 -06:00
}
// GetPullRequests returns pull requests according page and perPage
func ( g * GiteaDownloader ) GetPullRequests ( page , perPage int ) ( [ ] * base . PullRequest , bool , error ) {
if perPage > g . maxPerPage {
perPage = g . maxPerPage
}
2022-01-20 10:46:10 -07:00
allPRs := make ( [ ] * base . PullRequest , 0 , perPage )
2020-10-13 22:06:00 -06:00
prs , _ , err := g . client . ListRepoPullRequests ( g . repoOwner , g . repoName , gitea_sdk . ListPullRequestsOptions {
ListOptions : gitea_sdk . ListOptions {
Page : page ,
PageSize : perPage ,
} ,
State : gitea_sdk . StateAll ,
} )
if err != nil {
2022-10-24 13:29:17 -06:00
return nil , false , fmt . Errorf ( "error while listing pull requests (page: %d, pagesize: %d). Error: %w" , page , perPage , err )
2020-10-13 22:06:00 -06:00
}
for _ , pr := range prs {
var milestone string
if pr . Milestone != nil {
milestone = pr . Milestone . Title
}
2022-01-20 10:46:10 -07:00
labels := make ( [ ] * base . Label , 0 , len ( pr . Labels ) )
2020-10-13 22:06:00 -06:00
for i := range pr . Labels {
labels = append ( labels , g . convertGiteaLabel ( pr . Labels [ i ] ) )
}
var (
headUserName string
headRepoName string
headCloneURL string
headRef string
headSHA string
)
if pr . Head != nil {
if pr . Head . Repository != nil {
headUserName = pr . Head . Repository . Owner . UserName
headRepoName = pr . Head . Repository . Name
headCloneURL = pr . Head . Repository . CloneURL
}
headSHA = pr . Head . Sha
headRef = pr . Head . Ref
}
var mergeCommitSHA string
if pr . MergedCommitID != nil {
mergeCommitSHA = * pr . MergedCommitID
}
reactions , err := g . getIssueReactions ( pr . Index )
if err != nil {
2022-09-04 04:47:56 -06:00
WarnAndNotice ( "Unable to load reactions during migrating pull #%d in %s. Error: %v" , pr . Index , g , err )
2020-10-13 22:06:00 -06:00
}
var assignees [ ] string
for i := range pr . Assignees {
assignees = append ( assignees , pr . Assignees [ i ] . UserName )
}
2021-08-17 18:47:18 -06:00
createdAt := time . Time { }
2020-10-13 22:06:00 -06:00
if pr . Created != nil {
createdAt = * pr . Created
}
2021-08-17 18:47:18 -06:00
updatedAt := time . Time { }
2020-10-13 22:06:00 -06:00
if pr . Created != nil {
updatedAt = * pr . Updated
}
closedAt := pr . Closed
if pr . Merged != nil && closedAt == nil {
closedAt = pr . Merged
}
allPRs = append ( allPRs , & base . PullRequest {
Title : pr . Title ,
Number : pr . Index ,
PosterID : pr . Poster . ID ,
PosterName : pr . Poster . UserName ,
PosterEmail : pr . Poster . Email ,
Content : pr . Body ,
State : string ( pr . State ) ,
Created : createdAt ,
Updated : updatedAt ,
Closed : closedAt ,
Labels : labels ,
Milestone : milestone ,
Reactions : reactions ,
Assignees : assignees ,
Merged : pr . HasMerged ,
MergedTime : pr . Merged ,
MergeCommitSHA : mergeCommitSHA ,
IsLocked : pr . IsLocked ,
PatchURL : pr . PatchURL ,
Head : base . PullRequestBranch {
Ref : headRef ,
SHA : headSHA ,
RepoName : headRepoName ,
OwnerName : headUserName ,
CloneURL : headCloneURL ,
} ,
Base : base . PullRequestBranch {
Ref : pr . Base . Ref ,
SHA : pr . Base . Sha ,
RepoName : g . repoName ,
OwnerName : g . repoOwner ,
} ,
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
ForeignIndex : pr . Index ,
2020-10-13 22:06:00 -06:00
} )
2022-09-04 04:47:56 -06:00
// SECURITY: Ensure that the PR is safe
_ = CheckAndEnsureSafePR ( allPRs [ len ( allPRs ) - 1 ] , g . baseURL , g )
2020-10-13 22:06:00 -06:00
}
isEnd := len ( prs ) < perPage
if ! g . pagination {
isEnd = len ( prs ) == 0
}
return allPRs , isEnd , nil
}
// GetReviews returns pull requests review
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
func ( g * GiteaDownloader ) GetReviews ( reviewable base . Reviewable ) ( [ ] * base . Review , error ) {
2020-10-13 22:06:00 -06:00
if err := g . client . CheckServerVersionConstraint ( ">=1.12" ) ; err != nil {
log . Info ( "GiteaDownloader: instance to old, skip GetReviews" )
return nil , nil
}
2022-01-20 10:46:10 -07:00
allReviews := make ( [ ] * base . Review , 0 , g . maxPerPage )
2020-10-13 22:06:00 -06:00
for i := 1 ; ; i ++ {
// make sure gitea can shutdown gracefully
select {
case <- g . ctx . Done ( ) :
return nil , nil
default :
}
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
prl , _ , err := g . client . ListPullReviews ( g . repoOwner , g . repoName , reviewable . GetForeignIndex ( ) , gitea_sdk . ListPullReviewsOptions { ListOptions : gitea_sdk . ListOptions {
2020-10-13 22:06:00 -06:00
Page : i ,
PageSize : g . maxPerPage ,
} } )
if err != nil {
return nil , err
}
for _ , pr := range prl {
2022-06-08 20:50:05 -06:00
if pr . Reviewer == nil {
// Presumably this is a team review which we cannot migrate at present but we have to skip this review as otherwise the review will be mapped on to an incorrect user.
// TODO: handle team reviews
continue
}
2020-10-13 22:06:00 -06:00
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
rcl , _ , err := g . client . ListPullReviewComments ( g . repoOwner , g . repoName , reviewable . GetForeignIndex ( ) , pr . ID )
2020-10-13 22:06:00 -06:00
if err != nil {
return nil , err
}
var reviewComments [ ] * base . ReviewComment
for i := range rcl {
line := int ( rcl [ i ] . LineNum )
if rcl [ i ] . OldLineNum > 0 {
line = int ( rcl [ i ] . OldLineNum ) * - 1
}
reviewComments = append ( reviewComments , & base . ReviewComment {
ID : rcl [ i ] . ID ,
Content : rcl [ i ] . Body ,
TreePath : rcl [ i ] . Path ,
DiffHunk : rcl [ i ] . DiffHunk ,
Line : line ,
CommitID : rcl [ i ] . CommitID ,
PosterID : rcl [ i ] . Reviewer . ID ,
CreatedAt : rcl [ i ] . Created ,
UpdatedAt : rcl [ i ] . Updated ,
} )
}
2022-06-08 20:50:05 -06:00
review := & base . Review {
2020-10-13 22:06:00 -06:00
ID : pr . ID ,
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.
At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.
The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:
1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.
The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.
The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.
The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.
The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.
The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.
The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.
The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.
The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.
---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2022-03-17 11:08:35 -06:00
IssueIndex : reviewable . GetLocalIndex ( ) ,
2020-10-13 22:06:00 -06:00
ReviewerID : pr . Reviewer . ID ,
ReviewerName : pr . Reviewer . UserName ,
Official : pr . Official ,
CommitID : pr . CommitID ,
Content : pr . Body ,
CreatedAt : pr . Submitted ,
State : string ( pr . State ) ,
Comments : reviewComments ,
2022-06-08 20:50:05 -06:00
}
allReviews = append ( allReviews , review )
2020-10-13 22:06:00 -06:00
}
if len ( prl ) < g . maxPerPage {
break
}
}
return allReviews , nil
}