PSClassUtils.psm1
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 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 |
#Generated at 02/28/2019 17:25:19 by Stephane van Gulick Class CUClassParameter { [String]$Name [String]$Type hidden $Raw CUClassParameter([String]$Name,[String]$Type){ $this.Name = $Name $This.Type = $Type } CUClassParameter([String]$Name,[String]$Type,$Raw){ $this.Name = $Name $This.Type = $Type $this.Raw = $Raw } } Class CUClassProperty { [String]$ClassName [String]$Name [String]$Type [string]$Visibility Hidden $Raw CUClassProperty([String]$ClassName,[String]$Name,[String]$Type){ $this.ClassName = $ClassName $this.Name = $Name $this.Type = $Type } CUClassProperty([String]$ClassName,[String]$Name,[String]$Type,[String]$Visibility){ $this.ClassName = $ClassName $this.Name = $Name $this.Type = $Type $this.Visibility = $Visibility } CUClassProperty([String]$ClassName,[String]$Name,[String]$Type,[String]$Visibility,$Raw){ $this.ClassName = $ClassName $this.Name = $Name $this.Type = $Type $this.Visibility = $Visibility $this.Raw = $Raw } } Class CUClassMethod { [String]$ClassName [String]$Name [String]$ReturnType [CUClassParameter[]]$Parameter hidden $Raw [Bool]$Static CUClassMethod([String]$ClassName,[String]$Name,[String]$ReturnType,[CUClassParameter[]]$Parameter){ $this.ClassName = $ClassName $this.Name = $Name $This.ReturnType = $ReturnType $This.Parameter = $Parameter } CUClassMethod([String]$ClassName,[String]$Name,[String]$ReturnType,[CUClassParameter[]]$Parameter,$Raw){ $this.ClassName = $ClassName $this.Name = $Name $This.ReturnType = $ReturnType $This.Parameter = $Parameter $This.Raw = $Raw } SetIsStatic([Bool]$IsStatic){ $this.Static = $IsStatic } [Bool] IsStatic(){ return $this.Static } } Class CUClassConstructor { [String]$ClassName [String]$Name [CUClassParameter[]]$Parameter hidden $Raw #hidden $Extent CUClassConstructor([String]$ClassName,[String]$Name,[CUClassParameter[]]$Parameter){ $this.ClassName = $ClassName $this.Name = $Name $This.Parameter = $Parameter } CUClassConstructor([String]$ClassName,[String]$Name,[CUClassParameter[]]$Parameter,$Raw){ $this.ClassName = $ClassName $this.Name = $Name $This.Parameter = $Parameter $This.Raw = $Raw #$This.Extent = $Raw.Extent.Text } } Class ASTDocument { [System.Management.Automation.Language.StatementAst[]]$Classes [System.Management.Automation.Language.StatementAst[]]$Enums $Source $ClassName Hidden $Raw ASTDocument ([System.Management.Automation.Language.StatementAst[]]$Classes,[System.Management.Automation.Language.StatementAst[]]$Enums,$Source){ $This.Classes = $Classes $This.Enums = $Enums $This.Source = $Source $This.ClassName = $Classes.Name } ASTDocument([System.Management.Automation.Language.StatementAst[]]$Classes,[System.Management.Automation.Language.StatementAst[]]$Enums,$Source,[System.Management.Automation.Language.ScriptBlockAst]$RawAST){ $This.Classes = $Classes $This.Enums = $Enums $This.Source = $Source $This.ClassName = $Classes.Name $This.Raw = $RawAST } } Class ClassEnum { [String]$Name [String[]]$Member ClassEnum([String]$Name,[String[]]$Member){ $this.Name = $Name $this.Member = $Member } } Class CUClass { [String]$Name [CUClassProperty[]]$Property [CUClassConstructor[]]$Constructor [CUClassMethod[]]$Method [Bool]$IsInherited = $False [String]$ParentClassName [System.IO.FileInfo]$Path Hidden $Raw #Hidden $Ast CUClass($AST){ #$this.Raw = $RawAST $this.Raw = $AST $This.SetPropertiesFromAST() } CUClass ($Name,$Property,$Constructor,$Method){ $This.Name = $Name $This.Property = $Property $This.Constructor = $Constructor $This.Method = $Method } CUClass ($Name,$Property,$Constructor,$Method,$AST){ $This.Name = $Name $This.Property = $Property $This.Constructor = $Constructor $This.Method = $Method $This.Raw = $AST } ## Set Name, and call Other Set [void] SetPropertiesFromAST(){ $This.Name = $This.Raw.Name $This.Path = [System.IO.FileInfo]::new($This.Raw.Extent.File) $This.SetConstructorFromAST() $This.SetPropertyFromAST() $This.SetMethodFromAST() ## Inheritence Check If ( $This.Raw.BaseTypes ) { $This.IsInherited = $True $This.ParentClassName = $This.Raw.BaseTypes.TypeName.Name } } ## Find Constructors for the current Class [void] SetConstructorFromAST(){ $Constructors = $null $Constructors = $This.Raw.Members | Where-Object {$_.IsConstructor -eq $True} Foreach ( $Constructor in $Constructors ) { $Parameters = $null $Parameters = $Constructor.Parameters [CUClassParameter[]]$Paras = @() If ( $Parameters ) { Foreach ( $Parameter in $Parameters ) { $Type = $null # couldn't find another place where the returntype was located. # If you know a better place, please update this! I'll pay you beer. $Type = $Parameter.Extent.Text.Split("$")[0] $Paras += [CUClassParameter]::New($Parameter.Name.VariablePath.UserPath, $Type) } } $This.Constructor += [CUClassConstructor]::New($This.name,$Constructor.Name, $Paras,$Constructor) } } ## Find Methods for the current Class [void] SetMethodFromAST(){ $Methods = $null $Methods = $This.Raw.Members | Where-Object {$_.IsConstructor -eq $False} Foreach ( $Method in $Methods ) { $Parameters = $null $Parameters = $Method.Parameters [CUClassParameter[]]$Paras = @() If ( $Parameters ) { Foreach ( $Parameter in $Parameters ) { $Type = $null # couldn't find another place where the returntype was located. # If you know a better place, please update this! I'll pay you beer. $Type = $Parameter.Extent.Text.Split("$")[0] $Paras += [CUClassParameter]::New($Parameter.Name.VariablePath.UserPath, $Type) } } $M = [CUClassMethod]::New($This.Name,$Method.Name, $Method.ReturnType, $Paras,$Method) $M.SetIsStatic($Method.IsStatic) $This.Method += $M $M = $null } } ## Find Properties for the current Class [void] SetPropertyFromAST(){ $Properties = $This.Raw.Members | Where-Object {$_ -is [System.Management.Automation.Language.PropertyMemberAst]} If ($Properties) { Foreach ( $Pro in $Properties ) { If ( $Pro.IsHidden ) { $Visibility = "Hidden" } Else { $visibility = "public" } $This.Property += [CUClassProperty]::New($This.Name,$pro.Name, $pro.PropertyType.TypeName.Name, $Visibility,$Pro) } } } ## Return the content of Constructor [CUClassConstructor[]]GetCUClassConstructor(){ return $This.Constructor } ## Return the content of Method [CUClassMethod[]]GetCUClassMethod(){ return $This.Method } ## Return the content of Property [CUClassProperty[]]GetCUClassProperty(){ return $This.Property } } Enum PesterType { It Describe Context } Class PesterItBlock{ [String]$Name [String]$Value [PesterType]$Type [String]$Content [HashTable]$TestCases [Bool]$Pending = $false [Bool]$Skipped = $False PesterITBlock([String]$Name,[String]$Value,[PesterType]$Type,[String]$Content,[HashTable]$TestCases){ $this.Name = $Name $this.Value = $Value $this.Type = $Type $this.Content = $Content $This.TestCases = $TestCases } SetPending([Bool]$IsPending){ $this.Pending = $IsPending } [Bool] IsPending(){ return $This.Pending } SetSkipped([Bool]$IsSkipped){ $this.Pending = $IsSkipped } [Bool] IsSkipped(){ return $This.Skipped } } Class PesterDescribeBlock { [String]$Name [PesterItBlock[]]$ItBlocks [PesterType]$Type [String]$Fixture [String[]]$Tags PesterDescribeBlock([String]$Name,[PesterItBlock[]]$ItBlocks,[PesterType]$Type,[String]$Fixture,[String[]]$Tags){ $this.Name = $Name $this.ItBlocks = $ItBlocks $this.Type = $Type $this.Fixture = $Fixture $This.Tags = $Tags } } Class PesterScript { [System.IO.FileInfo]$path [PesterDescribeBlock[]]$DescribeBlocks PesterScript([System.Io.FileInfo]$Path){ $this.Path = $Path $This.DescribeBlocks = Get-CUPesterDescribeBlock -Path $This.path.FullName } } Function ConvertTo-titleCase { [CmdletBinding()] Param( [String]$String ) $TextInfo = (Get-Culture).TextInfo return $TextInfo.ToTitleCase($string) } function Find-CUClass { <# .SYNOPSIS Helper function to find classes, based on a path, Wraps Get-CuClass, return a Microsoft.PowerShell.Commands.GroupInfo object .DESCRIPTION Helper function to find classes, based on a path, Wraps Get-CuClass, return a Microsoft.PowerShell.Commands.GroupInfo object .NOTES Private function for PSClassUtils, used in Write-CUClassDiagram #> Param ( $Item, $Exclude ) If ( $Exclude ) { Write-Verbose "Find-CUClass -> Exclude Parameter Specified... $($Exclude.count) items to filter..." If ( $Exclude.Count -eq 1 ) { Get-ChildItem -path $item -Include '*.ps1', '*.psm1' | Get-CUCLass | Where-Object Name -NotLike $Exclude | Group-Object -Property Path } If ( $Exclude.Count -gt 1 ) { Get-ChildItem -path $item -Include '*.ps1', '*.psm1' | Get-CUCLass | Where-Object Name -NotIn $Exclude | Group-Object -Property Path } } Else { Write-Verbose "Find-CUClass -> Exclude Parameter NOT Specified..." Get-ChildItem -path $item -Include '*.ps1', '*.psm1' | Get-CUCLass | Group-Object -Property Path } } Function Get-CUAst { [CmdletBinding()] param ( [parameter(Mandatory=$True,ValueFromPipeline = $true)] [Alias('FullName')] [System.IO.FileInfo[]]$Path ) begin {} process { foreach($p in $Path){ Write-Verbose "Current file $p" If ( $P.Extension -in '.ps1','.psm1') { Write-Verbose "Current file $p is a PS1 or PSM1 file..." $Raw = [System.Management.Automation.Language.Parser]::ParseFile($p.FullName, [ref]$null, [ref]$Null) $AST = $Raw.FindAll( {$args[0] -is [System.Management.Automation.Language.TypeDefinitionAst]}, $true) ## If AST Count -gt 1 we need to retourn each one of them separatly Switch ($AST.count) { { $AST.count -eq 1 } { Write-Verbose "Current file $p contains 1 AST..." $AST } { $AST.count -gt 1 } { Write-Verbose "Current file $p contains $($ast.count) AST..." Foreach ( $x in $AST ) { $x } } Default { Write-Verbose "Current file $p contains $($ast.count) AST..." } } } Else { Write-Verbose "Current file $p is not a PS1 or PSM1 file..." } } } end { } } function New-CUGraphExport { <# .SYNOPSIS Helper function to generate a Graph export file, wraps Export-PSGraph. .DESCRIPTION Helper function to generate a Graph export file , wraps Export-PSGraph. .NOTES Private function for PSClassUtils, used in Write-CUClassDiagram #> param ( $Graph, $PassThru, $Path, $ChildPath, $OutPutFormat, [Switch]$Show ) $ExportParams = @{ ShowGraph = $Show OutPutFormat = $OutPutFormat DestinationPath = Join-Path -Path $Path -ChildPath ($ChildPath+'.'+$OutPutFormat) } If ( $PassThru ) { $Graph $null = $Graph | Export-PSGraph @ExportParams } Else { $Graph | Export-PSGraph @ExportParams } } function New-CUGraphParameters { <# .SYNOPSIS Helper function to generate a Graph, wrap Out-CUPSGraph. .DESCRIPTION Helper function to generate a Graph, wrap Out-CUPSGraph. .NOTES Private function for PSClassUtils, used in Write-CUClassDiagram #> Param ( $inputobject, $ignorecase, $showcomposition ) $GraphParams = @{ InputObject = $inputobject } If ( $ignorecase ) { $GraphParams.Add('IgnoreCase',$ignorecase) } If ( $showcomposition ) { $GraphParams.Add('ShowComposition',$showcomposition) } Out-CUPSGraph @GraphParams } Function Out-CUPSGraph { <# .SYNOPSIS Generates the graph output. It requires input from Get-CUAST (input of type ASTDOcument) .DESCRIPTION This function is based on psgraph, which wih is a module to generate diagrams using GraphViz. If psgraph is not present, it will throw. .EXAMPLE .INPUTS Pipeline input from a ASTDocument Object .OUTPUTS Output (if any) .PARAMETER InputObject This parameter expects an array of ASTDocument. (Can be generated using Get-CUAST). .PARAMETER IgnoreCase If there is a difference in the casesensitivity of the a parent class, and it's child class, drawing the inheritence might not work as expected. Forcing the case sensitivy to be everywhere the same when creating the objects in PSGraph resolves this issue (See issue here -> https://github.com/KevinMarquette/PSGraph/issues/68 ) Using -IgnoreCase will force all class names to be set to 'TitleCase', reglardless of the case sensitivity they had before. .NOTES version: 1.1 #> [CmdletBinding()] param ( [Parameter(Mandatory=$true,ValueFromPipeline = $true)] [Object[]]$inputObject, [Parameter(Mandatory = $False)] [Switch] $IgnoreCase, $ShowComposition ) begin { Write-Verbose "Out-CUPSGraph -> BEGIN BLOCK..." $AllGraphs = @() if(!(Get-Module -Name PSGraph)){ #Module is not loaded if(!(get-module -listavailable -name psgraph )){ #Module is not present throw "The module PSGraph is a prerequisite for this function to work. Please Install PSGraph first (You can use Install-CUDiagramPrerequisites to install them.)" }else{ Import-Module psgraph -Force } } } process { Write-Verbose "Out-CUPSGraph -> PROCESS BLOCK..." [System.Collections.ArrayList]$AllClasses = @() #$Graph = Graph -Attributes @{splines='ortho'} -ScriptBlock { $Graph = Graph -ScriptBlock { foreach($obj in $inputObject){ $CurrName = split-Path -leaf $obj.Name subgraph -Attributes @{label=($CurrName)} -ScriptBlock { Foreach( $Class in $obj.Group ) { If($IgnoreCase){ $RecordName = ConvertTo-TitleCase -String $Class.Name }else{ $RecordName = $Class.Name } #Adding className for futur use to identify composition $null = $AllClasses.Add($RecordName) # It needs to set to null to avoid to have 'numbers' as random points in the graph $Constructors = $Class.Constructor $Methods = $Class.Method $Properties = $Class.Property Record -Name $RecordName { If ($Properties) { Foreach ($pro in $Properties) { if ($pro.Visibility -eq "Hidden") { $visibility = "-" } Else { $visibility = "+" } $n = "$($visibility) [$($pro.Type)] `$$($pro.Name)" if ($n) { write-verbose "[Property][Row]Label:$($n) - Name: Row_$($pro.Name)" Row -label "$($n)" -Name "Row_$($pro.Name)" } else { #$pro.name } } } Row "-----Constructors-----" -Name "Row_Separator_Constructors" #Constructors If ( $Constructors ) { foreach ($con in $Constructors) { $RowName = "$($con.Name)" If ( $con.Parameter ) { foreach ($c in $con.Parameter) { $Parstr = $Parstr + $C.Type + '$' + $c.Name + "," } $Parstr = $Parstr.trim(",") } If ($Parstr) { $RowName = $RowName + "(" + $Parstr + ")" } Else { $RowName = $RowName + "()" } Row $RowName -Name "Row_$($con.Name)" } } Else { } #Methods Raw Row "-----Methods-----" -Name "Row_Separator_Methods" If ( $Methods ) { #Write-Host $Methods.Count #$i=0 Foreach ($mem in $Methods) { $visibility = "+" $Parstr = "" If ( $mem.Parameter ) { ForEach ( $p in $mem.Parameter ) { $Parstr = $Parstr + $p.Type + '$' + $p.Name + "," } $Parstr = $Parstr.trim(",") } $RowName = "$($mem.Name)" If ( $Parstr ) { $RowName = $RowName + "(" + $Parstr + ")" } Else { $RowName = $RowName + "()" } If ( $mem.IsHidden ) { $visibility = "-" } If($mem.IsStatic()){ $RowName = "{0} {1} {2}" -f $visibility,"static",$RowName }else{ $RowName = "{0} {1}" -f $visibility,$RowName } Row $RowName -Name "Row_$($mem.Name)" } } }#End Record }#end foreach Class }#End SubGraph ## InHeritance Foreach ($class in ($Obj.Group | where-Object IsInherited)){ If($IgnoreCase){ $Parent = ConvertTo-TitleCase -String $Class.ParentClassName $Child = ConvertTo-TitleCase -String $Class.Name }else{ $Parent = $Class.ParentClassName $Child = $Class.Name } edge -From $Parent -To $Child -Attributes @{arrowhead="empty"} } ##Composition if($ShowComposition){ Write-Verbose "Out-CUPSGraph -> ShowCoposition" #foreach class.Property.Type if in list of customClasses, then it is composition ## replace brackets when property type is an array of type Foreach($ClassProperty in $obj.group.property){ #if( $AllClasses -contains $ClassProperty.type ){ if( $AllClasses -contains ($ClassProperty.type -replace '\[\]','') ){ write-verbose "Out-CUPSGraph -> Composition relationship found:" #CompositionFound Write-Verbose "Out-CUPSGraph -> Composition: $($ClassProperty.Name):Row_$($ClassProperty.Name) to $($ClassProperty.Type)" edge -From ($ClassProperty.type -replace '\[\]','') -To "$($ClassProperty.className):Row_$($ClassProperty.Name -replace '\[\]','')" -Attributes @{arrowhead='diamond'} } } } } } $AlLGraphs += $Graph } end { Write-Verbose "Out-CUPSGraph -> END BLOCK..." Write-Verbose "Out-CUPSGraph -> END BLOCK: return graphs..." Return $AlLGraphs } } function Get-CUClass { <# .SYNOPSIS This function returns all classes, loaded in memory or present in a ps1 or psm1 file. .DESCRIPTION By default, the function will return all loaded classes in the current PSSession. You can specify a file path to explore the classes present in a ps1 or psm1 file. .PARAMETER ClassName Specify the name of the class. .PARAMETER Path The path of a file containing PowerShell Classes. Accept values from the pipeline. .PARAMETER Raw The raw switch will display the raw content of the Class. .EXAMPLE PS C:\> Get-CUClass Return all classes alreay loaded in current PSSession. .EXAMPLE PS C:\> Get-CUClass -ClassName CUClass Return the particuluar CUCLass. .EXAMPLE PS C:\> Get-CUClass -Path .\test.psm1,.\test2.psm1 Return all classes present in the test.psm1 and test2.psm1 file. .EXAMPLE PS C:\> Get-CUClass -Path .\test.psm1 -ClassName test Return test class present in the test.psm1 file. .EXAMPLE PS C:\PSClassUtils> Get-ChildItem -recurse | Get-CUClass Return all classes, recursively, present in the C:\PSClassUtils Folder. .INPUTS Accepts type [System.IO.FileInfo] .OUTPUTS Return type [CuClass] .NOTES Author: Stéphane van Gulick Participate & contribute --> https://github.com/Stephanevg/PSClassUtils #> [CmdletBinding()] Param( [Parameter(Mandatory = $False, ValueFromPipeline = $False)] $ClassName, [Alias("FullName")] [Parameter(ValueFromPipeline=$True,Position=1,ValueFromPipelineByPropertyName=$True)] [System.IO.FileInfo[]]$Path, [Parameter(Mandatory = $False)] [Switch]$Raw = $False ) BEGIN { } PROCESS { If ( ($Null -eq $PSBoundParameters['Path']) -And ($PSVersionTable.PSEdition -eq 'Core' ) ) { Throw 'This feature is not supported on PSCore, due to missing DotNet libraries. Please use -Path instead...' } $ClassParams = @{} If ( $Null -ne $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $PSBoundParameters['ClassName'] } If ( $Null -ne $PSBoundParameters['Path'] ) { Foreach ( $Path in $PSBoundParameters['Path'] ) { If ( $Path.Extension -in '.ps1', '.psm1') { If ($PSCmdlet.MyInvocation.ExpectingInput) { $ClassParams.Path = $Path.FullName } Else { $ClassParams.Path = (Get-Item (Resolve-Path $Path).Path).FullName } $Ast = Get-CUAst -Path $ClassParams.Path Foreach ( $x in $Ast ) { If(!($x.IsEnum)){ If ( $PSBoundParameters['ClassName'] ) { If ( $x.name -eq $PSBoundParameters['ClassName'] ) { If ( $PSBoundParameters['Raw'] ) { ([CUClass]::New($x)).Raw } Else { [CUClass]::New($x) } } } Else { If ( $PSBoundParameters['Raw'] ) { ([CUClass]::New($x)).Raw } Else { [CUClass]::New($x) } } } } } } } Else { Foreach ( $x in (Get-CULoadedClass @ClassParams ) ) { If ( $PSBoundParameters['ClassName'] ) { If ( $x.name -eq $PSBoundParameters['ClassName'] ) { If ( $PSBoundParameters['Raw'] ) { ([CUClass]::New($x)).Raw } Else { [CUClass]::New($x) } } } Else { If ( $PSBoundParameters['Raw'] ) { ([CUClass]::New($x)).Raw } Else { [CUClass]::New($x) } } } } } END {} } Function Get-CUClassConstructor { <# .SYNOPSIS This function returns all existing constructors of a specific powershell class. .DESCRIPTION This function returns all existing constructors of a specific powershell class. You can pipe the result of get-cuclass. Or you can specify a file to get all the constructors present in this specified file. .PARAMETER ClassName Specify the name of the class. .PARAMETER Path The path of a file containing PowerShell Classes. Accept values from the pipeline. .PARAMETER Raw The raw switch will display the raw content of the Class. .PARAMETER InputObject An object, or array of object of type CuClass .EXAMPLE PS C:\> Get-CUClassConstructor Return all the constructors of the classes loaded in the current PSSession. .EXAMPLE PS C:\> Get-CUClassConstructor -ClassName woop ClassName Name Parameter --------- ---- --------- woop woop woop woop {String, Number} Return constructors for the woop Class. .EXAMPLE PS C:\> Get-CUClassConstructor -Path .\Woop.psm1 ClassName Name Parameter --------- ---- --------- woop woop woop woop {String, Number} Return constructors for the woop Class present in the woop.psm1 file. .EXAMPLE PS C:\PSClassUtils> Gci -recurse | Get-CUClassConstructor -ClassName CuClass ClassName Name Parameter --------- ---- --------- CUClass CUClass {RawAST} CUClass CUClass {Name, Property, Constructor, Method} CUClass CUClass {Name, Property, Constructor, Method...} Return constructors for the CUclass Class present somewhere in the c:\psclassutils folder. .INPUTS String .OUTPUTS ClassConstructor .NOTES Author: Stéphane van Gulick Version: 0.7.1 www.powershellDistrict.com Report bugs or submit feature requests here: https://github.com/Stephanevg/PowerShellClassUtils #> [cmdletBinding(DefaultParameterSetName="All")] [OutputType([CUClassMethod[]])] Param( [Parameter(Mandatory=$False, ValueFromPipeline=$False)] [String[]]$ClassName, [Parameter(ValueFromPipeline=$True,ParameterSetName="Set1")] [CUClass[]]$InputObject, [Alias("FullName")] [Parameter(ValueFromPipeline=$True,ParameterSetName="Set2",ValueFromPipelineByPropertyName=$True)] [System.IO.FileInfo[]]$Path, [Switch]$Raw ) BEGIN {} PROCESS { Switch ( $PSCmdlet.ParameterSetName ) { ## CUClass as input Set1 { $ClassParams = @{} ## ClassName was specified If ( $null -ne $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $PSBoundParameters['ClassName'] } Foreach ( $Class in $InputObject ) { If ( $ClassParams.ClassName ) { If ( $Class.Name -eq $ClassParams.ClassName ) { if($Raw){ $Class.GetCUClassConstructor().Raw }Else{ $Class.GetCUClassConstructor() } } } Else { If ( $null -ne $Class.Constructor ) { if($Raw){ $Class.GetCUClassConstructor().Raw }Else{ $Class.GetCUClassConstructor() } } } } } Set2 { $ClassParams = @{} If ( $null -ne $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $PSBoundParameters['ClassName'] } Foreach ( $P in $Path ) { If ( $P.extension -in ".ps1",".psm1" ) { If ( $PSCmdlet.MyInvocation.ExpectingInput ) { $ClassParams.Path = $P.FullName } Else { $ClassParams.Path = (Get-Item (Resolve-Path $P).Path).FullName } $Class=Get-CuClass @ClassParams If ( $null -ne $Class.Constructor ) { if($Raw){ $Class.GetCUClassConstructor().Raw }Else{ $Class.GetCUClassConstructor() } } } } } Default { $ClassParams = @{} If ( $null -ne $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $PSBoundParameters['ClassName'] } Foreach($Class in (Get-CuClass @ClassParams)) { If ( $Class.Constructor.count -ne 0 ) { If ( $Raw ) { $Class.GetCUClassConstructor().Raw } Else { $Class.GetCUClassConstructor() } } } } } } END {} } Function Get-CUClassMethod { <# .SYNOPSIS This function returns all existing constructors of a specific powershell class. .DESCRIPTION This function returns all existing constructors of a specific powershell class. You can pipe the result of get-cuclass. Or you can specify a file to get all the constructors present in this specified file. .PARAMETER ClassName Specify the name of the class. .PARAMETER MethodName Specify the name of a specific Method .PARAMETER Path The path of a file containing PowerShell Classes. Accept values from the pipeline. .PARAMETER Raw The raw switch will display the raw content of the Class. .PARAMETER InputObject An object, or array of object of type CuClass .EXAMPLE PS C:\> Get-CUClassMethod Return all the methods of the classes loaded in the current PSSession. .EXAMPLE PS C:\> Get-CUClassMethod -ClassName woop ClassName Name Parameter --------- ---- --------- woop woop woop woop {String, Number} Return methods for the woop Class. .EXAMPLE PS C:\> Get-CUClassMethod -Path .\Woop.psm1 ClassName Name Parameter --------- ---- --------- woop woop woop woop {String, Number} Return methods for the woop Class present in the woop.psm1 file. .EXAMPLE PS C:\PSClassUtils> Gci -recurse | Get-CUClassMethod -ClassName CuClass ClassName Name Parameter --------- ---- --------- CUClass CUClass {RawAST} CUClass CUClass {Name, Property, Constructor, Method} CUClass CUClass {Name, Property, Constructor, Method...} Return methods for the CUclass Class present somewhere in the c:\psclassutils folder. .INPUTS String .OUTPUTS CUClassMethod .NOTES Author: Stéphane van Gulick Version: 0.7.1 www.powershellDistrict.com Report bugs or submit feature requests here: https://github.com/Stephanevg/PowerShellClassUtils #> [cmdletBinding(DefaultParameterSetName="All")] [OutputType([CUClassMethod[]])] Param( [Parameter(Mandatory=$False, ValueFromPipeline=$False)] [String[]]$ClassName, [Parameter(Mandatory=$False, ValueFromPipeline=$False)] [String[]]$MethodName='*', [Parameter(ValueFromPipeline=$True,ParameterSetName="Set1")] [CUClass[]]$InputObject, [Alias("FullName")] [Parameter(ValueFromPipeline=$True,ParameterSetName="Set2",ValueFromPipelineByPropertyName=$True)] [System.IO.FileInfo[]]$Path, [Switch]$Raw ) BEGIN {} PROCESS { Switch ( $PSCmdlet.ParameterSetName ) { ## CUClass as input Set1 { $ClassParams = @{} ## ClassName was specified If ( $null -ne $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $PSBoundParameters['ClassName'] } Foreach ( $Class in $InputObject ) { If ( $ClassParams.ClassName ) { If ( $Class.Name -eq $ClassParams.ClassName ) { If ( $PSBoundParameters['Raw'] ) { ($Class.GetCUClassMethod() | Where-Object Name -like $MethodName).Raw } Else { $Class.GetCUClassMethod() | Where-Object Name -like $MethodName } } } Else { If ( $null -ne $Class.Method ) { If ( $PSBoundParameters['Raw'] ) { ($Class.GetCUClassMethod() | Where-Object Name -like $MethodName).Raw } Else { $Class.GetCUClassMethod() | Where-Object Name -like $MethodName } } } } } ## System.io.FileInfo as Input Set2 { $ClassParams = @{} If ( $null -ne $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $PSBoundParameters['ClassName'] } Foreach ( $P in $Path ) { If ( $P.extension -in ".ps1",".psm1" ) { If ($PSCmdlet.MyInvocation.ExpectingInput) { $ClassParams.Path = $P.FullName } Else { $ClassParams.Path = (Get-Item (Resolve-Path $P).Path).FullName } $x=Get-CuClass @ClassParams If ( $null -ne $x.Method ) { If ( $PSBoundParameters['Raw'] ) { ($x.GetCUClassMethod() | Where-Object Name -like $MethodName).Raw } Else { $x.GetCUClassMethod() | Where-Object Name -like $MethodName } } } } } ## System.io.FileInfo or Path Not Specified Default { $ClassParams = @{} If ( $null -ne $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $PSBoundParameters['ClassName'] } Foreach( $x in (Get-CuClass @ClassParams) ){ If ( $x.Method.count -ne 0 ) { If ( $PSBoundParameters['Raw'] ) { ($x.GetCUClassMethod() | Where-Object Name -like $MethodName).Raw } Else { $x.GetCUClassMethod() | Where-Object Name -like $MethodName } } } } } } END {} } Function Get-CUClassProperty { <# .SYNOPSIS Short description .DESCRIPTION Long description .EXAMPLE PS C:\> <example usage> Explanation of what the example does .INPUTS Inputs (if any) .OUTPUTS Output (if any) .NOTES General notes #> [cmdletBinding()] Param( [Alias("FullName")] [Parameter(ParameterSetName = "Path", Position = 1, Mandatory = $False, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] [System.IO.FileInfo[]]$Path, [Parameter(Mandatory=$False, ValueFromPipeline=$False)] [String[]]$ClassName, [Parameter(ValueFromPipeline=$True)] [ValidateScript({ If ( !($_.GetType().Name -eq "CUClass" ) ) { Throw "InputObect Must be of type CUClass.."} Else { $True } })] [Object[]]$InputObject, [Switch]$Raw ) BEGIN {} PROCESS { $ClassParams = @{} If ($ClassName -or $PSBoundParameters['ClassName'] ) { $ClassParams.ClassName = $ClassName } If ($Path -or $PSBoundParameters['Path'] ) { $ClassParams.Path = $Path.FullName } If ($InputObject) { $ClassParams.ClassName = $ClassName } $Class = Get-CuClass @ClassParams If ($Class) { If($Raw){ $Class.GetCuClassProperty().Raw }else{ $Class.GetCuClassProperty() } } <# If ( $MyInvocation.PipelinePosition -eq 1 ) { ## Not from the Pipeline If ( $Null -eq $PSBoundParameters['InputObject'] ) { Throw "Please Specify an InputObject of type CUClass" } If ( $Null -eq $PSBoundParameters['ClassName'] ) { $InputObject.GetCuClassProperty() } Else { Foreach ( $C in $ClassName ){ ($InputObject | where Name -eq $c).GetCuClassProperty() } } } Else { ## From the Pipeline If ( $Null -eq $PSBoundParameters['ClassName'] ) { $InputObject.GetCuClassProperty() } Else { Throw "-ClassName parameter must be specified on the left side of the pipeline" } } #> } END {} } function Get-CUCommands { <# .SYNOPSIS Returns the list of commands available in the PSclassUtils module .DESCRIPTION All public commands will be returned. .EXAMPLE Get-CUCommands .NOTES Author: Stéphane van Gulick #> [CmdletBinding()] param ( ) return Get-Command -Module PSClassUtils } Function Get-CUEnum{ <# .SYNOPSIS This function returns enums existing in a document. .DESCRIPTION Returns a custom type [ClassEnum] .EXAMPLE Get-CuEnum -Path C:\plop\enum.ps1 Returns: Name Member ---- ------ woop {Absent, Present} .INPUTS String .OUTPUTS Classenum .NOTES Author: Stéphane van Gulick Version: 0.2.0 .LINK https://github.com/Stephanevg/PowerShellClassUtils #> [cmdletBinding()] Param( [Parameter(Mandatory=$false,ValueFromPipeline=$true)] [String[]] $Path = (throw "Please provide a path") ) begin{ } Process{ foreach($p in $Path){ $AST = Get-cuast -Path $p | ? {$_.IsEnum -eq $True} foreach($enum in $AST){ [ClassEnum]::New($enum.Name,$enum.members.Name) } } } End{ } } function Get-CULoadedClass { <# .SYNOPSIS Return all loaded classes in the current PSSession .DESCRIPTION Return all loaded classes in the current PSSession .EXAMPLE PS C:\> <example usage> Explanation of what the example does .INPUTS String .OUTPUTS ASTDocument .NOTES General notes #> [CmdletBinding()] param ( [String[]]$ClassName = '*' ) BEGIN { } PROCESS { Foreach ( $Name in $ClassName ) { [Array]$LoadedClasses = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetCustomAttributes($false) | Where-Object { $_ -is [System.Management.Automation.DynamicClassImplementationAssemblyAttribute]} } | ForEach-Object { $_.GetTypes() | Where-Object IsPublic | Where-Object { $_.Name -like $Name } | Select-Object @{l = 'Path'; e = {($_.Module.ScopeName.Replace([char]0x29F9, '\').replace([char]0x589, ':')) -replace '^\\', ''}} } Foreach ( $Class in ($LoadedClasses | Select-Object -Property Path -Unique) ) { #Get-CURaw -Path $Class.Path Get-CUAst -Path $Class.Path } } } END { } } Function Get-CUPesterDescribeBlock { [CmdletBinding()] Param( $Path, $InputObject ) if($Path){ $P = Get-Item -path $Path $Raw = [System.Management.Automation.Language.Parser]::ParseFile($p.FullName, [ref]$null, [ref]$Null) }elseif($InputObject){ $Raw = [System.Management.Automation.Language.Parser]::ParseInput($InputObject,[ref]$null, [ref]$Null) } $String = $Raw.FindAll( {$args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst]}, $true) $Data = @() $Data += $String | ? {$_.StringConstantType -eq "BareWord" -and $_.Value -eq 'Describe'} $AllDescribeBlocks = @() Foreach($d in $data){ $Hash = @{} $Hash.ElementType = $d.Value $Hash.ItBlocks = @() $Hash.Tags = "" $Hash.ItBlocks += Get-CUPesterITBlock -InputObject $d.Parent.Extent.Text $Hash.Content = $d.Parent.Extent.Text $Obj = [PesterDescribeBlock]::New($Hash.Name,$Hash.ItBlocks,[PesterType]::Describe,$Hash.Content,[String[]]$Tags) $Pattern = '^.*-tag(?<Tags>.*$)' $Options = @() $Options += [System.Text.RegularExpressions.RegexOptions]::Multiline $Options += [System.Text.RegularExpressions.RegexOptions]::IgnoreCase $rgx = [regex]::New($Pattern,$Options) $MyMatches = $rgx.Match($d.Parent.Extent.Text) $Hash.Tags = $MyMatches.Groups['Tags'].Value $Obj.Tags = $Hash.Tags $AllDescribeBlocks += $Obj } Return $AllDescribeBlocks } Function Get-CUPesterITBlock { [CmdletBinding()] Param( $Path, $InputObject ) if($Path){ $P = Get-Item -path $Path $Raw = [System.Management.Automation.Language.Parser]::ParseFile($p.FullName, [ref]$null, [ref]$Null) }elseif($InputObject){ $Raw = [System.Management.Automation.Language.Parser]::ParseInput($InputObject,[ref]$null, [ref]$Null) } $String = $Raw.FindAll( {$args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst]}, $true) $Data = @() $Data += $String | ? {$_.StringConstantType -eq "BareWord" -and $_.Value -eq 'it'} Foreach($d in $data){ $Hash = @{value='';content=''} $Hash.ElementType = $d.Value $Hash.Content = $d.Parent.Extent.Text $Hash.Name = $d.Parent.commandElements.Value[1] $Hash.Value = $d.Parent.CommandElements.Scriptblock.Extent $Hash.TestCases = $d.Parent.Parent.PipelineElements.CommandElements[-1].Elements $AllItBlocks = @() $Obj = [PesterItBlock]::New($Hash.Name,$Hash.Value,[PesterType]::It,$Hash.Content,$Hash.TestCases) $AllItBlocks += $Obj } return $AllItBlocks } Function Get-CUPesterScript { [CmdletBinding()] Param( [System.IO.FileInfo]$path ) $Hash = @{} $Hash.Path = $Path.FullName $Hash.Data = Get-CUPesterDescribeBlock -Path $path.FullName $obj = [PesterScript]::New($Path) return $obj } function Get-CURaw { <# .SYNOPSIS Return the raw content of a ps1 or psm1 file as a AST scriptblock type. .DESCRIPTION Return the raw content of a ps1 or psm1 file as a AST scriptblock type. .EXAMPLE PS C:\PSClassUtils> Get-CURaw -Path .\Classes\Private\01_ClassProperty.ps1 Attributes : {} UsingStatements : {} ParamBlock : BeginBlock : ProcessBlock : EndBlock : Class ClassProperty { [String]$Name [String]$Type ClassProperty([String]$Name,[String]$Type){ $this.Name = $Name $This.Type = $Type } } DynamicParamBlock : ScriptRequirements : Extent : Class ClassProperty { [String]$Name [String]$Type ClassProperty([String]$Name,[String]$Type){ $this.Name = $Name $This.Type = $Type } } Parent : The cmdlet return an AST type representing the content of the 01_ClassProperty.ps1 file .INPUTS Path of a ps1 or psm1 file .OUTPUTS ScriptBlockAST .NOTES Ref: https://mikefrobbins.com/2018/09/28/learning-about-the-powershell-abstract-syntax-tree-ast/ for implementing -raw AST #> [CmdletBinding()] param ( [Alias("FullName")] [Parameter(ParameterSetName="Path",Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)] [System.IO.FileInfo[]]$Path ) BEGIN{} PROCESS{ Foreach ( $P in $Path ) { If ( $MyInvocation.PipelinePosition -eq 1 ) { $P = Get-Item (resolve-path $P).Path } If ( $P.Extension -in '.ps1','.psm1') { #[scriptblock]::Create( $(Get-Content -Path $P.FullName -Raw) ).Ast [System.Management.Automation.Language.Parser]::ParseFile($p.FullName, [ref]$null, [ref]$Null) } } } END{} } function Install-CUDiagramPrerequisites { <# .SYNOPSIS This function installs the prerequisites for PSClassUtils. .DESCRIPTION Installation of PSGraph .EXAMPLE Istall-CUDiagramPrerequisites .EXAMPLE Istall-CUDiagramPrerequisites -proxy "10.10.10.10" .NOTES Author: Stephanevg Version: 2.0 #> [CmdletBinding()] param ( [String]$Proxy ) if(!(Get-Module -Name PSGraph)){ #Module is not loaded if(!(get-module -listavailable -name psgraph )){ if($proxy){ write-verbose "Install PSGraph" Install-Module psgraph -Verbose -proxy $proxy Import-Module psgraph -Force }else{ write-verbose "Install PSGraph" Install-Module psgraph -Verbose Import-Module psgraph -Force } }else{ Import-Module psgraph -Force } Install-GraphViz } } function Test-IsCustomType { # Test-PowershellDynamicClass Psobject # Test-PowershellDynamicClass MyClass # extrait et adapté de https://github.com/PowerShell/PowerShell-Tests Param ( [ValidateNotNullOrEmpty()] [Parameter(Position=0, Mandatory=$true,ValueFromPipeline = $true)] [type] $Type ) Process { $attrs = @($Type.Assembly.GetCustomAttributes($true)) $result = @($attrs | Where { $_ -is [System.Management.Automation.DynamicClassImplementationAssemblyAttribute] }) return ($result.Count -eq 1) } } function Write-CUClassDiagram { <# .SYNOPSIS This script allows to document automatically existing script(s)/module(s) containing classes by generating the corresponding UML Diagram. .DESCRIPTION Automatically generate a UML diagram of scripts/Modules that contain powershell classes. .PARAMETER Path The path that contains the classes that need to be documented. The path parameter should point to either a .ps1, .psm1 file, or a directory containing either/both of those file types. .PARAMETER ExportFolder This optional parameter, allows to specifiy an alternative export folder. By default, the diagram is created in the same folder as the source file. .PARAMETER OutPutFormat Using the parameter OutputFormat, it is possible change the default output format (.png) to one of the following ones: 'jpg', 'png', 'gif', 'imap', 'cmapx', 'jp2', 'json', 'pdf', 'plain', 'dot' .PARAMETER OutPutType OutPutType is a Set of 2 variables: Combined, Unique Combined, all files present in a directory are drawn in the same graph. Unique, all files present in a directory are drawn in their own graph. .PARAMETER Show Open's the generated diagram immediatly .PARAMETER IgnoreCase By default, Class names MUST be case identical to have the Write-CUClassDiagram cmdlet generate the correct inheritence tree. When the switch -IgnoreCase is specified, All class names will be converted to 'Titlecase' to force the case, and ensure the inheritence is correctly drawed in the Class Diagram. .PARAMETER PassThru When specified, the raw Graph in GraphViz format will be returned back in String format. .PARAMETER Recurse Dynamic Parameter, available only if the Path Parameter is a Directory containing other directories. If the parameter is used, all subfolders will be parsed. .EXAMPLE #Generate a UML diagram of the classes located in MyClass.Ps1 # The diagram will be automatically created in the same folder as the file that contains the classes (C:\Classes). Write-CUClassDiagram.ps1 -File C:\Classes\MyClass.ps1 .EXAMPLE #Various output formats are available using the parameter "OutPutFormat" Write-CUClassDiagram.ps1 -File C:\Classes\Logging.psm1 -ExportFolder C:\admin\ -OutputFormat gif Directory: C:\admin Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 12.06.2018 07:47 58293 Logging.gif .EXAMPLE Write-CUClassDiagram -Path "C:\Modules\PSClassUtils\Classes\Private\" -Show Will generate a diagram of all the private classes available in the Path specified, and immediatley show the diagram. .NOTES Author: Stephanevg / LxLeChat www: https://github.com/Stephanevg https://github.com/LxLeChat Report bugs or ask for feature requests here: https://github.com/Stephanevg/PsClassUtils .LINK https://github.com/Stephanevg/PsClassUtils #> [CmdletBinding()] param ( [Alias("FullName")] [Parameter(Mandatory=$True)] [String]$Path, [Parameter(Mandatory=$False)] [ValidateSet('Unique','Combined')] $OutPutType = 'Combined', [Parameter(Mandatory=$False)] [ValidateSet('jpg', 'png', 'gif', 'imap', 'cmapx', 'jp2', 'json', 'pdf', 'plain', 'dot')] [string]$OutputFormat = 'png', [Parameter(Mandatory=$False)] [ValidateScript({ Test-Path $_ })] [String]$ExportFolder, [Parameter(Mandatory=$False)] [Switch]$IgnoreCase, [Parameter(Mandatory=$False)] [Switch]$ShowComposition, [Parameter(Mandatory=$False)] [Switch]$Show, [Parameter(Mandatory = $false)] [Switch] $PassThru, [Parameter(Mandatory = $False)] [String[]]$Exclude ) ## Recurse Parameter should be present only when Path Parameter is a directory, and has child directories ## Otherwise Recurse Parameter is Useless DynamicParam{ $DynamicParams=New-Object System.Management.Automation.RuntimeDefinedParameterDictionary $PathItem = get-item $PSBoundParameters['Path'] If ( ($PathItem -is [System.Io.DirectoryInfo]) -and ((Get-ChildItem -Path $PathItem -Directory).Count -gt 0) ) { $ParameterName = "Recurse" $ParameterAttributes = New-Object System.Management.Automation.ParameterAttribute $Parameter = New-Object System.Management.Automation.RuntimeDefinedParameter $ParameterName,switch,$ParameterAttributes $DynamicParams.Add($ParameterName,$Parameter) return $DynamicParams } } Begin { <# The begining #> ## Check Exclude Parameters, Wildcard is only allowed when Exclude contains One item If ( $null -ne $MyInvocation.BoundParameters.Exclude ) { If ( $MyInvocation.BoundParameters.Exclude.count -eq 1 ) { If ( $MyInvocation.BoundParameters.Exclude -notmatch '^*?\w+\*?$' ) { Throw "Wildcard must be positionned at the end of your item..." } } If ( $MyInvocation.BoundParameters.Exclude.count -gt 1 ) { If ( (@($MyInvocation.BoundParameters.Exclude) -notmatch '^\w+$').Count -gt 0 ) { throw "One of your Exclude item contains a wildcard... Wildcard is only allowed on one item..." } } } } Process { ## Depending on the Type of the Path Parameter... File or Directory, other (default) $PathItem = Get-Item $PSBoundParameters['Path'] Switch ( $PathItem ) { { $PSItem -is [System.Io.FileInfo] } { Write-Verbose "Write-CuClassDiagram -> Dealing with a File..." ## Looking for Classes $Classes = Find-CUClass -Item $PSitem -Exclude $PSBoundParameters['Exclude'] If ( $Null -ne $Classes ) { $GraphParams = New-CUGraphParameters -InputObject $Classes -IgnoreCase $PSBoundParameters['IgnoreCase'] -ShowComposition $PSBoundParameters['ShowComposition'] If ( $PSBoundParameters['ExportFolder'] ) ## Export must be made in a specified folder { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath $PSitem.BaseName -OutputFormat $OutputFormat -Show } Else ## Show switch not used { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath $PSitem.BaseName -OutputFormat $OutputFormat } } Else ## Export must be in the same directory { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSitem.Directory -ChildPath $PSitem.BaseName -OutputFormat $OutputFormat -Show } Else ## Show Switch not used { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSitem.Directory -ChildPath $PSitem.BaseName -OutputFormat $OutputFormat } } } ## Empty class variable, not a class file } ## Not a file { $PSItem -is [System.Io.DirectoryInfo] } { Write-Verbose "Write-CuClassDiagram -> Dealing with a Directory..." If ( $PSBoundParameters['Recurse'] ) { Write-Verbose "Write-CuClassDiagram -> Recurse parameter used..." ## If OutPutType is not specified, we must use the default value, wich is Combined If ( $OutPutType -eq 'Combined' ) { Write-Verbose "Write-CuClassDiagram -> OutPutType Per Directory..." Foreach ( $Directory in $(Get-ChildItem -path $PSItem -Directory -Recurse) ) { $Classes = Find-CUClass -Item $($Directory.FullName+'\*') -Exclude $PSBoundParameters['Exclude'] ## If ( $Null -ne $Classes ) { $GraphParams = New-CUGraphParameters -InputObject $Classes -IgnoreCase $PSBoundParameters['IgnoreCase'] -ShowComposition $PSBoundParameters['ShowComposition'] If ( $PSBoundParameters['ExportFolder'] ) { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath $Directory.Name -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath $Directory.Name -OutputFormat $OutputFormat } } Else { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $Directory.FullName -ChildPath $Directory.Name -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $Directory.FullName -ChildPath $Directory.Name -OutputFormat $OutputFormat } } } ## No Classe(s) found, Next directory please .. ##> } ## No more directories to parse } ## Option Combined for OutPutType was not specified If ( $OutPutType -eq 'Unique' ) { Write-Verbose "Write-CuClassDiagram -> OutPutType Per File..." Foreach ( $Directory in $(Get-ChildItem -path $PSItem -Directory -Recurse) ) { $Classes = Find-CUClass -Item $($Directory.FullName+'\*') -Exclude $PSBoundParameters['Exclude'] If ( $Null -ne $Classes ) { Foreach ( $Group in $Classes ) { $GraphParams = New-CUGraphParameters -InputObject $Group -IgnoreCase $PSBoundParameters['IgnoreCase'] -ShowComposition $PSBoundParameters['ShowComposition'] If ( $PSBoundParameters['ExportFolder'] ) { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat } } Else { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path (get-item $group.name).Directory -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path (get-item $group.name).Directory -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat } } } } ## No Classes found } ## Foreach directory } ## Unique } Else { Write-Verbose "Write-CuClassDiagram -> Recurse Parameter NOT specified..." $Classes = Find-CUClass -Item (""+$PSitem.FullName+"\*") -Exclude $PSBoundParameters['Exclude'] If ( $Null -ne $Classes ) { Write-Verbose "Write-CuClassDiagram -> $($Classes.Count) Class(es) were found..." ## If OutPutType is not specified, we must use the default value, wich is Combined If ( $OutPutType -eq 'Combined') { Write-Verbose "Write-CuClassDiagram -> OutPutType Per Directory..." $GraphParams = New-CUGraphParameters -InputObject $Classes -IgnoreCase $PSBoundParameters['IgnoreCase'] -ShowComposition $PSBoundParameters['ShowComposition'] If ( $PSBoundParameters['ExportFolder'] ) { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath $PSItem.Name -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath $PSItem.Name -OutputFormat $OutputFormat } } Else { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSItem.FullName -ChildPath $PSitem.Name -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSItem.FullName -ChildPath $PSitem.Name -OutputFormat $OutputFormat } } } If ( $OutPutType -eq 'Unique' ) { Write-Verbose "Write-CuClassDiagram -> OutPutType Per File..." Foreach ( $Group in $Classes ) { $GraphParams = New-CUGraphParameters -InputObject $Group -IgnoreCase $PSBoundParameters['IgnoreCase'] -ShowComposition $PSBoundParameters['ShowComposition'] If ( $PSBoundParameters['ExportFolder'] ) { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path $PSBoundParameters['ExportFolder'] -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat } } Else { If ( $PSBoundParameters['show'] ) { ## Show Switch used New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path (get-item $group.name).Directory -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat -Show } Else { New-CUGraphExport -Graph $GraphParams -PassThru $PSBoundParameters['PassThru'] -Path (get-item $group.name).Directory -ChildPath (get-item $group.name).BaseName -OutputFormat $OutputFormat } } } } } ## No Classes found } ## Not a directory nor a file } ## Not a directory .. it's something else ... ! Default { Throw 'Path Parameter must be a file or a directory...' } ## Bye bye } } End { <# The end #> } } Function Write-CUPesterTests { <# .SYNOPSIS Generates Pester tests automatically for PowerShell Classes .DESCRIPTION Creates a Describe block for the class constructors, and for the Class Methods. Each of the describe block will contain child 'it' blocks which contains the corresponding tests. For each Method and Constructor the following tests will be created: 1) test to ensure that the command doesn't throw 2) for methods, it will first create an instance (using a parameterless constructor by default), then check if the return type is of the right type (for voided methods, it will check that nothing is returned.) 3) For Static Methods, it will check it will Check that when it is called, it doens't throws an error, and validated the return type is correct. (For voided methods it will check that nothing is returned.) .PARAMETER Path The Path parameter is mandatory. Must point to *.ps1 or *.psm1 file. The files must contain powershell classes. .EXAMPLE # The File C:\plop.ps1 MUST contain at least one class. Write-CUPesterTests -Path C:\plop.ps1 #Generates a C:\plop.Tests.Ps1 file with pester tests in it. .EXAMPLE Write-CUPesterTests -Path C:\plop.ps1 -Verbose VERBOSE: [PSClassUtils][Write-CUPesterTests] Generating tests for C:\Plop.ps1 VERBOSE: [PSClassUtils][Write-CUPesterTests][Woop] Starting tests Generating process for class --> [Woop] VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop][Constructors] Generating 'Describe' block for Constructors VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop][Constructors] Generating 'IT' blocks VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop] --> [Woop]::new() VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop] --> [Woop]::new([String]String,[int]Number) VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop][Methods] VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop] --> DoSomething() VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop] --> TrickyMethod($Salutations,$IsthatTrue) VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop] --> VoidedMethod() VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Woop] --> MyStaticMethod() VERBOSE: [PSClassUtils][Write-CUPesterTests]--> [Export] -->Exporting tests file to: Microsoft.PowerShell.Core\FileSystem::C:\Plop.Tests.Ps1 .EXAMPLE Write-CUPesterTests -Path C:\plop.ps1 -IgnoreParameterLessConstructor #This example will return create all the tests, except for the parameterLess constructor (which can be usefull for inheritence / 'interface' situations.) .INPUTS File containing Classes. Or folder containing files that contain classes. .OUTPUTS Void Or When Passthru is specified [Directory.IO.FileInfo] .NOTES Author: Stéphane van Gulick Version: 0.4.0 .LINK https://github.com/Stephanevg/PsClassUtils #> [cmdletBinding()] Param( $Path = (Throw "Path is mandatory. Please specifiy a Path to a .ps1 a .psm1 file or a folder containing one or more of these file types."), [System.IO.DirectoryInfo]$ExportFolderPath, [Switch]$IgnoreParameterLessConstructor, [Switch]$Combine, [Switch]$Passthru ) $PathObject = Get-Item $Path if ($PathObject -is [System.IO.DirectoryInfo]) { $Classes = gci $PathObject | Get-CUClass } elseif ($PathObject -is [System.IO.FileInfo]) { $Classes = Get-CUClass -Path $PathObject.FullName } $AllFiles = $Classes | Group-Object -Property Path $PesterTest = $null $sb = [System.Text.StringBuilder]::new() $CombineCount = 0 Foreach ($File in $AllFiles) { Write-verbose "[PSClassUtils][Write-CUPesterTests] Generating tests for $($File.Name)" $Header = "" if ($File.Name.EndsWith(".psm1")) { If ($CombineCount -eq 0) { $Header = "using module $($File.Name)" } } else { $Header = ". $($File.Name)" } #Optional Context blocks #Creating Describe Block [void]$sb.AppendLine($Header) Foreach ($Class in $File.Group) { Write-verbose "[PSClassUtils][Write-CUPesterTests][$($Class.Name)] Starting tests Generating process for class --> [$($Class.Name)]" Write-verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)][Constructors] Generating 'Describe' block for Constructors" $StartDescribeBlock = "Describe '[$($Class.Name)]-[Constructors]'{" [void]$sb.AppendLine($StartDescribeBlock) If (!($Class.Constructor)) { Write-verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)][Constructors] No overloaded Constructor to process" } else { Write-verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)][Constructors] Generating 'IT' blocks" #Creating itBlocks Foreach ($Constructor in $Class.Constructor) { $ConstructorIsParameterLess = $False #Constructors #$Constructor $Parstr = "" $SignatureRaw = "" foreach ($p in $Constructor.Parameter) { $Parstr = $Parstr + '$' + $p.Name + "," $SignatureRaw = $SignatureRaw + $p.Type + $p.Name + "," } $Signature = "(" + $SignatureRaw.Trim(",") + ")" $Parstr = $Parstr.trim(",") if ($Parstr) { $CallEnd = "(" + $Parstr + ")" } else { $ConstructorIsParameterLess = $true $CallEnd = "()" If($IgnoreParameterLessConstructor){ Write-verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)] `$IgnoreParameterLessConstructor detected! Parameterless constructor has been ignored" Continue } } Write-verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)] --> [$($Class.Name)]::new$($Signature)" If($ConstructorIsParameterLess){ $ItBlock = "It '[$($Class.Name)]-[Constructor] - Parameterless should Not Throw' {" }Else{ $ItBlock = "It '[$($Class.Name)]-[Constructor]$($Signature) should Not Throw' {" } [void]$sb.AppendLine($ItBlock) [void]$sb.AppendLine("") [void]$sb.AppendLine("# -- Arrange") [void]$sb.AppendLine("") if(!($ConstructorIsParameterLess)){ foreach ($p in $Constructor.Parameter) { [void]$sb.AppendLine("") [void]$sb.AppendLine('$' + $p.Name + "=" + "''") [void]$sb.AppendLine("") } } [void]$sb.AppendLine("# -- Act") [void]$sb.AppendLine("") [void]$sb.AppendLine("# -- Assert") [void]$sb.AppendLine("") $ConstructorCallBody = "{[$($Class.Name)]::New" + "$($CallEnd)}" [void]$sb.Append($ConstructorCallBody) $TestToExecute = " | Should Not Throw " [void]$sb.AppendLine($TestToExecute) [void]$sb.AppendLine("") [void]$sb.AppendLine("}# end of it block") [void]$sb.AppendLine("") } #Foreach Constructor } [void]$sb.AppendLine("") [void]$sb.AppendLine("}# end of Describe block") } If (!($Class.Method)) { Write-verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)] --> No Methods to process" }else{ Write-verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)][Methods]" [void]$sb.AppendLine("Describe '[$($Class.Name)]-[Methods]'{") [void]$sb.AppendLine("") Foreach ($Method in $class.Method) { $MethodIsParameterLess = $False $Parstr = "" $SignatureRaw = "" foreach ($p in $Method.Parameter) { $Parstr = $Parstr + $p.Name + "," $SignatureRaw = $SignatureRaw + '$' + $p.Name + "," } $Parstr = $Parstr.trim(",") $SignatureRaw = $SignatureRaw.trim(",") $MethodCall = "" $MethodCallBody = "[$($Class.Name)]$($Method.Name)" $MethodCallEnd = "" if ($Parstr) { $MethodCallEnd = "(" + $SignatureRaw + ")" } else { $MethodIsParameterLess = $True $MethodCallEnd += "()" } $REturnType = $Method.ReturnType.Extent.Text $Signature = "($SignatureRaw)" if ($Method.IsStatic()) { $MethodCall = $MethodCallBody.Replace("]", "]::") + $MethodCallEnd } else { $MethodCall = '$Instance.' + $($Method.Name) + $MethodCallEnd } $MethodCallEnd = "" if ($Method.IsHidden) { $visibility = "#Hidden Method" } else { $visibility = "#Public Method" } Write-Verbose "[PSClassUtils][Write-CUPesterTests]--> [$($Class.Name)] --> $($Method.Name)$($Signature)" [void]$sb.AppendLine($visibility) [void]$sb.AppendLine("It '[$($Class.Name)] --> $($Method.Name)$($Signature) : $($Method.ReturnType) - should Not Throw' {") [void]$sb.AppendLine("") [void]$sb.AppendLine("# -- Arrange") [void]$sb.AppendLine("") If(!($MethodIsParameterLess)){ foreach ($parameter in $Method.Parameter) { If ($parameter.Type) { [void]$sb.AppendLine($parameter.Type + "$" + $parameter.Name + " = ''") } else { [void]$sb.AppendLine("$" + $parameter.Name + " = ''") } [void]$sb.AppendLine("") } }Else{ } [void]$sb.AppendLine("# -- Act") [void]$sb.AppendLine("") if (!($Method.IsStatic())) { [void]$sb.AppendLine('$' + "Instance = [$($Class.Name)]::New()") [void]$sb.AppendLine("") }else{ } [void]$sb.AppendLine("# -- Assert") [void]$sb.AppendLine("") [void]$sb.AppendLine("{$MethodCall} | Should Not Throw") [void]$sb.AppendLine("") [void]$sb.AppendLine("} #End It Block") [void]$sb.AppendLine("") [void]$sb.AppendLine($visibility) If ($Method.ReturnType -eq '[void]' -or $Null -eq $Method.ReturnType) { [void]$sb.AppendLine("It '[$($Class.Name)] --> $($Method.Name)$($Signature) Should not return anything (voided)' {") } else { $ReturnType = $Method.ReturnType.Replace("[", "").Replace("]", "") [void]$sb.AppendLine("It '[$($Class.Name)] --> $($Method.Name)$($Signature) should return type [$($ReturnType)]' {") } [void]$sb.AppendLine("") [void]$sb.AppendLine("# -- Arrange") [void]$sb.AppendLine("") [void]$sb.AppendLine("# -- Act") [void]$sb.AppendLine("") if (!($Method.IsStatic())) { [void]$sb.AppendLine('$' + "Instance = [$($Class.Name)]::New()") } [void]$sb.AppendLine("# -- Assert") [void]$sb.AppendLine("") If ($Method.ReturnType -eq '[void]' -or $Null -eq $Method.ReturnType) { [void]$sb.AppendLine("$MethodCall" + '| should be $null') } else { [void]$sb.AppendLine("($MethodCall).GetType().Name | should be $ReturnType") } [void]$sb.AppendLine("") [void]$sb.AppendLine("} #End It Block") [void]$sb.AppendLine("") } #Foreach Method } #Closing Describe Block [void]$sb.AppendLine("}#EndDescribeBlock") $Item = Get-Item $File.Name $ExportFilename = $Item.Name.Replace($Item.Extension, ".Tests.Ps1") if ($ExportFolderPath) { $ExportFullPath = Join-Path $ExportFolder -ChildPath $ExportFilename } else { $ExportFullPath = Join-Path $Item.PSParentPath -ChildPath $ExportFilename } $TestfileName = $File write-verbose "[PSClassUtils][Write-CUPesterTests]--> [Export] -->Exporting tests file to: $($ExportFullPath)" $sb.ToString() | out-file -FilePath $ExportFullPath -Encoding utf8 If($Passthru){ Get-Item $ExportFullPath } }#End Foreach File } |