git_utils.go 1002 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package commonutils
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "time"
  7. "github.com/google/go-github/v41/github"
  8. )
  9. var ErrNoWorkflowRuns = errors.New("no previous workflow runs found")
  10. var ErrWorkflowNotFound = errors.New("no workflow found, file missing")
  11. func GetLatestWorkflowRun(client *github.Client, owner, repo, filename, branch string) (*github.WorkflowRun, error) {
  12. ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
  13. defer cancel()
  14. workflowRuns, ghResponse, err := client.Actions.ListWorkflowRunsByFileName(
  15. ctx, owner, repo, filename, &github.ListWorkflowRunsOptions{
  16. Branch: branch,
  17. ListOptions: github.ListOptions{
  18. Page: 1,
  19. PerPage: 1,
  20. },
  21. },
  22. )
  23. if ghResponse != nil && ghResponse.StatusCode == http.StatusNotFound {
  24. return nil, ErrWorkflowNotFound
  25. }
  26. if err != nil {
  27. return nil, err
  28. }
  29. if workflowRuns == nil || workflowRuns.GetTotalCount() == 0 {
  30. return nil, ErrNoWorkflowRuns
  31. }
  32. return workflowRuns.WorkflowRuns[0], nil
  33. }