Skip to content

Commit

Permalink
Adding first example (#3317)
Browse files Browse the repository at this point in the history
* Adding first example

This PR includes the source code for the tutorial that is hosted
here: https://bazel-contrib.github.io/SIG-rules-authors/go-tutorial.html

The code for the above html is on the gh-pages branch of the
SIG-rules-authors repository:
https://github.com/bazel-contrib/SIG-rules-authors/tree/gh-pages

This tutorial source code includes:

- basic go rules support
- a basic cobra CLI application
- unit test
- Gazelle support

After this PR is finalized we I will update the tutorial markdown.

We are also adding CI/CD for the example.  This PR modifies the
presubmit.yml file.  This project also uses the words file that
requires the installation of wamerican.

* Updates for PR review

- renamed the tutorial to basic-gazelle
- updated roll_dice to use instead of the word generator

* Updating presubmit for rename

* More Cleanup

- removing the word example code
- creating testing code for roll dice

* Added comment to file per code review

* Updated go mod

- removed dep that we do not need
- changed path

* removing dep

* Adding klog as the dependency

- Imported klog
- added klog to different go files
- used bazel to update go.mod
- used gazelle to updated the BUILD files

* Adding macos test

Adding testing the examples with the macos platform.

* Adding windows test
  • Loading branch information
chrislovecnm authored Dec 1, 2022
1 parent a524159 commit 42451f5
Show file tree
Hide file tree
Showing 18 changed files with 476 additions and 0 deletions.
53 changes: 53 additions & 0 deletions .bazelci/presubmit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,56 @@ tasks:
# so the documentation it generates doesn't match the checked in files.
# - Tracking issue https://github.com/bazelbuild/stardoc/issues/42.
- "-//docs:all"
# The following configurations test a seperate WORKSPACE under the examples folder
ubuntu2004_examples:
name: Examples test on Ubuntu
platform: ubuntu2004
working_directory: examples/basic-gazelle
build_targets:
- "//..."
test_targets:
- "//..."
macos_examples:
name: Examples test on MacOS
platform: macos
working_directory: examples/basic-gazelle
build_targets:
- "//..."
test_targets:
- "//..."
windows_examples:
platform: windows
name: Examples test on Windows
build_flags:
# Go requires a C toolchain that accepts options and emits errors like
# gcc or clang. The Go SDK does not support MSVC.
- "--cpu=x64_windows"
- "--compiler=mingw-gcc"
- '--action_env=PATH=C:\tools\msys64\usr\bin;C:\tools\msys64\bin;C:\tools\msys64\mingw64\bin;C:\python3\Scripts\;C:\python3;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\ProgramData\GooGet;C:\Program Files\Google\Compute Engine\metadata_scripts;C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Google\Compute Engine\sysprep;C:\ProgramData\chocolatey\bin;C:\Program Files\Git\cmd;C:\tools\msys64\usr\bin;c:\openjdk\bin;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\CMake\bin;c:\ninja;c:\bazel;c:\buildkite'
# NOTE(bazelbuild/bazel#10529): bazel doesn't register the mingw toolchain automatically.
# We also need the host and target platforms to have the mingw constraint value.
- "--extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows_mingw"
- "--host_platform=@io_bazel_rules_go//go/toolchain:windows_amd64_cgo"
- "--platforms=@io_bazel_rules_go//go/toolchain:windows_amd64_cgo"
- "--incompatible_enable_cc_toolchain_resolution"
working_directory: examples/basic-gazelle
build_targets:
- "//..."
test_targets:
- "//..."
test_flags:
# Go requires a C toolchain that accepts options and emits errors like
# gcc or clang. The Go SDK does not support MSVC.
- "--cpu=x64_windows"
- "--compiler=mingw-gcc"
- '--action_env=PATH=C:\tools\msys64\usr\bin;C:\tools\msys64\bin;C:\tools\msys64\mingw64\bin;C:\python3\Scripts\;C:\python3;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\ProgramData\GooGet;C:\Program Files\Google\Compute Engine\metadata_scripts;C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Google\Compute Engine\sysprep;C:\ProgramData\chocolatey\bin;C:\Program Files\Git\cmd;C:\tools\msys64\usr\bin;c:\openjdk\bin;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\CMake\bin;c:\ninja;c:\bazel;c:\buildkite'
- "--extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows_mingw"
- "--host_platform=@io_bazel_rules_go//go/toolchain:windows_amd64_cgo"
- "--platforms=@io_bazel_rules_go//go/toolchain:windows_amd64_cgo"
- "--incompatible_enable_cc_toolchain_resolution"
# On Windows CI, bazel (bazelisk) needs %LocalAppData% to find the cache directory.
# We invoke bazel in tests, so the tests need this, too.
- "--test_env=LOCALAPPDATA"
# go_bazel_test runs bazel in a test workspace. It needs the same flags as above.
- "--test_env=GO_BAZEL_TEST_BAZELFLAGS=--cpu=x64_windows --compiler=mingw-gcc --extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows_mingw --action_env=PATH --host_platform=@io_bazel_rules_go//go/toolchain:windows_amd64_cgo --incompatible_enable_cc_toolchain_resolution"
- "--test_env=PATH"
1 change: 1 addition & 0 deletions .bazelignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
tests/bcr
examples
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/tests/core/cgo/libimported.*
/tests/core/cgo/libversioned.*
/tests/bcr/bazel-*
/examples/*/bazel-*
5 changes: 5 additions & 0 deletions examples/basic-gazelle/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# We added this file as part of the tutorial
/bazel-basic-gazelle
/bazel-bin
/bazel-out
/bazel-testlogs
33 changes: 33 additions & 0 deletions examples/basic-gazelle/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
load("@bazel_gazelle//:def.bzl", "gazelle")

# gazelle:prefix github.com/bazelbuild/rules_go/examples/basic-gazelle
gazelle(name = "gazelle")

# adding rule to update deps
gazelle(
name = "gazelle-update-repos",
args = [
"-from_file=go.mod",
"-to_macro=deps.bzl%go_dependencies",
"-prune",
],
command = "update-repos",
)

go_library(
name = "basic-gazelle_lib",
srcs = ["main.go"],
importpath = "github.com/bazelbuild/rules_go/examples/basic-gazelle",
visibility = ["//visibility:private"],
deps = [
"//cmd",
"@io_k8s_klog_v2//:klog",
],
)

go_binary(
name = "basic-gazelle",
embed = [":basic-gazelle_lib"],
visibility = ["//visibility:public"],
)
9 changes: 9 additions & 0 deletions examples/basic-gazelle/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Go Rules Tutorial

## Updates

Please update both the source code here and the tutorial that is on the gh-pages branch here:
https://github.com/bazel-contrib/SIG-rules-authors/tree/gh-pages.

Updates to this tutorial require two PRs, as there are code block in the gh-pages tutorial mentioned
above.
4 changes: 4 additions & 0 deletions examples/basic-gazelle/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Go Rules Tutorial

This is the source code for the Go Rules tutorial that is available here:
https://bazel-contrib.github.io/SIG-rules-authors/go-tutorial.html
65 changes: 65 additions & 0 deletions examples/basic-gazelle/WORKSPACE
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Load the http ruleset and expose the http_archive rule
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

# Download rules_go ruleset.
# Bazel makes a https call and downloads the zip file, and then
# checks the sha.
http_archive(
name = "io_bazel_rules_go",
sha256 = "099a9fb96a376ccbbb7d291ed4ecbdfd42f6bc822ab77ae6f1b5cb9e914e94fa",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.35.0/rules_go-v0.35.0.zip",
"https://github.com/bazelbuild/rules_go/releases/download/v0.35.0/rules_go-v0.35.0.zip",
],
)

# Download the bazel_gazelle ruleset.
http_archive(
name = "bazel_gazelle",
sha256 = "efbbba6ac1a4fd342d5122cbdfdb82aeb2cf2862e35022c752eaddffada7c3f3",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.27.0/bazel-gazelle-v0.27.0.tar.gz",
"https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.27.0/bazel-gazelle-v0.27.0.tar.gz",
],
)

# Load rules_go ruleset and expose the toolchain and dep rules.
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")

# the line below instructs gazelle to save the go dependency definitions
# in the deps.bzl file. Located under '//'.
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies")

############################################################
# Define your own dependencies here using go_repository.
# Else, dependencies declared by rules_go/gazelle will be used.
# The first declaration of an external repository "wins".
############################################################

# The following line defines the symbol go_dependencies from the deps.bzl file.
# Having the deps in that file, helps the WORKSPACE file stay less
# cluttered. The library symbol go_dependencies is then added to
# the envionment. The line below calls that function.
load("//:deps.bzl", "go_dependencies")

# The next comment line includes a macro that gazelle reads.
# This macro tells Gazelle to look for repository rules in a macro in a .bzl file,
# and allows Gazelle to find the correct file to maintain the Go dependencies.
# Then the line after the comment calls go_dependencies(), and that funcation
# contains calls to various go_repository rules.

# gazelle:repository_macro deps.bzl%go_dependencies
go_dependencies()

# go_rules_dependencies is a function that registers external dependencies
# needed by the Go rules.
# https://github.com/bazelbuild/rules_go/blob/master/go/dependencies.rst#go_rules_dependencies
go_rules_dependencies()

# The next rule installs the Go toolchains. The Go version is specified
# using the version parameter. This rule will download the Go SDK.
# https://github.com/bazelbuild/rules_go/blob/master/go/toolchains.rst#go_register_toolchains
go_register_toolchains(version = "1.19.1")

# The following call configured the gazelle dependencies, Go environment and Go SDK.
gazelle_dependencies()
16 changes: 16 additions & 0 deletions examples/basic-gazelle/cmd/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")

go_library(
name = "cmd",
srcs = [
"roll.go",
"root.go",
],
importpath = "github.com/bazelbuild/rules_go/examples/basic-gazelle/cmd",
visibility = ["//visibility:public"],
deps = [
"//pkg/roll",
"@com_github_spf13_cobra//:cobra",
"@io_k8s_klog_v2//:klog",
],
)
44 changes: 44 additions & 0 deletions examples/basic-gazelle/cmd/roll.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"fmt"

"github.com/bazelbuild/rules_go/examples/basic-gazelle/pkg/roll"
"github.com/spf13/cobra"
"k8s.io/klog/v2"
)

// rollCmd represents the roll command
var rollCmd = &cobra.Command{
Use: "roll",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
klog.Info("calling roll")
fmt.Printf("Number rolled: %s\n", roll.Roll())
},
}

func init() {
rootCmd.AddCommand(rollCmd)

}
49 changes: 49 additions & 0 deletions examples/basic-gazelle/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"os"

"github.com/spf13/cobra"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "go-code-tutorial",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}

func init() {
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
61 changes: 61 additions & 0 deletions examples/basic-gazelle/deps.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
load("@bazel_gazelle//:deps.bzl", "go_repository")

def go_dependencies():
go_repository(
name = "com_github_cpuguy83_go_md2man_v2",
importpath = "github.com/cpuguy83/go-md2man/v2",
sum = "h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=",
version = "v2.0.2",
)
go_repository(
name = "com_github_go_logr_logr",
importpath = "github.com/go-logr/logr",
sum = "h1:QK40JKJyMdUDz+h+xvCsru/bJhvG0UxvePV0ufL/AcE=",
version = "v1.2.0",
)

go_repository(
name = "com_github_inconshreveable_mousetrap",
importpath = "github.com/inconshreveable/mousetrap",
sum = "h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=",
version = "v1.0.0",
)

go_repository(
name = "com_github_russross_blackfriday_v2",
importpath = "github.com/russross/blackfriday/v2",
sum = "h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=",
version = "v2.1.0",
)
go_repository(
name = "com_github_spf13_cobra",
importpath = "github.com/spf13/cobra",
sum = "h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=",
version = "v1.5.0",
)
go_repository(
name = "com_github_spf13_pflag",
importpath = "github.com/spf13/pflag",
sum = "h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=",
version = "v1.0.5",
)

go_repository(
name = "in_gopkg_check_v1",
importpath = "gopkg.in/check.v1",
sum = "h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=",
version = "v0.0.0-20161208181325-20d25e280405",
)

go_repository(
name = "in_gopkg_yaml_v2",
importpath = "gopkg.in/yaml.v2",
sum = "h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=",
version = "v2.4.0",
)
go_repository(
name = "io_k8s_klog_v2",
importpath = "k8s.io/klog/v2",
sum = "h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4=",
version = "v2.80.1",
)
14 changes: 14 additions & 0 deletions examples/basic-gazelle/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module github.com/bazelbuild/rules_go/examples/basic-gazelle

go 1.19

require (
github.com/spf13/cobra v1.5.0
k8s.io/klog/v2 v2.80.1
)

require (
github.com/go-logr/logr v1.2.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
)
14 changes: 14 additions & 0 deletions examples/basic-gazelle/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/go-logr/logr v1.2.0 h1:QK40JKJyMdUDz+h+xvCsru/bJhvG0UxvePV0ufL/AcE=
github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
k8s.io/klog/v2 v2.80.1 h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4=
k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0=
Loading

0 comments on commit 42451f5

Please sign in to comment.