Skip to content

Commit

Permalink
feat: github client artifact (#16)
Browse files Browse the repository at this point in the history
- Fix supabase form content
  • Loading branch information
miguelramos authored Jun 28, 2022
1 parent 267140c commit 59d98a9
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 18 deletions.
8 changes: 5 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@
"program": "${workspaceFolder}",
"args": [
"--root",
"./ui-libs",
"/Users/miguelramos/Public/Projects/websublime-workspace/sublime-ui",
"action",
"--kind",
"branch",
"--bucket",
"assets",
"--url",
"https://debvasmsyxrewpmqckdv.supabase.co",
"websublime/flare",
"--key",
""
"",
"--client",
"github"
]
},
{
Expand Down
27 changes: 22 additions & 5 deletions cmd/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func init() {
rootCmd.AddCommand(actionCmd)

actionCmd.Flags().StringVar(&cmd.Kind, "kind", "branch", "Kind of action (branch or tag)")
actionCmd.Flags().StringVar(&cmd.Client, "client", "supabase", "Client to use to upload to storage")
actionCmd.Flags().StringVar(&cmd.Client, "client", "supabase", "Client to use to upload to storage (supabase, github)")
actionCmd.Flags().StringVar(&cmd.Environment, "env", "develop", "Environment")

actionCmd.Flags().StringVar(&cmd.Bucket, "bucket", "", "Bucket storage name [REQUIRED]")
Expand Down Expand Up @@ -125,6 +125,7 @@ func (ctx *ActionCommand) ReleaseArtifact(cmd *cobra.Command) {
color.Info.Println("🥼 Commits counted: ", counter)

supabase := clients.NewSupabase(ctx.BaseUrl, ctx.Key, ctx.Environment)
github := clients.NewGithub(fmt.Sprintf("https://api.github.com/repos/%s/contents", ctx.BaseUrl), ctx.Key, ctx.Environment)

if ctx.Kind == "branch" {
pkgs = getSublimeBranchPackages(counter)
Expand Down Expand Up @@ -172,12 +173,21 @@ func (ctx *ActionCommand) ReleaseArtifact(cmd *cobra.Command) {
color.Info.Println("🥼 Founded", len(fileList), "files to be upload to assets bucket")

for idx := range fileList {
supabase.Upload(ctx.Bucket, fileList[idx], destinationFolder)
if ctx.Client == "supabase" {
supabase.Upload(ctx.Bucket, fileList[idx], destinationFolder)
} else if ctx.Client == "github" {
github.Upload("assets", fileList[idx], destinationFolder)
}
}

color.Info.Println("🥼 Files uploaded to bucket. Starting manifest creation")

manifestBaseLink := fmt.Sprintf("%s/storage/v1/object/public/%s/%s", ctx.BaseUrl, ctx.Bucket, destinationFolder)
var manifestBaseLink = ""
if ctx.Client == "supabase" {
manifestBaseLink = fmt.Sprintf("%s/storage/v1/object/public/%s/%s", ctx.BaseUrl, ctx.Bucket, destinationFolder)
} else if ctx.Client == "github" {
manifestBaseLink = fmt.Sprintf("https://cdn.jsdelivr.net/gh/%s/%s/%s", ctx.BaseUrl, "assets", destinationFolder)
}

manifestJson, _ := FileTemplates.ReadFile("templates/manifest.json")
manifestFile := core.CreateManifest(manifestJson, core.Manifest{
Expand All @@ -200,8 +210,15 @@ func (ctx *ActionCommand) ReleaseArtifact(cmd *cobra.Command) {
manifestDestination = pkgJson.Name
}

supabase.Upload("manifests", manifestFile.Name(), manifestDestination)
manifestLink := fmt.Sprintf("%s/storage/v1/object/public/%s/%s/%s", ctx.BaseUrl, "manifests", manifestDestination, filepath.Base(manifestFile.Name()))
var manifestLink = ""
if ctx.Client == "supabase" {
supabase.Upload("manifests", manifestFile.Name(), manifestDestination)
manifestLink = fmt.Sprintf("%s/storage/v1/object/public/%s/%s/%s", ctx.BaseUrl, "manifests", manifestDestination, filepath.Base(manifestFile.Name()))
} else if ctx.Client == "github" {
github.Upload("manifests", manifestFile.Name(), manifestDestination)
manifestLink = fmt.Sprintf("https://cdn.jsdelivr.net/gh/%s/%s/%s/%s", ctx.BaseUrl, "manifests", manifestDestination, filepath.Base(manifestFile.Name()))
}

os.Remove(manifestFile.Name())

color.Info.Println("🥼 Manifest uploaded to:", manifestLink)
Expand Down
134 changes: 134 additions & 0 deletions core/clients/github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
Copyright © 2022 Websublime.dev organization@websublime.dev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package clients

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"time"
)

type Github struct {
BaseURL string
ApiKey string
Environment string
HTTPClient *http.Client
}

type Payload struct {
Message string `json:"message"`
Content string `json:"content"`
Sha string `json:"sha,omitempty"`
}

type Content struct {
Sha string `json:"sha"`
}

func NewGithub(baseURL string, supabaseKey string, env string) *Github {
return &Github{
BaseURL: baseURL,
ApiKey: supabaseKey,
Environment: env,
HTTPClient: &http.Client{
Timeout: time.Minute,
},
}
}

func (ctx *Github) Upload(bucket string, filePath string, destination string) string {
file, err := os.OpenFile(filePath, os.O_RDWR, 0755)
if err != nil {
panic(fmt.Errorf("os.Open: %v", err))
}
file.Close()

data, err := ioutil.ReadFile(filePath)
if err != nil {
panic(fmt.Errorf("os.Open: %v", err))
}

base64data := base64.StdEncoding.EncodeToString(data)

currentTime := time.Now()
uri := fmt.Sprintf("%s/%s/%s/%s", ctx.BaseURL, bucket, destination, filepath.Base(file.Name()))
sha := ctx.GetContent(uri)

payload := Payload{
Message: fmt.Sprintf("Upload artifact %s at %s", filepath.Base(file.Name()), currentTime.Format("2006.01.02-15:04:05")),
Content: base64data,
}

if sha != "" {
payload.Sha = sha
}

json, _ := json.Marshal(payload)

req, _ := http.NewRequest("PUT", uri, bytes.NewBuffer(json))
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ctx.ApiKey))
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json; charset=UTF-8")

response, err := ctx.HTTPClient.Do(req)
if err != nil {
panic(fmt.Errorf("Couldn't upload file: %v", err))
}

defer response.Body.Close()

status := fmt.Sprintf("Upload artifact %s with status: %s", filepath.Base(file.Name()), response.Status)
fmt.Println(status)

return status
}

func (ctx *Github) GetContent(contentUri string) string {
content := Content{
Sha: "",
}

req, _ := http.NewRequest("GET", contentUri, nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ctx.ApiKey))
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json; charset=UTF-8")

response, err := ctx.HTTPClient.Do(req)
if err != nil {
panic(fmt.Errorf("Couldn't upload file: %v", err))
}

defer response.Body.Close()

body, err := ioutil.ReadAll(response.Body)
if err == nil {
json.Unmarshal(body, &content)
}

return content.Sha
}
32 changes: 22 additions & 10 deletions core/clients/supabase.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ package clients
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"os"
"path/filepath"
"strings"
Expand All @@ -47,6 +49,12 @@ type Supabase struct {
HTTPClient *http.Client
}

var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")

func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}

func NewSupabase(baseURL string, supabaseKey string, env string) *Supabase {
return &Supabase{
BaseURL: baseURL,
Expand All @@ -65,11 +73,6 @@ func (ctx *Supabase) Upload(bucket string, filePath string, destination string)
}
defer file.Close()

fileContents, err := ioutil.ReadFile(filePath)
if err != nil {
panic(fmt.Errorf("Couldn't read file: %v", err))
}

fileExtension := filepath.Ext(filePath)
mime := utils.GetMimeType(strings.TrimPrefix(fileExtension, "."))

Expand All @@ -80,23 +83,32 @@ func (ctx *Supabase) Upload(bucket string, filePath string, destination string)

payload := new(bytes.Buffer)
writer := multipart.NewWriter(payload)
defer writer.Close()

part, err := writer.CreateFormFile("file", filepath.Base(file.Name()))
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="file"; filename="%s"`,
escapeQuotes(filepath.Base(file.Name()))))
h.Set("Content-Type", mime)

formfile, err := writer.CreatePart(h)
if err != nil {
panic(fmt.Errorf("Couldn't create form for file: %v", err))
}

part.Write(fileContents)
_, err = io.Copy(formfile, file)
if err != nil {
panic(fmt.Errorf("Couldn't copy file to form: %v", err))
}

writer.Close()

uri := fmt.Sprintf("%s/storage/v1/object/%s/%s/%s", ctx.BaseURL, bucket, destination, filepath.Base(file.Name()))

req, _ := http.NewRequest("POST", uri, payload)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", ctx.ApiKey))
req.Header.Add("apikey", ctx.ApiKey)
req.Header.Add("x-upsert", "true")
//req.Header.Add("x-cache-control", "3600")
req.Header.Add("Content-Type", mime)
req.Header.Add("Content-Type", writer.FormDataContentType())
req.Header.Add("Content-Length", fmt.Sprintf("%d", stat.Size()))

// https://gist.github.com/mattetti/5914158/f4d1393d83ebedc682a3c8e7bdc6b49670083b84
Expand Down

0 comments on commit 59d98a9

Please sign in to comment.