Wednesday, 13 October 2021

Hacking go.mod files - there IS a better way

TL;DR; for our project, we're making heavy use of Go and, more specifically, modules: -

Modules are how Go manages dependencies.

A module is a collection of packages that are released, versioned, and distributed together. Modules may be downloaded directly from version control repositories or from module proxy servers.

A module is identified by a module path, which is declared in a go.mod file, together with information about the module’s dependencies. The module root directory is the directory that contains the go.mod file. The main module is the module containing the directory where the go command is invoked.

Each package within a module is a collection of source files in the same directory that are compiled together. A package path is the module path joined with the subdirectory containing the package (relative to the module root). For example, the module "golang.org/x/net" contains a package in the directory "html". That package’s path is "golang.org/x/net/html".

Source: Go Modules

In our specific use case, we have a go.mod file which contains the replace directive: -

A replace directive replaces the contents of a specific version of a module, or all versions of a module, with contents found elsewhere. The replacement may be specified with either another module path and version, or a platform-specific file path.

Source: replace directive

We had a requirement to update this replace directive, and have it point at a specific fork of a GitHub project rather than defaulting to the "main" upstream repository.

So, using the documentation's example: -

replace golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5

we wanted to change from fork to, say, foobar AND specific a different branch e.g. v1.5.7

Now it's perfectly easy to do this merely by hand-editing go.mod e.g. vi go.mod ....

BUT

there is ( as ever ) a better way ....

go mod edit --replace golang.org/x/net=example.com/foobar/net@v1.5.7

which gives us this in go.mod : -

replace golang.org/x/net => example.com/foobar/net v1.5.7

which is a much nicer approach ...

TL;DR; go mod edit is your friend!

No comments:

Note to self - use kubectl to query images in a pod or deployment

In both cases, we use JSON ... For a deployment, we can do this: - kubectl get deployment foobar --namespace snafu --output jsonpath="{...