src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

datetime.go (883B)


      1 package datetime
      2 
      3 import (
      4 	"context"
      5 	"fmt"
      6 	"os/exec"
      7 	"strings"
      8 )
      9 
     10 type Block struct {
     11 	format   string
     12 	label    string
     13 	timezone string
     14 }
     15 
     16 type Parameters struct {
     17 	Format   string
     18 	Label    string
     19 	Timezone string
     20 }
     21 
     22 func New(p Parameters) *Block {
     23 	if p.Timezone == "" {
     24 		p.Timezone = "UTC"
     25 	}
     26 
     27 	return &Block{
     28 		format:   p.Format,
     29 		label:    p.Label,
     30 		timezone: p.Timezone,
     31 	}
     32 }
     33 
     34 func (b *Block) Name() string {
     35 	return "datetime"
     36 }
     37 
     38 func (b *Block) Render(ctx context.Context) (string, error) {
     39 	cmd := exec.CommandContext(ctx, "date", b.format)
     40 	cmd.Env = append(cmd.Env, fmt.Sprintf("TZ=%s", b.timezone))
     41 
     42 	out, err := cmd.Output()
     43 	if err != nil {
     44 		return "", fmt.Errorf("failed to exec: %v", err)
     45 	}
     46 
     47 	if b.label != "" {
     48 		return fmt.Sprintf(
     49 			"%s %s", b.label, strings.TrimSpace(string(out)),
     50 		), nil
     51 	} else {
     52 		return strings.TrimSpace(string(out)), nil
     53 	}
     54 }