BREAKING CHANGE: Setup refactor and code cleanup

This MR makes several major tweaks to the codebase. Primarily it adjusts
the setup steps for the application so that rather than providing just
the project ID in the `.gitlab.nvim` file, users can also provide a
vareity of other settings, such as auth_token, base_branch, and so
forth. This is to make the project more extensible in the future.

This MR also fixes a variety of issues with error handling in the code,
primarily in the request/response model between the Lua jobs and the
Golang server.

BREAKING CHANGE: Modifies `.gitlab.nvim` and setup steps
This commit is contained in:
Harrison (Harry) Cramer
2023-08-06 11:21:39 -04:00
committed by Harrison Cramer
parent ade9f81426
commit 4f0d4b49ef
16 changed files with 281 additions and 293 deletions

View File

@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
@@ -18,25 +19,22 @@ func (c *Client) Approve() (string, int, error) {
}
func ApproveHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
c := r.Context().Value("client").(Client)
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
c.handleError(w, errors.New("Invalid request type"), "That request type is not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
client := r.Context().Value("client").(Client)
msg, status, err := client.Approve()
w.WriteHeader(status)
msg, status, err := c.Approve()
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: status,
}
json.NewEncoder(w).Encode(response)
c.handleError(w, err, "Could not approve MR", http.StatusBadRequest)
return
}
/* TODO: Check for non-200 status codes */
w.WriteHeader(status)
response := SuccessResponse{
Message: msg,
Status: http.StatusOK,

View File

@@ -1,8 +1,10 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strconv"
@@ -10,10 +12,12 @@ import (
)
type Client struct {
command string
projectId string
mergeId int
git *gitlab.Client
command string
projectId string
mergeId int
gitlabInstance string
authToken string
git *gitlab.Client
}
type Logger struct {
@@ -22,7 +26,9 @@ type Logger struct {
func (l Logger) Printf(s string, args ...interface{}) {
logString := fmt.Sprintf(s+"\n", args...)
file, err := os.OpenFile("./logs", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
logPath := os.Args[len(os.Args)-1]
file, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
@@ -31,21 +37,36 @@ func (l Logger) Printf(s string, args ...interface{}) {
}
/* This will initialize the client with the token and check for the basic project ID and command arguments */
func (c *Client) Init(branchName string) error {
func (c *Client) init(branchName string) error {
if len(os.Args) < 2 {
return errors.New("Must provide project ID!")
if len(os.Args) < 5 {
return errors.New("Must provide project ID, gitlab instance, port, and auth token!")
}
projectId := os.Args[1]
c.projectId = projectId
gitlabInstance := os.Args[2]
authToken := os.Args[4]
if projectId == "" {
return errors.New("Project ID cannot be empty")
}
if gitlabInstance == "" {
return errors.New("GitLab instance URL cannot be empty")
}
if authToken == "" {
return errors.New("Auth token cannot be empty")
}
c.gitlabInstance = gitlabInstance
c.projectId = projectId
c.authToken = authToken
var l Logger
git, err := gitlab.NewClient(os.Getenv("GITLAB_TOKEN"), gitlab.WithCustomLogger(l))
var apiCustUrl = fmt.Sprintf(c.gitlabInstance + "/api/v4")
git, err := gitlab.NewClient(authToken, gitlab.WithBaseURL(apiCustUrl), gitlab.WithCustomLogger(l))
if err != nil {
return fmt.Errorf("Failed to create client: %v", err)
@@ -77,3 +98,12 @@ func (c *Client) Init(branchName string) error {
return nil
}
func (c *Client) handleError(w http.ResponseWriter, err error, message string, status int) {
w.WriteHeader(status)
response := ErrorResponse{
Message: message,
Details: err.Error(),
}
json.NewEncoder(w).Encode(response)
}

View File

@@ -9,13 +9,12 @@ import (
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"time"
"github.com/xanzy/go-gitlab"
)
const mrVersionsUrl = "https://gitlab.com/api/v4/projects/%s/merge_requests/%d/versions"
const mrVersionsUrl = "%s/api/v4/projects/%s/merge_requests/%d/versions"
type MRVersion struct {
ID int `json:"id"`
@@ -64,10 +63,7 @@ func DeleteComment(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read request body"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not read request body", http.StatusBadRequest)
return
}
@@ -76,26 +72,20 @@ func DeleteComment(w http.ResponseWriter, r *http.Request) {
var deleteCommentRequest DeleteCommentRequest
err = json.Unmarshal(body, &deleteCommentRequest)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read JSON from request"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not read JSON from request", http.StatusBadRequest)
return
}
res, err := c.git.Discussions.DeleteMergeRequestDiscussionNote(c.projectId, c.mergeId, deleteCommentRequest.DiscussionId, deleteCommentRequest.NoteId)
w.WriteHeader(res.Response.StatusCode)
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: res.Response.StatusCode,
}
json.NewEncoder(w).Encode(response)
c.handleError(w, err, "Could not delete comment", res.StatusCode)
return
}
w.WriteHeader(res.StatusCode)
/* TODO: Check status code */
response := SuccessResponse{
Message: "Comment deleted succesfully",
Status: http.StatusOK,
@@ -110,10 +100,7 @@ func PostComment(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read request body"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not read request body", http.StatusBadRequest)
return
}
@@ -122,10 +109,7 @@ func PostComment(w http.ResponseWriter, r *http.Request) {
var postCommentRequest PostCommentRequest
err = json.Unmarshal(body, &postCommentRequest)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not unmarshal data from request body"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not unmarshal data from request body", http.StatusBadRequest)
return
}
@@ -135,24 +119,19 @@ func PostComment(w http.ResponseWriter, r *http.Request) {
}
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: res.StatusCode,
}
json.NewEncoder(w).Encode(response)
c.handleError(w, err, "Could not post comment", res.StatusCode)
return
}
w.WriteHeader(res.StatusCode)
/* TODO: Check for bad status codes */
response := SuccessResponse{
Message: "Comment created succesfully",
Status: http.StatusOK,
}
json.NewEncoder(w).Encode(response)
// w.WriteHeader(res.StatusCode)
// io.Copy(w, res.Body)
}
func EditComment(w http.ResponseWriter, r *http.Request) {
@@ -161,10 +140,7 @@ func EditComment(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read request body"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not read request body", http.StatusBadRequest)
return
}
@@ -173,10 +149,7 @@ func EditComment(w http.ResponseWriter, r *http.Request) {
var editCommentRequest EditCommentRequest
err = json.Unmarshal(body, &editCommentRequest)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not unmarshal data from request body"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not unmarshal data from request body", http.StatusBadRequest)
return
}
@@ -191,11 +164,7 @@ func EditComment(w http.ResponseWriter, r *http.Request) {
}
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: res.StatusCode,
}
json.NewEncoder(w).Encode(response)
c.handleError(w, err, "Could not edit comment", res.StatusCode)
return
}
@@ -209,7 +178,7 @@ func EditComment(w http.ResponseWriter, r *http.Request) {
func (c *Client) PostComment(cr PostCommentRequest) (*http.Response, error) {
err, response := getMRVersions(c.projectId, c.mergeId)
err, response := getMRVersions(c.gitlabInstance, c.projectId, c.mergeId, c.authToken)
if err != nil {
return nil, fmt.Errorf("Error making diff thread: %e", err)
}
@@ -255,14 +224,12 @@ func min(a int, b int) int {
}
/* Gets the latest merge request revision data */
func getMRVersions(projectId string, mergeId int) (e error, response *http.Response) {
gitlabToken := os.Getenv("GITLAB_TOKEN")
url := fmt.Sprintf(mrVersionsUrl, projectId, mergeId)
func getMRVersions(gitlabInstance string, projectId string, mergeId int, authToken string) (e error, response *http.Response) {
url := fmt.Sprintf(mrVersionsUrl, gitlabInstance, projectId, mergeId)
req, err := http.NewRequest(http.MethodGet, url, nil)
req.Header.Add("PRIVATE-TOKEN", gitlabToken)
req.Header.Add("PRIVATE-TOKEN", authToken)
if err != nil {
return err, nil
@@ -288,7 +255,7 @@ The go-gitlab client was not working for this API specifically 😢
*/
func (c *Client) CommentOnDeletion(lineNumber int, fileName string, comment string, diffVersionInfo MRVersion, i int) (*http.Response, error) {
deletionDiscussionUrl := fmt.Sprintf("https://gitlab.com/api/v4/projects/%s/merge_requests/%d/discussions", c.projectId, c.mergeId)
deletionDiscussionUrl := fmt.Sprintf(c.gitlabInstance+"/api/v4/projects/%s/merge_requests/%d/discussions", c.projectId, c.mergeId)
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
@@ -322,7 +289,7 @@ func (c *Client) CommentOnDeletion(lineNumber int, fileName string, comment stri
if err != nil {
return nil, fmt.Errorf("Error building request: %w", err)
}
req.Header.Add("PRIVATE-TOKEN", os.Getenv("GITLAB_TOKEN"))
req.Header.Add("PRIVATE-TOKEN", c.authToken)
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)

View File

@@ -1,26 +1,24 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
)
const mrUrl = "https://gitlab.com/api/v4/projects/%s/merge_requests/%d"
const mrUrl = "%s/api/v4/projects/%s/merge_requests/%d"
func (c *Client) Info() ([]byte, error) {
url := fmt.Sprintf(mrUrl, c.projectId, c.mergeId)
url := fmt.Sprintf(mrUrl, c.gitlabInstance, c.projectId, c.mergeId)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("Failed to build read request: %w", err)
}
req.Header.Set("PRIVATE-TOKEN", os.Getenv("GITLAB_TOKEN"))
req.Header.Set("PRIVATE-TOKEN", c.authToken)
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
@@ -46,19 +44,17 @@ func (c *Client) Info() ([]byte, error) {
}
func InfoHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
c := r.Context().Value("client").(Client)
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
c.handleError(w, errors.New("Invalid request type"), "That request type is not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
client := r.Context().Value("client").(Client)
msg, err := client.Info()
msg, err := c.Info()
if err != nil {
errResp := map[string]string{"message": err.Error()}
response, _ := json.Marshal(errResp)
w.WriteHeader(http.StatusInternalServerError)
w.Write(response)
c.handleError(w, err, "Could not get info", http.StatusBadRequest)
return
}

View File

@@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"net/http"
"sort"
@@ -62,24 +63,23 @@ func (c *Client) ListDiscussions() ([]*gitlab.Discussion, int, error) {
}
func ListDiscussionsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
c := r.Context().Value("client").(Client)
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
c.handleError(w, errors.New("Invalid request type"), "That request type is not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
c := r.Context().Value("client").(Client)
msg, status, err := c.ListDiscussions()
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: status,
}
json.NewEncoder(w).Encode(response)
c.handleError(w, err, "Could not list discussions", http.StatusBadRequest)
return
}
/* TODO: Check for non-200 statuses */
w.WriteHeader(status)
response := DiscussionsResponse{
SuccessResponse: SuccessResponse{
Message: "Discussions successfully fetched.",

View File

@@ -24,21 +24,21 @@ func main() {
/* Initialize Gitlab client */
var c Client
if err := c.Init(branchName); err != nil {
log.Fatalf("Failure: Failed to iniialize client: %v", err)
if err := c.init(branchName); err != nil {
log.Fatalf("Failure: Failed to initialize client: %v", err)
}
m := http.NewServeMux()
m.Handle("/approve", withGitlabContext(http.HandlerFunc(ApproveHandler), c))
m.Handle("/revoke", withGitlabContext(http.HandlerFunc(RevokeHandler), c))
m.Handle("/star", withGitlabContext(http.HandlerFunc(StarHandler), c))
m.Handle("/info", withGitlabContext(http.HandlerFunc(InfoHandler), c))
m.Handle("/discussions", withGitlabContext(http.HandlerFunc(ListDiscussionsHandler), c))
m.Handle("/comment", withGitlabContext(http.HandlerFunc(CommentHandler), c))
m.Handle("/reply", withGitlabContext(http.HandlerFunc(ReplyHandler), c))
port := fmt.Sprintf(":%s", os.Args[3])
server := &http.Server{
Addr: fmt.Sprintf(":%s", os.Args[2]),
Addr: port,
Handler: m,
}

View File

@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@@ -38,20 +39,17 @@ func (c *Client) Reply(r ReplyRequest) (*gitlab.Note, int, error) {
}
func ReplyHandler(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value("client").(Client)
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
c.handleError(w, errors.New("Invalid request type"), "That request type is not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
c := r.Context().Value("client").(Client)
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read request body"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not read request body", http.StatusBadRequest)
return
}
@@ -60,25 +58,18 @@ func ReplyHandler(w http.ResponseWriter, r *http.Request) {
err = json.Unmarshal(body, &replyRequest)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read JSON from request"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
c.handleError(w, err, "Could not read JSON from request", http.StatusBadRequest)
return
}
note, status, err := c.Reply(replyRequest)
w.Header().Set("Content-Type", "application/json")
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: status,
}
json.NewEncoder(w).Encode(response)
c.handleError(w, err, "Could not send reply", status)
return
}
w.WriteHeader(status)
response := ReplyResponse{
SuccessResponse: SuccessResponse{
Message: fmt.Sprintf("Replied: %s", note.Body),

View File

@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
@@ -19,25 +20,23 @@ func (c *Client) Revoke() (string, int, error) {
}
func RevokeHandler(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value("client").(Client)
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
c.handleError(w, errors.New("Invalid request type"), "That request type is not allowed", http.StatusMethodNotAllowed)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
client := r.Context().Value("client").(Client)
msg, status, err := client.Revoke()
w.WriteHeader(status)
msg, status, err := c.Revoke()
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: status,
}
json.NewEncoder(w).Encode(response)
c.handleError(w, err, "Could not revoke approval", http.StatusBadRequest)
return
}
w.WriteHeader(status)
response := SuccessResponse{
Message: msg,
Status: http.StatusOK,

View File

@@ -1,46 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/xanzy/go-gitlab"
)
func (c *Client) Star() (*gitlab.Project, int, error) {
project, res, err := c.git.Projects.StarProject(c.projectId)
if err != nil {
return nil, res.Response.StatusCode, fmt.Errorf("Starring project failed: %w", err)
}
return project, http.StatusOK, nil
}
func StarHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
client := r.Context().Value("client").(Client)
project, status, err := client.Star()
w.Header().Set("Content-Type", "application/json")
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: status,
}
json.NewEncoder(w).Encode(response)
return
}
response := SuccessResponse{
Message: fmt.Sprintf("Starred project %s successfully!", project.Name),
Status: http.StatusOK,
}
json.NewEncoder(w).Encode(response)
}

View File

@@ -2,6 +2,7 @@ package main
type ErrorResponse struct {
Message string `json:"message"`
Details string `json:"details"`
Status int `json:"status"`
}