Skip to content

Commit 35e4f38

Browse files
authored
Fix incorrect usage of os.Stat (#20125)
* Update main.go * Fix incorrect stat for link * add doc
1 parent fb1a129 commit 35e4f38

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

components/ide/jetbrains/launcher/main.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1186,10 +1186,13 @@ func linkRemotePlugin(launchCtx *LaunchContext) error {
11861186
return safeLink("/ide-desktop-plugins/gitpod-remote", remotePluginDir)
11871187
}
11881188

1189+
// safeLink creates a symlink from source to target, removing the old target if it exists
11891190
func safeLink(source, target string) error {
1190-
if _, err := os.Stat(target); err == nil {
1191+
if _, err := os.Lstat(target); err == nil {
11911192
// unlink the old symlink
1192-
_ = os.RemoveAll(target)
1193+
if err2 := os.RemoveAll(target); err2 != nil {
1194+
log.WithError(err).Error("failed to unlink old symlink")
1195+
}
11931196
}
11941197
return os.Symlink(source, target)
11951198
}

components/ide/jetbrains/launcher/main_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
package main
66

77
import (
8+
"fmt"
9+
"os"
10+
"path/filepath"
811
"strings"
912
"testing"
1013

@@ -105,3 +108,42 @@ func TestUpdatePlatformProperties(t *testing.T) {
105108
}
106109
})
107110
}
111+
112+
func Test_safeLink(t *testing.T) {
113+
type args struct {
114+
changeSource bool
115+
}
116+
t.Log("link folders twice")
117+
tests := []struct {
118+
name string
119+
args args
120+
wantErr bool
121+
}{
122+
{name: "happy path", args: args{changeSource: true}, wantErr: false},
123+
{name: "happy path 2", args: args{changeSource: false}, wantErr: false},
124+
}
125+
for index, tt := range tests {
126+
t.Run(tt.name, func(t *testing.T) {
127+
source := createTempDir(t, fmt.Sprintf("source_%d", index))
128+
target := createTempDir(t, fmt.Sprintf("target_%d", index))
129+
safeLink(source, target)
130+
os.RemoveAll(source)
131+
if tt.args.changeSource {
132+
source = createTempDir(t, fmt.Sprintf("source_new_%d", index))
133+
} else {
134+
source = createTempDir(t, fmt.Sprintf("source_%d", index))
135+
}
136+
if err := safeLink(source, target); (err != nil) != tt.wantErr {
137+
t.Errorf("safeLink() error = %v, wantErr %v", err, tt.wantErr)
138+
}
139+
})
140+
}
141+
}
142+
143+
func createTempDir(t *testing.T, dir string) string {
144+
path := filepath.Join(t.TempDir(), dir)
145+
if err := os.Mkdir(path, 0o755); err != nil {
146+
t.Fatal(err)
147+
}
148+
return path
149+
}

0 commit comments

Comments
 (0)