Skip to content
This repository has been archived by the owner on Oct 5, 2023. It is now read-only.

Commit

Permalink
unixfs: updated ls
Browse files Browse the repository at this point in the history
  • Loading branch information
magik6k committed Feb 4, 2019
1 parent 7bea2ef commit bb8d9d1
Showing 1 changed file with 75 additions and 19 deletions.
94 changes: 75 additions & 19 deletions unixfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (

"github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipld-format"
unixfspb "github.com/ipfs/go-unixfs/pb"
mh "github.com/multiformats/go-multihash"
)

Expand Down Expand Up @@ -129,7 +128,7 @@ loop:
type lsLink struct {
Name, Hash string
Size uint64
Type unixfspb.Data_DataType
Type iface.FileType
}

type lsObject struct {
Expand All @@ -141,30 +140,87 @@ type lsOutput struct {
Objects []lsObject
}

func (api *UnixfsAPI) Ls(ctx context.Context, p iface.Path) ([]*format.Link, error) {
var out lsOutput
err := api.core().request("ls", p.String()).Exec(ctx, &out)
func (api *UnixfsAPI) Ls(ctx context.Context, p iface.Path, opts ...caopts.UnixfsLsOption) (<-chan iface.LsLink, error) {
options, err := caopts.UnixfsLsOptions(opts...)
if err != nil {
return nil, err
}

if len(out.Objects) != 1 {
return nil, errors.New("unexpected objects len")
resp, err := api.core().request("ls", p.String()).
Option("resolve-type", options.ResolveChildren).
Option("size", options.ResolveChildren).
Option("stream", true).
Send(ctx)
if err != nil {
return nil, err
}
if resp.Error != nil {
return nil, resp.Error
}

links := make([]*format.Link, len(out.Objects[0].Links))
for i, l := range out.Objects[0].Links {
c, err := cid.Parse(l.Hash)
if err != nil {
return nil, err
}
links[i] = &format.Link{
Name: l.Name,
Size: l.Size,
Cid: c,
dec := json.NewDecoder(resp.Output)
out := make(chan iface.LsLink)

go func() {
defer resp.Close()
defer close(out)

for {
var link lsOutput
if err := dec.Decode(&link); err != nil {
if err == io.EOF {
return
}
select {
case out <- iface.LsLink{Err: err}:
case <-ctx.Done():
}
return
}

if len(link.Objects) != 1 {
select {
case out <- iface.LsLink{Err: errors.New("unexpected Objects len")}:
case <-ctx.Done():
}
return
}

if len(link.Objects[0].Links) != 1 {
select {
case out <- iface.LsLink{Err: errors.New("unexpected Links len")}:
case <-ctx.Done():
}
return
}

l0 := link.Objects[0].Links[0]

c, err := cid.Decode(l0.Hash)
if err != nil {
select {
case out <- iface.LsLink{Err: err}:
case <-ctx.Done():
}
return
}

select {
case out <- iface.LsLink{
Link: &format.Link{
Cid: c,
Name: l0.Name,
Size: l0.Size,
},
Size: l0.Size,
Type: l0.Type,
}:
case <-ctx.Done():
}
}
}
return links, nil
}()

return out, nil
}

func (api *UnixfsAPI) core() *HttpApi {
Expand Down

0 comments on commit bb8d9d1

Please sign in to comment.