huffman-archiver/cmd/encode.go

47 lines
874 B
Go
Raw Normal View History

2022-01-31 14:54:53 +05:00
package cmd
import (
"errors"
"github.com/spf13/cobra"
"huffman/internal/huffman"
"os"
)
var encodeCmd = &cobra.Command{
Use: "encode <archive name> <file name>",
Short: "Encodes the file",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return errors.New("filename is required")
}
if _, err := os.Stat(args[0]); err == nil {
return errors.New("archive file exists")
} else if !os.IsNotExist(err) {
panic(err)
}
if _, err := os.Stat(args[1]); os.IsNotExist(err) {
return errors.New("file is not exists")
} else if err != nil {
panic(err)
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
fromFile, err := os.Open(args[1])
if err != nil {
panic(err)
}
toFile, err := os.Create(args[0])
huffman.Encode(fromFile, toFile)
},
}
func init() {
rootCmd.AddCommand(encodeCmd)
}