2022-05-14 17:54:35 +00:00
package fs
2022-05-13 14:21:47 +00:00
import (
"fmt"
2023-05-26 09:35:13 +00:00
"path"
"time"
2022-05-13 14:21:47 +00:00
2023-05-26 09:35:13 +00:00
"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/filer"
2022-05-13 14:21:47 +00:00
"github.com/spf13/cobra"
)
2023-05-26 09:35:13 +00:00
func parseFileInfo ( info filer . FileInfo , parentDir string , isAbsolute bool ) map [ string ] string {
fullName := info . Name
if isAbsolute {
fullName = path . Join ( parentDir , info . Name )
}
return map [ string ] string {
"Name" : fullName ,
"ModTime" : info . ModTime . UTC ( ) . Format ( time . UnixDate ) ,
"Size" : fmt . Sprint ( info . Size ) ,
"Type" : info . Type ,
}
}
2022-05-13 14:21:47 +00:00
// lsCmd represents the ls command
var lsCmd = & cobra . Command {
2023-05-26 09:35:13 +00:00
Use : "ls <dir-name>" ,
Short : "Lists files" ,
Long : ` Lists files in a DBFS or WSFS directory ` ,
Args : cobra . MaximumNArgs ( 1 ) ,
Annotations : map [ string ] string { } ,
PreRunE : root . MustWorkspaceClient ,
2022-09-16 09:06:58 +00:00
2023-04-11 14:59:27 +00:00
RunE : func ( cmd * cobra . Command , args [ ] string ) error {
2023-05-26 09:35:13 +00:00
// Assign template according to whether -l is specified
template := cmdio . Heredoc ( `
{ { range . } } { { . Name } }
{ { end } }
` )
if longMode {
template = cmdio . Heredoc ( `
{ { range . } } { { . Type | printf "%-10s" } } { { . Size } } { { . ModTime } } { { . Name } }
{ { end } }
` )
}
// Path to list files from. Defaults to`/`
path := "/"
if len ( args ) > 0 {
path = args [ 0 ]
}
// Initialize workspace client
ctx := cmd . Context ( )
w := root . WorkspaceClient ( ctx )
f , err := filer . NewWorkspaceFilesClient ( w , path )
if err != nil {
return err
}
// Get file info
filesInfo , err := f . ReadDir ( ctx , "" )
if err != nil {
return err
}
// Parse it so it's ready to be rendered
output := make ( [ ] map [ string ] string , 0 )
for _ , info := range filesInfo {
output = append ( output , parseFileInfo ( info , path , absolute ) )
}
return cmdio . RenderWithTemplate ( ctx , output , template )
2022-05-13 14:21:47 +00:00
} ,
}
2023-05-26 09:35:13 +00:00
var longMode bool
var absolute bool
2022-05-13 14:21:47 +00:00
func init ( ) {
2023-05-26 09:35:13 +00:00
lsCmd . Flags ( ) . BoolVarP ( & longMode , "long" , "l" , false , "Displays full information including size, file type and modification time since Epoch in milliseconds." )
lsCmd . Flags ( ) . BoolVar ( & absolute , "absolute" , false , "Displays absolute paths." )
2022-05-13 14:21:47 +00:00
fsCmd . AddCommand ( lsCmd )
}