Search code examples
gomonorepogo-modules

Is it possible to dis-allow import of module (mono-repo), having multiple independent modules?


What I essentially have is a mono-repo, which doesn't have a go.mod at the root level. There are multiple directories inside this mono-repo, with each of them having their own go.mod files. I'll refer to them as sub-modules.

Now, I've figured out a way to be able to access the sub-modules independently (versioned) in a completely different codebase. The issue I'm facing now is, to dis-allow the import of the entire mono-repo, using:

go get link.to/mono-repo@commit_id ------> A

and only allow import using :

go get link.to/mono-repo/[email protected]

go get link.to/mono-repo/[email protected]

The command A is able to fetch the entire repo, and then can be used to access the inner modules. Is there any way to stop this from being allowed?

I tried a few things, like:

  • Added non-compilable code in a file noCompile.go at the root level. On go get..., the compilation error is printed, but use of the inner modules still works fine.
  • Added an init() function in the same noCompile.go file, which just calls panic(). This init function is not being executed, as the root directory is never directly accessed, only the inner modules are.

Is there ANY way to achieve what I'm intending to?


Solution

  • Any directory that contains its own go.mod file is excluded from the module in the parent directory. So if you go get link.to/mono-repo@commit_id, that should not contain the packages link.to/mono-repo/sub_mod1 or link.to/mono-repo/sub_mod2 (assuming that they exist and have their own go.mod files).

    I suspect that you were observing imports like import "link.to/mono-repo/sub_mod2/some/package/here" to resolve not because of that initial go get, but rather because the go command was resolving the missing imports (and adding the missing dependencies) automatically; see https://golang.org/ref/mod#go-mod-file-updates.

    As of Go 1.16 (released today!), most go commands no longer implicitly modify the go.mod file, so the fact that the module at the repo root does not include the contents of nested modules should hopefully be clearer.