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
diff --git a/tools/build_defs/repo/http.bzl b/tools/build_defs/repo/http.bzl
index 152dbe6..565ff97 100644
--- a/tools/build_defs/repo/http.bzl
+++ b/tools/build_defs/repo/http.bzl
@@ -34,6 +34,7 @@
":utils.bzl",
"patch",
"read_netrc",
+ "read_user_netrc",
"update_attrs",
"use_netrc",
"workspace_and_buildfile",
@@ -77,21 +78,9 @@
"""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 7608a5e..578981a 100644
--- a/tools/build_defs/repo/utils.bzl
+++ b/tools/build_defs/repo/utils.bzl
@@ -385,3 +385,25 @@
}
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)