get.go 6.85 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"
Jeromy's avatar
Jeromy committed
9
	gopath "path"
10
	"strings"
Matt Bell's avatar
Matt Bell committed
11

12
	core "github.com/ipfs/go-ipfs/core"
Jan Winkelmann's avatar
Jan Winkelmann committed
13
	e "github.com/ipfs/go-ipfs/core/commands/e"
14
	dag "github.com/ipfs/go-ipfs/merkledag"
15 16
	path "github.com/ipfs/go-ipfs/path"
	tar "github.com/ipfs/go-ipfs/thirdparty/tar"
rht's avatar
rht committed
17
	uarchive "github.com/ipfs/go-ipfs/unixfs/archive"
Jan Winkelmann's avatar
Jan Winkelmann committed
18

keks's avatar
keks committed
19
	"gx/ipfs/QmVs8An1faiQrNXtY8e51o5ssnrQs3YYBUfPbCMo34onJr/go-ipfs-cmds"
20
	"gx/ipfs/QmceUdzxkimdYsgtX733uNgzf1DLHyBKN6ehGSp85ayppM/go-ipfs-cmdkit"
Jan Winkelmann's avatar
Jan Winkelmann committed
21
	"gx/ipfs/QmeWjRodbcZFKe5tMN7poEx3izym6osrLSnTLf9UjJZBbs/pb"
Matt Bell's avatar
Matt Bell committed
22 23
)

24 25
var ErrInvalidCompressionLevel = errors.New("Compression level must be between 1 and 9")

Matt Bell's avatar
Matt Bell committed
26
var GetCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
27
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
28
		Tagline: "Download IPFS objects.",
Matt Bell's avatar
Matt Bell committed
29
		ShortDescription: `
Richard Littauer's avatar
Richard Littauer committed
30
Stores to disk the data contained an IPFS or IPNS object(s) at the given path.
Matt Bell's avatar
Matt Bell committed
31

32 33
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
34 35

To output a TAR archive instead of unpacked files, use '--archive' or '-a'.
36 37 38

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
39 40 41
`,
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
42 43
	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
44
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
45 46
	Options: []cmdkit.Option{
		cmdkit.StringOption("output", "o", "The path where the output should be stored."),
47 48
		cmdkit.BoolOption("archive", "a", "Output a TAR archive."),
		cmdkit.BoolOption("compress", "C", "Compress the output with GZIP compression."),
49
		cmdkit.IntOption("compression-level", "l", "The level of compression (1-9).").WithDefault(-1),
Matt Bell's avatar
Matt Bell committed
50
	},
51
	PreRun: func(req *cmds.Request, env interface{}) error {
52 53 54
		_, err := getCompressOptions(req)
		return err
	},
55 56
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env interface{}) {
		if len(req.Arguments) == 0 {
Jan Winkelmann's avatar
Jan Winkelmann committed
57
			res.SetError(errors.New("not enough arugments provided"), cmdkit.ErrClient)
58 59
			return
		}
60
		cmplvl, err := getCompressOptions(req)
61
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
62
			res.SetError(err, cmdkit.ErrNormal)
63 64 65
			return
		}

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

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

Jeromy's avatar
Jeromy committed
87 88 89 90
			res.SetLength(size)
		case *dag.RawNode:
			res.SetLength(uint64(len(dn.RawData())))
		default:
Jan Winkelmann's avatar
Jan Winkelmann committed
91
			res.SetError(err, cmdkit.ErrNormal)
92 93 94
			return
		}

95
		archive, _ := req.Options["archive"].(bool)
Jeromy's avatar
Jeromy committed
96
		reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl)
Matt Bell's avatar
Matt Bell committed
97
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
98
			res.SetError(err, cmdkit.ErrNormal)
99
			return
100
		}
101

Jan Winkelmann's avatar
Jan Winkelmann committed
102 103
		res.Emit(reader)
	},
104
	PostRun: map[cmds.PostRunType]func(*cmds.Request, cmds.ResponseEmitter) cmds.ResponseEmitter{
105
		cmds.CLI: func(req *cmds.Request, re cmds.ResponseEmitter) cmds.ResponseEmitter {
Jan Winkelmann's avatar
Jan Winkelmann committed
106 107 108 109 110 111
			reNext, res := cmds.NewChanResponsePair(req)

			go func() {
				defer re.Close()

				v, err := res.Next()
112
				if !cmds.HandleError(err, res, re) {
Jan Winkelmann's avatar
Jan Winkelmann committed
113 114 115 116 117 118 119 120 121
					return
				}

				outReader, ok := v.(io.Reader)
				if !ok {
					log.Error(e.New(e.TypeErr(outReader, v)))
					return
				}

122 123 124 125 126
				outPath, _ := req.Options["output"].(string)
				if len(outPath) == 0 {
					_, outPath = gopath.Split(req.Arguments[0])
					outPath = gopath.Clean(outPath)
				}
Jan Winkelmann's avatar
Jan Winkelmann committed
127 128 129 130 131 132 133

				cmplvl, err := getCompressOptions(req)
				if err != nil {
					re.SetError(err, cmdkit.ErrNormal)
					return
				}

134
				archive, _ := req.Options["archive"].(bool)
Jan Winkelmann's avatar
Jan Winkelmann committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

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

				if err := gw.Write(outReader, outPath); err != nil {
					re.SetError(err, cmdkit.ErrNormal)
				}
			}()

			return reNext
		},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151 152
	},
}
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
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
169 170 171 172 173 174
	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
175 176
	// setup bar reader
	// TODO: get total length of files
177
	bar := pb.New64(l).SetUnits(pb.U_BYTES)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178
	bar.Output = out
179 180 181 182 183 184 185 186

	// 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
187
	return bar
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
}
189

190 191
func getOutPath(req *cmds.Request) string {
	outPath, _ := req.Options["output"].(string)
192
	if outPath == "" {
193
		trimmed := strings.TrimRight(req.Arguments[0], "/")
194 195 196 197 198 199
		_, outPath = gopath.Split(trimmed)
		outPath = gopath.Clean(outPath)
	}
	return outPath
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200 201 202
type getWriter struct {
	Out io.Writer // for output to user
	Err io.Writer // for progress bar output
203

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204 205
	Archive     bool
	Compression int
Jeromy's avatar
Jeromy committed
206
	Size        int64
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207
}
208

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209 210 211 212 213 214 215 216 217 218 219 220
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"
221
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
	}

	// 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
239
	bar, barR := progressBarForReader(gw.Err, r, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240 241 242 243 244 245 246 247 248
	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
249
	bar := makeProgressBar(gw.Err, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250 251
	bar.Start()
	defer bar.Finish()
Jeromy's avatar
Jeromy committed
252
	defer bar.Set64(gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
253

Jeromy's avatar
Jeromy committed
254 255
	extractor := &tar.Extractor{fpath, bar.Add64}
	return extractor.Extract(r)
Matt Bell's avatar
Matt Bell committed
256 257
}

258 259
func getCompressOptions(req *cmds.Request) (int, error) {
	cmprs, _ := req.Options["compress"].(bool)
keks's avatar
keks committed
260
	cmplvl, _ := req.Options["compression-level"].(int)
261 262 263
	switch {
	case !cmprs:
		return gzip.NoCompression, nil
keks's avatar
keks committed
264
	case cmprs && cmplvl == -1:
265
		return gzip.DefaultCompression, nil
keks's avatar
keks committed
266
	case cmprs && (cmplvl < 1 || cmplvl > 9):
267
		return gzip.NoCompression, ErrInvalidCompressionLevel
268
	}
269
	return cmplvl, nil
270
}