From ac9010e87c5a672f335feb796dbe1270019a5f63 Mon Sep 17 00:00:00 2001 From: Caleb Martinez Date: Sun, 31 Mar 2019 05:37:02 -0400 Subject: [PATCH] Allow adding a custom string to pip's User-Agent via an environment variable (#5550) --- docs/html/user_guide.rst | 2 ++ news/5549.feature | 2 ++ src/pip/_internal/download.py | 4 ++++ tests/unit/test_download.py | 5 +++++ 4 files changed, 13 insertions(+) create mode 100644 news/5549.feature diff --git a/docs/html/user_guide.rst b/docs/html/user_guide.rst index 77974b00cb1..9b7e7ed4a0f 100644 --- a/docs/html/user_guide.rst +++ b/docs/html/user_guide.rst @@ -62,6 +62,8 @@ pip can be configured to connect through a proxy server in various ways: * using ``proxy`` in a :ref:`config-file` * by setting the standard environment-variables ``http_proxy``, ``https_proxy`` and ``no_proxy``. +* using the environment variable ``PIP_USER_AGENT_USER_DATA`` to include + a JSON-encoded string in the user-agent variable used in pip's requests. .. _`Requirements Files`: diff --git a/news/5549.feature b/news/5549.feature new file mode 100644 index 00000000000..895ccf648fc --- /dev/null +++ b/news/5549.feature @@ -0,0 +1,2 @@ +A custom (JSON-encoded) string can now be added to pip's User-Agent +using the ``PIP_USER_AGENT_USER_DATA`` environment variable. diff --git a/src/pip/_internal/download.py b/src/pip/_internal/download.py index dfc558ef403..2683cf08293 100644 --- a/src/pip/_internal/download.py +++ b/src/pip/_internal/download.py @@ -167,6 +167,10 @@ def user_agent(): # value to make it easier to know that the check has been run. data["ci"] = True if looks_like_ci() else None + user_data = os.environ.get("PIP_USER_AGENT_USER_DATA") + if user_data is not None: + data["user_data"] = user_data + return "{data[installer][name]}/{data[installer][version]} {json}".format( data=data, json=json.dumps(data, separators=(",", ":"), sort_keys=True), diff --git a/tests/unit/test_download.py b/tests/unit/test_download.py index 4272d7f8d2f..69354b08934 100644 --- a/tests/unit/test_download.py +++ b/tests/unit/test_download.py @@ -88,6 +88,11 @@ def test_user_agent__ci(monkeypatch, name, expected_like_ci): assert ('"ci":null' in user_agent) == (not expected_like_ci) +def test_user_agent_user_data(monkeypatch): + monkeypatch.setenv("PIP_USER_AGENT_USER_DATA", "some_string") + assert "some_string" in PipSession().headers["User-Agent"] + + class FakeStream(object): def __init__(self, contents):