|
| 1 | +// Copyright 2026 The go-python Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package bind |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "os" |
| 10 | + "strings" |
| 11 | +) |
| 12 | + |
| 13 | +// BackendEnvVar is the environment variable that selects which tool is used |
| 14 | +// to bind the generated cgo shim to CPython. |
| 15 | +const BackendEnvVar = "GOPY_BACKEND" |
| 16 | + |
| 17 | +// Backend names a CPython binding tool. |
| 18 | +type Backend string |
| 19 | + |
| 20 | +const ( |
| 21 | + BackendPyBindGen Backend = "pybindgen" // default |
| 22 | + BackendCFFI Backend = "cffi" |
| 23 | + BackendPyBind11 Backend = "pybind11" |
| 24 | + BackendNanobind Backend = "nanobind" |
| 25 | + BackendCAPI Backend = "capi" |
| 26 | + BackendCGO Backend = "cgo" |
| 27 | +) |
| 28 | + |
| 29 | +// backends lists every known backend and whether gopy can generate it yet. |
| 30 | +var backends = []struct { |
| 31 | + name Backend |
| 32 | + implemented bool |
| 33 | +}{ |
| 34 | + {BackendPyBindGen, true}, |
| 35 | + {BackendCFFI, false}, |
| 36 | + {BackendPyBind11, false}, |
| 37 | + {BackendNanobind, false}, |
| 38 | + {BackendCAPI, false}, |
| 39 | + {BackendCGO, false}, |
| 40 | +} |
| 41 | + |
| 42 | +// BackendFromEnv returns the backend selected by GOPY_BACKEND. |
| 43 | +// An unset or empty variable selects pybindgen. |
| 44 | +func BackendFromEnv() (Backend, error) { |
| 45 | + return parseBackend(os.Getenv(BackendEnvVar)) |
| 46 | +} |
| 47 | + |
| 48 | +func parseBackend(v string) (Backend, error) { |
| 49 | + v = strings.ToLower(strings.TrimSpace(v)) |
| 50 | + if v == "" { |
| 51 | + return BackendPyBindGen, nil |
| 52 | + } |
| 53 | + names := make([]string, len(backends)) |
| 54 | + for i, b := range backends { |
| 55 | + names[i] = string(b.name) |
| 56 | + if string(b.name) != v { |
| 57 | + continue |
| 58 | + } |
| 59 | + if !b.implemented { |
| 60 | + return "", fmt.Errorf("gopy: %s=%q is not implemented yet", BackendEnvVar, v) |
| 61 | + } |
| 62 | + return b.name, nil |
| 63 | + } |
| 64 | + return "", fmt.Errorf("gopy: unknown %s=%q (valid values: %s)", BackendEnvVar, v, strings.Join(names, ", ")) |
| 65 | +} |
0 commit comments