bashgobuildah

Formatting a Go date in a bash-friendly manner


Using buildah, I can find out the date my image was built at with this call:

buildah images --format '{{.CreatedAt}}' my_image

The --format argument is a Go template, as described for a related command.

This returns:

Nov 13, 2018 08:04

As far as I can tell that is my current timezone it uses, but it's not localised, and it's missing timezone information. If I feed the output into Linux's date like so:

date -d "`buildah images --format '{{.CreatedAt}}' my_container`" +%s

This gives me what I want, UNIX epoch seconds:

1542063840

However, since my '{{.CreatedAt}}' is a Go template that I should be able to format, how can I directly print out epoch seconds (or RFC-3339, etc) rather than relying on date.

As you can guess, I am an utter Go newbie and the documentation provided nothing I could copy-paste


NOTE: Following the below answer, enhancement request posted to the buildah issues db.


Solution

  • Unfortunately you are out of luck.

    The parameter value passed to the template execution is of type imageOutputParams, which is declared in images.go:

    type imageOutputParams struct {
        Tag       string
        ID        string
        Name      string
        Digest    string
        CreatedAt string
        Size      string
    }
    

    As you can see, the CreatedAt field is of type string, not a time.Time, so you can't call time.Time methods on it. Neither can you do any useful date/time processing on it without custom registered functions. But since you're just supplying the template text, you can't register custom functions either.

    The template you pass is executed in function outputUsingTemplate() like this:

    err = tmpl.Execute(os.Stdout, params)
    

    Where params is a value of the above mentioned struct.

    Recommend the project owners to add a new field holding the CreatedAt timestamp as a time.Time value, so you can get the epoch seconds using Time.Unix(). The template would look like this then:

    {{.CreatedAtTime.Unix}}