-
Notifications
You must be signed in to change notification settings - Fork 54
/
main.go
276 lines (246 loc) · 5.69 KB
/
main.go
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
70
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package main
import (
"context"
"fmt"
"io"
"net/url"
"os"
"os/signal"
gopath "path"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"github.com/cheggaaa/pb/v3"
files "github.com/ipfs/boxo/files"
ipath "github.com/ipfs/boxo/path"
iface "github.com/ipfs/kubo/core/coreiface"
cli "github.com/urfave/cli/v2"
)
var (
cleanup []func() error
cleanupMutex sync.Mutex
)
func main() {
// Do any cleanup on exit
defer doCleanup()
app := cli.NewApp()
app.Name = "ipget"
app.Usage = "Retrieve and save IPFS objects."
app.Version = version
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "specify output location",
},
&cli.StringFlag{
Name: "node",
Aliases: []string{"n"},
Usage: "specify ipfs node strategy (\"local\", \"spawn\", \"temp\" or \"fallback\")",
Value: "fallback",
},
&cli.StringSliceFlag{
Name: "peers",
Aliases: []string{"p"},
Usage: "specify a set of IPFS peers to connect to",
},
&cli.BoolFlag{
Name: "progress",
Usage: "show a progress bar",
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigExitCoder := make(chan cli.ExitCoder, 1)
app.Action = func(c *cli.Context) error {
if !c.Args().Present() {
return fmt.Errorf("usage: ipget <ipfs ref>")
}
outPath := c.String("output")
iPath, err := parsePath(c.Args().First())
if err != nil {
return err
}
// Use the final segment of the object's path if no path was given.
if outPath == "" {
trimmed := strings.TrimRight(iPath.String(), "/")
_, outPath = filepath.Split(trimmed)
outPath = filepath.Clean(outPath)
}
var ipfs iface.CoreAPI
switch c.String("node") {
case "fallback":
ipfs, err = http(ctx)
if err == nil {
break
}
fallthrough
case "spawn":
ipfs, err = spawn(ctx)
case "local":
ipfs, err = http(ctx)
case "temp":
ipfs, err = temp(ctx)
default:
return fmt.Errorf("no such 'node' strategy, %q", c.String("node"))
}
if err != nil {
return err
}
go connect(ctx, ipfs, c.StringSlice("peers"))
out, err := ipfs.Unixfs().Get(ctx, iPath)
if err != nil {
if err == context.Canceled {
return <-sigExitCoder
}
return cli.Exit(err, 2)
}
err = WriteTo(out, outPath, c.Bool("progress"))
if err != nil {
if err == context.Canceled {
return <-sigExitCoder
}
return cli.Exit(err, 2)
}
return nil
}
// Catch interrupt signal
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
sigExitCoder <- cli.Exit("", 128+int(sig.(syscall.Signal)))
cancel()
}()
// cli library requires flags before arguments
args := movePostfixOptions(os.Args)
err := app.Run(args)
if err != nil {
fmt.Fprintln(os.Stderr, err)
doCleanup()
os.Exit(1)
}
}
// movePostfixOptions moves non-flag arguments to end of argument list.
func movePostfixOptions(args []string) []string {
var endArgs []string
for idx := 1; idx < len(args); idx++ {
if args[idx][0] == '-' {
if !strings.Contains(args[idx], "=") {
idx++
}
continue
}
if endArgs == nil {
// on first write, make copy of args
newArgs := make([]string, len(args))
copy(newArgs, args)
args = newArgs
}
// add to args accumulator
endArgs = append(endArgs, args[idx])
// remove from real args list
args = args[:idx+copy(args[idx:], args[idx+1:])]
idx--
}
// append extracted arguments to the real args
return append(args, endArgs...)
}
func parsePath(path string) (ipath.Path, error) {
ipfsPath, err := ipath.NewPath(path)
if err == nil {
return ipfsPath, nil
}
origErr := err
ipfsPath, err = ipath.NewPath("/ipfs/" + path)
if err == nil {
return ipfsPath, nil
}
u, err := url.Parse(path)
if err != nil {
return nil, origErr
}
switch u.Scheme {
case "ipfs", "ipld", "ipns":
return ipath.NewPath(gopath.Join("/", u.Scheme, u.Host, u.Path))
case "http", "https":
return ipath.NewPath(u.Path)
}
return nil, fmt.Errorf("%q is not recognized as an IPFS path", path)
}
// WriteTo writes the given node to the local filesystem at fpath.
func WriteTo(nd files.Node, fpath string, progress bool) error {
s, err := nd.Size()
if err != nil {
return err
}
var bar *pb.ProgressBar
if progress {
bar = pb.New64(s).Start()
}
return writeToRec(nd, fpath, bar)
}
func writeToRec(nd files.Node, fpath string, bar *pb.ProgressBar) error {
switch nd := nd.(type) {
case *files.Symlink:
err := os.Symlink(nd.Target, fpath)
if err != nil {
return err
}
switch runtime.GOOS {
case "linux", "freebsd", "netbsd", "openbsd", "dragonfly":
return files.UpdateModTime(fpath, nd.ModTime())
default:
return nil
}
case files.File:
f, err := os.Create(fpath)
defer f.Close()
if err != nil {
return err
}
var r io.Reader = nd
if bar != nil {
r = bar.NewProxyReader(r)
}
_, err = io.Copy(f, r)
if err != nil {
return err
}
return files.UpdateMeta(fpath, nd.Mode(), nd.ModTime())
case files.Directory:
err := os.Mkdir(fpath, 0777)
if err != nil {
return err
}
entries := nd.Entries()
for entries.Next() {
child := filepath.Join(fpath, entries.Name())
if err := writeToRec(entries.Node(), child, bar); err != nil {
return err
}
}
if err = files.UpdateMeta(fpath, nd.Mode(), nd.ModTime()); err != nil {
return err
}
return entries.Err()
default:
return fmt.Errorf("file type %T at %q is not supported", nd, fpath)
}
}
func addCleanup(f func() error) {
cleanupMutex.Lock()
defer cleanupMutex.Unlock()
cleanup = append(cleanup, f)
}
func doCleanup() {
cleanupMutex.Lock()
defer cleanupMutex.Unlock()
for _, f := range cleanup {
if err := f(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
}