Skip to content

Commit

Permalink
enhancement: allow callers to use custom loggers
Browse files Browse the repository at this point in the history
  • Loading branch information
mstg committed Jan 5, 2022
1 parent ad004a1 commit 102ff04
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 38 deletions.
2 changes: 1 addition & 1 deletion cmd/srpmproc/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func runFetch(_ *cobra.Command, _ []string) {
log.Fatalf("could not get working directory: %v", err)
}

err = srpmproc.Fetch(cdnUrl, wd)
err = srpmproc.Fetch(os.Stdout, cdnUrl, wd)
if err != nil {
log.Fatal(err)
}
Expand Down
2 changes: 2 additions & 0 deletions pkg/data/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/rocky-linux/srpmproc/pkg/blob"
"log"
)

type FsCreatorFunc func(branch string) (billy.Filesystem, error)
Expand Down Expand Up @@ -52,4 +53,5 @@ type ProcessData struct {
AllowStreamBranches bool
FsCreator FsCreatorFunc
CdnUrl string
Log *log.Logger
}
7 changes: 3 additions & 4 deletions pkg/data/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
"github.com/go-git/go-billy/v5"
"hash"
"io"
"log"
"os"
"path/filepath"
)
Expand Down Expand Up @@ -93,9 +92,9 @@ func StrContains(a []string, b string) bool {
return false
}

// check if content and checksum matches
// CompareHash checks if content and checksum matches
// returns the hash type if success else nil
func CompareHash(content []byte, checksum string) hash.Hash {
func (pd *ProcessData) CompareHash(content []byte, checksum string) hash.Hash {
var hashType hash.Hash

switch len(checksum) {
Expand Down Expand Up @@ -123,7 +122,7 @@ func CompareHash(content []byte, checksum string) hash.Hash {

calculated := hex.EncodeToString(hashType.Sum(nil))
if calculated != checksum {
log.Printf("wanted checksum %s, but got %s", checksum, calculated)
pd.Log.Printf("wanted checksum %s, but got %s", checksum, calculated)
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/directives/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func add(cfg *srpmprocpb.Cfg, pd *data.ProcessData, md *data.ModeData, patchTree
return err
}

hashFunction := data.CompareHash(replacingBytes, addType.Lookaside)
hashFunction := pd.CompareHash(replacingBytes, addType.Lookaside)
if hashFunction == nil {
return errors.New(fmt.Sprintf("LOOKASIDE_HASH_DOES_NOT_MATCH:%s", addType.Lookaside))
}
Expand Down
8 changes: 3 additions & 5 deletions pkg/directives/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,21 @@ import (
"bytes"
"errors"
"fmt"
"log"

"github.com/bluekeyes/go-gitdiff/gitdiff"
"github.com/go-git/go-git/v5"
srpmprocpb "github.com/rocky-linux/srpmproc/pb"
"github.com/rocky-linux/srpmproc/pkg/data"
)

func patch(cfg *srpmprocpb.Cfg, _ *data.ProcessData, _ *data.ModeData, patchTree *git.Worktree, pushTree *git.Worktree) error {
func patch(cfg *srpmprocpb.Cfg, pd *data.ProcessData, _ *data.ModeData, patchTree *git.Worktree, pushTree *git.Worktree) error {
for _, patch := range cfg.Patch {
patchFile, err := patchTree.Filesystem.Open(patch.File)
if err != nil {
return errors.New(fmt.Sprintf("COULD_NOT_OPEN_PATCH_FILE:%s", patch.File))
}
files, _, err := gitdiff.Parse(patchFile)
if err != nil {
log.Printf("could not parse patch file: %v", err)
pd.Log.Printf("could not parse patch file: %v", err)
return errors.New(fmt.Sprintf("COULD_NOT_PARSE_PATCH_FILE:%s", patch.File))
}

Expand All @@ -58,7 +56,7 @@ func patch(cfg *srpmprocpb.Cfg, _ *data.ProcessData, _ *data.ModeData, patchTree

err = gitdiff.NewApplier(patchSubjectFile).ApplyFile(&output, patchedFile)
if err != nil {
log.Printf("could not apply patch: %v", err)
pd.Log.Printf("could not apply patch: %v", err)
return errors.New(fmt.Sprintf("COULD_NOT_APPLY_PATCH_WITH_SUBJECT:%s", srcPath))
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/directives/replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func replace(cfg *srpmprocpb.Cfg, pd *data.ProcessData, _ *data.ModeData, patchT
if err != nil {
return err
}
hasher := data.CompareHash(bts, replacing.WithLookaside)
hasher := pd.CompareHash(bts, replacing.WithLookaside)
if hasher == nil {
return errors.New("LOOKASIDE_FILE_AND_HASH_NOT_MATCHING")
}
Expand Down
15 changes: 7 additions & 8 deletions pkg/modes/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"fmt"
"github.com/rocky-linux/srpmproc/pkg/misc"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"sort"
Expand Down Expand Up @@ -142,7 +141,7 @@ func (g *GitMode) RetrieveSource(pd *data.ProcessData) (*data.ModeData, error) {
}

for _, branch := range latestTags {
log.Printf("tag: %s", strings.TrimPrefix(branch.remote, "refs/tags/"))
pd.Log.Printf("tag: %s", strings.TrimPrefix(branch.remote, "refs/tags/"))
branches = append(branches, *branch)
}

Expand Down Expand Up @@ -179,7 +178,7 @@ func (g *GitMode) WriteSource(pd *data.ProcessData, md *data.ModeData) error {
branchName = match[2]
refspec = config.RefSpec(fmt.Sprintf("+refs/heads/%s:%s", branchName, md.TagBranch))
}
log.Printf("checking out upstream refspec %s", refspec)
pd.Log.Printf("checking out upstream refspec %s", refspec)
err = remote.Fetch(&git.FetchOptions{
RemoteName: "upstream",
RefSpecs: []config.RefSpec{refspec},
Expand All @@ -205,7 +204,7 @@ func (g *GitMode) WriteSource(pd *data.ProcessData, md *data.ModeData) error {

metadataFile, err := md.Worktree.Filesystem.Open(fmt.Sprintf(".%s.metadata", md.Name))
if err != nil {
log.Printf("warn: could not open metadata file, so skipping: %v", err)
pd.Log.Printf("warn: could not open metadata file, so skipping: %v", err)
return nil
}

Expand Down Expand Up @@ -233,18 +232,18 @@ func (g *GitMode) WriteSource(pd *data.ProcessData, md *data.ModeData) error {

if md.BlobCache[hash] != nil {
body = md.BlobCache[hash]
log.Printf("retrieving %s from cache", hash)
pd.Log.Printf("retrieving %s from cache", hash)
} else {
fromBlobStorage, err := pd.BlobStorage.Read(hash)
if err != nil {
return err
}
if fromBlobStorage != nil && !pd.NoStorageDownload {
body = fromBlobStorage
log.Printf("downloading %s from blob storage", hash)
pd.Log.Printf("downloading %s from blob storage", hash)
} else {
url := fmt.Sprintf("%s/%s/%s/%s", pd.CdnUrl, md.Name, branchName, hash)
log.Printf("downloading %s", url)
pd.Log.Printf("downloading %s", url)

req, err := http.NewRequest("GET", url, nil)
if err != nil {
Expand Down Expand Up @@ -275,7 +274,7 @@ func (g *GitMode) WriteSource(pd *data.ProcessData, md *data.ModeData) error {
return fmt.Errorf("could not open file pointer: %v", err)
}

hasher := data.CompareHash(body, hash)
hasher := pd.CompareHash(body, hash)
if hasher == nil {
return fmt.Errorf("checksum in metadata does not match dist-git file")
}
Expand Down
11 changes: 8 additions & 3 deletions pkg/srpmproc/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"github.com/rocky-linux/srpmproc/pkg/data"
"io"
"io/ioutil"
"log"
"net/http"
Expand All @@ -12,7 +13,11 @@ import (
"strings"
)

func Fetch(cdnUrl string, dir string) error {
func Fetch(logger io.Writer, cdnUrl string, dir string) error {
pd := &data.ProcessData{
Log: log.New(logger, "", log.LstdFlags),
}

metadataPath := ""
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".metadata") {
Expand Down Expand Up @@ -53,7 +58,7 @@ func Fetch(cdnUrl string, dir string) error {
path := lineInfo[1]

url := fmt.Sprintf("%s/%s", cdnUrl, hash)
log.Printf("downloading %s", url)
pd.Log.Printf("downloading %s", url)

req, err := http.NewRequest("GET", url, nil)
if err != nil {
Expand All @@ -75,7 +80,7 @@ func Fetch(cdnUrl string, dir string) error {
return fmt.Errorf("could not close body handle: %v", err)
}

hasher := data.CompareHash(body, hash)
hasher := pd.CompareHash(body, hash)
if hasher == nil {
return fmt.Errorf("checksum in metadata does not match dist-git file")
}
Expand Down
10 changes: 5 additions & 5 deletions pkg/srpmproc/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func cfgPatches(pd *data.ProcessData, md *data.ModeData, patchTree *git.Worktree
continue
}

log.Printf("applying directive %s", info.Name())
pd.Log.Printf("applying directive %s", info.Name())
filePath := filepath.Join("ROCKY/CFG", info.Name())
directive, err := patchTree.Filesystem.Open(filePath)
if err != nil {
Expand Down Expand Up @@ -137,7 +137,7 @@ func executePatchesRpm(pd *data.ProcessData, md *data.ModeData) error {
err = repo.Fetch(fetchOptions)

refName := plumbing.NewBranchReferenceName(md.PushBranch)
log.Printf("set reference to ref: %s", refName)
pd.Log.Printf("set reference to ref: %s", refName)

if err != nil {
// no patches active
Expand Down Expand Up @@ -197,9 +197,9 @@ func getTipStream(pd *data.ProcessData, module string, pushBranch string, origPu
Auth: pd.Authenticator,
})
if err != nil {
log.Printf("could not import module: %s", module)
pd.Log.Printf("could not import module: %s", module)
if tries < 3 {
log.Printf("could not get rpm refs. will retry in 3s. %v", err)
pd.Log.Printf("could not get rpm refs. will retry in 3s. %v", err)
time.Sleep(3 * time.Second)
return getTipStream(pd, module, pushBranch, origPushBranch, tries+1)
}
Expand Down Expand Up @@ -302,7 +302,7 @@ func patchModuleYaml(pd *data.ProcessData, md *data.ModeData) error {

log.Println("This module contains the following rpms:")
for name := range module.Data.Components.Rpms {
log.Printf("\t- %s", name)
pd.Log.Printf("\t- %s", name)
}

defaultBranch := md.PushBranch
Expand Down
30 changes: 20 additions & 10 deletions pkg/srpmproc/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ import (
"github.com/rocky-linux/srpmproc/pkg/misc"
"github.com/rocky-linux/srpmproc/pkg/modes"
"github.com/rocky-linux/srpmproc/pkg/rpmutils"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"strings"
Expand Down Expand Up @@ -88,6 +90,7 @@ type ProcessDataRequest struct {
NoStorageDownload bool
SingleTag string
CdnUrl string
LogWriter io.Writer
}

func gitlabify(str string) string {
Expand Down Expand Up @@ -191,8 +194,14 @@ func NewProcessData(req *ProcessDataRequest) (*data.ProcessData, error) {
reqFsCreator = req.FsCreator
}

var writer io.Writer = os.Stdout
if req.LogWriter != nil {
writer = req.LogWriter
}
logger := log.New(writer, "", log.LstdFlags)

if req.TmpFsMode != "" {
log.Printf("using tmpfs dir: %s", req.TmpFsMode)
logger.Printf("using tmpfs dir: %s", req.TmpFsMode)
fsCreator = func(branch string) (billy.Filesystem, error) {
fs, err := reqFsCreator(branch)
if err != nil {
Expand Down Expand Up @@ -242,6 +251,7 @@ func NewProcessData(req *ProcessDataRequest) (*data.ProcessData, error) {
AllowStreamBranches: req.AllowStreamBranches,
FsCreator: fsCreator,
CdnUrl: req.CdnUrl,
Log: logger,
}, nil
}

Expand Down Expand Up @@ -344,7 +354,7 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {
if strings.HasPrefix(md.TagBranch, prefix) {
replace := strings.Replace(md.TagBranch, "refs/heads/", "", 1)
matchString = fmt.Sprintf("refs/tags/imports/%s/%s", replace, filepath.Base(pd.RpmLocation))
log.Printf("using match string: %s", matchString)
pd.Log.Printf("using match string: %s", matchString)
}
}
if !misc.GetTagImportRegex(pd.ImportBranchPrefix, pd.AllowStreamBranches).MatchString(matchString) {
Expand Down Expand Up @@ -377,7 +387,7 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {
shouldContinue := true
for _, ignoredTag := range tagIgnoreList {
if ignoredTag == "refs/tags/"+newTag {
log.Printf("skipping %s", ignoredTag)
pd.Log.Printf("skipping %s", ignoredTag)
shouldContinue = false
}
}
Expand All @@ -387,9 +397,9 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {

// create a new remote
remoteUrl := fmt.Sprintf("%s/%s/%s.git", pd.UpstreamPrefix, remotePrefix, gitlabify(md.Name))
log.Printf("using remote: %s", remoteUrl)
pd.Log.Printf("using remote: %s", remoteUrl)
refspec := config.RefSpec(fmt.Sprintf("+refs/heads/%s:refs/remotes/origin/%s", md.PushBranch, md.PushBranch))
log.Printf("using refspec: %s", refspec)
pd.Log.Printf("using refspec: %s", refspec)

_, err = repo.CreateRemote(&config.RemoteConfig{
Name: "origin",
Expand All @@ -407,7 +417,7 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {
})

refName := plumbing.NewBranchReferenceName(md.PushBranch)
log.Printf("set reference to ref: %s", refName)
pd.Log.Printf("set reference to ref: %s", refName)

var hash plumbing.Hash
if commitPin[md.PushBranch] != "" {
Expand Down Expand Up @@ -501,7 +511,7 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {
if err != nil {
return nil, err
}
log.Printf("wrote %s to blob storage", checksum)
pd.Log.Printf("wrote %s to blob storage", checksum)
}
alreadyUploadedBlobs = append(alreadyUploadedBlobs, checksum)
}
Expand Down Expand Up @@ -541,7 +551,7 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {

// show status
status, _ := w.Status()
log.Printf("successfully processed:\n%s", status)
pd.Log.Printf("successfully processed:\n%s", status)

statusLines := strings.Split(status.String(), "\n")
for _, line := range statusLines {
Expand All @@ -563,7 +573,7 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {
hashes = nil
pushRefspecs = append(pushRefspecs, "*:*")
} else {
log.Printf("tip %s", head.String())
pd.Log.Printf("tip %s", head.String())
hashes = append(hashes, head.Hash())
refOrigin := "refs/heads/" + md.PushBranch
pushRefspecs = append(pushRefspecs, config.RefSpec(fmt.Sprintf("HEAD:%s", refOrigin)))
Expand All @@ -588,7 +598,7 @@ func ProcessRPM(pd *data.ProcessData) (*srpmprocpb.ProcessResponse, error) {
return nil, fmt.Errorf("could not get commit object: %v", err)
}

log.Printf("committed:\n%s", obj.String())
pd.Log.Printf("committed:\n%s", obj.String())

_, err = repo.CreateTag(newTag, commit, &git.CreateTagOptions{
Tagger: &object.Signature{
Expand Down

0 comments on commit 102ff04

Please sign in to comment.