github.com/oam-dev/kubevela@v1.9.11/pkg/workflow/providers/time/date.go (about)

     1  /*
     2   Copyright 2021. The KubeVela Authors.
     3  
     4   Licensed under the Apache License, Version 2.0 (the "License");
     5   you may not use this file except in compliance with the License.
     6   You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10   Unless required by applicable law or agreed to in writing, software
    11   distributed under the License is distributed on an "AS IS" BASIS,
    12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   See the License for the specific language governing permissions and
    14   limitations under the License.
    15  */
    16  
    17  package time
    18  
    19  import (
    20  	"time"
    21  
    22  	monitorContext "github.com/kubevela/pkg/monitor/context"
    23  	wfContext "github.com/kubevela/workflow/pkg/context"
    24  	"github.com/kubevela/workflow/pkg/cue/model/value"
    25  	"github.com/kubevela/workflow/pkg/types"
    26  )
    27  
    28  const (
    29  	// ProviderName is provider name for install.
    30  	ProviderName = "time"
    31  )
    32  
    33  type provider struct {
    34  }
    35  
    36  func (h *provider) Timestamp(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
    37  	date, err := v.GetString("date")
    38  	if err != nil {
    39  		return err
    40  	}
    41  	layout, err := v.GetString("layout")
    42  	if err != nil {
    43  		return err
    44  	}
    45  	if layout == "" {
    46  		layout = time.RFC3339
    47  	}
    48  	t, err := time.Parse(layout, date)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	return v.FillObject(t.Unix(), "timestamp")
    53  }
    54  
    55  func (h *provider) Date(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error {
    56  	timestamp, err := v.GetInt64("timestamp")
    57  	if err != nil {
    58  		return err
    59  	}
    60  	layout, err := v.GetString("layout")
    61  	if err != nil {
    62  		return err
    63  	}
    64  
    65  	if layout == "" {
    66  		layout = time.RFC3339
    67  	}
    68  	t := time.Unix(timestamp, 0)
    69  	return v.FillObject(t.UTC().Format(layout), "date")
    70  }
    71  
    72  // Install register handlers to provider discover.
    73  func Install(p types.Providers) {
    74  	prd := &provider{}
    75  	p.Register(ProviderName, map[string]types.Handler{
    76  		"timestamp": prd.Timestamp,
    77  		"date":      prd.Date,
    78  	})
    79  }