From f4214746fcd15f0ef8c4e747ef8e3edca9f112a5 Mon Sep 17 00:00:00 2001 From: Zhongpeng Lin Date: Fri, 21 Jan 2022 04:31:27 -0800 Subject: [PATCH] Expose the logic to read user netrc file Repository rules that download repositories from internal website often need to read users `.netrc` files. This PR exposes the logic for other repository rules to use. Closes #14588. PiperOrigin-RevId: 423291624 --- tools/build_defs/repo/http.bzl | 19 ++++--------------- tools/build_defs/repo/utils.bzl | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/tools/build_defs/repo/http.bzl b/tools/build_defs/repo/http.bzl index 152dbe615ede8d..565ff97cd29f67 100644 --- a/tools/build_defs/repo/http.bzl +++ b/tools/build_defs/repo/http.bzl @@ -34,6 +34,7 @@ load( ":utils.bzl", "patch", "read_netrc", + "read_user_netrc", "update_attrs", "use_netrc", "workspace_and_buildfile", @@ -77,21 +78,9 @@ def _get_auth(ctx, urls): """Given the list of URLs obtain the correct auth dict.""" if ctx.attr.netrc: netrc = read_netrc(ctx, ctx.attr.netrc) - return use_netrc(netrc, urls, ctx.attr.auth_patterns) - - if "HOME" in ctx.os.environ and not ctx.os.name.startswith("windows"): - netrcfile = "%s/.netrc" % (ctx.os.environ["HOME"]) - if ctx.execute(["test", "-f", netrcfile]).return_code == 0: - netrc = read_netrc(ctx, netrcfile) - return use_netrc(netrc, urls, ctx.attr.auth_patterns) - - if "USERPROFILE" in ctx.os.environ and ctx.os.name.startswith("windows"): - netrcfile = "%s/.netrc" % (ctx.os.environ["USERPROFILE"]) - if ctx.path(netrcfile).exists: - netrc = read_netrc(ctx, netrcfile) - return use_netrc(netrc, urls, ctx.attr.auth_patterns) - - return {} + else: + netrc = read_user_netrc(ctx) + return use_netrc(netrc, urls, ctx.attr.auth_patterns) def _http_archive_impl(ctx): """Implementation of the http_archive rule.""" diff --git a/tools/build_defs/repo/utils.bzl b/tools/build_defs/repo/utils.bzl index 7608a5e7ab9b6c..578981a377a6ae 100644 --- a/tools/build_defs/repo/utils.bzl +++ b/tools/build_defs/repo/utils.bzl @@ -385,3 +385,25 @@ def use_netrc(netrc, urls, patterns): } return auth + +def read_user_netrc(ctx): + """Read user's default netrc file. + + Args: + ctx: The repository context of the repository rule calling this utility function. + + Returns: + dict mapping a machine names to a dict with the information provided about them. + """ + if ctx.os.name.startswith("windows"): + home_dir = ctx.os.environ.get("USERPROFILE", "") + else: + home_dir = ctx.os.environ.get("HOME", "") + + if not home_dir: + return {} + + netrcfile = "{}/.netrc".format(home_dir) + if not ctx.path(netrcfile).exists: + return {} + return read_netrc(ctx, netrcfile)