| 1 | package app |
| 2 | |
| 3 | import ( |
| 4 | "io/ioutil" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | ) |
| 8 | |
| 9 | // generateDirectories returns possible git repositories to pipe into git pkg |
| 10 | // load function |
| 11 | func generateDirectories(dirs []string, depth int) []string { |
| 12 | gitDirs := make([]string, 0) |
| 13 | for i := 0; i < depth; i++ { |
| 14 | directories, repositories := walkRecursive(dirs, gitDirs) |
| 15 | dirs = directories |
| 16 | gitDirs = repositories |
| 17 | } |
| 18 | return gitDirs |
| 19 | } |
| 20 | |
| 21 | // returns given values, first search directories and second stands for possible |
| 22 | // git repositories. Call this func from a "for i := 0; i<depth; i++" loop |
| 23 | func walkRecursive(search, appendant []string) ([]string, []string) { |
| 24 | max := len(search) |
| 25 | for i := 0; i < max; i++ { |
| 26 | if i >= len(search) { |
| 27 | continue |
| 28 | } |
| 29 | // find possible repositories and remaining ones, b slice is possible ones |
| 30 | a, b, err := separateDirectories(search[i]) |
| 31 | if err != nil { |
| 32 | continue |
| 33 | } |
| 34 | // since we started to search let's get rid of it and remove from search |
| 35 | // array |
| 36 | search[i] = search[len(search)-1] |
| 37 | search = search[:len(search)-1] |
| 38 | // lets append what we have found to continue recursion |
| 39 | search = append(search, a...) |
| 40 | appendant = append(appendant, b...) |
| 41 | } |
| 42 | return search, appendant |
| 43 | } |
| 44 | |
| 45 | // separateDirectories is to find all the files in given path. This method |
| 46 | // does not check if the given file is a valid git repositories |
| 47 | func separateDirectories(directory string) ([]string, []string, error) { |
| 48 | dirs := make([]string, 0) |
| 49 | gitDirs := make([]string, 0) |
| 50 | files, err := ioutil.ReadDir(directory) |
| 51 | // can we read the directory? |
| 52 | if err != nil { |
| 53 | return nil, nil, nil |
| 54 | } |
| 55 | for _, f := range files { |
| 56 | repo := directory + string(os.PathSeparator) + f.Name() |
| 57 | file, err := os.Open(repo) |
| 58 | // if we cannot open it, simply continue to iteration and don't consider |
| 59 | if err != nil { |
| 60 | file.Close() |
| 61 | continue |
| 62 | } |
| 63 | dir, err := filepath.Abs(file.Name()) |
| 64 | if err != nil { |
| 65 | file.Close() |
| 66 | continue |
| 67 | } |
| 68 | // with this approach, we ignore submodule or sub repositories in a git repository |
| 69 | ff, err := os.Open(dir + string(os.PathSeparator) + ".git") |
| 70 | if err != nil { |
| 71 | dirs = append(dirs, dir) |
| 72 | } else { |
| 73 | gitDirs = append(gitDirs, dir) |
| 74 | } |
| 75 | ff.Close() |
| 76 | file.Close() |
| 77 | |
| 78 | } |
| 79 | return dirs, gitDirs, nil |
| 80 | } |