diff --git a/sdk/environment.go b/sdk/environment.go index a7921a6b6a..86e97c1c44 100644 --- a/sdk/environment.go +++ b/sdk/environment.go @@ -1,6 +1,7 @@ package sdk import ( + json "encoding/json" "time" ) @@ -18,6 +19,46 @@ type Environment struct { FromRepository string `json:"from_repository,omitempty"` } +// UnmarshalJSON custom for last modified. +func (e *Environment) UnmarshalJSON(data []byte) error { + var tmp struct { + ID int64 `json:"id"` + Name string `json:"name"` + Variables []Variable `json:"variables"` + ProjectKey string `json:"project_key"` + Created time.Time `json:"created"` + Keys []EnvironmentKey `json:"keys"` + Usage *Usage `json:"usage"` + FromRepository string `json:"from_repository"` + } + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + e.ID = tmp.ID + e.Name = tmp.Name + e.Variables = tmp.Variables + e.ProjectKey = tmp.ProjectKey + e.Created = tmp.Created + e.Keys = tmp.Keys + e.Usage = tmp.Usage + e.FromRepository = tmp.FromRepository + + var v map[string]interface{} + if err := json.Unmarshal(data, &v); err != nil { + return err + } + if lastModifiedNumber, ok := v["last_modified"].(float64); ok { + e.LastModified = time.Unix(int64(lastModifiedNumber), 0) + } + if lastModifiedString, ok := v["last_modified"].(string); ok { + date, _ := time.Parse(time.RFC3339, lastModifiedString) + e.LastModified = date + } + + return nil +} + // EnvironmentVariableAudit represents an audit on an environment variable type EnvironmentVariableAudit struct { ID int64 `json:"id" yaml:"-" db:"id"` diff --git a/sdk/environment_test.go b/sdk/environment_test.go new file mode 100644 index 0000000000..bb7de499e2 --- /dev/null +++ b/sdk/environment_test.go @@ -0,0 +1,32 @@ +package sdk_test + +import ( + json "encoding/json" + "fmt" + "testing" + "time" + + "github.com/ovh/cds/sdk" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEnvironmentUnmarshal(t *testing.T) { + now := time.Unix(time.Now().Unix(), 0) + + nowBytes, err := json.Marshal(now) + require.NoError(t, err) + + data1 := []byte(fmt.Sprintf("{\"name\":\"one\",\"last_modified\":%s}", nowBytes)) + data2 := []byte(fmt.Sprintf("{\"name\":\"two\",\"last_modified\":%d}", now.Unix())) + + var one sdk.Environment + require.NoError(t, json.Unmarshal(data1, &one)) + assert.Equal(t, "one", one.Name) + assert.True(t, now.Equal(one.LastModified)) + + var two sdk.Environment + require.NoError(t, json.Unmarshal(data2, &two)) + assert.Equal(t, "two", two.Name) + assert.True(t, now.Equal(two.LastModified)) +}