File size: 80,461 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Text;
using System.Text.RegularExpressions;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Context information about a match.
/// </summary>
public sealed class MatchInfoContext : ICloneable
{
internal MatchInfoContext()
{
}
/// <summary>
/// Gets or sets the lines found before a match.
/// </summary>
public string[] PreContext { get; set; }
/// <summary>
/// Gets or sets the lines found after a match.
/// </summary>
public string[] PostContext { get; set; }
/// <summary>
/// Gets or sets the lines found before a match. Does not include
/// overlapping context and thus can be used to
/// display contiguous match regions.
/// </summary>
public string[] DisplayPreContext { get; set; }
/// <summary>
/// Gets or sets the lines found after a match. Does not include
/// overlapping context and thus can be used to
/// display contiguous match regions.
/// </summary>
public string[] DisplayPostContext { get; set; }
/// <summary>
/// Produce a deep copy of this object.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
public object Clone()
{
return new MatchInfoContext()
{
PreContext = (string[])PreContext?.Clone(),
PostContext = (string[])PostContext?.Clone(),
DisplayPreContext = (string[])DisplayPreContext?.Clone(),
DisplayPostContext = (string[])DisplayPostContext?.Clone()
};
}
}
/// <summary>
/// The object returned by select-string representing the result of a match.
/// </summary>
public class MatchInfo
{
private static readonly string s_inputStream = "InputStream";
/// <summary>
/// Gets or sets a value indicating whether the match was done ignoring case.
/// </summary>
/// <value>True if case was ignored.</value>
public bool IgnoreCase { get; set; }
/// <summary>
/// Gets or sets the number of the matching line.
/// </summary>
/// <value>The number of the matching line.</value>
public ulong LineNumber { get; set; }
/// <summary>
/// Gets or sets the text of the matching line.
/// </summary>
/// <value>The text of the matching line.</value>
public string Line { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether the matched portion of the string is highlighted.
/// </summary>
/// <value>Whether the matched portion of the string is highlighted with the negative VT sequence.</value>
private readonly bool _emphasize;
/// <summary>
/// Stores the starting index of each match within the line.
/// </summary>
private readonly IReadOnlyList<int> _matchIndexes;
/// <summary>
/// Stores the length of each match within the line.
/// </summary>
private readonly IReadOnlyList<int> _matchLengths;
/// <summary>
/// Initializes a new instance of the <see cref="MatchInfo"/> class with emphasis disabled.
/// </summary>
public MatchInfo()
{
this._emphasize = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="MatchInfo"/> class with emphasized matched text.
/// Used when virtual terminal sequences are supported.
/// </summary>
/// <param name="matchIndexes">Sets the matchIndexes.</param>
/// <param name="matchLengths">Sets the matchLengths.</param>
public MatchInfo(IReadOnlyList<int> matchIndexes, IReadOnlyList<int> matchLengths)
{
this._emphasize = true;
this._matchIndexes = matchIndexes;
this._matchLengths = matchLengths;
}
/// <summary>
/// Gets the base name of the file containing the matching line.
/// </summary>
/// <remarks>
/// It will be the string "InputStream" if the object came from the input stream.
/// This is a readonly property calculated from the path <see cref="Path"/>.
/// </remarks>
/// <value>The file name.</value>
public string Filename
{
get
{
if (!_pathSet)
{
return s_inputStream;
}
return _filename ??= System.IO.Path.GetFileName(_path);
}
}
private string _filename;
/// <summary>
/// Gets or sets the full path of the file containing the matching line.
/// </summary>
/// <remarks>
/// It will be "InputStream" if the object came from the input stream.
/// </remarks>
/// <value>The path name.</value>
public string Path
{
get => _pathSet ? _path : s_inputStream;
set
{
_path = value;
_pathSet = true;
}
}
private string _path = s_inputStream;
private bool _pathSet;
/// <summary>
/// Gets or sets the pattern that was used in the match.
/// </summary>
/// <value>The pattern string.</value>
public string Pattern { get; set; }
/// <summary>
/// Gets or sets context for the match, or null if -context was not specified.
/// </summary>
public MatchInfoContext Context { get; set; }
/// <summary>
/// Returns the path of the matching file truncated relative to the <paramref name="directory"/> parameter.
/// </summary>
/// <remarks>
/// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo
/// the routine would return bar\baz.c .
/// </remarks>
/// <param name="directory">The directory base the truncation on.</param>
/// <returns>The relative path that was produced.</returns>
public string RelativePath(string directory)
{
if (!_pathSet)
{
return this.Path;
}
string relPath = _path;
if (!string.IsNullOrEmpty(directory))
{
if (relPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase))
{
int offset = directory.Length;
if (offset < relPath.Length)
{
if (directory[offset - 1] == '\\' || directory[offset - 1] == '/')
{
relPath = relPath.Substring(offset);
}
else if (relPath[offset] == '\\' || relPath[offset] == '/')
{
relPath = relPath.Substring(offset + 1);
}
}
}
}
return relPath;
}
private const string MatchFormat = "{0}{1}:{2}:{3}";
private const string SimpleFormat = "{0}{1}";
// Prefixes used by formatting: Match and Context prefixes
// are used when context-tracking is enabled, otherwise
// the empty prefix is used.
private const string MatchPrefix = "> ";
private const string ContextPrefix = " ";
private const string EmptyPrefix = "";
/// <summary>
/// Returns the string representation of this object. The format
/// depends on whether a path has been set for this object or not.
/// </summary>
/// <remarks>
/// If the path component is set, as would be the case when matching
/// in a file, ToString() would return the path, line number and line text.
/// If path is not set, then just the line text is presented.
/// </remarks>
/// <returns>The string representation of the match object.</returns>
public override string ToString()
{
return ToString(null);
}
/// <summary>
/// Returns the string representation of the match object same format as ToString()
/// but trims the path to be relative to the <paramref name="directory"/> argument.
/// </summary>
/// <param name="directory">Directory to use as the root when calculating the relative path.</param>
/// <returns>The string representation of the match object.</returns>
public string ToString(string directory)
{
return ToString(directory, Line);
}
/// <summary>
/// Returns the string representation of the match object with the matched line passed
/// in as <paramref name="line"/> and trims the path to be relative to
/// the<paramref name="directory"/> argument.
/// </summary>
/// <param name="directory">Directory to use as the root when calculating the relative path.</param>
/// <param name="line">Line that the match occurs in.</param>
/// <returns>The string representation of the match object.</returns>
private string ToString(string directory, string line)
{
string displayPath = (directory != null) ? RelativePath(directory) : _path;
// Just return a single line if the user didn't
// enable context-tracking.
if (Context == null)
{
return FormatLine(line, this.LineNumber, displayPath, EmptyPrefix);
}
// Otherwise, render the full context.
List<string> lines = new(Context.DisplayPreContext.Length + Context.DisplayPostContext.Length + 1);
ulong displayLineNumber = this.LineNumber - (ulong)Context.DisplayPreContext.Length;
foreach (string contextLine in Context.DisplayPreContext)
{
lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix));
}
lines.Add(FormatLine(line, displayLineNumber++, displayPath, MatchPrefix));
foreach (string contextLine in Context.DisplayPostContext)
{
lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix));
}
return string.Join(System.Environment.NewLine, lines.ToArray());
}
/// <summary>
/// Returns the string representation of the match object same format as ToString()
/// and inverts the color of the matched text if virtual terminal is supported.
/// </summary>
/// <param name="directory">Directory to use as the root when calculating the relative path.</param>
/// <returns>The string representation of the match object with matched text inverted.</returns>
public string ToEmphasizedString(string directory)
{
if (!_emphasize)
{
return ToString(directory);
}
return ToString(directory, EmphasizeLine());
}
/// <summary>
/// Surrounds the matched text with virtual terminal sequences to invert it's color. Used in ToEmphasizedString.
/// </summary>
/// <returns>The matched line with matched text inverted.</returns>
private string EmphasizeLine()
{
string invertColorsVT100 = PSStyle.Instance.Reverse;
string resetVT100 = PSStyle.Instance.Reset;
char[] chars = new char[(_matchIndexes.Count * (invertColorsVT100.Length + resetVT100.Length)) + Line.Length];
int lineIndex = 0;
int charsIndex = 0;
for (int i = 0; i < _matchIndexes.Count; i++)
{
// Adds characters before match
Line.CopyTo(lineIndex, chars, charsIndex, _matchIndexes[i] - lineIndex);
charsIndex += _matchIndexes[i] - lineIndex;
lineIndex = _matchIndexes[i];
// Adds opening vt sequence
invertColorsVT100.CopyTo(0, chars, charsIndex, invertColorsVT100.Length);
charsIndex += invertColorsVT100.Length;
// Adds characters being emphasized
Line.CopyTo(lineIndex, chars, charsIndex, _matchLengths[i]);
lineIndex += _matchLengths[i];
charsIndex += _matchLengths[i];
// Adds closing vt sequence
resetVT100.CopyTo(0, chars, charsIndex, resetVT100.Length);
charsIndex += resetVT100.Length;
}
// Adds remaining characters in line
Line.CopyTo(lineIndex, chars, charsIndex, Line.Length - lineIndex);
return new string(chars);
}
/// <summary>
/// Formats a line for use in ToString.
/// </summary>
/// <param name="lineStr">The line to format.</param>
/// <param name="displayLineNumber">The line number to display.</param>
/// <param name="displayPath">The file path, formatted for display.</param>
/// <param name="prefix">The match prefix.</param>
/// <returns>The formatted line as a string.</returns>
private string FormatLine(string lineStr, ulong displayLineNumber, string displayPath, string prefix)
{
return _pathSet
? StringUtil.Format(MatchFormat, prefix, displayPath, displayLineNumber, lineStr)
: StringUtil.Format(SimpleFormat, prefix, lineStr);
}
/// <summary>
/// Gets or sets a list of all Regex matches on the matching line.
/// </summary>
public Match[] Matches { get; set; } = Array.Empty<Match>();
/// <summary>
/// Create a deep copy of this MatchInfo instance.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
internal MatchInfo Clone()
{
// Just do a shallow copy and then deep-copy the
// fields that need it.
MatchInfo clone = (MatchInfo)this.MemberwiseClone();
if (clone.Context != null)
{
clone.Context = (MatchInfoContext)clone.Context.Clone();
}
// Regex match objects are immutable, so we can get away
// with just copying the array.
clone.Matches = (Match[])clone.Matches.Clone();
return clone;
}
}
/// <summary>
/// A cmdlet to search through strings and files for particular patterns.
/// </summary>
[Cmdlet(VerbsCommon.Select, "String", DefaultParameterSetName = ParameterSetFile, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097119")]
[OutputType(typeof(bool), typeof(MatchInfo), ParameterSetName = new[] { ParameterSetFile, ParameterSetObject, ParameterSetLiteralFile })]
[OutputType(typeof(string), ParameterSetName = new[] { ParameterSetFileRaw, ParameterSetObjectRaw, ParameterSetLiteralFileRaw })]
public sealed class SelectStringCommand : PSCmdlet
{
private const string ParameterSetFile = "File";
private const string ParameterSetFileRaw = "FileRaw";
private const string ParameterSetObject = "Object";
private const string ParameterSetObjectRaw = "ObjectRaw";
private const string ParameterSetLiteralFile = "LiteralFile";
private const string ParameterSetLiteralFileRaw = "LiteralFileRaw";
/// <summary>
/// A generic circular buffer.
/// </summary>
/// <typeparam name="T">The type of items that are buffered.</typeparam>
private sealed class CircularBuffer<T> : ICollection<T>
{
// Ring of items
private readonly T[] _items;
// Current length, as opposed to the total capacity
// Current start of the list. Starts at 0, but may
// move forwards or wrap around back to 0 due to
// rotation.
private int _firstIndex;
/// <summary>
/// Initializes a new instance of the <see cref="CircularBuffer{T}"/> class.
/// </summary>
/// <param name="capacity">The maximum capacity of the buffer.</param>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="capacity"/> is negative.</exception>
public CircularBuffer(int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
_items = new T[capacity];
Clear();
}
/// <summary>
/// Gets the maximum capacity of the buffer. If more items
/// are added than the buffer has capacity for, then
/// older items will be removed from the buffer with
/// a first-in, first-out policy.
/// </summary>
public int Capacity => _items.Length;
/// <summary>
/// Whether or not the buffer is at capacity.
/// </summary>
public bool IsFull => Count == Capacity;
/// <summary>
/// Convert from a 0-based index to a buffer index which
/// has been properly offset and wrapped.
/// </summary>
/// <param name="zeroBasedIndex">The index to wrap.</param>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="zeroBasedIndex"/> is out of range.</exception>
/// <returns>
/// The actual index that <paramref name="zeroBasedIndex"/>
/// maps to.
/// </returns>
private int WrapIndex(int zeroBasedIndex)
{
if (Capacity == 0 || zeroBasedIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(zeroBasedIndex));
}
return (zeroBasedIndex + _firstIndex) % Capacity;
}
#region IEnumerable<T> implementation.
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
{
yield return _items[WrapIndex(i)];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
#endregion
#region ICollection<T> implementation
public int Count { get; private set; }
public bool IsReadOnly => false;
/// <summary>
/// Adds an item to the buffer. If the buffer is already
/// full, the oldest item in the list will be removed,
/// and the new item added at the logical end of the list.
/// </summary>
/// <param name="item">The item to add.</param>
public void Add(T item)
{
if (Capacity == 0)
{
return;
}
int itemIndex;
if (IsFull)
{
itemIndex = _firstIndex;
_firstIndex = (_firstIndex + 1) % Capacity;
}
else
{
itemIndex = _firstIndex + Count;
Count++;
}
_items[itemIndex] = item;
}
public void Clear()
{
_firstIndex = 0;
Count = 0;
}
public bool Contains(T item)
{
throw new NotImplementedException();
}
public void CopyTo(T[] array, int arrayIndex)
{
ArgumentNullException.ThrowIfNull(array);
ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
if (Count > (array.Length - arrayIndex))
{
throw new ArgumentException("arrayIndex");
}
// Iterate through the buffer in correct order.
foreach (T item in this)
{
array[arrayIndex++] = item;
}
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
#endregion
/// <summary>
/// Create an array of the items in the buffer. Items
/// will be in the same order they were added.
/// </summary>
/// <returns>The new array.</returns>
public T[] ToArray()
{
T[] result = new T[Count];
CopyTo(result, 0);
return result;
}
/// <summary>
/// Access an item in the buffer. Indexing is based off
/// of the order items were added, rather than any
/// internal ordering the buffer may be maintaining.
/// </summary>
/// <param name="index">The index of the item to access.</param>
/// <returns>The buffered item at index <paramref name="index"/>.</returns>
public T this[int index]
{
get
{
if (!(index >= 0 && index < Count))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return _items[WrapIndex(index)];
}
}
}
/// <summary>
/// An interface to a context tracking algorithm.
/// </summary>
private interface IContextTracker
{
/// <summary>
/// Gets matches with completed context information
/// that are ready to be emitted into the pipeline.
/// </summary>
IList<MatchInfo> EmitQueue { get; }
/// <summary>
/// Track a non-matching line for context.
/// </summary>
/// <param name="line">The line to track.</param>
void TrackLine(string line);
/// <summary>
/// Track a matching line.
/// </summary>
/// <param name="match">The line to track.</param>
void TrackMatch(MatchInfo match);
/// <summary>
/// Track having reached the end of the file,
/// giving the tracker a chance to process matches with
/// incomplete context information.
/// </summary>
void TrackEOF();
}
/// <summary>
/// A state machine to track display context for each match.
/// </summary>
private sealed class DisplayContextTracker : IContextTracker
{
private enum ContextState
{
InitialState,
CollectPre,
CollectPost,
}
private ContextState _contextState = ContextState.InitialState;
private readonly int _preContext;
private readonly int _postContext;
// The context leading up to the match.
private readonly CircularBuffer<string> _collectedPreContext;
// The context after the match.
private readonly List<string> _collectedPostContext;
// Current match info we are tracking postcontext for.
// At any given time, if set, this value will not be
// in the emitQueue but will be the next to be added.
private MatchInfo _matchInfo = null;
/// <summary>
/// Initializes a new instance of the <see cref="DisplayContextTracker"/> class.
/// </summary>
/// <param name="preContext">How much preContext to collect at most.</param>
/// <param name="postContext">How much postContext to collect at most.</param>
public DisplayContextTracker(int preContext, int postContext)
{
_preContext = preContext;
_postContext = postContext;
_collectedPreContext = new CircularBuffer<string>(preContext);
_collectedPostContext = new List<string>(postContext);
_emitQueue = new List<MatchInfo>();
Reset();
}
#region IContextTracker implementation
public IList<MatchInfo> EmitQueue => _emitQueue;
private readonly List<MatchInfo> _emitQueue;
// Track non-matching line
public void TrackLine(string line)
{
switch (_contextState)
{
case ContextState.InitialState:
break;
case ContextState.CollectPre:
_collectedPreContext.Add(line);
break;
case ContextState.CollectPost:
// We're not done collecting post-context.
_collectedPostContext.Add(line);
if (_collectedPostContext.Count >= _postContext)
{
// Now we're done.
UpdateQueue();
}
break;
}
}
// Track matching line
public void TrackMatch(MatchInfo match)
{
// Update the queue in case we were in the middle
// of collecting postcontext for an older match...
if (_contextState == ContextState.CollectPost)
{
UpdateQueue();
}
// Update the current matchInfo.
_matchInfo = match;
// If postContext is set, then we need to hold
// onto the match for a while and gather context.
// Otherwise, immediately move the match onto the queue
// and let UpdateQueue update our state instead.
if (_postContext > 0)
{
_contextState = ContextState.CollectPost;
}
else
{
UpdateQueue();
}
}
// Track having reached the end of the file.
public void TrackEOF()
{
// If we're in the middle of collecting postcontext, we
// already have a match and it's okay to queue it up
// early since there are no more lines to track context
// for.
if (_contextState == ContextState.CollectPost)
{
UpdateQueue();
}
}
#endregion
/// <summary>
/// Moves matchInfo, if set, to the emitQueue and
/// resets the tracking state.
/// </summary>
private void UpdateQueue()
{
if (_matchInfo != null)
{
_emitQueue.Add(_matchInfo);
if (_matchInfo.Context != null)
{
_matchInfo.Context.DisplayPreContext = _collectedPreContext.ToArray();
_matchInfo.Context.DisplayPostContext = _collectedPostContext.ToArray();
}
Reset();
}
}
// Reset tracking state. Does not reset the emit queue.
private void Reset()
{
_contextState = (_preContext > 0)
? ContextState.CollectPre
: ContextState.InitialState;
_collectedPreContext.Clear();
_collectedPostContext.Clear();
_matchInfo = null;
}
}
/// <summary>
/// A class to track logical context for each match.
/// </summary>
/// <remarks>
/// The difference between logical and display context is
/// that logical context includes as many context lines
/// as possible for a given match, up to the specified
/// limit, including context lines which overlap between
/// matches and other matching lines themselves. Display
/// context, on the other hand, is designed to display
/// a possibly-continuous set of matches by excluding
/// overlapping context (lines will only appear once)
/// and other matching lines (since they will appear
/// as their own match entries.).
/// </remarks>
private sealed class LogicalContextTracker : IContextTracker
{
// A union: string | MatchInfo. Needed since
// context lines could be either proper matches
// or non-matching lines.
private sealed class ContextEntry
{
public readonly string Line;
public readonly MatchInfo Match;
public ContextEntry(string line)
{
Line = line;
}
public ContextEntry(MatchInfo match)
{
Match = match;
}
public override string ToString() => Match?.Line ?? Line;
}
// Whether or not early entries found
// while still filling up the context buffer
// have been added to the emit queue.
// Used by UpdateQueue.
private bool _hasProcessedPreEntries;
private readonly int _preContext;
private readonly int _postContext;
// A circular buffer tracking both precontext and postcontext.
//
// Essentially, the buffer is separated into regions:
// | prectxt region (older entries, length = precontext) |
// | match region (length = 1) |
// | postctxt region (newer entries, length = postcontext) |
//
// When context entries containing a match reach the "middle"
// (the position between the pre/post context regions)
// of this buffer, and the buffer is full, we will know
// enough context to populate the Context properties of the
// match. At that point, we will add the match object
// to the emit queue.
private readonly CircularBuffer<ContextEntry> _collectedContext;
/// <summary>
/// Initializes a new instance of the <see cref="LogicalContextTracker"/> class.
/// </summary>
/// <param name="preContext">How much preContext to collect at most.</param>
/// <param name="postContext">How much postContext to collect at most.</param>
public LogicalContextTracker(int preContext, int postContext)
{
_preContext = preContext;
_postContext = postContext;
_collectedContext = new CircularBuffer<ContextEntry>(preContext + postContext + 1);
_emitQueue = new List<MatchInfo>();
}
#region IContextTracker implementation
public IList<MatchInfo> EmitQueue => _emitQueue;
private readonly List<MatchInfo> _emitQueue;
public void TrackLine(string line)
{
ContextEntry entry = new(line);
_collectedContext.Add(entry);
UpdateQueue();
}
public void TrackMatch(MatchInfo match)
{
ContextEntry entry = new(match);
_collectedContext.Add(entry);
UpdateQueue();
}
public void TrackEOF()
{
// If the buffer is already full,
// check for any matches with incomplete
// postcontext and add them to the emit queue.
// These matches can be identified by being past
// the "middle" of the context buffer (still in
// the postcontext region.
//
// If the buffer isn't full, then nothing will have
// ever been emitted and everything is still waiting
// on postcontext. So process the whole buffer.
int startIndex = _collectedContext.IsFull ? _preContext + 1 : 0;
EmitAllInRange(startIndex, _collectedContext.Count - 1);
}
#endregion
/// <summary>
/// Add all matches found in the specified range
/// to the emit queue, collecting as much context
/// as possible up to the limits specified in the constructor.
/// </summary>
/// <remarks>
/// The range is inclusive; the entries at
/// startIndex and endIndex will both be checked.
/// </remarks>
/// <param name="startIndex">The beginning of the match range.</param>
/// <param name="endIndex">The ending of the match range.</param>
private void EmitAllInRange(int startIndex, int endIndex)
{
for (int i = startIndex; i <= endIndex; i++)
{
MatchInfo match = _collectedContext[i].Match;
if (match != null)
{
int preStart = Math.Max(i - _preContext, 0);
int postLength = Math.Min(_postContext, _collectedContext.Count - i - 1);
Emit(match, preStart, i - preStart, i + 1, postLength);
}
}
}
/// <summary>
/// Add match(es) found in the match region to the
/// emit queue. Should be called every time an entry
/// is added to the context buffer.
/// </summary>
private void UpdateQueue()
{
// Are we at capacity and thus have enough postcontext?
// Is there a match in the "middle" of the buffer
// that we know the pre/post context for?
//
// If this is the first time we've reached full capacity,
// hasProcessedPreEntries will not be set, and we
// should go through the entire context, because it might
// have entries that never collected enough
// precontext. Otherwise, we should just look at the
// middle region.
if (_collectedContext.IsFull)
{
if (_hasProcessedPreEntries)
{
// Only process a potential match with exactly
// enough pre and post-context.
EmitAllInRange(_preContext, _preContext);
}
else
{
// Some of our early entries may not
// have enough precontext. Process them too.
EmitAllInRange(0, _preContext);
_hasProcessedPreEntries = true;
}
}
}
/// <summary>
/// Collects context from the specified ranges. Populates
/// the specified match with the collected context
/// and adds it to the emit queue.
/// </summary>
/// <remarks>
/// Context ranges must be within the bounds of the context buffer.
/// </remarks>
/// <param name="match">The match to operate on.</param>
/// <param name="preStartIndex">The start index of the preContext range.</param>
/// <param name="preLength">The length of the preContext range.</param>
/// <param name="postStartIndex">The start index of the postContext range.</param>
/// <param name="postLength">The length of the postContext range.</param>
private void Emit(MatchInfo match, int preStartIndex, int preLength, int postStartIndex, int postLength)
{
if (match.Context != null)
{
match.Context.PreContext = CopyContext(preStartIndex, preLength);
match.Context.PostContext = CopyContext(postStartIndex, postLength);
}
_emitQueue.Add(match);
}
/// <summary>
/// Collects context from the specified ranges.
/// </summary>
/// <remarks>
/// The range must be within the bounds of the context buffer.
/// </remarks>
/// <param name="startIndex">The index to start at.</param>
/// <param name="length">The length of the range.</param>
/// <returns>String representation of the collected context at the specified range.</returns>
private string[] CopyContext(int startIndex, int length)
{
string[] result = new string[length];
for (int i = 0; i < length; i++)
{
result[i] = _collectedContext[startIndex + i].ToString();
}
return result;
}
}
/// <summary>
/// A class to track both logical and display contexts.
/// </summary>
private sealed class ContextTracker : IContextTracker
{
private readonly IContextTracker _displayTracker;
private readonly IContextTracker _logicalTracker;
/// <summary>
/// Initializes a new instance of the <see cref="ContextTracker"/> class.
/// </summary>
/// <param name="preContext">How much preContext to collect at most.</param>
/// <param name="postContext">How much postContext to collect at most.</param>
public ContextTracker(int preContext, int postContext)
{
_displayTracker = new DisplayContextTracker(preContext, postContext);
_logicalTracker = new LogicalContextTracker(preContext, postContext);
EmitQueue = new List<MatchInfo>();
}
#region IContextTracker implementation
public IList<MatchInfo> EmitQueue { get; }
public void TrackLine(string line)
{
_displayTracker.TrackLine(line);
_logicalTracker.TrackLine(line);
UpdateQueue();
}
public void TrackMatch(MatchInfo match)
{
_displayTracker.TrackMatch(match);
_logicalTracker.TrackMatch(match);
UpdateQueue();
}
public void TrackEOF()
{
_displayTracker.TrackEOF();
_logicalTracker.TrackEOF();
UpdateQueue();
}
#endregion
/// <summary>
/// Update the emit queue based on the wrapped trackers.
/// </summary>
private void UpdateQueue()
{
// Look for completed matches in the logical
// tracker's queue. Since the logical tracker
// will try to collect as much context as
// possible, the display tracker will have either
// already finished collecting its context for the
// match or will have completed it at the same
// time as the logical tracker, so we can
// be sure the matches will have both logical
// and display context already populated.
foreach (MatchInfo match in _logicalTracker.EmitQueue)
{
EmitQueue.Add(match);
}
_logicalTracker.EmitQueue.Clear();
_displayTracker.EmitQueue.Clear();
}
}
/// <summary>
/// ContextTracker that does not work for the case when pre- and post context is 0.
/// </summary>
private sealed class NoContextTracker : IContextTracker
{
private readonly IList<MatchInfo> _matches = new List<MatchInfo>(1);
IList<MatchInfo> IContextTracker.EmitQueue => _matches;
void IContextTracker.TrackLine(string line)
{
}
void IContextTracker.TrackMatch(MatchInfo match) => _matches.Add(match);
void IContextTracker.TrackEOF()
{
}
}
/// <summary>
/// Gets or sets a culture name.
/// </summary>
[Parameter]
[ValidateSet(typeof(ValidateMatchStringCultureNamesGenerator))]
[ValidateNotNull]
public string Culture
{
get
{
switch (_stringComparison)
{
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
{
return OrdinalCultureName;
}
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
{
return InvariantCultureName;
}
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
{
return CurrentCultureName;
}
default:
{
break;
}
}
return _cultureName;
}
set
{
_cultureName = value;
InitCulture();
}
}
internal const string OrdinalCultureName = "Ordinal";
internal const string InvariantCultureName = "Invariant";
internal const string CurrentCultureName = "Current";
private string _cultureName = CultureInfo.CurrentCulture.Name;
private StringComparison _stringComparison = StringComparison.CurrentCultureIgnoreCase;
private CompareOptions _compareOptions = CompareOptions.IgnoreCase;
private delegate int CultureInfoIndexOf(string source, string value, int startIndex, int count, CompareOptions options);
private CultureInfoIndexOf _cultureInfoIndexOf = CultureInfo.CurrentCulture.CompareInfo.IndexOf;
private void InitCulture()
{
_stringComparison = default;
switch (_cultureName)
{
case OrdinalCultureName:
{
_stringComparison = CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
_compareOptions = CaseSensitive ? CompareOptions.Ordinal : CompareOptions.OrdinalIgnoreCase;
_cultureInfoIndexOf = CultureInfo.InvariantCulture.CompareInfo.IndexOf;
break;
}
case InvariantCultureName:
{
_stringComparison = CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase;
_compareOptions = CaseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase;
_cultureInfoIndexOf = CultureInfo.InvariantCulture.CompareInfo.IndexOf;
break;
}
case CurrentCultureName:
{
_stringComparison = CaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
_compareOptions = CaseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase;
_cultureInfoIndexOf = CultureInfo.CurrentCulture.CompareInfo.IndexOf;
break;
}
default:
{
var _cultureInfo = CultureInfo.GetCultureInfo(_cultureName);
_compareOptions = CaseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase;
_cultureInfoIndexOf = _cultureInfo.CompareInfo.IndexOf;
break;
}
}
}
/// <summary>
/// Gets or sets the current pipeline object.
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = ParameterSetObject)]
[Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = ParameterSetObjectRaw)]
[AllowNull]
[AllowEmptyString]
public PSObject InputObject
{
get => _inputObject;
set => _inputObject = LanguagePrimitives.IsNull(value) ? PSObject.AsPSObject(string.Empty) : value;
}
private PSObject _inputObject = AutomationNull.Value;
/// <summary>
/// Gets or sets the patterns to find.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
public string[] Pattern { get; set; }
private Regex[] _regexPattern;
/// <summary>
/// Gets or sets files to read from.
/// Globbing is done on these.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetFile)]
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetFileRaw)]
[FileinfoToString]
public string[] Path { get; set; }
/// <summary>
/// Gets or sets literal files to read from.
/// Globbing is not done on these.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetLiteralFile)]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetLiteralFileRaw)]
[FileinfoToString]
[Alias("PSPath", "LP")]
public string[] LiteralPath
{
get => Path;
set
{
Path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath;
/// <summary>
/// Gets or sets a value indicating if only string values containing matched lines should be returned.
/// If not (default) return MatchInfo (or bool objects, when Quiet is passed).
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = ParameterSetObjectRaw)]
[Parameter(Mandatory = true, ParameterSetName = ParameterSetFileRaw)]
[Parameter(Mandatory = true, ParameterSetName = ParameterSetLiteralFileRaw)]
public SwitchParameter Raw { get; set; }
/// <summary>
/// Gets or sets a value indicating if a pattern string should be matched literally.
/// If not (default) search using pattern as a Regular Expression.
/// </summary>
[Parameter]
public SwitchParameter SimpleMatch { get; set; }
/// <summary>
/// Gets or sets a value indicating if the search is case sensitive.If true, then do case-sensitive searches.
/// </summary>
[Parameter]
public SwitchParameter CaseSensitive { get; set; }
/// <summary>
/// Gets or sets a value indicating if the cmdlet will stop processing at the first successful match and
/// return true. If both List and Quiet parameters are given, an exception is thrown.
/// </summary>
[Parameter(ParameterSetName = ParameterSetObject)]
[Parameter(ParameterSetName = ParameterSetFile)]
[Parameter(ParameterSetName = ParameterSetLiteralFile)]
public SwitchParameter Quiet { get; set; }
/// <summary>
/// Gets or sets a value indicating if matching files should be listed.
/// This is the Unix functionality this switch is intended to mimic;
/// the actual action of this option is to stop after the first match
/// is found and returned from any particular file.
/// </summary>
[Parameter]
public SwitchParameter List { get; set; }
/// <summary>
/// Gets or sets a value indicating if highlighting should be disabled.
/// </summary>
[Parameter]
public SwitchParameter NoEmphasis { get; set; }
/// <summary>
/// Gets or sets files to include. Files matching
/// one of these (if specified) are included.
/// </summary>
/// <exception cref="WildcardPatternException">Invalid wildcard pattern was specified.</exception>
[Parameter]
[ValidateNotNullOrEmpty]
public string[] Include
{
get => _includeStrings;
set
{
// null check is not needed (because of ValidateNotNullOrEmpty),
// but we have to include it to silence OACR
_includeStrings = value ?? throw PSTraceSource.NewArgumentNullException(nameof(value));
_include = new WildcardPattern[_includeStrings.Length];
for (int i = 0; i < _includeStrings.Length; i++)
{
_include[i] = WildcardPattern.Get(_includeStrings[i], WildcardOptions.IgnoreCase);
}
}
}
private string[] _includeStrings;
private WildcardPattern[] _include;
/// <summary>
/// Gets or sets files to exclude. Files matching
/// one of these (if specified) are excluded.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string[] Exclude
{
get => _excludeStrings;
set
{
// null check is not needed (because of ValidateNotNullOrEmpty),
// but we have to include it to silence OACR
_excludeStrings = value ?? throw PSTraceSource.NewArgumentNullException("value");
_exclude = new WildcardPattern[_excludeStrings.Length];
for (int i = 0; i < _excludeStrings.Length; i++)
{
_exclude[i] = WildcardPattern.Get(_excludeStrings[i], WildcardOptions.IgnoreCase);
}
}
}
private string[] _excludeStrings;
private WildcardPattern[] _exclude;
/// <summary>
/// Gets or sets a value indicating whether to only show lines which do not match.
/// Equivalent to grep -v/findstr -v.
/// </summary>
[Parameter]
public SwitchParameter NotMatch { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the Matches property of MatchInfo should be set
/// to the result of calling System.Text.RegularExpressions.Regex.Matches() on
/// the corresponding line.
/// Has no effect if -SimpleMatch is also specified.
/// </summary>
[Parameter]
public SwitchParameter AllMatches { get; set; }
/// <summary>
/// Gets or sets the text encoding to process each file as.
/// </summary>
[Parameter]
[ArgumentToEncodingTransformation]
[ArgumentEncodingCompletions]
[ValidateNotNullOrEmpty]
public Encoding Encoding
{
get
{
return _encoding;
}
set
{
EncodingConversion.WarnIfObsolete(this, value);
_encoding = value;
}
}
private Encoding _encoding = Encoding.Default;
/// <summary>
/// Gets or sets the number of context lines to collect. If set to a
/// single integer value N, collects N lines each of pre-
/// and post- context. If set to a 2-tuple B,A, collects B
/// lines of pre- and A lines of post- context.
/// If set to a list with more than 2 elements, the
/// excess elements are ignored.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[ValidateCount(1, 2)]
[ValidateRange(0, int.MaxValue)]
public new int[] Context
{
get => _context;
set
{
// null check is not needed (because of ValidateNotNullOrEmpty),
// but we have to include it to silence OACR
_context = value ?? throw PSTraceSource.NewArgumentNullException("value");
if (_context.Length == 1)
{
_preContext = _context[0];
_postContext = _context[0];
}
else if (_context.Length >= 2)
{
_preContext = _context[0];
_postContext = _context[1];
}
}
}
private int[] _context;
private int _preContext = 0;
private int _postContext = 0;
// When we are in Raw mode or pre- and postcontext are zero, use the _noContextTracker, since we will not be needing trackedLines.
private IContextTracker GetContextTracker() => (Raw || (_preContext == 0 && _postContext == 0))
? _noContextTracker
: new ContextTracker(_preContext, _postContext);
// This context tracker is only used for strings which are piped
// directly into the cmdlet. File processing doesn't need
// to track state between calls to ProcessRecord, and so
// allocates its own tracker. The reason we can't
// use a single global tracker for both is that in the case of
// a mixed list of strings and FileInfo, the context tracker
// would get reset after each file.
private IContextTracker _globalContextTracker;
private IContextTracker _noContextTracker;
/// <summary>
/// This is used to handle the case were we're done processing input objects.
/// If true, process record will just return.
/// </summary>
private bool _doneProcessing;
private ulong _inputRecordNumber;
/// <summary>
/// Read command line parameters.
/// </summary>
protected override void BeginProcessing()
{
if (this.MyInvocation.BoundParameters.ContainsKey(nameof(Culture)) && !this.MyInvocation.BoundParameters.ContainsKey(nameof(SimpleMatch)))
{
InvalidOperationException exception = new(MatchStringStrings.CannotSpecifyCultureWithoutSimpleMatch);
ErrorRecord errorRecord = new(exception, "CannotSpecifyCultureWithoutSimpleMatch", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
InitCulture();
string suppressVt = Environment.GetEnvironmentVariable("__SuppressAnsiEscapeSequences");
if (!string.IsNullOrEmpty(suppressVt))
{
NoEmphasis = true;
}
if (!SimpleMatch)
{
RegexOptions regexOptions = CaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
_regexPattern = new Regex[Pattern.Length];
for (int i = 0; i < Pattern.Length; i++)
{
try
{
_regexPattern[i] = new Regex(Pattern[i], regexOptions);
}
catch (Exception e)
{
this.ThrowTerminatingError(BuildErrorRecord(MatchStringStrings.InvalidRegex, Pattern[i], e.Message, "InvalidRegex", e));
throw;
}
}
}
_noContextTracker = new NoContextTracker();
_globalContextTracker = GetContextTracker();
}
private readonly List<string> _inputObjectFileList = new(1) { string.Empty };
/// <summary>
/// Process the input.
/// </summary>
/// <exception cref="ArgumentException">Regular expression parsing error, path error.</exception>
/// <exception cref="FileNotFoundException">A file cannot be found.</exception>
/// <exception cref="DirectoryNotFoundException">A file cannot be found.</exception>
protected override void ProcessRecord()
{
if (_doneProcessing)
{
return;
}
// We may only have directories when we have resolved wildcards
var expandedPathsMaybeDirectory = false;
List<string> expandedPaths = null;
if (Path != null)
{
expandedPaths = ResolveFilePaths(Path, _isLiteralPath);
if (expandedPaths == null)
{
return;
}
expandedPathsMaybeDirectory = true;
}
else
{
if (_inputObject.BaseObject is FileInfo fileInfo)
{
_inputObjectFileList[0] = fileInfo.FullName;
expandedPaths = _inputObjectFileList;
}
}
if (expandedPaths != null)
{
foreach (var filename in expandedPaths)
{
if (expandedPathsMaybeDirectory && Directory.Exists(filename))
{
continue;
}
var foundMatch = ProcessFile(filename);
if (Quiet && foundMatch)
{
return;
}
}
// No results in any files.
if (Quiet)
{
var res = List ? null : Boxed.False;
WriteObject(res);
}
}
else
{
// Set the line number in the matched object to be the record number
_inputRecordNumber++;
bool matched;
MatchInfo result;
MatchInfo matchInfo = null;
if (_inputObject.BaseObject is string line)
{
matched = DoMatch(line, out result);
}
else
{
matchInfo = _inputObject.BaseObject as MatchInfo;
object objectToCheck = matchInfo ?? (object)_inputObject;
matched = DoMatch(objectToCheck, out result, out line);
}
if (matched)
{
// Don't re-write the line number if it was already set...
if (matchInfo == null)
{
result.LineNumber = _inputRecordNumber;
}
// doMatch will have already set the pattern and line text...
_globalContextTracker.TrackMatch(result);
}
else
{
_globalContextTracker.TrackLine(line);
}
// Emit any queued up objects...
if (FlushTrackerQueue(_globalContextTracker))
{
// If we're in quiet mode, go ahead and stop processing
// now.
if (Quiet)
{
_doneProcessing = true;
}
}
}
}
/// <summary>
/// Process a file which was either specified on the
/// command line or passed in as a FileInfo object.
/// </summary>
/// <param name="filename">The file to process.</param>
/// <returns>True if a match was found; otherwise false.</returns>
private bool ProcessFile(string filename)
{
var contextTracker = GetContextTracker();
bool foundMatch = false;
// Read the file one line at a time...
try
{
// see if the file is one the include exclude list...
if (!MeetsIncludeExcludeCriteria(filename))
{
return false;
}
using (FileStream fs = new(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new(fs, Encoding))
{
string line;
ulong lineNo = 0;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
lineNo++;
if (DoMatch(line, out MatchInfo result))
{
result.Path = filename;
result.LineNumber = lineNo;
contextTracker.TrackMatch(result);
}
else
{
contextTracker.TrackLine(line);
}
// Flush queue of matches to emit.
if (contextTracker.EmitQueue.Count > 0)
{
foundMatch = true;
// If -list or -quiet was specified, we only want to emit the first match
// for each file so record the object to emit and stop processing
// this file. It's done this way so the file is closed before emitting
// the result so the downstream cmdlet can actually manipulate the file
// that was found.
if (Quiet || List)
{
break;
}
FlushTrackerQueue(contextTracker);
}
}
}
}
// Check for any remaining matches. This could be caused
// by breaking out of the loop early for quiet or list
// mode, or by reaching EOF before we collected all
// our postcontext.
contextTracker.TrackEOF();
if (FlushTrackerQueue(contextTracker))
{
foundMatch = true;
}
}
catch (System.NotSupportedException nse)
{
WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, nse.Message, "ProcessingFile", nse));
}
catch (System.IO.IOException ioe)
{
WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, ioe.Message, "ProcessingFile", ioe));
}
catch (System.Security.SecurityException se)
{
WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, se.Message, "ProcessingFile", se));
}
catch (System.UnauthorizedAccessException uae)
{
WriteError(BuildErrorRecord(MatchStringStrings.FileReadError, filename, uae.Message, "ProcessingFile", uae));
}
return foundMatch;
}
/// <summary>
/// Emit any objects which have been queued up, and clear the queue.
/// </summary>
/// <param name="contextTracker">The context tracker to operate on.</param>
/// <returns>Whether or not any objects were emitted.</returns>
private bool FlushTrackerQueue(IContextTracker contextTracker)
{
// Do we even have any matches to emit?
if (contextTracker.EmitQueue.Count < 1)
{
return false;
}
if (Raw)
{
foreach (MatchInfo match in contextTracker.EmitQueue)
{
WriteObject(match.Line);
}
}
else if (Quiet && !List)
{
WriteObject(true);
}
else if (List)
{
WriteObject(contextTracker.EmitQueue[0]);
}
else
{
foreach (MatchInfo match in contextTracker.EmitQueue)
{
WriteObject(match);
}
}
contextTracker.EmitQueue.Clear();
return true;
}
/// <summary>
/// Complete processing. Emits any objects which have been queued up
/// due to -context tracking.
/// </summary>
protected override void EndProcessing()
{
// Check for a leftover match that was still tracking context.
_globalContextTracker.TrackEOF();
if (!_doneProcessing)
{
FlushTrackerQueue(_globalContextTracker);
}
}
private bool DoMatch(string operandString, out MatchInfo matchResult)
{
return DoMatchWorker(operandString, null, out matchResult);
}
private bool DoMatch(object operand, out MatchInfo matchResult, out string operandString)
{
MatchInfo matchInfo = operand as MatchInfo;
if (matchInfo != null)
{
// We're operating in filter mode. Match
// against the provided MatchInfo's line.
// If the user has specified context tracking,
// inform them that it is not allowed in filter
// mode and disable it. Also, reset the global
// context tracker used for processing pipeline
// objects to use the new settings.
operandString = matchInfo.Line;
if (_preContext > 0 || _postContext > 0)
{
_preContext = 0;
_postContext = 0;
_globalContextTracker = new ContextTracker(_preContext, _postContext);
WarnFilterContext();
}
}
else
{
operandString = (string)LanguagePrimitives.ConvertTo(operand, typeof(string), CultureInfo.InvariantCulture);
}
return DoMatchWorker(operandString, matchInfo, out matchResult);
}
/// <summary>
/// Check the operand and see if it matches, if this.quiet is not set, then
/// return a partially populated MatchInfo object with Line, Pattern, IgnoreCase set.
/// </summary>
/// <param name="operandString">The result of converting operand to a string.</param>
/// <param name="matchInfo">The input object in filter mode.</param>
/// <param name="matchResult">The match info object - this will be null if this.quiet is set.</param>
/// <returns>True if the input object matched.</returns>
private bool DoMatchWorker(string operandString, MatchInfo matchInfo, out MatchInfo matchResult)
{
bool gotMatch = false;
Match[] matches = null;
int patternIndex = 0;
matchResult = null;
List<int> indexes = null;
List<int> lengths = null;
bool shouldEmphasize = !NoEmphasis && Host.UI.SupportsVirtualTerminal;
// If Emphasize is set and VT is supported,
// the lengths and starting indexes of regex matches
// need to be passed in to the matchInfo object.
if (shouldEmphasize)
{
indexes = new List<int>();
lengths = new List<int>();
}
if (!SimpleMatch)
{
while (patternIndex < Pattern.Length)
{
Regex r = _regexPattern[patternIndex];
// Only honor allMatches if notMatch is not set,
// since it's a fairly expensive operation and
// notMatch takes precedent over allMatch.
if (AllMatches && !NotMatch)
{
MatchCollection mc = r.Matches(operandString);
if (mc.Count > 0)
{
matches = new Match[mc.Count];
((ICollection)mc).CopyTo(matches, 0);
if (shouldEmphasize)
{
foreach (Match match in matches)
{
indexes.Add(match.Index);
lengths.Add(match.Length);
}
}
gotMatch = true;
}
}
else
{
Match match = r.Match(operandString);
gotMatch = match.Success;
if (match.Success)
{
if (shouldEmphasize)
{
indexes.Add(match.Index);
lengths.Add(match.Length);
}
matches = new Match[] { match };
}
}
if (gotMatch)
{
break;
}
patternIndex++;
}
}
else
{
while (patternIndex < Pattern.Length)
{
string pat = Pattern[patternIndex];
int index = _cultureInfoIndexOf(operandString, pat, 0, operandString.Length, _compareOptions);
if (index >= 0)
{
if (shouldEmphasize)
{
indexes.Add(index);
lengths.Add(pat.Length);
}
gotMatch = true;
break;
}
patternIndex++;
}
}
if (NotMatch)
{
gotMatch = !gotMatch;
// If notMatch was specified with multiple
// patterns, then *none* of the patterns
// matched and any pattern could be picked
// to report in MatchInfo. However, that also
// means that patternIndex will have been
// incremented past the end of the pattern array.
// So reset it to select the first pattern.
patternIndex = 0;
}
if (gotMatch)
{
// if we were passed a MatchInfo object as the operand,
// we're operating in filter mode.
if (matchInfo != null)
{
// If the original MatchInfo was tracking context,
// we need to copy it and disable display context,
// since we can't guarantee it will be displayed
// correctly when filtered.
if (matchInfo.Context != null)
{
matchResult = matchInfo.Clone();
matchResult.Context.DisplayPreContext = Array.Empty<string>();
matchResult.Context.DisplayPostContext = Array.Empty<string>();
}
else
{
// Otherwise, just pass the object as is.
matchResult = matchInfo;
}
return true;
}
// otherwise construct and populate a new MatchInfo object
matchResult = shouldEmphasize
? new MatchInfo(indexes, lengths)
: new MatchInfo();
matchResult.IgnoreCase = !CaseSensitive;
matchResult.Line = operandString;
matchResult.Pattern = Pattern[patternIndex];
if (_preContext > 0 || _postContext > 0)
{
matchResult.Context = new MatchInfoContext();
}
// Matches should be an empty list, rather than null,
// in the cases of notMatch and simpleMatch.
matchResult.Matches = matches ?? Array.Empty<Match>();
return true;
}
return false;
}
/// <summary>
/// Get a list or resolved file paths.
/// </summary>
/// <param name="filePaths">The filePaths to resolve.</param>
/// <param name="isLiteralPath">True if the wildcard resolution should not be attempted.</param>
/// <returns>The resolved (absolute) paths.</returns>
private List<string> ResolveFilePaths(string[] filePaths, bool isLiteralPath)
{
List<string> allPaths = new();
foreach (string path in filePaths)
{
Collection<string> resolvedPaths;
ProviderInfo provider;
if (isLiteralPath)
{
resolvedPaths = new Collection<string>();
string resolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path, out provider, out _);
resolvedPaths.Add(resolvedPath);
}
else
{
resolvedPaths = GetResolvedProviderPathFromPSPath(path, out provider);
}
if (!provider.NameEquals(base.Context.ProviderNames.FileSystem))
{
// "The current provider ({0}) cannot open a file"
WriteError(BuildErrorRecord(MatchStringStrings.FileOpenError, provider.FullName, "ProcessingFile", null));
continue;
}
allPaths.AddRange(resolvedPaths);
}
return allPaths;
}
private static ErrorRecord BuildErrorRecord(string messageId, string argument, string errorId, Exception innerException)
{
return BuildErrorRecord(messageId, new object[] { argument }, errorId, innerException);
}
private static ErrorRecord BuildErrorRecord(string messageId, string arg0, string arg1, string errorId, Exception innerException)
{
return BuildErrorRecord(messageId, new object[] { arg0, arg1 }, errorId, innerException);
}
private static ErrorRecord BuildErrorRecord(string messageId, object[] arguments, string errorId, Exception innerException)
{
string fmtedMsg = StringUtil.Format(messageId, arguments);
ArgumentException e = new(fmtedMsg, innerException);
return new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null);
}
private void WarnFilterContext()
{
string msg = MatchStringStrings.FilterContextWarning;
WriteWarning(msg);
}
/// <summary>
/// Magic class that works around the limitations on ToString() for FileInfo.
/// </summary>
private sealed class FileinfoToStringAttribute : ArgumentTransformationAttribute
{
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
object result = inputData;
if (result is PSObject mso)
{
result = mso.BaseObject;
}
FileInfo fileInfo;
// Handle an array of elements...
if (result is IList argList)
{
object[] resultList = new object[argList.Count];
for (int i = 0; i < argList.Count; i++)
{
object element = argList[i];
mso = element as PSObject;
if (mso != null)
{
element = mso.BaseObject;
}
fileInfo = element as FileInfo;
resultList[i] = fileInfo?.FullName ?? element;
}
return resultList;
}
// Handle the singleton case...
fileInfo = result as FileInfo;
if (fileInfo != null)
{
return fileInfo.FullName;
}
return inputData;
}
}
/// <summary>
/// Check whether the supplied name meets the include/exclude criteria.
/// That is - it's on the include list if there is one and not on
/// the exclude list if there was one of those.
/// </summary>
/// <param name="filename">The filename to test.</param>
/// <returns>True if the filename is acceptable.</returns>
private bool MeetsIncludeExcludeCriteria(string filename)
{
bool ok = false;
// see if the file is on the include list...
if (_include != null)
{
foreach (WildcardPattern patternItem in _include)
{
if (patternItem.IsMatch(filename))
{
ok = true;
break;
}
}
}
else
{
ok = true;
}
if (!ok)
{
return false;
}
// now see if it's on the exclude list...
if (_exclude != null)
{
foreach (WildcardPattern patternItem in _exclude)
{
if (patternItem.IsMatch(filename))
{
ok = false;
break;
}
}
}
return ok;
}
}
/// <summary>
/// Get list of valid culture names for ValidateSet attribute.
/// </summary>
public class ValidateMatchStringCultureNamesGenerator : IValidateSetValuesGenerator
{
string[] IValidateSetValuesGenerator.GetValidValues()
{
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
var result = new List<string>(cultures.Length + 3);
result.Add(SelectStringCommand.OrdinalCultureName);
result.Add(SelectStringCommand.InvariantCultureName);
result.Add(SelectStringCommand.CurrentCultureName);
foreach (var cultureInfo in cultures)
{
result.Add(cultureInfo.Name);
}
return result.ToArray();
}
}
}
|