get.go 6.27 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2 3
package commands

import (
4
	"compress/gzip"
5
	"errors"
6
	"fmt"
Matt Bell's avatar
Matt Bell committed
7
	"io"
8
	"os"
Dominic Della Valle's avatar
Dominic Della Valle committed
9
	"path/filepath"
10
	"strings"
Matt Bell's avatar
Matt Bell committed
11

Łukasz Magiera's avatar
Łukasz Magiera committed
12 13 14
	"github.com/ipfs/go-ipfs/core/commands/cmdenv"
	"github.com/ipfs/go-ipfs/core/commands/e"
	"github.com/ipfs/go-ipfs/core/coreapi/interface"
Jan Winkelmann's avatar
Jan Winkelmann committed
15

Łukasz Magiera's avatar
Łukasz Magiera committed
16
	"gx/ipfs/QmQine7gvHncNevKtG9QXxf3nXcwSj6aDDmMm52mHofEEp/tar-utils"
17
	uarchive "gx/ipfs/QmSMJ4rZbCJaih3y82Ebq7BZqK6vU2FHsKcWKQiE1DPTpS/go-unixfs/archive"
Hector Sanjuan's avatar
Hector Sanjuan committed
18
	"gx/ipfs/QmWGm4AbZEbnmdgVTza52MSNpEmBdFVqzmAysRbjrRyGbH/go-ipfs-cmds"
Łukasz Magiera's avatar
Łukasz Magiera committed
19
	"gx/ipfs/QmYWB8oH6o7qftxoyqTTZhzLrhKCVT7NYahECQTwTtqbgj/pb"
20
	"gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
Matt Bell's avatar
Matt Bell committed
21 22
)

Łukasz Magiera's avatar
Łukasz Magiera committed
23
var ErrInvalidCompressionLevel = errors.New("compression level must be between 1 and 9")
24

Kejie Zhang's avatar
Kejie Zhang committed
25 26 27 28 29 30 31
const (
	outputOptionName           = "output"
	archiveOptionName          = "archive"
	compressOptionName         = "compress"
	compressionLevelOptionName = "compression-level"
)

Matt Bell's avatar
Matt Bell committed
32
var GetCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
33
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
34
		Tagline: "Download IPFS objects.",
Matt Bell's avatar
Matt Bell committed
35
		ShortDescription: `
Richard Littauer's avatar
Richard Littauer committed
36
Stores to disk the data contained an IPFS or IPNS object(s) at the given path.
Matt Bell's avatar
Matt Bell committed
37

38 39
By default, the output will be stored at './<ipfs-path>', but an alternate
path can be specified with '--output=<path>' or '-o=<path>'.
Matt Bell's avatar
Matt Bell committed
40 41

To output a TAR archive instead of unpacked files, use '--archive' or '-a'.
42 43 44

To compress the output with GZIP compression, use '--compress' or '-C'. You
may also specify the level of compression by specifying '-l=<1-9>'.
Matt Bell's avatar
Matt Bell committed
45 46 47
`,
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
48 49
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
Matt Bell's avatar
Matt Bell committed
50
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
51
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
52 53 54 55
		cmdkit.StringOption(outputOptionName, "o", "The path where the output should be stored."),
		cmdkit.BoolOption(archiveOptionName, "a", "Output a TAR archive."),
		cmdkit.BoolOption(compressOptionName, "C", "Compress the output with GZIP compression."),
		cmdkit.IntOption(compressionLevelOptionName, "l", "The level of compression (1-9)."),
Matt Bell's avatar
Matt Bell committed
56
	},
Jeromy's avatar
Jeromy committed
57
	PreRun: func(req *cmds.Request, env cmds.Environment) error {
58 59 60
		_, err := getCompressOptions(req)
		return err
	},
keks's avatar
keks committed
61
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
62
		cmplvl, err := getCompressOptions(req)
63
		if err != nil {
keks's avatar
keks committed
64
			return err
65 66
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
67
		api, err := cmdenv.GetApi(env, req)
Matt Bell's avatar
Matt Bell committed
68
		if err != nil {
keks's avatar
keks committed
69
			return err
Matt Bell's avatar
Matt Bell committed
70
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
71 72

		p, err := iface.ParsePath(req.Arguments[0])
rht's avatar
rht committed
73
		if err != nil {
keks's avatar
keks committed
74
			return err
rht's avatar
rht committed
75
		}
rht's avatar
rht committed
76

Łukasz Magiera's avatar
Łukasz Magiera committed
77 78 79 80
		file, err := api.Unixfs().Get(req.Context, p)
		if err != nil {
			return err
		}
81

Łukasz Magiera's avatar
Łukasz Magiera committed
82 83
		size, err := file.Size()
		if err != nil {
keks's avatar
keks committed
84
			return err
85 86
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
87 88
		res.SetLength(uint64(size))

Kejie Zhang's avatar
Kejie Zhang committed
89
		archive, _ := req.Options[archiveOptionName].(bool)
Łukasz Magiera's avatar
Łukasz Magiera committed
90
		reader, err := uarchive.FileArchive(file, p.String(), archive, cmplvl)
Matt Bell's avatar
Matt Bell committed
91
		if err != nil {
keks's avatar
keks committed
92
			return err
93
		}
94

keks's avatar
keks committed
95
		return res.Emit(reader)
Jan Winkelmann's avatar
Jan Winkelmann committed
96
	},
97
	PostRun: cmds.PostRunMap{
keks's avatar
keks committed
98 99 100 101 102 103 104 105 106 107
		cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
			req := res.Request()

			v, err := res.Next()
			if err != nil {
				return err
			}

			outReader, ok := v.(io.Reader)
			if !ok {
keks's avatar
keks committed
108
				return e.New(e.TypeErr(outReader, v))
keks's avatar
keks committed
109 110 111 112 113 114 115 116 117
			}

			outPath := getOutPath(req)

			cmplvl, err := getCompressOptions(req)
			if err != nil {
				return err
			}

Kejie Zhang's avatar
Kejie Zhang committed
118
			archive, _ := req.Options[archiveOptionName].(bool)
keks's avatar
keks committed
119 120 121 122 123 124 125 126 127 128

			gw := getWriter{
				Out:         os.Stdout,
				Err:         os.Stderr,
				Archive:     archive,
				Compression: cmplvl,
				Size:        int64(res.Length()),
			}

			return gw.Write(outReader, outPath)
Jan Winkelmann's avatar
Jan Winkelmann committed
129
		},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130 131
	},
}
132

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
type clearlineReader struct {
	io.Reader
	out io.Writer
}

func (r *clearlineReader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	if err == io.EOF {
		// callback
		fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF
	}
	return
}

func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader) {
Jeromy's avatar
Jeromy committed
148 149 150 151 152 153
	bar := makeProgressBar(out, l)
	barR := bar.NewProxyReader(r)
	return bar, &clearlineReader{barR, out}
}

func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
	// setup bar reader
	// TODO: get total length of files
156
	bar := pb.New64(l).SetUnits(pb.U_BYTES)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
	bar.Output = out
158 159 160 161 162 163 164 165

	// the progress bar lib doesn't give us a way to get the width of the output,
	// so as a hack we just use a callback to measure the output, then git rid of it
	bar.Callback = func(line string) {
		terminalWidth := len(line)
		bar.Callback = nil
		log.Infof("terminal width: %v\n", terminalWidth)
	}
Jeromy's avatar
Jeromy committed
166
	return bar
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167
}
168

169
func getOutPath(req *cmds.Request) string {
Kejie Zhang's avatar
Kejie Zhang committed
170
	outPath, _ := req.Options[outputOptionName].(string)
171
	if outPath == "" {
172
		trimmed := strings.TrimRight(req.Arguments[0], "/")
Dominic Della Valle's avatar
Dominic Della Valle committed
173 174
		_, outPath = filepath.Split(trimmed)
		outPath = filepath.Clean(outPath)
175 176 177 178
	}
	return outPath
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179 180 181
type getWriter struct {
	Out io.Writer // for output to user
	Err io.Writer // for progress bar output
182

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183 184
	Archive     bool
	Compression int
Jeromy's avatar
Jeromy committed
185
	Size        int64
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186
}
187

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188 189 190 191 192 193 194 195 196 197 198 199
func (gw *getWriter) Write(r io.Reader, fpath string) error {
	if gw.Archive || gw.Compression != gzip.NoCompression {
		return gw.writeArchive(r, fpath)
	}
	return gw.writeExtracted(r, fpath)
}

func (gw *getWriter) writeArchive(r io.Reader, fpath string) error {
	// adjust file name if tar
	if gw.Archive {
		if !strings.HasSuffix(fpath, ".tar") && !strings.HasSuffix(fpath, ".tar.gz") {
			fpath += ".tar"
200
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
	}

	// adjust file name if gz
	if gw.Compression != gzip.NoCompression {
		if !strings.HasSuffix(fpath, ".gz") {
			fpath += ".gz"
		}
	}

	// create file
	file, err := os.Create(fpath)
	if err != nil {
		return err
	}
	defer file.Close()

	fmt.Fprintf(gw.Out, "Saving archive to %s\n", fpath)
Jeromy's avatar
Jeromy committed
218
	bar, barR := progressBarForReader(gw.Err, r, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219 220 221 222 223 224 225 226 227
	bar.Start()
	defer bar.Finish()

	_, err = io.Copy(file, barR)
	return err
}

func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error {
	fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath)
Jeromy's avatar
Jeromy committed
228
	bar := makeProgressBar(gw.Err, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
229 230
	bar.Start()
	defer bar.Finish()
Jeromy's avatar
Jeromy committed
231
	defer bar.Set64(gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232

Steven Allen's avatar
Steven Allen committed
233
	extractor := &tar.Extractor{Path: fpath, Progress: bar.Add64}
Jeromy's avatar
Jeromy committed
234
	return extractor.Extract(r)
Matt Bell's avatar
Matt Bell committed
235 236
}

237
func getCompressOptions(req *cmds.Request) (int, error) {
Kejie Zhang's avatar
Kejie Zhang committed
238 239
	cmprs, _ := req.Options[compressOptionName].(bool)
	cmplvl, cmplvlFound := req.Options[compressionLevelOptionName].(int)
240 241 242
	switch {
	case !cmprs:
		return gzip.NoCompression, nil
Steven Allen's avatar
Steven Allen committed
243
	case cmprs && !cmplvlFound:
244
		return gzip.DefaultCompression, nil
keks's avatar
keks committed
245
	case cmprs && (cmplvl < 1 || cmplvl > 9):
246
		return gzip.NoCompression, ErrInvalidCompressionLevel
247
	}
248
	return cmplvl, nil
249
}