autogits/devel-importer/main.go

370 lines
12 KiB
Go
Raw Normal View History

2024-08-07 01:37:55 +02:00
package main
2024-09-10 18:24:41 +02:00
/*
* This file is part of Autogits.
*
* Copyright © 2024 SUSE LLC
*
* Autogits is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* Autogits is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* Foobar. If not, see <https://www.gnu.org/licenses/>.
*/
2024-08-07 01:37:55 +02:00
import (
"errors"
2024-08-09 17:53:18 +02:00
"flag"
2024-09-16 13:10:25 +02:00
"log"
2024-08-07 01:37:55 +02:00
"os"
"os/exec"
"path/filepath"
2024-08-09 17:53:18 +02:00
"slices"
2024-08-07 01:37:55 +02:00
"strings"
2024-08-13 09:28:04 +02:00
"time"
2024-08-07 01:37:55 +02:00
transport "github.com/go-openapi/runtime/client"
"src.opensuse.org/autogits/common"
apiclient "src.opensuse.org/autogits/common/gitea-generated/client"
2024-08-09 17:53:18 +02:00
"src.opensuse.org/autogits/common/gitea-generated/client/organization"
2024-08-07 01:37:55 +02:00
"src.opensuse.org/autogits/common/gitea-generated/client/repository"
"src.opensuse.org/autogits/common/gitea-generated/models"
)
const commandLineHelp = `
SYNTAX
devel-importer <obs-project> <gitea-org>`
func printHelp() {
log.Println(commandLineHelp)
2024-08-07 01:37:55 +02:00
}
func runObsCommand(args ...string) ([]byte, error) {
cmd := exec.Command("osc", args...)
return cmd.Output()
}
var DebugMode bool
2024-08-07 01:37:55 +02:00
func main() {
2024-08-09 17:53:18 +02:00
if err := common.RequireGiteaSecretToken(); err != nil {
log.Panicln("Missing GITEA_TOKEN")
2024-08-07 01:37:55 +02:00
}
2024-08-09 17:53:18 +02:00
if err := common.RequireObsSecretToken(); err != nil {
log.Panicln("Missing OBS_PASSWORD and/or OBS_USER")
2024-08-09 17:53:18 +02:00
}
//workflowConfig := flag.String("config", "", "Repository and workflow definition file")
giteaHost := flag.String("gitea", "src.opensuse.org", "Gitea instance")
//rabbitUrl := flag.String("url", "amqps://rabbit.opensuse.org", "URL for RabbitMQ instance")
flag.BoolVar(&DebugMode, "debug", false, "Extra debugging information")
// revNew := flag.Int("nrevs", 20, "Number of new revisions in factory branch. Indicator of broken history import")
purgeOnly := flag.Bool("purge", false, "Purges package repositories. Use with caution")
debugGitPath := flag.String("git-path", "", "Path for temporary git directory. Only used if DebugMode")
flag.Parse()
2024-09-16 13:10:25 +02:00
git, err := common.CreateGitHandler("Autogits - Devel Importer", "not.exist", "devel-importer")
if err != nil {
log.Panicln("Failed to allocate git handler. Err:", err)
2024-08-09 17:53:18 +02:00
}
if DebugMode {
log.Println(" - working directory:" + git.GitPath)
if len(*debugGitPath) > 0 {
git.Close()
git.GitPath = *debugGitPath
}
} else {
defer git.Close()
}
2024-08-09 17:53:18 +02:00
if flag.NArg() != 2 {
2024-08-07 01:37:55 +02:00
printHelp()
os.Exit(1)
}
2024-08-09 17:56:39 +02:00
prj := flag.Arg(0)
org := flag.Arg(1)
2024-08-07 01:37:55 +02:00
packageList, err := runObsCommand("ls", prj)
if err != nil {
2024-09-16 13:10:25 +02:00
log.Printf("Cannot list packages for project '%s'. Err: %v\n", prj, err)
2024-08-07 01:37:55 +02:00
}
packages := strings.Split(strings.TrimSpace(string(packageList)), "\n")
slices.Sort(packages)
for i := range packages {
packages[i] = strings.Split(packages[i], ":")[0]
}
packages = slices.Compact(packages)
log.Printf("%d packages: %s\n\n", len(packages), strings.Join(packages, " "))
2024-08-07 01:37:55 +02:00
r := transport.New(*giteaHost, apiclient.DefaultBasePath, [](string){"https"})
2024-08-07 01:37:55 +02:00
r.DefaultAuthentication = transport.BearerToken(common.GetGiteaToken())
2024-08-09 17:53:18 +02:00
// r.SetDebug(true)
2024-08-07 01:37:55 +02:00
client := apiclient.New(r, nil)
2024-08-11 23:27:34 +02:00
if *purgeOnly {
log.Println("Purging repositories...")
2024-08-09 17:53:18 +02:00
for _, pkg := range packages {
client.Repository.RepoDelete(repository.NewRepoDeleteParams().WithOwner(org).WithRepo(pkg), r.DefaultAuthentication)
}
os.Exit(10)
}
2024-09-17 15:06:29 +02:00
factoryRepos := make([]*models.Repository, 0, len(packages)*2)
develProjectPackages := make([]string, 0, len(packages))
2024-08-07 01:37:55 +02:00
for _, pkg := range packages {
src_pkg_name := strings.Split(pkg, ":")
2024-08-07 01:37:55 +02:00
repo, err := client.Repository.RepoGet(
repository.NewRepoGetParams().
WithDefaults().WithOwner("pool").WithRepo(src_pkg_name[0]),
2024-08-07 01:37:55 +02:00
r.DefaultAuthentication)
2024-09-17 15:06:29 +02:00
rpm, rpmErr := client.Repository.RepoGet(
repository.NewRepoGetParams().WithDefaults().WithOwner("rpm").WithRepo(src_pkg_name[0]),
r.DefaultAuthentication)
if rpmErr == nil {
factoryRepos = append(factoryRepos, rpm.Payload)
} else {
if !errors.Is(rpmErr, &repository.RepoGetNotFound{}) {
log.Panicln(rpmErr)
}
log.Println("No RPM package?", src_pkg_name)
}
2024-08-07 01:37:55 +02:00
if err != nil {
if !errors.Is(err, &repository.RepoGetNotFound{}) {
log.Panicln(err)
2024-08-07 01:37:55 +02:00
}
log.Println("Cannot find src package:", src_pkg_name)
2024-09-17 15:06:29 +02:00
develProjectPackages = append(develProjectPackages, src_pkg_name[0])
2024-08-07 01:37:55 +02:00
} else {
2024-09-17 15:06:29 +02:00
factoryRepos = append(factoryRepos, repo.Payload)
2024-08-09 17:53:18 +02:00
}
2024-09-17 15:06:29 +02:00
}
log.Println("Num repos found:", len(factoryRepos))
oldPackageNames := make([]string, 0, len(factoryRepos))
for _, repo := range factoryRepos {
oldPackageNames = append(oldPackageNames, repo.Name)
2024-08-09 17:53:18 +02:00
}
2024-09-17 15:06:29 +02:00
slices.Sort(oldPackageNames)
oldPackageNames = slices.Compact(oldPackageNames)
copy(oldPackageNames[2:], oldPackageNames)
log.Println("Num of old packages:", len(oldPackageNames))
2024-08-09 17:53:18 +02:00
// fork packags from pool
2024-09-17 15:06:29 +02:00
cmd := exec.Command("./git-importer", append([]string{"-r", git.GitPath}, oldPackageNames...)...)
2024-08-11 23:27:34 +02:00
out, err := cmd.CombinedOutput()
log.Println(string(out))
2024-08-11 23:27:34 +02:00
if err != nil {
log.Println("Error returned by importer.", err)
2024-08-11 23:27:34 +02:00
}
2024-08-13 09:28:04 +02:00
reposOK := true
2024-09-17 15:06:29 +02:00
log.Println("adding remotes...")
for i := range factoryRepos {
pkg := factoryRepos[i]
2024-08-09 17:53:18 +02:00
// verify that package was created by `git-importer`, or it's scmsync package and clone it
fi, err := os.Stat(filepath.Join(git.GitPath, pkg.Name))
if os.IsNotExist(err) {
// scmsync?
devel_project, err := runObsCommand("develproject", "openSUSE:Factory", pkg.Name)
if err != nil {
log.Panicln(err)
}
d := strings.Split(strings.TrimSpace(string(devel_project)), "/")
if len(d) != 2 {
log.Panicln("expected devel project/package. got:", d)
}
obs, _ := common.NewObsClient("api.opensuse.org")
meta, _ := obs.GetPackageMeta(d[0], d[1])
if len(meta.ScmSync) > 0 {
if err2 := git.CloneDevel("", pkg.Name, meta.ScmSync); err != nil {
log.Panicln(err2)
}
}
// try again, should now exist
if fi, err = os.Stat(filepath.Join(git.GitPath, pkg.Name)); err != nil {
log.Panicln(err)
}
} else if err != nil {
log.Panicln(err)
}
if !fi.IsDir() {
log.Panicln("Expected package file should be a directory. It's not.", fi)
}
2024-08-11 23:27:34 +02:00
// add remote repos
out := git.GitExecWithOutputOrPanic(pkg.Name, "remote", "show", "-n")
2024-09-17 15:06:29 +02:00
switch pkg.Owner.UserName {
case "pool":
if !slices.Contains(strings.Split(out, "\n"), "factory") {
out := git.GitExecWithOutputOrPanic(pkg.Name, "remote", "add", "factory", pkg.CloneURL)
if len(strings.TrimSpace(out)) > 1 {
log.Println(out)
}
2024-08-11 23:27:34 +02:00
}
2024-09-17 15:06:29 +02:00
case "rpm":
if !slices.Contains(strings.Split(out, "\n"), "rpm") {
out := git.GitExecWithOutputOrPanic(pkg.Name, "remote", "add", "rpm", pkg.CloneURL)
if len(strings.TrimSpace(out)) > 1 {
log.Println(out)
}
2024-08-09 17:53:18 +02:00
}
}
2024-09-17 15:06:29 +02:00
}
2024-08-09 17:53:18 +02:00
2024-09-17 15:06:29 +02:00
for _, pkgName := range oldPackageNames {
log.Println("fetching git:", pkgName)
remotes := common.SplitStringNoEmpty(git.GitExecWithOutputOrPanic(pkgName, "remote", "show", "-n"), "\n")
params := []string{"fetch", "--multiple"}
params = append(params, remotes...)
out := git.GitExecWithOutputOrPanic(pkgName, params...)
2024-08-11 23:27:34 +02:00
if len(strings.TrimSpace(out)) > 1 {
log.Println(out)
2024-08-11 23:27:34 +02:00
}
2024-08-09 17:53:18 +02:00
2024-08-11 23:27:34 +02:00
// check that nothing is broken with the update
if slices.Contains(remotes, "factory") {
head_branch := "factory"
out, err = git.GitExecWithOutput(pkgName, "rev-list", head_branch)
if err != nil {
head_branch = "HEAD"
out = git.GitExecWithOutputOrPanic(pkgName, "rev-list", "HEAD")
}
old_revs := strings.Split(out, "\n")
added_revs := []string{}
out = git.GitExecWithOutputOrPanic(pkgName, "rev-list", head_branch, "^factory/factory")
added_revs = strings.Split(out, "\n")
added_rpm_revs := []string{}
if slices.Contains(remotes, "rpm") {
out = git.GitExecWithOutputOrPanic(pkgName, "rev-list", head_branch, "^rpm/factory")
added_rpm_revs = strings.Split(out, "\n")
}
if len(added_revs) == len(old_revs) && len(added_rpm_revs) == len(old_revs) {
log.Printf("Something is wrong with rev-ist for (len %d): %s\n", len(added_revs), pkgName)
reposOK = false
}
2024-08-11 23:27:34 +02:00
}
2024-08-13 09:28:04 +02:00
}
2024-09-17 15:06:29 +02:00
args := make([]string, 4, len(develProjectPackages)+4)
2024-08-13 09:28:04 +02:00
args[0] = "-p"
args[1] = prj
args[2] = "-r"
args[3] = git.GitPath
2024-09-17 15:06:29 +02:00
args = append(args, develProjectPackages...)
2024-08-13 09:28:04 +02:00
cmd = exec.Command("./git-importer", args...)
out, err = cmd.CombinedOutput()
log.Println(out)
2024-08-13 09:28:04 +02:00
if err != nil {
log.Panicln("Error returned by importer.", err)
2024-08-13 09:28:04 +02:00
}
if !reposOK {
log.Println("aborting import due to broken repos above...")
2024-08-13 09:28:04 +02:00
}
2024-08-11 23:27:34 +02:00
2024-09-17 15:06:29 +02:00
for _, pkg := range factoryRepos {
2024-08-11 23:27:34 +02:00
// update package
2024-08-13 09:28:04 +02:00
fork, err := client.Repository.CreateFork(repository.NewCreateForkParams().
WithOwner("pool").
WithRepo(pkg.Name).
WithBody(&models.CreateForkOption{
Organization: org,
}), r.DefaultAuthentication)
if err != nil {
log.Panicln("Error while trying to create fork from pool/", pkg.Name, err)
2024-08-13 09:28:04 +02:00
}
2024-08-11 23:27:34 +02:00
2024-08-13 09:28:04 +02:00
repo := fork.Payload
repoList, err := client.Repository.RepoListBranches(
repository.NewRepoListBranchesParams().WithOwner(org).WithRepo(pkg.Name),
r.DefaultAuthentication,
)
if err != nil {
log.Panicln("Cannot get list of branches for forked repo:", org, "/", pkg.Name)
2024-08-13 09:28:04 +02:00
}
priorityBranches := []string{
"devel",
"factory",
}
idx := len(priorityBranches)
for _, branch := range repoList.Payload {
i := slices.Index(priorityBranches, branch.Name)
if i > -1 && i < idx {
idx = i
2024-08-11 23:27:34 +02:00
}
2024-08-13 09:28:04 +02:00
}
2024-08-11 23:27:34 +02:00
2024-08-13 09:28:04 +02:00
branchName := priorityBranches[idx]
remotes := git.GitExecWithOutputOrPanic(pkg.Name, "remote", "show")
2024-08-13 09:28:04 +02:00
if !slices.Contains(strings.Split(remotes, "\n"), "devel") {
git.GitExecOrPanic(pkg.Name, "remote", "add", "devel", repo.SSHURL)
2024-08-13 09:28:04 +02:00
}
git.GitExecOrPanic(pkg.Name, "branch", "main", "-f", branchName)
2024-08-13 09:28:04 +02:00
time.Sleep(2 * time.Second)
git.GitExecOrPanic(pkg.Name, "push", "devel", "main")
2024-08-13 09:28:04 +02:00
time.Sleep(2 * time.Second)
2024-08-11 23:27:34 +02:00
2024-08-13 09:28:04 +02:00
_, err = client.Repository.RepoEdit(repository.NewRepoEditParams().WithOwner(org).WithRepo(repo.Name).WithBody(&models.EditRepoOption{
DefaultBranch: "main",
DefaultMergeStyle: "fast-forward-only",
}), r.DefaultAuthentication)
if err != nil {
log.Panicln("Failed to set default branch for package fork:", repo.Owner.UserName, "/", repo.Name, err)
2024-08-13 09:28:04 +02:00
}
2024-08-09 17:53:18 +02:00
}
2024-09-17 15:06:29 +02:00
for _, pkg := range develProjectPackages {
2024-08-13 09:28:04 +02:00
ret, err := client.Organization.CreateOrgRepo(organization.NewCreateOrgRepoParams().WithOrg(org).WithBody(
&models.CreateRepoOption{
ObjectFormatName: "sha256",
AutoInit: false,
Name: &pkg,
DefaultBranch: "main",
}),
r.DefaultAuthentication,
)
if err != nil {
log.Panicln("Error creating new package repository:", pkg, err)
2024-08-13 09:28:04 +02:00
}
repo := ret.Payload
remotes := git.GitExecWithOutputOrPanic(pkg, "remote", "show")
2024-08-13 09:28:04 +02:00
if !slices.Contains(strings.Split(remotes, "\n"), "devel") {
git.GitExecOrPanic(pkg, "remote", "add", "devel", repo.SSHURL)
2024-08-13 09:28:04 +02:00
}
git.GitExecOrPanic(pkg, "branch", "main", "-f", "factory")
2024-08-13 09:28:04 +02:00
time.Sleep(2 * time.Second)
git.GitExecOrPanic(pkg, "push", "devel", "main")
2024-08-13 09:28:04 +02:00
time.Sleep(2 * time.Second)
_, err = client.Repository.RepoEdit(repository.NewRepoEditParams().WithOwner(org).WithRepo(pkg).WithBody(&models.EditRepoOption{
DefaultBranch: "main",
DefaultMergeStyle: "fast-forward-only",
}), r.DefaultAuthentication)
if err != nil {
log.Panicln("Failed to set default branch for package fork:", repo.Owner.UserName, "/", repo.Name, err)
2024-08-13 09:28:04 +02:00
}
2024-08-07 01:37:55 +02:00
}
}