fix(cache): require saving explicitly

This commit is contained in:
L. Yeung 2024-09-17 03:16:44 +08:00 committed by Jan De Dobbeleer
parent 9ce9ed72bb
commit 68a1e89f29
15 changed files with 31 additions and 40 deletions

6
src/cache/cache.go vendored
View file

@ -10,7 +10,7 @@ import (
) )
type Cache interface { type Cache interface {
Init(home string) Init(filePath string, persist bool)
Close() Close()
// Gets the value for a given key. // Gets the value for a given key.
// Returns the value and a boolean indicating if the key was found. // Returns the value and a boolean indicating if the key was found.
@ -27,9 +27,9 @@ const (
FileName = "omp.cache" FileName = "omp.cache"
) )
var SessionFileName = fmt.Sprintf("%s.%s", FileName, pid()) var SessionFileName = fmt.Sprintf("%s.%s", FileName, sessionID())
func pid() string { func sessionID() string {
pid := os.Getenv("POSH_PID") pid := os.Getenv("POSH_PID")
if len(pid) == 0 { if len(pid) == 0 {
log.Debug("POSH_PID not set, using process pid") log.Debug("POSH_PID not set, using process pid")

8
src/cache/file.go vendored
View file

@ -13,13 +13,15 @@ type File struct {
cache *maps.Concurrent cache *maps.Concurrent
cacheFilePath string cacheFilePath string
dirty bool dirty bool
persist bool
} }
func (fc *File) Init(cacheFilePath string) { func (fc *File) Init(cacheFilePath string, persist bool) {
defer log.Trace(time.Now(), cacheFilePath) defer log.Trace(time.Now(), cacheFilePath)
fc.cache = maps.NewConcurrent() fc.cache = maps.NewConcurrent()
fc.cacheFilePath = cacheFilePath fc.cacheFilePath = cacheFilePath
fc.persist = persist
log.Debug("loading cache file:", fc.cacheFilePath) log.Debug("loading cache file:", fc.cacheFilePath)
@ -47,14 +49,14 @@ func (fc *File) Init(cacheFilePath string) {
} }
func (fc *File) Close() { func (fc *File) Close() {
if !fc.dirty { if !fc.persist || !fc.dirty {
return return
} }
cache := fc.cache.ToSimple() cache := fc.cache.ToSimple()
if dump, err := json.MarshalIndent(cache, "", " "); err == nil { if dump, err := json.MarshalIndent(cache, "", " "); err == nil {
_ = os.WriteFile(fc.cacheFilePath, dump, 0644) _ = os.WriteFile(fc.cacheFilePath, dump, 0o644)
} }
} }

View file

@ -2,17 +2,18 @@ package mock
import mock "github.com/stretchr/testify/mock" import mock "github.com/stretchr/testify/mock"
// Cache is an autogenerated mock type for the cache type
type Cache struct { type Cache struct {
mock.Mock mock.Mock
} }
// close provides a mock function with given fields: func (_m *Cache) Init(filePath string, persist bool) {
_m.Called(filePath, persist)
}
func (_m *Cache) Close() { func (_m *Cache) Close() {
_m.Called() _m.Called()
} }
// get provides a mock function with given fields: key
func (_m *Cache) Get(key string) (string, bool) { func (_m *Cache) Get(key string) (string, bool) {
ret := _m.Called(key) ret := _m.Called(key)
@ -33,17 +34,10 @@ func (_m *Cache) Get(key string) (string, bool) {
return r0, r1 return r0, r1
} }
// init provides a mock function with given fields: home
func (_m *Cache) Init(home string) {
_m.Called(home)
}
// set provides a mock function with given fields: key, value, ttl
func (_m *Cache) Set(key, value string, ttl int) { func (_m *Cache) Set(key, value string, ttl int) {
_m.Called(key, value, ttl) _m.Called(key, value, ttl)
} }
// delete provides a mock function with given fields: key
func (_m *Cache) Delete(key string) { func (_m *Cache) Delete(key string) {
_m.Called(key) _m.Called(key)
} }

View file

@ -21,6 +21,7 @@ var (
cleared bool cleared bool
cached bool cached bool
jobCount int jobCount int
saveCache bool
command string command string
shellVersion string shellVersion string
@ -76,6 +77,7 @@ func createPrintCmd() *cobra.Command {
NoExitCode: noStatus, NoExitCode: noStatus,
Column: column, Column: column,
JobCount: jobCount, JobCount: jobCount,
SaveCache: saveCache,
} }
eng := prompt.New(flags) eng := prompt.New(flags)
@ -120,6 +122,7 @@ func createPrintCmd() *cobra.Command {
printCmd.Flags().BoolVar(&eval, "eval", false, "output the prompt for eval") printCmd.Flags().BoolVar(&eval, "eval", false, "output the prompt for eval")
printCmd.Flags().IntVar(&column, "column", 0, "the column position of the cursor") printCmd.Flags().IntVar(&column, "column", 0, "the column position of the cursor")
printCmd.Flags().IntVar(&jobCount, "job-count", 0, "number of background jobs") printCmd.Flags().IntVar(&jobCount, "job-count", 0, "number of background jobs")
printCmd.Flags().BoolVar(&saveCache, "save-cache", false, "save updated cache to file")
// Deprecated flags, should be kept to avoid breaking CLI integration. // Deprecated flags, should be kept to avoid breaking CLI integration.
printCmd.Flags().IntVarP(&status, "error", "e", 0, "last exit code") printCmd.Flags().IntVarP(&status, "error", "e", 0, "last exit code")
@ -130,6 +133,7 @@ func createPrintCmd() *cobra.Command {
_ = printCmd.Flags().MarkHidden("error") _ = printCmd.Flags().MarkHidden("error")
_ = printCmd.Flags().MarkHidden("no-exit-code") _ = printCmd.Flags().MarkHidden("no-exit-code")
_ = printCmd.Flags().MarkHidden("cached") _ = printCmd.Flags().MarkHidden("cached")
_ = printCmd.Flags().MarkHidden("save-cache")
return printCmd return printCmd
} }

View file

@ -68,7 +68,6 @@ type Environment interface {
Connection(connectionType ConnectionType) (*Connection, error) Connection(connectionType ConnectionType) (*Connection, error)
TemplateCache() *cache.Template TemplateCache() *cache.Template
LoadTemplateCache() LoadTemplateCache()
SetPromptCount()
CursorPosition() (row, col int) CursorPosition() (row, col int)
SystemInfo() (*SystemInfo, error) SystemInfo() (*SystemInfo, error)
Debug(message string) Debug(message string)
@ -92,7 +91,6 @@ type Flags struct {
TerminalWidth int TerminalWidth int
Strict bool Strict bool
Debug bool Debug bool
Manual bool
Plain bool Plain bool
Primary bool Primary bool
HasTransient bool HasTransient bool
@ -101,6 +99,7 @@ type Flags struct {
NoExitCode bool NoExitCode bool
Column int Column int
JobCount int JobCount int
SaveCache bool
} }
type CommandError struct { type CommandError struct {

View file

@ -281,10 +281,6 @@ func (env *Environment) DirIsWritable(path string) bool {
return args.Bool(0) return args.Bool(0)
} }
func (env *Environment) SetPromptCount() {
_ = env.Called()
}
func (env *Environment) CursorPosition() (int, int) { func (env *Environment) CursorPosition() (int, int) {
args := env.Called() args := env.Called()
return args.Int(0), args.Int(1) return args.Int(0), args.Int(1)

View file

@ -67,12 +67,13 @@ func (term *Terminal) Init() {
initCache := func(fileName string) *cache.File { initCache := func(fileName string) *cache.File {
cache := &cache.File{} cache := &cache.File{}
cache.Init(filepath.Join(term.CachePath(), fileName)) cache.Init(filepath.Join(term.CachePath(), fileName), term.CmdFlags.SaveCache)
return cache return cache
} }
term.deviceCache = initCache(cache.FileName) term.deviceCache = initCache(cache.FileName)
term.sessionCache = initCache(cache.SessionFileName) term.sessionCache = initCache(cache.SessionFileName)
term.setPromptCount()
term.ResolveConfigPath() term.ResolveConfigPath()
@ -81,8 +82,6 @@ func (term *Terminal) Init() {
} }
term.tmplCache = &cache.Template{} term.tmplCache = &cache.Template{}
term.SetPromptCount()
} }
func (term *Terminal) ResolveConfigPath() { func (term *Terminal) ResolveConfigPath() {
@ -737,27 +736,20 @@ func dirMatchesOneOf(dir, home, goos string, regexes []string) bool {
return false return false
} }
func (term *Terminal) SetPromptCount() { func (term *Terminal) setPromptCount() {
defer term.Trace(time.Now()) defer term.Trace(time.Now())
countStr := os.Getenv("POSH_PROMPT_COUNT")
if len(countStr) > 0 {
// this counter is incremented by the shell
count, err := strconv.Atoi(countStr)
if err == nil {
term.CmdFlags.PromptCount = count
return
}
}
var count int var count int
if val, found := term.Session().Get(cache.PROMPTCOUNTCACHE); found { if val, found := term.Session().Get(cache.PROMPTCOUNTCACHE); found {
count, _ = strconv.Atoi(val) count, _ = strconv.Atoi(val)
} }
// only write to cache if we're the primary prompt
// Only update the count if we're generating a primary prompt.
if term.CmdFlags.Primary { if term.CmdFlags.Primary {
count++ count++
term.Session().Set(cache.PROMPTCOUNTCACHE, strconv.Itoa(count), 1440) term.Session().Set(cache.PROMPTCOUNTCACHE, strconv.Itoa(count), 1440)
} }
term.CmdFlags.PromptCount = count term.CmdFlags.PromptCount = count
} }

View file

@ -79,6 +79,7 @@ function _omp_get_primary() {
else else
prompt=$( prompt=$(
"$_omp_executable" print primary \ "$_omp_executable" print primary \
--save-cache \
--shell=bash \ --shell=bash \
--shell-version="$BASH_VERSION" \ --shell-version="$BASH_VERSION" \
--status="$_omp_status" \ --status="$_omp_status" \

View file

@ -39,6 +39,7 @@ fn _omp-after-command-hook {|m|
fn _omp_get_prompt {|type @arguments| fn _omp_get_prompt {|type @arguments|
$_omp_executable print $type ^ $_omp_executable print $type ^
--save-cache ^
--shell=elvish ^ --shell=elvish ^
--shell-version=$E:POSH_SHELL_VERSION ^ --shell-version=$E:POSH_SHELL_VERSION ^
--status=$_omp_status ^ --status=$_omp_status ^

View file

@ -29,6 +29,7 @@ function _omp_get_prompt
return return
end end
$_omp_executable print $argv[1] \ $_omp_executable print $argv[1] \
--save-cache \
--shell=fish \ --shell=fish \
--shell-version=$FISH_VERSION \ --shell-version=$FISH_VERSION \
--status=$_omp_status \ --status=$_omp_status \

View file

@ -144,6 +144,7 @@ local function get_posh_prompt(prompt_type, ...)
local command = table.concat({ local command = table.concat({
'print', 'print',
prompt_type, prompt_type,
'--save-cache',
'--shell=cmd', '--shell=cmd',
status_option(), status_option(),
no_status_option(), no_status_option(),

View file

@ -28,6 +28,7 @@ def --wrapped _omp_get_prompt [
( (
^$_omp_executable print $type ^$_omp_executable print $type
--save-cache
--shell=nu --shell=nu
$"--shell-version=($env.POSH_SHELL_VERSION)" $"--shell-version=($env.POSH_SHELL_VERSION)"
$"--status=($env.LAST_EXIT_CODE)" $"--status=($env.LAST_EXIT_CODE)"

View file

@ -240,6 +240,7 @@ New-Module -Name "oh-my-posh-core" -ScriptBlock {
$terminalWidth = Get-TerminalWidth $terminalWidth = Get-TerminalWidth
Invoke-Utf8Posh @( Invoke-Utf8Posh @(
"print", $Type "print", $Type
"--save-cache"
"--shell=$script:ShellName" "--shell=$script:ShellName"
"--shell-version=$script:PSVersion" "--shell-version=$script:PSVersion"
"--status=$script:ErrorCode" "--status=$script:ErrorCode"

View file

@ -15,6 +15,7 @@ if ( ! $?_omp_enabled ) alias precmd '
unset _omp_cmd_executed; unset _omp_cmd_executed;
@ _omp_stack_count = $#dirstack - 1; @ _omp_stack_count = $#dirstack - 1;
set prompt = "`$_omp_executable:q print primary set prompt = "`$_omp_executable:q print primary
--save-cache
--shell=tcsh --shell=tcsh
--shell-version=$tcsh --shell-version=$tcsh
--status=$_omp_status --status=$_omp_status

View file

@ -3,7 +3,6 @@ export POSH_SHELL_VERSION=$ZSH_VERSION
export POSH_PID=$$ export POSH_PID=$$
export POWERLINE_COMMAND='oh-my-posh' export POWERLINE_COMMAND='oh-my-posh'
export CONDA_PROMPT_MODIFIER=false export CONDA_PROMPT_MODIFIER=false
export POSH_PROMPT_COUNT=0
export ZLE_RPROMPT_INDENT=0 export ZLE_RPROMPT_INDENT=0
export OSTYPE=$OSTYPE export OSTYPE=$OSTYPE
@ -74,9 +73,6 @@ function _omp_precmd() {
_omp_pipestatus=("$_omp_status") _omp_pipestatus=("$_omp_status")
fi fi
count=$((POSH_PROMPT_COUNT + 1))
export POSH_PROMPT_COUNT=$count
set_poshcontext set_poshcontext
_omp_set_cursor_position _omp_set_cursor_position
@ -122,6 +118,7 @@ function _omp_get_prompt() {
local type=$1 local type=$1
local args=("${@[2,-1]}") local args=("${@[2,-1]}")
$_omp_executable print $type \ $_omp_executable print $type \
--save-cache \
--shell=zsh \ --shell=zsh \
--shell-version=$ZSH_VERSION \ --shell-version=$ZSH_VERSION \
--status=$_omp_status \ --status=$_omp_status \