From 25c2f037cbb1b561071cbf49707de2b0cbe565de Mon Sep 17 00:00:00 2001 From: Alexey Yerin Date: Wed, 19 Aug 2020 23:05:50 +0300 Subject: [PATCH] Export options as environment variables (#448) * Export options as environment variables Any options from gOpts are available via lf_OPTION environment variables. For now it works only on booleans, integers and strings (no array support) * Do not export some of the options * Add support for arrays and fix numbers * Fix comments * Replace 1 and 0 with true and false * Export hidden,reverse,dirfirst and sortby options * Fix comments * Little fix * Simplify boolean conversion --- app.go | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/app.go b/app.go index 52850e1..410ebaf 100644 --- a/app.go +++ b/app.go @@ -9,6 +9,8 @@ import ( "os/exec" "os/signal" "path/filepath" + "reflect" + "strconv" "strings" "syscall" "time" @@ -333,6 +335,85 @@ func (app *app) exportFiles() { exportFiles(currFile, currSelections) } +func fieldToString(field reflect.Value) string { + kind := field.Kind() + var value string + + switch kind { + case reflect.Int: + value = strconv.Itoa(int(field.Int())) + case reflect.Bool: + value = strconv.FormatBool(field.Bool()) + case reflect.Slice: + for i := 0; i < field.Len(); i++ { + element := field.Index(i) + + if i == 0 { + value = fieldToString(element) + } else { + value += ":" + fieldToString(element) + } + } + default: + value = field.String() + } + + return value +} + +func (app *app) exportOpts() { + e := reflect.ValueOf(&gOpts).Elem() + + for i := 0; i < e.NumField(); i++ { + // Get name and prefix it with lf_ + name := e.Type().Field(i).Name + name = fmt.Sprintf("lf_%s", name) + + // Skip maps + if name == "lf_keys" || name == "lf_cmdkeys" || name == "lf_cmds" { + continue + } + + // Get string representation of the value + if name == "lf_sortType" { + var sortby string + + switch gOpts.sortType.method { + case naturalSort: + sortby = "natural" + case nameSort: + sortby = "name" + case sizeSort: + sortby = "size" + case timeSort: + sortby = "time" + case ctimeSort: + sortby = "ctime" + case atimeSort: + sortby = "atime" + case extSort: + sortby = "ext" + } + + os.Setenv("lf_sortby", sortby) + + reverse := strconv.FormatBool(gOpts.sortType.option&reverseSort != 0) + os.Setenv("lf_reverse", reverse) + + hidden := strconv.FormatBool(gOpts.sortType.option&hiddenSort != 0) + os.Setenv("lf_hidden", hidden) + + dirfirst := strconv.FormatBool(gOpts.sortType.option&dirfirstSort != 0) + os.Setenv("lf_dirfirst", dirfirst) + } else { + field := e.Field(i) + value := fieldToString(field) + + os.Setenv(name, value) + } + } +} + func waitKey() error { cmd := pauseCommand() @@ -356,6 +437,7 @@ func waitKey() error { // & No Yes No No No Do nothing func (app *app) runShell(s string, args []string, prefix string) { app.exportFiles() + app.exportOpts() cmd := shellCommand(s, args)