github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/helpers/path/directory.go (about)

     1  package path
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  )
     8  
     9  // CleanUpEmptyDirs is used to search all sub directories and removes
    10  // the directories which are empty.
    11  func CleanUpEmptyDirs(absPath string) error {
    12  	stat, err := os.Stat(absPath)
    13  	if err != nil && !os.IsNotExist(err) {
    14  		return err
    15  	} else if os.IsNotExist(err) || !stat.IsDir() {
    16  		return nil
    17  	}
    18  
    19  	fileItems, err := ioutil.ReadDir(absPath)
    20  	if err != nil {
    21  		return err
    22  	}
    23  
    24  	for _, fileItem := range fileItems {
    25  		if fileItem.IsDir() {
    26  			err = CleanUpEmptyDirs(filepath.Join(absPath, fileItem.Name()))
    27  			if err != nil {
    28  				return err
    29  			}
    30  		}
    31  	}
    32  
    33  	// Intentionally not checking for an error. It is fine if it fails
    34  	// this just means that the directory is not empty and has files in it
    35  	// (or has subdirectories which have files in it).
    36  	os.Remove(absPath)
    37  
    38  	return nil
    39  }