1// Copyright 2021 The Bazel Authors. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package main 16 17import ( 18 "encoding/json" 19 "errors" 20 "fmt" 21 "io" 22 "net/http" 23 "sort" 24 25 "golang.org/x/mod/semver" 26) 27 28func genBoilerplate(version, shasum, goVersion string) string { 29 return fmt.Sprintf(`load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 30 31http_archive( 32 name = "io_bazel_rules_go", 33 sha256 = "%[2]s", 34 urls = [ 35 "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/%[1]s/rules_go-%[1]s.zip", 36 "https://github.com/bazelbuild/rules_go/releases/download/%[1]s/rules_go-%[1]s.zip", 37 ], 38) 39 40load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") 41 42go_rules_dependencies() 43 44go_register_toolchains(version = "%[3]s")`, version, shasum, goVersion) 45} 46 47func findLatestGoVersion() (v string, err error) { 48 defer func() { 49 if err != nil { 50 err = fmt.Errorf("finding latest go version: %w", err) 51 } 52 }() 53 resp, err := http.Get("https://golang.org/dl/?mode=json") 54 if err != nil { 55 return "", err 56 } 57 defer resp.Body.Close() 58 data, err := io.ReadAll(resp.Body) 59 if err != nil { 60 return "", err 61 } 62 type version struct { 63 Version string 64 } 65 var versions []version 66 if err := json.Unmarshal(data, &versions); err != nil { 67 return "", err 68 } 69 if len(versions) == 0 { 70 return "", errors.New("no versions found") 71 } 72 sort.Slice(versions, func(i, j int) bool { 73 vi := "v" + versions[i].Version[len("go"):] 74 vj := "v" + versions[j].Version[len("go"):] 75 return semver.Compare(vi, vj) > 0 76 }) 77 return versions[0].Version[len("go"):], nil 78} 79