github.com/freiheit-com/kuberpult@v1.24.2-0.20240328135542-315d5630abe6/services/cd-service/pkg/repository/time.go (about)

     1  /*This file is part of kuberpult.
     2  
     3  Kuberpult is free software: you can redistribute it and/or modify
     4  it under the terms of the Expat(MIT) License as published by
     5  the Free Software Foundation.
     6  
     7  Kuberpult is distributed in the hope that it will be useful,
     8  but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  MIT License for more details.
    11  
    12  You should have received a copy of the MIT License
    13  along with kuberpult. If not, see <https://directory.fsf.org/wiki/License:Expat>.
    14  
    15  Copyright 2023 freiheit.com*/
    16  
    17  package repository
    18  
    19  import (
    20  	"context"
    21  	"time"
    22  )
    23  
    24  type ctxMarker struct{}
    25  
    26  var (
    27  	ctxMarkerKey = &ctxMarker{}
    28  )
    29  
    30  func getTimeNow(ctx context.Context) time.Time {
    31  	t, ok := ctx.Value(ctxMarkerKey).(time.Time)
    32  	if !ok {
    33  		panic("no time in context")
    34  	}
    35  	return t
    36  }
    37  
    38  func WithTimeNow(ctx context.Context, t time.Time) context.Context {
    39  	if _, ok := ctx.Value(ctxMarkerKey).(time.Time); ok {
    40  		// already has time. used in testing
    41  		return ctx
    42  	}
    43  	return context.WithValue(ctx, ctxMarkerKey, t)
    44  }