Skip to content

Commit

Permalink
python: add a wrapper to indirect 2/3
Browse files Browse the repository at this point in the history
  • Loading branch information
whilp committed Oct 8, 2018
1 parent 8a2f361 commit dc55afd
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 8 deletions.
2 changes: 1 addition & 1 deletion .bazelrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
common --python_top=//python
build --show_loading_progress
build --show_progress
build --show_progress_rate_limit=60.0
Expand All @@ -16,5 +17,4 @@ build:ci --nouse_action_cache
build:ci --sandbox_debug
build:ci --spawn_strategy=standalone
common:ci --color=no
common:ci --python_top=//python:py2
test:ci --test_strategy=standalone
14 changes: 7 additions & 7 deletions python/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
py_runtime(
name = "py2",
files = [],
interpreter_path = "/usr/bin/python2",
visibility = ["//visibility:public"],
load("@io_bazel_rules_go//go:def.bzl", "go_binary")

go_binary(
name = "wrapper",
srcs = ["wrapper.go"],
)

py_runtime(
name = "py3",
name = "python",
files = [],
interpreter_path = "/usr/bin/python3",
interpreter = ":wrapper",
visibility = ["//visibility:public"],
)
61 changes: 61 additions & 0 deletions python/wrapper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"bufio"
"fmt"
"log"
"os"
"strings"
"syscall"
)

func main() {
args := os.Args
env := os.Environ()
if err := wrap(args, env); err != nil {
log.Fatal(err)
}
}

func wrap(args []string, env []string) error {
python, _ := guess(args)

args = append([]string{python}, args[1:]...)
return syscall.Exec(python, args, env)
}

func guess(args []string) (string, error) {
python := python2()

if len(args) < 2 {
return python, fmt.Errorf("missing file argument")
}
file, err := os.Open(os.Args[1])
if err != nil {
return python, err
}
defer file.Close()

scanner := bufio.NewScanner(file)
scanner.Scan()
shebang := scanner.Text()
if err := scanner.Err(); err != nil {
return python, err
}

switch {
case strings.Contains(shebang, "python3"):
python = python3()
default:
python = python2()
}
return python, nil
}

func python2() string {
return "/usr/bin/python2"
}

func python3() string {
return "/usr/bin/python3"
}

0 comments on commit dc55afd

Please sign in to comment.