file-store/cmd/scmd.go

98 lines
2.3 KiB
Go

package cmd
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"github.com/google/uuid"
"github.com/spf13/cobra"
"git.keganmyers.com/terribleplan/file-store/pkg/storeserver"
)
var (
scmd_Chunks []int32
scmd_FileId string
)
func init() {
root.AddCommand(scmd)
scmd_put.Flags().Int32SliceVar(&scmd_Chunks, "chunks", []int32{}, "Which chunk files to put onto the remote server (default: none)")
scmd_put.Flags().StringVar(&scmd_FileId, "file-id", "", "The File ID to use for the stored file (default: detected from input file)")
scmd.AddCommand(scmd_put)
scmd.AddCommand(scmd_listFiles)
}
var scmd = &cobra.Command{
Use: "scmd",
Short: "Interact with store servers",
}
var scmd_put = &cobra.Command{
Use: "put [encoded-folder] [ssrv-address]",
Short: "Put chunk files onto remote storage",
Long: `Put chunk files onto remote storage.
The File ID (from either the basename of encoded-folder or --file-id) must be a UUID, which is how the file will be identified on remote storage.`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
// todo: sanity check of encoded-folder
encodedFolder, err := filepath.Abs(args[0])
if err != nil {
panic(err)
}
if scmd_FileId == "" {
scmd_FileId = filepath.Base(encodedFolder)
}
if _, err := uuid.Parse(scmd_FileId); err != nil {
panic(err)
}
file, err := os.Open(path.Join(encodedFolder, "meta.json"))
if err != nil {
panic(err)
}
data, err := io.ReadAll(file)
if err != nil {
panic(err)
}
file.Close()
client, err := storeserver.NewClient(args[1])
if err != nil {
panic(err)
}
if err := client.WriteFile(scmd_FileId, data); err != nil {
panic(err)
}
for _, chunkNumber := range scmd_Chunks {
file, err := os.Open(path.Join(encodedFolder, fmt.Sprintf("shard.%04d", chunkNumber)))
if err != nil {
panic(err)
}
client.WriteChunk(scmd_FileId, uint16(chunkNumber), file)
}
},
}
var scmd_listFiles = &cobra.Command{
Use: "list-files [ssrv-address]",
Short: "List files in remote storage",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
client, err := storeserver.NewClient(args[0])
if err != nil {
panic(err)
}
if err := client.ListFiles(func(fileId string) error {
fmt.Printf("%s\n", fileId)
return nil
}); err != nil {
panic(err)
}
},
}