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

Demi #20

Closed
wants to merge 2 commits into from
Closed

Demi #20

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ Example usage:

Opens relevant git repository in browser

*DEMO:* [bc-open](assets/bc-open.mp4)
*DEMO:* ![bc-open](https://github.com/pgaijin66/bc/blob/main/assets/bc-open.mp4)

https://github.com/pgaijin66/bc/blob/main/assets/bc-open.mp4


##### `bc commit`
```
Expand Down
Binary file added bin/bc-darwin
Binary file not shown.
177 changes: 175 additions & 2 deletions cmd/cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@ package main

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
Expand Down Expand Up @@ -191,6 +196,173 @@ func openBrowser() {
}
}

func isBranchExistsInOrigin(branchName string) bool {
cmd := exec.Command("git", "ls-remote", "--heads", "origin", branchName)
output, err := cmd.Output()
if err != nil {
fmt.Println("Error:", err)
return false
}

outputStr := strings.TrimSpace(string(output))

lines := strings.Split(outputStr, "\n")
lineCount := len(lines)
fmt.Println(lineCount)

// hack, this is to be done better
return lineCount > 1
}

func createPr() {
currentBranchName, err := getCurrentBranchName()
if err != nil {
log.Fatal("coult not get current branch name")
}

if !isBranchExistsInOrigin(currentBranchName) {
fmt.Println("Branch:", currentBranchName, "has not been pushed to origin. Please push and try again.")
os.Exit(1)
}

repoPathCmd := exec.Command("git", "rev-parse", "--show-toplevel")
repoPathOut, err := repoPathCmd.Output()
if err != nil {
fmt.Println("Error getting repository path:", err)
os.Exit(1)
}
repositoryPath := strings.TrimSpace(string(bytes.TrimSpace(repoPathOut)))
repositoryName := filepath.Base(repositoryPath)
repoOwnerCmd := exec.Command("git", "remote", "-v")
remoteOutput, err := repoOwnerCmd.Output()
if err != nil {
fmt.Println("Error getting remote information:", err)
os.Exit(1)
}

fmt.Println(string(repositoryName))
fmt.Println(string(remoteOutput))

remoteURL := string(remoteOutput)

lines := strings.Split(remoteURL, "\n")

// hack :D
lastLine := lines[len(lines)-2]

parts := strings.Split(lastLine, ":")
if len(parts) < 2 {
fmt.Println("Invalid remote URL format")
return
}

// Take the first part after splitting by "/"
repoOwner := strings.Split(parts[1], "/")[0]
fmt.Println("Repository Owner:", repoOwner)

var prTitle, prTicket, prType, prChangeType, destBranch string

fmt.Print("Title of the Pull Request: ")
fmt.Scanln(&prTitle)

fmt.Print("Is this PR associated with any ticket (eg: JIRA-124): ")
fmt.Scanln(&prTicket)

fmt.Println("Explain work done in this PR (When finished hit ctrl-d on a new line to proceed):")
scanner := bufio.NewScanner(os.Stdin)
var prMessage strings.Builder
for scanner.Scan() {
prMessage.WriteString(scanner.Text())
prMessage.WriteString("\n")
}
fmt.Print("PR type (eg: SHOW, SHIP. ASK): ")
fmt.Scanln(&prType)

fmt.Print("What kind of change is this (eg: Bufix, Feature, Breaking Change, Doc update): ")
fmt.Scanln(&prChangeType)

fmt.Print("Source branch name: ")
srcBranch := "feat/bc/create-pr-from-bc"
fmt.Scanln(&srcBranch)

fmt.Print("Destination branch name: ")
fmt.Scanln(&destBranch)

updatedTitle := fmt.Sprintf("%s(%s): %s", prTicket, prType, prTitle)

prBody := fmt.Sprintf(`# Change Description

%s

-------------------------------------------

# Type of PR

- [X] %s

-------------------------------------------

# Type of Change

- [X] %s

-------------------------------------------

## Checklist before requesting a review
- [X] I have performed a self-review of my code
- [X] I am ready to get this code reviewed
- [X] I have locally tested this code against linting and validating.`, prMessage.String(), prType, prChangeType)

payload := map[string]string{
"title": updatedTitle,
"body": prBody,
"head": srcBranch,
"base": destBranch,
}

payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
os.Exit(1)
}

ghToken := os.Getenv("GH_TOKEN")
if ghToken == "" {
fmt.Println("GitHub token not set")
os.Exit(1)
}

githubURL := fmt.Sprintf("https://api.github.com/repos/%s/%s/pulls", repoOwner, repositoryName)
fmt.Println(payload)
req, err := http.NewRequest("POST", githubURL, bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Println("Error creating HTTP request:", err)
os.Exit(1)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+ghToken)
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making HTTP request:", err)
os.Exit(1)
}
defer resp.Body.Close()

_, err = io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
os.Exit(1)
}

fmt.Println("Response Status:", resp.Status)
// fmt.Println("Response Body:", string(body))
}

func main() {
if !hasGit() {
fmt.Println("This is not a git repo. I am not needed here. Ta Ta !!!")
Expand Down Expand Up @@ -219,9 +391,10 @@ func main() {
case "help":
usage()
case "pr":
createPr()
// Handle pull request creation
fmt.Println("Pull request creation functionality is not implemented yet.")
os.Exit(1)
// fmt.Println("Pull request creation functionality is not implemented yet.")
// os.Exit(1)
default:
fmt.Println("Could not understand the command. Try running \"bc help\".")
os.Exit(1)
Expand Down
Loading