gum/file/command.go

73 lines
1.5 KiB
Go
Raw Normal View History

2022-10-01 00:40:10 +02:00
package file
import (
"errors"
2022-10-01 00:40:10 +02:00
"fmt"
"os"
"path/filepath"
2023-06-30 15:22:45 +02:00
"github.com/charmbracelet/gum/internal/exit"
"github.com/charmbracelet/bubbles/filepicker"
2022-10-01 00:40:10 +02:00
tea "github.com/charmbracelet/bubbletea"
)
// Run is the interface to picking a file.
func (o Options) Run() error {
if !o.File && !o.Directory {
return errors.New("at least one between --file and --directory must be set")
}
2022-10-01 00:40:10 +02:00
if o.Path == "" {
o.Path = "."
}
path, err := filepath.Abs(o.Path)
if err != nil {
return fmt.Errorf("file not found: %w", err)
2022-10-01 00:40:10 +02:00
}
fp := filepicker.New()
fp.CurrentDirectory = path
fp.Path = path
fp.Height = o.Height
fp.AutoHeight = o.Height == 0
fp.Cursor = o.Cursor
fp.DirAllowed = o.Directory
fp.FileAllowed = o.File
fp.ShowHidden = o.All
2023-05-31 20:07:00 +02:00
fp.Styles = filepicker.DefaultStyles()
fp.Styles.Cursor = o.CursorStyle.ToLipgloss()
fp.Styles.Symlink = o.SymlinkStyle.ToLipgloss()
fp.Styles.Directory = o.DirectoryStyle.ToLipgloss()
fp.Styles.File = o.FileStyle.ToLipgloss()
fp.Styles.Permission = o.PermissionsStyle.ToLipgloss()
fp.Styles.Selected = o.SelectedStyle.ToLipgloss()
fp.Styles.FileSize = o.FileSizeStyle.ToLipgloss()
2022-10-01 00:40:10 +02:00
2023-06-30 15:22:45 +02:00
m := model{
filepicker: fp,
timeout: o.Timeout,
hasTimeout: o.Timeout > 0,
aborted: false,
}
2022-10-18 02:23:59 +02:00
tm, err := tea.NewProgram(&m, tea.WithOutput(os.Stderr)).Run()
2022-10-01 00:40:10 +02:00
if err != nil {
return fmt.Errorf("unable to pick selection: %w", err)
2022-10-01 00:40:10 +02:00
}
m = tm.(model)
if m.aborted {
return exit.ErrAborted
}
2022-10-01 00:40:10 +02:00
if m.selectedPath == "" {
2022-10-01 00:40:10 +02:00
os.Exit(1)
}
fmt.Println(m.selectedPath)
2022-10-01 00:40:10 +02:00
return nil
}