github.com/covergates/covergates@v0.2.2-0.20201009050117-42ef8a19fb95/modules/repo/service.go (about)

     1  package repo
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/covergates/covergates/config"
     7  	"github.com/covergates/covergates/core"
     8  	"github.com/sirupsen/logrus"
     9  )
    10  
    11  // Service of repository
    12  type Service struct {
    13  	config     *config.Config
    14  	scmService core.SCMService
    15  	userStore  core.UserStore
    16  	repoStore  core.RepoStore
    17  }
    18  
    19  // NewService of repository
    20  func NewService(
    21  	config *config.Config,
    22  	scmService core.SCMService,
    23  	userStore core.UserStore,
    24  	repoStore core.RepoStore,
    25  ) *Service {
    26  	return &Service{
    27  		config:     config,
    28  		scmService: scmService,
    29  		userStore:  userStore,
    30  		repoStore:  repoStore,
    31  	}
    32  }
    33  
    34  // Synchronize repository with remote and store to database
    35  func (s *Service) Synchronize(ctx context.Context, user *core.User) error {
    36  	userRepos := make([]*core.Repo, 0)
    37  	for _, provider := range s.config.Providers() {
    38  		client, err := s.scmService.Client(provider)
    39  		if err != nil {
    40  			return err
    41  		}
    42  		repos, err := client.Repositories().List(ctx, user)
    43  		if err != nil {
    44  			logrus.Warnln(err)
    45  			continue
    46  		}
    47  		if err := s.repoStore.BatchUpdateOrCreate(repos); err != nil {
    48  			return err
    49  		}
    50  		userRepos = append(userRepos, repos...)
    51  	}
    52  	return s.userStore.UpdateRepositories(user, userRepos)
    53  }