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 {
Init(home string)
Init(filePath string, persist bool)
Close()
// Gets the value for a given key.
// Returns the value and a boolean indicating if the key was found.
@ -27,9 +27,9 @@ const (
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")
if len(pid) == 0 {
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
cacheFilePath string
dirty bool
persist bool
}
func (fc *File) Init(cacheFilePath string) {
func (fc *File) Init(cacheFilePath string, persist bool) {
defer log.Trace(time.Now(), cacheFilePath)
fc.cache = maps.NewConcurrent()
fc.cacheFilePath = cacheFilePath
fc.persist = persist
log.Debug("loading cache file:", fc.cacheFilePath)
@ -47,14 +49,14 @@ func (fc *File) Init(cacheFilePath string) {
}
func (fc *File) Close() {
if !fc.dirty {
if !fc.persist || !fc.dirty {
return
}
cache := fc.cache.ToSimple()
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"
// Cache is an autogenerated mock type for the cache type
type Cache struct {
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() {
_m.Called()
}
// get provides a mock function with given fields: key
func (_m *Cache) Get(key string) (string, bool) {
ret := _m.Called(key)
@ -33,17 +34,10 @@ func (_m *Cache) Get(key string) (string, bool) {
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) {
_m.Called(key, value, ttl)
}
// delete provides a mock function with given fields: key
func (_m *Cache) Delete(key string) {
_m.Called(key)
}

View file

@ -21,6 +21,7 @@ var (
cleared bool
cached bool
jobCount int
saveCache bool
command string
shellVersion string
@ -76,6 +77,7 @@ func createPrintCmd() *cobra.Command {
NoExitCode: noStatus,
Column: column,
JobCount: jobCount,
SaveCache: saveCache,
}
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().IntVar(&column, "column", 0, "the column position of the cursor")
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.
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("no-exit-code")
_ = printCmd.Flags().MarkHidden("cached")
_ = printCmd.Flags().MarkHidden("save-cache")
return printCmd
}

View file

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

View file

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

View file

@ -67,12 +67,13 @@ func (term *Terminal) Init() {
initCache := func(fileName string) *cache.File {
cache := &cache.File{}
cache.Init(filepath.Join(term.CachePath(), fileName))
cache.Init(filepath.Join(term.CachePath(), fileName), term.CmdFlags.SaveCache)
return cache
}
term.deviceCache = initCache(cache.FileName)
term.sessionCache = initCache(cache.SessionFileName)
term.setPromptCount()
term.ResolveConfigPath()
@ -81,8 +82,6 @@ func (term *Terminal) Init() {
}
term.tmplCache = &cache.Template{}
term.SetPromptCount()
}
func (term *Terminal) ResolveConfigPath() {
@ -737,27 +736,20 @@ func dirMatchesOneOf(dir, home, goos string, regexes []string) bool {
return false
}
func (term *Terminal) SetPromptCount() {
func (term *Terminal) setPromptCount() {
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
if val, found := term.Session().Get(cache.PROMPTCOUNTCACHE); found {
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 {
count++
term.Session().Set(cache.PROMPTCOUNTCACHE, strconv.Itoa(count), 1440)
}
term.CmdFlags.PromptCount = count
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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