91 lines
2.5 KiB
Go
91 lines
2.5 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"git.towk2.me/towk/configurator/pkg/client"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var downloadCmd = cobra.Command{
|
|
Use: "download",
|
|
Example: `
|
|
# download a file or directory (as archive)
|
|
configurator download
|
|
configurator download --host https://example.com --path test
|
|
configurator download --plugins smd,jinja2 --profile compute
|
|
curl $CONFIGURATOR_HOST/download/test?plugins=smd,jinja2
|
|
`,
|
|
Short: "Download and modify files with plugins",
|
|
PreRun: func(cmd *cobra.Command, args []string) {
|
|
setenv(&host, "CONFIGURATOR_HOST")
|
|
setenv(&path, "CONFIGURATOR_PATH")
|
|
},
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
var (
|
|
c = client.New(host)
|
|
res *http.Response
|
|
body []byte
|
|
err error
|
|
)
|
|
|
|
log.Debug().
|
|
Str("host", host).
|
|
Str("path", path).
|
|
Str("output", outputPath).
|
|
Send()
|
|
|
|
// set output path to match path if empty
|
|
if outputPath == "" {
|
|
if path != "." || path != "" {
|
|
outputPath = filepath.Base(path)
|
|
} else {
|
|
outputPath = fmt.Sprintf("%d.file", time.Now().Unix())
|
|
}
|
|
}
|
|
|
|
// make request to /download endpoint
|
|
// _, err = c.Download(outputPath, client.HTTPEnvelope{
|
|
// Path: fmt.Sprintf("/download/%s", path),
|
|
// Method: http.MethodGet,
|
|
// })
|
|
|
|
res, body, err = c.MakeRequest(client.HTTPEnvelope{
|
|
Path: fmt.Sprintf("/download/%s", path),
|
|
Method: http.MethodGet,
|
|
})
|
|
if err != nil {
|
|
log.Error().Err(err).Str("host", host).Msg("failed to make request")
|
|
os.Exit(1)
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
log.Error().Int("status", res.StatusCode).Str("host", host).Msg("response returned bad status")
|
|
os.Exit(1)
|
|
}
|
|
if outputPath != "" {
|
|
err = os.WriteFile(outputPath, body, 0o755)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("failed to write file(s) from download")
|
|
os.Exit(1)
|
|
}
|
|
} else {
|
|
fmt.Println(string(body))
|
|
}
|
|
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
downloadCmd.Flags().StringVar(&host, "host", "http://localhost:5050", "Set the configurator remote host (can be set with CONFIGURATOR_HOST)")
|
|
downloadCmd.Flags().StringVarP(&path, "path", "p", ".", "Set the path to list files (can be set with CONFIGURATOR_PATH)")
|
|
downloadCmd.Flags().StringVarP(&outputPath, "output", "o", "", "Set the output path to write files")
|
|
downloadCmd.Flags().StringVar(&profile, "profile", "", "Set the profile to use to populate data store")
|
|
downloadCmd.Flags().StringSliceVar(&plugins, "plugins", []string{}, "Set the plugins to run before downloading files")
|
|
|
|
rootCmd.AddCommand(&downloadCmd)
|
|
}
|