2016-11-23 03:38:20 +00:00
|
|
|
// Copyright © 2016 Zellyn Hunter <zellyn@gmail.com>
|
|
|
|
|
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/zellyn/diskii/lib/disk"
|
|
|
|
)
|
|
|
|
|
2016-12-01 02:42:42 +00:00
|
|
|
var missingok bool // flag for whether to consider deleting a nonexistent file okay
|
|
|
|
|
2016-11-23 03:38:20 +00:00
|
|
|
// deleteCmd represents the delete command, used to delete a file.
|
|
|
|
var deleteCmd = &cobra.Command{
|
|
|
|
Use: "delete",
|
|
|
|
Short: "delete a file",
|
|
|
|
Long: `Delete a file.
|
|
|
|
|
|
|
|
delete disk-image.dsk HELLO
|
|
|
|
`,
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
if err := runDelete(args); err != nil {
|
|
|
|
fmt.Fprintln(os.Stderr, err.Error())
|
|
|
|
os.Exit(-1)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
RootCmd.AddCommand(deleteCmd)
|
2016-12-01 02:42:42 +00:00
|
|
|
deleteCmd.Flags().BoolVarP(&missingok, "missingok", "f", false, "if true, don't consider deleting a nonexistent file an error")
|
2016-11-23 03:38:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// runDelete performs the actual delete logic.
|
|
|
|
func runDelete(args []string) error {
|
|
|
|
if len(args) != 2 {
|
|
|
|
return fmt.Errorf("delete expects a disk image filename, and a filename")
|
|
|
|
}
|
|
|
|
sd, err := disk.Open(args[0])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
op, err := disk.OperatorFor(sd)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
deleted, err := op.Delete(args[1])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-12-01 02:42:42 +00:00
|
|
|
if !deleted && !missingok {
|
2016-11-23 03:38:20 +00:00
|
|
|
return fmt.Errorf("file %q not found", args[1])
|
|
|
|
}
|
|
|
|
f, err := os.Create(args[0])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, err = sd.Write(f)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err = f.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|