12 "github.com/anacrolix/missinggo/slices"
15 // The info dictionary.
17 PieceLength int64 `bencode:"piece length"`
18 Pieces []byte `bencode:"pieces"`
19 Name string `bencode:"name"`
20 Length int64 `bencode:"length,omitempty"`
21 Private *bool `bencode:"private,omitempty"`
22 Files []FileInfo `bencode:"files,omitempty"`
25 // This is a helper that sets Files and Pieces from a root path and its
27 func (info *Info) BuildFromFilePath(root string) (err error) {
28 info.Name = filepath.Base(root)
30 err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
35 // Directories are implicit in torrent files.
37 } else if path == root {
38 // The root is a file.
39 info.Length = fi.Size()
42 relPath, err := filepath.Rel(root, path)
44 return fmt.Errorf("error getting relative path: %s", err)
46 info.Files = append(info.Files, FileInfo{
47 Path: strings.Split(relPath, string(filepath.Separator)),
55 slices.Sort(info.Files, func(l, r FileInfo) bool {
56 return strings.Join(l.Path, "/") < strings.Join(r.Path, "/")
58 err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
59 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
62 err = fmt.Errorf("error generating pieces: %s", err)
67 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
68 for _, fi := range info.UpvertedFiles() {
71 return fmt.Errorf("error opening %v: %s", fi, err)
73 wn, err := io.CopyN(w, r, fi.Length)
75 if wn != fi.Length || err != nil {
76 return fmt.Errorf("error hashing %v: %s", fi, err)
82 // Set info.Pieces by hashing info.Files.
83 func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) error {
84 if info.PieceLength == 0 {
85 return errors.New("piece length must be non-zero")
89 err := info.writeFiles(pw, open)
90 pw.CloseWithError(err)
96 wn, err := io.CopyN(hasher, pr, info.PieceLength)
106 pieces = hasher.Sum(pieces)
107 if wn < info.PieceLength {
115 func (info *Info) TotalLength() (ret int64) {
117 for _, fi := range info.Files {
126 func (info *Info) NumPieces() int {
127 if len(info.Pieces)%20 != 0 {
128 panic(len(info.Pieces))
130 return len(info.Pieces) / 20
133 func (info *Info) IsDir() bool {
134 return len(info.Files) != 0
137 // The files field, converted up from the old single-file in the parent info
138 // dict if necessary. This is a helper to avoid having to conditionally handle
139 // single and multi-file torrent infos.
140 func (info *Info) UpvertedFiles() []FileInfo {
141 if len(info.Files) == 0 {
144 // Callers should determine that Info.Name is the basename, and
145 // thus a regular file.
152 func (info *Info) Piece(index int) Piece {
153 return Piece{info, index}