Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api,cli): make user agent configurable #1277

Merged
merged 3 commits into from
Feb 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/api-usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ To connect to a GitLab server, create a ``gitlab.Gitlab`` object:
# anonymous gitlab instance, read-only for public resources
gl = gitlab.Gitlab('http://10.0.0.1')

# Define your own custom user agent for requests
gl = gitlab.Gitlab('http://10.0.0.1', user_agent='my-package/1.0.0')

# make an API request to create the gl.user object. This is mandatory if you
# use the username/password authentication.
gl.auth()
Expand Down
3 changes: 3 additions & 0 deletions docs/cli-usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ parameters. You can override the values in each GitLab server section.
- Integer between 1 and 100
- The number of items to return in listing queries. GitLab limits the
value at 100.
* - ``user_agent``
- ``str``
- A string defining a custom user agent to use when ``gitlab`` makes requests.

You must define the ``url`` in each GitLab server section.

Expand Down
20 changes: 12 additions & 8 deletions gitlab/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,20 @@
import requests.utils

import gitlab.config
from gitlab.__version__ import (
__author__,
__copyright__,
__email__,
__license__,
__title__,
__version__,
)
from gitlab.const import * # noqa
from gitlab.exceptions import * # noqa
from gitlab import utils # noqa
from requests_toolbelt.multipart.encoder import MultipartEncoder


__title__ = "python-gitlab"
__version__ = "2.6.0"
__author__ = "Gauvain Pocentek"
__email__ = "gauvainpocentek@gmail.com"
__license__ = "LGPL3"
__copyright__ = "Copyright 2013-2019 Gauvain Pocentek"

warnings.filterwarnings("default", category=DeprecationWarning, module="^gitlab")

REDIRECT_MSG = (
Expand Down Expand Up @@ -64,6 +65,7 @@ class Gitlab(object):
api_version (str): Gitlab API version to use (support for 4 only)
pagination (str): Can be set to 'keyset' to use keyset pagination
order_by (str): Set order_by globally
user_agent (str): A custom user agent to use for making HTTP requests.
"""

def __init__(
Expand All @@ -81,6 +83,7 @@ def __init__(
per_page=None,
pagination=None,
order_by=None,
user_agent=USER_AGENT,
):

self._api_version = str(api_version)
Expand All @@ -90,7 +93,7 @@ def __init__(
#: Timeout to use for requests to gitlab server
self.timeout = timeout
#: Headers that will be used in request to GitLab
self.headers = {"User-Agent": "%s/%s" % (__title__, __version__)}
self.headers = {"User-Agent": user_agent}

#: Whether SSL certificates should be validated
self.ssl_verify = ssl_verify
Expand Down Expand Up @@ -204,6 +207,7 @@ def from_config(cls, gitlab_id=None, config_files=None):
per_page=config.per_page,
pagination=config.pagination,
order_by=config.order_by,
user_agent=config.user_agent,
)

def auth(self):
Expand Down
6 changes: 6 additions & 0 deletions gitlab/__version__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
__author__ = "Gauvain Pocentek, python-gitlab team"
__copyright__ = "Copyright 2013-2019 Gauvain Pocentek, 2019-2021 python-gitlab team"
__email__ = "gauvainpocentek@gmail.com"
__license__ = "LGPL3"
__title__ = "python-gitlab"
__version__ = "2.6.0"
12 changes: 12 additions & 0 deletions gitlab/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import os
import configparser

from gitlab.const import USER_AGENT


def _env_config():
if "PYTHON_GITLAB_CFG" in os.environ:
Expand Down Expand Up @@ -177,3 +179,13 @@ def __init__(self, gitlab_id=None, config_files=None):
self.order_by = self._config.get(self.gitlab_id, "order_by")
except Exception:
pass

self.user_agent = USER_AGENT
try:
self.user_agent = self._config.get("global", "user_agent")
except Exception:
pass
try:
self.user_agent = self._config.get(self.gitlab_id, "user_agent")
except Exception:
pass
5 changes: 5 additions & 0 deletions gitlab/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from gitlab.__version__ import __title__, __version__


NO_ACCESS = 0
MINIMAL_ACCESS = 5
GUEST_ACCESS = 10
Expand Down Expand Up @@ -51,3 +54,5 @@

# specific project scope
SEARCH_SCOPE_PROJECT_NOTES = "notes"

USER_AGENT = "{}/{}".format(__title__, __version__)
max-wittig marked this conversation as resolved.
Show resolved Hide resolved
33 changes: 32 additions & 1 deletion gitlab/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@
import mock
import io

from gitlab import config
from gitlab import config, USER_AGENT
import pytest


custom_user_agent = "my-package/1.0.0"

valid_config = u"""[global]
default = one
ssl_verify = true
Expand All @@ -51,6 +53,17 @@
oauth_token = STUV
"""

custom_user_agent_config = """[global]
default = one
user_agent = {}

[one]
url = http://one.url
private_token = ABCDEF
""".format(
custom_user_agent
)

no_default_config = u"""[global]
[there]
url = http://there.url
Expand Down Expand Up @@ -178,3 +191,21 @@ def test_valid_data(m_open, path_exists):
assert "STUV" == cp.oauth_token
assert 2 == cp.timeout
assert True == cp.ssl_verify


@mock.patch("os.path.exists")
@mock.patch("builtins.open")
@pytest.mark.parametrize(
"config_string,expected_agent",
[
(valid_config, USER_AGENT),
(custom_user_agent_config, custom_user_agent),
],
)
def test_config_user_agent(m_open, path_exists, config_string, expected_agent):
fd = io.StringIO(config_string)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd

cp = config.GitlabConfigParser()
assert cp.user_agent == expected_agent
15 changes: 14 additions & 1 deletion gitlab/tests/test_gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

import pickle

import pytest
from httmock import HTTMock, response, urlmatch, with_httmock # noqa

from gitlab import Gitlab, GitlabList
from gitlab import Gitlab, GitlabList, USER_AGENT
from gitlab.v4.objects import CurrentUser


Expand Down Expand Up @@ -139,3 +140,15 @@ class MyGitlab(Gitlab):
config_path = default_config
gl = MyGitlab.from_config("one", [config_path])
assert isinstance(gl, MyGitlab)


@pytest.mark.parametrize(
"kwargs,expected_agent",
[
({}, USER_AGENT),
({"user_agent": "my-package/1.0.0"}, "my-package/1.0.0"),
],
)
def test_gitlab_user_agent(kwargs, expected_agent):
gl = Gitlab("http://localhost", **kwargs)
assert gl.headers["User-Agent"] == expected_agent
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


def get_version():
with open("gitlab/__init__.py") as f:
with open("gitlab/__version__.py") as f:
for line in f:
if line.startswith("__version__"):
return eval(line.split("=")[-1])
Expand Down