get.go 6.55 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

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

16
	tar "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"
19
	path "gx/ipfs/QmWqh9oob7ZHQRwU5CdTqpnC8ip8BEkFNrwXRxeNo5Y7vA/go-path"
Łukasz Magiera's avatar
Łukasz Magiera committed
20
	"gx/ipfs/QmYWB8oH6o7qftxoyqTTZhzLrhKCVT7NYahECQTwTtqbgj/pb"
21
	dag "gx/ipfs/Qmb2UEG2TAeVrEJSjqsZF7Y2he7wRDkrdt6c3bECxwZf4k/go-merkledag"
22
	"gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
Matt Bell's avatar
Matt Bell committed
23 24
)

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

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

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

40 41
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
42 43

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

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
47 48 49
`,
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
50 51
	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
52
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
53
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
54 55 56 57
		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
58
	},
Jeromy's avatar
Jeromy committed
59
	PreRun: func(req *cmds.Request, env cmds.Environment) error {
60 61 62
		_, err := getCompressOptions(req)
		return err
	},
keks's avatar
keks committed
63
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
64
		cmplvl, err := getCompressOptions(req)
65
		if err != nil {
keks's avatar
keks committed
66
			return err
67 68
		}

69
		node, err := cmdenv.GetNode(env)
Matt Bell's avatar
Matt Bell committed
70
		if err != nil {
keks's avatar
keks committed
71
			return err
Matt Bell's avatar
Matt Bell committed
72
		}
73 74
		p := path.Path(req.Arguments[0])
		ctx := req.Context
75
		dn, err := core.Resolve(ctx, node.Namesys, node.Resolver, p)
rht's avatar
rht committed
76
		if err != nil {
keks's avatar
keks committed
77
			return err
rht's avatar
rht committed
78
		}
rht's avatar
rht committed
79

Jeromy's avatar
Jeromy committed
80 81 82 83
		switch dn := dn.(type) {
		case *dag.ProtoNode:
			size, err := dn.Size()
			if err != nil {
keks's avatar
keks committed
84
				return err
Jeromy's avatar
Jeromy committed
85
			}
86

Jeromy's avatar
Jeromy committed
87 88 89 90
			res.SetLength(size)
		case *dag.RawNode:
			res.SetLength(uint64(len(dn.RawData())))
		default:
keks's avatar
keks committed
91
			return err
92 93
		}

Kejie Zhang's avatar
Kejie Zhang committed
94
		archive, _ := req.Options[archiveOptionName].(bool)
Jeromy's avatar
Jeromy committed
95
		reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl)
Matt Bell's avatar
Matt Bell committed
96
		if err != nil {
keks's avatar
keks committed
97
			return err
98
		}
99

keks's avatar
keks committed
100
		return res.Emit(reader)
Jan Winkelmann's avatar
Jan Winkelmann committed
101
	},
102
	PostRun: cmds.PostRunMap{
keks's avatar
keks committed
103 104 105 106 107 108 109 110 111 112
		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
113
				return e.New(e.TypeErr(outReader, v))
keks's avatar
keks committed
114 115 116 117 118 119 120 121 122
			}

			outPath := getOutPath(req)

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

Kejie Zhang's avatar
Kejie Zhang committed
123
			archive, _ := req.Options[archiveOptionName].(bool)
keks's avatar
keks committed
124 125 126 127 128 129 130 131 132 133

			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
134
		},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135 136
	},
}
137

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
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
153 154 155 156 157 158
	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
159 160
	// setup bar reader
	// TODO: get total length of files
161
	bar := pb.New64(l).SetUnits(pb.U_BYTES)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162
	bar.Output = out
163 164 165 166 167 168 169 170

	// 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
171
	return bar
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
}
173

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
184 185 186
type getWriter struct {
	Out io.Writer // for output to user
	Err io.Writer // for progress bar output
187

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188 189
	Archive     bool
	Compression int
Jeromy's avatar
Jeromy committed
190
	Size        int64
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
}
192

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
193 194 195 196 197 198 199 200 201 202 203 204
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"
205
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
	}

	// 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
223
	bar, barR := progressBarForReader(gw.Err, r, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225 226 227 228 229 230 231 232
	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
233
	bar := makeProgressBar(gw.Err, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234 235
	bar.Start()
	defer bar.Finish()
Jeromy's avatar
Jeromy committed
236
	defer bar.Set64(gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237

Steven Allen's avatar
Steven Allen committed
238
	extractor := &tar.Extractor{Path: fpath, Progress: bar.Add64}
Jeromy's avatar
Jeromy committed
239
	return extractor.Extract(r)
Matt Bell's avatar
Matt Bell committed
240 241
}

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