Skip to content

Commit

Permalink
fix(cache): require saving explicitly
Browse files Browse the repository at this point in the history
  • Loading branch information
lewis-yeung authored and JanDeDobbeleer committed Sep 19, 2024
1 parent 9ce9ed7 commit 68a1e89
Show file tree
Hide file tree
Showing 15 changed files with 31 additions and 40 deletions.
6 changes: 3 additions & 3 deletions src/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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")
Expand Down
8 changes: 5 additions & 3 deletions src/cache/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
}
}

Expand Down
14 changes: 4 additions & 10 deletions src/cache/mock/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)
}
4 changes: 4 additions & 0 deletions src/cli/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ var (
cleared bool
cached bool
jobCount int
saveCache bool

command string
shellVersion string
Expand Down Expand Up @@ -76,6 +77,7 @@ func createPrintCmd() *cobra.Command {
NoExitCode: noStatus,
Column: column,
JobCount: jobCount,
SaveCache: saveCache,
}

eng := prompt.New(flags)
Expand Down Expand Up @@ -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")
Expand All @@ -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
}
3 changes: 1 addition & 2 deletions src/runtime/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -92,7 +91,6 @@ type Flags struct {
TerminalWidth int
Strict bool
Debug bool
Manual bool
Plain bool
Primary bool
HasTransient bool
Expand All @@ -101,6 +99,7 @@ type Flags struct {
NoExitCode bool
Column int
JobCount int
SaveCache bool
}

type CommandError struct {
Expand Down
4 changes: 0 additions & 4 deletions src/runtime/mock/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 6 additions & 14 deletions src/runtime/terminal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -81,8 +82,6 @@ func (term *Terminal) Init() {
}

term.tmplCache = &cache.Template{}

term.SetPromptCount()
}

func (term *Terminal) ResolveConfigPath() {
Expand Down Expand Up @@ -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
}

Expand Down
1 change: 1 addition & 0 deletions src/shell/scripts/omp.bash
Original file line number Diff line number Diff line change
Expand Up @@ -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" \
Expand Down
1 change: 1 addition & 0 deletions src/shell/scripts/omp.elv
Original file line number Diff line number Diff line change
Expand Up @@ -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 ^
Expand Down
1 change: 1 addition & 0 deletions src/shell/scripts/omp.fish
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
1 change: 1 addition & 0 deletions src/shell/scripts/omp.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions src/shell/scripts/omp.nu
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down
1 change: 1 addition & 0 deletions src/shell/scripts/omp.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions src/shell/scripts/omp.tcsh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 1 addition & 4 deletions src/shell/scripts/omp.zsh
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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 \
Expand Down

0 comments on commit 68a1e89

Please sign in to comment.