-
Notifications
You must be signed in to change notification settings - Fork 0
chore: uploads command
#80
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
Draft
notnmeyer
wants to merge
1
commit into
main
Choose a base branch
from
chore/loo-5084/image-uploads
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+262
−3
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/http" | ||
| "os" | ||
|
|
||
| "github.com/loops-so/cli/internal/config" | ||
| "github.com/loops-so/loops-go" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| func runUploadsCreate(cfg *config.Config, path, emailMessageID, contentType string) (*loops.CompleteUploadResponse, error) { | ||
| info, err := os.Stat(path) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("open %q: %w", path, err) | ||
| } | ||
| if info.IsDir() { | ||
| return nil, fmt.Errorf("%q is a directory", path) | ||
| } | ||
|
|
||
| f, err := os.Open(path) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("open %q: %w", path, err) | ||
| } | ||
| defer f.Close() | ||
|
|
||
| if contentType == "" { | ||
| var sniff [512]byte | ||
| n, err := f.Read(sniff[:]) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("read %q: %w", path, err) | ||
| } | ||
| contentType = http.DetectContentType(sniff[:n]) | ||
| if _, err := f.Seek(0, 0); err != nil { | ||
| return nil, fmt.Errorf("seek %q: %w", path, err) | ||
| } | ||
| } | ||
|
|
||
| return newAPIClient(cfg).Upload(loops.UploadRequest{ | ||
| EmailMessageID: emailMessageID, | ||
| ContentType: contentType, | ||
| ContentLength: info.Size(), | ||
| Body: f, | ||
| }) | ||
| } | ||
|
|
||
| var uploadsCmd = &cobra.Command{ | ||
| Use: "uploads", | ||
| Short: "Manage uploaded email assets", | ||
| } | ||
|
|
||
| var uploadsCreateCmd = &cobra.Command{ | ||
| Use: "create <path>", | ||
| Short: "Upload a file as an email asset", | ||
| Args: cobra.ExactArgs(1), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| emailMessageID, _ := cmd.Flags().GetString("email-message-id") | ||
| contentType, _ := cmd.Flags().GetString("content-type") | ||
|
|
||
| cfg, err := loadConfig() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| result, err := runUploadsCreate(cfg, args[0], emailMessageID, contentType) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if isJSONOutput() { | ||
| return printJSON(cmd.OutOrStdout(), result) | ||
| } | ||
|
|
||
| t := newStyledTable(cmd.OutOrStdout(), "FIELD", "VALUE") | ||
| t.Row("emailAssetId", result.EmailAssetID) | ||
| t.Row("finalUrl", result.FinalURL) | ||
| return t.Render() | ||
| }, | ||
| } | ||
|
|
||
| func init() { | ||
| uploadsCreateCmd.Flags().StringP("email-message-id", "m", "", "Email message this asset belongs to (required)") | ||
| uploadsCreateCmd.Flags().String("content-type", "", "MIME type to use for the upload (default: sniffed from file contents)") | ||
| _ = uploadsCreateCmd.MarkFlagRequired("email-message-id") | ||
|
|
||
| uploadsCmd.AddCommand(uploadsCreateCmd) | ||
| rootCmd.AddCommand(uploadsCmd) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/zalando/go-keyring" | ||
| ) | ||
|
|
||
| // pngBytes is a minimal valid PNG header — enough for http.DetectContentType | ||
| // to return "image/png". | ||
| var pngBytes = []byte{ | ||
| 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, | ||
| 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, | ||
| } | ||
|
|
||
| type uploadServer struct { | ||
| srv *httptest.Server | ||
| createReq map[string]any | ||
| putBody []byte | ||
| putContentType string | ||
| putContentLen int64 | ||
| completeCalled bool | ||
| completeAssetID string | ||
| } | ||
|
|
||
| func serveUpload(t *testing.T) *uploadServer { | ||
| t.Helper() | ||
| keyring.MockInit() | ||
| t.Setenv("LOOPS_CONFIG_DIR", t.TempDir()) | ||
|
|
||
| state := &uploadServer{} | ||
| state.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| switch { | ||
| case r.Method == http.MethodPost && r.URL.Path == "/uploads": | ||
| if err := json.NewDecoder(r.Body).Decode(&state.createReq); err != nil { | ||
| t.Errorf("decode create body: %v", err) | ||
| } | ||
| fmt.Fprintf(w, `{"emailAssetId":"asset_123","presignedUrl":"%s/upload-target","expiresAt":"2026-05-21T12:00:00Z"}`, state.srv.URL) | ||
|
|
||
| case r.Method == http.MethodPut && r.URL.Path == "/upload-target": | ||
| state.putContentType = r.Header.Get("Content-Type") | ||
| state.putContentLen = r.ContentLength | ||
| state.putBody, _ = io.ReadAll(r.Body) | ||
| w.WriteHeader(http.StatusOK) | ||
|
|
||
| case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/uploads/") && strings.HasSuffix(r.URL.Path, "/complete"): | ||
| state.completeCalled = true | ||
| state.completeAssetID = strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/uploads/"), "/complete") | ||
| w.Write([]byte(`{"emailAssetId":"asset_123","finalUrl":"https://cdn.loops.so/asset_123.png"}`)) | ||
|
|
||
| default: | ||
| t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) | ||
| w.WriteHeader(http.StatusNotFound) | ||
| } | ||
| })) | ||
| t.Cleanup(state.srv.Close) | ||
| t.Setenv("LOOPS_API_KEY", "test-key") | ||
| t.Setenv("LOOPS_ENDPOINT_URL", state.srv.URL) | ||
| return state | ||
| } | ||
|
|
||
| func writeTempPNG(t *testing.T) string { | ||
| t.Helper() | ||
| dir := t.TempDir() | ||
| path := filepath.Join(dir, "image.png") | ||
| if err := os.WriteFile(path, pngBytes, 0o600); err != nil { | ||
| t.Fatalf("write temp file: %v", err) | ||
| } | ||
| return path | ||
| } | ||
|
|
||
| func TestRunUploadsCreate(t *testing.T) { | ||
| t.Run("sniffs content-type when blank and uploads file body", func(t *testing.T) { | ||
| state := serveUpload(t) | ||
| path := writeTempPNG(t) | ||
|
|
||
| result, err := runUploadsCreate(cfg(t), path, "em_abc123", "") | ||
| if err != nil { | ||
| t.Fatalf("unexpected error: %v", err) | ||
| } | ||
|
|
||
| if result.EmailAssetID != "asset_123" { | ||
| t.Errorf("EmailAssetID = %q, want asset_123", result.EmailAssetID) | ||
| } | ||
| if result.FinalURL != "https://cdn.loops.so/asset_123.png" { | ||
| t.Errorf("FinalURL = %q", result.FinalURL) | ||
| } | ||
|
|
||
| if state.createReq["emailMessageId"] != "em_abc123" { | ||
| t.Errorf("create emailMessageId = %v, want em_abc123", state.createReq["emailMessageId"]) | ||
| } | ||
| if state.createReq["contentType"] != "image/png" { | ||
| t.Errorf("create contentType = %v, want image/png (sniffed)", state.createReq["contentType"]) | ||
| } | ||
| if got, want := int64(state.createReq["contentLength"].(float64)), int64(len(pngBytes)); got != want { | ||
| t.Errorf("create contentLength = %d, want %d", got, want) | ||
| } | ||
|
|
||
| if state.putContentType != "image/png" { | ||
| t.Errorf("PUT Content-Type = %q, want image/png", state.putContentType) | ||
| } | ||
| if state.putContentLen != int64(len(pngBytes)) { | ||
| t.Errorf("PUT Content-Length = %d, want %d", state.putContentLen, len(pngBytes)) | ||
| } | ||
| if string(state.putBody) != string(pngBytes) { | ||
| t.Errorf("PUT body did not match source file") | ||
| } | ||
|
|
||
| if !state.completeCalled { | ||
| t.Error("complete endpoint was not called") | ||
| } | ||
| if state.completeAssetID != "asset_123" { | ||
| t.Errorf("complete called for assetID %q, want asset_123", state.completeAssetID) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("explicit --content-type overrides sniffing", func(t *testing.T) { | ||
| state := serveUpload(t) | ||
| path := writeTempPNG(t) | ||
|
|
||
| if _, err := runUploadsCreate(cfg(t), path, "em_abc123", "application/octet-stream"); err != nil { | ||
| t.Fatalf("unexpected error: %v", err) | ||
| } | ||
|
|
||
| if state.createReq["contentType"] != "application/octet-stream" { | ||
| t.Errorf("create contentType = %v, want application/octet-stream", state.createReq["contentType"]) | ||
| } | ||
| if state.putContentType != "application/octet-stream" { | ||
| t.Errorf("PUT Content-Type = %q, want application/octet-stream", state.putContentType) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("missing file returns error", func(t *testing.T) { | ||
| serveUpload(t) | ||
| if _, err := runUploadsCreate(cfg(t), "/does/not/exist.png", "em_abc123", ""); err == nil { | ||
| t.Fatal("expected error for missing file, got nil") | ||
| } | ||
| }) | ||
|
|
||
| t.Run("directory path returns error", func(t *testing.T) { | ||
| serveUpload(t) | ||
| if _, err := runUploadsCreate(cfg(t), t.TempDir(), "em_abc123", ""); err == nil { | ||
| t.Fatal("expected error for directory path, got nil") | ||
| } | ||
| }) | ||
|
|
||
| t.Run("create failure surfaces error", func(t *testing.T) { | ||
| keyring.MockInit() | ||
| t.Setenv("LOOPS_CONFIG_DIR", t.TempDir()) | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusBadRequest) | ||
| w.Write([]byte(`{"success":false,"message":"missing emailMessageId"}`)) | ||
| })) | ||
| t.Cleanup(srv.Close) | ||
| t.Setenv("LOOPS_API_KEY", "test-key") | ||
| t.Setenv("LOOPS_ENDPOINT_URL", srv.URL) | ||
|
|
||
| if _, err := runUploadsCreate(cfg(t), writeTempPNG(t), "", ""); err == nil { | ||
| t.Fatal("expected error, got nil") | ||
| } | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TODO: update this with the final release