|
15 | 15 | # You should have received a copy of the GNU Lesser General Public License |
16 | 16 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
17 | 17 |
|
| 18 | +import pathlib |
| 19 | +import traceback |
18 | 20 | import urllib.parse |
19 | | -from typing import Any, Callable, Dict, Optional, Union |
| 21 | +import warnings |
| 22 | +from typing import Any, Callable, Dict, Optional, Type, Union |
20 | 23 |
|
21 | 24 | import requests |
22 | 25 |
|
@@ -90,3 +93,36 @@ def __new__( # type: ignore |
90 | 93 |
|
91 | 94 | def remove_none_from_dict(data: Dict[str, Any]) -> Dict[str, Any]: |
92 | 95 | return {k: v for k, v in data.items() if v is not None} |
| 96 | + |
| 97 | + |
| 98 | +def warn( |
| 99 | + message: str, |
| 100 | + *, |
| 101 | + category: Optional[Type] = None, |
| 102 | + source: Optional[Any] = None, |
| 103 | +) -> None: |
| 104 | + """This `warnings.warn` wrapper function attempts to show the location causing the |
| 105 | + warning in the user code that called the library. |
| 106 | +
|
| 107 | + It does this by walking up the stack trace to find the first frame located outside |
| 108 | + the `gitlab/` directory. This is helpful to users as it shows them their code that |
| 109 | + is causing the warning. |
| 110 | + """ |
| 111 | + # Get `stacklevel` for user code so we indicate where issue is in |
| 112 | + # their code. |
| 113 | + pg_dir = pathlib.Path(__file__).parent.resolve() |
| 114 | + stack = traceback.extract_stack() |
| 115 | + stacklevel = 1 |
| 116 | + warning_from = "" |
| 117 | + for stacklevel, frame in enumerate(reversed(stack), start=1): |
| 118 | + if stacklevel == 2: |
| 119 | + warning_from = f" (python-gitlab: {frame.filename}:{frame.lineno})" |
| 120 | + frame_dir = str(pathlib.Path(frame.filename).parent.resolve()) |
| 121 | + if not frame_dir.startswith(str(pg_dir)): |
| 122 | + break |
| 123 | + warnings.warn( |
| 124 | + message=message + warning_from, |
| 125 | + category=category, |
| 126 | + stacklevel=stacklevel, |
| 127 | + source=source, |
| 128 | + ) |
0 commit comments