1package cmd
 2
 3import (
 4	"fmt"
 5	"path/filepath"
 6	"strings"
 7
 8	"github.com/charmbracelet/soft-serve/git"
 9	gitwish "github.com/charmbracelet/wish/git"
10	"github.com/spf13/cobra"
11)
12
13// ListCommand returns a command that list file or directory at path.
14func ListCommand() *cobra.Command {
15	lsCmd := &cobra.Command{
16		Use:     "ls PATH",
17		Aliases: []string{"list"},
18		Short:   "List file or directory at path.",
19		Args:    cobra.RangeArgs(0, 1),
20		RunE: func(cmd *cobra.Command, args []string) error {
21			ac, s := fromContext(cmd)
22			rn := ""
23			path := ""
24			ps := []string{}
25			if len(args) > 0 {
26				path = filepath.Clean(args[0])
27				ps = strings.Split(path, "/")
28				rn = ps[0]
29				auth := ac.AuthRepo(rn, s.PublicKey())
30				if auth < gitwish.ReadOnlyAccess {
31					return ErrUnauthorized
32				}
33			}
34			if path == "" || path == "." || path == "/" {
35				for _, r := range ac.Source.AllRepos() {
36					fmt.Fprintln(s, r.Name())
37				}
38				return nil
39			}
40			r, err := ac.Source.GetRepo(rn)
41			if err != nil {
42				return err
43			}
44			head, err := r.HEAD()
45			if err != nil {
46				return err
47			}
48			tree, err := r.Tree(head, "")
49			if err != nil {
50				return err
51			}
52			subpath := strings.Join(ps[1:], "/")
53			ents := git.Entries{}
54			te, err := tree.TreeEntry(subpath)
55			if err == git.ErrRevisionNotExist {
56				return ErrFileNotFound
57			}
58			if err != nil {
59				return err
60			}
61			if te.Type() == "tree" {
62				tree, err = tree.SubTree(subpath)
63				if err != nil {
64					return err
65				}
66				ents, err = tree.Entries()
67				if err != nil {
68					return err
69				}
70			} else {
71				ents = append(ents, te)
72			}
73			ents.Sort()
74			for _, ent := range ents {
75				fmt.Fprintf(s, "%s\t%d\t %s\n", ent.Mode(), ent.Size(), ent.Name())
76			}
77			return nil
78		},
79	}
80	return lsCmd
81}