Skip to content

Commit 6240713

Browse files
committed
playground: check file/dir name conflicts in txtar
1 parent 4d02eef commit 6240713

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

txtar.go

+12
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"errors"
1010
"fmt"
1111
"path"
12+
"path/filepath"
1213
"strings"
1314

1415
"golang.org/x/tools/txtar"
@@ -89,6 +90,7 @@ func splitFiles(src []byte) (*fileSet, error) {
8990
if numFiles > limitNumFiles {
9091
return nil, fmt.Errorf("too many files in txtar archive (%v exceeds limit of %v)", numFiles, limitNumFiles)
9192
}
93+
dirFileNameMap := map[string]string{} // holds which filename the dirname is part of
9294
for _, f := range a.Files {
9395
if len(f.Name) > 200 { // arbitrary limit
9496
return nil, errors.New("file name too long")
@@ -111,6 +113,16 @@ func splitFiles(src []byte) (*fileSet, error) {
111113
if fs.Contains(f.Name) {
112114
return nil, fmt.Errorf("duplicate file name %q", f.Name)
113115
}
116+
for i := 1; i < len(parts); i++ {
117+
dirname := filepath.Join(parts[:i]...)
118+
if fs.Contains(dirname) {
119+
return nil, fmt.Errorf("conflict file/dir name %q and %q", dirname, f.Name)
120+
}
121+
dirFileNameMap[dirname] = f.Name
122+
}
123+
if filename, ok := dirFileNameMap[f.Name]; ok {
124+
return nil, fmt.Errorf("conflict dir/file name %q and %q", filename, f.Name)
125+
}
114126
fs.AddFile(f.Name, f.Data)
115127
}
116128
return fs, nil

txtar_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,16 @@ func TestSplitFiles(t *testing.T) {
117117
in: strings.Repeat("-- x.go --\n", 50),
118118
wantErr: `too many files in txtar archive (50 exceeds limit of 20)`,
119119
},
120+
{
121+
name: "reject file overwritten by dir",
122+
in: "-- a --\n-- a/b --\n",
123+
wantErr: `conflict file/dir name "a" and "a/b"`,
124+
},
125+
{
126+
name: "reject dir overwritten by file",
127+
in: "-- a/b --\n-- a --\n",
128+
wantErr: `conflict dir/file name "a/b" and "a"`,
129+
},
120130
} {
121131
got, err := splitFiles([]byte(tt.in))
122132
var gotErr string

0 commit comments

Comments
 (0)