Skip to content

AfterApply hook doesn't work for environment-provided parameters #596

@monkpatch

Description

@monkpatch

Hello! Thank you for your hard work, your library is just perfect for building conveniently configurable cli applications. I love using it. However, I've encountered a problem.

In my application, a custom parameter with an AfterApply hook can be provided via:

  1. argv
  2. environment variable
  3. json config

The hook isn't called in the second case. A minimal reproduction script is provided below. It creates a temp directory, main.go there and installs kong, and then runs the app 3 times with different parameter suppliment methods.

#!/bin/bash

tempdir=$(mktemp -d)
echo "entering temp dir: $tempdir"
cd "$tempdir"

cat <<'EOF' >main.go
package main

import (
  "fmt"
  "github.com/alecthomas/kong"
)

type CustomField string

func (c CustomField) AfterApply() error {
  fmt.Println(c)
  return nil
}

type CLI struct {
  Config kong.ConfigFlag `name:"config"`
  CustomField CustomField `name:"custom-field" env:"CUSTOM_FIELD" required:""`
}

func main() {
  var cli CLI
  kong.Parse(&cli, kong.Configuration(kong.JSON))
}
EOF

go mod init repro
go get github.com/alecthomas/kong@v1.15.0

go run main.go --custom-field running-with-cli-parameter
CUSTOM_FIELD=running-with-env-parameter go run main.go
go run main.go --config <(echo '{"custom_field": "running-with-json-config"}')

The actual output:

entering temp dir: /var/folders/hv/2d98p0sj72vbvcps49zpm7yh0000gq/T/tmp.2FJWWmMOrS
go: creating new go.mod: module repro
go: to add module requirements and sums:
        go mod tidy
go: added github.com/alecthomas/kong v1.15.0
running-with-cli-parameter
running-with-json-config

The output expected by me:

entering temp dir: /var/folders/hv/2d98p0sj72vbvcps49zpm7yh0000gq/T/tmp.2FJWWmMOrS
go: creating new go.mod: module repro
go: to add module requirements and sums:
        go mod tidy
go: added github.com/alecthomas/kong v1.15.0
running-with-cli-parameter
running-with-env-parameter <------ this line
running-with-json-config

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions