]> Sergey Matveev's repositories - btrtrc.git/blob - cmd/torrent-metainfo-pprint/main.go
goimports -local
[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 flags.Files {
51                 d["Files"] = info.UpvertedFiles()
52         }
53         if flags.PieceHashes {
54                 d["PieceHashes"] = func() (ret []string) {
55                         for i := range iter.N(info.NumPieces()) {
56                                 ret = append(ret, hex.EncodeToString(info.Pieces[i*20:(i+1)*20]))
57                         }
58                         return
59                 }()
60         }
61         b, _ := json.MarshalIndent(d, "", "  ")
62         _, err = os.Stdout.Write(b)
63         return err
64 }
65
66 func main() {
67         defer envpprof.Stop()
68         tagflag.Parse(&flags)
69         err := processReader(bufio.NewReader(os.Stdin))
70         if err != nil {
71                 log.Fatal(err)
72         }
73         if !flags.JustName {
74                 os.Stdout.WriteString("\n")
75         }
76 }