Skip to content

Commit dc55afd

Browse files
committed
python: add a wrapper to indirect 2/3
bazelbuild/bazel#3517
1 parent 8a2f361 commit dc55afd

File tree

3 files changed

+69
-8
lines changed

3 files changed

+69
-8
lines changed

.bazelrc

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
common --python_top=//python
12
build --show_loading_progress
23
build --show_progress
34
build --show_progress_rate_limit=60.0
@@ -16,5 +17,4 @@ build:ci --nouse_action_cache
1617
build:ci --sandbox_debug
1718
build:ci --spawn_strategy=standalone
1819
common:ci --color=no
19-
common:ci --python_top=//python:py2
2020
test:ci --test_strategy=standalone

python/BUILD.bazel

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
py_runtime(
2-
name = "py2",
3-
files = [],
4-
interpreter_path = "/usr/bin/python2",
5-
visibility = ["//visibility:public"],
1+
load("@io_bazel_rules_go//go:def.bzl", "go_binary")
2+
3+
go_binary(
4+
name = "wrapper",
5+
srcs = ["wrapper.go"],
66
)
77

88
py_runtime(
9-
name = "py3",
9+
name = "python",
1010
files = [],
11-
interpreter_path = "/usr/bin/python3",
11+
interpreter = ":wrapper",
1212
visibility = ["//visibility:public"],
1313
)

python/wrapper.go

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"fmt"
6+
"log"
7+
"os"
8+
"strings"
9+
"syscall"
10+
)
11+
12+
func main() {
13+
args := os.Args
14+
env := os.Environ()
15+
if err := wrap(args, env); err != nil {
16+
log.Fatal(err)
17+
}
18+
}
19+
20+
func wrap(args []string, env []string) error {
21+
python, _ := guess(args)
22+
23+
args = append([]string{python}, args[1:]...)
24+
return syscall.Exec(python, args, env)
25+
}
26+
27+
func guess(args []string) (string, error) {
28+
python := python2()
29+
30+
if len(args) < 2 {
31+
return python, fmt.Errorf("missing file argument")
32+
}
33+
file, err := os.Open(os.Args[1])
34+
if err != nil {
35+
return python, err
36+
}
37+
defer file.Close()
38+
39+
scanner := bufio.NewScanner(file)
40+
scanner.Scan()
41+
shebang := scanner.Text()
42+
if err := scanner.Err(); err != nil {
43+
return python, err
44+
}
45+
46+
switch {
47+
case strings.Contains(shebang, "python3"):
48+
python = python3()
49+
default:
50+
python = python2()
51+
}
52+
return python, nil
53+
}
54+
55+
func python2() string {
56+
return "/usr/bin/python2"
57+
}
58+
59+
func python3() string {
60+
return "/usr/bin/python3"
61+
}

0 commit comments

Comments
 (0)