Skip to content

Commit

Permalink
Expose the logic to read user netrc file (bazelbuild#14990)
Browse files Browse the repository at this point in the history
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 bazelbuild#14588.

PiperOrigin-RevId: 423291624
(cherry picked from commit f421474)

Co-authored-by: Zhongpeng Lin <zplin@uber.com>
  • Loading branch information
brentleyjones and linzhp committed Mar 7, 2022
1 parent f15e0c7 commit 87ef5ce
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 15 deletions.
19 changes: 4 additions & 15 deletions tools/build_defs/repo/http.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ load(
":utils.bzl",
"patch",
"read_netrc",
"read_user_netrc",
"update_attrs",
"use_netrc",
"workspace_and_buildfile",
Expand Down Expand Up @@ -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."""
Expand Down
22 changes: 22 additions & 0 deletions tools/build_defs/repo/utils.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 87ef5ce

Please sign in to comment.