cli/cmd/upload.go

64 lines
1.5 KiB
Go

package cmd
import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
"io/ioutil"
"math"
"os"
"paste.ee/go"
"path"
)
// uploadCommandHandler handles the root command from Cobra
// The program takes two inputs, an arg list (files), or stdin.
// If args is empty, stdin will be used.
func uploadCommandHandler(cmd *cobra.Command, args []string) {
client := pastee.New(viper.GetString("apiKey"))
paste := &pastee.Paste{}
if len(args) > 0 && args[0] != "-" {
paste.Sections = make([]*pastee.Section, int(math.Min(float64(len(args)), 10)))
// File list
for i, filePath := range args {
if i >= 10 {
break
}
bytes, err := ioutil.ReadFile(filePath)
if err != nil {
cmd.PrintErrln("Unable to read file:", err)
os.Exit(1)
}
paste.Sections[i] = &pastee.Section{
Name: path.Base(filePath),
Contents: string(bytes),
}
}
} else {
// Stdin
stdinContents, err := ioutil.ReadAll(os.Stdin)
if err != nil {
cmd.PrintErrln("Error reading from stdin:", err)
os.Exit(1)
}
paste.Sections = []*pastee.Section{
{Contents: string(stdinContents)},
}
}
res, err := client.Submit(paste)
if err != nil {
cmd.PrintErrln("Unable to upload paste:", err)
os.Exit(1)
}
cmd.Println(res.Link)
}