diff --git a/utils/utils.go b/utils/utils.go index 25a7338a..7c62df50 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -240,6 +240,39 @@ func GetLatestReleaseTagsSorted(org string, repo string) ([]string, error) { return versions, nil } +// Gets release tag from github for a given org name, repo name(in that org) and tag +func GetLatestReleaseTagCommitSHA(org string, repo string) (string, error) { + url := fmt.Sprintf("https://github.com/%s/%s/tags", org, repo) + + resp, err := http.Get(url) + if err != nil { + return "", errors.New("cannot get list of tags from Github") + } + defer safeClose(resp.Body) + + if (resp.StatusCode == 404) { + return "", errors.New("repository is not found") + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + re := regexp.MustCompile("/commit/(.*?)\"") + releases := re.FindAllString(string(body), -1) + if len(releases) == 0 { + return "", errors.New("no commit found in this repository") + } + var commits []string + for _, rel := range releases { + latest := strings.ReplaceAll(rel, "/commit/", "") + latest = strings.ReplaceAll(latest, "\"", "") + commits = append(commits, latest) + } + + return commits[0], nil +} + // SafeClose is a helper function help to close the io func safeClose(co io.Closer) { if cerr := co.Close(); cerr != nil { diff --git a/utils/utils_test.go b/utils/utils_test.go index 523145be..b2df3700 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -78,3 +78,49 @@ func TestTransformMapKeys(t *testing.T) { }) } } + +func TestGetLatestReleaseTagCommitSHAInvalid(t *testing.T) { + cases := []struct{ + description string + org string + repo string + expectedErr string + }{ + { + description: "Test cases negative not existed repository", + org: "layer5labs", + repo: "meshery-extensions-package", + expectedErr: "repository is not found", + }, + { + description: "Test cases negative not existed repository", + org: "layer5io", + repo: "docs", + expectedErr: "no commit found in this repository", + }, + } + for _, tt := range cases { + t.Run(tt.description, func(t *testing.T){ + commitSHA, err := GetLatestReleaseTagCommitSHA(tt.org, tt.repo) + if err.Error() != tt.expectedErr { + t.Errorf("expected error %s, but got error %s", err, err.Error()) + } + + if commitSHA != "" { + t.Errorf("expected commitSHA string empty, but got %s", commitSHA) + } + }) + } +} + +func TestGetLatestReleaseTagCommitSHA(t *testing.T) { + commitSHA, err := GetLatestReleaseTagCommitSHA("kelseyhightower", "nocode") + if err != nil { + t.Errorf("expected no error, but got error %s", err) + } + + expectedSHA := "ed6c73fc16578ec53ea374585df2b965ce9f4a31" + if commitSHA != "ed6c73fc16578ec53ea374585df2b965ce9f4a31" { + t.Errorf("expected commitSHA %s, but got %s", commitSHA, expectedSHA) + } +}