From 8ce7be0101946dc6bccd5b57794ad91ef01c13b0 Mon Sep 17 00:00:00 2001 From: lihan Date: Wed, 13 Mar 2024 15:59:32 +0800 Subject: [PATCH] fix(powershell): due to a bug in PowerShell, we have to cleanup first when the shell open. When powershell is closed via the x button, this event will not be fired. See https://github.com/PowerShell/PowerShell/issues/8000 --- internal/manager.go | 20 +++++++++++++++++--- internal/shell/powershell.go | 11 +++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/internal/manager.go b/internal/manager.go index fc24557b..1dfe53b0 100644 --- a/internal/manager.go +++ b/internal/manager.go @@ -34,7 +34,8 @@ import ( ) const ( - pluginIndexUrl = "https://version-fox.github.io/version-fox-plugins/" + pluginIndexUrl = "https://version-fox.github.io/version-fox-plugins/" + cleanupFlagFilename = ".cleanup" ) type Arg struct { @@ -138,7 +139,9 @@ func (m *Manager) Remove(pluginName string) error { return fmt.Errorf("remove failed, err: %w", err) } pterm.Printf("Removing %s sdk...\n", source.InstallPath) - err = os.RemoveAll(source.InstallPath) + if err = os.RemoveAll(source.InstallPath); err != nil { + return err + } pterm.Printf("Remove %s plugin successfully! \n", pterm.LightGreen(pluginName)) return nil } @@ -335,6 +338,17 @@ func (m *Manager) Available() ([]*Category, error) { } func (m *Manager) CleanTmp() { + // once per day + cleanFlagPath := filepath.Join(m.PathMeta.TempPath, cleanupFlagFilename) + if !util.FileExists(cleanFlagPath) { + _ = os.WriteFile(cleanFlagPath, []byte(strconv.FormatInt(util.GetBeginOfToday(), 10)), 0666) + } else { + if str, err := os.ReadFile(cleanFlagPath); err == nil { + if i, err := strconv.ParseInt(string(str), 10, 64); err == nil && !util.IsBeforeToday(i) { + return + } + } + } dir, err := os.ReadDir(m.PathMeta.TempPath) if err == nil { _ = os.RemoveAll(m.PathMeta.CurTmpPath) @@ -352,7 +366,7 @@ func (m *Manager) CleanTmp() { continue } if util.IsBeforeToday(i) { - _ = os.Remove(filepath.Join(m.PathMeta.TempPath, file.Name())) + _ = os.RemoveAll(filepath.Join(m.PathMeta.TempPath, file.Name())) } } } diff --git a/internal/shell/powershell.go b/internal/shell/powershell.go index 1aaa0d68..d567d8da 100644 --- a/internal/shell/powershell.go +++ b/internal/shell/powershell.go @@ -32,8 +32,14 @@ var Pwsh Shell = pwsh{} const hook = ` {{.EnvContent}} +<# +Due to a bug in PowerShell, we have to cleanup first when the shell open. +#> +& '{{.SelfPath}}' env --cleanup 2>$null | Out-Null; + $__VFOX_PID=$pid; $originalPrompt = $function:prompt; + function prompt { $export = &"{{.SelfPath}}" env -s pwsh; if ($export) { @@ -42,6 +48,11 @@ function prompt { &$originalPrompt; } +<# + There is a bug here. + When powershell is closed via the x button, this event will not be fired. + See https://github.com/PowerShell/PowerShell/issues/8000 +#> Register-EngineEvent -SourceIdentifier PowerShell.Exiting -SupportEvent -Action { &"{{.SelfPath}}" env --cleanup; }