Add offset option to cat command
Allow an offset option to be passed to cat command License: MIT Signed-off-by: ForrestWeston <forrest@protocol.ai>
ForrestWeston committed
Jan 2, 2018 at 09:52 UTC
f0c772a4f390cbc7a2db39b731b8f1017cbbe1b5
1 file changed
+26
-3
core/commands/cat.go
+26
-3
@@ -2,6 +2,7 @@ package commands
2
3
import (
4
"context"
5
+ "fmt"
6
"io"
7
"os"
8
@@ -23,6 +24,9 @@ var CatCmd = &cmds.Command{
24
Arguments: []cmdkit.Argument{
25
cmdkit.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
26
},
27
+ Options: []cmdkit.Option{
28
+ cmdkit.IntOption("offset", "o", "Byte offset to begin reading from."),
29
+ },
30
Run: func(req cmds.Request, res cmds.ResponseEmitter) {
31
node, err := req.InvocContext().GetNode()
32
if err != nil {
@@ -36,8 +40,17 @@ var CatCmd = &cmds.Command{
40
return
41
}
42
}
43
+ offset, _, err := req.Option("offset").Int()
44
+ if err != nil {
45
+ res.SetError(err, cmdkit.ErrNormal)
46
+ return
47
+ }
48
+ if offset < 0 {
49
+ res.SetError(fmt.Errorf("Cannot specify negative offset."), cmdkit.ErrNormal)
50
+ return
51
+ }
52
40
- readers, length, err := cat(req.Context(), node, req.Arguments())
53
+ readers, length, err := cat(req.Context(), node, req.Arguments(), int64(offset))
54
if err != nil {
55
res.SetError(err, cmdkit.ErrNormal)
56
return
@@ -103,7 +116,7 @@ var CatCmd = &cmds.Command{
116
},
117
}
118
106
-func cat(ctx context.Context, node *core.IpfsNode, paths []string) ([]io.Reader, uint64, error) {
119
+func cat(ctx context.Context, node *core.IpfsNode, paths []string, offset int64) ([]io.Reader, uint64, error) {
120
readers := make([]io.Reader, 0, len(paths))
121
length := uint64(0)
122
for _, fpath := range paths {
@@ -111,8 +124,18 @@ func cat(ctx context.Context, node *core.IpfsNode, paths []string) ([]io.Reader,
124
if err != nil {
125
return nil, 0, err
126
}
127
+ if offset > int64(read.Size()) {
128
+ offset = offset - int64(read.Size())
129
+ continue
130
+ }
131
+ count, err := read.Seek(offset, io.SeekStart)
132
+ if err != nil {
133
+ return nil, 0, err
134
+ }
135
+ offset = 0
136
+
137
readers = append(readers, read)
115
- length += uint64(read.Size())
138
+ length += uint64(read.Size() - uint64(count))
139
}
140
return readers, length, nil
141
}