update for latest micro changes

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
2024-03-25 22:54:25 +03:00
parent ec5c6c591d
commit c362702c40
17 changed files with 1106 additions and 1043 deletions

View File

@@ -80,7 +80,7 @@ func ParseDSN(cfg *appconfig.DatabaseConfig) error {
case "sqlite", "sqlite3":
u.Scheme = "sqlite"
default:
return fmt.Error("unknown database %s", u.Scheme)
return fmt.Errorf("unknown database %s", u.Scheme)
}
cfg.Type = u.Scheme
@@ -104,7 +104,7 @@ func connect(ctx context.Context, cfg *appconfig.DatabaseConfig, log logger.Logg
db, err = connectSqlite(ctx, cfg.ConnStr)
cfg.Type = "sqlite"
default:
return nil, fmt.Error("unknown database type %s", cfg.Type)
return nil, fmt.Errorf("unknown database type %s", cfg.Type)
}
if err != nil {

View File

@@ -17,18 +17,18 @@ func (h *Handler) CommentCreate(ctx context.Context, req *pb.CommentCreateReq, r
err := req.Validate()
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validation error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
var com *models.Comment
if com, err = h.store.CommentCreate(ctx, req); err != nil {
logger.Error(ctx, err)
if errors.Is(err, sql.ErrNoRows) {
httpsrv.SetRspCode(ctx, http.StatusNotFound)
return httpsrv.SetError(NewNotFoundError(err))
}
logger.Error(ctx, "comment create error", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}

View File

@@ -16,17 +16,18 @@ func (h *Handler) CommentDelete(ctx context.Context, req *pb.CommentDeleteReq, r
err := req.Validate()
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validate error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
if err = h.store.CommentDelete(ctx, req); err != nil {
logger.Error(ctx, err)
if errors.Is(err, sql.ErrNoRows) {
httpsrv.SetRspCode(ctx, http.StatusNotFound)
return httpsrv.SetError(NewNotFoundError(err))
}
logger.Error(ctx, "comment delete error", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}

View File

@@ -15,14 +15,14 @@ func (h *Handler) CommentList(ctx context.Context, req *pb.CommentListReq, rsp *
err := req.Validate()
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validate error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
comments, err := h.store.CommentList(ctx, req)
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "comment list error", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}

View File

@@ -15,14 +15,14 @@ func (h *Handler) ModuleList(ctx context.Context, req *pb.ModuleListReq, rsp *pb
err := req.Validate()
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validate error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
modules, err := h.store.ModuleList(ctx, req)
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "module list error", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}

View File

@@ -14,14 +14,14 @@ func (h *Handler) PackageCreate(ctx context.Context, req *pb.PackageCreateReq, r
logger.Debug(ctx, "PackagesCreate handler start")
if err := req.Validate(); err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validate error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
pkg, err := h.store.PackageCreate(ctx, req)
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "package create error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}

View File

@@ -13,13 +13,13 @@ func (h *Handler) PackageDelete(ctx context.Context, req *pb.PackageDeleteReq, r
logger.Debug(ctx, "Start UpdatePackage")
if err := req.Validate(); err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validate error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
if err := h.store.PackageDelete(ctx, req); err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "package delete error", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}

View File

@@ -14,14 +14,14 @@ func (h *Handler) PackageLookup(ctx context.Context, req *pb.PackageLookupReq, r
logger.Debug(ctx, "Start PackagesLookup")
if err := req.Validate(); err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validate error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
pkg, err := h.store.PackageLookup(ctx, req)
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "package lookup", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}

View File

@@ -14,14 +14,14 @@ func (h *Handler) PackageUpdate(ctx context.Context, req *pb.PackageUpdateReq, r
logger.Debug(ctx, "Start UpdatePackage")
if err := req.Validate(); err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "validate error", err)
httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return httpsrv.SetError(NewValidationError(err))
}
pkg, err := h.store.PackageUpdate(ctx, req)
if err != nil {
logger.Error(ctx, err)
logger.Error(ctx, "package update error", err)
httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return httpsrv.SetError(NewInternalError(err))
}

View File

@@ -25,9 +25,7 @@ import (
"go.unistack.org/micro/v4/logger"
)
var (
ErrPRNotExist = errors.New("pull request does not exist")
)
var ErrPRNotExist = errors.New("pull request does not exist")
type Gitea struct {
URL string
@@ -62,7 +60,7 @@ type giteaPull struct {
}
func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod modules.Update) error {
logger.Debugf(ctx, fmt.Sprintf("RequestOpen start, mod title: %s", path))
logger.Debug(ctx, fmt.Sprintf("RequestOpen start, mod title: %s", path))
var buf []byte
var err error
@@ -99,16 +97,16 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
if err != nil {
logger.Fatal(ctx, fmt.Sprintf("failed to open repo: %v", err))
}
//извлекаем ссылки с объектами из удаленного объекта??
// извлекаем ссылки с объектами из удаленного объекта??
if err = repo.FetchContext(ctx, &git.FetchOptions{
Auth: &httpauth.BasicAuth{Username: g.Token, Password: g.Token},
Force: true,
}); err != nil && err != git.NoErrAlreadyUpToDate {
logger.Fatal(ctx, fmt.Sprintf("failed to fetch repo: %v", err))
} //обновляем репозиторий
} // обновляем репозиторий
var headRef *plumbing.Reference // вроде ссылка на гит
refIter, err := repo.Branches() //получение веток
refIter, err := repo.Branches() // получение веток
if err != nil {
logger.Fatal(ctx, fmt.Sprintf("failed to get branches: %v", err))
return err
@@ -118,11 +116,11 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
if err != nil {
break
}
if strings.Contains(ref.Name().String(), branch) { //todo вот тут возможно нужно переделать
if strings.Contains(ref.Name().String(), branch) { // todo вот тут возможно нужно переделать
headRef = ref
break
}
} //перебираем получение ветки и когда находим нужную выходим из цикла записав ветку в headRef
} // перебираем получение ветки и когда находим нужную выходим из цикла записав ветку в headRef
refIter.Close()
if headRef == nil {
@@ -132,7 +130,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
logger.Info(ctx, fmt.Sprintf("repo head %s", headRef))
wtree, err := repo.Worktree() //todo вроде рабочее дерево не нужно
wtree, err := repo.Worktree() // todo вроде рабочее дерево не нужно
if err != nil {
logger.Fatal(ctx, fmt.Sprintf("failed to get worktree: %v", err))
}
@@ -144,7 +142,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
}
for _, pull := range pulls {
logger.Debugf(ctx, fmt.Sprintf("PULL title - %s | ref - %s", pull.Title, pull.Base.Ref))
logger.Debug(ctx, fmt.Sprintf("PULL title - %s | ref - %s", pull.Title, pull.Base.Ref))
if strings.Contains(pull.Title, path) && strings.Contains(pull.Base.Ref, branch) {
logger.Info(ctx, fmt.Sprintf("PR for %s exists %s, call RequestUpdate", path, pull.URL))
return g.RequestUpdate(ctx, branch, path, mod)
@@ -156,7 +154,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
logger.Info(ctx, "reset worktree")
if err = wtree.Reset(&git.ResetOptions{Mode: git.HardReset}); err != nil {
logger.Error(ctx, fmt.Sprintf("failed to reset repo branch: %v", err))
} //вроде меняем ветку todo вроде можно удалить
} // вроде меняем ветку todo вроде можно удалить
if err = wtree.PullContext(ctx, &git.PullOptions{
Auth: &httpauth.BasicAuth{Username: g.Token, Password: g.Token},
@@ -165,7 +163,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
Force: true,
RemoteName: "origin",
}); err != nil && err != git.NoErrAlreadyUpToDate {
logger.Error(ctx, fmt.Sprintf("failed to pull repo: %v", err)) //подтягиваем изменения с удаленого репозитория
logger.Error(ctx, fmt.Sprintf("failed to pull repo: %v", err)) // подтягиваем изменения с удаленого репозитория
}
logger.Info(ctx, fmt.Sprintf("checkout ref %s", headRef))
@@ -177,7 +175,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
}); err != nil {
logger.Error(ctx, fmt.Sprintf("failed to checkout tree: %v", err))
return err
} //создаем новую ветку
} // создаем новую ветку
epath, err := exec.LookPath("go")
if errors.Is(err, exec.ErrDot) {
@@ -228,7 +226,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
logger.Fatal(ctx, fmt.Sprintf("failed to commit: %v", err))
}
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 как будто нужно переделать
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 как будто нужно переделать
logger.Info(ctx, fmt.Sprintf("try to push refspec %s", refspec))
@@ -270,7 +268,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
rsp, err := http.DefaultClient.Do(req)
if err != nil {
return err
} //Вроде создаем новый реквест на создание пулл реквеста
} // Вроде создаем новый реквест на создание пулл реквеста
if rsp.StatusCode != http.StatusCreated {
buf, _ = io.ReadAll(rsp.Body)
return fmt.Errorf("unknown error: %s", buf)
@@ -282,7 +280,7 @@ func (g *Gitea) RequestOpen(ctx context.Context, branch string, path string, mod
}
func (g *Gitea) RequestClose(ctx context.Context, branch string, path string) error {
logger.Debugf(ctx, fmt.Sprintf("RequestClose start, mod title: %s", path))
logger.Debug(ctx, fmt.Sprintf("RequestClose start, mod title: %s", path))
pulls, err := GetPulls(ctx, g.URL, g.Owner, g.Repository, g.Token)
if err != nil {
@@ -320,7 +318,7 @@ func (g *Gitea) RequestClose(ctx context.Context, branch string, path string) er
}
func (g *Gitea) RequestUpdate(ctx context.Context, branch string, path string, mod modules.Update) error {
logger.Debugf(ctx, fmt.Sprintf("RequestUpdate start, mod title: %s", path))
logger.Debug(ctx, fmt.Sprintf("RequestUpdate start, mod title: %s", path))
pulls, err := GetPulls(ctx, g.URL, g.Owner, g.Repository, g.Token)
if err != nil {
@@ -331,8 +329,8 @@ func (g *Gitea) RequestUpdate(ctx context.Context, branch string, path string, m
prExist := false
for _, pull := range pulls {
if strings.Contains(pull.Title, path) && pull.Base.Ref == branch {
logger.Info(ctx, fmt.Sprintf("don't skip %s since pr exist %s", path, pull.URL)) //todo
tVersion := getVersions(pull.Head.Ref) //Надо взять просто из названия ветки последнюю версию
logger.Info(ctx, fmt.Sprintf("don't skip %s since pr exist %s", path, pull.URL)) // todo
tVersion := getVersions(pull.Head.Ref) // Надо взять просто из названия ветки последнюю версию
if modules.IsNewerVersion(tVersion, mod.Version, false) {
reqDel, err := DeleteBranch(ctx, g.URL, g.Owner, g.Repository, pull.Head.Ref, g.Token)
if err != nil {
@@ -342,7 +340,7 @@ func (g *Gitea) RequestUpdate(ctx context.Context, branch string, path string, m
rsp, err := http.DefaultClient.Do(reqDel)
if err != nil {
logger.Error(ctx, fmt.Sprintf("Error with do request for branch: %s, err: %s, code: %v", branch, err, rsp.StatusCode))
continue //думаю что если не можем удалить ветку не стоит заканчивать работу, а перейти к следующей итерации
continue // думаю что если не можем удалить ветку не стоит заканчивать работу, а перейти к следующей итерации
}
logger.Info(ctx, fmt.Sprintf("Old pr %s successful delete", pull.Head.Ref))
} else {
@@ -362,7 +360,7 @@ func (g *Gitea) RequestUpdate(ctx context.Context, branch string, path string, m
}
func (g *Gitea) RequestList(ctx context.Context, branch string) (map[string]string, error) {
logger.Debugf(ctx, fmt.Sprintf("RequestList for %s", branch))
logger.Debug(ctx, fmt.Sprintf("RequestList for %s", branch))
gPulls, err := GetPulls(ctx, g.URL, g.Owner, g.Repository, g.Token)
if err != nil {
@@ -373,7 +371,7 @@ func (g *Gitea) RequestList(ctx context.Context, branch string) (map[string]stri
rMap := make(map[string]string)
for _, pull := range gPulls {
path = strings.Split(pull.Title, " ")[1] //todo Работет только для дефолтного шаблона
path = strings.Split(pull.Title, " ")[1] // todo Работет только для дефолтного шаблона
rMap[path] = pull.Title
}
@@ -410,7 +408,7 @@ func GetPulls(ctx context.Context, url, owner, repo, token string) ([]*giteaPull
nil)
if err != nil {
return nil, err
} //вроде запроса к репозиторию
} // вроде запроса к репозиторию
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")

View File

@@ -64,11 +64,11 @@ func (s *Sqlite) PackageModulesCreate(ctx context.Context, pkg *models.Package,
}
func (s *Sqlite) PackageDelete(ctx context.Context, req *pb.PackageDeleteReq) error {
return fmt.Error("need implement")
return fmt.Errorf("need implement")
}
func (s *Sqlite) PackageUpdate(ctx context.Context, req *pb.PackageUpdateReq) (*models.Package, error) {
return nil, fmt.Error("need implement")
return nil, fmt.Errorf("need implement")
}
func (s *Sqlite) PackageLookup(ctx context.Context, req *pb.PackageLookupReq) (*models.Package, error) {

View File

@@ -107,12 +107,12 @@ func parseModFile(ctx context.Context, store storage.Storage, pkg *models.Packag
ref, err := repo.Head()
if err != nil {
return fmt.Error("failed to get head: %v", err)
return fmt.Errorf("failed to get head: %v", err)
}
commit, err := repo.CommitObject(ref.Hash())
if err != nil {
return fmt.Error("failed to get commit: %v", err)
return fmt.Errorf("failed to get commit: %v", err)
}
tree, err := commit.Tree()
@@ -125,7 +125,7 @@ func parseModFile(ctx context.Context, store storage.Storage, pkg *models.Packag
err = tree.Files().ForEach(func(file *object.File) error {
if file == nil {
err = errors.New("file pointer is nil")
logger.Error(ctx, err)
logger.Error(ctx, "file tree error", err)
return err
}