1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
|
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""
Pylint custom checkers for SDK guidelines: C4717 - C4744
"""
import logging
import astroid
from pylint.checkers import BaseChecker
from pylint.interfaces import IAstroidChecker
logger = logging.getLogger(__name__)
class ClientConstructorTakesCorrectParameters(BaseChecker):
__implements__ = IAstroidChecker
name = "client-constructor"
priority = -1
msgs = {
"C4717": (
"Client constructor is missing a credential parameter. See details:"
" https://azure.github.io/azure-sdk/python_design.html#client-configuration",
"missing-client-constructor-parameter-credential",
"All client types should accept a credential parameter.",
),
"C4718": (
"Client constructor is missing a **kwargs parameter. See details:"
" https://azure.github.io/azure-sdk/python_design.html#client-configuration",
"missing-client-constructor-parameter-kwargs",
"All client types should accept a **kwargs parameter.",
)
}
options = (
(
"ignore-missing-client-constructor-parameter-credential",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client constructors without a credential parameter",
},
),
(
"ignore-missing-client-constructor-parameter-kwargs",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client constructors without a **kwargs parameter",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientConstructorTakesCorrectParameters, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits the constructor within a client class and checks that it has
credential and kwargs parameters.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.name == "__init__" and node.parent.name.endswith("Client") and \
node.parent.name not in self.ignore_clients:
arg_names = [argument.name for argument in node.args.args]
if "credential" not in arg_names:
self.add_message(
msgid="missing-client-constructor-parameter-credential", node=node, confidence=None
)
if not node.args.kwarg:
self.add_message(
msgid="missing-client-constructor-parameter-kwargs", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if constructor has correct parameters.")
pass
class ClientHasKwargsInPoliciesForCreateConfigurationMethod(BaseChecker):
__implements__ = IAstroidChecker
name = "configuration-policies-kwargs"
priority = -1
msgs = {
"C4719": (
"A policy in the create_configuration() function is missing a **kwargs argument. See details:"
" https://azure.github.io/azure-sdk/python_design.html#client-configuration",
"config-missing-kwargs-in-policy",
"All policies should take a **kwargs parameter.",
)
}
options = (
(
"ignore-config-missing-kwargs-in-policy",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow clients instantiate a policy without a kwargs parameter.",
},
),
)
def __init__(self, linter=None):
super(ClientHasKwargsInPoliciesForCreateConfigurationMethod, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits the any method called `create_configuration` or `create_config` and checks
that every policy in the method contains a kwargs parameter.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.name == "create_configuration" or node.name == "create_config":
node.decorators = None
for idx in range(len(node.body)):
# Gets each line of the method as a string
line = list(node.get_children())[idx].as_string()
if line.find("Policy") != -1:
if line.find("**kwargs") == -1:
self.add_message(
msgid="config-missing-kwargs-in-policy",
node=list(node.get_children())[idx],
confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if kwargs parameter in policies.")
pass
class ClientHasApprovedMethodNamePrefix(BaseChecker):
__implements__ = IAstroidChecker
name = "client-approved-method-name-prefix"
priority = -1
msgs = {
"C4720": (
"Client is not using an approved method name prefix. See details:"
" https://azure.github.io/azure-sdk/python_design.html#service-operations",
"unapproved-client-method-name-prefix",
"All clients should use the preferred verbs for method names.",
)
}
options = (
(
"ignore-unapproved-client-method-name-prefix",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow clients to not use preferred method name prefixes",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientHasApprovedMethodNamePrefix, self).__init__(linter)
def visit_classdef(self, node):
"""Visits every class in file and checks if it is a client. If it is a client, checks
that approved method name prefixes are present.
:param node: class node
:type node: ast.ClassDef
:return: None
"""
try:
if node.name.endswith("Client") and node.name not in self.ignore_clients:
client_methods = [child for child in node.get_children() if child.is_function]
approved_prefixes = ["get", "list", "create", "upsert", "set", "update", "replace", "append", "add",
"delete", "remove", "begin"]
for idx, method in enumerate(client_methods):
if method.name.startswith("__") or "_exists" in method.name or method.name.startswith("_") \
or method.name.startswith("from"):
continue
prefix = method.name.split("_")[0]
if prefix.lower() not in approved_prefixes:
self.add_message(
msgid="unapproved-client-method-name-prefix",
node=client_methods[idx],
confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client has approved method name prefix.")
pass
class ClientMethodsUseKwargsWithMultipleParameters(BaseChecker):
__implements__ = IAstroidChecker
name = "client-method-multiple-parameters"
priority = -1
msgs = {
"C4721": (
"Client has too many positional arguments. Use keyword-only arguments."
" See details: https://azure.github.io/azure-sdk/python_implementation.html#method-signatures",
"client-method-has-more-than-5-positional-arguments",
"Client method should use keyword-only arguments for some parameters.",
)
}
options = (
(
"ignore-client-method-has-more-than-5-positional-arguments",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client method to have more than 5 positional arguments",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientMethodsUseKwargsWithMultipleParameters, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that it doesn't have more than 5
positional arguments.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.is_method() and node.parent.name not in self.ignore_clients:
# Only bother checking method signatures with > 6 parameters (don't include self/cls/etc)
if len(node.args.args) > 6:
positional_args = len(node.args.args) - len(node.args.defaults)
if positional_args > 6:
self.add_message(
msgid="client-method-has-more-than-5-positional-arguments", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if kwargs is used for multiple parameters.")
pass
visit_asyncfunctiondef = visit_functiondef
class ClientMethodsHaveTypeAnnotations(BaseChecker):
__implements__ = IAstroidChecker
name = "client-method-type-annotations"
priority = -1
msgs = {
"C4722": (
"Client method is missing type annotations/comments, return type annotations/comments, or "
"mixing type annotations and comments. See details: "
" https://azure.github.io/azure-sdk/python_implementation.html#types-or-not",
"client-method-missing-type-annotations",
"Client method should use type annotations.",
)
}
options = (
(
"ignore-client-method-missing-type-annotations",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client method without type annotations",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientMethodsHaveTypeAnnotations, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that all type comments/annotations
and type returns are present.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.is_method() and node.parent.name not in self.ignore_clients:
if not node.name.startswith("_") or node.name == "__init__":
# Checks that method has python 2/3 type comments or annotations as shown here:
# https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
# check for type comments
if node.type_comment_args is None or node.type_comment_returns is None:
# type annotations default to a list of None when not present,
# so need extra logic here to check for any hints that may be present
type_annotations = [type_hint for type_hint in node.args.annotations if type_hint is not None]
# check for type annotations
# node.args.args is a list of ast.AssignName arguments
# node.returns is the type annotation return
# Note that if the method returns nothing it will be of type ast.Const.NoneType
if (type_annotations == [] and len(node.args.args) > 1) or node.returns is None:
self.add_message(
msgid="client-method-missing-type-annotations", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client methods missing type annotations.")
pass
visit_asyncfunctiondef = visit_functiondef
class ClientMethodsHaveTracingDecorators(BaseChecker):
__implements__ = IAstroidChecker
name = "client-method-has-tracing-decorator"
priority = -1
msgs = {
"C4723": (
"Client method is missing the distributed tracing decorator - `distributed_trace`. See details:"
" https://azure.github.io/azure-sdk/python_implementation.html#distributed-tracing",
"client-method-missing-tracing-decorator",
"Client method should support distributed tracing.",
),
"C4724": (
"Client async method is missing the distributed tracing decorator - `distributed_trace_async`. "
" See details: https://azure.github.io/azure-sdk/python_implementation.html#distributed-tracing",
"client-method-missing-tracing-decorator-async",
"Client method should support distributed tracing.",
),
}
options = (
(
"ignore-client-method-missing-tracing-decorator",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client method without tracing decorator.",
},
),
(
"ignore-client-method-missing-tracing-decorator-async",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client method without tracing decorator.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientMethodsHaveTracingDecorators, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that a distributed tracing decorator is present.
Ignores private methods, from_connection_string, and methods that retrieve child clients.
node.decoratornames() returns a set of the method's decorator names.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.is_method() and not node.name.startswith("_") and \
node.parent.name not in self.ignore_clients:
if node.args.kwarg and "azure.core.tracing.decorator.distributed_trace" not in node.decoratornames() \
and "builtins.classmethod" not in node.decoratornames():
self.add_message(
msgid="client-method-missing-tracing-decorator", node=node, confidence=None
)
except AttributeError:
pass
def visit_asyncfunctiondef(self, node):
"""Visits every method in the client and checks that a distributed tracing decorator is present.
Ignores private methods, from_connection_string, and methods that retrieve child clients.
node.decoratornames() returns a set of the method's decorator names.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.is_method() and not node.name.startswith("_") and \
node.parent.name not in self.ignore_clients:
if node.args.kwarg and "azure.core.tracing.decorator_async.distributed_trace_async" not in \
node.decoratornames() and "builtins.classmethod" not in node.decoratornames():
self.add_message(
msgid="client-method-missing-tracing-decorator-async", node=node, confidence=None
)
except AttributeError:
pass
class ClientsDoNotUseStaticMethods(BaseChecker):
__implements__ = IAstroidChecker
name = "client-does-not-use-static-methods"
priority = -1
msgs = {
"C4725": (
"Client should not use static methods (staticmethod). See details:"
" https://azure.github.io/azure-sdk/python_implementation.html#method-signatures",
"client-method-should-not-use-static-method",
"Client method should not use staticmethod.",
),
}
options = (
(
"ignore-client-method-should-not-use-static-method",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client method to use staticmethod.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientsDoNotUseStaticMethods, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that it does not use staticmethod.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.is_method() and node.parent.name not in self.ignore_clients:
# ignores private methods or methods that don't have any decorators
if not node.name.startswith("_") and node.decorators is not None:
if "builtins.staticmethod" in node.decoratornames():
self.add_message(
msgid="client-method-should-not-use-static-method", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client methods do not use staticmethods.")
pass
visit_asyncfunctiondef = visit_functiondef
class FileHasCopyrightHeader(BaseChecker):
__implements__ = IAstroidChecker
name = "file-has-copyright-header"
priority = -1
msgs = {
"C4726": (
"File is missing a copyright header. See details:"
" https://azure.github.io/azure-sdk/policies_opensource.html#",
"file-needs-copyright-header",
"Every source file should have a copyright header.",
),
}
options = (
(
"ignore-file-needs-copyright-header",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow file without a copyright header.",
},
),
)
def __init__(self, linter=None):
super(FileHasCopyrightHeader, self).__init__(linter)
def visit_module(self, node):
"""Visits every file and checks that a copyright header is present.
:param node: module node
:type node: ast.Module
:return: None
"""
try:
if not node.package: # don't throw an error on an __init__.py file
header = node.stream().read(200).lower()
if header.find(b'copyright') == -1:
self.add_message(
msgid="file-needs-copyright-header", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if file is missing a copyright header.")
pass
class ClientUsesCorrectNamingConventions(BaseChecker):
__implements__ = IAstroidChecker
name = "client-naming-conventions"
priority = -1
msgs = {
"C4727": (
"Client is using an incorrect naming convention. See details:"
" https://azure.github.io/azure-sdk/python_implementation.html#naming-conventions",
"client-incorrect-naming-convention",
"Client method should use correct naming conventions.",
)
}
options = (
(
"ignore-client-incorrect-naming-convention",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client to use incorrect naming conventions.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientUsesCorrectNamingConventions, self).__init__(linter)
def visit_classdef(self, node):
"""Visits every class in file and checks if it is a client.
Checks that correct naming convention is used for the client.
Also checks that any class constants use uppercase.
:param node: class node
:type node: ast.ClassDef
:return: None
"""
# check for correct capitalization for "Client" and whatever the first letter of the prefix is
if "_" in node.name or node.name.endswith("client") or node.name[0] != node.name[0].upper():
if not node.name.startswith("_") and node.name not in self.ignore_clients:
self.add_message(
msgid="client-incorrect-naming-convention", node=node, confidence=None
)
# check for correct naming convention in any class constants
if node.name.endswith("Client"):
for idx in range(len(node.body)):
try:
const_name = node.body[idx].targets[0].name
if const_name != const_name.upper():
self.add_message(
msgid="client-incorrect-naming-convention", node=node.body[idx], confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client uses correct naming conventions.")
pass
# check that methods in client class do not use camelcase
try:
for func in node.body:
if func.name != func.name.lower() and not func.name.startswith("_"):
self.add_message(
msgid="client-incorrect-naming-convention", node=func, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client uses correct naming conventions.")
pass
class ClientMethodsHaveKwargsParameter(BaseChecker):
__implements__ = IAstroidChecker
name = "client-methods-have-kwargs"
priority = -1
msgs = {
"C4728": (
"Client method is missing a **kwargs parameter. See details:"
" https://azure.github.io/azure-sdk/python_design.html#constructors-and-factory-methods",
"client-method-missing-kwargs",
"All client methods should accept a kwargs parameter.",
),
}
options = (
(
"ignore-client-method-missing-kwargs",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client method without a kwargs parameter",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientMethodsHaveKwargsParameter, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that it has a kwargs parameter.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.is_method() and node.parent.name not in self.ignore_clients:
# avoid false positive with @property
if node.decorators is not None:
if "builtins.property" in node.decoratornames():
return
if not node.name.startswith("_") and \
("azure.core.tracing.decorator.distributed_trace" in node.decoratornames() or
"azure.core.tracing.decorator_async.distributed_trace_async" in node.decoratornames()):
if not node.args.kwarg:
self.add_message(
msgid="client-method-missing-kwargs", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client uses kwargs parameter in method.")
pass
visit_asyncfunctiondef = visit_functiondef
class ClientMethodNamesDoNotUseDoubleUnderscorePrefix(BaseChecker):
__implements__ = IAstroidChecker
name = "client-methods-no-double-underscore"
priority = -1
msgs = {
"C4729": (
"Client method name should not use a double underscore prefix. See details:"
" https://azure.github.io/azure-sdk/python_implementation.html#public-vs-private",
"client-method-name-no-double-underscore",
"Client method names should not use a leading double underscore prefix.",
),
}
options = (
(
"ignore-client-method-name-no-double-underscore",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client method to have double underscore prefix.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
acceptable_names = ["__init__", "__enter__", "__exit__", "__aenter__", "__aexit__", "__repr__"]
def __init__(self, linter=None):
super(ClientMethodNamesDoNotUseDoubleUnderscorePrefix, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that no name begins with a double underscore.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.is_method() and node.parent.name not in self.ignore_clients:
if node.name.startswith("__") and node.name not in self.acceptable_names:
self.add_message(
msgid="client-method-name-no-double-underscore", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client method name does not use double underscore prefix.")
pass
visit_asyncfunctiondef = visit_functiondef
class ClientDocstringUsesLiteralIncludeForCodeExample(BaseChecker):
__implements__ = IAstroidChecker
name = "client-docstring-literal-include"
priority = -1
msgs = {
"C4730": (
"Client docstring should use a literal include directive for the code example. See details:"
" https://azure.github.io/azure-sdk/python_documentation.html#code-snippets",
"client-docstring-use-literal-include",
"Client/methods should use literal include directives for code examples.",
),
}
options = (
(
"ignore-client-docstring-use-literal-include",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client to use code block.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientDocstringUsesLiteralIncludeForCodeExample, self).__init__(linter)
def visit_classdef(self, node):
"""Visits every class in file and checks if it is a client.
Also checks that the class constructor uses literalinclude over a code-block for the code example.
:param node: class node
:type node: ast.ClassDef
:return: None
"""
try:
if node.name.endswith("Client") and node.name not in self.ignore_clients:
if node.doc.find("code-block") != -1:
self.add_message(
msgid="client-docstring-use-literal-include", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client uses literalinclude over code-block.")
pass
def visit_functiondef(self, node):
"""Visits every method in the client class and checks that it uses literalinclude
over a code-block for the code example.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.parent.name not in self.ignore_clients and node.is_method():
if node.doc.find("code-block") != -1:
self.add_message(
msgid="client-docstring-use-literal-include", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client uses literalinclude over code-block.")
pass
visit_asyncfunctiondef = visit_functiondef
class AsyncClientCorrectNaming(BaseChecker):
__implements__ = IAstroidChecker
name = "async-client-correct-naming"
priority = -1
msgs = {
"C4731": (
"Async client should not include `Async` in the client name. See details:"
" https://azure.github.io/azure-sdk/python_design.html#async-support",
"async-client-bad-name",
"Async clients should not have async in the name.",
),
}
options = (
(
"ignore-async-client-bad-name",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow async client to include async in its name.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(AsyncClientCorrectNaming, self).__init__(linter)
def visit_classdef(self, node):
"""Visits every class in file and checks that an async client does not use
async in its name.
:param node: class node
:type node: ast.ClassDef
:return: None
"""
try:
# avoid false positive when async name is used with a base class.
if node.name.endswith("Client") and "async" in node.name.lower() and "base" not in node.name.lower():
if not node.name.startswith("_") and node.name not in self.ignore_clients:
self.add_message(
msgid="async-client-bad-name", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if async client uses correct naming.")
pass
class SpecifyParameterNamesInCall(BaseChecker):
__implements__ = IAstroidChecker
name = "specify-parameter-names"
priority = -1
msgs = {
"C4732": (
"Specify the parameter names when calling methods with more than 2 required positional parameters."
" See details: https://azure.github.io/azure-sdk/python_implementation.html#python-codestyle-positional-params",
"specify-parameter-names-in-call",
"You should specify the parameter names when the method has more than two positional arguments.",
)
}
options = (
(
"ignore-specify-parameter-names-in-call",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Call the method without specifying parameter names.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(SpecifyParameterNamesInCall, self).__init__(linter)
def visit_call(self, node):
"""Visits every call in the client and checks that it specifies the parameter name in
the call if there are more than 2 require positional parameters.
:param node: call node
:type node: ast.Call
:return: None
"""
try:
klass = node.parent.parent.parent
function = node.parent.parent
if klass.name.endswith("Client") and klass.name not in self.ignore_clients and function.is_method():
# node.args represent positional arguments
if len(node.args) > 2 and node.func.attrname != "format":
self.add_message(
msgid="specify-parameter-names-in-call", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client methods specify parameters name in call.")
pass
class ClientListMethodsUseCorePaging(BaseChecker):
__implements__ = IAstroidChecker
name = "client-list-methods-use-paging"
priority = -1
msgs = {
"C4733": (
"Operations that return collections should return a value that implements the Paging protocol. See details:"
" https://azure.github.io/azure-sdk/python_design.html#response-formats",
"client-list-methods-use-paging",
"Client methods that return collections should use the Paging protocol.",
),
}
options = (
(
"ignore-client-list-methods-use-paging",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow collections method to not use paging protocol.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientListMethodsUseCorePaging, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that any list_ methods return
an ItemPaged or AsyncItemPaged value.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.parent.name not in self.ignore_clients and node.is_method():
if node.name.startswith("list"):
try:
# infer_call_result gives the method return value as a string
returns = next(node.infer_call_result()).as_string()
if returns.find("ItemPaged") == -1 and returns.find("AsyncItemPaged") == -1:
self.add_message(
msgid="client-list-methods-use-paging", node=node, confidence=None
)
except (astroid.exceptions.InferenceError, AttributeError): # astroid can't always infer the return
logger.debug("Pylint custom checker failed to check if client list method uses core paging.")
pass
except AttributeError:
logger.debug("Pylint custom checker failed to check if client list method uses core paging.")
pass
class ClientLROMethodsUseCorePolling(BaseChecker):
__implements__ = IAstroidChecker
name = "client-lro-methods-use-polling"
priority = -1
msgs = {
"C4734": (
"Long running operations should return a value that implements the Poller protocol. See details:"
" https://azure.github.io/azure-sdk/python_design.html#response-formats",
"client-lro-methods-use-polling",
"Long running operations should use the polling protocol.",
),
}
options = (
(
"ignore-client-lro-methods-use-polling",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow LRO method to not use polling protocol.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientLROMethodsUseCorePolling, self).__init__(linter)
def visit_functiondef(self, node):
"""Visits every method in the client and checks that any begin_ methods return
an LROPoller value.
:param node: function node
:type node: ast.FunctionDef
:return: None
"""
try:
if node.parent.name.endswith("Client") and node.parent.name not in self.ignore_clients and node.is_method():
if node.name.startswith("begin"):
try:
# infer_call_result gives the method return value as a string
returns = next(node.infer_call_result()).as_string()
if returns.find("LROPoller") == -1:
self.add_message(
msgid="client-lro-methods-use-polling", node=node, confidence=None
)
except (astroid.exceptions.InferenceError, AttributeError): # astroid can't always infer the return
logger.debug("Pylint custom checker failed to check if client begin method uses core polling.")
pass
except AttributeError:
logger.debug("Pylint custom checker failed to check if client begin method uses core polling.")
pass
class ClientLROMethodsUseCorrectNaming(BaseChecker):
__implements__ = IAstroidChecker
name = "client-lro-methods-use-correct-naming"
priority = -1
msgs = {
"C4735": (
"Methods that return an LROPoller should be prefixed with `begin_`. See details:"
" https://azure.github.io/azure-sdk/python_design.html#service-operations",
"lro-methods-use-correct-naming",
"Methods that return an LROPoller should be prefixed with `begin_`.",
),
}
options = (
(
"ignore-client-lro-methods-use-correct-naming",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow LRO method to use a different name.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientLROMethodsUseCorrectNaming, self).__init__(linter)
self.is_client = []
def visit_classdef(self, node):
"""Visits every class in file and checks if it is a client.
:param node: class node
:type node: ast.ClassDef
:return: None
"""
if node.name.endswith("Client") and node.name not in self.ignore_clients:
self.is_client.append(True)
else:
self.is_client.append(False)
def visit_return(self, node):
if self.is_client and self.is_client[-1]:
try:
# check for a return value of LROPoller in client class
if node.value.func.name == "LROPoller":
# get the method in which LROPoller is returned
method = node.value.func.scope()
if not method.name.startswith("begin") and not method.name.startswith("_"):
self.add_message(
msgid="lro-methods-use-correct-naming", node=method, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client method with polling uses correct naming.")
pass
class ClientConstructorDoesNotHaveConnectionStringParam(BaseChecker):
__implements__ = IAstroidChecker
name = "client-conn-str-not-in-constructor"
priority = -1
msgs = {
"C4736": (
"The constructor must not take a connection string. See details: "
"https://azure.github.io/azure-sdk/python_design.html#python-client-connection-string",
"connection-string-should-not-be-constructor-param",
"Client should have a method to create the client with a connection string.",
),
}
options = (
(
"ignore-connection-string-should-not-be-constructor-param",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow client to use connection string param in constructor.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(ClientConstructorDoesNotHaveConnectionStringParam, self).__init__(linter)
def visit_classdef(self, node):
"""Visits every class in file and checks if it is a client.
If it is a client, it checks that a connection string parameter is not used in the constructor.
:param node: class node
:type node: ast.ClassDef
:return: None
"""
try:
if node.name.endswith("Client") and node.name not in self.ignore_clients:
for func in node.body:
if func.name == "__init__":
for argument in func.args.args:
if argument.name == "connection_string" or argument.name == "conn_str":
self.add_message(
msgid="connection-string-should-not-be-constructor-param", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client uses connection string param in constructor.")
pass
class PackageNameDoesNotUseUnderscoreOrPeriod(BaseChecker):
__implements__ = IAstroidChecker
name = "package-name-incorrect"
priority = -1
msgs = {
"C4737": (
"Package name should not use an underscore or period. Replace with dash (-). See details: "
"https://azure.github.io/azure-sdk/python_design.html#packaging",
"package-name-incorrect",
"Package name should use dashes instead of underscore or period.",
),
}
options = (
(
"ignore-package-name-incorrect",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow package name to have a different naming convention.",
},
),
)
def __init__(self, linter=None):
super(PackageNameDoesNotUseUnderscoreOrPeriod, self).__init__(linter)
def visit_module(self, node):
"""Visits setup.py and checks that its package name follows correct naming convention.
:param node: module node
:type node: ast.Module
:return: None
"""
try:
if node.file.endswith("setup.py"):
for nod in node.body:
if isinstance(nod, astroid.Assign):
if nod.targets[0].name == "PACKAGE_NAME":
package = nod.value
if package.value.find(".") != -1 or package.value.find("_") != -1:
self.add_message(
msgid="package-name-incorrect", node=node, confidence=None
)
except Exception:
logger.debug("Pylint custom checker failed to check if package name is correct.")
pass
class ServiceClientUsesNameWithClientSuffix(BaseChecker):
__implements__ = IAstroidChecker
name = "client-name-incorrect"
priority = -1
msgs = {
"C4738": (
"Service client types should use a `Client` suffix. See details: "
"https://azure.github.io/azure-sdk/python_design.html#service-client",
"client-suffix-needed",
"Client should use the correct suffix.",
),
}
options = (
(
"ignore-client-suffix-needed",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow the client to have a different suffix.",
},
),
)
def __init__(self, linter=None):
super(ServiceClientUsesNameWithClientSuffix, self).__init__(linter)
def visit_module(self, node):
"""Visits a file that has "client" in the file name and checks that the service client
uses a `Client` suffix.
:param node: module node
:type node: ast.Module
:return: None
"""
try:
# ignore base clients
if node.file.endswith("base_client.py") or node.file.endswith("base_client_async.py"):
return
if node.file.endswith("client.py") or node.file.endswith("client_async.py"):
has_client_suffix = False
for idx in range(len(node.body)):
if isinstance(node.body[idx], astroid.ClassDef):
if node.body[idx].name.endswith("Client"):
has_client_suffix = True
if has_client_suffix is False:
self.add_message(
msgid="client-suffix-needed", node=node, confidence=None
)
except Exception:
logger.debug("Pylint custom checker failed to check if service client has a client suffix.")
pass
class CheckDocstringParameters(BaseChecker):
__implements__ = IAstroidChecker
name = "check-docstrings"
priority = -1
msgs = {
"C4739": (
'Params missing in docstring: "%s". See details: '
'https://azure.github.io/azure-sdk/python_documentation.html#docstrings',
"docstring-missing-param",
"Docstring missing for param.",
),
"C4740": (
'Param types missing in docstring: "%s". See details: '
'https://azure.github.io/azure-sdk/python_documentation.html#docstrings',
"docstring-missing-type",
"Docstring missing for param type.",
),
"C4741": (
"A return doc is missing in the docstring. See details: "
"https://azure.github.io/azure-sdk/python_documentation.html#docstrings",
"docstring-missing-return",
"Docstring missing for return doc.",
),
"C4742": (
"A return type is missing in the docstring. See details: "
"https://azure.github.io/azure-sdk/python_documentation.html#docstrings",
"docstring-missing-rtype",
"Docstring missing for return type.",
),
"C4743": (
'"%s" not found as a parameter. Use :keyword type myarg: if a keyword argument. See details: '
'https://azure.github.io/azure-sdk/python_documentation.html#docstrings',
"docstring-should-be-keyword",
"Docstring should use keywords.",
),
}
options = (
(
"ignore-docstring-missing-param",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow a docstring param mismatch.",
},
),
(
"ignore-docstring-missing-type",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow a docstring param type mismatch.",
},
),
(
"ignore-docstring-missing-return",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow a docstring return doc mismatch",
},
),
(
"ignore-docstring-missing-rtype",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow a docstring rtype mismatch",
},
),
(
"ignore-docstring-should-be-keyword",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow a docstring to not use keyword for documentation.",
},
),
)
def __init__(self, linter=None):
super(CheckDocstringParameters, self).__init__(linter)
def check_parameters(self, node):
"""Parse the docstring for any params and types
and compares it to the function's parameters.
Throws a pylint error if...
1. Missing param in docstring.
2. Missing a param type in the docstring.
3. Missing a return doc in the docstring when a function returns something.
4. Missing an rtype in the docstring when a function returns something.
5. Extra params in docstring that aren't function parameters. Change to keywords.
:param node: ast.ClassDef or ast.FunctionDef
:return: None
"""
arg_names = []
# specific case for constructor where docstring found in class def
if isinstance(node, astroid.ClassDef):
for constructor in node.body:
if isinstance(constructor, astroid.FunctionDef) and constructor.name == "__init__":
arg_names = [arg.name for arg in constructor.args.args]
break
if isinstance(node, astroid.FunctionDef):
arg_names = [arg.name for arg in node.args.args]
try:
# not every method will have a docstring so don't crash here, just return
docstring = node.doc.split(":")
except AttributeError:
return
docparams = {}
for idx, line in enumerate(docstring):
# this param has its type on a separate line
if line.startswith("param") and line.count(" ") == 1:
param = line.split("param ")[1]
docparams[param] = None
# this param has its type on the same line
if line.startswith("param") and line.count(" ") == 2:
_, param_type, param = line.split(" ")
docparams[param] = param_type
if line.startswith("type"):
param = line.split("type ")[1]
if param in docparams:
docparams[param] = docstring[idx+1]
# check that all params are documented
missing_params = []
for param in arg_names:
if param == "self" or param == "cls":
continue
if param not in docparams:
missing_params.append(param)
if missing_params:
self.add_message(
msgid="docstring-missing-param", args=(", ".join(missing_params)), node=node, confidence=None
)
# check if we have a type for each param and check if documented params that should be keywords
missing_types = []
should_be_keywords = []
for param in docparams:
if docparams[param] is None:
missing_types.append(param)
if param not in arg_names:
should_be_keywords.append(param)
if missing_types:
self.add_message(
msgid="docstring-missing-type", args=(", ".join(missing_types)), node=node, confidence=None
)
if should_be_keywords:
self.add_message(
msgid="docstring-should-be-keyword",
args=(", ".join(should_be_keywords)),
node=node,
confidence=None
)
def check_return(self, node):
"""Checks if function returns anything.
If return found, checks that the docstring contains a return doc and rtype.
:param node: ast.FunctionDef
:return: None
"""
try:
returns = next(node.infer_call_result()).as_string()
if returns == "None":
return
except (astroid.exceptions.InferenceError, AttributeError):
# this function doesn't return anything, just return
return
try:
# not every method will have a docstring so don't crash here, just return
docstring = node.doc.split(":")
except AttributeError:
return
has_return, has_rtype = False, False
for line in docstring:
if line.startswith("return"):
has_return = True
if line.startswith("rtype"):
has_rtype = True
if has_return is False:
self.add_message(
msgid="docstring-missing-return", node=node, confidence=None
)
if has_rtype is False:
self.add_message(
msgid="docstring-missing-rtype", node=node, confidence=None
)
def visit_classdef(self, node):
"""Visits every class in the file and finds the constructor.
Makes a call to compare class docstring with constructor params.
:param node: ast.ClassDef
:return: None
"""
try:
for func in node.body:
if isinstance(func, astroid.FunctionDef) and func.name == "__init__":
self.check_parameters(node)
except Exception:
logger.debug("Pylint custom checker failed to check docstrings.")
pass
def visit_functiondef(self, node):
"""Visits every function in the file and makes calls
to check docstring parameters and return statements.
:param node: ast.FunctionDef
:return: None
"""
try:
if node.name == "__init__":
return
self.check_parameters(node)
self.check_return(node)
except Exception:
logger.debug("Pylint custom checker failed to check docstrings.")
pass
# this line makes it work for async functions
visit_asyncfunctiondef = visit_functiondef
class CheckForPolicyUse(BaseChecker):
__implements__ = IAstroidChecker
name = "check-for-policies"
priority = -1
msgs = {
"C4739": (
"You should include a UserAgentPolicy in your HTTP pipeline. See details: "
"https://azure.github.io/azure-sdk/python_implementation.html#network-operations",
"missing-user-agent-policy",
"You should include a UserAgentPolicy in the HTTP Pipeline.",
),
"C4740": (
"You should include a LoggingPolicy in your HTTP pipeline. See details: "
"https://azure.github.io/azure-sdk/python_implementation.html#network-operations",
"missing-logging-policy",
"You should include a LoggingPolicy in the HTTP Pipeline.",
),
"C4741": (
"You should include a RetryPolicy in your HTTP pipeline. See details: "
"https://azure.github.io/azure-sdk/python_implementation.html#network-operations",
"missing-retry-policy",
"You should include a RetryPolicy in the HTTP Pipeline.",
),
"C4742": (
"You should include a DistributedTracingPolicy in your HTTP pipeline. See details: "
"https://azure.github.io/azure-sdk/python_implementation.html#network-operations",
"missing-distributed-tracing-policy",
"You should include a DistributedTracingPolicy in the HTTP Pipeline.",
),
}
options = (
(
"ignore-missing-user-agent-policy",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow the client to not have a UserAgentPolicy",
},
),
(
"ignore-missing-logging-policy",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow the client to not have a LoggingPolicy",
},
),
(
"ignore-missing-retry-policy",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow the client to not have a RetryPolicy",
},
),
(
"ignore-missing-distributed-tracing-policy",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow the client to not have a DistributedTracingPolicy",
},
),
)
def __init__(self, linter=None):
super(CheckForPolicyUse, self).__init__(linter)
self.node_to_use = None
self.has_policies = set()
self.ran_at_package_level = False
self.disable_logging_error = False
self.disable_user_agent_error = False
self.disable_tracing_error = False
self.disable_retry_error = False
def visit_function(self, node, policy):
"""Visits the function and searches line by line for the policy being used.
Also searches for if the policy came from the azure.core.configuration object.
:param node: ast.FunctionDef
:param policy: The policy imported in the file.
:return: None
"""
for func in node.body:
if isinstance(func, astroid.FunctionDef):
for idx, item in enumerate(func.body):
try:
line = list(node.get_children())[idx].as_string()
if line.find(policy) != -1:
self.has_policies.add(policy)
if line.find("config.logging_policy") != -1:
self.has_policies.add("NetworkTraceLoggingPolicy")
if line.find("config.retry_policy") != -1:
self.has_policies.add("RetryPolicy")
if line.find("config.user_agent_policy") != -1:
self.has_policies.add("UserAgentPolicy")
except IndexError:
pass
def visit_class(self, klass, policy):
"""Visits any classes in the file and then makes a call
to search its methods for the policy being used.
:param klass: A class within the file
:param policy: The policy imported in the file.
:return: None
"""
for idx, node in enumerate(klass):
if isinstance(node, astroid.ClassDef):
self.visit_function(node, policy)
def visit_module(self, node):
"""Visits every file in the package and searches for policies as base classes
or custom policies. If a core policy is imported in a file in calls helper
methods to check that the policy was used in the code.
This pylint checker is different from the others as it collects information across
many files and then reports any errors. Due to this difference, disable commands
must be searched for manually.
:param node: ast.Module
:return: None
"""
# only throw the error if pylint was run at package level since it needs to check all the files
# infer run location based on the location of the init file highest in dir hierarchy
if node.package: # the init file
count = node.file.split("azure-sdk-for-python")[1].count("-")
if node.file.split("azure-sdk-for-python")[1].count("\\") <= (5 + count) and \
node.file.split("azure-sdk-for-python")[1].count("/") <= (5 + count):
self.ran_at_package_level = True
# not really a good place to throw the pylint error, so we'll do it on the init file.
# By running this checker on all the files first and then reporting errors, pylint disables need to be
# done manually for some reason
if node.file.endswith("__init__.py") and self.node_to_use is None:
header = node.stream().read(200).lower()
if header.find(b'disable') != -1:
if header.find(b'missing-logging-policy') != -1:
self.disable_logging_error = True
if header.find(b'missing-user-agent-policy') != -1:
self.disable_user_agent_error = True
if header.find(b'missing-distributed-tracing-policy') != -1:
self.disable_tracing_error = True
if header.find(b'missing-retry-policy') != -1:
self.disable_retry_error = True
self.node_to_use = node
for idx in range(len(node.body)):
# Check if the core policy is the base class for some custom policy, or a custom policy is being used
# and we try our best to find it based on common naming conventions.
if isinstance(node.body[idx], astroid.ClassDef):
if "NetworkTraceLoggingPolicy" in node.body[idx].basenames:
self.has_policies.add("NetworkTraceLoggingPolicy")
if node.body[idx].name.find("LoggingPolicy") != -1:
self.has_policies.add("NetworkTraceLoggingPolicy")
if "RetryPolicy" in node.body[idx].basenames or "AsyncRetryPolicy" in node.body[idx].basenames:
self.has_policies.add("RetryPolicy")
if node.body[idx].name.find("RetryPolicy") != -1:
self.has_policies.add("RetryPolicy")
if "UserAgentPolicy" in node.body[idx].basenames:
self.has_policies.add("UserAgentPolicy")
if node.body[idx].name.find("UserAgentPolicy") != -1:
self.has_policies.add("UserAgentPolicy")
if "DistributedTracingPolicy" in node.body[idx].basenames:
self.has_policies.add("DistributedTracingPolicy")
if node.body[idx].name.find("TracingPolicy") != -1:
self.has_policies.add("DistributedTracingPolicy")
# policy is imported in this file, let's check that it gets used in the code
if isinstance(node.body[idx], astroid.ImportFrom):
for imp, pol in enumerate(node.body[idx].names):
if node.body[idx].names[imp][0].endswith("Policy") and \
node.body[idx].names[imp][0] not in self.has_policies:
self.visit_class(node.body, node.body[idx].names[imp][0])
def close(self):
"""This method is inherited from BaseChecker and called at the very end of linting a module.
It reports any errors and does a final check for any pylint disable statements.
:return: None
"""
if self.ran_at_package_level:
if self.disable_logging_error is False:
if "NetworkTraceLoggingPolicy" not in self.has_policies:
self.add_message(
msgid="missing-logging-policy", node=self.node_to_use, confidence=None
)
if self.disable_retry_error is False:
if "RetryPolicy" not in self.has_policies:
self.add_message(
msgid="missing-retry-policy", node=self.node_to_use, confidence=None
)
if self.disable_user_agent_error is False:
if "UserAgentPolicy" not in self.has_policies:
self.add_message(
msgid="missing-user-agent-policy", node=self.node_to_use, confidence=None
)
if self.disable_tracing_error is False:
if "DistributedTracingPolicy" not in self.has_policies:
self.add_message(
msgid="missing-distributed-tracing-policy", node=self.node_to_use, confidence=None
)
class CheckDocstringAdmonitionNewline(BaseChecker):
__implements__ = IAstroidChecker
name = "check-admonition"
priority = -1
msgs = {
"C4744": (
"The .. literalinclude statement needs a blank line above it. ",
"docstring-admonition-needs-newline",
"Put a newline after the example and before the literalinclude.",
),
}
options = (
(
"ignore-docstring-admonition-needs-newline",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow a docstring to not have newline after admonition example.",
},
),
)
def __init__(self, linter=None):
super(CheckDocstringAdmonitionNewline, self).__init__(linter)
def check_for_admonition(self, node):
"""Parse the docstring for an admonition statement.
If found, checks that the literalinclude statement has
two newlines above it.
:param node: ast.ClassDef or ast.FunctionDef
:return: None
"""
try:
# not every class/method will have a docstring so don't crash here, just return
if node.doc.find("admonition") != -1 and node.doc.find(".. literalinclude") != -1:
literal_include = node.doc.split(".. literalinclude")[0]
chars_list = list(reversed(literal_include))
for idx, char in enumerate(chars_list):
if char == '\n':
if chars_list[idx+1] == '\n':
break
else:
self.add_message(
"docstring-admonition-needs-newline", node=node, confidence=None
)
break
except Exception:
return
def visit_classdef(self, node):
"""Visits every class docstring.
:param node: ast.ClassDef
:return: None
"""
try:
for func in node.body:
if isinstance(func, astroid.FunctionDef) and func.name == "__init__":
self.check_for_admonition(node)
except Exception:
logger.debug("Pylint custom checker failed to check docstrings.")
pass
def visit_functiondef(self, node):
"""Visits every method docstring.
:param node: ast.FunctionDef
:return: None
"""
try:
if node.name == "__init__":
return
self.check_for_admonition(node)
except Exception:
logger.debug("Pylint custom checker failed to check docstrings.")
pass
# this line makes it work for async functions
visit_asyncfunctiondef = visit_functiondef
class CheckEnum(BaseChecker):
__implements__ = IAstroidChecker
name = "check-enum"
priority = -1
msgs = {
"C4746": (
"The enum must use uppercase naming. "
"https://azure.github.io/azure-sdk/python_design.html#enumerations",
"enum-must-be-uppercase",
"Capitalize enum name.",
),
"C4747":(
"The enum must inherit from CaseInsensitiveEnumMeta. "
"https://azure.github.io/azure-sdk/python_implementation.html#extensible-enumerations",
"enum-must-inherit-case-insensitive-enum-meta",
"Inherit CaseInsensitiveEnumMeta.",
),
}
options = (
(
"ignore-enum-must-be-uppercase",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow an enum to not be capitalized.",
},
),
(
"ignore-enum-must-inherit-case-insensitive-enum-meta",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow an enum to not inherit CaseInsensitiveEnumMeta.",
},
),
)
def __init__(self, linter=None):
super(CheckEnum, self).__init__(linter)
def visit_classdef(self, node):
"""Visits every enum class.
:param node: ast.ClassDef
:return: None
"""
try:
# If it has a metaclass, and is an enum class, check the capitalization
if node.declared_metaclass():
if node.declared_metaclass().name == "CaseInsensitiveEnumMeta":
self._enum_uppercase(node)
# Else if it does not have a metaclass, but it is an enum class
# Check both capitalization and throw pylint error for metaclass
elif node.bases[0].name == "str" and node.bases[1].name == "Enum":
self.add_message(
"enum-must-inherit-case-insensitive-enum-meta", node=node, confidence=None
)
self._enum_uppercase(node)
except Exception:
logger.debug("Pylint custom checker failed to check enum.")
pass
def _enum_uppercase(self, node):
"""Visits every enum within the class.
Checks if the enum is uppercase, if it isn't it
adds a pylint error message.
:param node: ast.ClassDef
:return: None
"""
# Check capitalization of enums assigned in the class
for nod in node.body:
if isinstance(nod, astroid.Assign):
if not nod.targets[0].name.isupper():
self.add_message(
"enum-must-be-uppercase", node=nod.targets[0], confidence=None
)
class CheckAPIVersion(BaseChecker):
__implements__ = IAstroidChecker
name = "check-api-version-kwarg"
priority = -1
msgs = {
"C4748": (
"The client constructor needs to take in an optional keyword-only api_version argument. "
"https://azure.github.io/azure-sdk/python_design.html#specifying-the-service-version",
"client-accepts-api-version-keyword",
"Accept a keyword argument called api_version.",
),
}
options = (
(
"ignore-client-accepts-api-version-keyword",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow for no keyword api version.",
},
),
)
ignore_clients = ["PipelineClient", "AsyncPipelineClient", "ARMPipelineClient", "AsyncARMPipelineClient"]
def __init__(self, linter=None):
super(CheckAPIVersion, self).__init__(linter)
def visit_classdef(self, node):
"""Visits every class in file and checks if it is a client.
If it is a client, it checks that there is an api_version keyword.
:param node: class node
:type node: ast.ClassDef
:return: None
"""
try:
api_version = False
if node.name.endswith("Client") and node.name not in self.ignore_clients:
if node.doc:
if ":keyword api_version:" in node.doc or ":keyword str api_version:" in node.doc:
api_version = True
if not api_version:
for func in node.body:
if isinstance(func, astroid.FunctionDef):
if func.name == '__init__':
if func.doc:
if ":keyword api_version:" in func.doc or ":keyword str api_version:" in func.doc:
api_version = True
if not api_version:
self.add_message(
msgid="client-accepts-api-version-keyword", node=node, confidence=None
)
except AttributeError:
logger.debug("Pylint custom checker failed to check if client takes in an optional keyword-only api_version argument.")
pass
class CheckNamingMismatchGeneratedCode(BaseChecker):
__implements__ = IAstroidChecker
name = "check-naming-mismatch"
priority = -1
msgs = {
"C4745": (
"Do not alias generated code. "
"This messes up sphinx, intellisense, and apiview, so please modify the name of the generated code through"
" the swagger / directives, or code customizations. See Details: "
"https://github.com/Azure/autorest/blob/main/docs/generate/built-in-directives.md",
"naming-mismatch",
"Do not alias models imported from the generated code.",
),
}
options = (
(
"ignore-naming-mismatch",
{
"default": False,
"type": "yn",
"metavar": "<y_or_n>",
"help": "Allow generated code to be aliased.",
},
),
)
def __init__(self, linter=None):
super(CheckNamingMismatchGeneratedCode, self).__init__(linter)
def visit_module(self, node):
"""Visits __init__.py and checks that there are not aliased models.
:param node: module node
:type node: ast.Module
:return: None
"""
try:
if node.file.endswith("__init__.py"):
aliased = []
for nod in node.body:
if isinstance(nod, astroid.ImportFrom) or isinstance(nod, astroid.Import):
# If the model has been aliased
for name in nod.names:
if name[1] is not None:
aliased.append(name[1])
for nod in node.body:
if isinstance(nod, astroid.Assign):
if nod.targets[0].as_string() == "__all__":
for models in nod.assigned_stmts():
for model_name in models.elts:
if model_name.value in aliased:
self.add_message(
msgid="naming-mismatch", node=model_name, confidence=None
)
except Exception:
logger.debug("Pylint custom checker failed to check if model is aliased.")
pass
# if a linter is registered in this function then it will be checked with pylint
def register(linter):
linter.register_checker(ClientsDoNotUseStaticMethods(linter))
linter.register_checker(ClientConstructorTakesCorrectParameters(linter))
linter.register_checker(ClientMethodsUseKwargsWithMultipleParameters(linter))
linter.register_checker(ClientMethodsHaveTypeAnnotations(linter))
linter.register_checker(ClientUsesCorrectNamingConventions(linter))
linter.register_checker(ClientMethodsHaveKwargsParameter(linter))
linter.register_checker(ClientHasKwargsInPoliciesForCreateConfigurationMethod(linter))
linter.register_checker(AsyncClientCorrectNaming(linter))
linter.register_checker(FileHasCopyrightHeader(linter))
linter.register_checker(ClientMethodNamesDoNotUseDoubleUnderscorePrefix(linter))
linter.register_checker(SpecifyParameterNamesInCall(linter))
linter.register_checker(ClientConstructorDoesNotHaveConnectionStringParam(linter))
linter.register_checker(PackageNameDoesNotUseUnderscoreOrPeriod(linter))
linter.register_checker(ServiceClientUsesNameWithClientSuffix(linter))
linter.register_checker(CheckDocstringAdmonitionNewline(linter))
linter.register_checker(CheckNamingMismatchGeneratedCode(linter))
linter.register_checker(CheckAPIVersion(linter))
linter.register_checker(CheckEnum(linter))
# disabled by default, use pylint --enable=check-docstrings if you want to use it
linter.register_checker(CheckDocstringParameters(linter))
# Rules are disabled until false positive rate improved
# linter.register_checker(CheckForPolicyUse(linter))
# linter.register_checker(ClientHasApprovedMethodNamePrefix(linter))
# linter.register_checker(ClientMethodsHaveTracingDecorators(linter))
# linter.register_checker(ClientDocstringUsesLiteralIncludeForCodeExample(linter))
# linter.register_checker(ClientListMethodsUseCorePaging(linter))
# linter.register_checker(ClientLROMethodsUseCorePolling(linter))
# linter.register_checker(ClientLROMethodsUseCorrectNaming(linter))
|