Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion bake/hclparser/stdlib.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ var stdlibFunctions = []funcDef{
{name: "trimspace", fn: stdlib.TrimSpaceFunc},
{name: "trimsuffix", fn: stdlib.TrimSuffixFunc},
{name: "try", fn: tryfunc.TryFunc, descriptionAlt: `Variadic function that tries to evaluate all of is arguments in sequence until one succeeds, in which case it returns that result, or returns an error if none of them succeed.`},
{name: "unixtimestampparse", factory: unixtimestampParseFunc},
{name: "upper", fn: stdlib.UpperFunc},
{name: "urlencode", fn: encoding.URLEncodeFunc, descriptionAlt: `Applies URL encoding to a given string.`},
{name: "uuidv4", fn: uuid.V4Func, descriptionAlt: `Generates and returns a Type-4 UUID in the standard hexadecimal string format.`},
Expand Down Expand Up @@ -248,7 +249,7 @@ func sanitizeFunc() function.Function {

// timestampFunc constructs a function that returns a string representation of the current date and time.
//
// This function was imported from terraform's datetime utilities.
// This function was imported from Terraform's datetime utilities.
func timestampFunc() function.Function {
return function.New(&function.Spec{
Description: `Returns a string representation of the current date and time.`,
Expand Down Expand Up @@ -281,6 +282,59 @@ func homedirFunc() function.Function {
})
}

// unixtimestampParseFunc, given a unix timestamp integer, will parse and
// return an object representation of that date and time
//
// This function is similar to the `unix_timestamp_parse` function in Terraform:
// https://registry.terraform.io/providers/hashicorp/time/latest/docs/functions/unix_timestamp_parse
func unixtimestampParseFunc() function.Function {
return function.New(&function.Spec{
Description: `Given a unix timestamp integer, will parse and return an object representation of that date and time. A unix timestamp is the number of seconds elapsed since January 1, 1970 UTC.`,
Params: []function.Parameter{
{
Name: "unix_timestamp",
Description: "Unix Timestamp integer to parse",
Type: cty.Number,
},
},
Type: function.StaticReturnType(cty.Object(map[string]cty.Type{
"year": cty.Number,
"year_day": cty.Number,
"day": cty.Number,
"month": cty.Number,
"month_name": cty.String,
"weekday": cty.Number,
"weekday_name": cty.String,
"hour": cty.Number,
"minute": cty.Number,
"second": cty.Number,
"rfc3339": cty.String,
"iso_year": cty.Number,
"iso_week": cty.Number,
})),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
ts, _ := args[0].AsBigFloat().Int64()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see above

Copy link

@sdavids sdavids Jul 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might want to also handle the error.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might want to also handle the error.

.Int64() does not return an error as second value but accuracy: https://pkg.go.dev/math/big#Float.Int64

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my note for the tests … someone could conceivably supply the following values -1, 0, 1.2, and "0"

unixTime := time.Unix(ts, 0).UTC()
isoYear, isoWeek := unixTime.ISOWeek()
return cty.ObjectVal(map[string]cty.Value{
"year": cty.NumberIntVal(int64(unixTime.Year())),
"year_day": cty.NumberIntVal(int64(unixTime.YearDay())),
"day": cty.NumberIntVal(int64(unixTime.Day())),
"month": cty.NumberIntVal(int64(unixTime.Month())),
"month_name": cty.StringVal(unixTime.Month().String()),
"weekday": cty.NumberIntVal(int64(unixTime.Weekday())),
"weekday_name": cty.StringVal(unixTime.Weekday().String()),
"hour": cty.NumberIntVal(int64(unixTime.Hour())),
"minute": cty.NumberIntVal(int64(unixTime.Minute())),
"second": cty.NumberIntVal(int64(unixTime.Second())),
"rfc3339": cty.StringVal(unixTime.Format(time.RFC3339)),
"iso_year": cty.NumberIntVal(int64(isoYear)),
"iso_week": cty.NumberIntVal(int64(isoWeek)),
}), nil
},
})
}

func Stdlib() map[string]function.Function {
funcs := make(map[string]function.Function, len(stdlibFunctions))
for _, v := range stdlibFunctions {
Expand Down
26 changes: 26 additions & 0 deletions bake/hclparser/stdlib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,29 @@ func TestHomedir(t *testing.T) {
require.NotEmpty(t, home.AsString())
require.True(t, filepath.IsAbs(home.AsString()))
}

func TestUnixTimestampParseFunc(t *testing.T) {
Copy link

@sdavids sdavids Jul 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might want to add tests for -1, 0, 1.2, and "0".

fn := unixtimestampParseFunc()
input := cty.NumberIntVal(1690328596)
got, err := fn.Call([]cty.Value{input})
require.NoError(t, err)

expected := map[string]cty.Value{
"year": cty.NumberIntVal(2023),
"year_day": cty.NumberIntVal(206),
"day": cty.NumberIntVal(25),
"month": cty.NumberIntVal(7),
"month_name": cty.StringVal("July"),
"weekday": cty.NumberIntVal(2),
"weekday_name": cty.StringVal("Tuesday"),
"hour": cty.NumberIntVal(23),
"minute": cty.NumberIntVal(43),
"second": cty.NumberIntVal(16),
"rfc3339": cty.StringVal("2023-07-25T23:43:16Z"),
"iso_year": cty.NumberIntVal(2023),
"iso_week": cty.NumberIntVal(30),
}
for k, v := range expected {
require.True(t, got.GetAttr(k).RawEquals(v), "field %s: got %v, want %v", k, got.GetAttr(k), v)
}
}
34 changes: 34 additions & 0 deletions docs/bake-stdlib.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ title: Bake standard library functions
| [`trimspace`](#trimspace) | Removes any consecutive space characters (as defined by Unicode) from the start and end of the given string. |
| [`trimsuffix`](#trimsuffix) | Removes the given suffix from the start of the given string, if present. |
| [`try`](#try) | Variadic function that tries to evaluate all of is arguments in sequence until one succeeds, in which case it returns that result, or returns an error if none of them succeed. |
| [`unixtimestampparse`](#unixtimestampparse) | Given a unix timestamp integer, will parse and return an object representation of that date and time. A unix timestamp is the number of seconds elapsed since January 1, 1970 UTC. |
| [`upper`](#upper) | Returns the given string with all Unicode letters translated to their uppercase equivalents. |
| [`urlencode`](#urlencode) | Applies URL encoding to a given string. |
| [`uuidv4`](#uuidv4) | Generates and returns a Type-4 UUID in the standard hexadecimal string format. |
Expand Down Expand Up @@ -1385,6 +1386,39 @@ target "webapp-dev" {
}
```

### <a name="unixtimestampparse"></a> `unixtimestampparse`

The returned object has the following attributes:
* `year` (Number) The year for the unix timestamp.
* `year_day` (Number) The day of the year for the unix timestamp, in the range 1-365 for non-leap years, and 1-366 in leap years.
* `day` (Number) The day of the month for the unix timestamp.
* `month` (Number) The month of the year for the unix timestamp.
* `month_name` (String) The name of the month for the unix timestamp (ex. "January").
* `weekday` (Number) The day of the week for the unix timestamp.
* `weekday_name` (String) The name of the day for the unix timestamp (ex. "Sunday").
* `hour` (Number) The hour within the day for the unix timestamp, in the range 0-23.
* `minute` (Number) The minute offset within the hour for the unix timestamp, in the range 0-59.
* `second` (Number) The second offset within the minute for the unix timestamp, in the range 0-59.
* `rfc3339` (String) The RFC3339 format string.
* `iso_year` (Number) The ISO 8601 year number.
* `iso_week` (Number) The ISO 8601 week number.

```hcl
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about

variable "SOURCE_DATE_EPOCH" {
  type    = number
  default = formattimestamp("X", "2015-10-21T00:00:00Z")
}

target "default" {
  args = {
    SOURCE_DATE_EPOCH = SOURCE_DATE_EPOCH
    BUILD_TIME = formattimestamp("YYYY-MM-DD'T'00:00:00Z", SOURCE_DATE_EPOCH)
  }
}

I'm also ok for special formatting for rfc3399 for less verbosity.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked at forking FormatDateFunc func as they are not willing to accept timestamp format: zclconf/go-cty#130 (comment) but there's quite a lot to fork and it might be better to be aligned so users are not confused. So that's why I opted for the terraform unix_timestamp_parse function func instead.

# docker-bake.hcl
variable "SOURCE_DATE_EPOCH" {
type = number
default = 1690328596
}
target "default" {
args = {
SOURCE_DATE_EPOCH = SOURCE_DATE_EPOCH
}
labels = {
"org.opencontainers.image.created" = unixtimestampparse(SOURCE_DATE_EPOCH).rfc3339
}
}
```

### <a name="upper"></a> `upper`

```hcl
Expand Down