Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a shortcut integration #32

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
gpt-updater:description
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this related to shortcut, do you mind to create a new PR for that?

8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,13 @@ Replace `<GITHUB_TOKEN>`, `<OPENAI_TOKEN>`, `<OWNER>`, `<REPO>`, and `<PR_NUMBER
### Description Command

The usage for the `description` command is similar to the `review` command. Replace `review` with `description` in the command above and execute.
Only difference is that `description` command has extra option `--jira-url` which is used to generate Jira links in the description.
The only difference is that the `description` command has extra options, `--jira-url` and `--shortcut-url`, which are used to generate Jira or Shortcut links in the description, accordingly.

### Templates

You can add the file `.github/pull_request_template.md` to your repository to customize the default pull request description. The template file can contain the following placeholders:

- `gpt-updater:description` - when this placeholder is present in your pull request description, it will be replaced with the generated description; otherwise, the entire description field will be replaced.

## GitHub Action

Expand Down
55 changes: 43 additions & 12 deletions cmd/description/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,23 @@ import (
ghClient "github.com/ravilushqa/gpt-pullrequest-updater/github"
"github.com/ravilushqa/gpt-pullrequest-updater/jira"
oAIClient "github.com/ravilushqa/gpt-pullrequest-updater/openai"
"github.com/ravilushqa/gpt-pullrequest-updater/shortcut"
)

var opts struct {
GithubToken string `long:"gh-token" env:"GITHUB_TOKEN" description:"GitHub token" required:"true"`
OpenAIToken string `long:"openai-token" env:"OPENAI_TOKEN" description:"OpenAI token" required:"true"`
Owner string `long:"owner" env:"OWNER" description:"GitHub owner" required:"true"`
Repo string `long:"repo" env:"REPO" description:"GitHub repo" required:"true"`
PRNumber int `long:"pr-number" env:"PR_NUMBER" description:"Pull request number" required:"true"`
OpenAIModel string `long:"openai-model" env:"OPENAI_MODEL" description:"OpenAI model" default:"gpt-3.5-turbo"`
Test bool `long:"test" env:"TEST" description:"Test mode"`
JiraURL string `long:"jira-url" env:"JIRA_URL" description:"Jira URL. Example: https://jira.atlassian.com"`
GithubToken string `long:"gh-token" env:"GITHUB_TOKEN" description:"GitHub token" required:"true"`
OpenAIToken string `long:"openai-token" env:"OPENAI_TOKEN" description:"OpenAI token" required:"true"`
Owner string `long:"owner" env:"OWNER" description:"GitHub owner" required:"true"`
Repo string `long:"repo" env:"REPO" description:"GitHub repo" required:"true"`
PRNumber int `long:"pr-number" env:"PR_NUMBER" description:"Pull request number" required:"true"`
OpenAIModel string `long:"openai-model" env:"OPENAI_MODEL" description:"OpenAI model" default:"gpt-3.5-turbo"`
Test bool `long:"test" env:"TEST" description:"Test mode"`
JiraURL string `long:"jira-url" env:"JIRA_URL" description:"Jira URL. Example: https://jira.atlassian.com"`
ShortcutBaseURL string `long:"shortcut-url" env:"SHORTCUT_URL" description:"Shortcut URL. Example: https://app.shortcut.com/foo"`
}

var descriptionInfo description.Info

func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
Expand All @@ -52,12 +56,17 @@ func run(ctx context.Context) error {
return fmt.Errorf("error getting pull request: %w", err)
}

if pr.Body != nil && description.IsDescriptionFinished(*pr.Body) {
fmt.Println("Pull request already has a generated description. Skipping...")
return nil
}

diff, err := githubClient.CompareCommits(ctx, opts.Owner, opts.Repo, pr.GetBase().GetSHA(), pr.GetHead().GetSHA())
if err != nil {
return fmt.Errorf("error getting commits: %w", err)
}

completion, err := description.GenerateCompletion(ctx, openAIClient, diff, pr)
descriptionInfo.Completion, err = description.GenerateCompletion(ctx, openAIClient, diff, pr)
if err != nil {
return fmt.Errorf("error generating completion: %w", err)
}
Expand All @@ -68,20 +77,42 @@ func run(ctx context.Context) error {
if err != nil {
fmt.Printf("Error extracting Jira ticket ID: %v \n", err)
} else {
completion = fmt.Sprintf("### JIRA ticket: [%s](%s) \n\n%s", id, jira.GenerateJiraTicketURL(opts.JiraURL, id), completion)
descriptionInfo.JiraInfo = fmt.Sprintf("### JIRA ticket: [%s](%s)", id, jira.GenerateJiraTicketURL(opts.JiraURL, id))
}
}

if opts.ShortcutBaseURL != "" {
descriptionInfo.ShortcutInfo = buildShortcutContent(opts.ShortcutBaseURL, pr)
}

if opts.Test {
return nil
}

// Update the pull request description
fmt.Println("Updating pull request")
updatePr := &github.PullRequest{Body: github.String(completion)}
if _, err = githubClient.UpdatePullRequest(ctx, opts.Owner, opts.Repo, opts.PRNumber, updatePr); err != nil {
updatedPr := description.BuildUpdatedPullRequest(pr.Body, descriptionInfo)
if _, err = githubClient.UpdatePullRequest(ctx, opts.Owner, opts.Repo, opts.PRNumber, updatedPr); err != nil {
return fmt.Errorf("error updating pull request: %w", err)
}

return nil
}

func buildShortcutContent(shortcutBaseURL string, pr *github.PullRequest) string {
fmt.Println("Adding Shortcut ticket")

id, err := shortcut.ExtractShortcutStoryID(*pr.Title)

if err != nil {
// Extracting from the branch name
id, err = shortcut.ExtractShortcutStoryID(*pr.Head.Ref)
}

if err != nil {
fmt.Printf("There is no Shortcut story ID: %v \n", err)
return ""
}

return fmt.Sprintf("### Shortcut story: [%s](%s)", id, shortcut.GenerateShortcutStoryURL(shortcutBaseURL, id))
}
44 changes: 44 additions & 0 deletions description/description.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,23 @@ package description
import (
"context"
"fmt"
"strings"

"github.com/google/go-github/v51/github"
"github.com/sashabaranov/go-openai"

oAIClient "github.com/ravilushqa/gpt-pullrequest-updater/openai"
)

const placeholder = "gpt-updater:description"
const placeholderFinished = "<!-- gpt-updater:description -->"

type Info struct {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The structure doesn't look flexible and, in my opinion, needs improvement. What do you think about keeping the old flat logic without an extra structure and simply validating that only JIRA or shortcut are allowed? If both are passed, then return an error.

Completion string
JiraInfo string
ShortcutInfo string
}

func GenerateCompletion(ctx context.Context, client *oAIClient.Client, diff *github.CommitsComparison, pr *github.PullRequest) (string, error) {
sumDiffs := calculateSumDiffs(diff)

Expand All @@ -24,6 +34,40 @@ func GenerateCompletion(ctx context.Context, client *oAIClient.Client, diff *git
return completion, err
}

func BuildUpdatedPullRequest(existingDescription *string, info Info) *github.PullRequest {

desc := ""

if info.JiraInfo != "" {
desc = info.JiraInfo + "\n\n" + desc
}

if info.ShortcutInfo != "" {
desc = info.ShortcutInfo + "\n\n" + desc
}

if info.Completion != "" {
desc += info.Completion
}

builtBody := fmt.Sprintf("%s\n## 🤖 gpt-updater description\n%s", placeholderFinished, desc)

if existingDescription != nil && needToUpdateByPlaceholder(*existingDescription) {
builtBody = strings.Replace(*existingDescription, placeholder, builtBody, 1)
}

return &github.PullRequest{Body: github.String(builtBody)}
}

func IsDescriptionFinished(existingDescription string) bool {
return strings.Contains(existingDescription, placeholderFinished)
}

func needToUpdateByPlaceholder(existingDescription string) bool {
return !strings.Contains(existingDescription, placeholderFinished) &&
strings.Contains(existingDescription, placeholder)
}

func calculateSumDiffs(diff *github.CommitsComparison) int {
sumDiffs := 0
for _, file := range diff.Files {
Expand Down
29 changes: 29 additions & 0 deletions shortcut/shortcut.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package shortcut

import (
"fmt"
"regexp"
)

const storyURLFormat = "%s/story/%s"

func ExtractShortcutStoryID(title string) (string, error) {

// This regular expression pattern matches a Shortcut story ID (e.g. sc-12345).
pattern := `sc-([\d]+)`
re, err := regexp.Compile(pattern)
if err != nil {
return "", fmt.Errorf("error compiling regex: %w", err)
}

matches := re.FindStringSubmatch(title)
if len(matches) < 2 {
return "", fmt.Errorf("no Shortcut story ID found in the input string")
}

return matches[1], nil
}

func GenerateShortcutStoryURL(shortcutBaseURL, ticketID string) string {
return fmt.Sprintf(storyURLFormat, shortcutBaseURL, ticketID)
}
51 changes: 51 additions & 0 deletions shortcut/shortcut_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package shortcut

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestExtractShortcutStoryID(t *testing.T) {
testCases := []struct {
title string
expectedID string
expectedErr bool
}{
{
title: "This is a sample title with a valid story ID sc-12345",
expectedID: "12345",
expectedErr: false,
},
{
title: "No story ID in this title",
expectedID: "",
expectedErr: true,
},
{
title: "Invalid story ID format sc-abcde",
expectedID: "",
expectedErr: true,
},
}

for _, tc := range testCases {
id, err := ExtractShortcutStoryID(tc.title)

if tc.expectedErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tc.expectedID, id)
}
}
}

func TestGenerateShortcutStoryURL(t *testing.T) {
baseURL := "https://app.shortcut.com/foo"
ticketID := "12345"
expectedURL := "https://app.shortcut.com/foo/story/12345"

url := GenerateShortcutStoryURL(baseURL, ticketID)
assert.Equal(t, expectedURL, url)
}