PumpkinSeed
PumpkinSeed

Reputation: 3113

Building multiple go plugins under a directory in one shot

I have a list of plugins under a subdir. I want to build all of them with a single command. There is an example dir layout.

plugins/cat/cat.go
plugins/dog/dog.go
plugins/cow/cow.go

I build them right now like:

go build -i -buildmode=plugin -o build/cat.so plugins/cat/cat.go
go build -i -buildmode=plugin -o build/dog.so plugins/dog/dog.go
go build -i -buildmode=plugin -o build/cow.so plugins/cow/cow.go

There is an other command (because it's in a Makefile), which help me to get closer:

# Ex.: make bin-so TARGET=cat
bin-so: builddir
    go build -i -buildmode=plugin -o build/$(TARGET).so plugins/$(TARGET)/$(TARGET).go

I want to create a single line which builds these plugins. I found out how I can list the folder names, but I have to use it somehow in the command above.

find ./plugins -mindepth 1 -maxdepth 1 -type d | awk 'sub(/^.*\//, "")'

So it will list the name of the folders, these are good to me, but I have to redirect it to the plugin builder command.

I want to have something similar (just an example):

find ./plugins -mindepth 1 -maxdepth 1 -type d | awk 'sub(/^.*\//, "")' | go build -i -buildmode=plugin -o build/$1).so plugins/$1/$1.go

Upvotes: 1

Views: 172

Answers (1)

Inian
Inian

Reputation: 85560

You can just do this in one find command with the -execdir option that allows you run commands directly on the basename of the files

find ./plugins -mindepth 1 -maxdepth 1 -type d -execdir bash -c '
    for arg; do
        name="${arg##*./}"
        go build -i -buildmode=plugin -o build/"${name}".so plugins/"${name}"/"${name}".go
    done' _ {} +

This is much better than using multiple pipelines after find to achieve the same result. Imagine the part within the sh -c '..' as a separate script and you are passing the arguments to the script with the names returned ./cow.go etc.

The advantage of -execdir here is you don't need to worry about the immediate paths before the directory names. You get the final base-name of the directories found.

See Understanding the -exec option of find on Unix.SE to learn more about each of the options used.

Upvotes: 2

Related Questions