]> Sergey Matveev's repositories - btrtrc.git/blob - cmd/torrent-metainfo-pprint/main.go
c6ab27ec88eb1468e20ac324e24a2e1dc745c751
[btrtrc.git] / cmd / torrent-metainfo-pprint / main.go
1 package main
2
3 import (
4         "bufio"
5         "encoding/hex"
6         "encoding/json"
7         "fmt"
8         "io"
9         "log"
10         "os"
11
12         "github.com/anacrolix/envpprof"
13         "github.com/anacrolix/tagflag"
14         "github.com/bradfitz/iter"
15
16         "github.com/anacrolix/torrent/metainfo"
17 )
18
19 var flags struct {
20         JustName    bool
21         PieceHashes bool
22         Files       bool
23         tagflag.StartPos
24 }
25
26 func processReader(r io.Reader) error {
27         metainfo, err := metainfo.Load(r)
28         if err != nil {
29                 return err
30         }
31         info, err := metainfo.UnmarshalInfo()
32         if err != nil {
33                 return fmt.Errorf("error unmarshalling info: %s", err)
34         }
35         if flags.JustName {
36                 fmt.Printf("%s\n", info.Name)
37                 return nil
38         }
39         d := map[string]interface{}{
40                 "Name":         info.Name,
41                 "NumPieces":    info.NumPieces(),
42                 "PieceLength":  info.PieceLength,
43                 "InfoHash":     metainfo.HashInfoBytes().HexString(),
44                 "NumFiles":     len(info.UpvertedFiles()),
45                 "TotalLength":  info.TotalLength(),
46                 "Announce":     metainfo.Announce,
47                 "AnnounceList": metainfo.AnnounceList,
48                 "UrlList":      metainfo.UrlList,
49         }
50         if len(metainfo.Nodes) >  0 {
51                 d["Nodes"] = metainfo.Nodes
52         }
53         if flags.Files {
54                 d["Files"] = info.UpvertedFiles()
55         }
56         if flags.PieceHashes {
57                 d["PieceHashes"] = func() (ret []string) {
58                         for i := range iter.N(info.NumPieces()) {
59                                 ret = append(ret, hex.EncodeToString(info.Pieces[i*20:(i+1)*20]))
60                         }
61                         return
62                 }()
63         }
64         b, _ := json.MarshalIndent(d, "", "  ")
65         _, err = os.Stdout.Write(b)
66         return err
67 }
68
69 func main() {
70         defer envpprof.Stop()
71         tagflag.Parse(&flags)
72         err := processReader(bufio.NewReader(os.Stdin))
73         if err != nil {
74                 log.Fatal(err)
75         }
76         if !flags.JustName {
77                 os.Stdout.WriteString("\n")
78         }
79 }