Skip to content

Commit

Permalink
Merge branch 'main' of github.com:nateinaction/rules_envfile
Browse files Browse the repository at this point in the history
  • Loading branch information
nateinaction committed May 12, 2021
2 parents 1a311ed + c8f591c commit b196f34
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 7 deletions.
3 changes: 2 additions & 1 deletion WORKSPACE
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ envfile(
name = "env",
files = [
# "non-package/non-package.env",
"//test-package:package.env"
"//test-package:package.env",
"//test-package:package2.env",
]
)
22 changes: 21 additions & 1 deletion env.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,39 @@ filegroup(
)
'''


def _envfile_impl(repository_ctx):
files = repository_ctx.attr.files
lines = ["# Generated by rules_envfile - do not modify"]

for file in files:
path = repository_ctx.path(file)
content = repository_ctx.read(path)
lines.append(content)
for line in content.splitlines():
env_var = line.split("=", 1)
key, value = env_var[0], env_var[1]
value = _quote(value) if not _starts_with_quote(value) else value
lines.append("{}={}".format(key, value))

env_file = "\n".join(lines)
repository_ctx.file("environment.bzl", env_file)
repository_ctx.file("BUILD.bazel", BUILD_DOT_BAZEL)


def _quote(value):
value = value.replace("\\", "\\\\")
value = value.replace("\"", "\\\"")
return "\"{}\"".format(value)


def _starts_with_quote(value):
valid_quote_chars = ['"', "'"]
for quote_type in valid_quote_chars:
if value.startswith(quote_type):
return True
return False


envfile = repository_rule(
implementation = _envfile_impl,
attrs = {
Expand Down
2 changes: 1 addition & 1 deletion test-package/package.env
Original file line number Diff line number Diff line change
@@ -1 +1 @@
PACKAGE="foo"
QUOTED="foo"
1 change: 1 addition & 0 deletions test-package/package2.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UNQUOTED=baz
5 changes: 3 additions & 2 deletions test/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
load("@env//:environment.bzl", "PACKAGE")
load("@env//:environment.bzl", "QUOTED", "UNQUOTED")

sh_test(
name = "test",
srcs = ["test.sh"],
env = {
"PACKAGE": PACKAGE,
"QUOTED": QUOTED,
"UNQUOTED": UNQUOTED,
},
)
9 changes: 7 additions & 2 deletions test/test.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
#!/bin/bash

if [ "${PACKAGE}" != "foo" ]; then
echo "PACKAGE not set"
if [ "${QUOTED}" != "foo" ]; then
echo "QUOTED not set"
exit 1
fi

if [ "${UNQUOTED}" != "baz" ]; then
echo "UNQUOTED not set"
exit 1
fi

Expand Down

0 comments on commit b196f34

Please sign in to comment.