2025-10-31 20:32:46 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"net/http"
|
|
|
|
|
"os"
|
2025-11-02 13:03:48 +00:00
|
|
|
"strings"
|
2025-10-31 20:47:11 +00:00
|
|
|
|
2025-11-02 13:27:04 +00:00
|
|
|
"github.com/Snider/Borg/pkg/compress"
|
2025-11-01 19:03:04 +00:00
|
|
|
"github.com/Snider/Borg/pkg/datanode"
|
2025-11-02 13:03:48 +00:00
|
|
|
"github.com/Snider/Borg/pkg/tarfs"
|
2025-10-31 20:32:46 +00:00
|
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// serveCmd represents the serve command
|
2025-11-14 10:36:35 +00:00
|
|
|
var serveCmd = NewServeCmd()
|
2025-10-31 20:32:46 +00:00
|
|
|
|
2025-11-14 10:36:35 +00:00
|
|
|
func NewServeCmd() *cobra.Command {
|
|
|
|
|
serveCmd := &cobra.Command{
|
|
|
|
|
Use: "serve [file]",
|
|
|
|
|
Short: "Serve a packaged PWA file",
|
|
|
|
|
Long: `Serves the contents of a packaged PWA file using a static file server.`,
|
|
|
|
|
Args: cobra.ExactArgs(1),
|
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
|
dataFile := args[0]
|
|
|
|
|
port, _ := cmd.Flags().GetString("port")
|
2025-10-31 20:32:46 +00:00
|
|
|
|
2025-11-14 10:36:35 +00:00
|
|
|
rawData, err := os.ReadFile(dataFile)
|
2025-11-02 13:03:48 +00:00
|
|
|
if err != nil {
|
2025-11-14 10:36:35 +00:00
|
|
|
return fmt.Errorf("Error reading data file: %w", err)
|
2025-11-02 13:03:48 +00:00
|
|
|
}
|
2025-11-14 10:36:35 +00:00
|
|
|
|
|
|
|
|
data, err := compress.Decompress(rawData)
|
2025-11-02 13:03:48 +00:00
|
|
|
if err != nil {
|
2025-11-14 10:36:35 +00:00
|
|
|
return fmt.Errorf("Error decompressing data: %w", err)
|
2025-11-02 13:03:48 +00:00
|
|
|
}
|
2025-10-31 20:32:46 +00:00
|
|
|
|
2025-11-14 10:36:35 +00:00
|
|
|
var fs http.FileSystem
|
|
|
|
|
if strings.HasSuffix(dataFile, ".matrix") {
|
|
|
|
|
fs, err = tarfs.New(data)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("Error creating TarFS from matrix tarball: %w", err)
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
dn, err := datanode.FromTar(data)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("Error creating DataNode from tarball: %w", err)
|
|
|
|
|
}
|
|
|
|
|
fs = http.FS(dn)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
http.Handle("/", http.FileServer(fs))
|
|
|
|
|
|
|
|
|
|
fmt.Printf("Serving PWA on http://localhost:%s\n", port)
|
|
|
|
|
err = http.ListenAndServe(":"+port, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("Error starting server: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
serveCmd.PersistentFlags().String("port", "8080", "Port to serve the PWA on")
|
|
|
|
|
return serveCmd
|
|
|
|
|
}
|
2025-10-31 20:32:46 +00:00
|
|
|
|
2025-11-14 10:36:35 +00:00
|
|
|
func GetServeCmd() *cobra.Command {
|
|
|
|
|
return serveCmd
|
2025-10-31 20:32:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func init() {
|
2025-11-14 10:36:35 +00:00
|
|
|
RootCmd.AddCommand(GetServeCmd())
|
2025-10-31 20:32:46 +00:00
|
|
|
}
|