Skip to content

Instantly share code, notes, and snippets.

@jwoglom
Created August 25, 2018 00:27
Show Gist options
  • Save jwoglom/17bdd5534fe0c3f01f7b438a28c2f203 to your computer and use it in GitHub Desktop.
Save jwoglom/17bdd5534fe0c3f01f7b438a28c2f203 to your computer and use it in GitHub Desktop.
// glocktobazel generates Bazel external repositories from a GLOCKFILE
package main
import (
"bufio"
"os"
"strings"
"fmt"
)
func main() {
glockfile, err := os.Open("GLOCKFILE")
defer glockfile.Close()
if err != nil {
panic(err)
}
var cmds []string
packages := map[string]string{}
scanner := bufio.NewScanner(glockfile)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if fields[0] == "cmd" {
cmds = append(cmds, fields[1])
} else {
packages[fields[0]] = fields[1]
}
}
fmt.Print(`
def go_repositories():
loaded = native.existing_rules()`)
for remote, commit := range packages {
pkgName := remoteToPackageName(remote)
fmt.Printf(`
if "%s" not in loaded:
native.new_git_repository(
name = "%s",
remote = "https://%s",
commit = "%s",
build_file = "BUILD",
)
`, pkgName, pkgName, remote, commit)
}
}
func remoteToPackageName(remote string) string {
parts := strings.Split(remote, "/")
domainParts := reverse(strings.Split(parts[0], "."))
pathParts := safePaths(parts[1:])
return strings.Join(append(domainParts, pathParts...), "_")
}
func reverse(arr []string) []string {
for i, j := 0, len(arr)-1; i<j; i, j = i+1, j-1 {
arr[i], arr[j] = arr[j], arr[i]
}
return arr
}
func safePaths(arr []string) []string {
var ret []string
for _, el := range arr {
ret = append(ret, safePath(el)...)
}
return ret
}
func safePath(part string) []string {
part = strings.Replace(part, "-", "_", -1)
part = strings.Replace(part, ".", "_", -1)
return strings.Split(part, "_")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment