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

Use stat to retain file permissions when copying files #259

Merged
merged 1 commit into from
Aug 12, 2022
Merged
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
40 changes: 26 additions & 14 deletions core/util.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@ load("@bazel_skylib//lib:versions.bzl", "versions")
def is_supported_platform(repository_ctx):
return repository_ctx.which("nix-build") != None

def _is_executable(repository_ctx, path):
stat_exe = repository_ctx.which("stat")
if stat_exe == None:
return False

# A hack to detect if stat in Nix shell is BSD stat as BSD stat does not
# support --version flag
is_bsd_stat = repository_ctx.execute([stat_exe, "--version"]).return_code != 0
if is_bsd_stat:
stat_args = ["-f", "%Lp", path]
else:
stat_args = ["-c", "%a", path]

arguments = [stat_exe] + stat_args
exec_result = repository_ctx.execute(arguments)
stdout = exec_result.stdout.strip()
mode = int(stdout, 8)
return mode & 0o100 != 0

def cp(repository_ctx, src, dest = None):
"""Copy the given file into the external repository root.

Expand All @@ -26,25 +45,18 @@ def cp(repository_ctx, src, dest = None):
if component
])

src_path = repository_ctx.path(src)
dest_path = repository_ctx.path(dest)
executable = _is_executable(repository_ctx, src_path)

# Copy the file
repository_ctx.file(
repository_ctx.path(dest),
repository_ctx.read(repository_ctx.path(src)),
executable = False,
dest_path,
repository_ctx.read(src_path),
executable = executable,
legacy_utf8 = False,
)

# Copy the executable bit of the source
# This is important to ensure that copied binaries are executable.
# Windows may not have chmod in path and doesn't have executable bits anyway.
if get_cpu_value(repository_ctx) != "x64_windows":
repository_ctx.execute([
repository_ctx.which("chmod"),
"--reference",
repository_ctx.path(src),
repository_ctx.path(dest),
])

return dest

def execute_or_fail(repository_ctx, arguments, failure_message = "", *args, **kwargs):
Expand Down