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 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
|
# maitch.py - Simple but flexible build system tool
# Copyright (C) 2012 Tony Houghton <h@realh.co.uk>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import atexit
import fnmatch
import os
import re
import shutil
import subprocess
import sys
import threading
import traceback
from curses import ascii
_mprint_lock = threading.Lock()
_mprint_fp = None
def mprint(*args, **kwargs):
""" Equivalent to python 3's print but also works in python < 2.6 """
global _mprint_lock
with _mprint_lock:
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '\n')
file = kwargs.get('file', sys.stdout)
s = sep.join(args) + end
file.write(s)
file.flush()
if _mprint_fp and file != _mprint_fp:
_mprint_fp.write(s)
_debug = False
def dprint(*args, **kwargs):
if _debug:
mprint(*args, **kwargs)
elif _mprint_fp:
kwargs['file'] = _mprint_fp
mprint(*args, **kwargs)
try:
from lockfile import FileLock
class FLock(FileLock):
def __init__(self, *args, **kwargs):
self.maitch_locked = False
FileLock.__init__(self, *args, **kwargs)
def acquire(self, timeout = None):
FileLock.acquire(self, timeout)
self.maitch_locked = True
def release(self):
if self.maitch_locked:
FileLock.release(self)
self.maitch_locked = False
except:
_nolock = True
else:
_nolock = False
# Where to look for sources if a relative path is given and the file
# doesn't exist relative to cwd.
# May be combined with bitwise or.
NOWHERE = 0
SRC = 1
TOP = 2
class MaitchError(Exception):
pass
class MaitchRuleError(MaitchError):
pass
class MaitchArgError(MaitchError):
pass
class MaitchChildError(MaitchError):
pass
class MaitchDirError(MaitchError):
pass
class MaitchNotFoundError(MaitchError):
pass
class MaitchRecursionError(MaitchError):
pass
class MaitchJobError(MaitchError):
pass
class MaitchInstallError(MaitchError):
pass
# subst behaviour if a variable isn't found
NOVAR_FATAL = 0 # Raise exception
NOVAR_BLANK = 1 # Replace with empty string
NOVAR_SKIP = 2 # Leave ${} construct untouched
class Context(object):
" The fundamental build context. "
def __init__(self, **kwargs):
"""
All kwargs are added to context's env. They may include:
PACKAGE = package name (compulsory).
BUILD_DIR = where to output all generated files, defaults to
"${MSCRIPT_REAL_DIR}/build". ${BUILD_DIR} is used as the cwd for
all commands and other directories should be specified relative
to it.
TOP_DIR = top level of package directory, defaults to ".."
SRC_DIR = top level of source directory, defaults to ${TOP_DIR}.
Otherwise it should be specified relative to TOP_DIR to make
sure dist stage works correctly.
Special env variables. These are expanded in all modes, not just
configure. They are not saved in the env file.
MSCRIPT_DIR: The directory containing the executable script running
the build (sys.argv[0]). Symlinks are not followed.
MSCRIPT_REAL_DIR: MSCRIPT_DIR with symlinks followed.
Useful attributes:
env: context's variables
mode: mode of build, one of "configure", "build", "install" or "dist";
taken from sys.argv[1]
build_dir, src_dir, top_dir: Expanded versions of above variables. Bear
in mind that these are expanded before you have a chance to add
any vars to env after constructing the ctx:- they may refer to
each other (non-recursively) but to no other variables.
Notes:
All "nodes" (sources, targets etc) are expressed as strings.
See process_nodes() for how they are accepted as arguments.
"""
self.lock = threading.RLock()
self.tmpfile_index = 0
# Make sure a package name was specified
self.package_name = kwargs['PACKAGE']
self.created_by_config = {}
self.installed = []
self.tar_contents = []
# Check mode
if len(sys.argv) < 2:
self.mode = 'help'
else:
self.mode = sys.argv[1]
if not self.mode in \
"help configure reconfigure build dist install uninstall " \
"clean pristine".split():
self.mode = 'help'
if self.mode == 'help':
ms = os.path.basename(sys.argv[0])
mprint("Help for maitch:\nUSAGE:")
for m in ["help", "configure", "reconfigure",
"build [TARGETS]", "install", "uninstall",
"clean", "pristine", "dist"]:
mprint(" python %s %s" % (ms, m))
mprint("""
Further variables may be set after the mode argument in the form VAR=value, or
VAR on its own for True. "--foo-bar" is equivalent to "FOO_BAR". Variables may
refer to each other eg FOO='${BAR}.baz'. Note that maitch does not read
variables directly from the environment. If you want to use, for example,
CFLAGS from the environment, add CFLAGS="$CFLAGS" to the configure command.
Variables can be set from the environment indirectly using MAITCHFLAGS. For
example:
export MAITCHFLAGS="CFLAGS=$CFLAGS;LDFLAGS=$LDFLAGS"
Note that multiple variables are separated by semicolons and you should not use
quoting within the MAITCHFLAGS string.
The most pivotal variable is BUILD_DIR which is the working directory and where
built files are saved. It will be created if necessary. If not specified it
defaults to a directory "build" in the same directory as %s
(symbolic links are followed).
TOP_DIR and SRC_DIR are the top level directory of the package, and the
subdirectory containing source files respectively. SRC_DIR is commonly
"${TOP_DIR}/src" or just "${TOP_DIR}". It is recommended that they are specified
as relative paths assuming a working directory of $BUILD_DIR. For example, when
the default BUILD_DIR is used, TOP_DIR='..'
Other predefined variables [default values shown in squarer brackets]:
""" % ms)
for v in _var_repository:
if v[3]:
alt = "/%s" % var_to_arg(v[0])
else:
alt = ""
if callable(v[1]):
default = 'dynamic'
else:
default = v[1]
print_wrapped(" %s%s [%s]: %s" %
(v[0], alt, default, v[2]),
80, 8, 0)
self.showed_var_header = False
return
self.env = {}
# From now on reconfigure is the same as configure
if self.mode == 'reconfigure':
self.mode = 'configure'
# Process MAITCHFLAGS first because it's lowest priority and
# subsequent processing will overwrite it
mf = os.environ.get('MAITCHFLAGS')
if mf:
self.__process_args(mf.split(';'))
# Get more env vars from kwargs
for k, v in kwargs.items():
self.env[k] = v
self.explicit_rules = {}
self.cli_targets = []
# Process command-line args
if len(sys.argv) > 2:
cli_env = self.__process_args(sys.argv[2:])
else:
cli_env = {}
# Everything hinges on BUILD_DIR
self.get_build_dir()
self.build_dir = os.path.abspath(self.subst(self.env['BUILD_DIR']))
self.ensure_out_dir(self.build_dir)
log_file = opj(self.build_dir, ".maitch", "log")
self.ensure_out_dir_for_file(log_file)
global _mprint_fp
_mprint_fp = open(log_file, 'w')
if self.mode != "dist":
# This message is to help text editors find the cwd in case errors
# are reported relative to it
mprint('make[0]: Entering directory "%s"' % \
self.build_dir)
os.chdir(self.build_dir)
# Get lock on BUILD_DIR
if not self.env.get('NO_LOCK'):
global _nolock
if _nolock:
mprint("Error: lockfile module unavailable. "
"Please install it or, as a last resort, "
"use the --no-lock option:\n"
"%s %s --no-lock ..." % (sys.argv[0], sys.argv[1]),
file = sys.stderr)
sys.exit(1)
f = self.get_lock_file_name()
self.ensure_out_dir_for_file(f)
self.lock_file = FLock(f)
self.lock_file.acquire(0)
atexit.register(lambda x: x.release(), self.lock_file)
else:
mprint("Warning: Locking disabled. This is not recommended.")
# If not in configure mode load a previous saved env.
if self.mode != 'configure':
n = self.env_file_name()
if os.path.exists(n):
fp = open(n, 'r')
for l in fp.readlines():
k, v = l.split('=', 1)
# Don't override command line or constructor
if not k in cli_env:
v = v.rstrip()
if v == 'True':
v = True
elif v == 'False':
v = False
elif len(v) \
and (ascii.isdigit(v[0]) \
or (v[0] == '-' and len(v) > 1)) \
and all([ascii.isdigit(a) for a in v[1:]]):
v = int(v)
self.env[k] = v
fp.close()
# Set defaults
for v in _var_repository:
if not self.env.get(v[0]):
if callable(v[1]):
d = v[1](v[0])
else:
d = v[1]
self.env[v[0]] = d
self.top_dir = self.subst(self.env['TOP_DIR'])
self.src_dir = self.subst(self.env['SRC_DIR'])
self.check_build_dir()
self.dest_dir = self.subst(self.env['DESTDIR'])
self.definitions = {}
self.created_by_config[opj(self.build_dir, ".maitch")] = True
# In dist mode everything is relative to TOP_DIR
if self.mode == "dist":
self.env['TOP_DIR'] = os.curdir
bd = os.path.abspath(self.build_dir)
self.env['BUILD_DIR'] = bd
td = os.path.abspath(self.top_dir)
mprint('make[0]: Entering directory "%s"' % td)
os.chdir(td)
if self.env.get('ENABLE_DEBUG'):
global _debug
_debug = True
def __process_args(self, args):
cli_env = {}
for a in args:
if '=' in a:
k, v = a.split('=', 1)
elif self.mode != 'build' or a.startswith('--'):
k = a
v = True
elif self.mode == 'build':
self.cli_targets.append(a)
if k.startswith('--'):
k = arg_to_var(k)
if self.var_is_special(k):
raise MaitchDirError("%s is a reserved variable" % k)
self.env[k] = v
cli_env[k] = v
return cli_env
def define(self, key, value):
""" Define a variable to be used in the build. At the moment the only
supported method is to output a C header ${BUILD_DIR}/config.h at the
end of the configure phase. Definitions are of the form:
#define key value
where double quotes are automatically added for string values unless
already enclosed in single quotes. True and False are converted to 1 and
0, while a value of None results in:
#undef key
being written instead. """
self.definitions[key] = value
def define_from_var(self, key, default = None):
""" Calls self.define() with env variable's value. """
self.define(key, self.env.get(key, default))
def __arg(self, help_name, help_body, var, antivar, default):
if self.mode == 'help':
if not self.showed_var_header:
mprint("\n%s supports these configure options:\n" %
self.package_name)
self.showed_var_header = True
print_formatted(help_body, 80, help_name, 20)
else:
if self.env.get(antivar):
self.setenv(var, False)
elif self.env.get(var) == None:
if callable(default):
default = default(self, var)
self.setenv(var, default)
def arg_enable(self, name, help, var = None, default = False):
""" Similar to autoconf's AC_ARG_ENABLE. Adds a variable which may
be enabled/disabled on the configure command line with --enable-name
or --disable-name. default may be a callable, in which case it will be
called as default(context, var) if the argument isn't given on the
command line, and var will be set to its return value. If var is not
given, it's generated in the form ENABLE_NAME. Its value in the env will
be 1 or 0. """
if default == True:
prefix = "disable"
else:
prefix = "enable"
arg = "--%s-%s" % (prefix, name)
if not var:
var = 'ENABLE_' + s_to_var(name)
self.__arg(arg, help, var, 'DISABLE' + var[6:], default)
def arg_disable(self, name, help, var = None, default = True):
""" Can be used as a shortcut for arg_enable with default = True or
to force help string to be shown as --disable-name when default is
callable. """
if not var:
var = 'ENABLE_' + s_to_var(name)
self.__arg("--disable-%s" % name, help, var,
'DISABLE' + var[6:], default)
def arg_with(self, name, help, var = None, default = False):
""" Like arg_enable but uses --with-name=... and --without-name=... """
if not var:
var = 'WITH_' + s_to_var(name)
self.__arg("--with-%s=VALUE" % name, help, var,
'WITHOUT' + var[4:], default)
def save_if_different(self, filename, content):
" Like global version but runs self.subst() on filename and content. "
save_if_different(self.subst(filename), self.subst(content))
def output_config_h(self):
sentinel = "%s__CONFIG_H" % self.package_name.upper()
keys = self.definitions.keys()
keys.sort()
s = "/* Auto-generated by maitch.py for %s */\n" \
"#ifndef %s\n#define %s\n\n" % \
(self.package_name, sentinel, sentinel)
for k in keys:
v = self.definitions[k]
if v == None:
s += "#undef %s\n\n" % k
continue
elif v == True:
v = 1
elif v == False:
v = 0
else:
if isinstance(v, basestring):
if (v[0] != "'" or v[-1] != "'"):
v = '"' + v + '"'
v = self.subst(v)
s += "#define %s %s\n\n" % (k, v)
s += "#endif /* %s */\n" % sentinel
filename = opj(self.build_dir, "config.h")
self.save_if_different(filename, s)
self.created_by_config[filename] = True
@staticmethod
def var_is_special(k):
return k == "MSCRIPT_DIR" or k == "MSCRIPT_REAL_DIR"
def check_build_dir(self):
clash = None
if self.top_dir == self.build_dir or self.top_dir == ".":
clash = 'TOP_DIR'
elif self.src_dir == self.build_dir or self.src_dir == ".":
clash = 'SRC_DIR'
if clash:
mprint("WARNING: BUILD_DIR == %s, unable to clean" % clash,
file = sys.stderr)
return False
return True
def tmpname(self):
""" Returns the name of a temporary file in ${BUILD_DIR}/.maitch
which is unique for this context. """
with self.lock:
self.tmpfile_index += 1
i = self.tmpfile_index
return opj(self.build_dir, ".maitch", "tmp%03d" % i)
def get_build_dir(self, kwargs = None):
""" Sets env's TOP_DIR and SRC_DIR, looking in kwargs or self.env,
setting defaults if necessary. """
if not kwargs:
kwargs = self.env
self.env['MSCRIPT_DIR'] = os.path.abspath(os.path.dirname(sys.argv[0]))
self.env['MSCRIPT_REAL_DIR'] = \
os.path.abspath(os.path.dirname(os.path.realpath(sys.argv[0])))
bd = kwargs.get('BUILD_DIR')
if bd:
bd = os.path.abspath(bd)
else:
bd = opj("${MSCRIPT_REAL_DIR}", "build")
self.env['BUILD_DIR'] = bd
td = kwargs.get('TOP_DIR')
if not td:
td = os.pardir
self.env['TOP_DIR'] = td
sd = kwargs.get('SRC_DIR')
if not sd:
sd = "${TOP_DIR}"
self.env['SRC_DIR'] = sd
def env_file_name(self):
""" Returns the filename of where env is saved, ensuring its
directory exists. """
n = self.make_out_path(".maitch", "env")
self.ensure_out_dir_for_file(n)
return n
def get_lock_file_name(self):
if self.env.get("LOCK_TOP"):
return os.path.abspath(opj(self.subst("${TOP_DIR}"), ".maitchlock"))
else:
return os.path.abspath(opj(self.subst("${BUILD_DIR}"),
".maitch", "lock"))
def release_lock(self, lock, lockname):
try:
lock.release()
except:
pass
try:
if os.path.isdir(lockname):
os.unlink(lockname)
else:
recursively_remove(lockname, False, [])
except:
pass
def add_rule(self, rule):
" Adds an explicit rule. "
for t in rule.targets:
self.explicit_rules[self.subst(t)] = rule
rule.ctx = self
def glob(self, pattern, dir = None, subdir = None, expand = None):
""" Returns a list of matching filenames relative to dir (default
${BUILD_DIR}). subdir, if given, is preserved at the start of each
filename. expand is whether to use the substituted/expanded version
of dir in the output. If not given/None it's True in all modes except
dist. """
if expand == None:
expand = self.mode != "dist"
if dir:
orig_dir = dir
dir = self.subst(dir)
else:
orig_dir = os.curdir
dir = os.path.abspath(orig_dir)
if subdir:
dir = opj(dir, subdir)
matches = fnmatch.filter(os.listdir(dir), pattern)
if expand or subdir:
if not expand:
dir = subdir
for i in range(len(matches)):
matches[i] = opj(dir, matches[i])
return matches
def glob_src(self, pattern, subdir = None, expand = None):
" Performs glob on src_dir. "
return self.glob(pattern, self.src_dir, subdir, expand)
def glob_all(self, pattern, subdir = None, expand = None):
""" Performs glob on both build_dir/src_dir. No pathname component
is added other than subdir. """
matches = self.glob(pattern, self.build_dir, subdir, expand)
for n in self.glob_src(pattern, subdir, expand):
if not n in matches:
matches.append(n)
return matches
def run(self):
" Run whichever stage of the build was specified on CLI. "
if self.mode == 'configure':
fp = open(self.env_file_name(), 'w')
for k, v in self.env.items():
if not self.var_is_special(k):
fp.write("%s=%s\n" % (k, v))
fp.close()
if self.definitions:
self.output_config_h()
fp = open(opj(self.build_dir, ".maitch", "manifest"), 'w')
for f in self.created_by_config.keys():
fp.write("%s\n" % f)
fp.close()
elif self.mode == 'build':
if len(self.cli_targets):
tgts = self.cli_targets
else:
tgts = self.explicit_rules.keys()
bg = BuildGroup(self, tgts)
if bg.cancelled:
sys.exit(1)
elif self.mode == 'clean':
filename = opj(self.build_dir, ".maitch", "manifest")
if os.path.exists(filename):
fp = open(filename, 'r')
for f in fp.readlines():
self.created_by_config[f.strip()] = True
fp.close()
self.clean(False)
elif self.mode == 'pristine':
self.clean(False, True)
elif self.mode == 'dist':
self.make_tarball()
elif self.mode == 'uninstall':
self.uninstall()
def make_tarball(self):
import tarfile
basedir = self.subst("${PACKAGE}-${VERSION}")
filename = os.path.abspath(
self.subst("${BUILD_DIR}/%s.tar.bz2" % basedir))
mprint("Creating tarball '%s'" % filename)
tar = tarfile.open(filename, 'w:bz2')
for f, kwargs in self.tar_contents:
kwargs = dict(kwargs)
dest = kwargs.get('arcname')
if dest:
dest = os.path.normpath(opj(basedir, dest))
else:
dest = os.path.normpath(opj(basedir, f))
kwargs['arcname'] = dest
mprint("Adding '%s' to tarball" % dest)
tar.add(self.subst(f), **kwargs)
tar.close()
def add_dist(self, objects, **kwargs):
if isinstance(objects, basestring):
objects = objects.split()
for o in objects:
self.tar_contents.append([o, kwargs])
def clean(self, fatal, pristine = False):
if not self.check_build_dir():
return
if pristine:
# Release lock prematurely because we're about to delete it!
self.lock_file.release()
keep = []
else:
keep = self.created_by_config
recursively_remove(self.build_dir, fatal, keep)
recursively_remove(opj(self.build_dir, ".maitch", "deps"), fatal, [])
def ensure_out_dir(self, *args):
""" Esnures the named directory exists. args is a single string or list
of strings. Single string may be absolute in which case it isn't
altered. Otherwise a path is made absolute using BUILD_DIR. """
if isinstance(args, basestring) and os.path.isabs(args):
path = args
else:
path = self.make_out_path(*args)
with self.lock:
if not os.path.isdir(path):
os.makedirs(path)
def ensure_out_dir_for_file(self, path):
""" As above but uses a single string only and acts on its
parent directory. """
self.ensure_out_dir(os.path.dirname(path))
def make_out_path(self, *args):
""" Creates an absolute filename from BUILD_DIR and args (single
string or list). """
if isinstance(args, basestring):
args = (args)
args = (self.build_dir,) + args
return self.subst(opj(*args))
def find_prog(self, prog, expand = False):
" Finds a binary in context's PATH. prog not expanded by default. "
mprint("Searching for program %s... " % prog, end = '')
if expand:
prog = self.subst(prog)
try:
p = find_prog(prog, self.env)
mprint("%s" % p)
except:
mprint("not found")
raise
return p
def find_prog_env(self, prog, var = None, expand = False):
""" Finds a program and sets an env var to its full path. If the var
is not specified a capitalised (etc) transform of the program name
is used. """
if not var:
var = s_to_var(prog)
self.env[var] = self.find_prog(prog, expand)
def prog_output(self, prog, use_shell = False):
""" Runs a program and returns its [stdout, stderr]. prog should be a
list or single string (former will not be split at spaces). Each
component will be expanded. cwd is set to BUILD_DIR. """
if isinstance(prog, basestring):
prog = prog.split()
for i in range(len(prog)):
prog[i] = self.subst(prog[i])
if not os.path.isabs(prog[0]):
prog[0] = self.find_prog(prog[0], False)
proc = subprocess.Popen(prog,
stdout = subprocess.PIPE, stderr = subprocess.PIPE,
shell = use_shell, cwd = self.build_dir)
result = proc.communicate()
if proc.returncode:
raise MaitchChildError("%s failed:\n%d:\n%s" % \
(' '.join(prog), proc.returncode, result[1].strip()))
return result
def prog_to_var(self, prog, var, use_shell = False):
" As prog_output(), storing stripped result into self.env[var]. "
output = self.prog_output(prog, use_shell)[0].strip()
dprint("prog_to_var: input: %s" % ' '.join(prog))
dprint("prog_to_var: output: %s" % output)
self.env[var] = output
def pkg_config(self, pkgs, prefix = None, version = None,
pkg_config = "${PKG_CONFIG}"):
""" Runs pkg-config (or optionally a similar tool) and sets
${prefix}_CFLAGS to the output of --flags and ${prefix}_LIBS
to the output of --libs. If prefix is None, derive it from pkg
eg "gobject-2.0 sqlite3" becomes GOBJECT_2_0_SQLITE3.
If version is given, also check that package's version is at least
as new (only works on one package at a time). """
mprint("Checking pkg-config %s..." % pkgs, end = '')
try:
if version:
try:
pvs = self.prog_output(
[pkg_config, '--modversion', pkgs])[0].strip()
except:
mprint("not found")
pkg_v = pvs.split('.')
v = version.split('.')
new_enough = True
for n in range(len(v)):
if v[n] > pkg_v[n]:
new_enough = True
break
elif v[n] < pkg_v[n]:
new_enough = False
break
if not new_enough:
mprint("too old")
raise MaitchPkgError("%s has version %s, "
"%s needs at least %s" %
(pkgs, pvs, self.package_name, version))
if not prefix:
prefix = make_var_name(pkg, True)
pkgs = pkgs.split()
self.prog_to_var([pkg_config, '--cflags'] + pkgs,
prefix + '_CFLAGS')
self.prog_to_var([pkg_config, '--libs'] + pkgs,
prefix + '_LIBS')
except:
mprint("error")
else:
mprint("ok")
def subst(self, s, novar = NOVAR_FATAL, recurse = True, at = False):
" Runs global subst() using self.env. "
return subst(self.env, s, novar, recurse, at)
def deps_from_cpp(self, sources, cppflags = None):
""" Runs "${CDEP} sources" and returns its dependencies
(one file per line). filename should be absolute. If cflags is
None, self.env['CFLAGS'] is used. """
if not cppflags:
cppflags = self.env.get('CPPFLAGS', "")
sources = process_nodes(sources)
sources = [self.find_source(s) for s in sources]
if not sources:
sources = []
prog = (self.subst("${CDEP} %s" % cppflags)).split() + sources
deps = self.prog_output(prog)[0]
deps = deps.split(':', 1)[1].replace('\\', '').split()
return deps
def find_sys_header(self, header, cflags = None):
""" Uses deps_from_cpp() to find the full path of a header in the
include path. Returns None if not found. """
mprint("Looking for header '%s'... " % header, end = '')
tmp = self.tmpname() + ".c"
fp = open(tmp, 'w')
fp.write("#include <%s>\n" % header)
fp.close()
deps = self.deps_from_cpp(tmp, cflags)
os.unlink(tmp)
for d in deps:
if d.endswith(os.sep + header):
mprint("%s" % d)
return d
mprint("not found")
return None
def check_compile(self, code, msg = None, cflags = None, libs = None):
""" Checks whether the program code can be compiled as C, returns
True or False. If msg is given prints "Checking msg... ". """
if msg:
mprint("Checking %s... " % msg, end = '')
if not cflags:
cflags = self.env.get('CFLAGS', "")
if not libs:
libs = self.env.get('LIBS', "")
tmp = self.tmpname()
fp = open(tmp + ".c", 'w')
fp.write(code)
fp.close()
prog = self.subst("${CC} -o %s %s %s %s" %
(tmp, tmp + ".c", libs, cflags)).split()
try:
self.prog_output(prog)
except MaitchChildError as e:
if msg:
mprint("no")
dprint("check_compile failed:\n%s" % str(e))
dprint("code was:\n%s" % code)
result = False
else:
if msg:
mprint("yes")
try:
os.unlink(tmp)
except OSError:
pass
result = True
os.unlink(tmp + ".c")
return result
def check_header(self, header, cflags = None, libs = None):
""" Uses check_compile to test whether header is available, calling
self.define('HAVE_HEADER_H', v) where v is 1 or None and HEADER_H is
derived from header by make_var_name(). Also sets env var with the
same name to True or False. """
if self.check_compile("""#include "%s"
int main() { return 0; }
""" % header,
"for header '%s'" % header, cflags, libs):
present = 1
else:
present = None
nm = make_var_name('HAVE_' + header, True)
self.define(nm, present)
self.setenv(nm, present == 1)
return present == 1
def check_func(self, func, cflags = None, libs = None, includes = None):
""" Like check_header but for a function. includes is an optional
list of header names. """
code = ""
if includes:
for i in includes:
code += '#include "%s"\n' % i
code += """
int main() { %s(); return 0; }
""" % func
if self.check_compile(code, "for function %s()" % func, cflags, libs):
present = 1
else:
present = None
nm = make_var_name('HAVE_' + func, True)
self.define(nm, present)
self.setenv(nm, present == 1)
return present == 1
def find_source(self, name, where = SRC, fatal = True):
""" Finds a source file relative to BUILD_DIR (higher priority) or
SRC_DIR, returning full path or raising exception if not found. Returns
absolute paths unchanged. If fatal is False, unfound files are
returned unchanged"""
name = self.subst(name)
if os.path.exists(name):
return name
if os.path.isabs(name):
if os.path.exists(name):
return name
else:
self.not_found(name)
p = opj(self.build_dir, name)
if os.path.exists(p):
return p
if where & SRC:
p = opj(self.src_dir, name)
if os.path.exists(p):
return p
if where & TOP:
p = opj(self.top_dir, name)
if os.path.exists(p):
return p
if fatal:
self.not_found(name)
else:
return name
@staticmethod
def not_found(name):
raise MaitchNotFoundError("Resource '%s' cannot be found" % name)
def setenv(self, k, v):
" Sets an env var. "
self.env[k] = v
def getenv(self, k, default = None):
" Returns an env var. "
return self.env.get(k)
def get_stamp(self, name, where = NOWHERE):
""" Returns the mtime for named file. Uses find_source() and subst and
therefore may raise MaitchNotFoundError or KeyError. """
n = self.find_source(self.subst(name), where)
return os.stat(name).st_mtime
def get_extreme_stamp(self, nodes, comparator, where = NOWHERE):
""" Like global version, but runs subst() and find_source() on each
item. Items that don't exist are skipped because some suffix rules
don't necessarily use all sources or targets (eg gob2 doesn't always
output a private header). """
pnodes = []
for n in nodes:
try:
pnodes.append(self.find_source(self.subst(n), where))
except MaitchNotFoundError:
pass
return get_extreme_stamp(pnodes, comparator)
def get_oldest(self, nodes, where = NOWHERE):
""" Like global version, but runs subst() and find_source() on each
item, so may raise MaitchNotFoundError or KeyError. """
return self.get_extreme_stamp(nodes, lambda a, b: a < b, where)
def get_newest(self, nodes, where = NOWHERE):
""" Like global version, but runs subst() and find_source() on each
item, so may raise MaitchNotFoundError or KeyError. """
return self.get_extreme_stamp(nodes, lambda a, b: a > b, where)
def subst_file(self, source, target, at = False):
""" As global version, using self.env. """
subst_file(self.env, source, target, at)
self.created_by_config[self.subst(target)] = True
def install(self, directory, sources = None,
mode = None, libtool = False, other_options = None):
""" Uses the install program to install files. Default mode is install's
default mode, which in turn defaults to rwxr-xr-x. sources may be string
with multiple files separated by spaces, or a list, or None to create
directory. other_options, which may also be a string or a list, are
additional options for install.
Automatically creates target directories.
If other_options contains -T, directory is the target filename.
In uninstall mode each installed file/directory is instead added to a
list which will be deleted in reverse order when run() is called. """
directory = process_nodes(directory)
if self.dest_dir:
directory = [self.dest_dir + os.sep + d for d in directory]
directory = [os.path.abspath(d) for d in directory]
if not sources:
sources = []
elif isinstance(sources, basestring):
sources = sources.split()
if len(directory) > 1 and sources:
raise MaitchInstallError("Can't install files to multiple " \
"directories")
if len(sources) > 1 and other_options and "-T" in other_options:
raise MaitchInstallError("Can only install one file where " \
"target is a filename instead of a directory")
if self.mode == 'uninstall':
if other_options and "-T" in other_options:
f = [directory[0]]
elif sources:
f = [opj(directory[0], os.path.basename(f)) \
for f in sources]
else:
f = directory
self.installed.append([f, libtool])
return
sources = [self.find_source(s, TOP | SRC, False) for s in sources]
if libtool:
cmd = ["${LIBTOOL}", "--mode=install", "${INSTALL}"]
else:
cmd = ["${INSTALL}"]
if isinstance(other_options, basestring):
cmd += other_options.split()
elif other_options:
cmd += list(other_options)
if mode:
cmd += ["-m", str(mode)]
if not sources:
cmd.append("-d")
cmd += sources + directory
if sources:
if other_options and "-T" in other_options:
dir = os.path.dirname(directory[0])
else:
dir = directory[0]
if not os.path.isdir(dir):
dd = self.dest_dir
self.dest_dir = None
try:
self.install(dir)
except:
raise
finally:
self.dest_dir = dd
cmd = [self.subst(c) for c in cmd]
mprint("%s" % ' '.join(cmd))
if subprocess.call(cmd, cwd = self.build_dir) != 0:
raise MaitchChildError("install failed")
def install_bin(self, sources, directory = "${BINDIR}", mode = None,
libtool = True, other_options = None):
self.install(directory, sources, mode, libtool, other_options)
def install_lib(self, sources, directory = "${LIBDIR}", mode = '0644',
libtool = True, other_options = None):
self.install(directory, sources, mode, libtool, other_options)
def install_data(self, sources, directory = "${PKGDATADIR}", mode = '0644',
libtool = False, other_options = None):
self.install(directory, sources, mode, libtool, other_options)
def install_doc(self, sources, directory = "${DOCDIR}", mode = '0644',
libtool = False, other_options = None):
self.install(directory, sources, mode, libtool, other_options)
def install_man(self, sources, directory = None, mode = '0644',
other_options = None):
if not directory:
directory = "${MANDIR}"
sources = process_nodes(sources)
dirs = {}
for s in sources:
if s.endswith('.gz'):
f = s[:-3]
else:
f = s
sec = f.rsplit('.', 1)[1]
d = dirs.get(sec)
if not d:
d = []
dirs[sec] = d
d.append(s)
for d, s in dirs.items():
self.install(opj(directory, "man%d" % int(d)), s, '0644')
def uninstall(self):
if not self.installed:
mprint("Noting to uninstall")
return
self.installed.reverse()
for fs, libtool in self.installed:
if libtool:
cmd = ["${LIBTOOL}", "--mode=uninstall", "rm", "-f"] + fs
cmd = [self.subst(c) for c in cmd]
mprint("%s" % ' '.join(cmd))
subprocess.call(cmd, cwd = self.build_dir)
else:
fs = [self.subst(f) for f in fs]
if os.path.isdir(fs[0]):
# If first is directory, then so are the rest
rm = os.rmdir
else:
rm = os.unlink
for f in fs:
self.delete(f, rm)
def delete(self, f, rm = None):
""" Delete a file, which is processed with self.subst(). The default
for rm is os.unlink, use os.rmdir for directories. """
if not rm:
rm = os.unlink
f = self.subst(f)
try:
rm(f)
except OSError:
mprint("Failed to delete '%s'" % f)
else:
mprint("Removed '%s'" % f)
def prune_directory(self, root):
""" Expands variables in root and prefixes ${DESTDIR} before
calling global version. """
# Note we can't use opj because root is (usually) absolute
root = os.path.normpath(self.subst("${DESTDIR}" + os.sep + root))
mprint("Removing empty directories from '%s'" % root)
return prune_directory(root)
class Rule(object):
"""
Standard rule.
"""
def __init__(self, **kwargs):
"""
Possible arguments (all optional except targets):
rule: A function or a string containing a command to be called.
A string should contain "${TGT}" and/or "${SRC}" for
targets and sources. This will not work if they contain spaces.
A function is called as func(ctx, env, [targets], [sources])
where ctx is the Context and targets and soures are expanded.
Note env is not the same as ctx.env, it will have ${TGT} and
${SRC} added.
An additional variable, ${TGT_DIR}, is set to the directory
name of the first target. Note ${TGT_DIR} is absolute but
${TGT} is not.
rule may be a heterogeneous list of functions or strings.
sources: See process_nodes() func for what's valid.
targets: As above, or a function which takes source(s) as input and
returns target(s).
deps: Dependencies other than sources; deps are satisfied before
sources.
wdeps: "Weak dependencies":- the targets will not be built until after
all wdeps are built, but the targets don't necessarily depend
on the wdeps. This makes sure dynamic dependency tracking
works properly when some headers are generated by other steps
eg by making C compiler rules wdep on all files generated by
gob2.
dep_func: A function to calculate implicit deps; takes a ctx and rule
as arguments and returns a list of filenames - absolute or
relative to BUILD_DIR. This is used only to work out whether the
target is out of date and needs to be rebuilt; it is not used
when working out the dependency chain.
use_shell: Whether to use shell if rule is a string (default False).
env: A dict containing env vars to override those from Context. Each
var may refer to its own name in its value to derive values
from the Context.
quiet: If True don't print the command about to be executed.
where: Where to look for sources: SRC, TOP or both (default SRC).
lock: Some jobs can't be run simultaneously so you can pass in a Lock
object to prevent that.
diffpat: If this is given (a list or string) it invokes special
behaviour. For each target T, if T already exists it's backed
up to T.old before running the rule. Then T is compared
line-by-line with T.old. Lines containing a match for a regex
in diffpat are considered equal. If the files are equal T is
replaced by T.old and touched.
This is to prevent VCS conflicts when a build changes a
POT-Creation-Date but not the content.
"""
if not 'where' in kwargs:
kwargs['where'] = SRC
rule = kwargs.get('rule')
if callable(rule) or isinstance(rule, basestring):
self.rules = [rule]
else:
self.rules = rule
self.sources = kwargs.get('sources')
if self.sources and isinstance(self.sources, basestring):
self.sources = process_nodes(self.sources)
self.targets = kwargs['targets']
if callable(self.targets):
self.targets = self.targets(self.sources)
elif isinstance(self.targets, basestring):
self.targets = process_nodes(self.targets)
self.deps = kwargs.get('deps')
if self.deps and isinstance(self.deps, basestring):
self.deps = process_nodes(self.deps)
self.wdeps = kwargs.get('wdeps')
if self.wdeps and isinstance(self.wdeps, basestring):
self.wdeps = process_nodes(self.wdeps)
self.dep_func = kwargs.get('dep_func')
self.use_shell = kwargs.get('use_shell')
self.env = kwargs.get('env')
self.quiet = kwargs.get('quiet')
self.blocking = []
self.blocked_by = []
self.completed = False
self.cached_env = None
self.cached_targets = None
self.cached_sources = None
self.cached_deps = []
self.where = kwargs['where']
self.lock = kwargs.get('lock')
diffpat = kwargs.get('diffpat')
if isinstance(diffpat, basestring):
diffpat = [diffpat]
if diffpat:
self.diffpat = [re.compile(d) for d in diffpat]
else:
self.diffpat = None
@staticmethod
def init_var(kwargs, var):
""" Call this from subclass' constructor if it uses var (specified in
lower case). If kwargs includes a key 'var' (lower case) env[VAR_] is
set to its value. Note the trailing _. This is because a variable
overridden here would commonly want to refer to itself (as ${VAR}) but
can't due to recursion. So accompanying variables should refer to one
set here with the trailing _. If kw var is not present, env[VAR_] is set
to ${VAR}. See CRule's use of libs and cflags for an example. """
val = kwargs.get(var)
if not val:
val = "${%s}" % var.upper()
env = kwargs.get('env')
if not env:
env = {}
kwargs['env'] = env
env[var.upper() + '_'] = val
def init_cflags(self, kwargs):
" For rules which use cflags. "
self.init_var(kwargs, 'cflags')
def init_libs(self, kwargs):
" For rules which use libs. "
self.init_var(kwargs, 'libs')
def process_env(self):
" Merges env with ctx's, with caching. Does not set TGT or SRC. "
if self.cached_env == None:
env = dict(self.ctx.env)
if self.env:
for k, v in self.env.items():
env[k] = v
self.cached_env = env
return self.cached_env
def process_env_tgt_src(self):
""" As process_env, but also returns expanded targets and sources
[env, targets sources] and adds them to env. """
env = self.process_env()
if self.cached_targets == None:
# Expand targets and sources, finding the sources, and prefixing
# targets with build_dir.
targets = [subst(env, t) for t in self.targets]
if self.sources:
sources = [self.ctx.find_source(subst(env, s), self.where) \
for s in self.sources]
else:
sources = None
# Add them to env
if sources:
env['SRC'] = ' '.join(sources)
else:
env['SRC'] = ''
if targets:
env['TGT'] = ' '.join(targets)
td = os.path.dirname(targets[0])
if not os.path.isabs(td):
td = opj(self.ctx.build_dir, td)
env['TGT_DIR'] = td
else:
env['TGT'] = ''
env['TGT_DIR'] = ''
self.cached_targets = targets
self.cached_sources = sources
return [self.cached_env, self.cached_targets, self.cached_sources]
def run(self):
" Run a job. "
if self.is_uptodate():
return
env, targets, sources = self.process_env_tgt_src()
if self.lock:
self.lock.acquire()
if self.diffpat:
for t in self.targets:
if os.path.exists(t):
shutil.copy(t, t + '.old')
try:
for rule in self.rules:
if callable(rule):
if not self.quiet:
mprint("Internal function: %s(%s, %s)" %
(rule.__name__, str(targets), str(sources)))
rule(self.ctx, env, targets, sources)
else:
r = subst(env, rule)
if not self.quiet:
mprint(r)
if self.use_shell:
prog = r
else:
prog = r.split()
if call_subprocess(prog,
shell = self.use_shell, cwd = self.ctx.build_dir):
dprint("%s NZ error code" % r)
raise MaitchChildError("Rule '%s' failed" % rule)
else:
dprint("%s executed successfully" % r)
except:
raise
else:
if self.diffpat:
for t in self.targets:
same = False
s = t + '.old'
if os.path.exists(t) and os.path.exists(s):
f = open(s, 'r')
u = f.readlines()
f.close()
f = open(t, 'r')
v = f.readlines()
f.close()
if len(u) == len(v):
same = True
for n in range(len(u)):
if u[n] != v[n]:
same = False
for p in self.diffpat:
if p.search(u[n]) and p.search(v[n]):
same = True
break
if not same:
break
if same:
os.rename(s, t)
else:
os.unlink(s)
finally:
if self.lock:
self.lock.release()
def __repr__(self):
return "JT:%s" % self.targets
#return "T:%s S:%s" % (self.targets, self.sources)
def list_static_deps(self):
""" Works out a rule's static dependencies ie deps + sources, but not
dep_func. Caches them and returns list. """
if self.deps:
deps = self.deps
else:
deps = []
if self.sources:
deps += self.sources
self.cached_deps = deps
return deps
def is_uptodate(self):
""" Returns False if any target is older than any source, dep, or result
of dep_func (implicit/dynamic deps). """
# If there are no dependencies target(s) must be rebuilt every time
if not self.cached_deps:
return False
# First find whether uptodate wrt static deps.
# If result is True extra variable newest_dep is available
uptodate = True
try:
oldest_target = self.ctx.get_oldest(self.targets, NOWHERE)
except MaitchNotFoundError, KeyError:
oldest_target = None
if not oldest_target:
uptodate = False
if uptodate:
# All sources and deps should be available at this point so
# OK to let exception propagate
newest_dep = self.ctx.get_newest(self.cached_deps, self.where)
if newest_dep and newest_dep > oldest_target:
uptodate = False
else:
newest_dep = None
if self.dep_func:
# Work out whether cached dynamic deps need updating
dyn_deps = None
deps_name = self.ctx.make_out_path(self.ctx.subst(
opj(".maitch", "deps", self.targets[0])))
if os.path.exists(deps_name):
deps_stamp = os.stat(deps_name).st_mtime
if not newest_dep:
newest_dep = self.ctx.get_newest(self.cached_deps,
self.where)
if newest_dep and newest_dep > deps_stamp:
# sources/static deps are newer than dynamics
rebuild_deps = True
else:
# see whether cached deps are older than any file they list
dyn_deps = load_deps(deps_name)
newest_impl_dep = get_newest(dyn_deps)
if newest_impl_dep > newest_dep:
newest_dep = newest_impl_dep
rebuild_deps = newest_impl_dep > deps_stamp
else:
rebuild_deps = True
if rebuild_deps:
dyn_deps = self.dep_func(self.ctx, self)
self.ctx.ensure_out_dir_for_file(deps_name)
fp = open(deps_name, 'w')
for d in dyn_deps:
fp.write(d + '\n')
fp.close()
if not dyn_deps:
dyn_deps = load_deps(deps_name)
# Now we have up-to-date implicit dyn_deps, check whether targets
# are older than them
if get_newest(dyn_deps) > oldest_target:
uptodate = False
return uptodate
class SuffixRule(Rule):
""" A rule where targets is a function that transforms sources by changing
their suffix, and optionally prefix. """
def __init__(self, **kwargs):
""" args are similar to those for a standard Rule but targets should
not be specified. deps are complete filenames as with explicit Rules.
sources and rule are compulsory.
suffix (compulsory): Suffix to be applied to targets. Source suffixes to
be stripped are inferred by looking for last period. Do not
include period, it's implied.
prefix (optional): Added to the start of the targets' leafname(s) -
after any directory components. Any separator between the prefix
and leafname (eg '-') should be included at the end of the
prefix. """
self.suffix = kwargs['suffix']
self.prefix = kwargs.get('prefix', '')
set_default(kwargs, 'targets', self.transform)
Rule.__init__(self, **kwargs)
def transform(self, sources):
targets = []
for s in sources:
s = s.rsplit('.', 1)[0]
if len(self.prefix):
p, l = os.path.split(s)
l = self.prefix + l
if p:
s = os.path.join(p, l)
else:
s = l
targets.append(s + '.' + self.suffix)
return targets
class TouchRule(Rule):
""" Use this as a dummy rule rather than use a Rule with no rule parameter.
The target(s) will be "touched" to update their timestamp. """
def __init__(self, **kwargs):
set_default(kwargs, 'rule', self.touch)
Rule.__init__(self, **kwargs)
def touch(self, ctx, env, tgts, srcs):
for t in tgts:
fp = open(t, 'w')
fp.close()
class CRuleBase(SuffixRule):
" Standard rule for compiling C to an object file. "
def __init__(self, **kwargs):
self.flagsname = kwargs['flagsname']
set_default(kwargs, 'rule', "${%s} ${%s_} -c -o ${TGT} ${SRC}" %
(kwargs['compiler'], self.flagsname))
set_default(kwargs, 'suffix', "o")
set_default(kwargs, 'dep_func', self.get_implicit_deps)
SuffixRule.__init__(self, **kwargs)
def get_implicit_deps(self, ctx, rule):
# rule will be a static rule generated from self with a single source
env = self.process_env()
try:
return ctx.deps_from_cpp(rule.sources, env[self.flagsname + '_'])
except MaitchNotFoundError:
return None
class CRule(CRuleBase):
" Standard rule for compiling C to an object file. "
def __init__(self, **kwargs):
self.init_cflags(kwargs)
set_default(kwargs, 'compiler', "CC");
set_default(kwargs, 'flagsname', "CFLAGS");
CRuleBase.__init__(self, **kwargs)
class CxxRule(CRuleBase):
" Standard rule for compiling C++ to an object file. "
def __init__(self, **kwargs):
self.init_var(kwargs, 'CXXFLAGS')
set_default(kwargs, 'compiler', "CXX");
set_default(kwargs, 'flagsname', "CXXFLAGS");
CRuleBase.__init__(self, **kwargs)
class LibtoolCRuleBase(CRuleBase):
def __init__(self, **kwargs):
""" Additional kwargs:
libtool_flags.
libtool_mode_arg: -shared, -static etc.
"""
self.init_var(kwargs, 'libtool_flags')
self.init_var(kwargs, 'libtool_mode_arg')
set_default(kwargs, 'suffix', "lo")
set_default(kwargs, 'rule',
"${LIBTOOL} --mode=compile --tag=%s ${LIBTOOL_FLAGS_} "
"${%s} ${LIBTOOL_MODE_ARG_} ${%s_} -c -o ${TGT} ${SRC}" %
(kwargs['tag'], kwargs['compiler'], kwargs['flagsname']))
CRuleBase.__init__(self, **kwargs)
class LibtoolCRule(LibtoolCRuleBase):
" libtool version of CRule. "
def __init__(self, **kwargs):
""" Additional kwargs:
libtool_flags.
libtool_mode_arg: -shared, -static etc.
"""
self.init_cflags(kwargs)
set_default(kwargs, 'compiler', "CC");
set_default(kwargs, 'flagsname', "CFLAGS");
set_default(kwargs, 'tag', "CC");
LibtoolCRuleBase.__init__(self, **kwargs)
class LibtoolCxxRule(LibtoolCRuleBase):
" libtool version of CxxRule. "
def __init__(self, **kwargs):
""" Additional kwargs:
libtool_flags.
libtool_mode_arg: -shared, -static etc.
"""
self.init_var(kwargs, 'cxxflags')
set_default(kwargs, 'compiler', "CXX");
set_default(kwargs, 'flagsname', "CXXFLAGS");
set_default(kwargs, 'tag', "CXX");
LibtoolCRuleBase.__init__(self, **kwargs)
class ShlibCRule(LibtoolCRule):
" Compiles C into an object file suitable for a shared library. "
def __init__(self, **kwargs):
kwargs['libtool_mode_arg'] = "-shared %s" % \
kwargs.get('libtool_mode_arg', '')
LibtoolCRule.__init__(self, **kwargs)
class StaticLibCRule(LibtoolCRule):
" Compiles C into an object file suitable for a static library. "
def __init__(self, **kwargs):
kwargs['libtool_mode_arg'] = "-static %s" % \
kwargs.get('libtool_mode_arg', '')
LibtoolCRule.__init__(self, **kwargs)
class ShlibCxxRule(LibtoolCxxRule):
" Compiles C++ into an object file suitable for a shared library. "
def __init__(self, **kwargs):
kwargs['libtool_mode_arg'] = "-shared %s" % \
kwargs.get('libtool_mode_arg', '')
LibtoolCxxRule.__init__(self, **kwargs)
class StaticLibCxxRule(LibtoolCxxRule):
" Compiles C++ into an object file suitable for a static library. "
def __init__(self, **kwargs):
kwargs['libtool_mode_arg'] = "-static %s" % \
kwargs.get('libtool_mode_arg', '')
LibtoolCxxRule.__init__(self, **kwargs)
class ProgramRuleBase(Rule):
" Standard rule for linking mutiple object files and libs into a program. "
def __init__(self, **kwargs):
self.init_libs(kwargs)
self.init_var(kwargs, 'ldflags')
set_default(kwargs, 'rule',
"${%s} ${%s_} ${LIBS_} ${LDFLAGS_} -o ${TGT} ${SRC}" %
(kwargs['linker'], kwargs['flagsname']))
Rule.__init__(self, **kwargs)
class CProgramRule(Rule):
"Standard rule for linking C object files and libs into a program."
def __init__(self, **kwargs):
self.init_cflags(kwargs)
set_default(kwargs, 'linker', "CC");
set_default(kwargs, 'flagsname', "CFLAGS");
ProgramRuleBase.__init__(self, **kwargs)
class CxxProgramRule(Rule):
"Standard rule for linking C++ object files and libs into a program."
def __init__(self, **kwargs):
self.init_cflags(kwargs)
set_default(kwargs, 'linker', "CXX");
set_default(kwargs, 'flagsname', "CXXFLAGS");
ProgramRuleBase.__init__(self, **kwargs)
class LibtoolProgramRuleBase(ProgramRuleBase):
" Use libtool during linking. "
def __init__(self, **kwargs):
self.init_var(kwargs, 'libtool_flags')
self.init_var(kwargs, 'libtool_mode_arg')
set_default(kwargs, 'rule',
"${LIBTOOL} --mode=link --tag=%s ${LIBTOOL_FLAGS_} "
"${%s} ${LIBTOOL_MODE_ARG_} "
"${%s_} ${LIBS_} ${LDFLAGS_} -o ${TGT} ${SRC}" %
(kwargs['tag'], kwargs['linker'], kwargs['flagsname']))
ProgramRuleBase.__init__(self, **kwargs)
class LibtoolCProgramRule(LibtoolProgramRuleBase):
" Use libtool to link C. "
def __init__(self, **kwargs):
self.init_cflags(kwargs)
set_default(kwargs, 'linker', "CC");
set_default(kwargs, 'flagsname', "CFLAGS");
set_default(kwargs, 'tag', "CC");
LibtoolProgramRuleBase.__init__(self, **kwargs)
class LibtoolCxxProgramRule(LibtoolProgramRuleBase):
" Use libtool to link C. "
def __init__(self, **kwargs):
self.init_var(kwargs, 'cxxflags')
set_default(kwargs, 'linker', "CXX");
set_default(kwargs, 'flagsname', "CXXFLAGS");
set_default(kwargs, 'tag', "CXX");
LibtoolProgramRuleBase.__init__(self, **kwargs)
class CShlibRule(LibtoolCProgramRule):
""" Standard rule to create a shared C library with libtool. See the
libtool manual for an explanation of its interface version system.
-release is not supported (yet). """
def __init__(self, **kwargs):
version = kwargs.get('libtool_version')
if version:
version = "-version-info %d:%d:%d" % tuple(version)
else:
version = ""
kwargs['libtool_mode_arg'] = "-shared %s %s" % \
(kwargs.get('libtool_mode_arg', ''), version)
LibtoolCProgramRule.__init__(self, **kwargs)
class CxxShlibRule(LibtoolCxxProgramRule):
""" Standard rule to create a shared C++ library with libtool. See the
libtool manual for an explanation of its interface version system.
-release is not supported (yet). """
def __init__(self, **kwargs):
version = kwargs.get('libtool_version')
if version:
version = "-version-info %d:%d:%d" % tuple(version)
else:
version = ""
kwargs['libtool_mode_arg'] = "-shared %s %s" % \
(kwargs.get('libtool_mode_arg', ''), version)
LibtoolCxxProgramRule.__init__(self, **kwargs)
class CStaticLibRule(LibtoolCProgramRule):
""" Standard rule to create a static C library with libtool. See the
libtool manual for an explanation of its interface version system.
-release is not supported (yet). """
def __init__(self, **kwargs):
version = kwargs.get('libtool_version')
if version:
version = "-version-info %d:%d:%d" % tuple(version)
else:
version = ""
kwargs['libtool_mode_arg'] = "-static %s %s" % \
(kwargs.get('libtool_mode_arg', ''), version)
LibtoolCProgramRule.__init__(self, **kwargs)
class CxxStaticLibRule(LibtoolCxxProgramRule):
""" Standard rule to create a static C++ library with libtool. See the
libtool manual for an explanation of its interface version system.
-release is not supported (yet). """
def __init__(self, **kwargs):
version = kwargs.get('libtool_version')
if version:
version = "-version-info %d:%d:%d" % tuple(version)
else:
version = ""
kwargs['libtool_mode_arg'] = "-static %s %s" % \
(kwargs.get('libtool_mode_arg', ''), version)
LibtoolCxxProgramRule.__init__(self, **kwargs)
def mkdir_rule(ctx, env, targets, sources):
""" A rule function to ensure targets' directories exist. """
for t in targets:
ctx.ensure_out_dir_for_file(t)
def PotRules(ctx, **kwargs):
""" Returns a pair (list) of rules for generating a .pot file from a list of
source files eg POTFILES.in where filenames are relative to TOP_DIR. Default
source is "${TOP_DIR}/po/POTFILES.in", default target is
${TOP_DIR}/po/${PACKAGE}.pot.
rule defaults to ${XGETTEXT}, may be overridden - note that source for this
rule is generated POTFILES, not POTFILES.in.
XGETTEXT is not set by default. *_XGETTEXT_OPTS is generated on the fly.
Special args:
copyright_holder
package
version
bugs_addr
opts_prefix: Goes on front of _XGETTEXT_OPTS added to env.
'^"POT-Creation-Date:' is added to a new or existing diffpat.
"""
def generate_potfiles(ctx, env, targets, sources):
potfiles = []
for s in sources:
fp = open(subst(env, s), 'r')
for f in fp.readlines():
f = f.strip()
if len(f) and f[0] != '#':
potfiles.append(opj(env['TOP_DIR'], f.strip()))
fp.close()
t = subst(env, targets[0])
ctx.ensure_out_dir_for_file(t)
fp = open(t, 'w')
for f in potfiles:
fp.write("%s\n" % f)
fp.close()
def pot_deps(ctx, rule):
deps = []
for s in process_nodes(rule.sources):
fp = open(ctx.subst(s), 'r')
for f in fp.readlines():
deps.append(f.strip())
return deps
opts_prefix = kwargs.get('opts_prefix', "")
varname = "%s_XGETTEXT_OPTS" % opts_prefix
if not 'where' in kwargs:
kwargs['where'] = SRC | TOP
try:
src1 = kwargs['sources']
except KeyError:
src1 = ["${TOP_DIR}/po/POTFILES.in"]
rule1 = Rule(rule = generate_potfiles,
sources = src1,
targets = ["${BUILD_DIR}/po/POTFILES"],
where = kwargs['where'])
kwargs['sources'] = ["${BUILD_DIR}/po/POTFILES"]
if not 'targets' in kwargs:
kwargs['targets'] = ["${TOP_DIR}/po/${PACKAGE}.pot"]
if not 'rule' in kwargs:
kwargs['rule'] = "${XGETTEXT} ${%s} -f ${SRC} -o ${TGT}" % varname
if not 'dep_func' in kwargs:
kwargs['dep_func'] = pot_deps
xgto = []
copyrt = kwargs.get('copyright_holder')
if copyrt:
xgto.append('--copyright-holder=%s' % copyrt)
pkg = kwargs.get('package')
if not pkg:
pkg = "${PACKAGE}"
xgto.append('--package-name=${PACKAGE}')
ver = kwargs.get('version')
if ver:
xgto.append('--package-version=%s' % ver)
ba = kwargs.get('bugs_addr')
if ba:
xgto.append('--msgid-bugs-address=%s' % ba)
for n in range(len(xgto)):
s = ctx.subst(xgto[n])
if any([ascii.isspace(c) for c in s]):
if "'" in s:
if '"' in s:
raise MaitchRuleError(
"Unable to quote xgettext option: %s" % s)
xgto[n] = '"%s"' % s
else:
xgto[n] = "'%s'" % s
kwargs['use_shell'] = True
ctx.setenv(varname, ' '.join(xgto))
diffpat = kwargs.get('diffpat')
if not diffpat:
diffpat = []
kwargs['diffpat'] = diffpat
elif isinstance(diffpat, basestring):
diffpat = [diffpat]
kwargs['diffpat'] = diffpat
if not '^"POT-Creation-Date:' in diffpat:
diffpat.append('^"POT-Creation-Date:')
rule2 = Rule(**kwargs)
return [rule1, rule2]
class PoRule(Rule):
""" Updates a po file from a pot (default src is
${TOP_DIR}/po/${PACKAGE}.pot). """
def __init__(self, *args, **kwargs):
if not 'sources' in kwargs:
kwargs['sources'] = "${TOP_DIR}/po/${PACKAGE}.pot"
if not 'rule' in kwargs:
kwargs['rule'] = "${MSGMERGE} -q -U ${TGT} ${SRC}"
diffpat = kwargs.get('diffpat')
if not diffpat:
diffpat = []
kwargs['diffpat'] = diffpat
elif isinstance(diffpat, basestring):
diffpat = [diffpat]
kwargs['diffpat'] = diffpat
if not '^"POT-Creation-Date:' in diffpat:
diffpat.append('^"POT-Creation-Date:')
Rule.__init__(self, *args, **kwargs)
def parse_linguas(ctx, podir = None, linguas = None):
if not podir:
podir = opj("${TOP_DIR}", "po")
if not linguas:
linguas = opj(podir, "LINGUAS")
langs = []
fp = open(ctx.subst(linguas), 'r')
for l in fp.readlines():
l = l.strip()
if not l or l[0] == '#':
continue
langs.append(l)
fp.close()
return langs
def PoRulesFromLinguas(ctx, *args, **kwargs):
""" Generates a PoRule for each language listed in linguas. Default linguas
is podir/LINGUAS. Default podir is ${TOP_DIR}/po. Other args are passed to
each PoRule. Also generates .mo rules unless nomo is True. """
podir = kwargs.get('podir')
if not podir:
podir = opj("${TOP_DIR}", "po")
linguas = kwargs.get('linguas')
if not linguas:
linguas = opj(podir, "LINGUAS")
nomo = kwargs.get("nomo")
langs = parse_linguas(ctx, linguas = linguas)
rules = []
for l in langs:
f = opj(podir, l + ".po")
if not os.path.isfile(ctx.subst(f)):
raise MaitchNotFoundError("Linguas file %s includes %s, "
"but no corresponding po file found" % (linguas, l))
kwargs['targets'] = f
rules.append(PoRule(*args, **kwargs))
if not nomo:
rules.append(Rule(rule = "${MSGFMT} -c -o ${TGT} ${SRC}",
targets = opj("po", l + ".mo"),
sources = f))
return rules
def StandardTranslationRules(ctx, *args, **kwargs):
""" Returns all rules necessary to build translation files. kwargs are as
for PotRules + PoRulesForLinguas """
return PotRules(ctx, *args, **kwargs) + \
PoRulesFromLinguas(ctx, *args, **kwargs)
def call_subprocess(*args, **kwargs):
""" Like subprocess.Call() with stdout and stderr logged.
stdout and stderr in kwargs are overridden. """
kwargs['stdout'] = subprocess.PIPE
kwargs['stderr'] = subprocess.PIPE
sp = subprocess.Popen(*args, **kwargs)
dprint("%s has pid %d" % (args, sp.pid))
[out, err] = sp.communicate()
dprint("pid %d finished, output follows" % sp.pid)
out = out.strip()
if out:
mprint(out)
err = err.strip()
if err:
mprint(err, file = sys.stderr)
return sp.returncode
def report_exception():
""" Reports the last raised exception. """
mprint(traceback.format_exc(), file = sys.stderr)
def print_formatted(body, columns = 80, heading = None, h_columns = 20):
""" Prints body, wrapped at the specified number of columns. If heading is
given, h_columns are reserved on the left for it. """
if heading and len(heading) >= h_columns:
print_wrapped(heading, columns)
print_wrapped(body, columns, h_columns)
elif heading:
print_wrapped(heading + ' ' * (h_columns - len(heading)) + body,
columns, h_columns, 0)
else:
print_wrapped(body, columns, h_columns)
def print_wrapped(s, columns = 80, indent = 0, first_indent = None,
file = sys.stdout):
""" Prints s wrapped to fit in columns, optionally indented,
with an optional alternative indent for the first line. """
if first_indent == None:
first_indent = indent
i = ' ' * first_indent
current_indent = first_indent
while len(s) > columns - current_indent:
l = s[:columns - current_indent]
s = s[columns - current_indent:]
if ascii.isspace(l[-1]):
l = l[:-1]
split = []
else:
split = l.rsplit(None, 1)
if len(split) > 1:
l = split[0]
s = split[1] + s
file.write("%s%s\n" % (i, l))
i = ' ' * indent
current_indent = indent
if s:
file.write("%s%s\n" % (i, s))
file.flush()
def subst_file(env, source, target, at = False):
""" Run during configure phase to create a copy of source as target
with ${} constructs substituted. Uses save_if_different() to avoid
unnecessary rebuilds. """
fp = open(subst(env, source), 'r')
s = fp.read()
fp.close()
save_if_different(subst(env, target), subst(env, s, at = at))
def save_if_different(filename, content):
""" Saves content to filename, only if file doesn't already contain
identical content. """
if os.path.exists(filename):
fp = open(filename, 'r')
old = fp.read()
fp.close()
else:
old = None
if content != old:
if old == None:
mprint("Creating '%s'" % filename)
else:
mprint("Updating '%s'" % filename)
fp = open(filename, 'w')
fp.write(content)
fp.close()
else:
mprint("'%s' is unchanged" % filename)
def set_default(d, k, v):
" Sets d[k] = v only if d doesn't already contain k. "
if not d.get(k):
d[k] = v
def opj(*args):
""" Like os.path.join and also calls os.path.normpath """
return os.path.normpath(os.path.join(*args))
def prune_directory(root):
""" Recursively moves all empty directories at root. Returns False if
remaining files meant one or more directories could not be deleted. """
if not os.path.exists(root):
return True
success = True
subs = os.listdir(root)
for n in subs:
n = opj(root, n)
if os.path.isdir(n):
success = prune_directory(n) and success
elif os.path.exists(n):
mprint("Unable to remove non-empty directory '%s'" % root,
file = sys.stderr)
success = False
if success:
try:
os.rmdir(root)
except:
mprint("Unable to remove directory '%s'" % root, file = sys.stderr)
success = False
return success
_subst_re = re.compile(r"(\$\{-?([a-zA-Z0-9_]+)\})")
_subst_re_at = re.compile(r"(@-?([a-zA-Z0-9_]+)@)")
def subst(env, s, novar = NOVAR_FATAL, recurse = True, at = False):
"""
Processes string s, substituting ${var} with values from dict env
with var as the key. To prevent substitution put a '-' after the
opening brace. It will be removed. Most variables are expanded
recursively immediately before use.
If fatal is False, bad matches are left unexpanded.
If at is True, substitute @VAR@ instead.
"""
def ms(match):
s = match.group(2)
if s[0] == '-':
if at:
return "@%s@" % s[1:]
else:
return "${%s}" % s[1:]
elif novar == NOVAR_FATAL:
return env[s]
else:
if novar == NOVAR_BLANK:
dr = ''
else:
dr = match.group(0)
return env.get(s, dr)
if at:
rex = _subst_re_at
else:
rex = _subst_re
result, n = rex.subn(ms, s)
if recurse and n:
return subst(env, result, novar, True, at)
return result
def process_nodes(nodes):
"""
nodes may be a string with a single node filename, several names
separated by spaces, or a list of strings - one per node, each may
contain spaces. Returns a list of nodes.
"""
if isinstance(nodes, basestring):
return nodes.split()
else:
return list(nodes)
def recursively_remove(path, fatal, excep):
""" Deletes path and all its contents, leaving behind exceptions.
Returns False if path could not be deleted because it contains an
exception. If something can not be deleted only propagate exception
if fatal is True. """
if fatal:
contents = os.listdir(path)
else:
try:
contents = os.listdir(path)
except:
return True
removable = True
if contents:
for f in contents:
f = opj(path, f)
if f in excep:
removable = False
elif os.path.isdir(f):
if not recursively_remove(f, fatal, excep):
removable = False
elif fatal:
os.unlink(f)
else:
try:
os.unlink(f)
except OSError:
removable = False
if removable:
if fatal:
os.rmdir(path)
else:
try:
os.rmdir(path)
except OSError:
removable = False
return removable
def find_prog(name, env = os.environ):
if os.path.isabs(name):
return name
path = env.get('PATH', '/bin:/usr/bin:/usr/local/bin')
for p in path.split(':'):
n = opj(p, name)
if os.path.exists(n):
return n
raise MaitchNotFoundError("%s program not found in PATH" % name)
_var_repository = []
def add_var(name, default = "", desc = "", as_arg = False):
"""
Registers a variable name with a default value which will be used if the
variable isn't specified on the command-line. If as_arg is True it can
be specified as a -- option ie --foo-bar=baz is equivalent to the usual
form FOO_BAR=baz. default may be a function, called as function(name)
to calculate the default value dynamically.
"""
global _var_repository
_var_repository.append([name, default, desc, as_arg])
_prog_var_repository = {}
def add_prog(var, prog):
global _prog_var_repository
_prog_var_repository[var] = prog
def find_prog_by_var(var):
p = _prog_var_repository.get(var)
if not p:
p = var_to_s(var)
return find_prog(p)
def s_to_var(s):
return s.upper().replace('-', '_').replace('.', '_').replace(' ', '_')
def var_to_s(s):
return s.lower().replace('_', '-')
def arg_to_var(s):
return s_to_var(s[2:])
def var_to_arg(s):
return '--' + var_to_s(s)
def make_var_name(template, upper = False):
""" Makes an eligible variable name from template by replacing special
characters with '_' and also prepending a '_' if template has a leading
digit. ALso optionally converts to upper case. """
if ascii.isdigit(template[0]):
s = "_"
else:
s = ""
for c in template:
if c != '_' and not ascii.isalnum(c):
s += "_"
else:
s += c
if upper:
s = s.upper()
return s
def change_suffix(files, old, new):
""" Returns a new list of files with old suffix replaced with new
(include the '.' in the parameters). files may be a space-separated string
or a list/tuple of strings. Non-matching suffixes are left unchanged. """
changed = []
if isinstance(files, basestring):
files = files.split()
l = len(old)
for f in files:
if f.endswith(old):
f = f[:-l] + new
changed.append(f)
return changed
def add_prefix(files, prefix):
""" Returns a new list of files with prefix added to leafname.
files may be a space-separated string or a list/tuple of strings. """
changed = []
if isinstance(files, basestring):
files = files.split()
changed = []
for f in files:
head, tail = os.path.split(f)
changed.append(opj(head, prefix + tail))
return changed
def change_suffix_with_prefix(files, old, new, prefix):
return add_prefix(change_suffix(files, old, new), prefix)
def get_extreme_stamp(nodes, comparator):
""" Gets stamp for each item in nodes and returns the highest
according to comparator. Returns None for an empty list or raises
MaitchNotFoundError if any member is not found. """
stamp = None
for n in nodes:
if not os.path.exists(n):
raise MaitchNotFoundError("Can't find '%s' to get timestamp" % n)
s = os.stat(n).st_mtime
if stamp == None:
stamp = s
else:
r = comparator(s, stamp)
if r == True or r > 0:
stamp = s
return stamp
def get_oldest(nodes):
""" See get_extreme_stamp(). """
return get_extreme_stamp(nodes, lambda a, b: a < b)
def get_newest(nodes):
""" See get_extreme_stamp(). """
return get_extreme_stamp(nodes, lambda a, b: a > b)
def load_deps(f):
""" Loads a list of filenames from file with absolute name f. """
fp = open(f, 'r')
deps = []
while 1:
l = fp.readline()
if l:
deps.append(l.strip())
else:
break
fp.close()
return deps
class BuildGroup(object):
" Class to organise the build, arranging tasks in order of dependency. "
def __init__(self, ctx, targets):
""" ctx is the context containing info for the build. targets is a
list of targets. """
self.ctx = ctx
# cond is used to allow builders to wait until a new task is ready
# and to access the queue in a thread-safe way
self.cond = threading.Condition(ctx.lock)
# ready_queue isn't really ordered, jobs are just appended as they
# become unblocked. This is nice and simple.
# Additionally all jobs are added to ready_queue before checking
# up-to-dateness; this is checked just before they would run and
# up-to-date jobs are skipped and handled as if they were just run.
self.ready_queue = []
# quick way to find whether a target is due to be, or has been, built
self.queued = {}
# Jobs are added here until unblocked, then moved to ready_queue
self.pending_jobs = []
# Add jobs
for tgt in targets:
self.add_target(tgt)
# Start builders
self.cancelled = False
self.threads = []
n = int(self.ctx.env.get('PARALLEL', 1))
if n < 1:
n = 1
mprint("Starting %d build thread(s)" % n)
for n in range(n):
t = Builder(self)
self.threads.append(t)
t.start()
# Wait for threads; doesn't matter what order they finish in
for t in self.threads:
dprint("Main loop waiting for %s to finish" % t.describe())
t.join()
def add_target(self, target):
if not target in self.queued:
self.add_job(self.ctx.explicit_rules[target])
def add_job(self, job):
if job in self.pending_jobs:
return
job.calculating = True
with self.cond:
self.pending_jobs.append(job)
for t in job.targets:
self.queued[self.ctx.subst(t)] = job
self.satisfy_deps(job)
job.calculating = False
if not len(job.blocked_by):
self.do_while_locked(self.make_job_ready, job)
def do_while_locked(self, func, *args, **kwargs):
""" Lock cond and run func(*args, **kwargs), handling errors in a
thread-safe way. Returns result of func. """
self.cond.acquire()
try:
result = func(*args, **kwargs)
except:
self.cancel_all_jobs()
self.cond.release()
raise
self.cond.release()
return result
def cancel_all_jobs(self):
dprint("Cancelling all jobs")
# Cond.notify_all() sometimes freezes all threads instead of
# awakening them, so only choice is to exit
with self.cond:
if not self.cancelled:
self.cancelled = True
self.ready_queue = []
self.pending_jobs = []
self.cond.notify_all()
dprint("Leaving cancel_all_jobs")
def make_job_ready(self, job):
" Moves a job from pending_jobs to ready_queue. "
with self.cond:
# We may still get here after all jobs have been cancelled due
# to an error
try:
self.pending_jobs.remove(job)
except ValueError:
pass
else:
self.ready_queue.append(job)
self.cond.notify()
def satisfy_deps(self, job):
if job.wdeps:
deps = job.wdeps
else:
deps = []
sdeps = job.list_static_deps()
if sdeps:
deps += sdeps
if not len(deps):
return
for dep in deps:
dep = self.ctx.subst(dep)
try:
# Has a rule to build this dep already been queued?
rule = self.queued.get(dep)
if rule:
if rule.calculating:
raise MaitchRecursionError("%s and %s have circular "
"dependencies" % (rule, dep))
self.mark_blocking(job, rule)
continue
# Is there an explicit rule for it?
rule = self.ctx.explicit_rules.get(dep)
if rule:
self.mark_blocking(job, rule)
self.add_job(rule)
continue
# Does file already exist?
self.ctx.find_source(dep, job.where)
except:
mprint("Error trying to satisfy dep '%s' of '%s'" % (dep, job),
file = sys.stderr)
raise
def mark_blocking(self, blocked, blocker):
with self.cond:
if not blocked in blocker.blocking:
blocker.blocking.append(blocked)
if not blocker in blocked.blocked_by:
blocked.blocked_by.append(blocker)
def job_done(self, job):
for j in job.blocking:
self.do_while_locked(self.unblock_job, j, job)
if not len(self.ready_queue) and not len(self.pending_jobs):
with self.cond:
self.cond.notify_all()
def unblock_job(self, blocked, blocker):
""" 'blocked' is no longer blocked by 'blocker'. Call while locked.
blocker is not altered, but if blocked has no remaining blockers it's
moved to ready_queue. """
try:
blocked.blocked_by.remove(blocker)
except ValueError:
raise MaitchError(
"%s was supposed to be blocked by %s but wasn't" %
(blocked, blocker))
if not len(blocked.blocked_by):
self.make_job_ready(blocked)
_thread_index = 0
class Builder(threading.Thread):
""" A Builder starts a new thread which waits for jobs to be added to
BuildGroup's ready_queue, pops one at a time and runs it. """
def __init__(self, build_group):
global builder_index
with build_group.cond:
global _thread_index
self.index = _thread_index
_thread_index += 1
self.bg = build_group
threading.Thread.__init__(self)
def describe(self):
return "Builder Thread %d" % self.index
def run(self):
finished = False
dprint("Starting %s" % self.describe())
try:
while not finished:
job = None
dprint("%s acquiring cond" % self.describe())
with self.bg.cond:
if not len(self.bg.ready_queue):
if len(self.bg.pending_jobs):
dprint("%s waiting for jobs" % self.describe())
self.bg.cond.wait()
dprint("%s awoken" % self.describe())
# Check both queues again, because they could have both
# changed while we were waiting
if not len(self.bg.ready_queue) and \
not len(self.bg.pending_jobs):
# No jobs left, we're done
dprint("%s finished" % self.describe())
finished = True
elif len(self.bg.ready_queue):
job = self.bg.ready_queue.pop()
dprint("%s released cond" % self.describe())
if job:
dprint("%s running job %s" % (self.describe(), str(job)))
job.run()
dprint("%s completed job %s" % (self.describe(), str(job)))
self.bg.job_done(job)
dprint("%s marked job %s done" % \
(self.describe(), str(job)))
except:
dprint("Exception in %s" % self.describe())
report_exception()
self.bg.cancel_all_jobs()
dprint("%s finished" % self.describe())
# Commonly used variables
add_var('PARALLEL', '0', "Number of build operations to run at once", True)
add_var('PREFIX', '/usr/local', "Base directory for installation", True)
add_var('BINDIR', '${PREFIX}/bin', "Installation directory for binaries", True)
add_var('LIBDIR', '${PREFIX}/lib',
"Installation directory for shared libraries "
"(you should use multiarch where possible)", True)
add_var('SYSCONFDIR', '/etc',
"Installation directory for system config files", True)
add_var('MANDIR', '${DATADIR}/man',
"Installation directory for man pages", True)
add_var('DATADIR', '${PREFIX}/share',
"Installation directory for data files", True)
add_var('LOCALEDIR', '${DATADIR}/locale',
"Installation directory for locale data", True)
add_var('PKGDATADIR', '${PREFIX}/share/${PACKAGE}',
"Installation directory for this package's data files", True)
add_var('DOCDIR', '${PREFIX}/share/doc/${PACKAGE}',
"Installation directory for this package's documentation", True)
add_var('HTMLDIR', '${DOCDIR}',
"Installation directory for this package's HTML documentation", True)
add_var('DESTDIR', '',
"Prepended to prefix at installation (for packaging)", True)
add_var('LOCK_TOP', False, "Lock ${TOP_DIR} instead of ${BUILD_DIR}")
add_var('NO_LOCK', False, "Disable locking (not recommended)")
add_var('ENABLE_DEBUG', False, "Enable the printing of maitch debug messages")
add_var('CC', '${GCC}', "C compiler")
add_var('CXX', '${GCC}', "C++ compiler")
add_var('GCC', find_prog_by_var, "GNU C compiler")
add_var('CPP', find_prog_by_var, "C preprocessor")
add_var('LIBTOOL', find_prog_by_var, "libtool compiler frontend for libraries")
add_var('CDEP', '${CPP} -M', "C preprocessor with option to print deps")
add_var('CFLAGS', '', "C compiler flags")
add_var('CPPFLAGS', '', "C preprocessor flags")
add_var('LIBS', '', "libraries and linker options")
add_var('LDFLAGS', '', "Extra linker options")
add_var('CXXFLAGS', '${CFLAGS}', "C++ compiler flags")
add_var('LIBTOOL_MODE_ARG', '', "Default libtool mode argument(s)")
add_var('LIBTOOL_FLAGS', '', "Additional libtool flags")
add_var('PKG_CONFIG', find_prog_by_var, "pkg-config")
add_var('INSTALL', find_prog_by_var, "install program")
|