|
| 1 | +package file |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "strconv" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/spf13/cobra" |
| 13 | + |
| 14 | + "github.com/a68366/pfix-cli/internal/cmdutil" |
| 15 | + "github.com/a68366/pfix-cli/internal/planfix" |
| 16 | +) |
| 17 | + |
| 18 | +type downloadOptions struct { |
| 19 | + id int |
| 20 | + output string // -o: "" auto-name, "-" stdout, else path/dir |
| 21 | + force bool |
| 22 | + quiet bool |
| 23 | + json bool |
| 24 | + client func() (*planfix.Client, error) |
| 25 | + out io.Writer |
| 26 | + errOut io.Writer |
| 27 | +} |
| 28 | + |
| 29 | +func newDownloadCmd(g *cmdutil.GlobalOpts) *cobra.Command { |
| 30 | + o := &downloadOptions{} |
| 31 | + cmd := &cobra.Command{ |
| 32 | + Use: "download <id>", |
| 33 | + Short: "Download a file's bytes", |
| 34 | + Long: "Download a file's bytes.\n\n" + |
| 35 | + "By default writes ./<file-name> (a metadata lookup resolves the name). -o <path>\n" + |
| 36 | + "writes to that path; -o <dir>/ writes <dir>/<file-name>; -o - streams to stdout.\n" + |
| 37 | + "Refuses to overwrite an existing file unless --force.", |
| 38 | + Args: cobra.ExactArgs(1), |
| 39 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 40 | + id, err := cmdutil.ValidateID(args[0]) |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + o.id = id |
| 45 | + o.quiet, o.json = g.Quiet, g.JSON |
| 46 | + o.client = g.ClientFunc() |
| 47 | + o.out = cmd.OutOrStdout() |
| 48 | + o.errOut = cmd.ErrOrStderr() |
| 49 | + return runDownload(cmd.Context(), o) |
| 50 | + }, |
| 51 | + } |
| 52 | + cmd.Flags().StringVarP(&o.output, "output", "o", "", "Output path, a directory, or - for stdout") |
| 53 | + cmd.Flags().BoolVar(&o.force, "force", false, "Overwrite an existing file") |
| 54 | + return cmd |
| 55 | +} |
| 56 | + |
| 57 | +func runDownload(ctx context.Context, o *downloadOptions) error { |
| 58 | + // --jq implies --json (GlobalOpts.PreRun), so o.json covers both. |
| 59 | + if o.json { |
| 60 | + return fmt.Errorf("file download writes raw bytes; --json/--jq are not supported (use -o -)") |
| 61 | + } |
| 62 | + client, err := o.client() |
| 63 | + if err != nil { |
| 64 | + return err |
| 65 | + } |
| 66 | + idPath := "file/" + strconv.Itoa(o.id) |
| 67 | + |
| 68 | + dest, toStdout, err := resolveDest(ctx, o, client, idPath) |
| 69 | + if err != nil { |
| 70 | + return err |
| 71 | + } |
| 72 | + |
| 73 | + var w io.Writer |
| 74 | + var f *os.File |
| 75 | + if toStdout { |
| 76 | + w = o.out |
| 77 | + } else { |
| 78 | + flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL |
| 79 | + if o.force { |
| 80 | + flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC |
| 81 | + } |
| 82 | + f, err = os.OpenFile(dest, flag, 0o644) |
| 83 | + if err != nil { |
| 84 | + if os.IsExist(err) { |
| 85 | + return fmt.Errorf("%s exists (use --force to overwrite)", dest) |
| 86 | + } |
| 87 | + return err |
| 88 | + } |
| 89 | + w = f |
| 90 | + } |
| 91 | + |
| 92 | + resp, err := client.Stream(ctx, idPath+"/download") |
| 93 | + if err != nil { |
| 94 | + cleanupPartial(f) |
| 95 | + return err |
| 96 | + } |
| 97 | + defer resp.Body.Close() |
| 98 | + if resp.StatusCode >= 300 { |
| 99 | + data, _ := io.ReadAll(resp.Body) |
| 100 | + cleanupPartial(f) |
| 101 | + return cmdutil.DescribeAPIError(planfix.ParseError(resp.StatusCode, data)) |
| 102 | + } |
| 103 | + |
| 104 | + n, err := io.Copy(w, resp.Body) |
| 105 | + if err != nil { |
| 106 | + cleanupPartial(f) |
| 107 | + return err |
| 108 | + } |
| 109 | + if resp.ContentLength >= 0 && n != resp.ContentLength { |
| 110 | + cleanupPartial(f) |
| 111 | + return fmt.Errorf("download truncated: got %d bytes, expected %d", n, resp.ContentLength) |
| 112 | + } |
| 113 | + if f != nil { |
| 114 | + if err := f.Close(); err != nil { |
| 115 | + return err |
| 116 | + } |
| 117 | + } |
| 118 | + if !o.quiet && !toStdout { |
| 119 | + fmt.Fprintf(o.errOut, "Saved %s (%d bytes)\n", dest, n) |
| 120 | + } |
| 121 | + return nil |
| 122 | +} |
| 123 | + |
| 124 | +// resolveDest decides where bytes go. "-" → stdout. "" → ./<api-name>. A value |
| 125 | +// that names an existing directory, or ends in a path separator, → <dir>/<api-name>. |
| 126 | +// Any other value is a literal path. The API name is validated with SafeFileName |
| 127 | +// only when pfix (not the user) supplies the final segment. |
| 128 | +func resolveDest(ctx context.Context, o *downloadOptions, client *planfix.Client, idPath string) (string, bool, error) { |
| 129 | + if o.output == "-" { |
| 130 | + return "", true, nil |
| 131 | + } |
| 132 | + fetchName := func() (string, error) { |
| 133 | + raw, err := client.JSON(ctx, "GET", idPath, nil) |
| 134 | + if err != nil { |
| 135 | + return "", cmdutil.DescribeAPIError(err) |
| 136 | + } |
| 137 | + var env struct { |
| 138 | + File struct { |
| 139 | + Name string `json:"name"` |
| 140 | + } `json:"file"` |
| 141 | + } |
| 142 | + if err := cmdutil.DecodeJSON(raw, &env); err != nil { |
| 143 | + return "", err |
| 144 | + } |
| 145 | + return cmdutil.SafeFileName(env.File.Name) |
| 146 | + } |
| 147 | + if o.output == "" { |
| 148 | + name, err := fetchName() |
| 149 | + if err != nil { |
| 150 | + return "", false, err |
| 151 | + } |
| 152 | + return name, false, nil |
| 153 | + } |
| 154 | + isDir := strings.HasSuffix(o.output, string(os.PathSeparator)) |
| 155 | + if !isDir { |
| 156 | + if fi, err := os.Stat(o.output); err == nil && fi.IsDir() { |
| 157 | + isDir = true |
| 158 | + } |
| 159 | + } |
| 160 | + if isDir { |
| 161 | + name, err := fetchName() |
| 162 | + if err != nil { |
| 163 | + return "", false, err |
| 164 | + } |
| 165 | + return filepath.Join(o.output, name), false, nil |
| 166 | + } |
| 167 | + return o.output, false, nil |
| 168 | +} |
| 169 | + |
| 170 | +func cleanupPartial(f *os.File) { |
| 171 | + if f != nil { |
| 172 | + f.Close() |
| 173 | + os.Remove(f.Name()) |
| 174 | + } |
| 175 | +} |
0 commit comments