Skip to content

Instantly share code, notes, and snippets.

@neumachen
Created January 29, 2018 01:35
Show Gist options
  • Select an option

  • Save neumachen/a30261f1fc92c0abd11f18cc697ddb6a to your computer and use it in GitHub Desktop.

Select an option

Save neumachen/a30261f1fc92c0abd11f18cc697ddb6a to your computer and use it in GitHub Desktop.
A sample code to show how to check if a directory is empty extending magicalbanana/env custom parser funcs
package config
import (
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"reflect"
)
// URLType is a helper var that represents the `reflect.Type`` of `url.URL`
var URLType = reflect.TypeOf(url.URL{})
// ParseURL is a basic parser for the url.URL type that should be used with
// `env.ParseWithFuncs()`
func ParseURL(v string) (interface{}, error) {
u, pErr := url.ParseRequestURI(v)
if pErr != nil {
return nil, pErr
}
return *u, nil
}
// MigrationsDir represents a file directory
type MigrationsDir string
// MigrationsDirType is a helper var that represents the `reflect.Type` of
// `Directory`
var MigrationsDirType = reflect.TypeOf(MigrationsDir(""))
// LoadMigrationsDir ...
func LoadMigrationsDir(v string) (interface{}, error) {
fdir, err := os.Open(v)
if err != nil {
return nil, err
}
defer fdir.Close()
finfo, err := fdir.Stat()
if err != nil {
return nil, err
}
if !finfo.Mode().IsDir() {
return nil, fmt.Errorf("the given path: %s, is not a directory", fdir.Name())
}
ok, err := directoryEmpty(fdir)
if err != nil {
return nil, err
}
if ok {
return nil, fmt.Errorf("the given path: %s, is empty", filepath.Dir(fdir.Name()))
}
return MigrationsDir(v), nil
}
func directoryEmpty(f *os.File) (bool, error) {
_, err := f.Readdirnames(1)
if err == io.EOF {
return true, nil
}
return false, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment