@@ -26,49 +26,11 @@ import (
2626// should contain paths relative to dir. It returns an error if any file
2727// in keep does not exist.
2828func checkAndClean (dir string , keep []string ) error {
29- keepSet , err := check (dir , keep )
30- if err != nil {
31- return err
32- }
33- return clean (dir , keepSet )
34- }
35-
36- // check validates the given directory and returns a set of files to keep.
37- // It ensures that the provided directory exists and is a directory.
38- // It also verifies that all files specified in 'keep' exist within 'dir'.
39- func check (dir string , keep []string ) (map [string ]bool , error ) {
40- info , err := os .Stat (dir )
41- if err != nil {
42- if errors .Is (err , fs .ErrNotExist ) {
43- return nil , nil
44- }
45- return nil , fmt .Errorf ("cannot access output directory %q: %w" , dir , err )
46- }
47- if ! info .IsDir () {
48- return nil , fmt .Errorf ("%q is not a directory" , dir )
49- }
5029 keepSet := make (map [string ]bool )
5130 for _ , k := range keep {
52- path := filepath .Join (dir , k )
53- if _ , err := os .Stat (path ); errors .Is (err , fs .ErrNotExist ) {
54- return nil , fmt .Errorf ("keep file %q does not exist" , k )
55- }
56- // Effectively get a canonical relative path. While in most cases
57- // this will be equal to k, it might not be - in particular,
58- // on Windows the directory separator in paths returned by Rel
59- // will be a backslash.
60- rel , err := filepath .Rel (dir , path )
61- if err != nil {
62- return nil , err
63- }
64- keepSet [rel ] = true
31+ keepSet [filepath .Clean (k )] = true
6532 }
66- return keepSet , nil
67- }
68-
69- // clean removes files from dir that are not in keepSet.
70- func clean (dir string , keepSet map [string ]bool ) error {
71- return filepath .WalkDir (dir , func (path string , d fs.DirEntry , err error ) error {
33+ err := filepath .WalkDir (dir , func (path string , d fs.DirEntry , err error ) error {
7234 if err != nil {
7335 return err
7436 }
@@ -80,8 +42,28 @@ func clean(dir string, keepSet map[string]bool) error {
8042 return err
8143 }
8244 if keepSet [rel ] {
45+ keepSet [rel ] = false
8346 return nil
8447 }
8548 return os .Remove (path )
8649 })
50+ if err != nil {
51+ if errors .Is (err , fs .ErrNotExist ) {
52+ // The top-level directory was not found. This happens when
53+ // calling `librarian generate` on new libraries and it is not
54+ // an error.
55+ return nil
56+ }
57+ return err
58+ }
59+ var missing []string
60+ for relative , v := range keepSet {
61+ if v {
62+ missing = append (missing , relative )
63+ }
64+ }
65+ if len (missing ) != 0 {
66+ return fmt .Errorf ("some keep files %q do not exist" , keep )
67+ }
68+ return nil
8769}
0 commit comments