Feat: Upload Files (#59)

This MR adds the ability to add files to comments, notes, replys, and MR descriptions via a picker.

The file will get uploaded to Gitlab and the filepath will be automatically added into the current popup buffer at the current line. You can then save the changes with the normal save functionality.
This commit is contained in:
Harrison (Harry) Cramer
2023-09-08 10:02:01 -04:00
committed by GitHub
parent 45329f4d69
commit 4e473dab7e
11 changed files with 166 additions and 11 deletions

71
cmd/attachment.go Normal file
View File

@@ -0,0 +1,71 @@
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
type AttachmentRequest struct {
FilePath string `json:"file_path"`
FileName string `json:"file_name"`
}
type AttachmentResponse struct {
SuccessResponse
Markdown string `json:"markdown"`
Alt string `json:"alt"`
Url string `json:"url"`
}
func AttachmentHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
c := r.Context().Value("client").(Client)
w.Header().Set("Content-Type", "application/json")
var attachmentRequest AttachmentRequest
body, err := io.ReadAll(r.Body)
if err != nil {
c.handleError(w, err, "Could not read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
err = json.Unmarshal(body, &attachmentRequest)
if err != nil {
c.handleError(w, err, "Could not unmarshal JSON", http.StatusBadRequest)
return
}
file, err := os.Open(attachmentRequest.FilePath)
if err != nil {
c.handleError(w, err, fmt.Sprintf("Could not read %s", attachmentRequest.FilePath), http.StatusBadRequest)
return
}
defer file.Close()
projectFile, res, err := c.git.Projects.UploadFile(c.projectId, file, attachmentRequest.FileName)
if err != nil {
c.handleError(w, err, fmt.Sprintf("Could not upload %s to Gitlab", attachmentRequest.FilePath), res.StatusCode)
return
}
fileResponse := AttachmentResponse{
SuccessResponse: SuccessResponse{
Status: http.StatusOK,
Message: "File uploaded successfully",
},
Markdown: projectFile.Markdown,
Alt: projectFile.Alt,
Url: projectFile.URL,
}
json.NewEncoder(w).Encode(fileResponse)
}

View File

@@ -30,6 +30,7 @@ func main() {
m := http.NewServeMux()
m.Handle("/mr/description", withGitlabContext(http.HandlerFunc(DescriptionHandler), c))
m.Handle("/mr/attachment", withGitlabContext(http.HandlerFunc(AttachmentHandler), c))
m.Handle("/mr/reviewer", withGitlabContext(http.HandlerFunc(ReviewersHandler), c))
m.Handle("/mr/revisions", withGitlabContext(http.HandlerFunc(RevisionsHandler), c))
m.Handle("/mr/assignee", withGitlabContext(http.HandlerFunc(AssigneesHandler), c))