From 6583b4eba8b1bdb5661f4b36d2d46a7ad887455f Mon Sep 17 00:00:00 2001 From: Sascha Schwarze Date: Fri, 24 Nov 2023 09:56:49 +0100 Subject: [PATCH] Use v1 Tekton PipelineRun and v1beta1 Build and BuildRun --- .github/actions/setup/action.yaml | 7 + Makefile | 4 +- controllers/customrun_controller.go | 31 +- controllers/inventory_controller.go | 6 +- controllers/pipelinerun_controller.go | 24 +- hack/download-crds.sh | 6 + main.go | 10 +- pkg/constants/constants.go | 17 +- pkg/filter/annotation.go | 22 +- pkg/filter/annotation_test.go | 20 +- pkg/filter/buildrun.go | 4 +- pkg/filter/buildrun_test.go | 8 +- pkg/filter/customrun.go | 24 +- pkg/filter/customrun_test.go | 40 +- pkg/filter/extra_fields.go | 4 +- pkg/filter/label.go | 6 +- pkg/filter/label_test.go | 4 +- pkg/filter/pipelinerun.go | 24 +- pkg/filter/pipelinerun_test.go | 34 +- pkg/inventory/fake_test.go | 19 +- pkg/inventory/interface.go | 8 +- pkg/inventory/inventory.go | 30 +- pkg/inventory/inventory_test.go | 62 +- test/integration/customrun_controller_test.go | 36 +- test/integration/helper_test.go | 27 +- test/integration/inventory_controller_test.go | 8 +- .../pipelinerun_controller_test.go | 4 +- test/integration/suite_test.go | 12 +- test/stubs/shipwright.go | 47 +- test/stubs/tekton.go | 75 +- .../apis/build/v1beta1/build_conversion.go | 451 ++++++ .../pkg/apis/build/v1beta1/build_types.go | 276 ++++ .../apis/build/v1beta1/buildrun_conversion.go | 256 ++++ .../pkg/apis/build/v1beta1/buildrun_types.go | 385 +++++ .../pkg/apis/build/v1beta1/buildstrategy.go | 202 +++ .../build/v1beta1/buildstrategy_conversion.go | 278 ++++ .../apis/build/v1beta1/buildstrategy_types.go | 94 ++ .../clusterbuildstrategy_conversion.go | 59 + .../v1beta1/clusterbuildstrategy_types.go | 95 ++ .../build/pkg/apis/build/v1beta1/doc.go | 8 + .../build/pkg/apis/build/v1beta1/parameter.go | 54 + .../build/pkg/apis/build/v1beta1/register.go | 36 + .../build/pkg/apis/build/v1beta1/source.go | 124 ++ .../build/pkg/apis/build/v1beta1/trigger.go | 15 + .../pkg/apis/build/v1beta1/trigger_types.go | 66 + .../pkg/apis/build/v1beta1/trigger_when.go | 41 + .../build/v1beta1/zz_generated.deepcopy.go | 1317 +++++++++++++++++ .../shipwright-io/build/pkg/ctxlog/context.go | 55 + .../shipwright-io/build/pkg/ctxlog/log.go | 75 + vendor/modules.txt | 2 + 50 files changed, 4217 insertions(+), 295 deletions(-) create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_conversion.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_types.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_conversion.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_types.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_conversion.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_types.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_conversion.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_types.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/doc.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/parameter.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/register.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/source.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_types.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_when.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/zz_generated.deepcopy.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/ctxlog/context.go create mode 100644 vendor/github.com/shipwright-io/build/pkg/ctxlog/log.go diff --git a/.github/actions/setup/action.yaml b/.github/actions/setup/action.yaml index 3e1e2a68..db637d36 100644 --- a/.github/actions/setup/action.yaml +++ b/.github/actions/setup/action.yaml @@ -15,3 +15,10 @@ runs: cache: true check-latest: true - uses: ko-build/setup-ko@v0.6 + - name: install-goml + shell: bash + run: | + TAG_NAME="$(curl -s https://api.github.com/repos/herrjulz/goml/releases/latest | jq -r '.tag_name')" + curl -o /usr/local/bin/goml -L -s "https://github.com/herrjulz/goml/releases/download/${TAG_NAME}/goml-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m | sed -e 's/x86_64/amd64/')" + chmod +x /usr/local/bin/goml + goml -v diff --git a/Makefile b/Makefile index 9c88b506..d53d248b 100644 --- a/Makefile +++ b/Makefile @@ -37,8 +37,8 @@ CHART_DIR ?= ./chart MANIFEST_DIR ?= $(CHART_DIR)/generated # shipwright and tekton target versions to download upstream crd resources -SHIPWRIGHT_VERSION ?= v0.11.0 -TEKTON_VERSION ?= v0.44.0 +SHIPWRIGHT_VERSION ?= v0.12.0 +TEKTON_VERSION ?= v0.53.2 # full path to the directory where the crds are downloaded CRD_DIR ?= $(LOCAL_BIN)/crds diff --git a/controllers/customrun_controller.go b/controllers/customrun_controller.go index c2e61b1d..96b4bedf 100644 --- a/controllers/customrun_controller.go +++ b/controllers/customrun_controller.go @@ -8,11 +8,11 @@ import ( "context" "fmt" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/filter" "github.com/go-logr/logr" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -46,9 +46,9 @@ type CustomRunReconciler struct { // BuildRun name is randomly generated using the Run's name as base. func (r *CustomRunReconciler) generateBuildRun( ctx context.Context, - customRun *tknv1beta1.CustomRun, -) (*v1alpha1.BuildRun, error) { - br := v1alpha1.BuildRun{ + customRun *tektonapibeta.CustomRun, +) (*buildapi.BuildRun, error) { + br := buildapi.BuildRun{ ObjectMeta: metav1.ObjectMeta{ Namespace: customRun.GetNamespace(), Name: names.SimpleNameGenerator.GenerateName(fmt.Sprintf("%s-", customRun.Name)), @@ -56,10 +56,9 @@ func (r *CustomRunReconciler) generateBuildRun( filter.OwnedByTektonCustomRun: customRun.Name, }, }, - Spec: v1alpha1.BuildRunSpec{ - BuildRef: &v1alpha1.BuildRef{ - APIVersion: &customRun.Spec.CustomRef.APIVersion, - Name: customRun.Spec.CustomRef.Name, + Spec: buildapi.BuildRunSpec{ + Build: buildapi.ReferencedBuild{ + Name: &customRun.Spec.CustomRef.Name, }, ParamValues: filter.TektonCustomRunParamsToShipwrightParamValues(customRun), Timeout: customRun.Spec.Timeout, @@ -75,8 +74,8 @@ func (r *CustomRunReconciler) generateBuildRun( // reflectBuildRunStatusOnTektonRun reflects the BuildRun status on the Run instance. func (r *CustomRunReconciler) reflectBuildRunStatusOnTektonCustomRun( logger logr.Logger, - customRun *tknv1beta1.CustomRun, - br *v1alpha1.BuildRun, + customRun *tektonapibeta.CustomRun, + br *buildapi.BuildRun, ) { if br.Status.CompletionTime != nil { customRun.Status.CompletionTime = br.Status.CompletionTime @@ -127,7 +126,7 @@ func (r *CustomRunReconciler) Reconcile( ) (ctrl.Result, error) { logger := log.FromContext(ctx) - var customRun tknv1beta1.CustomRun + var customRun tektonapibeta.CustomRun err := r.Get(ctx, req.NamespacedName, &customRun) if err != nil { if !errors.IsNotFound(err) { @@ -154,7 +153,7 @@ func (r *CustomRunReconciler) Reconcile( return RequeueOnError(err) } - var br = &v1alpha1.BuildRun{} + var br = &buildapi.BuildRun{} // when the status extra-fields is empty, it means the BuildRun instance is not created yet, thus // the first step is issuing the instance and later on watching over its status updates if extraFields.IsEmpty() { @@ -204,7 +203,7 @@ func (r *CustomRunReconciler) Reconcile( logger.V(0).Info("Tekton CustomRun instance is cancelled, cancelling the BuildRun too") originalBr := br.DeepCopy() - br.Spec.State = v1alpha1.BuildRunRequestedStatePtr(v1alpha1.BuildRunStateCancel) + br.Spec.State = buildapi.BuildRunRequestedStatePtr(buildapi.BuildRunStateCancel) if err = r.Client.Patch(ctx, br, client.MergeFrom(originalBr)); err != nil { logger.V(0).Error(err, "trying to patch BuildRun with cancellation state") return RequeueOnError(err) @@ -232,9 +231,9 @@ func (r *CustomRunReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). // watches Tekton Run instances, that's the principal resource for this controller - For(&tknv1beta1.CustomRun{}). + For(&tektonapibeta.CustomRun{}). // it also watches over BuildRun instances that are owned by this controller - Owns(&v1alpha1.BuildRun{}). + Owns(&buildapi.BuildRun{}). // filtering out objects that aren't ready for reconciliation WithEventFilter(predicate.NewPredicateFuncs(filter.CustomRunEventFilterPredicate)). // making sure the controller reconciles one instance at the time in order to not create a diff --git a/controllers/inventory_controller.go b/controllers/inventory_controller.go index c5ceb1c0..34848ca4 100644 --- a/controllers/inventory_controller.go +++ b/controllers/inventory_controller.go @@ -7,7 +7,7 @@ package controllers import ( "context" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/inventory" "k8s.io/apimachinery/pkg/api/errors" @@ -32,7 +32,7 @@ type InventoryReconciler struct { func (r *InventoryReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { logger := log.FromContext(ctx) - var b v1alpha1.Build + var b buildapi.Build if err := r.Get(ctx, req.NamespacedName, &b); err != nil { if !errors.IsNotFound(err) { logger.Error(err, "Unable to fetch Build, removing from the Inventory") @@ -59,7 +59,7 @@ func (r *InventoryReconciler) SetupWithManager(mgr ctrl.Manager) error { } return ctrl.NewControllerManagedBy(mgr). - For(&v1alpha1.Build{}). + For(&buildapi.Build{}). Complete(r) } diff --git a/controllers/pipelinerun_controller.go b/controllers/pipelinerun_controller.go index ae63153f..049a0a0b 100644 --- a/controllers/pipelinerun_controller.go +++ b/controllers/pipelinerun_controller.go @@ -8,12 +8,12 @@ import ( "context" "fmt" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/constants" "github.com/shipwright-io/triggers/pkg/filter" "github.com/shipwright-io/triggers/pkg/inventory" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -42,10 +42,10 @@ type PipelineRunReconciler struct { // establish ownership. Only returns the created object name and error. func (r *PipelineRunReconciler) createBuildRun( ctx context.Context, - pipelineRun *tknv1beta1.PipelineRun, + pipelineRun *tektonapi.PipelineRun, buildName string, ) (string, error) { - br := v1alpha1.BuildRun{ + br := buildapi.BuildRun{ ObjectMeta: metav1.ObjectMeta{ Namespace: pipelineRun.GetNamespace(), GenerateName: fmt.Sprintf("%s-", buildName), @@ -53,15 +53,15 @@ func (r *PipelineRunReconciler) createBuildRun( filter.OwnedByTektonPipelineRun: pipelineRun.GetName(), }, OwnerReferences: []metav1.OwnerReference{{ - APIVersion: constants.TektonAPIv1beta1, + APIVersion: constants.TektonAPIv1, Kind: "PipelineRun", Name: pipelineRun.GetName(), UID: pipelineRun.GetUID(), }}, }, - Spec: v1alpha1.BuildRunSpec{ - BuildRef: &v1alpha1.BuildRef{ - Name: buildName, + Spec: buildapi.BuildRunSpec{ + Build: buildapi.ReferencedBuild{ + Name: &buildName, }, }, } @@ -75,7 +75,7 @@ func (r *PipelineRunReconciler) createBuildRun( // the PipelineRun annotations to documented the created BuildRuns. func (r *PipelineRunReconciler) issueBuildRunsForPipelineRun( ctx context.Context, - pipelineRun *tknv1beta1.PipelineRun, + pipelineRun *tektonapi.PipelineRun, buildNames []string, ) ([]string, error) { var created []string @@ -99,7 +99,7 @@ func (r *PipelineRunReconciler) Reconcile( ) (ctrl.Result, error) { logger := log.FromContext(ctx) - var pipelineRun tknv1beta1.PipelineRun + var pipelineRun tektonapi.PipelineRun if err := r.Get(ctx, req.NamespacedName, &pipelineRun); err != nil { if !errors.IsNotFound(err) { logger.Error(err, "Unable to fetch PipelineRun") @@ -123,7 +123,7 @@ func (r *PipelineRunReconciler) Reconcile( ) // search for Builds with Pipeline triggers matching current ObjectRef criteria - buildsToBeIssued := r.buildInventory.SearchForObjectRef(v1alpha1.PipelineTrigger, objectRef) + buildsToBeIssued := r.buildInventory.SearchForObjectRef(buildapi.PipelineTrigger, objectRef) if len(buildsToBeIssued) == 0 { return Done() } @@ -197,7 +197,7 @@ func (r *PipelineRunReconciler) SetupWithManager(mgr ctrl.Manager) error { } return ctrl.NewControllerManagedBy(mgr). - For(&tknv1beta1.PipelineRun{}). + For(&tektonapi.PipelineRun{}). WithEventFilter(predicate.NewPredicateFuncs(filter.PipelineRunEventFilterPredicate)). WithOptions(controller.Options{MaxConcurrentReconciles: 1}). Complete(r) diff --git a/hack/download-crds.sh b/hack/download-crds.sh index ce48927c..46898c61 100755 --- a/hack/download-crds.sh +++ b/hack/download-crds.sh @@ -66,6 +66,10 @@ for f in ${SHIPWRIGHT_CRD_FILES[@]}; do URL_BASE="https://${REPO_HOST}/${SHIPWRIGHT_REPO_PATH}" echo "# - ${URL_BASE}/${f}" do_curl "${URL_BASE}" "${f}" + # The integration tests run without Conversion, therefore disable it and make beta the stored version + goml delete -f "${CRD_DIR}/${f}" -p spec.conversion + goml set -f "${CRD_DIR}/${f}" -p spec.versions.name:v1alpha1.storage -v false + goml set -f "${CRD_DIR}/${f}" -p spec.versions.name:v1beta1.storage -v true done echo "# Tekton '${TEKTON_VERSION}' CRDs stored at: '${CRD_DIR}'" @@ -74,4 +78,6 @@ for f in ${TEKTON_CRD_FILES[@]}; do URL_BASE="https://${REPO_HOST}/${TEKTON_REPO_PATH}" echo "# - ${URL_BASE}/${f}" do_curl "${URL_BASE}" "${f}" + # The integration tests run without Conversion, therefore disable it + goml delete -f "${CRD_DIR}/${f}" -p spec.conversion 2>/dev/null || true done diff --git a/main.go b/main.go index d0cec225..5c4b4a02 100644 --- a/main.go +++ b/main.go @@ -8,11 +8,12 @@ import ( "flag" "os" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/controllers" "github.com/shipwright-io/triggers/pkg/inventory" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" @@ -33,8 +34,9 @@ var ( func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) - utilruntime.Must(v1alpha1.AddToScheme(scheme)) - utilruntime.Must(tknv1beta1.AddToScheme(scheme)) + utilruntime.Must(buildapi.AddToScheme(scheme)) + utilruntime.Must(tektonapi.AddToScheme(scheme)) + utilruntime.Must(tektonapibeta.AddToScheme(scheme)) } func main() { diff --git a/pkg/constants/constants.go b/pkg/constants/constants.go index 4db5f015..a3fcd36b 100644 --- a/pkg/constants/constants.go +++ b/pkg/constants/constants.go @@ -7,19 +7,24 @@ package constants import ( "fmt" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" ) var ( + TektonAPIv1 = fmt.Sprintf("%s/%s", + tektonapi.SchemeGroupVersion.Group, + tektonapi.SchemeGroupVersion.Version, + ) TektonAPIv1beta1 = fmt.Sprintf("%s/%s", - tknv1beta1.SchemeGroupVersion.Group, - tknv1beta1.SchemeGroupVersion.Version, + tektonapibeta.SchemeGroupVersion.Group, + tektonapibeta.SchemeGroupVersion.Version, ) ShipwrightAPIVersion = fmt.Sprintf( "%s/%s", - v1alpha1.SchemeGroupVersion.Group, - v1alpha1.SchemeGroupVersion.Version, + buildapi.SchemeGroupVersion.Group, + buildapi.SchemeGroupVersion.Version, ) ) diff --git a/pkg/filter/annotation.go b/pkg/filter/annotation.go index 4db4cfaf..e55b9227 100644 --- a/pkg/filter/annotation.go +++ b/pkg/filter/annotation.go @@ -9,9 +9,9 @@ import ( "encoding/json" "reflect" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/util" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" ) // TriggeredBuild represents previously triggered builds by storing together the original build name @@ -19,11 +19,11 @@ import ( // Inventory. type TriggeredBuild struct { BuildName string `json:"buildName"` - ObjectRef *v1alpha1.WhenObjectRef `json:"objectRef"` + ObjectRef *buildapi.WhenObjectRef `json:"objectRef"` } // PipelineRunGetAnnotations extract the annotations, return an empty map otherwise. -func PipelineRunGetAnnotations(pipelineRun *tknv1beta1.PipelineRun) map[string]string { +func PipelineRunGetAnnotations(pipelineRun *tektonapi.PipelineRun) map[string]string { annotations := pipelineRun.GetAnnotations() if annotations == nil { annotations = map[string]string{} @@ -31,7 +31,7 @@ func PipelineRunGetAnnotations(pipelineRun *tknv1beta1.PipelineRun) map[string]s return annotations } -func PipelineRunAnnotatedNameMatchesObject(pipelineRun *tknv1beta1.PipelineRun) bool { +func PipelineRunAnnotatedNameMatchesObject(pipelineRun *tektonapi.PipelineRun) bool { annotations := PipelineRunGetAnnotations(pipelineRun) value, ok := annotations[TektonPipelineRunName] if !ok { @@ -40,7 +40,7 @@ func PipelineRunAnnotatedNameMatchesObject(pipelineRun *tknv1beta1.PipelineRun) return pipelineRun.GetName() == value } -func PipelineRunAnnotateName(pipelineRun *tknv1beta1.PipelineRun) { +func PipelineRunAnnotateName(pipelineRun *tektonapi.PipelineRun) { annotations := PipelineRunGetAnnotations(pipelineRun) annotations[TektonPipelineRunName] = pipelineRun.GetName() pipelineRun.SetAnnotations(annotations) @@ -64,7 +64,7 @@ func UnmarshalIntoTriggeredAnnotationSlice(payload string) ([]TriggeredBuild, er // valid slice of the type. When the annotation is empty, or not present, an empty slice is returned // instead. func PipelineRunExtractTriggeredBuildsSlice( - pipelineRun *tknv1beta1.PipelineRun, + pipelineRun *tektonapi.PipelineRun, ) ([]TriggeredBuild, error) { annotations := PipelineRunGetAnnotations(pipelineRun) value, ok := annotations[TektonPipelineRunTriggeredBuilds] @@ -78,7 +78,7 @@ func PipelineRunExtractTriggeredBuildsSlice( func TriggereBuildsContainsObjectRef( triggeredBuilds []TriggeredBuild, buildNames []string, - objectRef *v1alpha1.WhenObjectRef, + objectRef *buildapi.WhenObjectRef, ) bool { for _, entry := range triggeredBuilds { // first of all, the build name must be the same @@ -103,7 +103,7 @@ func TriggereBuildsContainsObjectRef( func AppendIntoTriggeredBuildSliceAsAnnotation( triggeredBuilds []TriggeredBuild, buildNames []string, - objectRef *v1alpha1.WhenObjectRef, + objectRef *buildapi.WhenObjectRef, ) (string, error) { for _, buildName := range buildNames { entry := TriggeredBuild{ @@ -122,10 +122,10 @@ func AppendIntoTriggeredBuildSliceAsAnnotation( // PipelineRunAppendTriggeredBuildsAnnotation set or update the triggered-builds annotation. func PipelineRunAppendTriggeredBuildsAnnotation( - pipelineRun *tknv1beta1.PipelineRun, + pipelineRun *tektonapi.PipelineRun, triggeredBuilds []TriggeredBuild, buildNames []string, - objectRef *v1alpha1.WhenObjectRef, + objectRef *buildapi.WhenObjectRef, ) error { annotations := pipelineRun.GetAnnotations() if annotations == nil { diff --git a/pkg/filter/annotation_test.go b/pkg/filter/annotation_test.go index f0c1f999..55823f81 100644 --- a/pkg/filter/annotation_test.go +++ b/pkg/filter/annotation_test.go @@ -9,9 +9,9 @@ import ( "reflect" "testing" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/test/stubs" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" ) func TestPipelineRunExtractTriggeredBuildsSlice(t *testing.T) { @@ -25,7 +25,7 @@ func TestPipelineRunExtractTriggeredBuildsSlice(t *testing.T) { pipelineRunWithTriggeredBuildsAnnotation := stubs.TektonPipelineRun("pipeline") triggeredBuilds := []TriggeredBuild{{ BuildName: "build", - ObjectRef: &v1alpha1.WhenObjectRef{}, + ObjectRef: &buildapi.WhenObjectRef{}, }} triggeredBuildsAnnotationBytes, err := json.Marshal(triggeredBuilds) if err != nil { @@ -37,7 +37,7 @@ func TestPipelineRunExtractTriggeredBuildsSlice(t *testing.T) { tests := []struct { name string - pipelineRun tknv1beta1.PipelineRun + pipelineRun tektonapi.PipelineRun want []TriggeredBuild wantErr bool }{{ @@ -77,7 +77,7 @@ func TestTriggereBuildsContainsObjectRef(t *testing.T) { name string triggeredBuilds []TriggeredBuild buildNames []string - objectRef *v1alpha1.WhenObjectRef + objectRef *buildapi.WhenObjectRef want bool }{{ name: "triggered builds contains objectRef", @@ -133,31 +133,31 @@ func TestAppendIntoTriggeredBuildSliceAsAnnotation(t *testing.T) { name string triggeredBuilds []TriggeredBuild buildNames []string - objectRef *v1alpha1.WhenObjectRef + objectRef *buildapi.WhenObjectRef want string wantErr bool }{{ name: "empty inputs", triggeredBuilds: []TriggeredBuild{}, buildNames: []string{}, - objectRef: &v1alpha1.WhenObjectRef{}, + objectRef: &buildapi.WhenObjectRef{}, want: "[]", wantErr: false, }, { name: "empty triggered-builds with a single build", triggeredBuilds: []TriggeredBuild{}, buildNames: []string{"build"}, - objectRef: &v1alpha1.WhenObjectRef{}, + objectRef: &buildapi.WhenObjectRef{}, want: "[{\"buildName\":\"build\",\"objectRef\":{}}]", wantErr: false, }, { name: "single triggered-build with single build", triggeredBuilds: []TriggeredBuild{{ BuildName: "previous-build", - ObjectRef: &v1alpha1.WhenObjectRef{}, + ObjectRef: &buildapi.WhenObjectRef{}, }}, buildNames: []string{"build"}, - objectRef: &v1alpha1.WhenObjectRef{}, + objectRef: &buildapi.WhenObjectRef{}, want: "[{\"buildName\":\"previous-build\",\"objectRef\":{}}," + "{\"buildName\":\"build\",\"objectRef\":{}}]", wantErr: false, diff --git a/pkg/filter/buildrun.go b/pkg/filter/buildrun.go index 73742fb3..ec85f76a 100644 --- a/pkg/filter/buildrun.go +++ b/pkg/filter/buildrun.go @@ -5,7 +5,7 @@ package filter import ( - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/constants" "k8s.io/apimachinery/pkg/types" @@ -13,7 +13,7 @@ import ( // ExtractBuildRunCustomRunOwner inspect the object owners for Tekton CustomRun and returns it, // otherwise nil. -func ExtractBuildRunCustomRunOwner(br *v1alpha1.BuildRun) *types.NamespacedName { +func ExtractBuildRunCustomRunOwner(br *buildapi.BuildRun) *types.NamespacedName { for _, ownerRef := range br.OwnerReferences { if ownerRef.APIVersion == constants.TektonAPIv1beta1 && ownerRef.Kind == "CustomRun" { return &types.NamespacedName{Namespace: br.GetNamespace(), Name: ownerRef.Name} diff --git a/pkg/filter/buildrun_test.go b/pkg/filter/buildrun_test.go index b8de01cc..782db8fa 100644 --- a/pkg/filter/buildrun_test.go +++ b/pkg/filter/buildrun_test.go @@ -8,7 +8,7 @@ import ( "reflect" "testing" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/constants" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -17,11 +17,11 @@ import ( func TestExtractBuildRunCustomRunOwner(t *testing.T) { tests := []struct { name string - br *v1alpha1.BuildRun + br *buildapi.BuildRun want *types.NamespacedName }{{ name: "buildrun not owned by tekton customrun", - br: &v1alpha1.BuildRun{ + br: &buildapi.BuildRun{ ObjectMeta: metav1.ObjectMeta{ OwnerReferences: []metav1.OwnerReference{}, }, @@ -29,7 +29,7 @@ func TestExtractBuildRunCustomRunOwner(t *testing.T) { want: nil, }, { name: "buildrun owned by tekton customrun", - br: &v1alpha1.BuildRun{ + br: &buildapi.BuildRun{ ObjectMeta: metav1.ObjectMeta{ OwnerReferences: []metav1.OwnerReference{{ APIVersion: constants.TektonAPIv1beta1, diff --git a/pkg/filter/customrun.go b/pkg/filter/customrun.go index 2bc5947a..c6b34f33 100644 --- a/pkg/filter/customrun.go +++ b/pkg/filter/customrun.go @@ -5,29 +5,29 @@ package filter import ( - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/constants" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" ) // TektonCustomRunParamsToShipwrightParamValues transforms the informed Tekton Run params into Shipwright // ParamValues slice. -func TektonCustomRunParamsToShipwrightParamValues(customRun *tknv1beta1.CustomRun) []v1alpha1.ParamValue { - paramValues := []v1alpha1.ParamValue{} +func TektonCustomRunParamsToShipwrightParamValues(customRun *tektonapibeta.CustomRun) []buildapi.ParamValue { + paramValues := []buildapi.ParamValue{} for i, p := range customRun.Spec.Params { - paramValue := v1alpha1.ParamValue{Name: p.Name} - if p.Value.Type == tknv1beta1.ParamTypeArray { - paramValue.Values = []v1alpha1.SingleValue{} + paramValue := buildapi.ParamValue{Name: p.Name} + if p.Value.Type == tektonapibeta.ParamTypeArray { + paramValue.Values = []buildapi.SingleValue{} for _, v := range p.Value.ArrayVal { v := v - paramValue.Values = append(paramValue.Values, v1alpha1.SingleValue{ + paramValue.Values = append(paramValue.Values, buildapi.SingleValue{ Value: &v, }) } } else { - paramValue.SingleValue = &v1alpha1.SingleValue{ + paramValue.SingleValue = &buildapi.SingleValue{ Value: &customRun.Spec.Params[i].Value.StringVal, } } @@ -37,7 +37,7 @@ func TektonCustomRunParamsToShipwrightParamValues(customRun *tknv1beta1.CustomRu } // customRunReferencesShipwright inspect the CustomRun instance looking for a TaskRef pointing to Shipwright. -func customRunReferencesShipwright(customRun *tknv1beta1.CustomRun) bool { +func customRunReferencesShipwright(customRun *tektonapibeta.CustomRun) bool { if customRun.Spec.CustomRef == nil { return false } @@ -51,7 +51,7 @@ func customRunReferencesShipwright(customRun *tknv1beta1.CustomRun) bool { func CustomRunEventFilterPredicate(obj client.Object) bool { logger := loggerForClientObj(obj, "controller.run-filter") - br, ok := obj.(*v1alpha1.BuildRun) + br, ok := obj.(*buildapi.BuildRun) if ok { logger.V(0).Info("Inspecting BuildRun instance for Tekton's CustomRun ownership") return ExtractBuildRunCustomRunOwner(br) != nil @@ -59,7 +59,7 @@ func CustomRunEventFilterPredicate(obj client.Object) bool { // the custom-tasks controller watches over Tekton's CustomRun and BuildRun objects, thus here we // ignore casting errors and skip the object - customRun, ok := obj.(*tknv1beta1.CustomRun) + customRun, ok := obj.(*tektonapibeta.CustomRun) if !ok { logger.V(0).Error(nil, "Object is not a Tekton CustomRun!") return false diff --git a/pkg/filter/customrun_test.go b/pkg/filter/customrun_test.go index 4f32b030..62ed4970 100644 --- a/pkg/filter/customrun_test.go +++ b/pkg/filter/customrun_test.go @@ -8,10 +8,10 @@ import ( "reflect" "testing" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/test/stubs" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -20,45 +20,45 @@ func TestTektonCustomRunParamsToShipwrightParamValues(t *testing.T) { tests := []struct { name string - customRun *tknv1beta1.CustomRun - want []v1alpha1.ParamValue + customRun *tektonapibeta.CustomRun + want []buildapi.ParamValue }{{ name: "run does not contain params", - customRun: &tknv1beta1.CustomRun{ - Spec: tknv1beta1.CustomRunSpec{ - Params: []tknv1beta1.Param{}, + customRun: &tektonapibeta.CustomRun{ + Spec: tektonapibeta.CustomRunSpec{ + Params: []tektonapibeta.Param{}, }, }, - want: []v1alpha1.ParamValue{}, + want: []buildapi.ParamValue{}, }, { name: "run contains an string param", - customRun: &tknv1beta1.CustomRun{ - Spec: tknv1beta1.CustomRunSpec{ - Params: []tknv1beta1.Param{{ + customRun: &tektonapibeta.CustomRun{ + Spec: tektonapibeta.CustomRunSpec{ + Params: []tektonapibeta.Param{{ Name: "string", - Value: *tknv1beta1.NewArrayOrString(value), + Value: *tektonapibeta.NewArrayOrString(value), }}, }, }, - want: []v1alpha1.ParamValue{{ + want: []buildapi.ParamValue{{ Name: "string", - SingleValue: &v1alpha1.SingleValue{ + SingleValue: &buildapi.SingleValue{ Value: &value, }, }}, }, { name: "run contains an string-array param", - customRun: &tknv1beta1.CustomRun{ - Spec: tknv1beta1.CustomRunSpec{ - Params: []tknv1beta1.Param{{ + customRun: &tektonapibeta.CustomRun{ + Spec: tektonapibeta.CustomRunSpec{ + Params: []tektonapibeta.Param{{ Name: "string-array", - Value: *tknv1beta1.NewArrayOrString(value, value), + Value: *tektonapibeta.NewArrayOrString(value, value), }}, }, }, - want: []v1alpha1.ParamValue{{ + want: []buildapi.ParamValue{{ Name: "string-array", - Values: []v1alpha1.SingleValue{{ + Values: []buildapi.SingleValue{{ Value: &value, }, { Value: &value, diff --git a/pkg/filter/extra_fields.go b/pkg/filter/extra_fields.go index fa491d25..7a4b2f71 100644 --- a/pkg/filter/extra_fields.go +++ b/pkg/filter/extra_fields.go @@ -5,7 +5,7 @@ package filter import ( - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "k8s.io/apimachinery/pkg/types" ) @@ -30,7 +30,7 @@ func (e *ExtraFields) GetNamespacedName() types.NamespacedName { } // NewExtraFields instantiates a ExtraFields with informed BuildRun. -func NewExtraFields(br *v1alpha1.BuildRun) ExtraFields { +func NewExtraFields(br *buildapi.BuildRun) ExtraFields { return ExtraFields{ BuildRunNamespace: br.GetNamespace(), BuildRunName: br.GetName(), diff --git a/pkg/filter/label.go b/pkg/filter/label.go index 02c7fbb4..f54b39bb 100644 --- a/pkg/filter/label.go +++ b/pkg/filter/label.go @@ -8,11 +8,11 @@ import ( "strings" "github.com/shipwright-io/triggers/pkg/util" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" ) // PipelineRunGetLabels extract labels from informed object, returns an empty map when `nil` labels. -func PipelineRunGetLabels(pipelineRun *tknv1beta1.PipelineRun) map[string]string { +func PipelineRunGetLabels(pipelineRun *tektonapi.PipelineRun) map[string]string { labels := pipelineRun.GetLabels() if labels == nil { labels = map[string]string{} @@ -22,7 +22,7 @@ func PipelineRunGetLabels(pipelineRun *tknv1beta1.PipelineRun) map[string]string // AppendIssuedBuildRunsLabel update or add the label to document the BuildRuns issued for the // PipelineRun instance informed. -func AppendIssuedBuildRunsLabel(pipelineRun *tknv1beta1.PipelineRun, buildRunsIssued []string) { +func AppendIssuedBuildRunsLabel(pipelineRun *tektonapi.PipelineRun, buildRunsIssued []string) { labels := PipelineRunGetLabels(pipelineRun) // contains all BuildRuns issued for the PipelineRun instance diff --git a/pkg/filter/label_test.go b/pkg/filter/label_test.go index 83216001..c1a71507 100644 --- a/pkg/filter/label_test.go +++ b/pkg/filter/label_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/shipwright-io/triggers/test/stubs" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" ) func TestAppendIssuedBuildRunsLabel(t *testing.T) { @@ -19,7 +19,7 @@ func TestAppendIssuedBuildRunsLabel(t *testing.T) { tests := []struct { name string - pipelineRun tknv1beta1.PipelineRun + pipelineRun tektonapi.PipelineRun buildRunsIssued []string want string }{{ diff --git a/pkg/filter/pipelinerun.go b/pkg/filter/pipelinerun.go index 1b9ba799..0ec92c16 100644 --- a/pkg/filter/pipelinerun.go +++ b/pkg/filter/pipelinerun.go @@ -10,12 +10,12 @@ import ( "strings" "time" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/constants" clock "k8s.io/utils/clock/testing" "sigs.k8s.io/controller-runtime/pkg/client" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" "knative.dev/pkg/apis" ) @@ -40,7 +40,7 @@ var ( // pipelineRunReferencesShipwright checks if the informed PipelineRun is referring to a Shipwright // resource via TaskRef. -func pipelineRunReferencesShipwright(pipelineRun *tknv1beta1.PipelineRun) bool { +func pipelineRunReferencesShipwright(pipelineRun *tektonapi.PipelineRun) bool { if pipelineRun.Status.PipelineSpec == nil { return false } @@ -61,7 +61,7 @@ func pipelineRunReferencesShipwright(pipelineRun *tknv1beta1.PipelineRun) bool { func PipelineRunEventFilterPredicate(obj client.Object) bool { logger := loggerForClientObj(obj, "controller.pipelinerun-filter") - pipelineRun, ok := obj.(*tknv1beta1.PipelineRun) + pipelineRun, ok := obj.(*tektonapi.PipelineRun) if !ok { logger.V(0).Error(nil, "Unable to cast object as Tekton PipelineRun") return false @@ -88,20 +88,20 @@ func PipelineRunEventFilterPredicate(obj client.Object) bool { func ParsePipelineRunStatus( ctx context.Context, now time.Time, - pipelineRun *tknv1beta1.PipelineRun, + pipelineRun *tektonapi.PipelineRun, ) (string, error) { switch { case pipelineRun.IsDone(): if pipelineRun.Status.GetCondition(apis.ConditionSucceeded).IsTrue() { - return tknv1beta1.PipelineRunReasonSuccessful.String(), nil + return tektonapi.PipelineRunReasonSuccessful.String(), nil } - return tknv1beta1.PipelineRunReasonFailed.String(), nil + return tektonapi.PipelineRunReasonFailed.String(), nil case pipelineRun.IsCancelled(): - return tknv1beta1.PipelineRunReasonCancelled.String(), nil + return tektonapi.PipelineRunReasonCancelled.String(), nil case pipelineRun.HasTimedOut(ctx, clock.NewFakePassiveClock(now)): return "TimedOut", nil case pipelineRun.HasStarted(): - return tknv1beta1.PipelineRunReasonStarted.String(), nil + return tektonapi.PipelineRunReasonStarted.String(), nil default: return "", fmt.Errorf("unable to parse pipelinerun %q current status", pipelineRun.GetNamespacedName()) @@ -112,8 +112,8 @@ func ParsePipelineRunStatus( func PipelineRunToObjectRef( ctx context.Context, now time.Time, - pipelineRun *tknv1beta1.PipelineRun, -) (*v1alpha1.WhenObjectRef, error) { + pipelineRun *tektonapi.PipelineRun, +) (*buildapi.WhenObjectRef, error) { status, err := ParsePipelineRunStatus(ctx, now, pipelineRun) if err != nil { return nil, err @@ -127,7 +127,7 @@ func PipelineRunToObjectRef( } } - return &v1alpha1.WhenObjectRef{ + return &buildapi.WhenObjectRef{ Name: pipelineRun.Spec.PipelineRef.Name, Status: []string{status}, Selector: labels, diff --git a/pkg/filter/pipelinerun_test.go b/pkg/filter/pipelinerun_test.go index fb077e05..23bbec57 100644 --- a/pkg/filter/pipelinerun_test.go +++ b/pkg/filter/pipelinerun_test.go @@ -12,19 +12,19 @@ import ( "github.com/shipwright-io/triggers/pkg/constants" "github.com/shipwright-io/triggers/test/stubs" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" ) func Test_pipelineRunReferencesShipwright(t *testing.T) { tests := []struct { name string - pipelineRun *tknv1beta1.PipelineRun + pipelineRun *tektonapi.PipelineRun want bool }{{ name: "pipelinerun has status.pipelinespec nil", - pipelineRun: &tknv1beta1.PipelineRun{ - Status: tknv1beta1.PipelineRunStatus{ - PipelineRunStatusFields: tknv1beta1.PipelineRunStatusFields{ + pipelineRun: &tektonapi.PipelineRun{ + Status: tektonapi.PipelineRunStatus{ + PipelineRunStatusFields: tektonapi.PipelineRunStatusFields{ PipelineSpec: nil, }, }, @@ -32,11 +32,11 @@ func Test_pipelineRunReferencesShipwright(t *testing.T) { want: false, }, { name: "pipelinerun does not references shipwright build", - pipelineRun: &tknv1beta1.PipelineRun{ - Status: tknv1beta1.PipelineRunStatus{ - PipelineRunStatusFields: tknv1beta1.PipelineRunStatusFields{ - PipelineSpec: &tknv1beta1.PipelineSpec{ - Tasks: []tknv1beta1.PipelineTask{{}}, + pipelineRun: &tektonapi.PipelineRun{ + Status: tektonapi.PipelineRunStatus{ + PipelineRunStatusFields: tektonapi.PipelineRunStatusFields{ + PipelineSpec: &tektonapi.PipelineSpec{ + Tasks: []tektonapi.PipelineTask{{}}, }, }, }, @@ -44,13 +44,13 @@ func Test_pipelineRunReferencesShipwright(t *testing.T) { want: false, }, { name: "pipelinerun references shipwright build", - pipelineRun: &tknv1beta1.PipelineRun{ - Status: tknv1beta1.PipelineRunStatus{ - PipelineRunStatusFields: tknv1beta1.PipelineRunStatusFields{ - PipelineSpec: &tknv1beta1.PipelineSpec{ - Tasks: []tknv1beta1.PipelineTask{{ + pipelineRun: &tektonapi.PipelineRun{ + Status: tektonapi.PipelineRunStatus{ + PipelineRunStatusFields: tektonapi.PipelineRunStatusFields{ + PipelineSpec: &tektonapi.PipelineSpec{ + Tasks: []tektonapi.PipelineTask{{ Name: "task", - TaskRef: &tknv1beta1.TaskRef{ + TaskRef: &tektonapi.TaskRef{ Name: "shipwright-build", APIVersion: constants.ShipwrightAPIVersion, Kind: "Build", @@ -74,7 +74,7 @@ func Test_pipelineRunReferencesShipwright(t *testing.T) { func TestParsePipelineRunStatus(t *testing.T) { tests := []struct { name string - pipelineRun tknv1beta1.PipelineRun + pipelineRun tektonapi.PipelineRun want string wantErr bool }{{ diff --git a/pkg/inventory/fake_test.go b/pkg/inventory/fake_test.go index 6e13648c..c23bf7b1 100644 --- a/pkg/inventory/fake_test.go +++ b/pkg/inventory/fake_test.go @@ -8,7 +8,7 @@ import ( "log" "sync" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/test/stubs" "k8s.io/apimachinery/pkg/types" ) @@ -18,7 +18,7 @@ import ( type FakeInventory struct { m sync.Mutex - cache map[types.NamespacedName]*v1alpha1.Build + cache map[types.NamespacedName]*buildapi.Build } var _ Interface = &FakeInventory{} @@ -34,7 +34,7 @@ func (i *FakeInventory) Contains(name string) bool { } // Add adds a Build to the cache. -func (i *FakeInventory) Add(b *v1alpha1.Build) { +func (i *FakeInventory) Add(b *buildapi.Build) { i.m.Lock() defer i.m.Unlock() @@ -61,10 +61,9 @@ func (i *FakeInventory) search() []SearchResult { for _, b := range i.cache { secretName := types.NamespacedName{} if b.Spec.Trigger != nil && - b.Spec.Trigger.SecretRef != nil && - b.Spec.Trigger.SecretRef.Name != "" { + b.Spec.Trigger.TriggerSecret != nil { secretName.Namespace = b.GetNamespace() - secretName.Namespace = b.Spec.Trigger.SecretRef.Name + secretName.Name = *b.Spec.Trigger.TriggerSecret } searchResults = append(searchResults, SearchResult{ BuildName: types.NamespacedName{Namespace: b.GetNamespace(), Name: b.GetName()}, @@ -76,8 +75,8 @@ func (i *FakeInventory) search() []SearchResult { // SearchForObjectRef returns all Builds in cache. func (i *FakeInventory) SearchForObjectRef( - v1alpha1.TriggerType, - *v1alpha1.WhenObjectRef, + buildapi.TriggerType, + *buildapi.WhenObjectRef, ) []SearchResult { i.m.Lock() defer i.m.Unlock() @@ -86,7 +85,7 @@ func (i *FakeInventory) SearchForObjectRef( } // SearchForGit returns all Builds in cache. -func (i *FakeInventory) SearchForGit(v1alpha1.TriggerType, string, string) []SearchResult { +func (i *FakeInventory) SearchForGit(buildapi.TriggerType, string, string) []SearchResult { i.m.Lock() defer i.m.Unlock() @@ -96,6 +95,6 @@ func (i *FakeInventory) SearchForGit(v1alpha1.TriggerType, string, string) []Sea // NewFakeInventory instante a fake inventory for testing. func NewFakeInventory() *FakeInventory { return &FakeInventory{ - cache: map[types.NamespacedName]*v1alpha1.Build{}, + cache: map[types.NamespacedName]*buildapi.Build{}, } } diff --git a/pkg/inventory/interface.go b/pkg/inventory/interface.go index e80a5c4a..4417f780 100644 --- a/pkg/inventory/interface.go +++ b/pkg/inventory/interface.go @@ -5,13 +5,13 @@ package inventory import ( - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "k8s.io/apimachinery/pkg/types" ) type Interface interface { - Add(*v1alpha1.Build) + Add(*buildapi.Build) Remove(types.NamespacedName) - SearchForObjectRef(v1alpha1.TriggerType, *v1alpha1.WhenObjectRef) []SearchResult - SearchForGit(v1alpha1.TriggerType, string, string) []SearchResult + SearchForObjectRef(buildapi.TriggerType, *buildapi.WhenObjectRef) []SearchResult + SearchForGit(buildapi.TriggerType, string, string) []SearchResult } diff --git a/pkg/inventory/inventory.go b/pkg/inventory/inventory.go index 0722f7c9..8c3d513e 100644 --- a/pkg/inventory/inventory.go +++ b/pkg/inventory/inventory.go @@ -7,7 +7,7 @@ package inventory import ( "sync" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/util" "github.com/go-logr/logr" @@ -30,20 +30,20 @@ var _ Interface = &Inventory{} // TriggerRules keeps the source and webhook trigger information for each Build instance. type TriggerRules struct { - source v1alpha1.Source - trigger v1alpha1.Trigger + source buildapi.Source + trigger buildapi.Trigger } // SearchFn search function signature. type SearchFn func(TriggerRules) bool // Add insert or update an existing record. -func (i *Inventory) Add(b *v1alpha1.Build) { +func (i *Inventory) Add(b *buildapi.Build) { i.m.Lock() defer i.m.Unlock() if b.Spec.Trigger == nil { - b.Spec.Trigger = &v1alpha1.Trigger{} + b.Spec.Trigger = &buildapi.Trigger{} } buildName := types.NamespacedName{Namespace: b.GetNamespace(), Name: b.GetName()} i.logger.V(0).Info( @@ -73,7 +73,7 @@ func (i *Inventory) Remove(buildName types.NamespacedName) { // loopByWhenType execute the search function informed against each inventory entry, when it returns // true it returns the build name on the search results instance. -func (i *Inventory) loopByWhenType(triggerType v1alpha1.TriggerType, fn SearchFn) []SearchResult { +func (i *Inventory) loopByWhenType(triggerType buildapi.TriggerType, fn SearchFn) []SearchResult { found := []SearchResult{} for k, v := range i.cache { for _, when := range v.trigger.When { @@ -82,9 +82,9 @@ func (i *Inventory) loopByWhenType(triggerType v1alpha1.TriggerType, fn SearchFn } if fn(v) { secretName := types.NamespacedName{} - if v.trigger.SecretRef != nil { + if v.trigger.TriggerSecret != nil { secretName.Namespace = k.Namespace - secretName.Name = v.trigger.SecretRef.Name + secretName.Name = *v.trigger.TriggerSecret } found = append(found, SearchResult{ BuildName: k, @@ -100,8 +100,8 @@ func (i *Inventory) loopByWhenType(triggerType v1alpha1.TriggerType, fn SearchFn // SearchForObjectRef search for builds using the ObjectRef as query parameters. func (i *Inventory) SearchForObjectRef( - triggerType v1alpha1.TriggerType, - objectRef *v1alpha1.WhenObjectRef, + triggerType buildapi.TriggerType, + objectRef *buildapi.WhenObjectRef, ) []SearchResult { i.m.Lock() defer i.m.Unlock() @@ -153,7 +153,7 @@ func (i *Inventory) SearchForObjectRef( // SearchForGit search for builds using the Git repository details, like the URL, branch name and // such type of information. func (i *Inventory) SearchForGit( - triggerType v1alpha1.TriggerType, + triggerType buildapi.TriggerType, repoURL string, branch string, ) []SearchResult { @@ -163,7 +163,13 @@ func (i *Inventory) SearchForGit( return i.loopByWhenType(triggerType, func(tr TriggerRules) bool { // first thing to compare, is the repository URL, it must match in order to define the actual // builds that are representing the repository - if !CompareURLs(repoURL, *tr.source.URL) { + if tr.source.GitSource == nil { + return false + } + if tr.source.GitSource.URL == nil { + return false + } + if !CompareURLs(repoURL, *tr.source.GitSource.URL) { return false } diff --git a/pkg/inventory/inventory_test.go b/pkg/inventory/inventory_test.go index 13ecace3..a4db511e 100644 --- a/pkg/inventory/inventory_test.go +++ b/pkg/inventory/inventory_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/onsi/gomega" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/test/stubs" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -47,30 +47,30 @@ func TestInventorySearchForgit(t *testing.T) { i.Add(buildWithTrigger) t.Run("should not find any results", func(_ *testing.T) { - found := i.SearchForGit(v1alpha1.GitHubWebHookTrigger, "", "") + found := i.SearchForGit(buildapi.GitHubWebHookTrigger, "", "") g.Expect(len(found)).To(gomega.Equal(0)) - found = i.SearchForGit(v1alpha1.GitHubWebHookTrigger, stubs.RepoURL, "") + found = i.SearchForGit(buildapi.GitHubWebHookTrigger, stubs.RepoURL, "") g.Expect(len(found)).To(gomega.Equal(0)) }) t.Run("should find the build object", func(_ *testing.T) { - found := i.SearchForGit(v1alpha1.GitHubWebHookTrigger, stubs.RepoURL, stubs.Branch) + found := i.SearchForGit(buildapi.GitHubWebHookTrigger, stubs.RepoURL, stubs.Branch) g.Expect(len(found)).To(gomega.Equal(1)) }) } func TestInventory_SearchForObjectRef(t *testing.T) { - buildWithObjectRefName := v1alpha1.Build{ + buildWithObjectRefName := buildapi.Build{ ObjectMeta: metav1.ObjectMeta{ Namespace: stubs.Namespace, Name: "buildname", }, - Spec: v1alpha1.BuildSpec{ - Trigger: &v1alpha1.Trigger{ - When: []v1alpha1.TriggerWhen{{ - Type: v1alpha1.PipelineTrigger, - ObjectRef: &v1alpha1.WhenObjectRef{ + Spec: buildapi.BuildSpec{ + Trigger: &buildapi.Trigger{ + When: []buildapi.TriggerWhen{{ + Type: buildapi.PipelineTrigger, + ObjectRef: &buildapi.WhenObjectRef{ Name: "name", Status: []string{"Successful"}, }, @@ -78,17 +78,17 @@ func TestInventory_SearchForObjectRef(t *testing.T) { }, }, } - buildWithObjectRefSelector := v1alpha1.Build{ + buildWithObjectRefSelector := buildapi.Build{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{"k": "v"}, Namespace: stubs.Namespace, Name: "buildname", }, - Spec: v1alpha1.BuildSpec{ - Trigger: &v1alpha1.Trigger{ - When: []v1alpha1.TriggerWhen{{ - Type: v1alpha1.PipelineTrigger, - ObjectRef: &v1alpha1.WhenObjectRef{ + Spec: buildapi.BuildSpec{ + Trigger: &buildapi.Trigger{ + When: []buildapi.TriggerWhen{{ + Type: buildapi.PipelineTrigger, + ObjectRef: &buildapi.WhenObjectRef{ Status: []string{"Successful"}, Selector: map[string]string{"k": "v"}, }, @@ -99,15 +99,15 @@ func TestInventory_SearchForObjectRef(t *testing.T) { tests := []struct { name string - builds []v1alpha1.Build - whenType v1alpha1.TriggerType - objectRef v1alpha1.WhenObjectRef + builds []buildapi.Build + whenType buildapi.TriggerType + objectRef buildapi.WhenObjectRef want []SearchResult }{{ name: "find build by name", - builds: []v1alpha1.Build{buildWithObjectRefName}, - whenType: v1alpha1.PipelineTrigger, - objectRef: v1alpha1.WhenObjectRef{ + builds: []buildapi.Build{buildWithObjectRefName}, + whenType: buildapi.PipelineTrigger, + objectRef: buildapi.WhenObjectRef{ Name: "name", Status: []string{"Successful"}, }, @@ -116,9 +116,9 @@ func TestInventory_SearchForObjectRef(t *testing.T) { }}, }, { name: "find build by label selector", - builds: []v1alpha1.Build{buildWithObjectRefSelector}, - whenType: v1alpha1.PipelineTrigger, - objectRef: v1alpha1.WhenObjectRef{ + builds: []buildapi.Build{buildWithObjectRefSelector}, + whenType: buildapi.PipelineTrigger, + objectRef: buildapi.WhenObjectRef{ Status: []string{"Successful"}, Selector: map[string]string{"k": "v"}, }, @@ -127,18 +127,18 @@ func TestInventory_SearchForObjectRef(t *testing.T) { }}, }, { name: "does not find builds, due to wrong selector", - builds: []v1alpha1.Build{buildWithObjectRefSelector}, - whenType: v1alpha1.PipelineTrigger, - objectRef: v1alpha1.WhenObjectRef{ + builds: []buildapi.Build{buildWithObjectRefSelector}, + whenType: buildapi.PipelineTrigger, + objectRef: buildapi.WhenObjectRef{ Status: []string{"Successful"}, Selector: map[string]string{"wrong": "label"}, }, want: []SearchResult{}, }, { name: "does not find builds, due to wrong name", - builds: []v1alpha1.Build{buildWithObjectRefSelector}, - whenType: v1alpha1.PipelineTrigger, - objectRef: v1alpha1.WhenObjectRef{ + builds: []buildapi.Build{buildWithObjectRefSelector}, + whenType: buildapi.PipelineTrigger, + objectRef: buildapi.WhenObjectRef{ Name: "wrong", Status: []string{"Successful"}, }, diff --git a/test/integration/customrun_controller_test.go b/test/integration/customrun_controller_test.go index ff7dcd9b..c5275071 100644 --- a/test/integration/customrun_controller_test.go +++ b/test/integration/customrun_controller_test.go @@ -9,11 +9,11 @@ import ( "fmt" "time" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/filter" "github.com/shipwright-io/triggers/test/stubs" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -40,7 +40,7 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { return err } - return assertBuildRun(*brNamespacedName, func(br *v1alpha1.BuildRun) error { + return assertBuildRun(*brNamespacedName, func(br *buildapi.BuildRun) error { brOwner := filter.ExtractBuildRunCustomRunOwner(br) if brOwner == nil { return fmt.Errorf("BuildRun doesn't have the owner set") @@ -57,7 +57,7 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { // assertTektonCustomRunUnknownCondition inspects the informed Tekton CustomRun instance to make sure the // condition recorded is "unknown". - assertTektonCustomRunUnknownCondition := func(customRun *tknv1beta1.CustomRun) error { + assertTektonCustomRunUnknownCondition := func(customRun *tektonapibeta.CustomRun) error { if len(customRun.Status.Conditions) != 1 { return fmt.Errorf("Unexpected amount of conditions on Tekton CustomRun status") } @@ -75,7 +75,7 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { // assertBuildRunConditionIsReflectedOnTektonCustomRun inspects the informed Tekton CustomRun object to // assert one of its conditions matches the informed last-transition-time. assertBuildRunConditionIsReflectedOnTektonCustomRun := func( - customRun *tknv1beta1.CustomRun, + customRun *tektonapibeta.CustomRun, LastTransitionTime metav1.Time, ) error { for _, c := range customRun.Status.Conditions { @@ -89,7 +89,7 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { // testTektonCustomRunTriggersBuildRun test case making sure the informed run instance has // triggered BuildRuns accordingly. - testTektonCustomRunTriggersBuildRun := func(customRun *tknv1beta1.CustomRun) types.NamespacedName { + testTektonCustomRunTriggersBuildRun := func(customRun *tektonapibeta.CustomRun) types.NamespacedName { By("Issuing a new Tekton CustomRun instance referencing Shipwright") Expect(createAndUpdateCustomRun(ctx, customRun)).Should(Succeed()) runNamespacedName := client.ObjectKeyFromObject(customRun) @@ -127,10 +127,10 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { // updateBuildRunCondition updates the BuildRun with the condition. updateBuildRunCondition := func( brNamespacedName types.NamespacedName, - condition v1alpha1.Condition, + condition buildapi.Condition, ) error { - return assertBuildRun(brNamespacedName, func(br *v1alpha1.BuildRun) error { - br.Status = v1alpha1.BuildRunStatus{Conditions: []v1alpha1.Condition{condition}} + return assertBuildRun(brNamespacedName, func(br *buildapi.BuildRun) error { + br.Status = buildapi.BuildRunStatus{Conditions: []buildapi.Condition{condition}} return kubeClient.Status().Update(ctx, br) }) } @@ -141,8 +141,8 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { brNamespacedName types.NamespacedName, lastTransitionTime metav1.Time, ) error { - return updateBuildRunCondition(brNamespacedName, v1alpha1.Condition{ - Type: v1alpha1.Succeeded, + return updateBuildRunCondition(brNamespacedName, buildapi.Condition{ + Type: buildapi.Succeeded, Status: corev1.ConditionTrue, LastTransitionTime: lastTransitionTime, Reason: "reason", @@ -152,8 +152,8 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { // updateBuildRunStatusMarkAsFailed marks the BuildRun as failed. updateBuildRunStatusMarkAsFailed := func(brNamespacedName types.NamespacedName) error { - return updateBuildRunCondition(brNamespacedName, v1alpha1.Condition{ - Type: v1alpha1.Succeeded, + return updateBuildRunCondition(brNamespacedName, buildapi.Condition{ + Type: buildapi.Succeeded, Status: corev1.ConditionFalse, LastTransitionTime: metav1.Now(), Reason: "failed", @@ -211,7 +211,7 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { eventuallyWithTimeoutFn(func() error { return assertTektonCustomRun( client.ObjectKeyFromObject(customRun), - func(r *tknv1beta1.CustomRun) error { + func(r *tektonapibeta.CustomRun) error { return assertBuildRunConditionIsReflectedOnTektonCustomRun(r, lastTransitionTime) }, ) @@ -245,7 +245,7 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { eventuallyWithTimeoutFn(func() error { return assertTektonCustomRun( client.ObjectKeyFromObject(customRun), - func(r *tknv1beta1.CustomRun) error { + func(r *tektonapibeta.CustomRun) error { if r.IsSuccessful() { return fmt.Errorf("run %q is marked as successful", r.GetName()) } @@ -273,12 +273,12 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { By(fmt.Sprintf("Canceling the Tekton CustomRun %q", customRun.GetName())) originalRun := customRun.DeepCopy() - customRun.Spec.Status = tknv1beta1.CustomRunSpecStatusCancelled + customRun.Spec.Status = tektonapibeta.CustomRunSpecStatusCancelled eventuallyWithTimeoutFn(func() error { return assertTektonCustomRun( client.ObjectKeyFromObject(customRun), - func(r *tknv1beta1.CustomRun) error { + func(r *tektonapibeta.CustomRun) error { return kubeClient.Patch(ctx, customRun, client.MergeFrom(originalRun)) }, ) @@ -289,7 +289,7 @@ var _ = Describe("CustomRun Controller", Ordered, Serial, func() { eventuallyWithTimeoutFn(func() error { return assertBuildRun( brNamespacedName, - func(br *v1alpha1.BuildRun) error { + func(br *buildapi.BuildRun) error { if !br.IsCanceled() { return fmt.Errorf("the BuildRun %q should be cancelled", br.GetName()) } diff --git a/test/integration/helper_test.go b/test/integration/helper_test.go index 2b9e8ab4..e23c3c3d 100644 --- a/test/integration/helper_test.go +++ b/test/integration/helper_test.go @@ -9,12 +9,13 @@ import ( "fmt" "time" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/pkg/filter" "github.com/shipwright-io/triggers/test/stubs" "k8s.io/apimachinery/pkg/types" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" . "github.com/onsi/gomega" @@ -31,22 +32,22 @@ var ( gracefulWait = 3 * time.Second ) -type TektonCustomRunAssertFn func(customRun *tknv1beta1.CustomRun) error +type TektonCustomRunAssertFn func(customRun *tektonapibeta.CustomRun) error // assertTektonCustomRun retrieves the Tekton CustomRun instance and execute the informed func with it. func assertTektonCustomRun(runNamespacedName types.NamespacedName, fn TektonCustomRunAssertFn) error { - var customRun tknv1beta1.CustomRun + var customRun tektonapibeta.CustomRun if err := kubeClient.Get(ctx, runNamespacedName, &customRun); err != nil { return err } return fn(&customRun) } -type BuildRunAssertFn func(br *v1alpha1.BuildRun) error +type BuildRunAssertFn func(br *buildapi.BuildRun) error // assertBuildRun retrieves the BuildRun instance and execute the informed func with it. func assertBuildRun(brNamespacedName types.NamespacedName, fn BuildRunAssertFn) error { - var br v1alpha1.BuildRun + var br buildapi.BuildRun if err := kubeClient.Get(ctx, brNamespacedName, &br); err != nil { return err } @@ -62,7 +63,7 @@ func eventuallyWithTimeoutFn(fn interface{}) gomegatypes.AsyncAssertion { // amountOfBuildRunsFn counts the amount of BuildRuns on "default" namespace. func amountOfBuildRunsFn() int { - var brs v1alpha1.BuildRunList + var brs buildapi.BuildRunList err := kubeClient.List(ctx, &brs) if err != nil { return -1 @@ -73,7 +74,7 @@ func amountOfBuildRunsFn() int { // deleteAllBuildRuns deletes all BuildRuns using DeleteAllOf ignoring possible not-found errors. func deleteAllBuildRuns() error { return client.IgnoreNotFound( - kubeClient.DeleteAllOf(ctx, &v1alpha1.BuildRun{}, + kubeClient.DeleteAllOf(ctx, &buildapi.BuildRun{}, client.InNamespace(stubs.Namespace), &client.DeleteAllOfOptions{ DeleteOptions: client.DeleteOptions{GracePeriodSeconds: &zero}, @@ -87,7 +88,7 @@ func deleteAllBuildRuns() error { // // [0] https://github.com/kubernetes-sigs/controller-runtime/pull/1640 // [1] https://github.com/kubernetes-sigs/controller-runtime/issues/1835 -func createAndUpdatePipelineRun(ctx context.Context, pipelineRun *tknv1beta1.PipelineRun) error { +func createAndUpdatePipelineRun(ctx context.Context, pipelineRun *tektonapi.PipelineRun) error { status := pipelineRun.Status.DeepCopy() var err error @@ -95,7 +96,7 @@ func createAndUpdatePipelineRun(ctx context.Context, pipelineRun *tknv1beta1.Pip return err } - var created tknv1beta1.PipelineRun + var created tektonapi.PipelineRun if err = kubeClient.Get(ctx, client.ObjectKeyFromObject(pipelineRun), &created); err != nil { return err } @@ -106,13 +107,13 @@ func createAndUpdatePipelineRun(ctx context.Context, pipelineRun *tknv1beta1.Pip // createAndUpdateCustomRun creates and updates a Run instance, using the same workaround described // on createAndUpdatePipelineRun function. -func createAndUpdateCustomRun(ctx context.Context, customRun *tknv1beta1.CustomRun) error { +func createAndUpdateCustomRun(ctx context.Context, customRun *tektonapibeta.CustomRun) error { err := kubeClient.Create(ctx, customRun) if err != nil { return err } - var created tknv1beta1.CustomRun + var created tektonapibeta.CustomRun if err = kubeClient.Get(ctx, client.ObjectKeyFromObject(customRun), &created); err != nil { return err } @@ -126,7 +127,7 @@ func createAndUpdateCustomRun(ctx context.Context, customRun *tknv1beta1.CustomR func extractBuildRunNamespacedNameFromCustomRunExtraFields( runNamespacedName types.NamespacedName, ) (*types.NamespacedName, error) { - var customRun tknv1beta1.CustomRun + var customRun tektonapibeta.CustomRun err := kubeClient.Get(ctx, runNamespacedName, &customRun) if err != nil { return nil, err diff --git a/test/integration/inventory_controller_test.go b/test/integration/inventory_controller_test.go index e537a535..bc7559f9 100644 --- a/test/integration/inventory_controller_test.go +++ b/test/integration/inventory_controller_test.go @@ -8,7 +8,7 @@ import ( "context" "time" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/test/stubs" . "github.com/onsi/ginkgo/v2" @@ -31,8 +31,8 @@ var _ = Describe("Build Inventory Controller", Ordered, func() { // amount of instances stored in the Inventory. searchForBuildWithGitHubTriggerFn := func() int { return len(buildInventory.SearchForGit( - v1alpha1.GitHubWebHookTrigger, - *buildWithGitHubTrigger.Spec.Source.URL, + buildapi.GitHubWebHookTrigger, + *buildWithGitHubTrigger.Spec.Source.GitSource.URL, stubs.Branch, )) } @@ -46,7 +46,7 @@ var _ = Describe("Build Inventory Controller", Ordered, func() { // the amount of instances found in the Inventory. searchForBuildWithPipelineTriggerFn := func() int { return len(buildInventory.SearchForObjectRef( - v1alpha1.PipelineTrigger, + buildapi.PipelineTrigger, buildWithPipelineTrigger.Spec.Trigger.When[0].ObjectRef, )) } diff --git a/test/integration/pipelinerun_controller_test.go b/test/integration/pipelinerun_controller_test.go index 62d2bd74..8ac74a94 100644 --- a/test/integration/pipelinerun_controller_test.go +++ b/test/integration/pipelinerun_controller_test.go @@ -11,7 +11,7 @@ import ( "github.com/shipwright-io/triggers/pkg/filter" "github.com/shipwright-io/triggers/test/stubs" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -93,7 +93,7 @@ var _ = Describe("PipelineRun Controller", Ordered, func() { eventuallyWithTimeoutFn(amountOfBuildRunsFn).Should(Equal(1)) eventuallyWithTimeoutFn(func() bool { - var pr tknv1beta1.PipelineRun + var pr tektonapi.PipelineRun if err := kubeClient.Get(ctx, pipelineRun.GetNamespacedName(), &pr); err != nil { return false } diff --git a/test/integration/suite_test.go b/test/integration/suite_test.go index d52fd02b..585b2049 100644 --- a/test/integration/suite_test.go +++ b/test/integration/suite_test.go @@ -10,11 +10,12 @@ import ( "testing" "time" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" "github.com/shipwright-io/triggers/controllers" "github.com/shipwright-io/triggers/pkg/inventory" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" @@ -66,10 +67,13 @@ var _ = BeforeSuite(func() { err = scheme.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) - err = v1alpha1.AddToScheme(scheme.Scheme) + err = buildapi.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) - err = tknv1beta1.AddToScheme(scheme.Scheme) + err = tektonapi.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + + err = tektonapibeta.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) kubeClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) diff --git a/test/stubs/shipwright.go b/test/stubs/shipwright.go index ba77a1f2..cd7e7707 100644 --- a/test/stubs/shipwright.go +++ b/test/stubs/shipwright.go @@ -7,7 +7,7 @@ package stubs import ( "fmt" - "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + buildapi "github.com/shipwright-io/build/pkg/apis/build/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -20,19 +20,19 @@ const ( var ( // TriggerWhenPushToMain describes a trigger for a github push event on default branch. - TriggerWhenPushToMain = v1alpha1.TriggerWhen{ - Type: v1alpha1.GitHubWebHookTrigger, - GitHub: &v1alpha1.WhenGitHub{ - Events: []v1alpha1.GitHubEventName{ - v1alpha1.GitHubPushEvent, + TriggerWhenPushToMain = buildapi.TriggerWhen{ + Type: buildapi.GitHubWebHookTrigger, + GitHub: &buildapi.WhenGitHub{ + Events: []buildapi.GitHubEventName{ + buildapi.GitHubPushEvent, }, Branches: []string{Branch}, }, } // TriggerWhenPipelineSucceeded describes a trigger for Tekton Pipeline on status "succeeded". - TriggerWhenPipelineSucceeded = v1alpha1.TriggerWhen{ - Type: v1alpha1.PipelineTrigger, - ObjectRef: &v1alpha1.WhenObjectRef{ + TriggerWhenPipelineSucceeded = buildapi.TriggerWhen{ + Type: buildapi.PipelineTrigger, + ObjectRef: &buildapi.WhenObjectRef{ Name: PipelineNameInTrigger, Status: []string{"Succeeded"}, Selector: map[string]string{}, @@ -41,25 +41,28 @@ var ( ) // ShipwrightBuild returns a Build using informed output image base and name. -func ShipwrightBuild(outputImageBase, name string) *v1alpha1.Build { - strategyKind := v1alpha1.BuildStrategyKind("ClusterBuildStrategy") +func ShipwrightBuild(outputImageBase, name string) *buildapi.Build { + strategyKind := buildapi.BuildStrategyKind("ClusterBuildStrategy") contextDir := "source-build" - return &v1alpha1.Build{ + return &buildapi.Build{ ObjectMeta: metav1.ObjectMeta{ Namespace: Namespace, Name: name, }, - Spec: v1alpha1.BuildSpec{ - Strategy: v1alpha1.Strategy{ + Spec: buildapi.BuildSpec{ + Strategy: buildapi.Strategy{ Kind: &strategyKind, Name: "buildpacks-v3", }, - Source: v1alpha1.Source{ - URL: &RepoURL, + Source: buildapi.Source{ + Type: buildapi.GitType, + GitSource: &buildapi.Git{ + URL: &RepoURL, + }, ContextDir: &contextDir, }, - Output: v1alpha1.Image{ + Output: buildapi.Image{ Image: fmt.Sprintf("%s/%s:latest", outputImageBase, name), }, }, @@ -70,16 +73,16 @@ func ShipwrightBuild(outputImageBase, name string) *v1alpha1.Build { func ShipwrightBuildWithTriggers( outputImageBase, name string, - triggers ...v1alpha1.TriggerWhen, -) *v1alpha1.Build { + triggers ...buildapi.TriggerWhen, +) *buildapi.Build { b := ShipwrightBuild(outputImageBase, name) - b.Spec.Trigger = &v1alpha1.Trigger{When: triggers} + b.Spec.Trigger = &buildapi.Trigger{When: triggers} return b } // ShipwrightBuildRun returns a empty BuildRun instance using informed name. -func ShipwrightBuildRun(name string) *v1alpha1.BuildRun { - return &v1alpha1.BuildRun{ +func ShipwrightBuildRun(name string) *buildapi.BuildRun { + return &buildapi.BuildRun{ ObjectMeta: metav1.ObjectMeta{ Namespace: Namespace, Name: name, diff --git a/test/stubs/tekton.go b/test/stubs/tekton.go index e9e43e54..fc7d86d5 100644 --- a/test/stubs/tekton.go +++ b/test/stubs/tekton.go @@ -10,41 +10,42 @@ import ( "github.com/shipwright-io/triggers/pkg/constants" - tknv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" + tektonapibeta "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -var TektonPipelineRunStatusCustomTaskShipwright = &tknv1beta1.PipelineSpec{ - Tasks: []tknv1beta1.PipelineTask{TektonPipelineTaskRefToShipwright}, +var TektonPipelineRunStatusCustomTaskShipwright = &tektonapi.PipelineSpec{ + Tasks: []tektonapi.PipelineTask{TektonPipelineTaskRefToShipwright}, } -var TektonPipelineTaskRefToShipwright = tknv1beta1.PipelineTask{ +var TektonPipelineTaskRefToShipwright = tektonapi.PipelineTask{ Name: "shipwright", - TaskRef: &tknv1beta1.TaskRef{ + TaskRef: &tektonapi.TaskRef{ APIVersion: constants.ShipwrightAPIVersion, Name: "name", }, } -var TektonTaskRefToTekton = &tknv1beta1.TaskRef{ +var TektonTaskRefToTekton = &tektonapibeta.TaskRef{ Name: "task-ex", } -func TektonTaskRefToShipwright(name string) *tknv1beta1.TaskRef { - return &tknv1beta1.TaskRef{ +func TektonTaskRefToShipwright(name string) *tektonapibeta.TaskRef { + return &tektonapibeta.TaskRef{ APIVersion: constants.ShipwrightAPIVersion, Kind: "Build", Name: name, } } -func TektonCustomRun(name string, ref *tknv1beta1.TaskRef) *tknv1beta1.CustomRun { - return &tknv1beta1.CustomRun{ +func TektonCustomRun(name string, ref *tektonapibeta.TaskRef) *tektonapibeta.CustomRun { + return &tektonapibeta.CustomRun{ ObjectMeta: metav1.ObjectMeta{ Namespace: Namespace, Name: name, }, - Spec: tknv1beta1.CustomRunSpec{ + Spec: tektonapibeta.CustomRunSpec{ CustomRef: ref, }, } @@ -52,80 +53,80 @@ func TektonCustomRun(name string, ref *tknv1beta1.TaskRef) *tknv1beta1.CustomRun // TektonCustomRunStarted returns a started (now) CustomRun instance using the name and TaskRef // informed. -func TektonCustomRunStarted(name string, ref *tknv1beta1.TaskRef) *tknv1beta1.CustomRun { +func TektonCustomRunStarted(name string, ref *tektonapibeta.TaskRef) *tektonapibeta.CustomRun { customRun := TektonCustomRun(name, ref) - customRun.Status = tknv1beta1.CustomRunStatus{ - CustomRunStatusFields: tknv1beta1.CustomRunStatusFields{ + customRun.Status = tektonapibeta.CustomRunStatus{ + CustomRunStatusFields: tektonapibeta.CustomRunStatusFields{ StartTime: &metav1.Time{Time: time.Now()}, }, } return customRun } -func TektonPipelineRunCanceled(name string) tknv1beta1.PipelineRun { +func TektonPipelineRunCanceled(name string) tektonapi.PipelineRun { pipelineRun := TektonPipelineRun(name) - pipelineRun.Spec.Status = tknv1beta1.PipelineRunSpecStatus( - tknv1beta1.PipelineRunReasonCancelled, + pipelineRun.Spec.Status = tektonapi.PipelineRunSpecStatus( + tektonapi.PipelineRunReasonCancelled, ) - pipelineRun.Status.PipelineRunStatusFields = tknv1beta1.PipelineRunStatusFields{ - PipelineSpec: &tknv1beta1.PipelineSpec{Description: "testing"}, + pipelineRun.Status.PipelineRunStatusFields = tektonapi.PipelineRunStatusFields{ + PipelineSpec: &tektonapi.PipelineSpec{Description: "testing"}, } return pipelineRun } -func TektonPipelineRunRunning(name string) tknv1beta1.PipelineRun { +func TektonPipelineRunRunning(name string) tektonapi.PipelineRun { pipelineRun := TektonPipelineRun(name) pipelineRun.Status.StartTime = &metav1.Time{Time: time.Now()} - pipelineRun.Status.PipelineRunStatusFields = tknv1beta1.PipelineRunStatusFields{ + pipelineRun.Status.PipelineRunStatusFields = tektonapi.PipelineRunStatusFields{ StartTime: &metav1.Time{Time: time.Now()}, - PipelineSpec: &tknv1beta1.PipelineSpec{Description: "testing"}, + PipelineSpec: &tektonapi.PipelineSpec{Description: "testing"}, } return pipelineRun } -func TektonPipelineRunTimedOut(name string) tknv1beta1.PipelineRun { +func TektonPipelineRunTimedOut(name string) tektonapi.PipelineRun { pipelineRun := TektonPipelineRun(name) - pipelineRun.Spec.Timeouts = &tknv1beta1.TimeoutFields{ + pipelineRun.Spec.Timeouts = &tektonapi.TimeoutFields{ Pipeline: &metav1.Duration{Duration: time.Second}, } - pipelineRun.Status.PipelineRunStatusFields = tknv1beta1.PipelineRunStatusFields{ + pipelineRun.Status.PipelineRunStatusFields = tektonapi.PipelineRunStatusFields{ StartTime: &metav1.Time{ Time: time.Date(1982, time.January, 1, 0, 0, 0, 0, time.Local), }, - PipelineSpec: &tknv1beta1.PipelineSpec{Description: "testing"}, + PipelineSpec: &tektonapi.PipelineSpec{Description: "testing"}, } return pipelineRun } -func TektonPipelineRunSucceeded(name string) tknv1beta1.PipelineRun { +func TektonPipelineRunSucceeded(name string) tektonapi.PipelineRun { pipelineRun := TektonPipelineRun(name) pipelineRun.Status.MarkSucceeded("Succeeded", fmt.Sprintf("PipelineRun %q has succeeded", name)) - pipelineRun.Status.PipelineRunStatusFields = tknv1beta1.PipelineRunStatusFields{ - PipelineSpec: &tknv1beta1.PipelineSpec{Description: "testing"}, + pipelineRun.Status.PipelineRunStatusFields = tektonapi.PipelineRunStatusFields{ + PipelineSpec: &tektonapi.PipelineSpec{Description: "testing"}, } return pipelineRun } -func TektonPipelineRunFailed(name string) tknv1beta1.PipelineRun { +func TektonPipelineRunFailed(name string) tektonapi.PipelineRun { pipelineRun := TektonPipelineRun(name) pipelineRun.Status.MarkFailed("Failed", fmt.Sprintf("PipelineRun %q has failed", name)) - pipelineRun.Status.PipelineRunStatusFields = tknv1beta1.PipelineRunStatusFields{ - PipelineSpec: &tknv1beta1.PipelineSpec{Description: "testing"}, + pipelineRun.Status.PipelineRunStatusFields = tektonapi.PipelineRunStatusFields{ + PipelineSpec: &tektonapi.PipelineSpec{Description: "testing"}, } return pipelineRun } -func TektonPipelineRun(name string) tknv1beta1.PipelineRun { - return tknv1beta1.PipelineRun{ +func TektonPipelineRun(name string) tektonapi.PipelineRun { + return tektonapi.PipelineRun{ ObjectMeta: metav1.ObjectMeta{ Namespace: Namespace, Name: name, }, - Spec: tknv1beta1.PipelineRunSpec{ - PipelineRef: &tknv1beta1.PipelineRef{ + Spec: tektonapi.PipelineRunSpec{ + PipelineRef: &tektonapi.PipelineRef{ Name: name, }, }, - Status: tknv1beta1.PipelineRunStatus{}, + Status: tektonapi.PipelineRunStatus{}, } } diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_conversion.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_conversion.go new file mode 100644 index 00000000..c246cd52 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_conversion.go @@ -0,0 +1,451 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + "context" + "strconv" + + "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + "github.com/shipwright-io/build/pkg/ctxlog" + "github.com/shipwright-io/build/pkg/webhook" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/pointer" +) + +const ( + betaGroupVersion = "shipwright.io/v1beta1" + alphaGroupVersion = "shipwright.io/v1alpha1" +) + +// ensure v1beta1 implements the Conversion interface +var _ webhook.Conversion = (*Build)(nil) + +// ConvertTo converts this Build object to v1alpha1 format. +func (src *Build) ConvertTo(ctx context.Context, obj *unstructured.Unstructured) error { + ctxlog.Debug(ctx, "Converting Build from beta to alpha", "namespace", src.Namespace, "name", src.Name) + + var alphaBuild v1alpha1.Build + + alphaBuild.TypeMeta = src.TypeMeta + alphaBuild.TypeMeta.APIVersion = alphaGroupVersion + + alphaBuild.ObjectMeta = src.ObjectMeta + + src.Spec.ConvertTo(&alphaBuild.Spec) + + // convert annotation-controlled features + if src.Spec.Retention != nil && src.Spec.Retention.AtBuildDeletion != nil { + // We must create a new Map as otherwise the addition is not kept + alphaBuild.ObjectMeta.Annotations = map[string]string{} + for k, v := range src.Annotations { + alphaBuild.ObjectMeta.Annotations[k] = v + } + alphaBuild.ObjectMeta.Annotations[v1alpha1.AnnotationBuildRunDeletion] = strconv.FormatBool(*src.Spec.Retention.AtBuildDeletion) + } + + // convert OCIArtifact to Bundle + if src.Spec.Source.OCIArtifact != nil { + alphaBuild.Spec.Source.BundleContainer = &v1alpha1.BundleContainer{ + Image: src.Spec.Source.OCIArtifact.Image, + Prune: (*v1alpha1.PruneOption)(src.Spec.Source.OCIArtifact.Prune), + } + } + + mapito, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&alphaBuild) + if err != nil { + ctxlog.Error(ctx, err, "failed structuring the newObject") + } + obj.Object = mapito + + return nil + +} + +// ConvertFrom converts a provided v1alpha1.Build object into this v1beta1.Build object. +func (src *Build) ConvertFrom(ctx context.Context, obj *unstructured.Unstructured) error { + + var alphaBuild v1alpha1.Build + + unstructured := obj.UnstructuredContent() + err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured, &alphaBuild) + if err != nil { + ctxlog.Error(ctx, err, "failed unstructuring the convertedObject") + } + + ctxlog.Debug(ctx, "Converting Build from alpha to beta", "namespace", alphaBuild.Namespace, "name", alphaBuild.Name) + + src.ObjectMeta = alphaBuild.ObjectMeta + src.TypeMeta = alphaBuild.TypeMeta + src.TypeMeta.APIVersion = betaGroupVersion + + src.Spec.ConvertFrom(&alphaBuild.Spec) + + // convert annotation-controlled features + if value, set := alphaBuild.Annotations[v1alpha1.AnnotationBuildRunDeletion]; set { + if src.Spec.Retention == nil { + src.Spec.Retention = &BuildRetention{} + } + src.Spec.Retention.AtBuildDeletion = pointer.Bool(value == "true") + delete(src.ObjectMeta.Annotations, v1alpha1.AnnotationBuildRunDeletion) + } + + src.Status = BuildStatus{ + Registered: alphaBuild.Status.Registered, + Reason: (*BuildReason)(alphaBuild.Status.Reason), + Message: alphaBuild.Status.Message, + } + + return nil +} + +func (dest *BuildSpec) ConvertFrom(orig *v1alpha1.BuildSpec) error { + // Handle BuildSpec Source + specSource := Source{} + + // only interested on spec.sources as long as an item of the list + // is of the type LocalCopy. Otherwise, we move into bundle or git types. + index, isLocal := v1alpha1.IsLocalCopyType(orig.Sources) + if isLocal { + specSource.Type = LocalType + specSource.LocalSource = &Local{ + Name: orig.Sources[index].Name, + Timeout: orig.Sources[index].Timeout, + } + } else { + if orig.Source.BundleContainer != nil { + specSource.Type = OCIArtifactType + specSource.OCIArtifact = &OCIArtifact{ + Image: orig.Source.BundleContainer.Image, + Prune: (*PruneOption)(orig.Source.BundleContainer.Prune), + } + if orig.Source.Credentials != nil { + specSource.OCIArtifact.PullSecret = &orig.Source.Credentials.Name + } + } else { + specSource.Type = GitType + specSource.GitSource = &Git{ + URL: orig.Source.URL, + Revision: orig.Source.Revision, + } + if orig.Source.Credentials != nil { + specSource.GitSource.CloneSecret = &orig.Source.Credentials.Name + } + } + } + specSource.ContextDir = orig.Source.ContextDir + dest.Source = specSource + + // Handle BuildSpec Triggers + if orig.Trigger != nil { + dest.Trigger = &Trigger{} + for i := range orig.Trigger.When { + dest.Trigger.When = append(dest.Trigger.When, convertToBetaTriggers(&orig.Trigger.When[i])) + } + if orig.Trigger.SecretRef != nil { + dest.Trigger.TriggerSecret = &orig.Trigger.SecretRef.Name + } + } + + // Handle BuildSpec Strategy + dest.Strategy = Strategy{ + Name: orig.StrategyName(), + Kind: (*BuildStrategyKind)(orig.Strategy.Kind), + } + + // Handle BuildSpec ParamValues + for _, p := range orig.ParamValues { + param := convertBetaParamValue(p) + dest.ParamValues = append(dest.ParamValues, param) + } + + //handle spec.Dockerfile migration + if orig.Dockerfile != nil { + dockerfileParam := ParamValue{ + Name: "dockerfile", + SingleValue: &SingleValue{ + Value: orig.Dockerfile, + }, + } + dest.ParamValues = append(dest.ParamValues, dockerfileParam) + } + + // handle spec.Builder migration + if orig.Builder != nil { + builderParam := ParamValue{ + Name: "builder-image", + SingleValue: &SingleValue{ + Value: &orig.Builder.Image, + }, + } + dest.ParamValues = append(dest.ParamValues, builderParam) + } + + // Handle BuildSpec Output + dest.Output.Image = orig.Output.Image + dest.Output.Insecure = orig.Output.Insecure + if orig.Output.Credentials != nil { + dest.Output.PushSecret = &orig.Output.Credentials.Name + } + + dest.Output.Annotations = orig.Output.Annotations + dest.Output.Labels = orig.Output.Labels + + // Handle BuildSpec Timeout + dest.Timeout = orig.Timeout + + // Handle BuildSpec Env + dest.Env = orig.Env + + // Handle BuildSpec Retention + if orig.Retention != nil { + dest.Retention = &BuildRetention{ + FailedLimit: orig.Retention.FailedLimit, + SucceededLimit: orig.Retention.SucceededLimit, + TTLAfterFailed: orig.Retention.TTLAfterFailed, + TTLAfterSucceeded: orig.Retention.TTLAfterSucceeded, + } + } + + // Handle BuildSpec Volumes + dest.Volumes = []BuildVolume{} + for _, vol := range orig.Volumes { + aux := BuildVolume{ + Name: vol.Name, + VolumeSource: vol.VolumeSource, + } + dest.Volumes = append(dest.Volumes, aux) + } + + return nil +} + +func (dest *BuildSpec) ConvertTo(bs *v1alpha1.BuildSpec) error { + // Handle BuildSpec Sources or Source + if dest.Source.Type == LocalType && dest.Source.LocalSource != nil { + bs.Sources = append(bs.Sources, v1alpha1.BuildSource{ + Name: dest.Source.LocalSource.Name, + Type: v1alpha1.LocalCopy, + Timeout: dest.Source.LocalSource.Timeout, + }) + } else { + bs.Source = getAlphaBuildSource(*dest) + } + + // Handle BuildSpec Trigger + if dest.Trigger != nil { + bs.Trigger = &v1alpha1.Trigger{} + for _, t := range dest.Trigger.When { + tw := v1alpha1.TriggerWhen{} + t.convertToAlpha(&tw) + bs.Trigger.When = append(bs.Trigger.When, tw) + } + if dest.Trigger.TriggerSecret != nil { + bs.Trigger.SecretRef = &corev1.LocalObjectReference{Name: *dest.Trigger.TriggerSecret} + } + } + + // Handle BuildSpec Strategy + bs.Strategy = v1alpha1.Strategy{ + Name: dest.StrategyName(), + Kind: (*v1alpha1.BuildStrategyKind)(dest.Strategy.Kind), + } + + // Handle BuildSpec Builder, TODO + bs.Builder = nil + + // Handle BuildSpec ParamValues + bs.ParamValues = nil + for _, p := range dest.ParamValues { + if p.Name == "dockerfile" && p.SingleValue != nil { + bs.Dockerfile = p.SingleValue.Value + continue + } + + if p.Name == "builder-image" && p.SingleValue != nil { + bs.Builder = &v1alpha1.Image{ + Image: *p.SingleValue.Value, + } + continue + } + param := v1alpha1.ParamValue{} + p.convertToAlpha(¶m) + bs.ParamValues = append(bs.ParamValues, param) + } + + // Handle BuildSpec Output + bs.Output.Image = dest.Output.Image + bs.Output.Insecure = dest.Output.Insecure + if dest.Output.PushSecret != nil { + bs.Output.Credentials = &corev1.LocalObjectReference{} + bs.Output.Credentials.Name = *dest.Output.PushSecret + } + bs.Output.Annotations = dest.Output.Annotations + bs.Output.Labels = dest.Output.Labels + + // Handle BuildSpec Timeout + bs.Timeout = dest.Timeout + + // Handle BuildSpec Env + bs.Env = dest.Env + + // Handle BuildSpec Retention + if dest.Retention != nil && + (dest.Retention.FailedLimit != nil || + dest.Retention.SucceededLimit != nil || + dest.Retention.TTLAfterFailed != nil || + dest.Retention.TTLAfterSucceeded != nil) { + bs.Retention = &v1alpha1.BuildRetention{ + FailedLimit: dest.Retention.FailedLimit, + SucceededLimit: dest.Retention.SucceededLimit, + TTLAfterFailed: dest.Retention.TTLAfterFailed, + TTLAfterSucceeded: dest.Retention.TTLAfterSucceeded, + } + } + + // Handle BuildSpec Volumes + bs.Volumes = []v1alpha1.BuildVolume{} + for _, vol := range dest.Volumes { + aux := v1alpha1.BuildVolume{ + Name: vol.Name, + VolumeSource: vol.VolumeSource, + } + bs.Volumes = append(bs.Volumes, aux) + } + + return nil +} + +func (p ParamValue) convertToAlpha(dest *v1alpha1.ParamValue) { + + if p.SingleValue != nil && p.SingleValue.Value != nil { + dest.SingleValue = &v1alpha1.SingleValue{} + dest.Value = p.Value + } + + if p.ConfigMapValue != nil { + dest.SingleValue = &v1alpha1.SingleValue{ + ConfigMapValue: (*v1alpha1.ObjectKeyRef)(p.ConfigMapValue), + } + } + + if p.SecretValue != nil { + dest.SingleValue = &v1alpha1.SingleValue{ + SecretValue: (*v1alpha1.ObjectKeyRef)(p.SecretValue), + } + } + + dest.Name = p.Name + + for _, singleValue := range p.Values { + dest.Values = append(dest.Values, v1alpha1.SingleValue{ + Value: singleValue.Value, + ConfigMapValue: (*v1alpha1.ObjectKeyRef)(singleValue.ConfigMapValue), + SecretValue: (*v1alpha1.ObjectKeyRef)(singleValue.SecretValue), + }) + } +} + +func (p TriggerWhen) convertToAlpha(dest *v1alpha1.TriggerWhen) { + dest.Name = p.Name + dest.Type = v1alpha1.TriggerType(p.Type) + + dest.GitHub = &v1alpha1.WhenGitHub{} + for _, e := range p.GitHub.Events { + dest.GitHub.Events = append(dest.GitHub.Events, v1alpha1.GitHubEventName(e)) + } + dest.GitHub.Branches = p.GetBranches(GitHubWebHookTrigger) + + dest.Image = (*v1alpha1.WhenImage)(p.Image) + dest.ObjectRef = (*v1alpha1.WhenObjectRef)(p.ObjectRef) + +} + +func convertBetaParamValue(orig v1alpha1.ParamValue) ParamValue { + p := ParamValue{} + if orig.SingleValue != nil && orig.SingleValue.Value != nil { + p.SingleValue = &SingleValue{} + p.Value = orig.Value + } + + if orig.ConfigMapValue != nil { + p.SingleValue = &SingleValue{} + p.ConfigMapValue = (*ObjectKeyRef)(orig.ConfigMapValue) + } + if orig.SecretValue != nil { + p.SingleValue = &SingleValue{} + p.SecretValue = (*ObjectKeyRef)(orig.SecretValue) + } + + p.Name = orig.Name + + for _, singleValue := range orig.Values { + p.Values = append(p.Values, SingleValue{ + Value: singleValue.Value, + ConfigMapValue: (*ObjectKeyRef)(singleValue.ConfigMapValue), + SecretValue: (*ObjectKeyRef)(singleValue.SecretValue), + }) + } + return p +} + +func convertToBetaTriggers(orig *v1alpha1.TriggerWhen) TriggerWhen { + dest := TriggerWhen{ + Name: orig.Name, + Type: TriggerType(orig.Type), + } + + dest.GitHub = &WhenGitHub{} + for _, e := range orig.GitHub.Events { + dest.GitHub.Events = append(dest.GitHub.Events, GitHubEventName(e)) + } + + dest.GitHub.Branches = orig.GetBranches(v1alpha1.GitHubWebHookTrigger) + dest.Image = (*WhenImage)(orig.Image) + dest.ObjectRef = (*WhenObjectRef)(orig.ObjectRef) + + return dest +} + +func getAlphaBuildSource(src BuildSpec) v1alpha1.Source { + source := v1alpha1.Source{} + var credentials corev1.LocalObjectReference + var revision *string + + switch src.Source.Type { + case OCIArtifactType: + if src.Source.OCIArtifact != nil && src.Source.OCIArtifact.PullSecret != nil { + credentials = corev1.LocalObjectReference{ + Name: *src.Source.OCIArtifact.PullSecret, + } + } + source.BundleContainer = &v1alpha1.BundleContainer{ + Image: src.Source.OCIArtifact.Image, + Prune: (*v1alpha1.PruneOption)(src.Source.OCIArtifact.Prune), + } + default: + if src.Source.GitSource != nil && src.Source.GitSource.CloneSecret != nil { + credentials = corev1.LocalObjectReference{ + Name: *src.Source.GitSource.CloneSecret, + } + } + if src.Source.GitSource != nil { + source.URL = src.Source.GitSource.URL + revision = src.Source.GitSource.Revision + } + + } + + if credentials.Name != "" { + source.Credentials = &credentials + } + + source.Revision = revision + source.ContextDir = src.Source.ContextDir + + return source +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_types.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_types.go new file mode 100644 index 00000000..738fa05e --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/build_types.go @@ -0,0 +1,276 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// BuildReason is a type used for populating the +// Build Status.Reason field +type BuildReason string + +const ( + // SucceedStatus indicates that all validations Succeeded + SucceedStatus BuildReason = "Succeeded" + // BuildStrategyNotFound indicates that a namespaced-scope strategy was not found in the namespace + BuildStrategyNotFound BuildReason = "BuildStrategyNotFound" + // ClusterBuildStrategyNotFound indicates that a cluster-scope strategy was not found + ClusterBuildStrategyNotFound BuildReason = "ClusterBuildStrategyNotFound" + // SetOwnerReferenceFailed indicates that setting ownerReferences between a Build and a BuildRun failed + SetOwnerReferenceFailed BuildReason = "SetOwnerReferenceFailed" + // SpecSourceSecretRefNotFound indicates the referenced secret in source is missing + SpecSourceSecretRefNotFound BuildReason = "SpecSourceSecretRefNotFound" + // SpecOutputSecretRefNotFound indicates the referenced secret in output is missing + SpecOutputSecretRefNotFound BuildReason = "SpecOutputSecretRefNotFound" + // SpecBuilderSecretRefNotFound indicates the referenced secret in builder is missing + SpecBuilderSecretRefNotFound BuildReason = "SpecBuilderSecretRefNotFound" + // MultipleSecretRefNotFound indicates that multiple secrets are missing + MultipleSecretRefNotFound BuildReason = "MultipleSecretRefNotFound" + // SpecEnvNameCanNotBeBlank indicates that the name for an environment variable is blank + SpecEnvNameCanNotBeBlank BuildReason = "SpecEnvNameCanNotBeBlank" + // SpecEnvOnlyOneOfValueOrValueFromMustBeSpecified indicates that both value and valueFrom were specified + SpecEnvOnlyOneOfValueOrValueFromMustBeSpecified BuildReason = "SpecEnvOnlyOneOfValueOrValueFromMustBeSpecified" + // RuntimePathsCanNotBeEmpty indicates that the spec.runtime feature is used but the paths were not specified + RuntimePathsCanNotBeEmpty BuildReason = "RuntimePathsCanNotBeEmpty" + // RestrictedParametersInUse indicates the definition of reserved shipwright parameters + RestrictedParametersInUse BuildReason = "RestrictedParametersInUse" + // WrongParameterValueType indicates that a single value was provided for an array parameter, or vice-versa + WrongParameterValueType BuildReason = "WrongParameterValueType" + // UndefinedParameter indicates the definition of param that was not defined in the strategy parameters + UndefinedParameter BuildReason = "UndefinedParameter" + // InconsistentParameterValues indicates that parameter values have more than one of configMapValue, secretValue, or value set + InconsistentParameterValues BuildReason = "InconsistentParameterValues" + // EmptyArrayItemParameterValues indicates that array parameters contain an item where none of configMapValue, secretValue, or value is set + EmptyArrayItemParameterValues BuildReason = "EmptyArrayItemParameterValues" + // IncompleteConfigMapValueParameterValues indicates that a configMapValue is specified where the name or the key is empty + IncompleteConfigMapValueParameterValues BuildReason = "IncompleteConfigMapValueParameterValues" + // IncompleteSecretValueParameterValues indicates that a secretValue is specified where the name or the key is empty + IncompleteSecretValueParameterValues BuildReason = "IncompleteSecretValueParameterValues" + // RemoteRepositoryUnreachable indicates the referenced repository is unreachable + RemoteRepositoryUnreachable BuildReason = "RemoteRepositoryUnreachable" + // BuildNameInvalid indicates the build name is invalid + BuildNameInvalid BuildReason = "BuildNameInvalid" + // VolumeDoesNotExist indicates that volume referenced by the Build does not exist, therefore Build cannot be run + VolumeDoesNotExist BuildReason = "VolumeDoesNotExist" + // VolumeNotOverridable indicates that volume defined by build is not set as overridable in the strategy + VolumeNotOverridable BuildReason = "VolumeNotOverridable" + // UndefinedVolume indicates that volume defined by build is not found in the strategy + UndefinedVolume BuildReason = "UndefinedVolume" + // TriggerNameCanNotBeBlank indicates the trigger condition does not have a name + TriggerNameCanNotBeBlank BuildReason = "TriggerNameCanNotBeBlank" + // TriggerInvalidType indicates the trigger type is invalid + TriggerInvalidType BuildReason = "TriggerInvalidType" + // TriggerInvalidGitHubWebHook indicates the trigger type GitHub is invalid + TriggerInvalidGitHubWebHook BuildReason = "TriggerInvalidGitHubWebHook" + // TriggerInvalidImage indicates the trigger type Image is invalid + TriggerInvalidImage BuildReason = "TriggerInvalidImage" + // TriggerInvalidPipeline indicates the trigger type Pipeline is invalid + TriggerInvalidPipeline BuildReason = "TriggerInvalidPipeline" + + // AllValidationsSucceeded indicates a Build was successfully validated + AllValidationsSucceeded = "all validations succeeded" +) + +// BuildReasonPtr returns a pointer to the passed BuildReason. +func BuildReasonPtr(s BuildReason) *BuildReason { + return &s +} + +// ConditionStatusPtr returns a pointer to the passed ConditionStatus. +func ConditionStatusPtr(s corev1.ConditionStatus) *corev1.ConditionStatus { + return &s +} + +const ( + // BuildDomain is the domain used for all labels and annotations for this resource + BuildDomain = "build.shipwright.io" + + // LabelBuild is a label key for defining the build name + LabelBuild = BuildDomain + "/name" + + // LabelBuildGeneration is a label key for defining the build generation + LabelBuildGeneration = BuildDomain + "/generation" + + // AnnotationBuildRefSecret is an annotation that tells the Build Controller to reconcile on + // events of the secret only if is referenced by a Build in the same namespace + AnnotationBuildRefSecret = BuildDomain + "/referenced.secret" + + // AnnotationBuildVerifyRepository tells the Build Controller to check a remote repository. If the annotation is not set + // or has a value of 'true', the controller triggers the validation. A value of 'false' means the controller + // will bypass checking the remote repository. + AnnotationBuildVerifyRepository = BuildDomain + "/verify.repository" +) + +// BuildSpec defines the desired state of Build +type BuildSpec struct { + // Source refers to the location where the source code is, + // this could be a git repository, a local source or an oci + // artifact + Source Source `json:"source"` + + // Trigger defines the scenarios where a new build should be triggered. + // + // +optional + Trigger *Trigger `json:"trigger,omitempty"` + + // Strategy references the BuildStrategy to use to build the container + // image. + Strategy Strategy `json:"strategy"` + + // Params is a list of key/value that could be used + // to set strategy parameters + // + // +optional + ParamValues []ParamValue `json:"paramValues,omitempty"` + + // Output refers to the location where the built image would be pushed. + Output Image `json:"output"` + + // Timeout defines the maximum amount of time the Build should take to execute. + // + // +optional + // +kubebuilder:validation:Format=duration + Timeout *metav1.Duration `json:"timeout,omitempty"` + + // Env contains additional environment variables that should be passed to the build container + // +optional + Env []corev1.EnvVar `json:"env,omitempty"` + + // Contains information about retention params + // + // +optional + Retention *BuildRetention `json:"retention,omitempty"` + + // Volumes contains volume Overrides of the BuildStrategy volumes in case those are allowed + // to be overridden. Must only contain volumes that exist in the corresponding BuildStrategy + // +optional + Volumes []BuildVolume `json:"volumes,omitempty"` +} + +// BuildVolume is a volume that will be mounted in build pod during build step +type BuildVolume struct { + // Name of the Build Volume + // +required + Name string `json:"name"` + + // Represents the source of a volume to mount + // +required + corev1.VolumeSource `json:",inline"` +} + +// StrategyName returns the name of the configured strategy, or 'undefined' in +// case the strategy is nil (not set) +func (buildSpec *BuildSpec) StrategyName() string { + if buildSpec == nil { + return "undefined (nil buildSpec)" + } + + return buildSpec.Strategy.Name +} + +// Image refers to an container image with credentials +type Image struct { + // Image is the reference of the image. + Image string `json:"image"` + + // Insecure defines whether the registry is not secure + // + // +optional + Insecure *bool `json:"insecure,omitempty"` + + // Describes the secret name for pushing a container image. + // + // +optional + PushSecret *string `json:"pushSecret,omitempty"` + + // Annotations references the additional annotations to be applied on the image + // + // +optional + Annotations map[string]string `json:"annotations,omitempty"` + + // Labels references the additional labels to be applied on the image + // + // +optional + Labels map[string]string `json:"labels,omitempty"` +} + +// BuildStatus defines the observed state of Build +// +// NOTICE: This is deprecated and will be removed in a future release. +type BuildStatus struct { + // The Register status of the Build + // +optional + Registered *corev1.ConditionStatus `json:"registered,omitempty"` + + // The reason of the registered Build, it's an one-word camelcase + // +optional + Reason *BuildReason `json:"reason,omitempty"` + + // The message of the registered Build, either an error or succeed message + // +optional + Message *string `json:"message,omitempty"` +} + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Build is the Schema representing a Build definition +// +kubebuilder:subresource:status +// +kubebuilder:resource:path=builds,scope=Namespaced +// +kubebuilder:printcolumn:name="Registered",type="string",JSONPath=".status.registered",description="The register status of the Build" +// +kubebuilder:printcolumn:name="Reason",type="string",JSONPath=".status.reason",description="The reason of the registered Build, either an error or succeed message" +// +kubebuilder:printcolumn:name="BuildStrategyKind",type="string",JSONPath=".spec.strategy.kind",description="The BuildStrategy type which is used for this Build" +// +kubebuilder:printcolumn:name="BuildStrategyName",type="string",JSONPath=".spec.strategy.name",description="The BuildStrategy name which is used for this Build" +// +kubebuilder:printcolumn:name="CreationTime",type="date",JSONPath=".metadata.creationTimestamp",description="The create time of this Build" +type Build struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec BuildSpec `json:"spec"` + Status BuildStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// BuildList contains a list of Build +type BuildList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Build `json:"items"` +} + +// BuildRetention struct for buildrun cleanup +type BuildRetention struct { + // FailedLimit defines the maximum number of failed buildruns that should exist. + // + // +optional + // +kubebuilder:validation:Minimum=1 + FailedLimit *uint `json:"failedLimit,omitempty"` + // SucceededLimit defines the maximum number of succeeded buildruns that should exist. + // + // +optional + // +kubebuilder:validation:Minimum=1 + SucceededLimit *uint `json:"succeededLimit,omitempty"` + // TTLAfterFailed defines the maximum duration of time the failed buildrun should exist. + // + // +optional + // +kubebuilder:validation:Format=duration + TTLAfterFailed *metav1.Duration `json:"ttlAfterFailed,omitempty"` + // TTLAfterSucceeded defines the maximum duration of time the succeeded buildrun should exist. + // + // +optional + // +kubebuilder:validation:Format=duration + TTLAfterSucceeded *metav1.Duration `json:"ttlAfterSucceeded,omitempty"` + // AtBuildDeletion defines if related BuildRuns should be deleted when deleting the Build. + // + // +optional + AtBuildDeletion *bool `json:"atBuildDeletion,omitempty"` +} + +func init() { + SchemeBuilder.Register(&Build{}, &BuildList{}) +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_conversion.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_conversion.go new file mode 100644 index 00000000..41180e9a --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_conversion.go @@ -0,0 +1,256 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + "context" + + "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + "github.com/shipwright-io/build/pkg/ctxlog" + "github.com/shipwright-io/build/pkg/webhook" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/pointer" +) + +// ensure v1beta1 implements the Conversion interface +var _ webhook.Conversion = (*BuildRun)(nil) + +// To Alpha +func (src *BuildRun) ConvertTo(ctx context.Context, obj *unstructured.Unstructured) error { + ctxlog.Debug(ctx, "Converting BuildRun from beta to alpha", "namespace", src.Namespace, "name", src.Name) + + var alphaBuildRun v1alpha1.BuildRun + + alphaBuildRun.TypeMeta = src.TypeMeta + alphaBuildRun.TypeMeta.APIVersion = alphaGroupVersion + alphaBuildRun.ObjectMeta = src.ObjectMeta + + // BuildRunSpec BuildSpec + if src.Spec.Build.Build != nil { + newBuildSpec := v1alpha1.BuildSpec{} + if err := src.Spec.Build.Build.ConvertTo(&newBuildSpec); err != nil { + return err + } + alphaBuildRun.Spec.BuildSpec = &newBuildSpec + } else if src.Spec.Build.Name != nil { + alphaBuildRun.Spec.BuildRef = &v1alpha1.BuildRef{ + Name: *src.Spec.Build.Name, + } + } + + // BuildRunSpec Sources + if src.Spec.Source != nil && src.Spec.Source.Type == LocalType && src.Spec.Source.LocalSource != nil { + alphaBuildRun.Spec.Sources = append(alphaBuildRun.Spec.Sources, v1alpha1.BuildSource{ + Name: src.Spec.Source.LocalSource.Name, + Type: v1alpha1.LocalCopy, + Timeout: src.Spec.Source.LocalSource.Timeout, + }) + } + + // BuildRunSpec ServiceAccount + // With the deprecation of serviceAccount.Generate, serviceAccount is set to ".generate" to have the SA created on fly. + if src.Spec.ServiceAccount != nil && *src.Spec.ServiceAccount == ".generate" { + alphaBuildRun.Spec.ServiceAccount = &v1alpha1.ServiceAccount{ + Name: &src.ObjectMeta.Name, + Generate: pointer.Bool(true), + } + } else { + alphaBuildRun.Spec.ServiceAccount = &v1alpha1.ServiceAccount{ + Name: src.Spec.ServiceAccount, + } + } + + // BuildRunSpec Timeout + alphaBuildRun.Spec.Timeout = src.Spec.Timeout + + // BuildRunSpec ParamValues + alphaBuildRun.Spec.ParamValues = nil + for _, p := range src.Spec.ParamValues { + param := v1alpha1.ParamValue{} + p.convertToAlpha(¶m) + alphaBuildRun.Spec.ParamValues = append(alphaBuildRun.Spec.ParamValues, param) + } + + // BuildRunSpec Image + + if src.Spec.Output != nil { + alphaBuildRun.Spec.Output = &v1alpha1.Image{ + Image: src.Spec.Output.Image, + Annotations: src.Spec.Output.Annotations, + Labels: src.Spec.Output.Labels, + } + if src.Spec.Output.PushSecret != nil { + alphaBuildRun.Spec.Output.Credentials = &corev1.LocalObjectReference{ + Name: *src.Spec.Output.PushSecret, + } + } + } + + // BuildRunSpec State + alphaBuildRun.Spec.State = (*v1alpha1.BuildRunRequestedState)(src.Spec.State) + + // BuildRunSpec Env + alphaBuildRun.Spec.Env = src.Spec.Env + + // BuildRunSpec Retention + alphaBuildRun.Spec.Retention = (*v1alpha1.BuildRunRetention)(src.Spec.Retention) + + // BuildRunSpec Volumes + alphaBuildRun.Spec.Volumes = []v1alpha1.BuildVolume{} + for _, vol := range src.Spec.Volumes { + alphaBuildRun.Spec.Volumes = append(alphaBuildRun.Spec.Volumes, v1alpha1.BuildVolume{ + Name: vol.Name, + VolumeSource: vol.VolumeSource, + }) + } + + mapito, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&alphaBuildRun) + if err != nil { + ctxlog.Error(ctx, err, "failed structuring the newObject") + } + obj.Object = mapito + + return nil + +} + +// From Alpha +func (src *BuildRun) ConvertFrom(ctx context.Context, obj *unstructured.Unstructured) error { + + var alphaBuildRun v1alpha1.BuildRun + + unstructured := obj.UnstructuredContent() + err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured, &alphaBuildRun) + if err != nil { + ctxlog.Error(ctx, err, "failed unstructuring the buildrun convertedObject") + } + + ctxlog.Debug(ctx, "Converting BuildRun from alpha to beta", "namespace", alphaBuildRun.Namespace, "name", alphaBuildRun.Name) + + src.ObjectMeta = alphaBuildRun.ObjectMeta + src.TypeMeta = alphaBuildRun.TypeMeta + src.TypeMeta.APIVersion = betaGroupVersion + + src.Spec.ConvertFrom(&alphaBuildRun.Spec) + + var sourceStatus *SourceResult + for _, s := range alphaBuildRun.Status.Sources { + sourceStatus = &SourceResult{ + Git: (*GitSourceResult)(s.Git), + OciArtifact: (*OciArtifactSourceResult)(s.Bundle), + } + } + + conditions := []Condition{} + + for _, c := range alphaBuildRun.Status.Conditions { + ct := Condition{ + Type: Type(c.Type), + Status: c.Status, + LastTransitionTime: c.LastTransitionTime, + Reason: c.Reason, + Message: c.Message, + } + conditions = append(conditions, ct) + } + + if alphaBuildRun.Status.FailureDetails != nil { + src.Status.FailureDetails = &FailureDetails{ + Reason: alphaBuildRun.Status.FailureDetails.Reason, + Message: alphaBuildRun.Status.FailureDetails.Message, + Location: (*Location)(alphaBuildRun.Status.FailureDetails.Location), + } + } + + src.Status = BuildRunStatus{ + Source: sourceStatus, + Output: (*Output)(alphaBuildRun.Status.Output), + Conditions: conditions, + TaskRunName: alphaBuildRun.Status.LatestTaskRunRef, + StartTime: alphaBuildRun.Status.StartTime, + CompletionTime: alphaBuildRun.Status.CompletionTime, + FailureDetails: src.Status.FailureDetails, + } + + buildBeta := Build{} + if alphaBuildRun.Status.BuildSpec != nil { + buildBeta.Spec.ConvertFrom(alphaBuildRun.Status.BuildSpec) + src.Status.BuildSpec = &buildBeta.Spec + } + + return nil +} + +func (dest *BuildRunSpec) ConvertFrom(orig *v1alpha1.BuildRunSpec) error { + + // BuildRunSpec BuildSpec + if orig.BuildSpec != nil { + dest.Build.Build = &BuildSpec{} + dest.Build.Build.ConvertFrom(orig.BuildSpec) + } + if orig.BuildRef != nil { + dest.Build.Name = &orig.BuildRef.Name + } + + // only interested on spec.sources as long as an item of the list + // is of the type LocalCopy. Otherwise, we move into bundle or git types. + index, isLocal := v1alpha1.IsLocalCopyType(orig.Sources) + if isLocal { + dest.Source = &BuildRunSource{ + Type: LocalType, + LocalSource: &Local{ + Name: orig.Sources[index].Name, + Timeout: orig.Sources[index].Timeout, + }, + } + } + + if orig.ServiceAccount != nil { + dest.ServiceAccount = orig.ServiceAccount.Name + } + + dest.Timeout = orig.Timeout + + // BuildRunSpec ParamValues + dest.ParamValues = []ParamValue{} + for _, p := range orig.ParamValues { + param := convertBetaParamValue(p) + dest.ParamValues = append(dest.ParamValues, param) + } + + // Handle BuildRunSpec Output + if orig.Output != nil { + dest.Output = &Image{ + Image: orig.Output.Image, + Annotations: orig.Output.Annotations, + Labels: orig.Output.Labels, + } + + if orig.Output.Credentials != nil { + dest.Output.PushSecret = &orig.Output.Credentials.Name + } + } + + // BuildRunSpec State + dest.State = (*BuildRunRequestedState)(orig.State) + + // BuildRunSpec Env + dest.Env = orig.Env + + // BuildRunSpec Retention + dest.Retention = (*BuildRunRetention)(orig.Retention) + + // BuildRunSpec Volumes + dest.Volumes = []BuildVolume{} + for _, vol := range orig.Volumes { + dest.Volumes = append(dest.Volumes, BuildVolume{ + Name: vol.Name, + VolumeSource: vol.VolumeSource, + }) + } + return nil +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_types.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_types.go new file mode 100644 index 00000000..7a40e822 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildrun_types.go @@ -0,0 +1,385 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + // BuildRunDomain is the domain used for all labels and annotations for this resource + BuildRunDomain = "buildrun.shipwright.io" + + // LabelBuildRun is a label key for BuildRuns to define the name of the BuildRun + LabelBuildRun = BuildRunDomain + "/name" + + // LabelBuildRunGeneration is a label key for BuildRuns to define the generation + LabelBuildRunGeneration = BuildRunDomain + "/generation" +) + +type ReferencedBuild struct { + // Build refers to an embedded build specification + // + // +optional + Build *BuildSpec `json:"spec,omitempty"` + + // Name of the referent; More info: http://kubernetes.io/docs/user-guide/identifiers#names + // + // +optional + Name *string `json:"name,omitempty"` +} + +// BuildRunSpec defines the desired state of BuildRun +type BuildRunSpec struct { + // Build refers to an embedded build specification + // This field is mandatory + // + Build ReferencedBuild `json:"build"` + + // Source refers to the location where the source code is, + // this could only be a local source + // + // +optional + Source *BuildRunSource `json:"source,omitempty"` + + // ServiceAccount refers to the kubernetes serviceaccount + // which is used for resource control. + // Default serviceaccount will be set if it is empty + // + // +optional + ServiceAccount *string `json:"serviceAccount,omitempty"` + + // Timeout defines the maximum run time of this BuildRun. + // + // +optional + // +kubebuilder:validation:Format=duration + Timeout *metav1.Duration `json:"timeout,omitempty"` + + // Params is a list of key/value that could be used + // to set strategy parameters + // + // +optional + ParamValues []ParamValue `json:"paramValues,omitempty"` + + // Output refers to the location where the generated + // image would be pushed to. It will overwrite the output image in build spec + // + // +optional + Output *Image `json:"output,omitempty"` + + // State is used for canceling a buildrun (and maybe more later on). + // + // +optional + State *BuildRunRequestedState `json:"state,omitempty"` + + // Env contains additional environment variables that should be passed to the build container + // + // +optional + Env []corev1.EnvVar `json:"env,omitempty"` + + // Contains information about retention params + // +optional + Retention *BuildRunRetention `json:"retention,omitempty"` + + // Volumes contains volume Overrides of the BuildStrategy volumes in case those are allowed + // to be overridden. Must only contain volumes that exist in the corresponding BuildStrategy + // +optional + Volumes []BuildVolume `json:"volumes,omitempty"` +} + +// BuildRunRequestedState defines the buildrun state the user can provide to override whatever is the current state. +type BuildRunRequestedState string + +// BuildRunRequestedStatePtr returns a pointer to the passed BuildRunRequestedState. +func BuildRunRequestedStatePtr(s BuildRunRequestedState) *BuildRunRequestedState { + return &s +} + +const ( + // BuildRunStateCancel indicates that the user wants to cancel the BuildRun, + // if not already canceled or terminated + BuildRunStateCancel = "BuildRunCanceled" + + // BuildRunStatePodEvicted indicates that if the pods got evicted + // due to some reason. (Probably ran out of ephemeral storage) + BuildRunStatePodEvicted = "PodEvicted" +) + +// SourceResult holds the results emitted from the different sources +type SourceResult struct { + + // Git holds the results emitted from the + // source step of type git + // + // +optional + Git *GitSourceResult `json:"git,omitempty"` + + // OciArtifact holds the results emitted from + // the source step of type ociArtifact + // + // +optional + OciArtifact *OciArtifactSourceResult `json:"ociArtifact,omitempty"` +} + +// OciArtifactSourceResult holds the results emitted from the bundle source +type OciArtifactSourceResult struct { + // Digest hold the image digest result + Digest string `json:"digest,omitempty"` +} + +// GitSourceResult holds the results emitted from the git source +type GitSourceResult struct { + // CommitSha holds the commit sha of git source + CommitSha string `json:"commitSha,omitempty"` + + // CommitAuthor holds the commit author of a git source + CommitAuthor string `json:"commitAuthor,omitempty"` + + // BranchName holds the default branch name of the git source + // this will be set only when revision is not specified in Build object + // + // +optional + BranchName string `json:"branchName,omitempty"` +} + +// Output holds the information about the container image that the BuildRun built +type Output struct { + // Digest holds the digest of output image + // + // +optional + Digest string `json:"digest,omitempty"` + + // Size holds the compressed size of output image + // + // +optional + Size int64 `json:"size,omitempty"` +} + +// BuildRunStatus defines the observed state of BuildRun +type BuildRunStatus struct { + // Source holds the results emitted from the source step + // + // +optional + Source *SourceResult `json:"source,omitempty"` + + // Output holds the results emitted from step definition of an output + // + // +optional + Output *Output `json:"output,omitempty"` + + // Conditions holds the latest available observations of a resource's current state. + Conditions Conditions `json:"conditions,omitempty"` + + // TaskRunName is the name of the TaskRun responsible for executing this BuildRun. + // + // +optional + TaskRunName *string `json:"taskRunName,omitempty"` + + // StartTime is the time the build is actually started. + // +optional + StartTime *metav1.Time `json:"startTime,omitempty"` + + // CompletionTime is the time the build completed. + // +optional + CompletionTime *metav1.Time `json:"completionTime,omitempty"` + + // BuildSpec is the Build Spec of this BuildRun. + // +optional + BuildSpec *BuildSpec `json:"buildSpec,omitempty"` + + // FailureDetails contains error details that are collected and surfaced from TaskRun + // +optional + FailureDetails *FailureDetails `json:"failureDetails,omitempty"` +} + +// Location describes the location where the failure happened +type Location struct { + Pod string `json:"pod,omitempty"` + Container string `json:"container,omitempty"` +} + +// FailureDetails describes an error while building images +type FailureDetails struct { + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + Location *Location `json:"location,omitempty"` +} + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// BuildRun is the Schema representing an instance of build execution +// +kubebuilder:subresource:status +// +kubebuilder:resource:path=buildruns,scope=Namespaced,shortName=br;brs +// +kubebuilder:printcolumn:name="Succeeded",type="string",JSONPath=".status.conditions[?(@.type==\"Succeeded\")].status",description="The Succeeded status of the BuildRun" +// +kubebuilder:printcolumn:name="Reason",type="string",JSONPath=".status.conditions[?(@.type==\"Succeeded\")].reason",description="The Succeeded reason of the BuildRun" +// +kubebuilder:printcolumn:name="StartTime",type="date",JSONPath=".status.startTime",description="The start time of this BuildRun" +// +kubebuilder:printcolumn:name="CompletionTime",type="date",JSONPath=".status.completionTime",description="The completion time of this BuildRun" +type BuildRun struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec BuildRunSpec `json:"spec"` + Status BuildRunStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// BuildRunList contains a list of BuildRun +type BuildRunList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []BuildRun `json:"items"` +} + +// IsDone returns true if the BuildRun's status indicates that it is done. +func (br *BuildRun) IsDone() bool { + c := br.Status.GetCondition(Succeeded) + return c != nil && c.GetStatus() != corev1.ConditionUnknown +} + +// HasStarted returns true if the BuildRun has a valid start time set in its status. +func (br *BuildRun) HasStarted() bool { + return br.Status.StartTime != nil && !br.Status.StartTime.IsZero() +} + +// IsSuccessful returns true if the BuildRun's status indicates that it is done. +func (br *BuildRun) IsSuccessful() bool { + c := br.Status.GetCondition(Succeeded) + return c != nil && c.GetStatus() == corev1.ConditionTrue +} + +// IsCanceled returns true if the BuildRun's spec status is set to BuildRunCanceled state. +func (br *BuildRun) IsCanceled() bool { + return br.Spec.State != nil && *br.Spec.State == BuildRunStateCancel +} + +// Conditions defines a list of Condition +type Conditions []Condition + +// Type used for defining the conditiont Type field flavour +type Type string + +const ( + // Succeeded specifies that the resource has finished. + // For resources that run to completion. + Succeeded Type = "Succeeded" +) + +// Condition defines the required fields for populating +// Build controllers Conditions +type Condition struct { + // Type of condition + // +required + Type Type `json:"type" description:"type of status condition"` + + // Status of the condition, one of True, False, Unknown. + // +required + Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` + + // LastTransitionTime last time the condition transit from one status to another. + LastTransitionTime metav1.Time `json:"lastTransitionTime" description:"last time the condition transit from one status to another"` + + // The reason for the condition last transition. + Reason string `json:"reason" description:"one-word CamelCase reason for the condition's last transition"` + + // A human readable message indicating details about the transition. + Message string `json:"message" description:"human-readable message indicating details about last transition"` +} + +// BuildRunRetention struct for buildrun cleanup +type BuildRunRetention struct { + // TTLAfterFailed defines the maximum duration of time the failed buildrun should exist. + // + // +optional + // +kubebuilder:validation:Format=duration + TTLAfterFailed *metav1.Duration `json:"ttlAfterFailed,omitempty"` + // TTLAfterSucceeded defines the maximum duration of time the succeeded buildrun should exist. + // + // +optional + // +kubebuilder:validation:Format=duration + TTLAfterSucceeded *metav1.Duration `json:"ttlAfterSucceeded,omitempty"` +} + +func init() { + SchemeBuilder.Register(&BuildRun{}, &BuildRunList{}) +} + +// GetReason returns the condition Reason, it ensures that by getting the Reason +// the call will not panic if the Condition is not present +func (c *Condition) GetReason() string { + if c == nil { + return "" + } + return c.Reason +} + +// GetMessage returns the condition Message, it ensures that by getting the Message +// the call will not panic if the Condition is not present +func (c *Condition) GetMessage() string { + if c == nil { + return "" + } + return c.Message +} + +// GetStatus returns the condition Status, it ensures that by getting the Status +// the call will not panic if the Condition is not present +func (c *Condition) GetStatus() corev1.ConditionStatus { + if c == nil { + return "" + } + return c.Status +} + +// GetCondition returns a condition based on a type from a list of Conditions +func (brs *BuildRunStatus) GetCondition(t Type) *Condition { + for _, c := range brs.Conditions { + if c.Type == t { + return &c + } + } + return nil +} + +// IsFailed returns a condition with a False Status +// based on a type from a list of Conditions. +func (brs *BuildRunStatus) IsFailed(t Type) bool { + for _, c := range brs.Conditions { + if c.Type == t { + return c.Status == corev1.ConditionFalse + } + } + return false +} + +// SetCondition updates a list of conditions with the provided condition +func (brs *BuildRunStatus) SetCondition(condition *Condition) { + var idx = -1 + for i, c := range brs.Conditions { + if c.Type == condition.Type { + idx = i + break + } + } + + if idx != -1 { + brs.Conditions[idx] = *condition + } else { + brs.Conditions = append(brs.Conditions, *condition) + } +} + +// BuildName returns the name of the associated build, which can be a referenced +// build resource or an embedded build specification +func (buildrunSpec *BuildRunSpec) BuildName() string { + if buildrunSpec.Build.Name != nil { + return *buildrunSpec.Build.Name + } + + // Only BuildRuns with a ReferencedBuild can actually return a proper Build name + return "" +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy.go new file mode 100644 index 00000000..1997a63f --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy.go @@ -0,0 +1,202 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +const ( + // NamespacedBuildStrategyKind indicates that the buildstrategy type has a namespaced scope. + NamespacedBuildStrategyKind BuildStrategyKind = "BuildStrategy" + + // ClusterBuildStrategyKind indicates that buildstrategy type has a cluster scope. + ClusterBuildStrategyKind BuildStrategyKind = "ClusterBuildStrategy" +) + +// BuildStrategySpec defines the desired state of BuildStrategy +type BuildStrategySpec struct { + Steps []Step `json:"steps,omitempty"` + Parameters []Parameter `json:"parameters,omitempty"` + SecurityContext *BuildStrategySecurityContext `json:"securityContext,omitempty"` + Volumes []BuildStrategyVolume `json:"volumes,omitempty"` +} + +// ParameterType indicates the type of a parameter +type ParameterType string + +// Valid ParamTypes: +const ( + ParameterTypeString ParameterType = "string" + ParameterTypeArray ParameterType = "array" +) + +// Parameter holds a name-description with a default value +// that allows strategy steps to be parameterize. +// Build users can set a value for parameter via the Build +// or BuildRun spec.paramValues object. +// +optional +type Parameter struct { + // Name of the parameter + // +required + Name string `json:"name"` + + // Description on the parameter purpose + // +required + Description string `json:"description"` + + // Type of the parameter. The possible types are "string" and "array", + // and "string" is the default. + // +optional + Type ParameterType `json:"type,omitempty"` + + // Default value for a string parameter + // +optional + Default *string `json:"default,omitempty"` + + // Default values for an array parameter + // +optional + Defaults *[]string `json:"defaults"` +} + +// BuildStrategySecurityContext defines a UID and GID for the build that is to be used for the build strategy steps as +// well as for shipwright-managed steps such as the source retrieval, or the image processing. +// The value can be overwritten on the steps for the strategy steps. +// If omitted, then UID and GID from the Shipwright configuration will be used for the shipwright-managed steps. +type BuildStrategySecurityContext struct { + + // The UID to run the entrypoint of the container process. + // Defaults to user specified in image metadata if unspecified. + // Can be overwritten by the security context on the step level. + RunAsUser int64 `json:"runAsUser"` + + // The GID to run the entrypoint of the container process. + // Defaults to group specified in image metadata if unspecified. + // Can be overwritten by the security context on the step level. + RunAsGroup int64 `json:"runAsGroup"` +} + +// BuildStrategyVolume is a volume that will be mounted in build pod during build step +// of the Build Strategy +type BuildStrategyVolume struct { + // Indicates that this Volume can be overridden in a Build or BuildRun. + // Defaults to false + // +optional + Overridable *bool `json:"overridable,omitempty"` + + // Name of the Build Volume + // +required + Name string `json:"name"` + + // Description of the Build Volume + // +optional + Description *string `json:"description,omitempty"` + + // Represents the source of a volume to mount + // +required + corev1.VolumeSource `json:",inline"` +} + +// BuildStep defines a partial step that needs to run in container for building the image. +// If the build step declares a volumeMount, Shipwright will create an emptyDir volume mount for the named volume. +// Build steps which share the same named volume in the volumeMount will share the same underlying emptyDir volume. +// This behavior is deprecated, and will be removed when full volume support is added to build strategies as specified +// in SHIP-0022. +type Step struct { + // Name of the container specified as a DNS_LABEL. + // Each container in a pod must have a unique name (DNS_LABEL). + // Cannot be updated. + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + // Container image name. + // More info: https://kubernetes.io/docs/concepts/containers/images + // This field is optional to allow higher level config management to default or override + // container images in workload controllers like Deployments and StatefulSets. + // +optional + Image string `json:"image,omitempty" protobuf:"bytes,2,opt,name=image"` + // Entrypoint array. Not executed within a shell. + // The container image's ENTRYPOINT is used if this is not provided. + // Variable references $(VAR_NAME) are expanded using the container's environment. If a variable + // cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced + // to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. "$$(VAR_NAME)" will + // produce the string literal "$(VAR_NAME)". Escaped references will never be expanded, regardless + // of whether the variable exists or not. Cannot be updated. + // More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell + // +optional + Command []string `json:"command,omitempty" protobuf:"bytes,3,rep,name=command"` + // Arguments to the entrypoint. + // The container image's CMD is used if this is not provided. + // Variable references $(VAR_NAME) are expanded using the container's environment. If a variable + // cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced + // to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. "$$(VAR_NAME)" will + // produce the string literal "$(VAR_NAME)". Escaped references will never be expanded, regardless + // of whether the variable exists or not. Cannot be updated. + // More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell + // +optional + Args []string `json:"args,omitempty" protobuf:"bytes,4,rep,name=args"` + // Container's working directory. + // If not specified, the container runtime's default will be used, which + // might be configured in the container image. + // Cannot be updated. + // +optional + WorkingDir string `json:"workingDir,omitempty" protobuf:"bytes,5,opt,name=workingDir"` + // List of environment variables to set in the container. + // Cannot be updated. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + Env []corev1.EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,7,rep,name=env"` + // Compute Resources required by this container. + // Cannot be updated. + // More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ + // +optional + Resources corev1.ResourceRequirements `json:"resources,omitempty" protobuf:"bytes,8,opt,name=resources"` + // Pod volumes to mount into the container's filesystem. + // Cannot be updated. + // +optional + // +patchMergeKey=mountPath + // +patchStrategy=merge + VolumeMounts []corev1.VolumeMount `json:"volumeMounts,omitempty" patchStrategy:"merge" patchMergeKey:"mountPath" protobuf:"bytes,9,rep,name=volumeMounts"` + // Image pull policy. + // One of Always, Never, IfNotPresent. + // Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. + // Cannot be updated. + // More info: https://kubernetes.io/docs/concepts/containers/images#updating-images + // +optional + ImagePullPolicy corev1.PullPolicy `json:"imagePullPolicy,omitempty" protobuf:"bytes,14,opt,name=imagePullPolicy,casttype=PullPolicy"` + // SecurityContext defines the security options the container should be run with. + // If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext. + // More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/ + // +optional + SecurityContext *corev1.SecurityContext `json:"securityContext,omitempty" protobuf:"bytes,15,opt,name=securityContext"` +} + +// BuildStrategyStatus defines the observed state of BuildStrategy +type BuildStrategyStatus struct { +} + +// BuildStrategyKind defines the type of BuildStrategy used by the build. +type BuildStrategyKind string + +// Strategy can be used to refer to a specific instance of a buildstrategy. +// Copied from CrossVersionObjectReference: https://github.com/kubernetes/kubernetes/blob/169df7434155cbbc22f1532cba8e0a9588e29ad8/pkg/apis/autoscaling/types.go#L64 +type Strategy struct { + // Name of the referent; More info: http://kubernetes.io/docs/user-guide/identifiers#names + Name string `json:"name"` + + // BuildStrategyKind indicates the kind of the buildstrategy, namespaced or cluster scoped. + Kind *BuildStrategyKind `json:"kind,omitempty"` +} + +// BuilderStrategy defines the common elements of build strategies +type BuilderStrategy interface { + GetAnnotations() map[string]string + GetName() string + GetGeneration() int64 + GetResourceLabels() map[string]string + GetBuildSteps() []Step + GetParameters() []Parameter + GetSecurityContext() *BuildStrategySecurityContext + GetVolumes() []BuildStrategyVolume +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_conversion.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_conversion.go new file mode 100644 index 00000000..1b0715fa --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_conversion.go @@ -0,0 +1,278 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + "context" + "strings" + + "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + "github.com/shipwright-io/build/pkg/ctxlog" + "github.com/shipwright-io/build/pkg/webhook" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/pointer" +) + +// ensure v1beta1 implements the Conversion interface +var _ webhook.Conversion = (*BuildStrategy)(nil) + +// ConvertTo converts this object to its v1alpha1 equivalent +func (src *BuildStrategy) ConvertTo(ctx context.Context, obj *unstructured.Unstructured) error { + ctxlog.Debug(ctx, "Converting BuildStrategy from beta to alpha", "namespace", src.Namespace, "name", src.Name) + + var bs v1alpha1.BuildStrategy + bs.TypeMeta = src.TypeMeta + bs.TypeMeta.APIVersion = alphaGroupVersion + bs.ObjectMeta = src.ObjectMeta + + src.Spec.ConvertTo(&bs.Spec) + + mapito, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&bs) + if err != nil { + ctxlog.Error(ctx, err, "failed structuring the newObject") + } + obj.Object = mapito + + return nil +} + +func (src *BuildStrategySpec) ConvertTo(bs *v1alpha1.BuildStrategySpec) { + usesMigratedDockerfileArg, usesMigratedBuilderArg := false, false + + bs.Parameters = []v1alpha1.Parameter{} + for _, param := range src.Parameters { + if param.Name == "dockerfile" && param.Type == ParameterTypeString && param.Default != nil && *param.Default == "Dockerfile" { + usesMigratedDockerfileArg = true + continue + } + + if param.Name == "builder-image" && param.Type == ParameterTypeString && param.Default == nil { + usesMigratedBuilderArg = true + continue + } + + bs.Parameters = append(bs.Parameters, v1alpha1.Parameter{ + Name: param.Name, + Description: param.Description, + Type: v1alpha1.ParameterType(param.Type), + Default: param.Default, + Defaults: param.Defaults, + }) + } + + bs.BuildSteps = []v1alpha1.BuildStep{} + for _, step := range src.Steps { + + buildStep := v1alpha1.BuildStep{ + Container: corev1.Container{ + Name: step.Name, + Image: step.Image, + Command: step.Command, + Args: step.Args, + WorkingDir: step.WorkingDir, + Env: step.Env, + Resources: step.Resources, + VolumeMounts: step.VolumeMounts, + ImagePullPolicy: step.ImagePullPolicy, + SecurityContext: step.SecurityContext, + }, + } + + if usesMigratedDockerfileArg { + // Migrate to legacy argument + + for commandIndex, command := range buildStep.Command { + if strings.Contains(command, "$(params.dockerfile)") { + buildStep.Command[commandIndex] = strings.ReplaceAll(command, "$(params.dockerfile)", "$(params.DOCKERFILE)") + } + } + + for argIndex, arg := range buildStep.Args { + if strings.Contains(arg, "$(params.dockerfile)") { + buildStep.Args[argIndex] = strings.ReplaceAll(arg, "$(params.dockerfile)", "$(params.DOCKERFILE)") + } + } + + for envIndex, env := range buildStep.Env { + if strings.Contains(env.Value, "$(params.dockerfile)") { + buildStep.Env[envIndex].Value = strings.ReplaceAll(env.Value, "$(params.dockerfile)", "$(params.DOCKERFILE)") + } + } + } + + if usesMigratedBuilderArg { + // Migrate to legacy argument + + for commandIndex, command := range buildStep.Command { + if strings.Contains(command, "$(params.builder-image)") { + buildStep.Command[commandIndex] = strings.ReplaceAll(command, "$(params.builder-image)", "$(build.builder.image)") + } + } + + for argIndex, arg := range buildStep.Args { + if strings.Contains(arg, "$(params.builder-image)") { + buildStep.Args[argIndex] = strings.ReplaceAll(arg, "$(params.builder-image)", "$(build.builder.image)") + } + } + + for envIndex, env := range buildStep.Env { + if strings.Contains(env.Value, "$(params.builder-image)") { + buildStep.Env[envIndex].Value = strings.ReplaceAll(env.Value, "$(params.builder-image)", "$(build.builder.image)") + } + } + } + + bs.BuildSteps = append(bs.BuildSteps, buildStep) + } + + if src.SecurityContext != nil { + bs.SecurityContext = (*v1alpha1.BuildStrategySecurityContext)(src.SecurityContext) + } + + bs.Volumes = []v1alpha1.BuildStrategyVolume{} + for _, vol := range src.Volumes { + bs.Volumes = append(bs.Volumes, v1alpha1.BuildStrategyVolume{ + Overridable: vol.Overridable, + Name: vol.Name, + Description: vol.Description, + VolumeSource: vol.VolumeSource, + }) + } +} + +// ConvertFrom converts from v1alpha1.BuildStrategy into this object. +func (src *BuildStrategy) ConvertFrom(ctx context.Context, obj *unstructured.Unstructured) error { + var bs v1alpha1.BuildStrategy + + unstructured := obj.UnstructuredContent() + err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured, &bs) + if err != nil { + ctxlog.Error(ctx, err, "failed unstructuring the buildrun convertedObject") + } + + ctxlog.Debug(ctx, "Converting BuildStrategy from alpha to beta", "namespace", bs.Namespace, "name", bs.Name) + + src.ObjectMeta = bs.ObjectMeta + src.TypeMeta = bs.TypeMeta + src.TypeMeta.APIVersion = betaGroupVersion + + src.Spec.ConvertFrom(bs.Spec) + + return nil +} + +func (src *BuildStrategySpec) ConvertFrom(bs v1alpha1.BuildStrategySpec) { + src.Steps = []Step{} + + usesDockerfile, usesBuilderImage := false, false + + for _, brStep := range bs.BuildSteps { + step := Step{ + Name: brStep.Name, + Image: brStep.Image, + Command: brStep.Command, + Args: brStep.Args, + WorkingDir: brStep.WorkingDir, + Env: brStep.Env, + Resources: brStep.Resources, + VolumeMounts: brStep.VolumeMounts, + ImagePullPolicy: brStep.ImagePullPolicy, + SecurityContext: brStep.SecurityContext, + } + + // Migrate legacy argument usage + + for commandIndex, command := range step.Command { + if strings.Contains(command, "$(params.DOCKERFILE)") { + usesDockerfile = true + step.Command[commandIndex] = strings.ReplaceAll(command, "$(params.DOCKERFILE)", "$(params.dockerfile)") + } + if strings.Contains(command, "$(build.dockerfile)") { + usesDockerfile = true + step.Command[commandIndex] = strings.ReplaceAll(command, "$(build.dockerfile)", "$(params.dockerfile)") + } + if strings.Contains(command, "$(build.builder.image)") { + usesBuilderImage = true + step.Command[commandIndex] = strings.ReplaceAll(command, "$(build.builder.image)", "$(params.builder-image)") + } + } + + for argIndex, arg := range step.Args { + if strings.Contains(arg, "$(params.DOCKERFILE)") { + usesDockerfile = true + step.Args[argIndex] = strings.ReplaceAll(arg, "$(params.DOCKERFILE)", "$(params.dockerfile)") + } + if strings.Contains(arg, "$(build.dockerfile)") { + usesDockerfile = true + step.Args[argIndex] = strings.ReplaceAll(arg, "$(build.dockerfile)", "$(params.dockerfile)") + } + if strings.Contains(arg, "$(build.builder.image)") { + usesBuilderImage = true + step.Args[argIndex] = strings.ReplaceAll(arg, "$(build.builder.image)", "$(params.builder-image)") + } + } + + for envIndex, env := range step.Env { + if strings.Contains(env.Value, "$(params.DOCKERFILE)") { + usesDockerfile = true + step.Env[envIndex].Value = strings.ReplaceAll(env.Value, "$(params.DOCKERFILE)", "$(params.dockerfile)") + } + if strings.Contains(env.Value, "$(build.dockerfile)") { + usesDockerfile = true + step.Env[envIndex].Value = strings.ReplaceAll(env.Value, "$(build.dockerfile)", "$(params.dockerfile)") + } + if strings.Contains(env.Value, "$(build.builder.image)") { + usesBuilderImage = true + step.Env[envIndex].Value = strings.ReplaceAll(env.Value, "$(build.builder.image)", "$(params.builder-image)") + } + } + + src.Steps = append(src.Steps, step) + } + + src.Parameters = []Parameter{} + for _, param := range bs.Parameters { + src.Parameters = append(src.Parameters, Parameter{ + Name: param.Name, + Description: param.Description, + Type: ParameterType(param.Type), + Default: param.Default, + Defaults: param.Defaults, + }) + } + + // Add replacement for legacy arguments + + if usesDockerfile { + src.Parameters = append(src.Parameters, Parameter{ + Name: "dockerfile", + Description: "The Dockerfile to be built.", + Type: ParameterTypeString, + Default: pointer.String("Dockerfile"), + }) + } + + if usesBuilderImage { + src.Parameters = append(src.Parameters, Parameter{ + Name: "builder-image", + Description: "The builder image.", + Type: ParameterTypeString, + }) + } + + src.SecurityContext = (*BuildStrategySecurityContext)(bs.SecurityContext) + + src.Volumes = []BuildStrategyVolume{} + for _, vol := range bs.Volumes { + src.Volumes = append(src.Volumes, BuildStrategyVolume{ + Overridable: vol.Overridable, + Name: vol.Name, + Description: vol.Description, + VolumeSource: vol.VolumeSource, + }) + } +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_types.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_types.go new file mode 100644 index 00000000..2d1ece05 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/buildstrategy_types.go @@ -0,0 +1,94 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + "strconv" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + // BuildStrategyDomain is the domain used for all labels and annotations for this resource + BuildStrategyDomain = "buildstrategy.shipwright.io" + + // LabelBuildStrategyName is a label key for defining the build strategy name + LabelBuildStrategyName = BuildStrategyDomain + "/name" + + // LabelBuildStrategyGeneration is a label key for defining the build strategy generation + LabelBuildStrategyGeneration = BuildStrategyDomain + "/generation" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// BuildStrategy is the Schema representing a strategy in the namespace scope to build images from source code. +// +kubebuilder:subresource:status +// +kubebuilder:resource:path=buildstrategies,scope=Namespaced,shortName=bs;bss +type BuildStrategy struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec BuildStrategySpec `json:"spec,omitempty"` + Status BuildStrategyStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// BuildStrategyList contains a list of BuildStrategy +type BuildStrategyList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []BuildStrategy `json:"items"` +} + +// GetAnnotations returns the annotations of the build strategy +func (s BuildStrategy) GetAnnotations() map[string]string { + return s.Annotations +} + +// GetName returns the name of the build strategy +func (s BuildStrategy) GetName() string { + return s.Name +} + +// GetGeneration returns the current generation sequence number of the build +// strategy resource +func (s BuildStrategy) GetGeneration() int64 { + return s.Generation +} + +// GetResourceLabels returns labels that define the build strategy name and +// generation to be used in labels map of a resource +func (s BuildStrategy) GetResourceLabels() map[string]string { + return map[string]string{ + LabelBuildStrategyName: s.Name, + LabelBuildStrategyGeneration: strconv.FormatInt(s.Generation, 10), + } +} + +// GetBuildSteps returns the spec build steps of the build strategy +func (s BuildStrategy) GetBuildSteps() []Step { + return s.Spec.Steps +} + +// GetParameters returns the parameters defined by the build strategy +func (s BuildStrategy) GetParameters() []Parameter { + return s.Spec.Parameters +} + +// GetSecurityContext returns the security context defined by the build strategy +func (s BuildStrategy) GetSecurityContext() *BuildStrategySecurityContext { + return s.Spec.SecurityContext +} + +// GetVolumes returns the volumes defined by the build strategy +func (s BuildStrategy) GetVolumes() []BuildStrategyVolume { + return s.Spec.Volumes +} + +func init() { + SchemeBuilder.Register(&BuildStrategy{}, &BuildStrategyList{}) +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_conversion.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_conversion.go new file mode 100644 index 00000000..6a15007f --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_conversion.go @@ -0,0 +1,59 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + "context" + + "github.com/shipwright-io/build/pkg/apis/build/v1alpha1" + "github.com/shipwright-io/build/pkg/ctxlog" + "github.com/shipwright-io/build/pkg/webhook" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// ensure v1beta1 implements the Conversion interface +var _ webhook.Conversion = (*ClusterBuildStrategy)(nil) + +// ConvertTo converts this object to its v1alpha1 equivalent +func (src *ClusterBuildStrategy) ConvertTo(ctx context.Context, obj *unstructured.Unstructured) error { + ctxlog.Debug(ctx, "Converting ClusterBuildStrategy from beta to alpha", "namespace", src.Namespace, "name", src.Name) + + var bs v1alpha1.ClusterBuildStrategy + bs.TypeMeta = src.TypeMeta + bs.TypeMeta.APIVersion = alphaGroupVersion + bs.ObjectMeta = src.ObjectMeta + + src.Spec.ConvertTo(&bs.Spec) + + mapito, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&bs) + if err != nil { + ctxlog.Error(ctx, err, "failed structuring the newObject") + } + obj.Object = mapito + + return nil +} + +// ConvertFrom converts v1alpha1.ClusterBuildStrategy into this object +func (src *ClusterBuildStrategy) ConvertFrom(ctx context.Context, obj *unstructured.Unstructured) error { + var cbs v1alpha1.ClusterBuildStrategy + + unstructured := obj.UnstructuredContent() + err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured, &cbs) + if err != nil { + ctxlog.Error(ctx, err, "failed unstructuring the buildrun convertedObject") + } + + ctxlog.Debug(ctx, "Converting ClusterBuildStrategy from alpha to beta", "namespace", cbs.Namespace, "name", cbs.Name) + + src.ObjectMeta = cbs.ObjectMeta + src.TypeMeta = cbs.TypeMeta + src.TypeMeta.APIVersion = betaGroupVersion + + src.Spec.ConvertFrom(cbs.Spec) + + return nil +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_types.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_types.go new file mode 100644 index 00000000..42df5846 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/clusterbuildstrategy_types.go @@ -0,0 +1,95 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import ( + "strconv" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + // ClusterBuildStrategyDomain is the domain used for all labels and annotations for this resource + ClusterBuildStrategyDomain = "clusterbuildstrategy.shipwright.io" + + // LabelClusterBuildStrategyName is a label key for defining the cluster build strategy name + LabelClusterBuildStrategyName = ClusterBuildStrategyDomain + "/name" + + // LabelClusterBuildStrategyGeneration is a label key for defining the cluster build strategy generation + LabelClusterBuildStrategyGeneration = ClusterBuildStrategyDomain + "/generation" +) + +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterBuildStrategy is the Schema representing a strategy in the cluster scope to build images from source code. +// +kubebuilder:subresource:status +// +kubebuilder:resource:path=clusterbuildstrategies,scope=Cluster,shortName=cbs;cbss +type ClusterBuildStrategy struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec BuildStrategySpec `json:"spec,omitempty"` + Status BuildStrategyStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterBuildStrategyList contains a list of ClusterBuildStrategy +type ClusterBuildStrategyList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ClusterBuildStrategy `json:"items"` +} + +// GetAnnotations returns the annotations of the build strategy +func (s ClusterBuildStrategy) GetAnnotations() map[string]string { + return s.Annotations +} + +// GetName returns the name of the build strategy +func (s ClusterBuildStrategy) GetName() string { + return s.Name +} + +// GetGeneration returns the current generation sequence number of the build +// strategy resource +func (s ClusterBuildStrategy) GetGeneration() int64 { + return s.Generation +} + +// GetResourceLabels returns labels that define the build strategy name and +// generation to be used in labels map of a resource +func (s ClusterBuildStrategy) GetResourceLabels() map[string]string { + return map[string]string{ + LabelClusterBuildStrategyName: s.Name, + LabelClusterBuildStrategyGeneration: strconv.FormatInt(s.Generation, 10), + } +} + +// GetBuildSteps returns the spec build steps of the build strategy +func (s ClusterBuildStrategy) GetBuildSteps() []Step { + return s.Spec.Steps +} + +// GetParameters returns the parameters defined by the build strategy +func (s ClusterBuildStrategy) GetParameters() []Parameter { + return s.Spec.Parameters +} + +// GetSecurityContext returns the security context defined by the build strategy +func (s ClusterBuildStrategy) GetSecurityContext() *BuildStrategySecurityContext { + return s.Spec.SecurityContext +} + +// GetVolumes returns the volumes defined by the build strategy +func (s ClusterBuildStrategy) GetVolumes() []BuildStrategyVolume { + return s.Spec.Volumes +} + +func init() { + SchemeBuilder.Register(&ClusterBuildStrategy{}, &ClusterBuildStrategyList{}) +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/doc.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/doc.go new file mode 100644 index 00000000..5f2e0735 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/doc.go @@ -0,0 +1,8 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +// Package v1beta1 contains API Schema definitions for the build v1beta1 API group +// +k8s:deepcopy-gen=package,register +// +groupName=shipwright.io +package v1beta1 diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/parameter.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/parameter.go new file mode 100644 index 00000000..283e67d1 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/parameter.go @@ -0,0 +1,54 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +type ObjectKeyRef struct { + + // Name of the object + // +required + Name string `json:"name"` + + // Key inside the object + // +required + Key string `json:"key"` + + // An optional format to add pre- or suffix to the object value. For example 'KEY=${SECRET_VALUE}' or 'KEY=${CONFIGMAP_VALUE}' depending on the context. + // +optional + Format *string `json:"format"` +} + +// The value type contains the properties for a value, this allows for an +// easy extension in the future to support more kinds +type SingleValue struct { + + // The value of the parameter + // +optional + Value *string `json:"value"` + + // The ConfigMap value of the parameter + // +optional + ConfigMapValue *ObjectKeyRef `json:"configMapValue"` + + // The secret value of the parameter + // +optional + SecretValue *ObjectKeyRef `json:"secretValue"` +} + +// ParamValue is a key/value that populates a strategy parameter +// used in the execution of the strategy steps +type ParamValue struct { + + // Inline the properties of a value + // +optional + *SingleValue `json:",inline"` + + // Name of the parameter + // +required + Name string `json:"name"` + + // Values of an array parameter + // +optional + Values []SingleValue `json:"values,omitempty"` +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/register.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/register.go new file mode 100644 index 00000000..b23dbfe4 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/register.go @@ -0,0 +1,36 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +// NOTE: Boilerplate only. Ignore this file. + +// Package v1beta1 contains API Schema definitions for the build v1beta1 API group +// +k8s:deepcopy-gen=package,register +// +groupName=shipwright.io +package v1beta1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +var ( + // SchemeGroupVersion is group version used to register these objects + SchemeGroupVersion = schema.GroupVersion{Group: "shipwright.io", Version: "v1beta1"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme + SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} + + // AddToScheme is used in the generated kube code + AddToScheme = SchemeBuilder.AddToScheme +) + +// Kind takes an unqualified kind and returns back a Group qualified GroupKind +func Kind(kind string) schema.GroupKind { + return SchemeGroupVersion.WithKind(kind).GroupKind() +} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/source.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/source.go new file mode 100644 index 00000000..dad73167 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/source.go @@ -0,0 +1,124 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package v1beta1 + +import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + +// PruneOption defines the supported options for image pruning +type PruneOption string + +// BuildSourceType enumerates build source type names. +type BuildSourceType string + +// LocalType represents a alternative build workflow that instead of `git clone` the repository, it +// employs the data uploaded by the user, streamed directly into the POD. +const LocalType BuildSourceType = "Local" + +// GitType represents the default build workflow behaviour. Where the source code is `git clone` from +// a public or private repository +const GitType BuildSourceType = "Git" + +// OCIArtifactType represents a source code bundle container image to pull. This is where the source code resides. +const OCIArtifactType BuildSourceType = "OCI" + +const ( + // Do not delete image after it was pulled + PruneNever PruneOption = "Never" + + // Delete image after it was successfully pulled + PruneAfterPull PruneOption = "AfterPull" +) + +type Local struct { + // Timeout how long the BuildSource execution must take. + // + // +optional + Timeout *metav1.Duration `json:"timeout,omitempty"` + + // Name of the local step + Name string `json:"name,omitempty"` +} + +// Git describes the git repository to pull +type Git struct { + // URL describes the URL of the Git repository. + // + // +optional + URL *string `json:"url,omitempty"` + + // Revision describes the Git revision (e.g., branch, tag, commit SHA, + // etc.) to fetch. + // + // If not defined, it will fallback to the repository's default branch. + // + // +optional + Revision *string `json:"revision,omitempty"` + + // CloneSecret references a Secret that contains credentials to access + // the repository. + // + // +optional + CloneSecret *string `json:"cloneSecret,omitempty"` +} + +// OCIArtifact describes the source code bundle container to pull +type OCIArtifact struct { + // Image reference, i.e. quay.io/org/image:tag + Image string `json:"image"` + + // Prune specifies whether the image is suppose to be deleted. Allowed + // values are 'Never' (no deletion) and `AfterPull` (removal after the + // image was successfully pulled from the registry). + // + // If not defined, it defaults to 'Never'. + // + // +optional + Prune *PruneOption `json:"prune,omitempty"` + // PullSecret references a Secret that contains credentials to access + // the repository. + // + // +optional + PullSecret *string `json:"pullSecret,omitempty"` +} + +// Source describes the Git source repository to fetch. +type Source struct { + // Type is the BuildSource qualifier, the type of the data-source. + // + // +optional + Type BuildSourceType `json:"type,omitempty"` + + // ContextDir is a path to subfolder in the repo. Optional. + // + // +optional + ContextDir *string `json:"contextDir,omitempty"` + + // OCIArtifact + // + // +optional + OCIArtifact *OCIArtifact `json:"ociArtifact,omitempty"` + + // GitSource + // + // +optional + GitSource *Git `json:"git,omitempty"` + + // LocalSource + // + // +optional + LocalSource *Local `json:"local,omitempty"` +} + +// BuildRunSource describes the local source to use +type BuildRunSource struct { + // Type is the BuildRunSource qualifier, the type of the data-source. + // Only LocalType is supported. + // + // +optional + Type BuildSourceType `json:"type,omitempty"` + // LocalSource + // + LocalSource *Local `json:"local,omitempty"` +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger.go new file mode 100644 index 00000000..633417b3 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger.go @@ -0,0 +1,15 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 +package v1beta1 + +// Trigger represents the webhook trigger configuration for a Build. +type Trigger struct { + // When the list of scenarios when a new build should take place. + When []TriggerWhen `json:"when,omitempty"` + + // TriggerSecret points to a local object carrying the secret token to validate webhook request. + // + // +optional + TriggerSecret *string `json:"triggerSecret,omitempty"` +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_types.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_types.go new file mode 100644 index 00000000..ea6550f7 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_types.go @@ -0,0 +1,66 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 +package v1beta1 + +// TriggerType set of TriggerWhen valid names. +type TriggerType string + +const ( + // GitHubWebHookTrigger GitHubWebHookTrigger trigger type name. + GitHubWebHookTrigger TriggerType = "GitHub" + + // ImageTrigger Image trigger type name. + ImageTrigger TriggerType = "Image" + + // PipelineTrigger Tekton Pipeline trigger type name. + PipelineTrigger TriggerType = "Pipeline" +) + +// GitHubEventName set of WhenGitHub valid event names. +type GitHubEventName string + +const ( + // GitHubPullRequestEvent github pull-request event name. + GitHubPullRequestEvent GitHubEventName = "PullRequest" + + // GitHubPushEvent git push webhook event name. + GitHubPushEvent GitHubEventName = "Push" +) + +// WhenImage attributes to match Image events. +type WhenImage struct { + // Names fully qualified image names. + // + // +optional + Names []string `json:"names,omitempty"` +} + +// WhenGitHub attributes to match GitHub events. +type WhenGitHub struct { + // Events GitHub event names. + // + // +kubebuilder:validation:MinItems=1 + Events []GitHubEventName `json:"events,omitempty"` + + // Branches slice of branch names where the event applies. + // + // +optional + Branches []string `json:"branches,omitempty"` +} + +// WhenObjectRef attributes to reference local Kubernetes objects. +type WhenObjectRef struct { + // Name target object name. + // + // +optional + Name string `json:"name,omitempty"` + + // Status object status. + Status []string `json:"status,omitempty"` + + // Selector label selector. + // + // +optional + Selector map[string]string `json:"selector,omitempty"` +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_when.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_when.go new file mode 100644 index 00000000..1617c0b1 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/trigger_when.go @@ -0,0 +1,41 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 +package v1beta1 + +// TriggerWhen a given scenario where the webhook trigger is applicable. +type TriggerWhen struct { + // Name name or the short description of the trigger condition. + Name string `json:"name"` + + // Type the event type + Type TriggerType `json:"type"` + + // GitHub describes how to trigger builds based on GitHub (SCM) events. + // + // +optional + GitHub *WhenGitHub `json:"github,omitempty"` + + // Image slice of image names where the event applies. + // + // +optional + Image *WhenImage `json:"image,omitempty"` + + // ObjectRef describes how to match a foreign resource, either using the name or the label + // selector, plus the current resource status. + // + // +optional + ObjectRef *WhenObjectRef `json:"objectRef,omitempty"` +} + +// GetBranches return a slice of branch names based on the WhenTypeName informed. +func (w *TriggerWhen) GetBranches(whenType TriggerType) []string { + switch whenType { + case GitHubWebHookTrigger: + if w.GitHub == nil { + return nil + } + return w.GitHub.Branches + } + return nil +} diff --git a/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 00000000..4c3dc1df --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/apis/build/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,1317 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1beta1 + +import ( + corev1 "k8s.io/api/core/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Build) DeepCopyInto(out *Build) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Build. +func (in *Build) DeepCopy() *Build { + if in == nil { + return nil + } + out := new(Build) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Build) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildList) DeepCopyInto(out *BuildList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Build, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildList. +func (in *BuildList) DeepCopy() *BuildList { + if in == nil { + return nil + } + out := new(BuildList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BuildList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildRetention) DeepCopyInto(out *BuildRetention) { + *out = *in + if in.FailedLimit != nil { + in, out := &in.FailedLimit, &out.FailedLimit + *out = new(uint) + **out = **in + } + if in.SucceededLimit != nil { + in, out := &in.SucceededLimit, &out.SucceededLimit + *out = new(uint) + **out = **in + } + if in.TTLAfterFailed != nil { + in, out := &in.TTLAfterFailed, &out.TTLAfterFailed + *out = new(v1.Duration) + **out = **in + } + if in.TTLAfterSucceeded != nil { + in, out := &in.TTLAfterSucceeded, &out.TTLAfterSucceeded + *out = new(v1.Duration) + **out = **in + } + if in.AtBuildDeletion != nil { + in, out := &in.AtBuildDeletion, &out.AtBuildDeletion + *out = new(bool) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildRetention. +func (in *BuildRetention) DeepCopy() *BuildRetention { + if in == nil { + return nil + } + out := new(BuildRetention) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildRun) DeepCopyInto(out *BuildRun) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildRun. +func (in *BuildRun) DeepCopy() *BuildRun { + if in == nil { + return nil + } + out := new(BuildRun) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BuildRun) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildRunList) DeepCopyInto(out *BuildRunList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]BuildRun, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildRunList. +func (in *BuildRunList) DeepCopy() *BuildRunList { + if in == nil { + return nil + } + out := new(BuildRunList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BuildRunList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildRunRetention) DeepCopyInto(out *BuildRunRetention) { + *out = *in + if in.TTLAfterFailed != nil { + in, out := &in.TTLAfterFailed, &out.TTLAfterFailed + *out = new(v1.Duration) + **out = **in + } + if in.TTLAfterSucceeded != nil { + in, out := &in.TTLAfterSucceeded, &out.TTLAfterSucceeded + *out = new(v1.Duration) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildRunRetention. +func (in *BuildRunRetention) DeepCopy() *BuildRunRetention { + if in == nil { + return nil + } + out := new(BuildRunRetention) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildRunSource) DeepCopyInto(out *BuildRunSource) { + *out = *in + if in.LocalSource != nil { + in, out := &in.LocalSource, &out.LocalSource + *out = new(Local) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildRunSource. +func (in *BuildRunSource) DeepCopy() *BuildRunSource { + if in == nil { + return nil + } + out := new(BuildRunSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildRunSpec) DeepCopyInto(out *BuildRunSpec) { + *out = *in + in.Build.DeepCopyInto(&out.Build) + if in.Source != nil { + in, out := &in.Source, &out.Source + *out = new(BuildRunSource) + (*in).DeepCopyInto(*out) + } + if in.ServiceAccount != nil { + in, out := &in.ServiceAccount, &out.ServiceAccount + *out = new(string) + **out = **in + } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(v1.Duration) + **out = **in + } + if in.ParamValues != nil { + in, out := &in.ParamValues, &out.ParamValues + *out = make([]ParamValue, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Output != nil { + in, out := &in.Output, &out.Output + *out = new(Image) + (*in).DeepCopyInto(*out) + } + if in.State != nil { + in, out := &in.State, &out.State + *out = new(BuildRunRequestedState) + **out = **in + } + if in.Env != nil { + in, out := &in.Env, &out.Env + *out = make([]corev1.EnvVar, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Retention != nil { + in, out := &in.Retention, &out.Retention + *out = new(BuildRunRetention) + (*in).DeepCopyInto(*out) + } + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]BuildVolume, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildRunSpec. +func (in *BuildRunSpec) DeepCopy() *BuildRunSpec { + if in == nil { + return nil + } + out := new(BuildRunSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildRunStatus) DeepCopyInto(out *BuildRunStatus) { + *out = *in + if in.Source != nil { + in, out := &in.Source, &out.Source + *out = new(SourceResult) + (*in).DeepCopyInto(*out) + } + if in.Output != nil { + in, out := &in.Output, &out.Output + *out = new(Output) + **out = **in + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.TaskRunName != nil { + in, out := &in.TaskRunName, &out.TaskRunName + *out = new(string) + **out = **in + } + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = (*in).DeepCopy() + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = (*in).DeepCopy() + } + if in.BuildSpec != nil { + in, out := &in.BuildSpec, &out.BuildSpec + *out = new(BuildSpec) + (*in).DeepCopyInto(*out) + } + if in.FailureDetails != nil { + in, out := &in.FailureDetails, &out.FailureDetails + *out = new(FailureDetails) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildRunStatus. +func (in *BuildRunStatus) DeepCopy() *BuildRunStatus { + if in == nil { + return nil + } + out := new(BuildRunStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildSpec) DeepCopyInto(out *BuildSpec) { + *out = *in + in.Source.DeepCopyInto(&out.Source) + if in.Trigger != nil { + in, out := &in.Trigger, &out.Trigger + *out = new(Trigger) + (*in).DeepCopyInto(*out) + } + in.Strategy.DeepCopyInto(&out.Strategy) + if in.ParamValues != nil { + in, out := &in.ParamValues, &out.ParamValues + *out = make([]ParamValue, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + in.Output.DeepCopyInto(&out.Output) + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(v1.Duration) + **out = **in + } + if in.Env != nil { + in, out := &in.Env, &out.Env + *out = make([]corev1.EnvVar, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Retention != nil { + in, out := &in.Retention, &out.Retention + *out = new(BuildRetention) + (*in).DeepCopyInto(*out) + } + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]BuildVolume, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildSpec. +func (in *BuildSpec) DeepCopy() *BuildSpec { + if in == nil { + return nil + } + out := new(BuildSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildStatus) DeepCopyInto(out *BuildStatus) { + *out = *in + if in.Registered != nil { + in, out := &in.Registered, &out.Registered + *out = new(corev1.ConditionStatus) + **out = **in + } + if in.Reason != nil { + in, out := &in.Reason, &out.Reason + *out = new(BuildReason) + **out = **in + } + if in.Message != nil { + in, out := &in.Message, &out.Message + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildStatus. +func (in *BuildStatus) DeepCopy() *BuildStatus { + if in == nil { + return nil + } + out := new(BuildStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildStrategy) DeepCopyInto(out *BuildStrategy) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Status = in.Status + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildStrategy. +func (in *BuildStrategy) DeepCopy() *BuildStrategy { + if in == nil { + return nil + } + out := new(BuildStrategy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BuildStrategy) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildStrategyList) DeepCopyInto(out *BuildStrategyList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]BuildStrategy, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildStrategyList. +func (in *BuildStrategyList) DeepCopy() *BuildStrategyList { + if in == nil { + return nil + } + out := new(BuildStrategyList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BuildStrategyList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildStrategySecurityContext) DeepCopyInto(out *BuildStrategySecurityContext) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildStrategySecurityContext. +func (in *BuildStrategySecurityContext) DeepCopy() *BuildStrategySecurityContext { + if in == nil { + return nil + } + out := new(BuildStrategySecurityContext) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildStrategySpec) DeepCopyInto(out *BuildStrategySpec) { + *out = *in + if in.Steps != nil { + in, out := &in.Steps, &out.Steps + *out = make([]Step, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Parameters != nil { + in, out := &in.Parameters, &out.Parameters + *out = make([]Parameter, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.SecurityContext != nil { + in, out := &in.SecurityContext, &out.SecurityContext + *out = new(BuildStrategySecurityContext) + **out = **in + } + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]BuildStrategyVolume, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildStrategySpec. +func (in *BuildStrategySpec) DeepCopy() *BuildStrategySpec { + if in == nil { + return nil + } + out := new(BuildStrategySpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildStrategyStatus) DeepCopyInto(out *BuildStrategyStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildStrategyStatus. +func (in *BuildStrategyStatus) DeepCopy() *BuildStrategyStatus { + if in == nil { + return nil + } + out := new(BuildStrategyStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildStrategyVolume) DeepCopyInto(out *BuildStrategyVolume) { + *out = *in + if in.Overridable != nil { + in, out := &in.Overridable, &out.Overridable + *out = new(bool) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + in.VolumeSource.DeepCopyInto(&out.VolumeSource) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildStrategyVolume. +func (in *BuildStrategyVolume) DeepCopy() *BuildStrategyVolume { + if in == nil { + return nil + } + out := new(BuildStrategyVolume) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BuildVolume) DeepCopyInto(out *BuildVolume) { + *out = *in + in.VolumeSource.DeepCopyInto(&out.VolumeSource) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildVolume. +func (in *BuildVolume) DeepCopy() *BuildVolume { + if in == nil { + return nil + } + out := new(BuildVolume) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterBuildStrategy) DeepCopyInto(out *ClusterBuildStrategy) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Status = in.Status + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBuildStrategy. +func (in *ClusterBuildStrategy) DeepCopy() *ClusterBuildStrategy { + if in == nil { + return nil + } + out := new(ClusterBuildStrategy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterBuildStrategy) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterBuildStrategyList) DeepCopyInto(out *ClusterBuildStrategyList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterBuildStrategy, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBuildStrategyList. +func (in *ClusterBuildStrategyList) DeepCopy() *ClusterBuildStrategyList { + if in == nil { + return nil + } + out := new(ClusterBuildStrategyList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterBuildStrategyList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Condition) DeepCopyInto(out *Condition) { + *out = *in + in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Condition. +func (in *Condition) DeepCopy() *Condition { + if in == nil { + return nil + } + out := new(Condition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in Conditions) DeepCopyInto(out *Conditions) { + { + in := &in + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Conditions. +func (in Conditions) DeepCopy() Conditions { + if in == nil { + return nil + } + out := new(Conditions) + in.DeepCopyInto(out) + return *out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *FailureDetails) DeepCopyInto(out *FailureDetails) { + *out = *in + if in.Location != nil { + in, out := &in.Location, &out.Location + *out = new(Location) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FailureDetails. +func (in *FailureDetails) DeepCopy() *FailureDetails { + if in == nil { + return nil + } + out := new(FailureDetails) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Git) DeepCopyInto(out *Git) { + *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(string) + **out = **in + } + if in.Revision != nil { + in, out := &in.Revision, &out.Revision + *out = new(string) + **out = **in + } + if in.CloneSecret != nil { + in, out := &in.CloneSecret, &out.CloneSecret + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Git. +func (in *Git) DeepCopy() *Git { + if in == nil { + return nil + } + out := new(Git) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GitSourceResult) DeepCopyInto(out *GitSourceResult) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitSourceResult. +func (in *GitSourceResult) DeepCopy() *GitSourceResult { + if in == nil { + return nil + } + out := new(GitSourceResult) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Image) DeepCopyInto(out *Image) { + *out = *in + if in.Insecure != nil { + in, out := &in.Insecure, &out.Insecure + *out = new(bool) + **out = **in + } + if in.PushSecret != nil { + in, out := &in.PushSecret, &out.PushSecret + *out = new(string) + **out = **in + } + if in.Annotations != nil { + in, out := &in.Annotations, &out.Annotations + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Image. +func (in *Image) DeepCopy() *Image { + if in == nil { + return nil + } + out := new(Image) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Local) DeepCopyInto(out *Local) { + *out = *in + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(v1.Duration) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Local. +func (in *Local) DeepCopy() *Local { + if in == nil { + return nil + } + out := new(Local) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Location) DeepCopyInto(out *Location) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Location. +func (in *Location) DeepCopy() *Location { + if in == nil { + return nil + } + out := new(Location) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *OCIArtifact) DeepCopyInto(out *OCIArtifact) { + *out = *in + if in.Prune != nil { + in, out := &in.Prune, &out.Prune + *out = new(PruneOption) + **out = **in + } + if in.PullSecret != nil { + in, out := &in.PullSecret, &out.PullSecret + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OCIArtifact. +func (in *OCIArtifact) DeepCopy() *OCIArtifact { + if in == nil { + return nil + } + out := new(OCIArtifact) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ObjectKeyRef) DeepCopyInto(out *ObjectKeyRef) { + *out = *in + if in.Format != nil { + in, out := &in.Format, &out.Format + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectKeyRef. +func (in *ObjectKeyRef) DeepCopy() *ObjectKeyRef { + if in == nil { + return nil + } + out := new(ObjectKeyRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *OciArtifactSourceResult) DeepCopyInto(out *OciArtifactSourceResult) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OciArtifactSourceResult. +func (in *OciArtifactSourceResult) DeepCopy() *OciArtifactSourceResult { + if in == nil { + return nil + } + out := new(OciArtifactSourceResult) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Output) DeepCopyInto(out *Output) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Output. +func (in *Output) DeepCopy() *Output { + if in == nil { + return nil + } + out := new(Output) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ParamValue) DeepCopyInto(out *ParamValue) { + *out = *in + if in.SingleValue != nil { + in, out := &in.SingleValue, &out.SingleValue + *out = new(SingleValue) + (*in).DeepCopyInto(*out) + } + if in.Values != nil { + in, out := &in.Values, &out.Values + *out = make([]SingleValue, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ParamValue. +func (in *ParamValue) DeepCopy() *ParamValue { + if in == nil { + return nil + } + out := new(ParamValue) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Parameter) DeepCopyInto(out *Parameter) { + *out = *in + if in.Default != nil { + in, out := &in.Default, &out.Default + *out = new(string) + **out = **in + } + if in.Defaults != nil { + in, out := &in.Defaults, &out.Defaults + *out = new([]string) + if **in != nil { + in, out := *in, *out + *out = make([]string, len(*in)) + copy(*out, *in) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Parameter. +func (in *Parameter) DeepCopy() *Parameter { + if in == nil { + return nil + } + out := new(Parameter) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ReferencedBuild) DeepCopyInto(out *ReferencedBuild) { + *out = *in + if in.Build != nil { + in, out := &in.Build, &out.Build + *out = new(BuildSpec) + (*in).DeepCopyInto(*out) + } + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReferencedBuild. +func (in *ReferencedBuild) DeepCopy() *ReferencedBuild { + if in == nil { + return nil + } + out := new(ReferencedBuild) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SingleValue) DeepCopyInto(out *SingleValue) { + *out = *in + if in.Value != nil { + in, out := &in.Value, &out.Value + *out = new(string) + **out = **in + } + if in.ConfigMapValue != nil { + in, out := &in.ConfigMapValue, &out.ConfigMapValue + *out = new(ObjectKeyRef) + (*in).DeepCopyInto(*out) + } + if in.SecretValue != nil { + in, out := &in.SecretValue, &out.SecretValue + *out = new(ObjectKeyRef) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SingleValue. +func (in *SingleValue) DeepCopy() *SingleValue { + if in == nil { + return nil + } + out := new(SingleValue) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Source) DeepCopyInto(out *Source) { + *out = *in + if in.ContextDir != nil { + in, out := &in.ContextDir, &out.ContextDir + *out = new(string) + **out = **in + } + if in.OCIArtifact != nil { + in, out := &in.OCIArtifact, &out.OCIArtifact + *out = new(OCIArtifact) + (*in).DeepCopyInto(*out) + } + if in.GitSource != nil { + in, out := &in.GitSource, &out.GitSource + *out = new(Git) + (*in).DeepCopyInto(*out) + } + if in.LocalSource != nil { + in, out := &in.LocalSource, &out.LocalSource + *out = new(Local) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Source. +func (in *Source) DeepCopy() *Source { + if in == nil { + return nil + } + out := new(Source) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SourceResult) DeepCopyInto(out *SourceResult) { + *out = *in + if in.Git != nil { + in, out := &in.Git, &out.Git + *out = new(GitSourceResult) + **out = **in + } + if in.OciArtifact != nil { + in, out := &in.OciArtifact, &out.OciArtifact + *out = new(OciArtifactSourceResult) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceResult. +func (in *SourceResult) DeepCopy() *SourceResult { + if in == nil { + return nil + } + out := new(SourceResult) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Step) DeepCopyInto(out *Step) { + *out = *in + if in.Command != nil { + in, out := &in.Command, &out.Command + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Args != nil { + in, out := &in.Args, &out.Args + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Env != nil { + in, out := &in.Env, &out.Env + *out = make([]corev1.EnvVar, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + in.Resources.DeepCopyInto(&out.Resources) + if in.VolumeMounts != nil { + in, out := &in.VolumeMounts, &out.VolumeMounts + *out = make([]corev1.VolumeMount, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.SecurityContext != nil { + in, out := &in.SecurityContext, &out.SecurityContext + *out = new(corev1.SecurityContext) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Step. +func (in *Step) DeepCopy() *Step { + if in == nil { + return nil + } + out := new(Step) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Strategy) DeepCopyInto(out *Strategy) { + *out = *in + if in.Kind != nil { + in, out := &in.Kind, &out.Kind + *out = new(BuildStrategyKind) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Strategy. +func (in *Strategy) DeepCopy() *Strategy { + if in == nil { + return nil + } + out := new(Strategy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Trigger) DeepCopyInto(out *Trigger) { + *out = *in + if in.When != nil { + in, out := &in.When, &out.When + *out = make([]TriggerWhen, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.TriggerSecret != nil { + in, out := &in.TriggerSecret, &out.TriggerSecret + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Trigger. +func (in *Trigger) DeepCopy() *Trigger { + if in == nil { + return nil + } + out := new(Trigger) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TriggerWhen) DeepCopyInto(out *TriggerWhen) { + *out = *in + if in.GitHub != nil { + in, out := &in.GitHub, &out.GitHub + *out = new(WhenGitHub) + (*in).DeepCopyInto(*out) + } + if in.Image != nil { + in, out := &in.Image, &out.Image + *out = new(WhenImage) + (*in).DeepCopyInto(*out) + } + if in.ObjectRef != nil { + in, out := &in.ObjectRef, &out.ObjectRef + *out = new(WhenObjectRef) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TriggerWhen. +func (in *TriggerWhen) DeepCopy() *TriggerWhen { + if in == nil { + return nil + } + out := new(TriggerWhen) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WhenGitHub) DeepCopyInto(out *WhenGitHub) { + *out = *in + if in.Events != nil { + in, out := &in.Events, &out.Events + *out = make([]GitHubEventName, len(*in)) + copy(*out, *in) + } + if in.Branches != nil { + in, out := &in.Branches, &out.Branches + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WhenGitHub. +func (in *WhenGitHub) DeepCopy() *WhenGitHub { + if in == nil { + return nil + } + out := new(WhenGitHub) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WhenImage) DeepCopyInto(out *WhenImage) { + *out = *in + if in.Names != nil { + in, out := &in.Names, &out.Names + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WhenImage. +func (in *WhenImage) DeepCopy() *WhenImage { + if in == nil { + return nil + } + out := new(WhenImage) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WhenObjectRef) DeepCopyInto(out *WhenObjectRef) { + *out = *in + if in.Status != nil { + in, out := &in.Status, &out.Status + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WhenObjectRef. +func (in *WhenObjectRef) DeepCopy() *WhenObjectRef { + if in == nil { + return nil + } + out := new(WhenObjectRef) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/shipwright-io/build/pkg/ctxlog/context.go b/vendor/github.com/shipwright-io/build/pkg/ctxlog/context.go new file mode 100644 index 00000000..d50a507b --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/ctxlog/context.go @@ -0,0 +1,55 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package ctxlog + +import ( + "context" + + "github.com/go-logr/logr" + + logf "sigs.k8s.io/controller-runtime/pkg/log" +) + +type contextLogger struct{} + +var ( + loggerKey = &contextLogger{} +) + +// NewParentContext returns a new context from the +// parent context.Background one. This new context +// stores our logger implementation +func NewParentContext(log logr.Logger) context.Context { + ctx := context.Background() + ctx = context.WithValue(ctx, loggerKey, log) + return ctx +} + +// NewContext returns a new child context based on our logger +// key(loggerKey). This function is useful for spawning children +// context with a particular logging name for each controller +func NewContext(ctx context.Context, name string) context.Context { + l := ExtractLogger(ctx) + + l = l.WithName(name) + + return context.WithValue(ctx, loggerKey, l) +} + +// ExtractLogger returns a logger based on the loggerKey +// This function retrieves from an existing context the value, +// which in this case is an instance of our logger +func ExtractLogger(ctx context.Context) logr.Logger { + log, ok := ctx.Value(loggerKey).(logr.Logger) + if !ok || log.GetSink() == nil { + if logger, err := logr.FromContext(ctx); err == nil { + log = logger + } + if log.GetSink() == nil { + log = log.WithSink(logf.NullLogSink{}) + } + } + return log +} diff --git a/vendor/github.com/shipwright-io/build/pkg/ctxlog/log.go b/vendor/github.com/shipwright-io/build/pkg/ctxlog/log.go new file mode 100644 index 00000000..7ab39d96 --- /dev/null +++ b/vendor/github.com/shipwright-io/build/pkg/ctxlog/log.go @@ -0,0 +1,75 @@ +// Copyright The Shipwright Contributors +// +// SPDX-License-Identifier: Apache-2.0 + +package ctxlog + +import ( + "context" + "flag" + "io" + + "github.com/go-logr/logr" + "go.uber.org/zap/zapcore" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + logf "sigs.k8s.io/controller-runtime/pkg/log" +) + +var ( + defaultLogLevel = zapcore.DebugLevel + + flagOptions = &zap.Options{ + Level: &defaultLogLevel, + } +) + +// CustomZapFlagSet creates a flag.FlagSet containing the zap logger default flags to configure the zap options and it +// includes a custom flag `--zap-level` for backwards compatibility reasons +func CustomZapFlagSet() *flag.FlagSet { + f := flag.NewFlagSet("zap", flag.ExitOnError) + flagOptions.BindFlags(f) + + // Add --zap-level for backwards compatibility and hard-wire it against the log level settings. Remove this line and + // the defaultLogLevel as soon as enough time has passed to fix the flag usage. + f.Var(&defaultLogLevel, "zap-level", "Deprecated: Please use --zap-log-level instead; set log level") + + return f +} + +// NewLogger returns a new Logger instance +// by using the controller-runtime log/zap logging +// implementation +func NewLogger(name string) logr.Logger { + l := zap.New(zap.UseFlagOptions(flagOptions)) + logf.SetLogger(l) + + return l.WithName(name) +} + +// NewLoggerTo returns a new Logger which logs +// to a given destination. +func NewLoggerTo(destWriter io.Writer, name string) logr.Logger { + l := zap.New(zap.UseFlagOptions(flagOptions), zap.WriteTo(destWriter)) + logf.SetLogger(l) + + return l.WithName(name) +} + +// Error returns an ERROR level log from an specified context +func Error(ctx context.Context, err error, msg string, v ...interface{}) { + l := ExtractLogger(ctx) + l.Error(err, msg, v...) +} + +// Debug returns an DEBUG level log from an specified context +func Debug(ctx context.Context, msg string, v ...interface{}) { + l := ExtractLogger(ctx) + l.V(1).Info(msg, v...) +} + +// Info returns an INFO level log from an specified context +func Info(ctx context.Context, msg string, v ...interface{}) { + l := ExtractLogger(ctx) + l.Info(msg, v...) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index bdc50768..4f715a41 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -247,6 +247,8 @@ github.com/prometheus/statsd_exporter/pkg/mapper/fsm # github.com/shipwright-io/build v0.12.0 ## explicit; go 1.20 github.com/shipwright-io/build/pkg/apis/build/v1alpha1 +github.com/shipwright-io/build/pkg/apis/build/v1beta1 +github.com/shipwright-io/build/pkg/ctxlog github.com/shipwright-io/build/pkg/webhook # github.com/spf13/pflag v1.0.5 ## explicit; go 1.12