Skip to content

Commit

Permalink
Issue #175: Add '--read-only' flag
Browse files Browse the repository at this point in the history
  • Loading branch information
F1bonacc1 committed May 6, 2024
1 parent 1f2fd35 commit 7188be7
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 11 deletions.
6 changes: 5 additions & 1 deletion src/cmd/project_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ func startTui(runner app.IProject) {
tuiOptions := []tui.Option{
tui.WithRefreshRate(time.Duration(*pcFlags.RefreshRate) * time.Second),
}
if !*pcFlags.IsReadOnlyMode {
config.CreateProcCompHome()
}
settings := config.NewSettings().Load()

tuiOptions = append(tuiOptions,
Expand All @@ -92,7 +95,8 @@ func startTui(runner app.IProject) {
tuiOptions = append(tuiOptions,
ternary(pcFlags.SortColumnChanged,
tui.WithStateSorter(getColumnId(*pcFlags.SortColumn), !*pcFlags.IsReverseSort),
tui.WithStateSorter(getColumnId(settings.Sort.By), !settings.Sort.IsReversed)))
tui.WithStateSorter(getColumnId(settings.Sort.By), !settings.Sort.IsReversed)),
tui.WithReadOnlyMode(*pcFlags.IsReadOnlyMode))

tui.SetupTui(runner, tuiOptions...)
}
Expand Down
3 changes: 2 additions & 1 deletion src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func init() {
nsAdmitter := &admitter.NamespaceAdmitter{}
opts.AddAdmitter(nsAdmitter)

rootCmd.Flags().BoolVarP(pcFlags.Headless, "tui", "t", *pcFlags.Headless, "enable TUI (-t=false) (env: "+config.EnvVarNameTui+")")
rootCmd.Flags().BoolVarP(pcFlags.Headless, "tui", "t", *pcFlags.Headless, "enable TUI (disable with -t=false) (env: "+config.EnvVarNameTui+")")
rootCmd.PersistentFlags().BoolVar(pcFlags.KeepTuiOn, "keep-tui", *pcFlags.KeepTuiOn, "keep TUI running even after all processes exit")
rootCmd.PersistentFlags().BoolVar(pcFlags.NoServer, "no-server", *pcFlags.NoServer, "disable HTTP server (env: "+config.EnvVarNameNoServer+")")
rootCmd.PersistentFlags().BoolVar(pcFlags.IsOrderedShutDown, "ordered-shutdown", *pcFlags.IsOrderedShutDown, "shut down processes in reverse dependency order")
Expand All @@ -77,6 +77,7 @@ func init() {
rootCmd.Flags().StringArrayVarP(&opts.FileNames, "config", "f", config.GetConfigDefault(), "path to config files to load (env: "+config.EnvVarNameConfig+")")
rootCmd.Flags().StringArrayVarP(&nsAdmitter.EnabledNamespaces, "namespace", "n", nil, "run only specified namespaces (default all)")
rootCmd.PersistentFlags().StringVarP(pcFlags.LogFile, "log-file", "L", *pcFlags.LogFile, "Specify the log file path (env: "+config.LogPathEnvVarName+")")
rootCmd.PersistentFlags().BoolVar(pcFlags.IsReadOnlyMode, "read-only", *pcFlags.IsReadOnlyMode, "enable read-only mode (env: "+config.EnvVarReadOnlyMode+")")
rootCmd.Flags().AddFlag(commonFlags.Lookup(flagReverse))
rootCmd.Flags().AddFlag(commonFlags.Lookup(flagSort))
rootCmd.Flags().AddFlag(commonFlags.Lookup(flagTheme))
Expand Down
3 changes: 3 additions & 0 deletions src/config/Flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const (
EnvVarNameConfig = "PC_CONFIG_FILES"
EnvVarNameNoServer = "PC_NO_SERVER"
EnvVarUnixSocketPath = "PC_SOCKET_PATH"
EnvVarReadOnlyMode = "PC_READ_ONLY"
)

// Flags represents PC configuration flags.
Expand Down Expand Up @@ -60,6 +61,7 @@ type Flags struct {
PcThemeChanged bool
UnixSocketPath *string
IsUnixSocket *bool
IsReadOnlyMode *bool
}

// NewFlags returns new configuration flags.
Expand All @@ -84,6 +86,7 @@ func NewFlags() *Flags {
PcTheme: toPtr(DefaultThemeName),
UnixSocketPath: toPtr(""),
IsUnixSocket: toPtr(false),
IsReadOnlyMode: toPtr(getReadOnlyDefault()),
}
}

Expand Down
45 changes: 40 additions & 5 deletions src/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const (
LogFileMode = os.FileMode(0600)
themeFileName = "theme.yaml"
settingsFileName = "settings.yaml"
configHome = "process-compose"
)

var (
Expand Down Expand Up @@ -88,20 +89,41 @@ func GetConfigDefault() []string {
return []string{}
}

func procCompHome() string {
func CreateProcCompHome() string {
if env := os.Getenv(pcConfigEnv); env != "" {
return env
}
xdgPcHome, err := xdg.ConfigFile("process-compose")
xdgPcHome, err := xdg.ConfigFile(configHome)
if err != nil {
log.Fatal().Err(err).Msg("Unable to create configuration directory")
}

err = os.MkdirAll(xdgPcHome, 0700)
if err != nil {
log.Fatal().Err(err).Msg("Unable to create configuration directory for process compose")
}

return xdgPcHome
}

func getProcConfigDir() string {
if env := os.Getenv(pcConfigEnv); env != "" {
return env
}
xdgPcHome, err := xdg.SearchConfigFile(configHome)
if err != nil {
log.Warn().Err(err).Msg("Path not found for process compose config home")
}
return xdgPcHome
}

func GetShortCutsPath() string {
pcHome := getProcConfigDir()
if pcHome == "" {
return ""
}
for _, path := range scFiles {
scPath := filepath.Join(procCompHome(), path)
scPath := filepath.Join(pcHome, path)
if _, err := os.Stat(scPath); err == nil {
return scPath
}
Expand All @@ -110,12 +132,20 @@ func GetShortCutsPath() string {
}

func GetThemesPath() string {
themePath := filepath.Join(procCompHome(), themeFileName)
pcHome := getProcConfigDir()
if pcHome == "" {
return ""
}
themePath := filepath.Join(pcHome, themeFileName)
return themePath
}

func GetSettingsPath() string {
settingsPath := filepath.Join(procCompHome(), settingsFileName)
pcHome := getProcConfigDir()
if pcHome == "" {
return ""
}
settingsPath := filepath.Join(pcHome, settingsFileName)
return settingsPath
}

Expand Down Expand Up @@ -163,3 +193,8 @@ func GetUnixSocketPath() string {
}
return filepath.Join(os.TempDir(), fmt.Sprintf("process-compose-%d.sock", os.Getpid()))
}

func getReadOnlyDefault() bool {
_, found := os.LookupEnv(EnvVarReadOnlyMode)
return found
}
8 changes: 8 additions & 0 deletions src/config/themes.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"errors"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v3"
"os"
Expand All @@ -12,6 +13,10 @@ const (
CustomStyleName = "Custom Style"
)

var (
errThemeNotFound = errors.New("custom theme not found")
)

// Themes represents a list of styles.
type Themes struct {
styles []*Styles
Expand Down Expand Up @@ -56,6 +61,9 @@ func NewThemes() *Themes {

func (t *Themes) loadFromFile() (*Styles, error) {
filePath := GetThemesPath()
if filePath == "" || !fileExists(filePath) {
return nil, errThemeNotFound
}
b, err := os.ReadFile(filePath)
if err != nil {
log.Warn().Err(err).Msgf("Error reading themes file %s", filePath)
Expand Down
2 changes: 1 addition & 1 deletion src/tui/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ func (a Action) writeToggleButton(w io.Writer, state bool, style config.Help) {
a.ToggleDescription[state])
}

func getDefaultActions() *ShortCuts {
func newShortCuts() *ShortCuts {
sc := &ShortCuts{
ShortCutKeys: map[ActionName]*Action{
ActionLogScreen: {
Expand Down
7 changes: 7 additions & 0 deletions src/tui/tui_option.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@ func WithTheme(theme string) Option {
return nil
}
}

func WithReadOnlyMode(isReadOnly bool) Option {
return func(view *pcView) error {
view.isReadOnlyMode = isReadOnly
return nil
}
}
15 changes: 12 additions & 3 deletions src/tui/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ type pcView struct {
helpDialog *helpDialog
settings *config.Settings
isFullScreen bool
isReadOnlyMode bool
}

func newPcView(project app.IProject) *pcView {
Expand All @@ -89,7 +90,6 @@ func newPcView(project app.IProject) *pcView {
scrSplitState: LogProcHalf,
helpText: tview.NewTextView().SetDynamicColors(true),
loggedProc: "",
shortcuts: getDefaultActions(),
procCountCell: tview.NewTableCell(""),
mainGrid: tview.NewGrid(),
logsTextArea: tview.NewTextArea(),
Expand All @@ -102,8 +102,11 @@ func newPcView(project app.IProject) *pcView {
},
procColumns: map[ColumnID]string{},
selectedNs: AllNS,
themes: config.NewThemes(),
settings: config.NewSettings(),

// configuration
shortcuts: newShortCuts(),
themes: config.NewThemes(),
settings: config.NewSettings(),
}
pv.ctxApp, pv.cancelAppFn = context.WithCancel(context.Background())
pv.statTable = pv.createStatTable()
Expand Down Expand Up @@ -400,12 +403,18 @@ func (pv *pcView) updateHelpTextView() {
}

func (pv *pcView) saveTuiState() {
if pv.isReadOnlyMode {
log.Debug().Msg("Not saving TUI state in read-only mode")
return
}
pv.settings.Sort.By = columnNames[pv.stateSorter.sortByColumn]
pv.settings.Sort.IsReversed = !pv.stateSorter.isAsc
pv.settings.Theme = pv.styles.GetStyleName()
err := pv.settings.Save()
if err != nil {
log.Error().Err(err).Msg("Failed to save settings")
} else {
log.Debug().Msg("Saved TUI state")
}
}

Expand Down

0 comments on commit 7188be7

Please sign in to comment.