github.com/paketoio/libpak@v1.3.1/detect.go (about)

     1  /*
     2   * Copyright 2018-2020 the original author or authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      https://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package libpak
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/buildpacks/libcnb"
    23  	"github.com/imdario/mergo"
    24  	"github.com/paketoio/libpak/bard"
    25  	"github.com/paketoio/libpak/internal"
    26  )
    27  
    28  // Detect is called by the main function of a buildpack, for detection.
    29  func Detect(f libcnb.DetectFunc, options ...libcnb.Option) {
    30  	libcnb.Detect(
    31  		func(context libcnb.DetectContext) (libcnb.DetectResult, error) {
    32  
    33  			// TODO: Remove once pack supports bindings natively
    34  			bindings, err := libcnb.NewBindingsFromEnvironment("CNB_BINDINGS")
    35  			if err != nil {
    36  				return libcnb.DetectResult{}, fmt.Errorf("unable to get bindings from $CNB_BINDINGS: %w", err)
    37  			}
    38  			if err := mergo.Merge(&context.Platform.Bindings, bindings); err != nil {
    39  				return libcnb.DetectResult{}, fmt.Errorf("unable to merge bindings %+v and %+v: %w", context.Platform.Bindings, bindings, err)
    40  			}
    41  
    42  			result, err := f(context)
    43  			if err != nil {
    44  				err = bard.IdentifiableError{
    45  					Name:        context.Buildpack.Info.Name,
    46  					Description: context.Buildpack.Info.Version,
    47  					Err:         err,
    48  				}
    49  			}
    50  
    51  			return result, err
    52  		},
    53  		append([]libcnb.Option{
    54  			libcnb.WithExitHandler(internal.NewExitHandler()),
    55  			libcnb.WithTOMLWriter(internal.NewTOMLWriter()),
    56  		}, options...)...,
    57  	)
    58  
    59  }