Add filtersAdd() and the code that uses it to swarmFiltersAddCmd.Run()
License: MIT Signed-off-by: Yuval Langer <yuval.langer@gmail.com>
Yuval Langer committed
Jun 20, 2016 at 23:24 UTC
bd9b31203959b464744d9daaf4df8b62706b1cb1
1 file changed
+65
core/commands/swarm.go
+65
@@ -9,6 +9,9 @@ import (
9
"sort"
10
11
cmds "github.com/ipfs/go-ipfs/commands"
12
+ repo "github.com/ipfs/go-ipfs/repo"
13
+ config "github.com/ipfs/go-ipfs/repo/config"
14
+ "github.com/ipfs/go-ipfs/repo/fsrepo"
15
iaddr "github.com/ipfs/go-ipfs/thirdparty/ipfsaddr"
16
pstore "gx/ipfs/QmXHUpFsnpCmanRnacqYkFoLoFfEq5yS2nUgGkAjJ1Nj9j/go-libp2p-peerstore"
17
swarm "gx/ipfs/QmdBpVuSYuTGDA8Kn66CbKvEThXqKUh2nTANZEhzSxqrmJ/go-libp2p/p2p/net/swarm"
@@ -458,6 +461,23 @@ add your filters to the ipfs config file.
461
return
462
}
463
464
+ r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
465
+ if err != nil {
466
+ res.SetError(err, cmds.ErrNormal)
467
+ return
468
+ }
469
+ defer r.Close()
470
+ cfg, err := r.Config()
471
+ if err != nil {
472
+ res.SetError(err, cmds.ErrNormal)
473
+ return
474
+ }
475
+
476
+ if len(req.Arguments()) == 0 {
477
+ res.SetError(errors.New("no filters to add"), cmds.ErrClient)
478
+ return
479
+ }
480
+
481
for _, arg := range req.Arguments() {
482
mask, err := mafilter.NewMask(arg)
483
if err != nil {
@@ -467,6 +487,15 @@ add your filters to the ipfs config file.
487
488
snet.Filters.AddDialFilter(mask)
489
}
490
+
491
+ added, err := filtersAdd(r, cfg, req.Arguments())
492
+ if err != nil {
493
+ res.SetError(err, cmds.ErrNormal)
494
+ return
495
+
496
+ }
497
+
498
+ res.SetOutput(&stringList{added})
499
},
500
}
501
@@ -519,3 +548,39 @@ remove your filters from the ipfs config file.
548
}
549
},
550
}
551
+
552
+func filtersAdd(r repo.Repo, cfg *config.Config, filters []string) ([]string, error) {
553
+ addedMap := map[string]struct{}{}
554
+ addedList := make([]string, 0, len(filters))
555
+
556
+ // re-add cfg swarm filters to rm dupes
557
+ oldFilters := cfg.Swarm.AddrFilters
558
+ cfg.Swarm.AddrFilters = nil
559
+
560
+ // add new filters
561
+ for _, filter := range filters {
562
+ if _, found := addedMap[filter]; found {
563
+ continue
564
+ }
565
+
566
+ cfg.Swarm.AddrFilters = append(cfg.Swarm.AddrFilters, filter)
567
+ addedList = append(addedList, filter)
568
+ addedMap[filter] = struct{}{}
569
+ }
570
+
571
+ // add back original filters. in this order so that we output them.
572
+ for _, filter := range oldFilters {
573
+ if _, found := addedMap[filter]; found {
574
+ continue
575
+ }
576
+
577
+ cfg.Swarm.AddrFilters = append(cfg.Swarm.AddrFilters, filter)
578
+ addedMap[filter] = struct{}{}
579
+ }
580
+
581
+ if err := r.SetConfig(cfg); err != nil {
582
+ return nil, err
583
+ }
584
+
585
+ return addedList, nil
586
+}