Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ruby_binary compatible with container #17

Merged
merged 8 commits into from
Dec 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ before_install:
- bundle install
install:
- bazel $BAZEL_OPTS build $BAZEL_BUILD_OPTS --show_progress_rate_limit 0 -- //...
- (cd examples && bazel $BAZEL_OPTS build $BAZEL_BUILD_OPTS --show_progress_rate_limit 0 -- //...)
- (cd examples/simple_script && bazel $BAZEL_OPTS build $BAZEL_BUILD_OPTS --show_progress_rate_limit 0 -- //...)
script:
- bazel $BAZEL_OPTS test $BAZEL_BUILD_OPTS --show_progress_rate_limit 0 --test_output=streamed -- //...
- (cd examples && bazel $BAZEL_OPTS test $BAZEL_BUILD_OPTS --show_progress_rate_limit 0 --test_output=streamed -- //...)
- (cd examples/simple_script && bazel $BAZEL_OPTS test $BAZEL_BUILD_OPTS --show_progress_rate_limit 0 --test_output=streamed -- //...)
# If this fails run `bazel run :buildifier`
- bazel run :buildifier-check
# If this fails run `bundle exec rubocop -a`
Expand All @@ -47,4 +47,4 @@ env:
global:
- PATH=$PATH:$HOME/local/bin
- BAZEL_OPTS="--host_jvm_args=-Xmx500m --host_jvm_args=-Xms500m"
- BAZEL_BUILD_OPTS="--curses=no --genrule_strategy=standalone --spawn_strategy=standalone --verbose_failures -j 20"
- BAZEL_BUILD_OPTS="--curses=no --verbose_failures -j 20"
32 changes: 32 additions & 0 deletions WORKSPACE
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,35 @@ gazelle_dependencies()
load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")

protobuf_deps()

# rules_docker

http_archive(
name = "io_bazel_rules_docker",
sha256 = "14ac30773fdb393ddec90e158c9ec7ebb3f8a4fd533ec2abbfd8789ad81a284b",
strip_prefix = "rules_docker-0.12.1",
urls = ["https://github.com/bazelbuild/rules_docker/releases/download/v0.12.1/rules_docker-v0.12.1.tar.gz"],
)

load(
"@io_bazel_rules_docker//repositories:repositories.bzl",
container_repositories = "repositories",
)

container_repositories()

load("@io_bazel_rules_docker//repositories:deps.bzl", container_deps = "deps")

container_deps()

load(
"@io_bazel_rules_docker//container:container.bzl",
"container_pull",
)

container_pull(
name = "ruby_base_container",
digest = "sha256:da560e130d6a4b75b099e932a98331ec3b2420b914d51a88edc4fe3c60aee9b1", # alpine linux/amd64
registry = "docker.io",
repository = "library/ruby",
)
1 change: 0 additions & 1 deletion examples/simple_script/.rspec

This file was deleted.

9 changes: 6 additions & 3 deletions examples/simple_script/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@ ruby_binary(
)

ruby_test(
name = "default_test",
srcs = ["script_spec.rb"],
main = "script_spec.rb",
name = "script_spec",
srcs = [
"script.rb",
"spec/script_spec.rb",
],
main = "spec/script_spec.rb",
rubyopt = ["-rrspec/autorun"], # require autorun because it is needed
deps = [
"//lib:foo",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@

require_relative '../script'

describe OSSRand do
it begin
expect(oss_rand).to be String
describe 'oss_rand' do
it 'generates a String' do
expect(oss_rand).to be_a_kind_of String
end
end
12 changes: 2 additions & 10 deletions ruby/private/BUILD.host_runtime.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ ruby_toolchain(
name = "ruby_host",
interpreter = "//:ruby_bin",
bundler = "//:bundler",
init_files = ["//:init_loadpath"],
rubyopt = [
"-I../org_ruby_lang_ruby_host/bundler/lib",
"-I$(RUNFILES_DIR)/org_ruby_lang_ruby_host/bundler/lib",
],
runtime = "//:runtime",
is_host = True,
rules_ruby_workspace = "{rules_ruby_workspace}",
# TODO(yugui) Extract platform info from RbConfig
# exec_compatible_with = [],
Expand All @@ -27,12 +27,6 @@ sh_binary(
data = [":runtime"],
)

filegroup(
name = "init_loadpath",
srcs = ["init_loadpath.rb"],
data = ["loadpath.lst"],
)

cc_import(
name = "libruby",
hdrs = glob({hdrs}),
Expand All @@ -57,8 +51,6 @@ filegroup(
srcs = glob(
include = ["**/*"],
exclude = [
"init_loadpath.rb",
"loadpath.lst",
"BUILD.bazel",
"WORKSPACE",
],
Expand Down
31 changes: 20 additions & 11 deletions ruby/private/binary.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ load(
_transitive_deps = "transitive_deps",
)

def _to_manifest_path(ctx, file):
if file.short_path.startswith("../"):
return file.short_path[3:]
else:
return ("%s/%s" % (ctx.workspace_name, file.short_path))

def _ruby_binary_impl(ctx):
sdk = ctx.toolchains[TOOLCHAIN_TYPE_NAME].ruby_runtime
interpreter = sdk.interpreter[DefaultInfo].files_to_run.executable
init_files = [f for t in sdk.init_files for f in t.files.to_list()]
init_flags = " ".join(["-r${PATH_PREFIX}%s" % f.short_path for f in init_files])

main = ctx.file.main
if not main:
Expand All @@ -20,30 +24,35 @@ def _ruby_binary_impl(ctx):
break
if not main:
fail(
("main must be present unless the name of the rule matches to one " +
"of the srcs"),
("main must be present unless the name of the rule matches to " +
"one of the srcs"),
"main",
)

if sdk.is_host:
interpreter_file_deps = []
interpreter_trans_deps = []
else:
interpreter_file_deps = [interpreter]
interpreter_trans_deps = [sdk.interpreter]

executable = ctx.actions.declare_file(ctx.attr.name)
deps = _transitive_deps(
ctx,
extra_files = init_files + [interpreter, executable],
extra_deps = sdk.init_files + [sdk.interpreter],
extra_files = interpreter_file_deps + [executable],
extra_deps = interpreter_trans_deps,
)

rubyopt = reversed(deps.rubyopt.to_list())
rubyopt += ["-I${PATH_PREFIX}%s" % inc for inc in deps.incpaths.to_list()]

ctx.actions.expand_template(
template = ctx.file._wrapper_template,
output = executable,
substitutions = {
"{interpreter}": interpreter.short_path,
"{init_flags}": init_flags,
"{rubyopt}": " ".join(rubyopt),
"{main}": main.short_path,
"{workspace_name}": ctx.label.workspace_name or ctx.workspace_name,
"{loadpaths}": repr(deps.incpaths.to_list()),
"{rubyopt}": repr(rubyopt),
"{main}": repr(_to_manifest_path(ctx, main)),
},
is_executable = True,
)
Expand Down
140 changes: 126 additions & 14 deletions ruby/private/binary_wrapper.tpl
Original file line number Diff line number Diff line change
@@ -1,14 +1,126 @@
#!/bin/sh

if [ -n "${RUNFILES_DIR+x}" ]; then
PATH_PREFIX=$RUNFILES_DIR/{workspace_name}/
elif [ -s `dirname $0`/../../MANIFEST ]; then
PATH_PREFIX=`cd $(dirname $0); pwd`/
elif [ -d $0.runfiles ]; then
PATH_PREFIX=`cd $0.runfiles; pwd`/{workspace_name}/
else
echo "WARNING: it does not look to be at the .runfiles directory" >&2
exit 1
fi

$PATH_PREFIX{interpreter} --disable-gems {init_flags} {rubyopt} -I${PATH_PREFIX} {main} "$@"
#!/usr/bin/env ruby

# Ruby-port of the Bazel's wrapper script for Python

# Copyright 2017 The Bazel Authors. All rights reserved.
# Copyright 2019 BazelRuby Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require 'rbconfig'

def find_runfiles
stub_filename = File.absolute_path($0)
runfiles = "#{stub_filename}.runfiles"
loop do
case
when File.directory?(runfiles)
return runfiles
when %r!(.*\.runfiles)/.*!o =~ stub_filename
return $1
when File.symlink?(stub_filename)
target = File.readlink(stub_filename)
stub_filename = File.absolute_path(target, File.dirname(stub_filename))
else
break
end
end
raise "Cannot find .runfiles directory for #{$0}"
end

def create_loadpath_entries(custom, runfiles)
[runfiles] + custom.map {|path| File.join(runfiles, path) }
end

def get_repository_imports(runfiles)
Dir.children(runfiles).map {|d|
File.join(runfiles, d)
}.select {|d|
File.directory? d
}
end

# Finds the runfiles manifest or the runfiles directory.
def runfiles_envvar(runfiles)
# If this binary is the data-dependency of another one, the other sets
# RUNFILES_MANIFEST_FILE or RUNFILES_DIR for our sake.
manifest = ENV['RUNFILES_MANIFEST_FILE']
if manifest
return ['RUNFILES_MANIFEST_FILE', manifest]
end

dir = ENV['RUNFILES_DIR']
if dir
return ['RUNFILES_DIR', dir]
end

# Look for the runfiles "output" manifest, argv[0] + ".runfiles_manifest"
manifest = runfiles + '_manifest'
if File.exists?(manifest)
return ['RUNFILES_MANIFEST_FILE', manifest]
end

# Look for the runfiles "input" manifest, argv[0] + ".runfiles/MANIFEST"
manifest = File.join(runfiles, 'MANIFEST')
if File.exists?(manifest)
return ['RUNFILES_DIR', manifest]
end

# If running in a sandbox and no environment variables are set, then
# Look for the runfiles next to the binary.
if runfiles.end_with?('.runfiles') and File.directory?(runfiles)
return ['RUNFILES_DIR', runfiles]
end
end

def find_ruby_binary
File.join(
RbConfig::CONFIG['bindir'],
RbConfig::CONFIG['ruby_install_name'],
)
end

def main(args)
custom_loadpaths = {loadpaths}
runfiles = find_runfiles

loadpaths = create_loadpath_entries(custom_loadpaths, runfiles)
loadpaths += get_repository_imports(runfiles)
loadpaths += ENV['RUBYLIB'].split(':') if ENV.key?('RUBYLIB')
ENV['RUBYLIB'] = loadpaths.join(':')

runfiles_envkey, runfiles_envvalue = runfiles_envvar(runfiles)
ENV[runfiles_envkey] = runfiles_envvalue if runfiles_envkey

ruby_program = find_ruby_binary

main = {main}
main = File.join(runfiles, main)
rubyopt = {rubyopt}.map do |opt|
opt.gsub(/\${(.+?)}/o) do
case $1
when 'RUNFILES_DIR'
runfiles
else
ENV[$1]
end
end
end
exec(ruby_program, '--disable-gems', *rubyopt, main, *args)
# TODO(yugui) Support windows
end

if __FILE__ == $0
main(ARGV)
end
6 changes: 3 additions & 3 deletions ruby/private/bundle/create_bundle_build_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
exclude = {exclude},
),
deps = [":bundler_setup"],
rubyopt = ["-r../{repo_name}/lib/bundler/setup.rb"],
rubyopt = ["-r${RUNFILES_DIR}/{repo_name}/lib/bundler/setup.rb"],
)

# PULL EACH GEM INDIVIDUALLY
Expand All @@ -48,7 +48,7 @@
exclude = {exclude},
),
deps = {deps},
rubyopt = ["-r../{repo_name}/lib/bundler/setup.rb"],
rubyopt = ["-r${RUNFILES_DIR}/{repo_name}/lib/bundler/setup.rb"],
)

'
Expand All @@ -57,7 +57,7 @@
ruby_library(
name = "all",
deps = {deps},
rubyopt = ["-r../{repo_name}/lib/bundler/setup.rb"],
rubyopt = ["-r${RUNFILES_DIR}/{repo_name}/lib/bundler/setup.rb"],
)
'
require "bundler"
Expand Down
Loading