tar.go 2.32 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
package commands

import (
	"io"
	"strings"

	cmds "github.com/ipfs/go-ipfs/commands"
	core "github.com/ipfs/go-ipfs/core"
	path "github.com/ipfs/go-ipfs/path"
	tar "github.com/ipfs/go-ipfs/tar"
)

var TarCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "utility functions for tar files in ipfs",
	},

	Subcommands: map[string]*cmds.Command{
		"add": tarAddCmd,
		"cat": tarCatCmd,
	},
}

var tarAddCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "import a tar file into ipfs",
		ShortDescription: `
'ipfs tar add' will parse a tar file and create a merkledag structure to represent it.
`,
	},

	Arguments: []cmds.Argument{
		cmds.FileArg("file", true, false, "tar file to add").EnableStdin(),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		nd, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		fi, err := req.Files().NextFile()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		node, err := tar.ImportTar(fi, nd.DAG)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		k, err := node.Key()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		fi.FileName()
		res.SetOutput(&AddedObject{
			Name: fi.FileName(),
			Hash: k.B58String(),
		})
	},
	Type: AddedObject{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			o := res.Output().(*AddedObject)
70
			return strings.NewReader(o.Hash + "\n"), nil
Jeromy's avatar
Jeromy committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
		},
	},
}

var tarCatCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "export a tar file from ipfs",
		ShortDescription: `
'ipfs tar cat' will export a tar file from a previously imported one in ipfs
`,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("path", true, false, "ipfs path of archive to export").EnableStdin(),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		nd, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		p, err := path.ParsePath(req.Arguments()[0])
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		root, err := core.Resolve(req.Context(), nd, p)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		r, err := tar.ExportTar(req.Context(), root, nd.DAG)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(r)
	},
}