repo.go 2.05 KB
Newer Older
1 2 3 4 5
package commands

import (
	"bytes"
	"fmt"
6 7
	"io"

8
	cmds "github.com/jbenet/go-ipfs/commands"
9
	corerepo "github.com/jbenet/go-ipfs/core/corerepo"
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
	u "github.com/jbenet/go-ipfs/util"
)

var RepoCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Manipulate the IPFS repo",
		ShortDescription: `
'ipfs repo' is a plumbing command used to manipulate the repo.
`,
	},

	Subcommands: map[string]*cmds.Command{
		"gc": repoGcCmd,
	},
}

var repoGcCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Perform a garbage collection sweep on the repo",
		ShortDescription: `
'ipfs repo gc' is a plumbing command that will sweep the local
set of stored objects and remove ones that are not pinned in
order to reclaim hard disk space.
`,
	},

	Options: []cmds.Option{
		cmds.BoolOption("quiet", "q", "Write minimal output"),
	},
39
	Run: func(req cmds.Request, res cmds.Response) {
40 41
		n, err := req.Context().GetNode()
		if err != nil {
42 43
			res.SetError(err, cmds.ErrNormal)
			return
44 45
		}

46
		gcOutChan, err := corerepo.GarbageCollectAsync(n, req.Context().Context)
47
		if err != nil {
48 49
			res.SetError(err, cmds.ErrNormal)
			return
50 51
		}

Jeromy's avatar
Jeromy committed
52
		outChan := make(chan interface{})
53 54
		res.SetOutput((<-chan interface{})(outChan))

Jeromy's avatar
Jeromy committed
55 56 57 58 59 60
		go func() {
			defer close(outChan)
			for k := range gcOutChan {
				outChan <- k
			}
		}()
61
	},
62
	Type: corerepo.KeyRemoved{},
63 64
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
65
			outChan, ok := res.Output().(<-chan interface{})
66 67 68 69 70 71 72 73 74 75
			if !ok {
				return nil, u.ErrCast()
			}

			quiet, _, err := res.Request().Option("quiet").Bool()
			if err != nil {
				return nil, err
			}

			marshal := func(v interface{}) (io.Reader, error) {
76
				obj, ok := v.(*corerepo.KeyRemoved)
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
				if !ok {
					return nil, u.ErrCast()
				}

				var buf *bytes.Buffer
				if quiet {
					buf = bytes.NewBufferString(string(obj.Key) + "\n")
				} else {
					buf = bytes.NewBufferString(fmt.Sprintf("removed %s\n", obj.Key))
				}
				return buf, nil
			}

			return &cmds.ChannelMarshaler{
				Channel:   outChan,
				Marshaler: marshal,
			}, nil
		},
	},
}