Skip to content

Commit

Permalink
feat: support static upload
Browse files Browse the repository at this point in the history
  • Loading branch information
fredliang44 committed Jan 10, 2021
1 parent 2924f6b commit 43fbfa4
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 41 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.idea/
.idea/
dist
45 changes: 45 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# This is an example .goreleaser.yml file with some sane defaults.
# Make sure to check the documentation at http://goreleaser.com
before:
hooks:
# You may remove this if you don't use go modules.
- go mod download
# you may remove this if you don't need go generate
- go generate ./...
builds:
- env:
- CGO_ENABLED=0
binary: let
goos:
- linux
- windows
- darwin

archives:
- replacements:
darwin: Darwin
linux: Linux
windows: Windows
386: i386
amd64: x86_64
checksum:
name_template: 'checksums.txt'
snapshot:
name_template: "{{ .Tag }}-next"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
scoop:
commit_author:
name: Fred Liang
email: fred@oasis.ac
homepage: "https://alpha.let.sh.ch/"
description: "let.sh command line interface."
release:
github:
owner: let-sh
name: cli
prerelease: auto
60 changes: 41 additions & 19 deletions cmd/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package cmd

import (
"encoding/json"
"fmt"
"github.com/let-sh/cli/log"
"github.com/let-sh/cli/requests"
"github.com/let-sh/cli/types"
Expand All @@ -36,14 +37,13 @@ var deployCmd = &cobra.Command{
Short: "Deploy your current project to let.sh",
Long: `Deploy your current project to let.sh with a single command line`,
Run: func(cmd *cobra.Command, args []string) {
log.BStart("deploying")

// check whether user is logged in
if utils.Credentials.Token == "" {
log.Warning("please login via `lets login` first")
return
}

log.BStart("deploying")
// merge config
// cli flag > config file > auto saved config > detected config & types
{
Expand All @@ -56,6 +56,12 @@ var deployCmd = &cobra.Command{
_, err := os.Stat("index.html")
if !os.IsNotExist(err) {
deploymentConfig.Type = "static"
deploymentConfig.Static = "./"
}

if len(inputStaticDir) > 0 {
deploymentConfig.Type = "static"
deploymentConfig.Static = inputStaticDir
}

// check if js by package.json
Expand Down Expand Up @@ -107,11 +113,23 @@ var deployCmd = &cobra.Command{
// TODO: respect .gitignore

}

log.S.StopFail()
fmt.Printf("name: %s\n", deploymentConfig.Name)
fmt.Printf("type: %s\n", deploymentConfig.Type)
time.Sleep(time.Second * 2)

// if contains static, upload static files to oss
if utils.ItemExists([]string{"static"}, deploymentConfig.Type) {
if err := oss.UploadDirToStaticSource(deploymentConfig.Static, deploymentConfig.Name, deploymentConfig.Name+"-"+hashID); err != nil {
log.Error(err)
return
}
}

// if contains dynamic, upload dynamic files to oss
// then trigger deployment
{
if utils.ItemExists([]string{"gin", "express"}, deploymentConfig.Type) {

// create temp dir
dir := os.TempDir()
Expand All @@ -132,30 +150,32 @@ var deployCmd = &cobra.Command{
}

oss.UploadFileToCodeSource(dir+"/"+deploymentConfig.Name+"-"+hashID+".tar.gz", deploymentConfig.Name+"-"+hashID+".tar.gz", deploymentConfig.Name)
}

configBytes, _ := json.Marshal(deploymentConfig)
deployment, err := requests.Deploy(deploymentConfig.Type, deploymentConfig.Name, string(configBytes), inputCN)
if err != nil {
log.Error(err)
return
}

configBytes, _ := json.Marshal(deploymentConfig)
deployment, err := requests.Deploy(deploymentConfig.Type, deploymentConfig.Name, string(configBytes), inputCN)
log.BStart("deploying")
// awaiting deployment result
for {
currentStatus, err := requests.GetDeploymentStatus(deployment.ID)
if err != nil {
log.Error(err)
return
}
// awaiting deployment result

for {
currentStatus, err := requests.GetDeploymentStatus(deployment.ID)
if err != nil {
log.Error(err)
}
log.BUpdate(" NetworkStage: " + currentStatus.NetworkStage + ", PackerStage: " + currentStatus.PackerStage + ", Status: " + currentStatus.Status)

log.BUpdate(" NetworkStage: " + currentStatus.NetworkStage + ", PackerStage: " + currentStatus.PackerStage + ", Status: " + currentStatus.Status)

time.Sleep(time.Second * 2)
if currentStatus.Done {
break
}
if currentStatus.Done {
break
}

log.S.StopMessage(" deploy succeed\nyou could visit https://" + currentStatus.TargetFQDN)
}
log.Success("deploy succeed")

log.BStop()
return
},
Expand All @@ -165,6 +185,7 @@ var deploymentConfig types.LetConfig
var inputProjectName string
var inputProjectType string
var inputCN bool
var inputStaticDir string

func init() {
rootCmd.AddCommand(deployCmd)
Expand All @@ -173,5 +194,6 @@ func init() {
// is called directly, e.g.:
deployCmd.Flags().StringVarP(&inputProjectName, "project", "p", "", "current project name")
deployCmd.Flags().StringVarP(&inputProjectType, "type", "t", "", "current project type, e.g. react")
deployCmd.Flags().StringVarP(&inputStaticDir, "static", "", "", "static dir name (if deploy type is static)")
deployCmd.Flags().BoolVarP(&inputCN, "cn", "", true, "deploy in mainland of china")
}
18 changes: 8 additions & 10 deletions log/banner.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import (
var S *yacspin.Spinner

func init() {

//s = spinner.New(spinner.CharSets[14], 50*time.Millisecond)
}

func BStart(message string) {
cfg := yacspin.Config{
Frequency: 50 * time.Millisecond,
CharSet: yacspin.CharSets[14],
Expand All @@ -18,23 +23,16 @@ func init() {
StopColors: []string{"fgGreen"},
}
S, _ = yacspin.New(cfg)

//s = spinner.New(spinner.CharSets[14], 50*time.Millisecond)
}

func BStart(suffix string) {
S.Suffix(" " + suffix)
//s.Suffix = " " + suffix
S.Message(" " + message)
S.Start()
}

func BUpdate(suffix string) {
S.Suffix(suffix)
func BUpdate(message string) {
S.Message(message)
}

func BStop() {
S.Stop()

}

func BPause() {
Expand Down
9 changes: 9 additions & 0 deletions log/color.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package log

import "github.com/fatih/color"

var Green = color.New(color.FgGreen).SprintFunc()

var Red = color.New(color.FgRed).SprintFunc()

var Yellow = color.New(color.FgHiYellow).SprintFunc()
6 changes: 6 additions & 0 deletions requests/graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ query($type: String!, $name: String!) {

func Deploy(projectType, projectName, config string, cn bool) (deployment struct {
ID string `json:"id"`
TargetFQDN string `json:"targetFQDN"`
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
Expand All @@ -91,6 +92,7 @@ func Deploy(projectType, projectName, config string, cn bool) (deployment struct
mutation($type: String!, $name: String!, $config: String, $cn: Boolean) {
deploy(input:{type:$type, projectName:$name, config:$config, cn:$cn}) {
id
targetFQDN
networkStage
packerStage
status
Expand All @@ -108,6 +110,7 @@ mutation($type: String!, $name: String!, $config: String, $cn: Boolean) {
var respData struct {
Deploy struct {
ID string `json:"id"`
TargetFQDN string `json:"targetFQDN"`
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
Expand All @@ -125,6 +128,7 @@ mutation($type: String!, $name: String!, $config: String, $cn: Boolean) {
}

func GetDeploymentStatus(id string) (deployment struct {
TargetFQDN string `json:"targetFQDN"`
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
Expand All @@ -133,6 +137,7 @@ func GetDeploymentStatus(id string) (deployment struct {
req := graphql.NewRequest(`
query($id: UUID!) {
deployment(id:$id) {
targetFQDN
networkStage
packerStage
status
Expand All @@ -146,6 +151,7 @@ query($id: UUID!) {
// run it and capture the response
var respData struct {
Deployment struct {
TargetFQDN string `json:"targetFQDN"`
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
Expand Down
19 changes: 19 additions & 0 deletions utils/functions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package utils

import "reflect"

func ItemExists(slice interface{}, item interface{}) bool {
s := reflect.ValueOf(slice)

if s.Kind() != reflect.Slice {
panic("Invalid data-type")
}

for i := 0; i < s.Len(); i++ {
if s.Index(i).Interface() == item {
return true
}
}

return false
}
19 changes: 8 additions & 11 deletions utils/oss/oss.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import (
var bar *mpb.Bar

func UploadFileToCodeSource(filepath, filename, projectName string) {
log.BPause()

// create and start new bar
fi, _ := os.Stat(filepath)

Expand All @@ -39,6 +37,7 @@ func UploadFileToCodeSource(filepath, filename, projectName string) {
decor.Name(" ] "),
decor.EwmaSpeed(decor.UnitKB, "% .2f", 1024),
),
mpb.BarRemoveOnComplete(),
)

stsToken, err := requests.GetStsToken("buildBundle", projectName)
Expand Down Expand Up @@ -73,10 +72,7 @@ func UploadFileToCodeSource(filepath, filename, projectName string) {
fmt.Println("Error:", err)
os.Exit(-1)
}
//bar.Abort(true)

log.S.Suffix(" deploying ")
log.BUnpause()
bar.Completed()
}

func UploadDirToStaticSource(dirPath, projectName, bundleID string) error {
Expand All @@ -89,6 +85,7 @@ func UploadDirToStaticSource(dirPath, projectName, bundleID string) error {
// 创建OSSClient实例
endpoint := strings.Join(strings.Split(stsToken.Host, ".")[1:], ".")
client, err := oss.New(endpoint, stsToken.AccessKeyID, stsToken.AccessKeySecret, oss.SecurityToken(stsToken.SecurityToken))

if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
Expand All @@ -103,7 +100,6 @@ func UploadDirToStaticSource(dirPath, projectName, bundleID string) error {
}

// Read directory and close.

dir, err := os.Open(dirPath)
if err != nil {
return err
Expand Down Expand Up @@ -148,7 +144,9 @@ func UploadDirToStaticSource(dirPath, projectName, bundleID string) error {
}
return
}
err = bucket.PutObjectFromFile(projectName+"-"+bundleID, filepath.Join(dirPath, name))
objKey := bundleID + "/" + name
filePath := filepath.Join(dirPath, name)
err = bucket.PutObjectFromFile(objKey, filePath)

if err != nil {
select {
Expand All @@ -165,19 +163,18 @@ func UploadDirToStaticSource(dirPath, projectName, bundleID string) error {
}

// Collect results from workers

for i := 0; i < len(names); i++ {
select {
case res := <-resChan:
fmt.Println(res)
// collect result
_ = res
case err := <-errChan:
return err
}
}
log.S.Suffix(" deploying ")
log.BUnpause()
return nil

}

type OssProgressListener struct {
Expand Down

0 comments on commit 43fbfa4

Please sign in to comment.