Skip to content

Commit

Permalink
refactor: use rctx.download with file: URL to copy files in npm_trans…
Browse files Browse the repository at this point in the history
…late_lock (aspect-build#821)
  • Loading branch information
gregmagolan authored Jan 24, 2023
1 parent 399a312 commit 01111b2
Showing 1 changed file with 8 additions and 38 deletions.
46 changes: 8 additions & 38 deletions npm/private/npm_translate_lock_state.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -328,53 +328,23 @@ def _write_action_cache(priv, rctx, label_store):
def _copy_input_file(priv, rctx, label_store, key):
if not label_store.has(key):
fail("key not found '{}'".format(key))
if _is_text_file(label_store.path(key)):
_copy_text_file(priv, rctx, label_store, key)
else:
_copy_binary_file(priv, rctx, label_store, key)

def _is_text_file(p):
# we can assume some files types are text files that are commonly copied
return p.endswith(".yaml") or p.endswith(".json") or p.endswith(".npmrc") or p.endswith(".lock")

def _copy_text_file(priv, rctx, label_store, key):
contents = rctx.read(label_store.path(key))
if _should_update_pnpm_lock(priv):
# NB: rctx.read will convert binary files to text but that is acceptable for
# the purposes of calculating a hash of the file
_set_input_hash(
priv,
label_store.relative_path(key),
utils.hash(contents),
utils.hash(rctx.read(label_store.path(key))),
)
rctx.file(
label_store.repository_path(key),
content = contents,
executable = False,
)

def _copy_binary_file(priv, rctx, label_store, key):
# For the purposes of the hash we can load the file in text mode
contents = rctx.read(label_store.path(key))
if _should_update_pnpm_lock(priv):
_set_input_hash(
priv,
label_store.relative_path(key),
utils.hash(contents),
)

# Create a sibling file to ensure the output directory exists
rctx.file(
label_store.repository_path(key) + "_",
content = "",
executable = False,
# use rctx.download to copy the file instead of rctx.read + rctx.file so that
# binary files are handled correctly
rctx.download(
output = label_store.repository_path(key),
url = "file:" + label_store.path(key),
)

# Copy the file over using cp (xcopy on Windows)
is_windows = repo_utils.is_windows(rctx)
cp_args = ["cp", "-f", label_store.path(key), label_store.repository_path(key)] if not is_windows else ["xcopy", "/Y", label_store.path(key).replace("/", "\\"), label_store.repository_path(key).replace("/", "\\")]
result = rctx.execute(cp_args, quiet = rctx.attr.quiet)
if result.return_code:
fail("copy {} to {} failed:\nSTDOUT:\n{}\nSTDERR:\n{}".format(label_store.path(key), label_store.repository_path(key), result.stdout, result.stderr))

################################################################################
def _load_npmrc(priv, rctx, npmrc_path):
contents = parse_npmrc(rctx.read(npmrc_path))
Expand Down

0 comments on commit 01111b2

Please sign in to comment.