Skip to content

Commit 53f1f3b

Browse files
committed
Replace string check with syscall.Errno
1 parent 769bb7a commit 53f1f3b

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

agent/files.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
"os"
1111
"path/filepath"
1212
"strconv"
13-
"strings"
13+
"syscall"
1414

1515
"golang.org/x/xerrors"
1616

@@ -139,7 +139,7 @@ func (a *agent) writeFile(ctx context.Context, r *http.Request, path string) (Ht
139139
switch {
140140
case errors.Is(err, os.ErrPermission):
141141
status = http.StatusForbidden
142-
case strings.Contains(err.Error(), "not a directory"):
142+
case errors.Is(err, syscall.ENOTDIR):
143143
status = http.StatusBadRequest
144144
}
145145
return status, err
@@ -151,8 +151,7 @@ func (a *agent) writeFile(ctx context.Context, r *http.Request, path string) (Ht
151151
switch {
152152
case errors.Is(err, os.ErrPermission):
153153
status = http.StatusForbidden
154-
case strings.Contains(err.Error(), "is a directory") ||
155-
strings.Contains(err.Error(), "not a directory"):
154+
case errors.Is(err, syscall.EISDIR):
156155
status = http.StatusBadRequest
157156
}
158157
return status, err

agent/files_test.go

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ import (
77
"net/http"
88
"os"
99
"path/filepath"
10+
"syscall"
1011
"testing"
1112

1213
"github.com/spf13/afero"
1314
"github.com/stretchr/testify/require"
14-
"golang.org/x/xerrors"
1515

1616
"github.com/coder/coder/v2/agent"
1717
"github.com/coder/coder/v2/agent/agenttest"
@@ -48,11 +48,19 @@ func (fs *testFs) Create(name string) (afero.File, error) {
4848
// lets you nest them underneath files, somehow.
4949
stat, err := fs.Fs.Stat(name)
5050
if err == nil && stat.IsDir() {
51-
return nil, xerrors.New("is a directory")
51+
return nil, &os.PathError{
52+
Op: "open",
53+
Path: name,
54+
Err: syscall.EISDIR,
55+
}
5256
}
5357
stat, err = fs.Fs.Stat(filepath.Dir(name))
5458
if err == nil && !stat.IsDir() {
55-
return nil, xerrors.New("not a directory")
59+
return nil, &os.PathError{
60+
Op: "open",
61+
Path: name,
62+
Err: syscall.ENOTDIR,
63+
}
5664
}
5765
return fs.Fs.Create(name)
5866
}
@@ -65,11 +73,19 @@ func (fs *testFs) MkdirAll(name string, mode os.FileMode) error {
6573
// lets you nest them underneath files somehow.
6674
stat, err := fs.Fs.Stat(filepath.Dir(name))
6775
if err == nil && !stat.IsDir() {
68-
return xerrors.New("not a directory")
76+
return &os.PathError{
77+
Op: "mkdir",
78+
Path: name,
79+
Err: syscall.ENOTDIR,
80+
}
6981
}
7082
stat, err = fs.Fs.Stat(name)
7183
if err == nil && !stat.IsDir() {
72-
return xerrors.New("not a directory")
84+
return &os.PathError{
85+
Op: "mkdir",
86+
Path: name,
87+
Err: syscall.ENOTDIR,
88+
}
7389
}
7490
return fs.Fs.MkdirAll(name, mode)
7591
}

0 commit comments

Comments
 (0)