2024-02-14 23:03:30 +03:00
package gitea
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
2024-02-21 18:52:55 +03:00
"regexp"
2024-02-14 23:03:30 +03:00
"strings"
"text/template"
"time"
"git.unistack.org/unistack-org/pkgdash/internal/configcli"
"git.unistack.org/unistack-org/pkgdash/internal/modules"
"github.com/go-git/go-git/v5"
gitconfig "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
httpauth "github.com/go-git/go-git/v5/plumbing/transport/http"
"go.unistack.org/micro/v4/logger"
)
2024-03-15 21:18:58 +03:00
var (
2024-03-21 14:36:32 +03:00
ErrPRNotExist = errors . New ( "pull request does not exist" )
2024-03-15 21:18:58 +03:00
)
2024-02-14 23:03:30 +03:00
type Gitea struct {
2024-03-15 21:18:58 +03:00
URL string
Token string
PRTitle string
PRBody string
Repository string
2024-03-15 23:12:39 +03:00
Owner string
2024-02-14 23:03:30 +03:00
}
2024-03-15 21:18:58 +03:00
func NewGitea ( cfg configcli . Config ) * Gitea {
2024-02-14 23:03:30 +03:00
return & Gitea {
2024-03-15 21:18:58 +03:00
URL : cfg . Source . APIURL ,
2024-03-17 15:49:59 +03:00
Token : os . Getenv ( "gitea_token" ) ,
2024-03-15 21:18:58 +03:00
PRTitle : cfg . PullRequestTitle ,
PRBody : cfg . PullRequestBody ,
Repository : cfg . Source . Repository ,
2024-03-15 23:12:39 +03:00
Owner : cfg . Source . Owner ,
2024-02-14 23:03:30 +03:00
}
}
type giteaPull struct {
URL string ` json:"url" `
Title string ` json:"title" `
Base struct {
Ref string ` json:"ref" `
} ` json:"base" `
2024-03-21 14:36:32 +03:00
Head struct {
Ref string ` json:"ref" `
} ` json:"head" `
2024-02-14 23:03:30 +03:00
ID int64 ` json:"id" `
}
2024-03-15 21:18:58 +03:00
func ( g * Gitea ) RequestOpen ( ctx context . Context , branch string , path string , mod modules . Update ) error {
2024-03-21 15:29:36 +03:00
logger . Debugf ( ctx , fmt . Sprintf ( "RequestOpen start, mod title: %s" , path ) )
2024-02-14 23:03:30 +03:00
var buf [ ] byte
var err error
// создания шаблона названия для пулл реквеста
2024-03-15 21:18:58 +03:00
tplTitle , err := template . New ( "pull_request_title" ) . Parse ( g . PRTitle )
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to parse template: %v" , err ) )
2024-02-14 23:03:30 +03:00
}
wTitle := bytes . NewBuffer ( nil )
// создания шаблона тела для пулл реквеста
2024-03-15 21:18:58 +03:00
tplBody , err := template . New ( "pull_request_body" ) . Parse ( g . PRTitle )
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to parse template: %v" , err ) )
2024-02-14 23:03:30 +03:00
}
wBody := bytes . NewBuffer ( nil )
2024-03-15 23:12:39 +03:00
data := map [ string ] string {
"Name" : path ,
"VersionOld" : mod . Module . Version ,
"VersionNew" : mod . Version ,
}
if err = tplTitle . Execute ( wTitle , data ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to execute template: %v" , err ) )
2024-03-15 23:12:39 +03:00
}
if err = tplBody . Execute ( wBody , data ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to execute template: %v" , err ) )
2024-03-15 23:12:39 +03:00
}
2024-02-14 23:03:30 +03:00
// открытие гит репозитория с опцией обхода репозитория для нахождения .git
repo , err := git . PlainOpenWithOptions ( "." , & git . PlainOpenOptions { DetectDotGit : true } )
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to open repo: %v" , err ) )
2024-02-14 23:03:30 +03:00
}
//извлекаем ссылки с объектами из удаленного объекта??
if err = repo . FetchContext ( ctx , & git . FetchOptions {
2024-03-15 21:18:58 +03:00
Auth : & httpauth . BasicAuth { Username : g . Token , Password : g . Token } ,
2024-02-14 23:03:30 +03:00
Force : true ,
} ) ; err != nil && err != git . NoErrAlreadyUpToDate {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to fetch repo: %v" , err ) )
2024-02-21 18:52:55 +03:00
} //обновляем репозиторий
2024-02-14 23:03:30 +03:00
var headRef * plumbing . Reference // вроде ссылка на гит
refIter , err := repo . Branches ( ) //получение веток
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to get branches: %v" , err ) )
2024-03-21 15:29:36 +03:00
return err
2024-02-14 23:03:30 +03:00
}
for {
ref , err := refIter . Next ( )
if err != nil {
break
}
2024-03-15 21:59:29 +03:00
if strings . Contains ( ref . Name ( ) . String ( ) , branch ) { //todo вот тут возможно нужно переделать
2024-02-14 23:03:30 +03:00
headRef = ref
break
}
} //перебираем получение ветки и когда находим нужную выходим из цикла записав ветку в headRef
refIter . Close ( )
if headRef == nil {
2024-03-17 16:45:46 +03:00
logger . Fatal ( ctx , "failed to get repo branch head" )
2024-03-21 15:29:36 +03:00
return err
2024-02-14 23:03:30 +03:00
} // Н е получили нужную ветку
2024-03-21 15:29:36 +03:00
logger . Info ( ctx , fmt . Sprintf ( "repo head %s" , headRef ) )
2024-02-14 23:03:30 +03:00
2024-02-21 18:52:55 +03:00
wtree , err := repo . Worktree ( ) //todo вроде рабочее дерево не нужно
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to get worktree: %v" , err ) )
2024-02-14 23:03:30 +03:00
}
2024-03-21 14:36:32 +03:00
pulls , err := GetPulls ( ctx , g . URL , g . Owner , g . Repository , g . Token )
if err != nil && err != ErrPRNotExist {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "GetPulls error: %s" , err ) )
2024-02-14 23:03:30 +03:00
return err
}
2024-03-21 14:36:32 +03:00
for _ , pull := range pulls {
2024-03-23 18:52:13 +03:00
logger . Debugf ( ctx , fmt . Sprintf ( "PULL title - %s | ref - %s" , pull . Title , pull . Base . Ref ) )
2024-03-21 14:36:32 +03:00
if strings . Contains ( pull . Title , path ) && strings . Contains ( pull . Base . Ref , branch ) {
2024-03-23 18:52:13 +03:00
logger . Info ( ctx , fmt . Sprintf ( "PR for %s exists %s, call RequestUpdate" , path , pull . URL ) )
return g . RequestUpdate ( ctx , branch , path , mod )
2024-03-21 14:36:32 +03:00
} // хотим проверить есть ли пулл реквест для этой ветки, если есть то выходим
2024-02-14 23:03:30 +03:00
}
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "update %s from %s to %s" , path , mod . Module . Version , mod . Version ) )
2024-02-14 23:03:30 +03:00
2024-03-17 16:45:46 +03:00
logger . Info ( ctx , "reset worktree" )
2024-02-14 23:03:30 +03:00
if err = wtree . Reset ( & git . ResetOptions { Mode : git . HardReset } ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "failed to reset repo branch: %v" , err ) )
2024-02-21 18:52:55 +03:00
} //вроде меняем ветку todo вроде можно удалить
2024-02-14 23:03:30 +03:00
if err = wtree . PullContext ( ctx , & git . PullOptions {
2024-03-15 21:18:58 +03:00
Auth : & httpauth . BasicAuth { Username : g . Token , Password : g . Token } ,
2024-02-14 23:03:30 +03:00
Depth : 1 ,
// RemoteURL :
Force : true ,
RemoteName : "origin" ,
} ) ; err != nil && err != git . NoErrAlreadyUpToDate {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "failed to pull repo: %v" , err ) ) //подтягиваем изменения с удаленого репозитория
2024-02-14 23:03:30 +03:00
}
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "checkout ref %s" , headRef ) )
2024-02-14 23:03:30 +03:00
if err = wtree . Checkout ( & git . CheckoutOptions {
Hash : headRef . Hash ( ) ,
2024-02-21 18:52:55 +03:00
Branch : plumbing . NewBranchReferenceName ( fmt . Sprintf ( "pkgdash/go_modules/%s-%s" , path , mod . Version ) ) ,
2024-02-14 23:03:30 +03:00
Create : true ,
Force : true ,
} ) ; err != nil {
2024-03-21 15:45:29 +03:00
logger . Error ( ctx , fmt . Sprintf ( "failed to checkout tree: %v" , err ) )
return err
2024-02-21 18:52:55 +03:00
} //создаем новую ветку
2024-02-14 23:03:30 +03:00
epath , err := exec . LookPath ( "go" )
if errors . Is ( err , exec . ErrDot ) {
err = nil
}
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to find go command: %v" , err ) )
2024-02-14 23:03:30 +03:00
} // ищем go файл
var cmd * exec . Cmd
var out [ ] byte
2024-03-17 15:41:25 +03:00
cmd = exec . CommandContext ( ctx , epath , "mod" , "edit" , fmt . Sprintf ( "-droprequire=%s" , mod . Module . Path ) )
if out , err = cmd . CombinedOutput ( ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to run go mod edit: %s err: %v" , out , err ) )
2024-03-17 15:41:25 +03:00
}
2024-02-14 23:03:30 +03:00
cmd = exec . CommandContext ( ctx , epath , "mod" , "edit" , fmt . Sprintf ( "-require=%s@%s" , path , mod . Version ) )
if out , err = cmd . CombinedOutput ( ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to run go mod edit: %s err: %v" , out , err ) )
2024-02-14 23:03:30 +03:00
} // пытаемся выполнить команду go mod edit с новой версией модуля
cmd = exec . CommandContext ( ctx , epath , "mod" , "tidy" )
if out , err = cmd . CombinedOutput ( ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to run go mod tidy: %s err: %v" , out , err ) )
2024-02-14 23:03:30 +03:00
} // пытаемся выполнить команду go mod tidy пытаемся подтянуть новую версию модуля
2024-03-17 16:45:46 +03:00
logger . Info ( ctx , "worktree add go.mod" )
2024-02-14 23:03:30 +03:00
if _ , err = wtree . Add ( "go.mod" ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to add file: %v" , err ) )
2024-02-14 23:03:30 +03:00
}
2024-03-17 16:45:46 +03:00
logger . Info ( ctx , "worktree add go.sum" )
2024-02-14 23:03:30 +03:00
if _ , err = wtree . Add ( "go.sum" ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to add file: %v" , err ) )
2024-02-14 23:03:30 +03:00
}
2024-03-17 16:45:46 +03:00
logger . Info ( ctx , "worktree commit" )
2024-02-14 23:03:30 +03:00
_ , err = wtree . Commit ( wTitle . String ( ) , & git . CommitOptions {
Parents : [ ] plumbing . Hash { headRef . Hash ( ) } ,
Author : & object . Signature {
Name : "gitea-actions" ,
Email : "info@unistack.org" ,
When : time . Now ( ) ,
} ,
} ) // хотим за коммитить изменения
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to commit: %v" , err ) )
2024-02-14 23:03:30 +03:00
}
2024-03-15 21:59:29 +03:00
refspec := gitconfig . RefSpec ( fmt . Sprintf ( "+refs/heads/pkgdash/go_modules/%s-%s:refs/heads/pkgdash/go_modules/%s-%s" , path , mod . Version , path , mod . Version ) ) //todo как будто нужно переделать
2024-02-14 23:03:30 +03:00
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "try to push refspec %s" , refspec ) )
2024-02-14 23:03:30 +03:00
if err = repo . PushContext ( ctx , & git . PushOptions {
RefSpecs : [ ] gitconfig . RefSpec { refspec } ,
2024-03-15 21:18:58 +03:00
Auth : & httpauth . BasicAuth { Username : g . Token , Password : g . Token } ,
2024-02-14 23:03:30 +03:00
Force : true ,
} ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Fatal ( ctx , fmt . Sprintf ( "failed to push repo branch: %v" , err ) )
2024-02-14 23:03:30 +03:00
} // пытаемся за пушить изменения
body := map [ string ] string {
2024-03-17 16:45:46 +03:00
"base" : branch ,
2024-02-14 23:03:30 +03:00
"body" : wBody . String ( ) ,
2024-03-15 21:59:29 +03:00
"head" : fmt . Sprintf ( "pkgdash/go_modules/%s-%s" , path , mod . Version ) ,
2024-02-14 23:03:30 +03:00
"title" : wTitle . String ( ) ,
}
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "raw body: %#+v" , body ) )
2024-02-14 23:03:30 +03:00
buf , err = json . Marshal ( body )
if err != nil {
return err
}
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "marshal body: %s" , buf ) )
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
req , err := http . NewRequestWithContext (
2024-03-15 23:12:39 +03:00
ctx ,
http . MethodPost ,
fmt . Sprintf ( "%s/repos/%s/%s/pulls?token=%s" , g . URL , g . Owner , g . Repository , g . Token ) ,
bytes . NewReader ( buf ) ,
)
2024-02-14 23:03:30 +03:00
if err != nil {
return err
}
req . Header . Add ( "Accept" , "application/json" )
req . Header . Add ( "Content-Type" , "application/json" )
2024-03-21 14:36:32 +03:00
rsp , err := http . DefaultClient . Do ( req )
2024-02-14 23:03:30 +03:00
if err != nil {
return err
} //Вроде создаем новый реквест на создание пулл реквеста
if rsp . StatusCode != http . StatusCreated {
buf , _ = io . ReadAll ( rsp . Body )
return fmt . Errorf ( "unknown error: %s" , buf )
}
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "PR create for %s-%s" , path , mod . Version ) )
2024-03-21 14:36:32 +03:00
2024-02-14 23:03:30 +03:00
return nil
}
2024-03-21 14:36:32 +03:00
func ( g * Gitea ) RequestClose ( ctx context . Context , branch string , path string ) error {
2024-03-21 15:29:36 +03:00
logger . Debugf ( ctx , fmt . Sprintf ( "RequestClose start, mod title: %s" , path ) )
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
pulls , err := GetPulls ( ctx , g . URL , g . Owner , g . Repository , g . Token )
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "GetPulls error: %s" , err ) )
2024-02-14 23:03:30 +03:00
return err
}
2024-02-21 18:52:55 +03:00
prExist := false
2024-03-21 14:36:32 +03:00
var b string // Name of the branch to be deleted
2024-02-14 23:03:30 +03:00
for _ , pull := range pulls {
2024-02-21 18:52:55 +03:00
if strings . Contains ( pull . Title , path ) && pull . Base . Ref == branch {
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "PR for %s exists: %s" , path , pull . URL ) )
2024-02-21 18:52:55 +03:00
prExist = true
2024-03-21 14:36:32 +03:00
b = pull . Head . Ref
2024-02-14 23:03:30 +03:00
}
}
2024-02-21 18:52:55 +03:00
if ! prExist {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "skip %s since pr does not exist" , path ) )
2024-03-15 21:18:58 +03:00
return ErrPRNotExist
2024-02-21 18:52:55 +03:00
}
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
req , err := DeleteBranch ( ctx , g . URL , g . Owner , g . Repository , b , g . Token )
2024-02-21 18:52:55 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "failed to create request for delete the branch: %s, err: %s" , branch , err ) )
2024-02-21 18:52:55 +03:00
return err
}
2024-03-21 14:36:32 +03:00
rsp , err := http . DefaultClient . Do ( req )
2024-02-21 18:52:55 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "failed to do request for delete the branch: %s, err: %s, code: %s" , branch , err , rsp . StatusCode ) )
2024-02-14 23:03:30 +03:00
return err
}
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "Delete branch for %s successful" , path ) )
2024-02-14 23:03:30 +03:00
return nil
}
2024-03-21 14:36:32 +03:00
func ( g * Gitea ) RequestUpdate ( ctx context . Context , branch string , path string , mod modules . Update ) error {
2024-03-21 15:29:36 +03:00
logger . Debugf ( ctx , fmt . Sprintf ( "RequestUpdate start, mod title: %s" , path ) )
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
pulls , err := GetPulls ( ctx , g . URL , g . Owner , g . Repository , g . Token )
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "GetPulls error: %s" , err ) )
2024-02-14 23:03:30 +03:00
return err
}
2024-02-21 18:52:55 +03:00
prExist := false
2024-02-14 23:03:30 +03:00
for _ , pull := range pulls {
2024-03-21 14:36:32 +03:00
if strings . Contains ( pull . Title , path ) && pull . Base . Ref == branch {
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "don't skip %s since pr exist %s" , path , pull . URL ) ) //todo
tVersion := getVersions ( pull . Head . Ref ) //Надо взять просто из названия ветки последнюю версию
2024-03-21 14:36:32 +03:00
if modules . IsNewerVersion ( tVersion , mod . Version , false ) {
reqDel , err := DeleteBranch ( ctx , g . URL , g . Owner , g . Repository , pull . Head . Ref , g . Token )
2024-02-21 18:52:55 +03:00
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "Error with create request for branch: %s, err: %s" , branch , err ) )
2024-02-21 18:52:55 +03:00
continue
}
rsp , err := http . DefaultClient . Do ( reqDel )
if err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "Error with do request for branch: %s, err: %s, code: %v" , branch , err , rsp . StatusCode ) )
2024-02-21 18:52:55 +03:00
continue //думаю что если не можем удалить ветку не стоит заканчивать работу, а перейти к следующей итерации
}
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "Old pr %s successful delete" , pull . Head . Ref ) )
2024-03-21 15:29:36 +03:00
} else {
return nil
2024-02-21 18:52:55 +03:00
}
prExist = true
2024-02-14 23:03:30 +03:00
}
}
2024-02-21 18:52:55 +03:00
if ! prExist {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "skip %s since pr does not exist" , path ) )
2024-03-15 21:18:58 +03:00
return ErrPRNotExist
2024-02-21 18:52:55 +03:00
}
2024-02-14 23:03:30 +03:00
2024-03-21 15:13:38 +03:00
logger . Info ( ctx , fmt . Sprintf ( "update %s from %s to %s" , path , mod . Module . Version , mod . Version ) )
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
return g . RequestOpen ( ctx , branch , path , mod )
}
2024-02-14 23:03:30 +03:00
2024-03-23 18:52:13 +03:00
func ( g * Gitea ) RequestList ( ctx context . Context , branch string ) ( map [ string ] string , error ) {
logger . Debugf ( ctx , fmt . Sprintf ( "RequestList for %s" , branch ) )
gPulls , err := GetPulls ( ctx , g . URL , g . Owner , g . Repository , g . Token )
if err != nil {
return nil , err
}
var path string
rMap := make ( map [ string ] string )
for _ , pull := range gPulls {
path = strings . Split ( pull . Title , " " ) [ 1 ] //todo Работет только для дефолтного шаблона
rMap [ path ] = pull . Title
}
return rMap , nil
}
2024-03-21 14:36:32 +03:00
func getVersions ( s string ) string {
re := regexp . MustCompile ( "[vV][0-9]+\\.[0-9]+\\.[0-9]+" )
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
version := re . FindString ( s )
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
return version
}
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
func DeleteBranch ( ctx context . Context , url , owner , repo , branch , token string ) ( * http . Request , error ) {
var buf [ ] byte
req , err := http . NewRequestWithContext ( ctx , http . MethodDelete , fmt . Sprintf ( "%s/repos/%s/%s/branches/%s?token=%s" , url , owner , repo , branch , token ) , bytes . NewReader ( buf ) )
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 14:36:32 +03:00
return nil , err
2024-02-14 23:03:30 +03:00
}
2024-03-21 14:36:32 +03:00
req . Header . Add ( "Accept" , "application/json" )
req . Header . Add ( "Content-Type" , "application/json" )
return req , err
}
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
func GetPulls ( ctx context . Context , url , owner , repo , token string ) ( [ ] * giteaPull , error ) {
var pulls [ ] * giteaPull
var err error
2024-02-14 23:03:30 +03:00
2024-03-21 14:36:32 +03:00
req , err := http . NewRequestWithContext (
ctx ,
http . MethodGet ,
fmt . Sprintf ( "%s/repos/%s/%s/pulls?state=open&token=%s" , url , owner , repo , token ) ,
nil )
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 14:36:32 +03:00
return nil , err
} //вроде запроса к репозиторию
2024-02-14 23:03:30 +03:00
req . Header . Add ( "Accept" , "application/json" )
req . Header . Add ( "Content-Type" , "application/json" )
2024-03-21 14:36:32 +03:00
rsp , err := http . DefaultClient . Do ( req ) // выполнение запроса
2024-02-14 23:03:30 +03:00
if err != nil {
2024-03-21 14:36:32 +03:00
return nil , err
2024-02-14 23:03:30 +03:00
}
2024-03-21 14:36:32 +03:00
buf , _ := io . ReadAll ( rsp . Body )
2024-02-21 18:52:55 +03:00
2024-03-21 14:36:32 +03:00
switch rsp . StatusCode {
case http . StatusOK :
if err = json . Unmarshal ( buf , & pulls ) ; err != nil {
2024-03-21 15:13:38 +03:00
logger . Error ( ctx , fmt . Sprintf ( "failed to decode response %s err: %v" , buf , err ) )
2024-03-21 14:36:32 +03:00
return nil , err
}
return pulls , nil
case http . StatusNotFound :
logger . Info ( ctx , "PL is not exist for %s" , repo )
return nil , ErrPRNotExist
default :
return nil , fmt . Errorf ( "unknown error: %s" , buf )
2024-02-21 18:52:55 +03:00
}
}