github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/os/osutilpb/dir_util.go (about)

     1  package osutilpb
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"path"
     8  	"path/filepath"
     9  	"strings"
    10  )
    11  
    12  //  for tests, this is something like
    13  // C:\Users\pbberlin\AppData\Local\Temp\go-build722556939\github.com\...
    14  func DirOfExecutable() string {
    15  	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    16  	if err != nil {
    17  		log.Fatal(err)
    18  	}
    19  	// fmt.Println(dir)
    20  	return dir
    21  }
    22  
    23  func GetFilesByExtension(dir, dotExtension string, verbose bool) []string {
    24  
    25  	ret := make([]string, 0)
    26  
    27  	if dir == "" {
    28  		dir = "."
    29  	}
    30  	dirname := dir + string(filepath.Separator)
    31  
    32  	//  a far shorter way seems to be
    33  	//	files, err := filepath.Glob(dirname + "test*.html")
    34  
    35  	d, err := os.Open(dirname)
    36  	if err != nil {
    37  		fmt.Println(err)
    38  		os.Exit(1)
    39  	}
    40  	defer d.Close()
    41  
    42  	files, err := d.Readdir(-1)
    43  	if err != nil {
    44  		fmt.Println(err)
    45  		os.Exit(1)
    46  	}
    47  
    48  	if verbose {
    49  		fmt.Printf("scanning dir %v\n", dirname)
    50  	}
    51  
    52  	for _, file := range files {
    53  		if file.Mode().IsRegular() {
    54  			if filepath.Ext(file.Name()) == dotExtension {
    55  				if verbose {
    56  					fmt.Printf("  found file %v \n", file.Name())
    57  				}
    58  				ret = append(ret, file.Name())
    59  			}
    60  		}
    61  	}
    62  
    63  	return ret
    64  }
    65  
    66  // PathDirReverse is the opposite of path.Dir(filepath)
    67  // It returns the *first* dir of filepath; not the last
    68  //
    69  // Relative paths are converted to root
    70  // dir1/dir2  => /dir1, /dir2
    71  func PathDirReverse(filepath string) (dir, remainder string, dirs []string) {
    72  
    73  	filepath = strings.Replace(filepath, "\\", "/", -1)
    74  
    75  	filepath = path.Join(filepath, "")
    76  
    77  	if filepath == "/" || filepath == "" || filepath == "." {
    78  		return "/", "", []string{}
    79  	}
    80  
    81  	filepath = strings.TrimPrefix(filepath, "/")
    82  
    83  	dirs = strings.Split(filepath, "/")
    84  
    85  	if len(dirs) == 1 {
    86  		return "/" + dirs[0], "", []string{}
    87  	} else {
    88  		return "/" + dirs[0], "/" + strings.Join(dirs[1:], "/"), dirs[1:]
    89  	}
    90  
    91  	return
    92  
    93  }