Last active
February 8, 2019 18:09
-
-
Save wobbol/e60d0bf27cc6fa255bde1864b3513645 to your computer and use it in GitHub Desktop.
Match filepaths like find (3)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"path/filepath" | |
"regexp" | |
"log" | |
) | |
// includeName checks if the name should be allowed or not based on the exclude patterns | |
func includeName(name string, patterns []string) (bool, error) { | |
sanitizedName := filepath.ToSlash(name) // Convert path seperators to '/' | |
for _, p := range patterns { | |
m, err := regexp.MatchString(p, sanitizedName) | |
if m || (err != nil) { | |
// Matches filepath - exclude | |
return false, err | |
} | |
} | |
// No filters matched - include the file | |
return true, nil | |
} | |
func main() { | |
// Use the first name for *nix and the second one for windows testing. | |
name := []string{"/vendor/gofoo", "/vendor/gobar", "/main.go"} | |
//name := []string{`\vendor\gofoo`, `\vendor\gobar`, `\main.go`} | |
// This regexp must match the whole pathname for a file to be excluded, just like find (3) | |
excludes := []string{`\/vendor.*`} | |
for _ , s := range name { | |
include, err := includeName(s, excludes) | |
if include { | |
fmt.Print("inc ") | |
} else { | |
fmt.Print("exc ") | |
} | |
fmt.Println(s) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment