@@ -19,6 +19,7 @@ import (
1919 "fmt"
2020 "os"
2121 "path/filepath"
22+ "slices"
2223 "testing"
2324
2425 "github.com/google/go-cmp/cmp"
@@ -137,3 +138,90 @@ libraries:
137138 })
138139 }
139140}
141+
142+ func TestCleanOutput (t * testing.T ) {
143+ for _ , test := range []struct {
144+ name string
145+ files []string
146+ keep []string
147+ want []string
148+ wantErr bool
149+ }{
150+ {
151+ name : "removes all except keep list" ,
152+ files : []string {"Cargo.toml" , "README.md" , "src/lib.rs" },
153+ keep : []string {"Cargo.toml" },
154+ want : []string {"Cargo.toml" },
155+ },
156+ {
157+ name : "empty directory with keep list" ,
158+ files : []string {},
159+ keep : []string {"Cargo.toml" },
160+ wantErr : true ,
161+ },
162+ {
163+ name : "only kept file" ,
164+ files : []string {"Cargo.toml" },
165+ keep : []string {"Cargo.toml" },
166+ want : []string {"Cargo.toml" },
167+ },
168+ {
169+ name : "keep file not found" ,
170+ files : []string {"README.md" , "src/lib.rs" },
171+ keep : []string {"Cargo.toml" },
172+ wantErr : true ,
173+ },
174+ {
175+ name : "keep multiple files" ,
176+ files : []string {"Cargo.toml" , "README.md" , "src/lib.rs" },
177+ keep : []string {"Cargo.toml" , "README.md" },
178+ want : []string {"Cargo.toml" , "README.md" },
179+ },
180+ {
181+ name : "empty keep list" ,
182+ files : []string {"Cargo.toml" , "README.md" },
183+ keep : []string {},
184+ want : []string {},
185+ },
186+ {
187+ name : "keep nested files" ,
188+ files : []string {"Cargo.toml" , "README.md" , "src/lib.rs" , "src/operation.rs" , "src/endpoint.rs" },
189+ keep : []string {"src/operation.rs" , "src/endpoint.rs" },
190+ want : []string {"src/endpoint.rs" , "src/operation.rs" },
191+ },
192+ } {
193+ t .Run (test .name , func (t * testing.T ) {
194+ dir := t .TempDir ()
195+ for _ , f := range test .files {
196+ path := filepath .Join (dir , f )
197+ if err := os .MkdirAll (filepath .Dir (path ), 0755 ); err != nil {
198+ t .Fatal (err )
199+ }
200+ if err := os .WriteFile (path , []byte ("test" ), 0644 ); err != nil {
201+ t .Fatal (err )
202+ }
203+ }
204+ err := cleanOutput (dir , test .keep )
205+ if test .wantErr {
206+ if err == nil {
207+ t .Fatal ("expected error, got nil" )
208+ }
209+ return
210+ }
211+ if err != nil {
212+ t .Fatal (err )
213+ }
214+ var got []string
215+ for _ , f := range test .files {
216+ if _ , err := os .Stat (filepath .Join (dir , f )); err == nil {
217+ got = append (got , f )
218+ }
219+ }
220+ slices .Sort (got )
221+ slices .Sort (test .want )
222+ if ! slices .Equal (got , test .want ) {
223+ t .Errorf ("got %v, want %v" , got , test .want )
224+ }
225+ })
226+ }
227+ }
0 commit comments