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
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
|
// Project.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
// Viktoria Dudka <viktoriad@remobjects.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
// Copyright (c) 2009 RemObjects Software
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using MonoDevelop.Core;
using MonoDevelop.Core.Serialization;
using MonoDevelop.Projects;
using System.Threading.Tasks;
using MonoDevelop.Projects.MSBuild;
using System.Xml;
using MonoDevelop.Core.Instrumentation;
using MonoDevelop.Core.Assemblies;
using MonoDevelop.Projects.Extensions;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using MonoDevelop.Core.Collections;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using System.Runtime.CompilerServices;
namespace MonoDevelop.Projects
{
/// <summary>
/// A project
/// </summary>
/// <remarks>
/// This is the base class for MonoDevelop projects. A project is a solution item which has a list of
/// source code files and which can be built to generate an output.
/// </remarks>
public class Project : SolutionItem
{
string[] flavorGuids = new string[0];
static Counter<ProjectEventMetadata> ProjectOpenedCounter = InstrumentationService.CreateCounter<ProjectEventMetadata> ("Project Opened", "Project Model", id:"Ide.Project.Open");
string[] buildActions;
MSBuildProject sourceProject;
MSBuildProject userProject;
string productVersion;
string schemaVersion;
bool modifiedInMemory;
ProjectExtension projectExtension;
RunConfigurationCollection runConfigurations;
bool defaultRunConfigurationCreated;
List<string> defaultImports;
ProjectItemCollection items;
List<string> projectCapabilities;
IEnumerable<string> loadedAvailableItemNames = ImmutableList<string>.Empty;
CachingCoreCompileEvaluator compileEvaluator;
protected Project ()
{
runConfigurations = new RunConfigurationCollection (this);
items = new ProjectItemCollection (this);
FileService.FileChanged += HandleFileChanged;
files = new ProjectFileCollection ();
Items.Bind (files);
DependencyResolutionEnabled = true;
compileEvaluator = new CachingCoreCompileEvaluator ();
}
public ProjectItemCollection Items {
get { return items; }
}
public RunConfigurationCollection RunConfigurations {
get {
CreateDefaultConfiguration ();
return runConfigurations;
}
}
protected Project (params string[] flavorGuids): this()
{
this.flavorGuids = flavorGuids;
}
protected Project (ProjectCreateInformation projectCreateInfo, XmlElement projectOptions): this()
{
var ids = projectOptions != null ? projectOptions.GetAttribute ("flavorIds") : null;
if (!string.IsNullOrEmpty (ids)) {
this.flavorGuids = ids.Split (new [] {';'}, StringSplitOptions.RemoveEmptyEntries);
}
}
protected override void OnSetShared ()
{
base.OnSetShared ();
items.SetShared ();
files.SetShared ();
}
internal class CreationContext
{
public MSBuildProject Project { get; set; }
public string TypeGuid { get; set; }
public string[] FlavorGuids { get; set; }
internal static CreationContext Create (MSBuildProject p, string typeGuid)
{
return new CreationContext {
Project = p,
TypeGuid = typeGuid
};
}
internal static CreationContext Create (string typeGuid, string[] flavorGuids)
{
return new CreationContext {
TypeGuid = typeGuid,
FlavorGuids = flavorGuids
};
}
}
CreationContext creationContext;
internal void SetCreationContext (CreationContext ctx)
{
creationContext = ctx;
}
protected override void OnInitialize ()
{
base.OnInitialize ();
if (creationContext != null) {
if (IsExtensionChainCreated)
throw new InvalidOperationException ("Extension chain already created for this object");
TypeGuid = creationContext.TypeGuid;
string projectTypeGuids;
if (creationContext.Project != null) {
this.sourceProject = creationContext.Project;
// Configure target framework here for projects that target multiple frameworks so the
// project capabilities are correct when they are initialized in InitBeforeProjectExtensionLoad.
ConfigureActiveTargetFramework ();
projectTypeGuids = sourceProject.EvaluatedProperties.GetValue ("ProjectTypeGuids");
if (projectTypeGuids != null) {
var subtypeGuids = new List<string> ();
foreach (string guid in projectTypeGuids.Split (';')) {
string sguid = guid.Trim ();
if (sguid.Length > 0 && string.Compare (sguid, creationContext.TypeGuid, StringComparison.OrdinalIgnoreCase) != 0)
subtypeGuids.Add (guid);
}
flavorGuids = subtypeGuids.ToArray ();
}
} else {
sourceProject = new MSBuildProject ();
sourceProject.FileName = FileName;
flavorGuids = creationContext.FlavorGuids;
}
}
if (sourceProject == null) {
sourceProject = new MSBuildProject ();
sourceProject.FileName = FileName;
}
// Loads minimal data required to instantiate extensions and prepare for project loading
InitBeforeProjectExtensionLoad ();
}
/// <summary>
/// Initialization to be done before extensions are loaded
/// </summary>
void InitBeforeProjectExtensionLoad ()
{
var ggroup = sourceProject.GetOrCreateGlobalPropertyGroup ();
// Load the evaluated properties
InitMainGroupProperties (ggroup);
// Capabilities have to be loaded here since extensions may be activated or deactivated depending on them
LoadProjectCapabilities ();
}
void InitMainGroupProperties (MSBuildPropertyGroup globalGroup)
{
// Create a project instance to be used for comparing old and new values in the global property group
// We use a dummy configuration and platform to avoid loading default values from the configurations
// while evaluating
var c = Guid.NewGuid ().ToString ();
using (var pi = CreateProjectInstaceForConfiguration (c, c))
mainGroupProperties = pi.GetPropertiesLinkedToGroup (globalGroup);
}
protected override void OnExtensionChainInitialized ()
{
projectExtension = ExtensionChain.GetExtension<ProjectExtension> ();
base.OnExtensionChainInitialized ();
if (creationContext != null && creationContext.Project != null)
FileName = creationContext.Project.FileName;
sourceProject.UseMSBuildEngine = MSBuildProjectService.UseMSBuildEngineForProject (this);
InitFormatProperties ();
}
public IEnumerable<string> FlavorGuids {
get { return flavorGuids; }
}
public IPropertySet ProjectProperties {
get { return mainGroupProperties ?? MSBuildProject.GetGlobalPropertyGroup (); }
}
public MSBuildProject MSBuildProject {
get {
return sourceProject;
}
}
public List<string> DefaultImports {
get {
if (defaultImports == null) {
var list = new List<string> ();
ProjectExtension.OnGetDefaultImports (list);
defaultImports = list;
}
return defaultImports;
}
}
new public ProjectConfiguration CreateConfiguration (string name, string platform, ConfigurationKind kind = ConfigurationKind.Blank)
{
return (ProjectConfiguration) base.CreateConfiguration (name, platform, kind);
}
new public ProjectConfiguration CreateConfiguration (string id, ConfigurationKind kind = ConfigurationKind.Blank)
{
return (ProjectConfiguration) base.CreateConfiguration (id, kind);
}
new public ProjectConfiguration CloneConfiguration (SolutionItemConfiguration configuration, string newName, string newPlatform)
{
return (ProjectConfiguration) base.CloneConfiguration (configuration, newName, newPlatform);
}
new public ProjectConfiguration CloneConfiguration (SolutionItemConfiguration configuration, string newId)
{
return (ProjectConfiguration) base.CloneConfiguration (configuration, newId);
}
protected override void OnConfigurationAdded (ConfigurationEventArgs args)
{
var conf = (ProjectConfiguration)args.Configuration;
// Initialize the property group only if the project is not being loaded (in which case it will
// be initialized by the ReadProject method) or if the project is new (because it will be initialized
// after the project is fully written, since only then all imports are in place
if (!Loading && !sourceProject.IsNewProject)
InitConfiguration (conf);
base.OnConfigurationAdded (args);
}
void InitConfiguration (ProjectConfiguration conf)
{
var pi = CreateProjectInstaceForConfiguration (conf.Name, conf.Platform);
conf.Properties = pi.GetPropertiesLinkedToGroup (conf.MainPropertyGroup);
conf.ProjectInstance = pi;
}
protected override void OnConfigurationRemoved (ConfigurationEventArgs args)
{
var conf = (ProjectConfiguration) args.Configuration;
if (conf.ProjectInstance != null) {
// Dispose the project instance that was used to load the configuration
conf.Properties = conf.MainPropertyGroup;
conf.ProjectInstance.Dispose ();
conf.ProjectInstance = null;
}
base.OnConfigurationRemoved (args);
}
protected override void OnItemReady ()
{
base.OnItemReady ();
}
internal virtual void ImportDefaultRunConfiguration (ProjectRunConfiguration config)
{
}
public ProjectRunConfiguration CreateRunConfiguration (string name)
{
var c = CreateRunConfigurationInternal (name);
// When creating a ProcessRunConfiguration, set the value of ExternalConsole and PauseConsoleOutput from the default configuration
var pc = c as ProcessRunConfiguration;
if (pc != null) {
var dc = RunConfigurations.FirstOrDefault (rc => rc.IsDefaultConfiguration) as ProcessRunConfiguration;
if (dc != null) {
pc.ExternalConsole = dc.ExternalConsole;
pc.PauseConsoleOutput = dc.PauseConsoleOutput;
}
}
return c;
}
ProjectRunConfiguration CreateRunConfigurationInternal (string name)
{
var c = CreateUninitializedRunConfiguration (name);
c.Initialize (this);
return c;
}
public ProjectRunConfiguration CreateUninitializedRunConfiguration (string name)
{
return ProjectExtension.OnCreateRunConfiguration (name);
}
public ProjectRunConfiguration CloneRunConfiguration (ProjectRunConfiguration runConfig)
{
var clone = CreateUninitializedRunConfiguration (runConfig.Name);
clone.CopyFrom (runConfig, false);
return clone;
}
public ProjectRunConfiguration CloneRunConfiguration (ProjectRunConfiguration runConfig, string newName)
{
var clone = CreateUninitializedRunConfiguration (newName);
clone.CopyFrom (runConfig, true);
return clone;
}
void CreateDefaultConfiguration ()
{
// If the project doesn't have a Default run configuration, create one
if (!defaultRunConfigurationCreated) {
defaultRunConfigurationCreated = true;
if (!runConfigurations.Any (c => c.IsDefaultConfiguration)) {
var rc = CreateRunConfigurationInternal ("Default");
ImportDefaultRunConfiguration (rc);
runConfigurations.Insert (0, rc);
}
}
}
protected override IEnumerable<SolutionItemRunConfiguration> OnGetRunConfigurations ()
{
return RunConfigurations;
}
protected virtual void OnGetDefaultImports (List<string> imports)
{
}
public string ToolsVersion { get; private set; }
internal bool CheckAllFlavorsSupported ()
{
return FlavorGuids.All (ProjectExtension.SupportsFlavor);
}
ProjectExtension ProjectExtension {
get {
if (projectExtension == null)
AssertExtensionChainCreated ();
return projectExtension;
}
}
[Obsolete]
public MSBuildSupport MSBuildEngineSupport { get; private set; }
protected override void OnModified (SolutionItemModifiedEventArgs args)
{
if (!Loading) {
modifiedInMemory = true;
ClearCachedData ().Ignore ();
}
base.OnModified (args);
}
protected override Task OnLoad (ProgressMonitor monitor)
{
return Task.Run (async delegate {
await LoadAsync (monitor);
});
}
async Task LoadAsync (ProgressMonitor monitor)
{
if (sourceProject == null || sourceProject.IsNewProject) {
sourceProject = await MSBuildProject.LoadAsync (FileName).ConfigureAwait (false);
sourceProject.UseMSBuildEngine = MSBuildProjectService.UseMSBuildEngineForProject (this);
sourceProject.Evaluate ();
}
IMSBuildPropertySet globalGroup = sourceProject.GetGlobalPropertyGroup ();
// Avoid crash if there is not global group
if (globalGroup == null)
sourceProject.AddNewPropertyGroup (false);
ProjectExtension.OnPrepareForEvaluation (sourceProject);
ReadProject (monitor, sourceProject);
}
void LoadProjectCapabilities ()
{
projectCapabilities = sourceProject.EvaluatedItems.Where (it => it.Name == "ProjectCapability").Select (it => it.Include.Trim ()).Where (s => s.Length > 0).Distinct ().ToList ();
}
/// <summary>
/// Runs the generator target and sends file change notifications if any files were modified, returns the build result
/// </summary>
public Task<TargetEvaluationResult> PerformGeneratorAsync (ConfigurationSelector configuration, string generatorTarget)
{
return BindTask<TargetEvaluationResult> (async cancelToken => {
var cancelSource = new CancellationTokenSource ();
cancelToken.Register (() => cancelSource.Cancel ());
using (var monitor = new ProgressMonitor (cancelSource)) {
return await this.PerformGeneratorAsync (monitor, configuration, generatorTarget);
}
});
}
/// <summary>
/// Runs the generator target and sends file change notifications if any files were modified, returns the build result
/// </summary>
public Task<TargetEvaluationResult> PerformGeneratorAsync (ProgressMonitor monitor, ConfigurationSelector configuration, string generatorTarget)
{
return this.RunTarget (monitor, generatorTarget, configuration);
}
/// <summary>
/// Gets the analyzer files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
public Task<ImmutableArray<FilePath>> GetAnalyzerFilesAsync (ConfigurationSelector configuration)
{
if (sourceProject == null)
return Task.FromResult (ImmutableArray<FilePath>.Empty);
return BindTask<ImmutableArray<FilePath>> (cancelToken => {
var cancelSource = new CancellationTokenSource ();
cancelToken.Register (() => cancelSource.Cancel ());
using (var monitor = new ProgressMonitor (cancelSource)) {
return GetAnalyzerFilesAsync (monitor, configuration);
}
});
}
/// <summary>
/// Gets the analyzer files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
public Task<ImmutableArray<FilePath>> GetAnalyzerFilesAsync (ProgressMonitor monitor, ConfigurationSelector configuration)
{
return ProjectExtension.OnGetAnalyzerFiles (monitor, configuration);
}
/// <summary>
/// Gets the source files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
public Task<ImmutableArray<ProjectFile>> GetSourceFilesAsync (ConfigurationSelector configuration)
{
if (sourceProject == null)
return Task.FromResult (ImmutableArray<ProjectFile>.Empty);
return BindTask<ImmutableArray<ProjectFile>> (cancelToken => {
var cancelSource = new CancellationTokenSource ();
cancelToken.Register (() => cancelSource.Cancel ());
using (var monitor = new ProgressMonitor (cancelSource)) {
return GetSourceFilesAsync (monitor, configuration);
}
});
}
/// <summary>
/// Gets the source files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
public Task<ImmutableArray<ProjectFile>> GetSourceFilesAsync (ProgressMonitor monitor, ConfigurationSelector configuration)
{
return ProjectExtension.OnGetSourceFiles (monitor, configuration);
}
/// <summary>
/// Gets the analyzer files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
protected virtual async Task<ImmutableArray<FilePath>> OnGetAnalyzerFiles (ProgressMonitor monitor, ConfigurationSelector configuration)
{
var coreCompileResult = await compileEvaluator.GetItemsFromCoreCompileDependenciesAsync (this, monitor, configuration);
return coreCompileResult.AnalyzerFiles;
}
/// <summary>
/// Gets the source files that are included in the project, including any that are added by `CoreCompileDependsOn`
/// </summary>
protected virtual async Task<ImmutableArray<ProjectFile>> OnGetSourceFiles (ProgressMonitor monitor, ConfigurationSelector configuration)
{
// pre-load the results with the current list of files in the project
var evaluatedItems = await GetEvaluatedSourceFiles (configuration);
// add in any compile items that we discover from running the CoreCompile dependencies
var coreCompileResult = await compileEvaluator.GetItemsFromCoreCompileDependenciesAsync (this, monitor, configuration);
var evaluatedCompileItems = coreCompileResult.SourceFiles;
var results = new HashSet<ProjectFile> (evaluatedItems, ProjectFileFilePathComparer.Instance);
results.UnionWith (evaluatedCompileItems);
return results.ToImmutableArray ();
}
class ProjectFileFilePathComparer : IEqualityComparer<ProjectFile>
{
public readonly static ProjectFileFilePathComparer Instance = new ProjectFileFilePathComparer ();
public bool Equals (ProjectFile x, ProjectFile y) => x.FilePath == y.FilePath;
public int GetHashCode (ProjectFile obj) => obj.FilePath.GetHashCode ();
}
object evaluatedSourceFilesLock = new object ();
string evaluatedSourceFilesConfiguration;
TaskCompletionSource<ImmutableArray<ProjectFile>> evaluatedSourceFilesTask;
async Task<ImmutableArray<ProjectFile>> GetEvaluatedSourceFiles (ConfigurationSelector configuration)
{
bool startTask = false;
TaskCompletionSource<ImmutableArray<ProjectFile>> currentTask = null;
var config = configuration != null ? GetConfiguration (configuration) : null;
lock (evaluatedSourceFilesLock) {
if (evaluatedSourceFilesTask == null || evaluatedSourceFilesConfiguration != config?.Id) {
// The configuration changed or query not yet done
evaluatedSourceFilesConfiguration = config?.Id;
evaluatedSourceFilesTask = new TaskCompletionSource<ImmutableArray<ProjectFile>> ();
startTask = true;
}
currentTask = evaluatedSourceFilesTask;
}
if (startTask) {
var buildActions = GetBuildActions ().Where (a => a != "Folder" && a != "--").ToArray ();
var results = ImmutableArray.CreateBuilder<ProjectFile> ();
var pri = await CreateProjectInstaceForConfigurationAsync (config?.Name, config?.Platform, false);
foreach (var it in pri.EvaluatedItems.Where (i => buildActions.Contains (i.Name)))
results.Add (CreateProjectFile (it));
currentTask.SetResult (results.ToImmutable ());
}
return await currentTask.Task;
}
protected override Task OnClearCachedData ()
{
lock (evaluatedSourceFilesLock) {
evaluatedSourceFilesConfiguration = null;
evaluatedSourceFilesTask = null;
}
compileEvaluator.ResetCachedCompileItems ();
return base.OnClearCachedData ();
}
/// <summary>
/// When the MSBuild imports in a project change we need to let the type system know so
/// it can update its source files. A NuGet package may contain only MSBuild targets
/// which modify the CoreCompileDependsOn property. Just having the MSBuild targets
/// file in the NuGet package will not trigger any notifications that the type system
/// is monitoring so here we trigger a Files notification.
/// </summary>
void OnMSBuildProjectImportChanged (object sender, EventArgs args)
{
// Ensure MSBuild tasks used when building are up to date after imports changed.
ShutdownProjectBuilder ();
compileEvaluator.MarkDirty ();
Runtime.RunInMainThread (() => {
NotifyModified ("Files");
}).Ignore ();
}
ProjectFile CreateProjectFile (IMSBuildItemEvaluated item)
{
return new ProjectFile (MSBuildProjectService.FromMSBuildPath (sourceProject.BaseDirectory, item.Include), item.Name) { Project = this };
}
readonly struct CoreCompileEvaluationResult
{
public static CoreCompileEvaluationResult Empty = new CoreCompileEvaluationResult (ImmutableArray<ProjectFile>.Empty, ImmutableArray<FilePath>.Empty);
public CoreCompileEvaluationResult (ImmutableArray<ProjectFile> sourceFiles, ImmutableArray<FilePath> analyzerFiles)
{
SourceFiles = sourceFiles;
AnalyzerFiles = analyzerFiles;
}
public readonly ImmutableArray<ProjectFile> SourceFiles;
public readonly ImmutableArray<FilePath> AnalyzerFiles;
}
class CachingCoreCompileEvaluator
{
readonly object evaluatedCompileItemsLock = new object ();
string evaluatedCompileItemsConfiguration;
bool reevaluateCoreCompileDependsOn;
TaskCompletionSource<CoreCompileEvaluationResult> evaluatedCompileItemsTask;
public void MarkDirty ()
{
lock (evaluatedCompileItemsLock) {
// Do not re-evaluate if the compile items have never been evaluated.
if (evaluatedCompileItemsTask != null)
reevaluateCoreCompileDependsOn = true;
}
}
/// <summary>
/// Gets the list of files that are included as Compile items from the evaluation of the CoreCompile dependecy targets
/// </summary>
public async Task<CoreCompileEvaluationResult> GetItemsFromCoreCompileDependenciesAsync (Project project, ProgressMonitor monitor, ConfigurationSelector configuration)
{
var config = configuration != null ? project.GetConfiguration (configuration) : project.DefaultConfiguration;
if (config == null)
return CoreCompileEvaluationResult.Empty;
// Check if there is already a task for getting the items for the provided configuration
TaskCompletionSource<CoreCompileEvaluationResult> currentTask = null;
bool startTask = false;
bool reevaluate = false;
lock (evaluatedCompileItemsLock) {
if (evaluatedCompileItemsConfiguration != config.Id || reevaluateCoreCompileDependsOn) {
// The configuration changed or query not yet done
evaluatedCompileItemsConfiguration = config.Id;
evaluatedCompileItemsTask = new TaskCompletionSource<CoreCompileEvaluationResult> ();
startTask = true;
reevaluate = reevaluateCoreCompileDependsOn;
reevaluateCoreCompileDependsOn = false;
}
currentTask = evaluatedCompileItemsTask;
}
if (reevaluate) {
// Ensure CoreCompileDependsOn is up to date.
await project.ReevaluateProject (monitor, resetCachedCompileItems: false);
}
if (startTask) {
var coreCompileDependsOn = project.sourceProject.EvaluatedProperties.GetValue<string> ("CoreCompileDependsOn");
if (string.IsNullOrEmpty (coreCompileDependsOn)) {
currentTask.SetResult (CoreCompileEvaluationResult.Empty);
return currentTask.Task.Result;
}
var result = CoreCompileEvaluationResult.Empty;
var dependsList = string.Join (";", coreCompileDependsOn.Split (new [] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).Where (s => s.Length > 0));
try {
// evaluate the Compile targets
var ctx = new TargetEvaluationContext ();
ctx.ItemsToEvaluate.Add ("Compile");
ctx.ItemsToEvaluate.Add ("Analyzer");
ctx.LoadReferencedProjects = false;
ctx.BuilderQueue = BuilderQueue.ShortOperations;
ctx.LogVerbosity = MSBuildVerbosity.Quiet;
var evalResult = await project.RunTarget (monitor, dependsList, config.Selector, ctx);
if (evalResult != null && evalResult.Items != null) {
result = ProcessMSBuildItems (evalResult.Items, project);
}
} catch (Exception ex) {
LoggingService.LogInternalError (string.Format ("Error running target {0}", dependsList), ex);
}
currentTask.SetResult (result);
}
return await currentTask.Task;
}
public void ResetCachedCompileItems ()
{
lock (evaluatedCompileItemsLock) {
evaluatedCompileItemsConfiguration = null;
}
}
CoreCompileEvaluationResult ProcessMSBuildItems (IEnumerable<IMSBuildItemEvaluated> items, Project project)
{
var analyzerList = new List<FilePath> ();
var sourceFilesList = new List<ProjectFile> ();
foreach (var item in items) {
var msbuildPath = MSBuildProjectService.FromMSBuildPath (project.sourceProject.BaseDirectory, item.Include);
if (item.Name == "Compile") {
var subtype = Subtype.Code;
const string subtypeKey = "SubType";
if (item.Metadata.HasProperty (subtypeKey)) {
var property = item.Metadata.GetProperty (subtypeKey);
if (property.Value == "Designer")
subtype = Subtype.Designer;
}
var projectFile = new ProjectFile (msbuildPath, item.Name, subtype) { Project = project };
sourceFilesList.Add (projectFile);
} else if (item.Name == "Analyzer")
analyzerList.Add (msbuildPath);
}
return new CoreCompileEvaluationResult (sourceFilesList.ToImmutableArray (), analyzerList.ToImmutableArray ());
}
}
/// <summary>
/// Called just after the MSBuild project is loaded but before it is evaluated.
/// </summary>
/// <param name="project">The project</param>
/// <remarks>
/// Subclasses can override this method to transform the MSBuild project before it is evaluated.
/// For example, it can be used to add or remove imports, or to set custom values for properties.
/// Changes done in the MSBuild files are not saved.
/// </remarks>
protected virtual void OnPrepareForEvaluation (MSBuildProject project)
{
}
internal protected override async Task OnSave (ProgressMonitor monitor)
{
SetFastBuildCheckDirty ();
string content = await WriteProjectAsync (monitor);
// Doesn't save the file to disk if the content did not change
if (await sourceProject.SaveAsync (FileName, content)) {
if (userProject != null) {
if (!userProject.GetAllObjects ().Any ())
File.Delete (userProject.FileName);
else
await userProject.SaveAsync (userProject.FileName);
}
await ClearCachedData ();
RefreshProjectBuilder ().Ignore ();
}
// Need to clear this flag at the end to prevent a race condition where the project is modified in memory
// then saved immediately afterwards. Clearing this flag was originally done at the beginning of this method
// which could cause the type system to get old reference information. The project modified event triggers
// the type system to get updated reference information. If the type system access the project when it is
// saving, after the modifiedInMemory flag is reset, but before the cached data is cleared or the project
// builder refreshed, then out of date information can be returned to the type system. One way to reproduce
// this was to update a NuGet package in a project that used a packages.config file.
modifiedInMemory = false;
}
protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions ()
{
return base.CreateDefaultExtensions ().Concat (Enumerable.Repeat (new DefaultMSBuildProjectExtension (), 1));
}
internal protected override IEnumerable<string> GetItemTypeGuids ()
{
return base.GetItemTypeGuids ().Concat (flavorGuids);
}
protected override void OnGetProjectEventMetadata (IDictionary<string, string> metadata)
{
base.OnGetProjectEventMetadata (metadata);
var sb = new System.Text.StringBuilder ();
var first = true;
var projectTypes = this.GetTypeTags ().ToList ();
foreach (var p in projectTypes.Where (x => (x != "DotNet") || projectTypes.Count == 1)) {
if (!first)
sb.Append (", ");
sb.Append (p);
first = false;
}
metadata["ProjectTypes"] = sb.ToString ();
}
protected override ProjectEventMetadata OnGetProjectEventMetadata (ConfigurationSelector configurationSelector)
{
var metadata = base.OnGetProjectEventMetadata (configurationSelector);
var sb = new System.Text.StringBuilder ();
var first = true;
var projectTypes = this.GetTypeTags ().ToList ();
foreach (var p in projectTypes.Where (x => (x != "DotNet") || projectTypes.Count == 1)) {
if (!first)
sb.Append (", ");
sb.Append (p);
first = false;
}
metadata.ProjectTypes = sb.ToString ();
metadata.ProjectID = ItemId;
metadata.ProjectType = TypeGuid;
metadata.ProjectFlavor = FlavorGuids.FirstOrDefault () ?? TypeGuid;
var capabilities = GetProjectCapabilities ();
if (capabilities.Any ())
metadata.Capabilities = string.Join (" ", capabilities);
var c = GetConfiguration (configurationSelector);
if (c != null) {
metadata.Configuration = c.Id;
metadata.Platform = GetExplicitPlatform (c);
}
return metadata;
}
protected override void OnEndLoad ()
{
base.OnEndLoad ();
ProjectOpenedCounter.Inc (1, null, GetProjectEventMetadata (null));
if (sourceProject != null)
sourceProject.ImportChanged += OnMSBuildProjectImportChanged;
InitializeFileWatcher ();
}
/// <summary>
/// Description of the project.
/// </summary>
private string description = "";
public string Description {
get { return description ?? ""; }
set {
description = value;
NotifyModified ("Description");
}
}
/// <summary>
/// Determines whether the provided file can be as part of this project
/// </summary>
/// <returns>
/// <c>true</c> if the file can be compiled; otherwise, <c>false</c>.
/// </returns>
/// <param name='fileName'>
/// File name
/// </param>
public bool IsCompileable (string fileName)
{
return ProjectExtension.OnGetIsCompileable (fileName);
}
protected virtual bool OnGetIsCompileable (string fileName)
{
return false;
}
/// <summary>
/// Determines whether the provided build action is a compile action
/// </summary>
/// <returns><c>true</c> if this instance is compile build action the specified buildAction; otherwise, <c>false</c>.</returns>
/// <param name="buildAction">Build action.</param>
public bool IsCompileBuildAction (string buildAction)
{
return ProjectExtension.OnGetIsCompileBuildAction (buildAction);
}
protected virtual bool OnGetIsCompileBuildAction (string buildAction)
{
return buildAction == BuildAction.Compile;
}
/// <summary>
/// Files of the project
/// </summary>
public ProjectFileCollection Files {
get { return files; }
}
private ProjectFileCollection files;
FilePath baseIntermediateOutputPath;
public FilePath BaseIntermediateOutputPath {
get {
if (!baseIntermediateOutputPath.IsNullOrEmpty)
return baseIntermediateOutputPath;
return BaseDirectory.Combine ("obj");
}
set {
if (value.IsNullOrEmpty)
value = FilePath.Null;
if (baseIntermediateOutputPath == value)
return;
NotifyModified ("BaseIntermediateOutputPath");
}
}
/// <summary>
/// Gets the project type and its base types.
/// </summary>
public IEnumerable<string> GetTypeTags ()
{
HashSet<string> sset = new HashSet<string> ();
ProjectExtension.OnGetTypeTags (sset);
return sset;
}
protected virtual void OnGetTypeTags (HashSet<string> types)
{
}
public bool HasFlavor<T> ()
{
return GetService (typeof(T)) != null;
}
public T GetFlavor<T> () where T:ProjectExtension
{
return (T) GetService (typeof(T));
}
internal IEnumerable<ProjectExtension> GetFlavors ()
{
return ExtensionChain.GetAllExtensions ().OfType<ProjectExtension> ();
}
public IEnumerable<string> GetProjectCapabilities ()
{
return (IEnumerable<string>)projectCapabilities ?? ImmutableList<string>.Empty;
}
/// <summary>
/// Checks if the project has a capability or a combination of capabilities (including AND, OR, NOT logic).
/// </summary>
/// <returns><c>true</c> if the project has the required capabilities.</returns>
/// <param name="capabilityExpression">Expression of capabilities</param>
/// <remarks>The expression can be something like "(VisualC | CSharp) + (MSTest | NUnit)".
/// The "|" is the OR operator. The "&" and "+" characters are both AND operators.
/// The "!" character is the NOT operator. Parentheses force evaluation precedence order.
/// A null or empty expression is evaluated as a match.</remarks>
public bool IsCapabilityMatch (string capabilityExpression)
{
return SimpleExpressionEvaluator.Evaluate (capabilityExpression, (IList<string>)projectCapabilities ?? ImmutableList<string>.Empty);
}
public event EventHandler ProjectCapabilitiesChanged;
void NotifyProjectCapabilitiesChanged ()
{
ProjectCapabilitiesChanged?.Invoke (this, EventArgs.Empty);
}
/// <summary>
/// Gets or sets the icon of the project.
/// </summary>
/// <value>
/// The stock icon.
/// </value>
public IconId StockIcon {
get {
if (stockIcon != null)
return stockIcon.Value;
else
return ProjectExtension.StockIcon;
}
set { this.stockIcon = value; NotifyModified ("StockIcon"); }
}
IconId? stockIcon;
/// <summary>
/// List of languages that this project supports
/// </summary>
/// <value>
/// The identifiers of the supported languages.
/// </value>
public string[] SupportedLanguages {
get { return ProjectExtension.SupportedLanguages; }
}
protected virtual string[] OnGetSupportedLanguages ()
{
return new String[] { "" };
}
/// <summary>
/// Gets the default build action for a file
/// </summary>
/// <returns>
/// The default build action.
/// </returns>
/// <param name='fileName'>
/// File name.
/// </param>
public string GetDefaultBuildAction (string fileName)
{
return ProjectExtension.OnGetDefaultBuildAction (fileName);
}
protected virtual string OnGetDefaultBuildAction (string fileName)
{
return IsCompileable (fileName) ? BuildAction.Compile : BuildAction.None;
}
internal ProjectItem CreateProjectItem (IMSBuildItemEvaluated item)
{
return ProjectExtension.OnCreateProjectItem (item);
}
protected virtual ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item)
{
if (item.Name == "Folder")
return new ProjectFile ();
var type = MSBuildProjectService.GetProjectItemType (item.Name);
if (type != null)
return (ProjectItem) Activator.CreateInstance (type, true);
// Unknown item. Must be a file.
if (!string.IsNullOrEmpty (item.Include) && !UnsupportedItems.Contains (item.Name) && IsValidFile (item.Include))
return new ProjectFile ();
return new UnknownProjectItem (item.Name, item.Include);
}
bool IsValidFile (string path)
{
// If it is an absolute uri, it's not a valid file
try {
if (Uri.IsWellFormedUriString (path, UriKind.Absolute)) {
var f = new Uri (path);
return f.Scheme == "file";
}
} catch {
// Old mono versions may crash in IsWellFormedUriString if the path
// is not an uri.
}
return true;
}
// Items generated by VS but which MD is not using and should be ignored
internal static readonly IList<string> UnsupportedItems = new string[] {
"BootstrapperFile", "AppDesigner", "WebReferences", "WebReferenceUrl", "Service",
"ProjectReference", "Reference", // Reference elements are included here because they are special-cased for DotNetProject, and they are unsupported in other types of projects
"InternalsVisibleTo",
"InternalsVisibleToTest"
};
/// <summary>
/// Gets a project file.
/// </summary>
/// <returns>
/// The project file.
/// </returns>
/// <param name='fileName'>
/// File name.
/// </param>
public ProjectFile GetProjectFile (string fileName)
{
return files.GetFile (fileName);
}
/// <summary>
/// Determines whether a file belongs to this project
/// </summary>
/// <param name='fileName'>
/// File name
/// </param>
public bool IsFileInProject (string fileName)
{
return files.GetFile (fileName) != null;
}
/// <summary>
/// Gets a list of build actions supported by this project
/// </summary>
/// <remarks>
/// Common actions are grouped at the top, separated by a "--" entry *IF* there are
/// more "uncommon" actions than "common" actions
/// </remarks>
public string[] GetBuildActions ()
{
if (buildActions != null)
return buildActions;
buildActions = GetBuildActions (predicate: null);
return buildActions;
}
string[] GetBuildActions (Predicate<string> predicate)
{
// find all the actions in use and add them to the list of standard actions
HashSet<string> actions = new HashSet<string> ();
//ad the standard actions
foreach (string action in ProjectExtension.OnGetStandardBuildActions ().Concat (loadedAvailableItemNames))
actions.Add (action);
//add any more actions that are in the project file
foreach (ProjectFile pf in files)
actions.Add (pf.BuildAction);
//remove the "common" actions, since they're handled separately
IList<string> commonActions = ProjectExtension.OnGetCommonBuildActions ();
foreach (string action in commonActions)
if (actions.Contains (action))
actions.Remove (action);
if (predicate != null)
commonActions = commonActions.Where (action => predicate (action)).ToList ();
//calculate dimensions for our new array and create it
int dashPos = commonActions.Count;
bool hasDash = commonActions.Count > 0 && actions.Count > 0;
int arrayLen = commonActions.Count + actions.Count;
int uncommonStart = hasDash ? dashPos + 1 : dashPos;
if (hasDash)
arrayLen++;
var buildActions = new string[arrayLen];
//populate it
if (commonActions.Count > 0)
commonActions.CopyTo (buildActions, 0);
if (hasDash)
buildActions[dashPos] = "--";
if (actions.Count > 0)
actions.CopyTo (buildActions, uncommonStart);
//sort the actions
if (hasDash) {
//it may be better to leave common actions in the order that the project specified
//Array.Sort (buildActions, 0, commonActions.Count, StringComparer.Ordinal);
Array.Sort (buildActions, uncommonStart, arrayLen - uncommonStart, StringComparer.Ordinal);
} else {
Array.Sort (buildActions, StringComparer.Ordinal);
}
return buildActions;
}
/// <summary>
/// Gets a list of build actions supported by this project for the file.
/// </summary>
/// <remarks>
/// Common actions are grouped at the top, separated by a "--" entry *IF* there are
/// "uncommon" actions and "common" actions
/// </remarks>
public string[] GetBuildActions (string fileName)
{
return GetBuildActions (buildAction => ProjectExtension.OnGetFileSupportsBuildAction (fileName, buildAction));
}
/// <summary>
/// Gets a list of standard build actions.
/// </summary>
protected virtual IEnumerable<string> OnGetStandardBuildActions ()
{
return BuildAction.StandardActions;
}
/// <summary>
/// Gets a list of common build actions (common actions are shown first in the project build action list)
/// </summary>
protected virtual IList<string> OnGetCommonBuildActions ()
{
return BuildAction.StandardActions;
}
protected virtual bool OnGetFileSupportsBuildAction (string fileName, string buildAction)
{
return true;
}
protected override void OnDispose ()
{
DisposeFileWatcher ();
foreach (ProjectConfiguration c in Configurations)
c.ProjectInstance?.Dispose ();
foreach (var item in items) {
IDisposable disp = item as IDisposable;
if (disp != null)
disp.Dispose ();
}
FileService.FileChanged -= HandleFileChanged;
RemoteBuildEngineManager.UnloadProject (FileName).Ignore ();
if (sourceProject != null) {
sourceProject.ImportChanged -= OnMSBuildProjectImportChanged;
sourceProject.Dispose ();
sourceProject = null;
}
base.OnDispose ();
}
/// <summary>
/// Runs a build or execution target.
/// </summary>
/// <returns>
/// The result of the operation
/// </returns>
/// <param name='monitor'>
/// A progress monitor
/// </param>
/// <param name='target'>
/// Name of the target
/// </param>
/// <param name='configuration'>
/// Configuration to use to run the target
/// </param>
public Task<TargetEvaluationResult> RunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context = null)
{
// Initialize the evaluation context. This initialization is shared with FastCheckNeedsBuild.
// Extenders will override OnConfigureTargetEvaluationContext to add custom properties and do other
// initializations required by MSBuild.
context = ProjectExtension.OnConfigureTargetEvaluationContext (target, configuration, context ?? new TargetEvaluationContext ());
return ProjectExtension.OnRunTarget (monitor, target, configuration, context);
}
public bool SupportsTarget (string target)
{
return !IsUnsupportedProject && ProjectExtension.OnGetSupportsTarget (target);
}
protected virtual bool OnGetSupportsTarget (string target)
{
return sourceProject.EvaluatedTargetsIgnoringCondition.Any (t => t.Name == target);
}
protected virtual bool OnGetSupportsImportedItem (IMSBuildItemEvaluated buildItem)
{
return false;
}
/// <summary>
/// Initialize the evaluation context that is going to be used to execute an MSBuild target.
/// </summary>
/// <returns>The updated context.</returns>
/// <param name="target">Target.</param>
/// <param name="configuration">Configuration.</param>
/// <param name="context">Context.</param>
/// <remarks>
/// This method can be overriden to add custom properties and do other initializations on the evaluation
/// context. The method is always called before executing OnRunTarget and other methods that do
/// target evaluations. The method can modify the provided context instance and return it, or it can
/// create a new instance.
/// </remarks>
protected virtual TargetEvaluationContext OnConfigureTargetEvaluationContext (string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
return context;
}
/// <summary>
/// Runs a build or execution target.
/// </summary>
/// <returns>
/// The result of the operation
/// </returns>
/// <param name='monitor'>
/// A progress monitor
/// </param>
/// <param name='target'>
/// Name of the target
/// </param>
/// <param name='configuration'>
/// Configuration to use to run the target
/// </param>
/// <remarks>
/// Subclasses can override this method to provide a custom implementation of project operations such as
/// build or clean. The default implementation delegates the execution to the more specific OnBuild
/// and OnClean methods, or to the item handler for other targets.
/// </remarks>
internal protected virtual Task<TargetEvaluationResult> OnRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (target == ProjectService.BuildTarget)
return RunBuildTarget (monitor, configuration, context);
else if (target == ProjectService.CleanTarget)
return RunCleanTarget (monitor, configuration, context);
return RunMSBuildTarget (monitor, target, configuration, context);
}
async Task<TargetEvaluationResult> DoRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (configuration == null) {
throw new ArgumentNullException ("configuration");
}
if (target == ProjectService.BuildTarget) {
SolutionItemConfiguration conf = GetConfiguration (configuration);
if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Build)) {
if (monitor.CancellationToken.IsCancellationRequested)
return new TargetEvaluationResult (BuildResult.CreateCancelled ().SetSource (this));
if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Build, configuration)) {
var r = new BuildResult ();
r.AddError (GettextCatalog.GetString ("Custom command execution failed"));
return new TargetEvaluationResult (r.SetSource (this));
}
return new TargetEvaluationResult (BuildResult.CreateSuccess ().SetSource (this));
}
} else if (target == ProjectService.CleanTarget) {
SetFastBuildCheckDirty ();
SolutionItemConfiguration config = GetConfiguration (configuration);
if (config != null && config.CustomCommands.HasCommands (CustomCommandType.Clean)) {
if (monitor.CancellationToken.IsCancellationRequested)
return new TargetEvaluationResult (BuildResult.CreateCancelled ().SetSource (this));
if (!await config.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Clean, configuration)) {
var r = new BuildResult ();
r.AddError (GettextCatalog.GetString ("Custom command execution failed"));
return new TargetEvaluationResult (r.SetSource (this));
}
return new TargetEvaluationResult (BuildResult.CreateSuccess ().SetSource (this));
}
}
var tr = await OnRunTarget (monitor, target, configuration, context);
if (tr != null)
tr.BuildResult.SourceTarget = this;
return tr;
}
async Task<TargetEvaluationResult> RunMSBuildTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (!MSBuildProject.UseMSBuildEngine) {
#pragma warning disable CS0612 // obsolete
return await DeprecatedRunMSBuildTarget (monitor, target, configuration);
#pragma warning restore CS0612
}
var includeReferencedProjects = context?.LoadReferencedProjects ?? false;
var configs = GetConfigurations (configuration, includeReferencedProjects);
string [] evaluateItems = context != null ? context.ItemsToEvaluate.ToArray () : new string [0];
string [] evaluateProperties = context != null ? context.PropertiesToEvaluate.ToArray () : new string [0];
var globalProperties = CreateGlobalProperties (target);
if (context != null) {
var md = (ProjectItemMetadata)context.GlobalProperties;
md.SetProject (sourceProject);
foreach (var p in md.GetProperties ())
globalProperties [p.Name] = p.Value;
}
MSBuildResult result = null;
await Task.Run (async delegate {
bool operationRequiresExclusiveLock = context.BuilderQueue == BuilderQueue.LongOperations;
TimerCounter<ProjectEventMetadata> buildTimer = null;
switch (target) {
case "Build": buildTimer = Counters.BuildMSBuildProjectTimer; break;
case "Clean": buildTimer = Counters.CleanMSBuildProjectTimer; break;
}
var metadata = CreateProjectEventMetadata (configuration);
var t1 = Counters.RunMSBuildTargetTimer.BeginTiming (metadata);
var t2 = buildTimer?.BeginTiming (metadata);
IRemoteProjectBuilder builder = await GetProjectBuilder (monitor.CancellationToken, context, setBusy: operationRequiresExclusiveLock).ConfigureAwait (false);
string [] targets;
if (target.IndexOf (';') != -1)
targets = target.Split (new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
else
targets = new string [] { target };
var logger = context.Loggers.Count != 1 ? new ProxyLogger (this, context.Loggers) : context.Loggers.First ();
try {
result = await builder.Run (configs, monitor.Log, logger, context.LogVerbosity, targets, evaluateItems, evaluateProperties, globalProperties, monitor.CancellationToken).ConfigureAwait (false);
} finally {
builder.Dispose ();
t1.End ();
if (t2 != null) {
AddRunMSBuildTargetTimerMetadata (metadata, result, target, configuration);
t2.End ();
if (IsFirstBuild && target == "Build") {
await Runtime.RunInMainThread (() => IsFirstBuild = false);
}
}
}
});
var br = new BuildResult ();
foreach (var err in result.Errors) {
FilePath file = null;
if (err.File != null)
file = Path.Combine (Path.GetDirectoryName (err.ProjectFile ?? ItemDirectory.ToString ()), err.File);
br.Append (new BuildError (file, err.LineNumber, err.ColumnNumber, err.Code, err.Message) {
Subcategory = err.Subcategory,
EndLine = err.EndLineNumber,
EndColumn = err.EndColumnNumber,
IsWarning = err.IsWarning,
HelpKeyword = err.HelpKeyword,
});
}
// Get the evaluated properties
var properties = new Dictionary<string, IMSBuildPropertyEvaluated> ();
foreach (var p in result.Properties)
properties [p.Key] = new MSBuildPropertyEvaluated (sourceProject, p.Key, p.Value, p.Value);
var props = new MSBuildPropertyGroupEvaluated (sourceProject);
props.SetProperties (properties);
// Get the evaluated items
var evItems = new List<IMSBuildItemEvaluated> ();
foreach (var it in result.Items.SelectMany (d => d.Value)) {
var eit = new MSBuildItemEvaluated (sourceProject, it.Name, it.ItemSpec, it.ItemSpec);
if (it.Metadata.Count > 0) {
var imd = (MSBuildPropertyGroupEvaluated)eit.Metadata;
properties = new Dictionary<string, IMSBuildPropertyEvaluated> ();
foreach (var m in it.Metadata)
properties [m.Key] = new MSBuildPropertyEvaluated (sourceProject, m.Key, m.Value, m.Value);
imd.SetProperties (properties);
}
evItems.Add (eit);
}
return new TargetEvaluationResult (br, evItems, props);
}
[Obsolete]
async Task<TargetEvaluationResult> DeprecatedRunMSBuildTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration)
{
RemoteBuildEngineManager.UnloadProject (FileName).Ignore ();
if (this is DotNetProject dnp) {
var handler = new MD1.MD1DotNetProjectHandler (dnp);
return new TargetEvaluationResult (await handler.RunTarget (monitor, target, configuration));
}
return null;
}
/// <summary>
/// Gets or sets the FirstBuild user property. This is true if this is a new
/// project and has not yet been built.
/// </summary>
internal bool IsFirstBuild {
get {
return UserProperties.GetValue ("FirstBuild", false);
}
set {
if (value) {
UserProperties.SetValue ("FirstBuild", value);
} else {
UserProperties.RemoveValue ("FirstBuild");
}
}
}
void AddRunMSBuildTargetTimerMetadata (
ProjectEventMetadata metadata,
MSBuildResult result,
string target,
ConfigurationSelector configuration)
{
if (target == "Build") {
metadata.BuildType = 4;
} else if (target == "Clean") {
metadata.BuildType = 1;
}
metadata.BuildTypeString = target;
metadata.FirstBuild = IsFirstBuild;
bool success = false;
bool cancelled = false;
if (result != null) {
success = !result.Errors.Any (error => !error.IsWarning);
if (!success) {
cancelled = result.Errors [0].Message == "Build cancelled";
}
}
metadata.Success = success;
metadata.Cancelled = cancelled;
}
string activeTargetFramework;
void ConfigureActiveTargetFramework ()
{
activeTargetFramework = GetActiveTargetFramework ();
if (activeTargetFramework != null) {
MSBuildProject.SetGlobalProperty ("TargetFramework", activeTargetFramework);
MSBuildProject.Evaluate ();
}
}
/// <summary>
/// If an SDK project targets multiple target frameworks then this returns the first
/// target framework. Otherwise it returns null. This also handles the odd case if
/// the TargetFrameworks property is being used but only one framework is defined
/// there. Since here an active target framework must be returned even though multiple
/// target frameworks are not being used.
/// </summary>
string GetActiveTargetFramework ()
{
var frameworks = GetTargetFrameworks (MSBuildProject);
if (frameworks != null && frameworks.Any ())
return frameworks.FirstOrDefault ();
return null;
}
/// <summary>
/// Returns target frameworks defined in the TargetFrameworks property for SDK projects
/// if the TargetFramework property is not defined. It returns null otherwise.
/// </summary>
static string[] GetTargetFrameworks (MSBuildProject project)
{
if (!project.GetReferencedSDKs ().Any ())
return null;
var propertyGroup = project.GetGlobalPropertyGroup ();
string propertyValue = propertyGroup?.GetValue ("TargetFramework", null);
if (propertyValue != null)
return null;
propertyValue = project.EvaluatedProperties.GetValue ("TargetFrameworks", null);
if (propertyValue != null)
return propertyValue.Split (new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
return null;
}
/// <summary>
/// Sets a global TargetFramework property for multi-target projects so MSBuild targets work.
/// For Build and Clean the TargetFramework property is not set so all frameworks are built.
/// </summary>
internal Dictionary<string, string> CreateGlobalProperties (string target)
{
var properties = new Dictionary<string, string> ();
string framework = activeTargetFramework;
if (framework != null && target != ProjectService.BuildTarget && target != ProjectService.CleanTarget)
properties ["TargetFramework"] = framework;
return properties;
}
internal ProjectConfigurationInfo [] GetConfigurations (ConfigurationSelector configuration, bool includeReferencedProjects = true)
{
var visitedProjects = new HashSet<Project> ();
visitedProjects.Add (this);
return GetConfigurations (configuration, includeReferencedProjects, visitedProjects);
}
ProjectConfigurationInfo[] GetConfigurations (ConfigurationSelector configuration, bool includeReferencedProjects, HashSet<Project> visited)
{
var sc = ParentSolution != null ? ParentSolution.GetConfiguration (configuration) : null;
// Returns a list of project/configuration information for the provided item and all its references
List<ProjectConfigurationInfo> configs = new List<ProjectConfigurationInfo> ();
var c = GetConfiguration (configuration);
configs.Add (new ProjectConfigurationInfo () {
ProjectFile = FileName,
Configuration = c != null ? c.Name : "",
Platform = c != null ? GetExplicitPlatform (c) : "",
ProjectGuid = ItemId,
Enabled = sc == null || sc.BuildEnabledForItem (this)
});
if (includeReferencedProjects) {
foreach (var refProject in GetReferencedItems (configuration).OfType<Project> ().Where (p => p.SupportsBuild ())) {
if (!visited.Add (refProject))
continue;
// Recursively get all referenced projects. This is necessary if one of the referenced
// projects is using the local copy flag.
foreach (var rp in refProject.GetConfigurations (configuration, true, visited)) {
if (!configs.Any (pc => pc.ProjectFile == rp.ProjectFile))
configs.Add (rp);
}
}
}
return configs.ToArray ();
}
//for some reason, MD internally handles "AnyCPU" as "", but we need to be explicit when
//passing it to the build engine
static string GetExplicitPlatform (SolutionItemConfiguration configObject)
{
if (string.IsNullOrEmpty (configObject.Platform)) {
return "AnyCPU";
}
return configObject.Platform;
}
#region Project builder management
AsyncCriticalSection builderLock = new AsyncCriticalSection ();
internal async Task<IRemoteProjectBuilder> GetProjectBuilder (CancellationToken token, OperationContext context, bool setBusy = false, bool allowBusy = false)
{
TargetRuntime runtime = null;
var ap = this as IAssemblyProject;
runtime = ap != null ? ap.TargetRuntime : Runtime.SystemAssemblyService.CurrentRuntime;
var sln = ParentSolution;
var slnFile = sln != null ? sln.FileName : null;
// Extract the session ID from the current build context, if there is one
object buildSessionId = null;
if (context != null)
context.SessionData.TryGetValue (MSBuildSolutionExtension.MSBuildProjectOperationId, out buildSessionId);
var builder = await RemoteBuildEngineManager.GetRemoteProjectBuilder (FileName, slnFile, runtime, ToolsVersion, buildSessionId, setBusy, allowBusy);
if (modifiedInMemory) {
modifiedInMemory = false;
string content = await WriteProjectAsync (new ProgressMonitor (), inMemoryOnly: true);
try {
await RemoteBuildEngineManager.RefreshProjectWithContent (FileName, content);
} catch {
builder.Dispose ();
throw;
}
}
return builder;
}
void GetReferencedSDKs (Project project, ref HashSet<string> sdks, HashSet<string> traversedProjects)
{
traversedProjects.Add (project.ItemId);
var projectSdks = project.MSBuildProject.GetReferencedSDKs ();
if (projectSdks.Length > 0) {
if (sdks == null)
sdks = new HashSet<string> ();
sdks.UnionWith (projectSdks);
}
var dotNetProject = project as DotNetProject;
if (dotNetProject == null)
return;
// Check project references.
foreach (var projectReference in dotNetProject.References.Where (pr => pr.ReferenceType == ReferenceType.Project)) {
if (traversedProjects.Contains (projectReference.ProjectGuid))
continue;
var p = projectReference.ResolveProject (ParentSolution);
if (p != null)
GetReferencedSDKs (p, ref sdks, traversedProjects);
}
}
public Task RefreshProjectBuilder ()
{
return RemoteBuildEngineManager.RefreshProject (FileName);
}
public void ReloadProjectBuilder ()
{
RemoteBuildEngineManager.RefreshProject (FileName).Ignore ();
}
public void ShutdownProjectBuilder ()
{
// Unload the remote build engine so new MSBuild task assemblies can be used.
// This prevents the old MSBuild task assemblies from being used at build time
// after a NuGet package has been updated.
RemoteBuildEngineManager.UnloadProject (FileName).Ignore ();
string solutionFileName = ParentSolution?.FileName;
if (solutionFileName != null)
RemoteBuildEngineManager.UnloadSolution (solutionFileName).Ignore ();
}
#endregion
[Obsolete ("This property is ignored, msbuild is now always used")]
internal protected bool RequiresMicrosoftBuild {
get { return true; }
set { }
}
/// <summary>
/// Adds a file to the project
/// </summary>
/// <returns>
/// The file instance.
/// </returns>
/// <param name='filename'>
/// Absolute path to the file.
/// </param>
public ProjectFile AddFile (string filename)
{
return AddFile (filename, null);
}
public IEnumerable<ProjectFile> AddFiles (IEnumerable<FilePath> files)
{
return AddFiles (files, null);
}
/// <summary>
/// Adds a file to the project
/// </summary>
/// <returns>
/// The file instance.
/// </returns>
/// <param name='filename'>
/// Absolute path to the file.
/// </param>
/// <param name='buildAction'>
/// Build action to assign to the file.
/// </param>
public ProjectFile AddFile (string filename, string buildAction)
{
foreach (ProjectFile fInfo in Files) {
if (fInfo.Name == filename) {
return fInfo;
}
}
ProjectFile newFile = CreateProjectFileForGlobItem (filename, buildAction);
if (newFile != null) {
Files.Add (newFile);
return newFile;
}
if (String.IsNullOrEmpty (buildAction)) {
buildAction = GetDefaultBuildAction (filename);
}
ProjectFile newFileInformation = new ProjectFile (filename, buildAction);
Files.Add (newFileInformation);
return newFileInformation;
}
public IEnumerable<ProjectFile> AddFiles (IEnumerable<FilePath> files, string buildAction)
{
List<ProjectFile> newFiles = new List<ProjectFile> ();
foreach (FilePath filename in files) {
ProjectFile newFile = CreateProjectFileForGlobItem (filename, buildAction);
if (newFile != null) {
newFiles.Add (newFile);
continue;
}
string ba = buildAction;
if (String.IsNullOrEmpty (ba))
ba = GetDefaultBuildAction (filename);
ProjectFile newFileInformation = new ProjectFile (filename, ba);
newFiles.Add (newFileInformation);
}
Files.AddRange (newFiles);
return newFiles;
}
/// <summary>
/// Imported glob item may define a different build action and metadata for a file
/// so this is read and applied to the new ProjectFile.
/// </summary>
ProjectFile CreateProjectFileForGlobItem (FilePath file, string buildAction)
{
if (!UseAdvancedGlobSupport)
return null;
var include = MSBuildProjectService.ToMSBuildPath (ItemDirectory, file);
var globItems = sourceProject.FindGlobItemsIncludingFile (include).ToList ();
if ((globItems.Count == 1) && (buildAction == null || globItems [0].Name == buildAction)) {
var eit = CreateFakeEvaluatedItem (sourceProject, globItems [0], include, null);
var projectFile = CreateProjectItem (eit) as ProjectFile;
if (projectFile != null) {
projectFile.Read (this, eit);
// Force UnevaluatedInclude to be reset to prevent Remove items
// being left in project after file is re-added.
projectFile.BackingItem = null;
return projectFile;
}
}
return null;
}
/// <summary>
/// Adds a file to the project
/// </summary>
/// <param name='projectFile'>
/// The file.
/// </param>
public void AddFile (ProjectFile projectFile)
{
Files.Add (projectFile);
}
/// <summary>
/// Adds a directory to the project.
/// </summary>
/// <returns>
/// The directory instance.
/// </returns>
/// <param name='relativePath'>
/// Relative path of the directory.
/// </param>
/// <remarks>
/// The directory is created if it doesn't exist
/// </remarks>
public ProjectFile AddDirectory (string relativePath)
{
string newPath = Path.Combine (BaseDirectory, relativePath);
foreach (ProjectFile fInfo in Files)
if (fInfo.Name == newPath && fInfo.Subtype == Subtype.Directory)
return fInfo;
if (!Directory.Exists (newPath)) {
if (File.Exists (newPath)) {
string message = GettextCatalog.GetString ("Cannot create directory {0}, as a file with that name exists.", newPath);
throw new InvalidOperationException (message);
}
FileService.CreateDirectory (newPath);
}
ProjectFile newDir = new ProjectFile (newPath);
newDir.Subtype = Subtype.Directory;
AddFile (newDir);
return newDir;
}
protected override async Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration, OperationContext operationContext)
{
var newContext = operationContext as TargetEvaluationContext ?? new TargetEvaluationContext (operationContext);
return (await RunTarget (monitor, "Build", configuration, newContext)).BuildResult;
}
async Task<TargetEvaluationResult> RunBuildTarget (ProgressMonitor monitor, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (!(GetConfiguration (configuration) is ProjectConfiguration conf)) {
var cres = new BuildResult ();
cres.AddError (GettextCatalog.GetString ("Configuration '{0}' not found in project '{1}'", configuration.ToString (), Name));
return new TargetEvaluationResult (cres);
}
StringParserService.Properties["Project"] = Name;
if (!MSBuildProject.UseMSBuildEngine) {
#pragma warning disable CS0612 // obsolete
return await RunDeprecatedBuildTarget (monitor, configuration, conf);
#pragma warning restore CS0612
}
// Build is always a long operation. Make sure we build the project in the right builder.
context.BuilderQueue = BuilderQueue.LongOperations;
var result = await RunMSBuildTarget (monitor, "Build", configuration, context);
if (!result.BuildResult.Failed)
SetFastBuildCheckClean (configuration, context);
return result;
}
[Obsolete]
async Task<TargetEvaluationResult> RunDeprecatedBuildTarget (ProgressMonitor monitor, ConfigurationSelector configuration, ProjectConfiguration conf)
{
string outputDir = conf.OutputDirectory;
try {
var directoryInfo = new DirectoryInfo (outputDir);
if (!directoryInfo.Exists) {
directoryInfo.Create ();
}
} catch (Exception e) {
throw new ApplicationException ("Can't create project output directory " + outputDir + " original exception:\n" + e.ToString ());
}
//copy references and files marked to "CopyToOutputDirectory"
CopySupportFiles (monitor, configuration);
monitor.Log.WriteLine (GettextCatalog.GetString ("Performing main compilation…"));
BuildResult res = await DoBuild (monitor, configuration);
if (res != null) {
string errorString = GettextCatalog.GetPluralString ("{0} error", "{0} errors", res.ErrorCount, res.ErrorCount);
string warningString = GettextCatalog.GetPluralString ("{0} warning", "{0} warnings", res.WarningCount, res.WarningCount);
monitor.Log.WriteLine (GettextCatalog.GetString ("Build complete -- ") + errorString + ", " + warningString);
}
return new TargetEvaluationResult (res);
}
bool disableFastUpToDateCheck;
// The configuration of the last build that completed successfully,
// null if any file in the project has since changed
string fastUpToDateCheckGoodConfig;
// The global properties used in the last build
IPropertySet fastUpToDateCheckGlobalProperties;
// Timestamp of the last build
DateTime fastUpToDateTimestamp;
public bool FastCheckNeedsBuild (ConfigurationSelector configuration)
{
return FastCheckNeedsBuild (configuration, new TargetEvaluationContext ());
}
public bool FastCheckNeedsBuild (ConfigurationSelector configuration, TargetEvaluationContext context)
{
// Initialize the evaluation context. This initialization is shared with RunTarget.
// Extenders will override OnConfigureTargetEvaluationContext to add custom properties and do other
// initializations required by MSBuild.
context = ProjectExtension.OnConfigureTargetEvaluationContext ("Build", configuration, context ?? new TargetEvaluationContext ());
return ProjectExtension.OnFastCheckNeedsBuild (configuration, context);
}
[Obsolete ("Use OnFastCheckNeedsBuild (configuration, TargetEvaluationContext)")]
protected virtual bool OnFastCheckNeedsBuild (ConfigurationSelector configuration)
{
if (disableFastUpToDateCheck || fastUpToDateCheckGoodConfig == null)
return true;
var cfg = GetConfiguration (configuration);
if (cfg == null || cfg.Id != fastUpToDateCheckGoodConfig)
return true;
return false;
}
/// <summary>
/// Checks if this project needs to be built.
/// </summary>
/// <returns><c>true</c>, if the project is dirty and needs to be rebuilt, <c>false</c> otherwise.</returns>
/// <param name="configuration">Build configuration.</param>
/// <param name="context">Evaluation context.</param>
/// <remarks>
/// This method can be overriden to provide custom logic for checking if a project needs to be built, either
/// due to changes in the content or in the configuration.
/// </remarks>
protected virtual bool OnFastCheckNeedsBuild (ConfigurationSelector configuration, TargetEvaluationContext context)
{
// Chain the new OnFastCheckNeedsBuild override to the old one, so that extensions
// using the old API keep working
#pragma warning disable 618
if (ProjectExtension.OnFastCheckNeedsBuild (configuration))
return true;
#pragma warning restore 618
// Shouldn't need to build, but if a dependency was changed since this project build flag was reset,
// the project needs to be rebuilt
foreach (var dep in GetReferencedItems (configuration).OfType<Project> ()) {
if (dep.FastCheckNeedsBuild (configuration, context) || dep.fastUpToDateTimestamp >= fastUpToDateTimestamp) {
fastUpToDateCheckGoodConfig = null;
return true;
}
}
// Check if global properties have changed
var cachedCount = fastUpToDateCheckGlobalProperties != null ? fastUpToDateCheckGlobalProperties.GetProperties ().Count () : 0;
if (cachedCount != context.GlobalProperties.GetProperties ().Count ())
return true;
if (cachedCount == 0)
return false;
foreach (var p in context.GlobalProperties.GetProperties ()) {
if (fastUpToDateCheckGlobalProperties.GetValue (p.Name) != p.Value)
return true;
}
return false;
}
protected void SetFastBuildCheckDirty ()
{
fastUpToDateCheckGoodConfig = null;
}
void SetFastBuildCheckClean (ConfigurationSelector configuration, TargetEvaluationContext context)
{
var cfg = GetConfiguration (configuration);
fastUpToDateCheckGoodConfig = cfg != null ? cfg.Id : null;
fastUpToDateCheckGlobalProperties = context.GlobalProperties;
fastUpToDateTimestamp = DateTime.Now;
}
/// <summary>
/// Copies the support files to the output directory
/// </summary>
/// <param name='monitor'>
/// Progress monitor.
/// </param>
/// <param name='configuration'>
/// Configuration for which to copy the files.
/// </param>
/// <remarks>
/// Copies all support files to the output directory of the given configuration. Support files
/// include: assembly references with the Local Copy flag, data files with the Copy to Output option, etc.
/// </remarks>
[Obsolete ("Use MSBuild")]
public void CopySupportFiles (ProgressMonitor monitor, ConfigurationSelector configuration)
{
ProjectConfiguration config = (ProjectConfiguration) GetConfiguration (configuration);
foreach (FileCopySet.Item item in GetSupportFileList (configuration)) {
FilePath dest = Path.GetFullPath (Path.Combine (config.OutputDirectory, item.Target));
FilePath src = Path.GetFullPath (item.Src);
try {
if (dest == src)
continue;
if (item.CopyOnlyIfNewer && File.Exists (dest) && (File.GetLastWriteTimeUtc (dest) >= File.GetLastWriteTimeUtc (src)))
continue;
// Use Directory.Create so we don't trigger the VersionControl addin and try to
// add the directory to version control.
if (!Directory.Exists (Path.GetDirectoryName (dest)))
Directory.CreateDirectory (Path.GetDirectoryName (dest));
if (File.Exists (src)) {
dest.Delete ();
FileService.CopyFile (src, dest);
// Copied files can't be read-only, so they can be removed when rebuilding the project
FileAttributes atts = File.GetAttributes (dest);
if (atts.HasFlag (FileAttributes.ReadOnly))
File.SetAttributes (dest, atts & ~FileAttributes.ReadOnly);
}
else
monitor.ReportError (GettextCatalog.GetString ("Could not find support file '{0}'.", src), null);
} catch (IOException ex) {
monitor.ReportError (GettextCatalog.GetString ("Error copying support file '{0}'.", dest), ex);
}
}
}
/// <summary>
/// Removes all support files from the output directory
/// </summary>
/// <param name='monitor'>
/// Progress monitor.
/// </param>
/// <param name='configuration'>
/// Configuration for which to delete the files.
/// </param>
/// <remarks>
/// Deletes all support files from the output directory of the given configuration. Support files
/// include: assembly references with the Local Copy flag, data files with the Copy to Output option, etc.
/// </remarks>
[Obsolete ("Use MSBuild")]
public async Task DeleteSupportFiles (ProgressMonitor monitor, ConfigurationSelector configuration)
{
ProjectConfiguration config = (ProjectConfiguration) GetConfiguration (configuration);
foreach (FileCopySet.Item item in GetSupportFileList (configuration)) {
FilePath dest = Path.Combine (config.OutputDirectory, item.Target);
// Ignore files which were not copied
if (Path.GetFullPath (dest) == Path.GetFullPath (item.Src))
continue;
try {
await dest.DeleteAsync ();
} catch (IOException ex) {
monitor.ReportError (GettextCatalog.GetString ("Error deleting support file '{0}'.", dest), ex);
}
}
}
/// <summary>
/// Gets a list of files required to use the project output
/// </summary>
/// <returns>
/// A list of files.
/// </returns>
/// <param name='configuration'>
/// Build configuration for which get the list
/// </param>
/// <remarks>
/// Returns a list of all files that are required to use the project output binary, for example: data files with
/// the Copy to Output option, debug information files, generated resource files, etc.
/// </remarks>
[Obsolete ("Use MSBuild")]
public FileCopySet GetSupportFileList (ConfigurationSelector configuration)
{
var list = new FileCopySet ();
PopulateSupportFileList (list, configuration);
return list;
}
/// <summary>
/// Gets a list of files required to use the project output
/// </summary>
/// <param name='list'>
/// List where to add the support files.
/// </param>
/// <param name='configuration'>
/// Build configuration for which get the list
/// </param>
/// <remarks>
/// Returns a list of all files that are required to use the project output binary, for example: data files with
/// the Copy to Output option, debug information files, generated resource files, etc.
/// </remarks>
[Obsolete("Use MSBuild")]
internal protected virtual void PopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration)
{
ProjectExtension.OnPopulateSupportFileList (list, configuration);
}
void DoPopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration)
{
foreach (ProjectFile pf in Files) {
if (pf.CopyToOutputDirectory == FileCopyMode.None)
continue;
list.Add (pf.FilePath, pf.CopyToOutputDirectory == FileCopyMode.PreserveNewest, pf.ProjectVirtualPath);
}
}
/// <summary>
/// Gets a list of files generated when building this project
/// </summary>
/// <returns>
/// A list of files.
/// </returns>
/// <param name='configuration'>
/// Build configuration for which get the list
/// </param>
/// <remarks>
/// Returns a list of all files that are generated when this project is built, including: the generated binary,
/// debug information files, satellite assemblies.
/// </remarks>
[Obsolete ("Use MSBuild")]
public List<FilePath> GetOutputFiles (ConfigurationSelector configuration)
{
if (configuration == null) {
throw new ArgumentNullException ("configuration");
}
var list = new List<FilePath> ();
PopulateOutputFileList (list, configuration);
return list;
}
/// <summary>
/// Gets a list of files retuired to use the project output
/// </summary>
/// <param name='list'>
/// List where to add the support files.
/// </param>
/// <param name='configuration'>
/// Build configuration for which get the list
/// </param>
/// <remarks>
/// Returns a list of all files that are required to use the project output binary, for example: data files with
/// the Copy to Output option, debug information files, generated resource files, etc.
/// </remarks>
[Obsolete("Use MSBuild")]
internal protected virtual void PopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration)
{
ProjectExtension.OnPopulateOutputFileList (list, configuration);
}
[Obsolete]
void DoPopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration)
{
string file = GetOutputFileName (configuration);
if (file != null)
list.Add (file);
}
/// <summary>
/// Builds the project
/// </summary>
/// <param name="monitor">A progress monitor</param>
/// <param name="solutionConfiguration">Configuration to use to build the project</param>
/// <param name="operationContext">Context information.</param>
public Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector solutionConfiguration, ProjectOperationContext operationContext)
{
return base.Build (monitor, solutionConfiguration, false, operationContext);
}
/// <summary>
/// Builds the project
/// </summary>
/// <param name="monitor">A progress monitor</param>
/// <param name="solutionConfiguration">Configuration to use to build the project</param>
/// <param name="buildReferences">When set to <c>true</c>, the referenced items will be built before building this item.</param>
/// <param name="operationContext">Context information.</param>
public Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector solutionConfiguration, bool buildReferences, ProjectOperationContext operationContext)
{
return base.Build (monitor, solutionConfiguration, buildReferences, operationContext);
}
/// <summary>
/// Builds the project.
/// </summary>
/// <returns>
/// The build result.
/// </returns>
/// <param name='monitor'>
/// Progress monitor.
/// </param>
/// <param name='configuration'>
/// Configuration to build.
/// </param>
/// <remarks>
/// This method is invoked to build the project. Support files such as files with the Copy to Output flag will
/// be copied before calling this method.
/// </remarks>
[Obsolete("Use MSBuild")]
protected virtual Task<BuildResult> DoBuild (ProgressMonitor monitor, ConfigurationSelector configuration)
{
return Task.FromResult (BuildResult.CreateSuccess ());
}
protected override async Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration, OperationContext buildSession)
{
var newContext = buildSession as TargetEvaluationContext ?? new TargetEvaluationContext (buildSession);
return (await RunTarget (monitor, "Clean", configuration, newContext)).BuildResult;
}
Task<TargetEvaluationResult> RunCleanTarget (ProgressMonitor monitor, ConfigurationSelector configuration, TargetEvaluationContext context)
{
if (!(GetConfiguration (configuration) is ProjectConfiguration config)) {
monitor.ReportError (GettextCatalog.GetString ("Configuration '{0}' not found in project '{1}'", configuration, Name), null);
return Task.FromResult (new TargetEvaluationResult (BuildResult.CreateSuccess ()));
}
if (!MSBuildProject.UseMSBuildEngine) {
#pragma warning disable CS0612 // obsolete
return RunDeprecatedCleanTarget (monitor, configuration, config);
#pragma warning restore CS0612
}
// Clean is considered a long operation. Make sure we build the project in the right builder.
context.BuilderQueue = BuilderQueue.LongOperations;
return RunMSBuildTarget (monitor, "Clean", configuration, context);
}
[Obsolete]
async Task<TargetEvaluationResult> RunDeprecatedCleanTarget (ProgressMonitor monitor, ConfigurationSelector configuration, ProjectConfiguration config)
{
monitor.Log.WriteLine ("Removing output files...");
var filesToDelete = GetOutputFiles (configuration).ToArray ();
await Task.Run (delegate {
// Delete generated files
foreach (FilePath file in filesToDelete) {
if (File.Exists (file)) {
file.Delete ();
if (file.ParentDirectory.CanonicalPath != config.OutputDirectory.CanonicalPath && !Directory.EnumerateFiles (file.ParentDirectory).Any ())
file.ParentDirectory.Delete ();
}
}
});
await DeleteSupportFiles (monitor, configuration);
var res = await DoClean (monitor, config.Selector);
monitor.Log.WriteLine (GettextCatalog.GetString ("Clean complete"));
return new TargetEvaluationResult (res);
}
[Obsolete("Use MSBuild")]
protected virtual Task<BuildResult> DoClean (ProgressMonitor monitor, ConfigurationSelector configuration)
{
return Task.FromResult (BuildResult.CreateSuccess ());
}
protected override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration, SolutionItemRunConfiguration runConfiguration)
{
ProjectConfiguration config = GetConfiguration (configuration) as ProjectConfiguration;
if (config == null)
monitor.ReportError (GettextCatalog.GetString ("Configuration '{0}' not found in project '{1}'", configuration, Name), null);
return Task.FromResult (0);
}
/// <summary>
/// Gets the absolute path to the output file generated by this project.
/// </summary>
/// <returns>
/// Absolute path the the output file.
/// </returns>
/// <param name='configuration'>
/// Build configuration.
/// </param>
public FilePath GetOutputFileName (ConfigurationSelector configuration)
{
return ProjectExtension.OnGetOutputFileName (configuration);
}
protected virtual FilePath OnGetOutputFileName (ConfigurationSelector configuration)
{
return FilePath.Null;
}
internal protected override bool OnGetNeedsBuilding (ConfigurationSelector configuration)
{
return CheckNeedsBuild (configuration);
}
protected override void OnSetNeedsBuilding (ConfigurationSelector configuration)
{
var of = GetOutputFileName (configuration);
if (File.Exists (of))
File.Delete (of);
}
/// <summary>
/// Checks if the project needs to be built
/// </summary>
/// <returns>
/// <c>True</c> if the project needs to be built (it has changes)
/// </returns>
/// <param name='configuration'>
/// Build configuration.
/// </param>
protected virtual bool CheckNeedsBuild (ConfigurationSelector configuration)
{
DateTime tim = GetLastBuildTime (configuration);
if (tim == DateTime.MinValue)
return true;
foreach (ProjectFile file in Files) {
if (file.BuildAction == BuildAction.Content || file.BuildAction == BuildAction.None)
continue;
try {
if (File.GetLastWriteTime (file.FilePath) > tim)
return true;
} catch (IOException) {
// Ignore.
}
}
foreach (SolutionFolderItem pref in GetReferencedItems (configuration)) {
if (pref.GetLastBuildTime (configuration) > tim)
return true;
}
try {
if (File.GetLastWriteTime (FileName) > tim)
return true;
} catch {
// Ignore
}
return false;
}
protected internal override DateTime OnGetLastBuildTime (ConfigurationSelector configuration)
{
string file = GetOutputFileName (configuration);
if (file == null)
return DateTime.MinValue;
FileInfo finfo = new FileInfo (file);
if (!finfo.Exists)
return DateTime.MinValue;
else
return finfo.LastWriteTime;
}
void HandleFileChanged (object source, FileEventArgs e)
{
// File change events are fired asynchronously, so the project might already be
// disposed when the event is received.
if (Disposed)
return;
OnFileChanged (source, e);
}
internal virtual void OnFileChanged (object source, FileEventArgs e)
{
foreach (FileEventInfo fi in e) {
ProjectFile file = GetProjectFile (fi.FileName);
if (file != null) {
SetFastBuildCheckDirty ();
try {
NotifyFileChangedInProject (file);
} catch {
// Workaround Mono bug. The watcher seems to
// stop watching if an exception is thrown in
// the event handler
}
}
}
}
protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles)
{
var baseFiles = base.OnGetItemFiles (includeReferencedFiles);
if (includeReferencedFiles) {
List<FilePath> col = new List<FilePath> ();
foreach (ProjectFile pf in Files) {
if (pf.Subtype != Subtype.Directory)
col.Add (pf.FilePath);
}
baseFiles = baseFiles.Concat (col);
}
return baseFiles;
}
internal void NotifyItemsAdded (IEnumerable<ProjectItem> objs)
{
ProjectExtension.OnItemsAdded (objs);
}
internal void NotifyItemsRemoved (IEnumerable<ProjectItem> objs)
{
ProjectExtension.OnItemsRemoved (objs);
}
protected virtual void OnItemsAdded (IEnumerable<ProjectItem> objs)
{
foreach (var it in objs) {
if (it.Project != null)
throw new InvalidOperationException (it.GetType ().Name + " already belongs to a project");
it.Project = this;
}
if (monitorItemsModifiedDuringReevaluation) {
if (itemsAddedDuringReevaluation == null)
itemsAddedDuringReevaluation = ImmutableList.CreateBuilder<ProjectItem> ();
itemsAddedDuringReevaluation.AddRange (objs);
}
NotifyModified ("Items");
if (ProjectItemAdded != null)
ProjectItemAdded (this, new ProjectItemEventArgs (objs.Select (pi => new ProjectItemEventInfo (this, pi))));
NotifyFileAddedToProject (objs.OfType<ProjectFile> ());
}
protected virtual void OnItemsRemoved (IEnumerable<ProjectItem> objs)
{
foreach (var it in objs)
it.Project = null;
if (monitorItemsModifiedDuringReevaluation) {
if (itemsRemovedDuringReevaluation == null)
itemsRemovedDuringReevaluation = ImmutableList.CreateBuilder<ProjectItem> ();
itemsRemovedDuringReevaluation.AddRange (objs);
}
NotifyModified ("Items");
if (ProjectItemRemoved != null)
ProjectItemRemoved (this, new ProjectItemEventArgs (objs.Select (pi => new ProjectItemEventInfo (this, pi))));
NotifyFileRemovedFromProject (objs.OfType<ProjectFile> ());
}
bool monitorItemsModifiedDuringReevaluation;
internal ImmutableList<ProjectItem>.Builder itemsAddedDuringReevaluation;
internal ImmutableList<ProjectItem>.Builder itemsRemovedDuringReevaluation;
internal void NotifyFileChangedInProject (ProjectFile file)
{
OnFileChangedInProject (new ProjectFileEventArgs (this, file));
}
internal void NotifyFilePropertyChangedInProject (ProjectFile file, string property)
{
NotifyModified ("Files");
OnFilePropertyChangedInProject (new ProjectFileEventArgs (this, file, property));
}
// A collection of files that depend on other files for which the dependencies
// have not yet been resolved.
UnresolvedFileCollection unresolvedDeps;
void NotifyFileRemovedFromProject (IEnumerable<ProjectFile> objs)
{
if (!objs.Any ())
return;
var args = new ProjectFileEventArgs ();
foreach (ProjectFile file in objs) {
args.Add (new ProjectFileEventInfo (this, file));
if (DependencyResolutionEnabled) {
unresolvedDeps.Remove (file);
foreach (ProjectFile f in file.DependentChildren) {
f.DependsOnFile = null;
if (!string.IsNullOrEmpty (f.DependsOn))
unresolvedDeps.Add (f);
}
file.DependsOn = null;
}
}
NotifyModified ("Files");
OnFileRemovedFromProject (args);
ParentSolution?.OnRootDirectoriesChanged ();
}
void NotifyFileAddedToProject (IEnumerable<ProjectFile> objs)
{
if (!objs.Any ())
return;
var args = new ProjectFileEventArgs ();
foreach (ProjectFile file in objs) {
args.Add (new ProjectFileEventInfo (this, file));
ResolveDependencies (file);
}
NotifyModified ("Files");
OnFileAddedToProject (args);
if (!Loading)
ParentSolution?.OnRootDirectoriesChanged ();
}
internal void UpdateDependency (ProjectFile file, FilePath oldPath)
{
unresolvedDeps.Remove (file, oldPath);
ResolveDependencies (file);
}
internal void ResolveDependencies (ProjectFile file)
{
if (!DependencyResolutionEnabled)
return;
if (!file.ResolveParent ())
unresolvedDeps.Add (file);
List<ProjectFile> resolved = null;
foreach (ProjectFile unres in unresolvedDeps.GetUnresolvedFilesForPath (file.FilePath)) {
if (string.IsNullOrEmpty (unres.DependsOn)) {
if (resolved == null)
resolved = new List<ProjectFile> ();
resolved.Add (unres);
}
if (unres.ResolveParent (file)) {
if (resolved == null)
resolved = new List<ProjectFile> ();
resolved.Add (unres);
}
}
if (resolved != null)
foreach (ProjectFile pf in resolved)
unresolvedDeps.Remove (pf);
}
bool DependencyResolutionEnabled {
get { return unresolvedDeps != null; }
set {
if (value) {
if (unresolvedDeps != null)
return;
unresolvedDeps = new UnresolvedFileCollection ();
foreach (ProjectFile file in files)
ResolveDependencies (file);
} else {
unresolvedDeps = null;
}
}
}
IPropertySet mainGroupProperties;
void ReadProject (ProgressMonitor monitor, MSBuildProject msproject)
{
if (File.Exists (msproject.FileName + ".user")) {
userProject = new MSBuildProject (msproject.EngineManager);
userProject.Load (msproject.FileName + ".user");
}
ProjectExtension.OnReadProjectHeader (monitor, msproject);
modifiedInMemory = false;
ProjectExtension.OnReadProject (monitor, msproject);
NeedsReload = false;
}
AsyncCriticalSection writeProjectLock = new AsyncCriticalSection ();
internal async Task<string> WriteProjectAsync (ProgressMonitor monitor, bool inMemoryOnly = false)
{
using (await writeProjectLock.EnterAsync ().ConfigureAwait (false)) {
return await Task.Run (() => {
WriteProject (monitor, inMemoryOnly);
return sourceProject.SaveToString ();
}).ConfigureAwait (false);
}
}
ITimeTracker writeTimer;
void WriteProject (ProgressMonitor monitor, bool inMemoryOnly)
{
if (saving) {
LoggingService.LogError ("WriteProject called while the project is already being written");
return;
}
saving = true;
writeTimer = Counters.WriteMSBuildProject.BeginTiming ();
try {
sourceProject.FileName = FileName;
writeTimer.Trace ("Writing project header");
OnWriteProjectHeader (monitor, sourceProject);
writeTimer.Trace ("Writing project content");
ProjectExtension.OnWriteProject (monitor, sourceProject);
var globalGroup = sourceProject.GetGlobalPropertyGroup ();
globalGroup.PurgeDefaultProperties ();
globalGroup.ResetIsNewFlags ();
if (sourceProject.IsNewProject) {
// If the project is new, the evaluated properties lists are empty. Now that the project is saved,
// those lists can be filled, so that the project is left in the same state it would have if it
// was just loaded.
sourceProject.Evaluate ();
InitMainGroupProperties (globalGroup);
foreach (ProjectConfiguration conf in Configurations)
InitConfiguration (conf);
foreach (var es in runConfigurations)
InitRunConfiguration ((ProjectRunConfiguration)es);
}
sourceProject.IsNewProject = false;
// If saving to disk then clear any new remove items added in-memory.
if (!inMemoryOnly)
newMSBuildRemoveItems.Clear ();
writeTimer.Trace ("Project written");
} finally {
writeTimer.End ();
saving = false;
}
}
bool saving;
class ConfigData
{
public ConfigData (string conf, string plt, MSBuildPropertyGroup grp)
{
Config = conf;
Platform = plt;
Group = grp;
}
public string Config;
public string Platform;
public MSBuildPropertyGroup Group;
public bool Exists;
public bool IsNew; // The group did not exist in the original file
}
const string Unspecified = null;
ITimeTracker timer;
protected virtual void OnReadProjectHeader (ProgressMonitor monitor, MSBuildProject msproject)
{
timer = Counters.ReadMSBuildProject.BeginTiming ();
ToolsVersion = msproject.ToolsVersion;
if (string.IsNullOrEmpty (ToolsVersion))
ToolsVersion = "2.0";
productVersion = msproject.EvaluatedProperties.GetValue ("ProductVersion");
schemaVersion = msproject.EvaluatedProperties.GetValue ("SchemaVersion");
if (!IsReevaluating) {
// Get the project ID
string itemGuid = msproject.EvaluatedProperties.GetValue ("ProjectGuid");
if (itemGuid == null)
itemGuid = defaultItemId ?? Guid.NewGuid ().ToString ("B").ToUpper ();
// Workaround for a VS issue. VS doesn't include the curly braces in the ProjectGuid
// of shared projects.
if (!itemGuid.StartsWith ("{", StringComparison.Ordinal))
itemGuid = "{" + itemGuid + "}";
ItemId = itemGuid.ToUpper ();
}
// Get the project GUIDs
string projectTypeGuids = msproject.EvaluatedProperties.GetValue ("ProjectTypeGuids");
var subtypeGuids = new List<string> ();
if (projectTypeGuids != null) {
foreach (string guid in projectTypeGuids.Split (';')) {
string sguid = guid.Trim ();
if (sguid.Length > 0 && string.Compare (sguid, TypeGuid, StringComparison.OrdinalIgnoreCase) != 0)
subtypeGuids.Add (guid);
}
}
flavorGuids = subtypeGuids.ToArray ();
if (!CheckAllFlavorsSupported ()) {
var guids = new [] { TypeGuid };
var projectInfo = MSBuildProjectService.GetUnknownProjectTypeInfo (guids.Concat (flavorGuids).ToArray (), FileName);
IsUnsupportedProject = true;
if (projectInfo != null)
UnsupportedProjectMessage = projectInfo.GetInstructions ();
}
// Common properties
Description = msproject.EvaluatedProperties.GetValue ("Description", "");
baseIntermediateOutputPath = msproject.EvaluatedProperties.GetPathValue ("BaseIntermediateOutputPath", defaultValue:BaseDirectory.Combine ("obj"), relativeToProject:true);
disableFastUpToDateCheck = msproject.EvaluatedProperties.GetValue ("DisableFastUpToDateCheck", false);
msproject.EvaluatedProperties.ReadObjectProperties (this, GetType (), true);
}
protected virtual void OnReadProject (ProgressMonitor monitor, MSBuildProject msproject)
{
// Read available item types
// Read this first in case the OnGetSupportsImportedItem needs this information.
loadedAvailableItemNames = msproject.EvaluatedItems.Where (i => i.Name == "AvailableItemName").Select (i => i.Include).ToArray ();
timer.Trace ("Read project items");
LoadProjectItems (msproject, ProjectItemFlags.None, usedMSBuildItems);
loadedProjectItems = new HashSet<ProjectItem> (Items);
timer.Trace ("Read configurations");
List<ConfigData> configData = GetConfigData (msproject, true);
var configs = new List<ProjectConfiguration> ();
foreach (var cgrp in configData)
configs.Add (LoadConfiguration (monitor, cgrp, cgrp.Config, cgrp.Platform));
Configurations.SetItems (configs);
timer.Trace ("Read run configurations");
List<ConfigData> runConfigData = new List<ConfigData> ();
GetRunConfigData (runConfigData, msproject, true);
GetRunConfigData (runConfigData, userProject, true);
var runConfigs = new List<ProjectRunConfiguration> ();
foreach (var cgrp in runConfigData)
runConfigs.Add (LoadRunConfiguration (monitor, cgrp, cgrp.Config));
defaultRunConfigurationCreated = false;
runConfigurations.SetItems (runConfigs);
// Read extended properties
timer.Trace ("Read extended properties");
msproject.ReadExternalProjectProperties (this, GetType (), true);
// Ensure buildActions are refreshed if loadedAvailableItemNames have been updated.
buildActions = null;
}
List<ConfigData> GetConfigData (MSBuildProject msproject, bool includeEvaluated)
{
List<ConfigData> configData = new List<ConfigData> ();
foreach (MSBuildPropertyGroup cgrp in msproject.PropertyGroups) {
string conf, platform;
if (ParseConfigCondition (cgrp.Condition, out conf, out platform) && conf != null && platform != null) {
// If a group for this configuration already was found, set the new group. If there are changes we want to modify the last group.
var existing = configData.FirstOrDefault (cd => cd.Config == conf && cd.Platform == platform);
if (existing == null)
configData.Add (new ConfigData (conf, platform, cgrp));
else
existing.Group = cgrp;
}
}
if (includeEvaluated) {
var confValues = msproject.ConditionedProperties.GetCombinedPropertyValues ("Configuration");
var platValues = msproject.ConditionedProperties.GetCombinedPropertyValues ("Platform");
var confPlatValues = msproject.ConditionedProperties.GetCombinedPropertyValues ("Configuration", "Platform");
// First of all, add configurations that have been specified using both the Configuration and Platform properties.
foreach (var co in confPlatValues) {
var c = co.GetValue ("Configuration");
var ep = co.GetValue ("Platform");
ep = ep == "AnyCPU" ? "" : ep;
if (!configData.Any (cd => cd.Config == c && cd.Platform == ep))
configData.Add (new ConfigData (c, ep, null));
}
// Now add configurations for which a platform has not been specified, but only if no other configuration
// exists with the same name. Combine them with individually specified platforms, if available
foreach (var c in confValues.Select (v => v.GetValue ("Configuration"))) {
if (platValues.Count > 0) {
foreach (var plat in platValues.Select (v => v.GetValue ("Platform"))) {
var ep = plat == "AnyCPU" ? "" : plat;
if (!configData.Any (cd => cd.Config == c && cd.Platform == ep))
configData.Add (new ConfigData (c, ep, null));
}
} else {
if (!configData.Any (cd => cd.Config == c))
configData.Add (new ConfigData (c, "", null));
}
}
}
return configData;
}
bool ParseConfigCondition (string cond, out string config, out string platform)
{
config = platform = Unspecified;
int i = cond.IndexOf ("==", StringComparison.Ordinal);
if (i == -1)
return false;
if (cond.Substring (0, i).Trim () == "'$(Configuration)|$(Platform)'") {
if (!ExtractConfigName (cond.Substring (i + 2), out cond))
return false;
i = cond.IndexOf ('|');
if (i != -1) {
config = cond.Substring (0, i);
platform = cond.Substring (i+1);
} else {
// Invalid configuration
return false;
}
if (platform == "AnyCPU")
platform = string.Empty;
return true;
}
else if (cond.Substring (0, i).Trim () == "'$(Configuration)'") {
if (!ExtractConfigName (cond.Substring (i + 2), out config))
return false;
platform = Unspecified;
return true;
}
else if (cond.Substring (0, i).Trim () == "'$(Platform)'") {
config = Unspecified;
if (!ExtractConfigName (cond.Substring (i + 2), out platform))
return false;
if (platform == "AnyCPU")
platform = string.Empty;
return true;
}
return false;
}
bool ExtractConfigName (string name, out string config)
{
config = name.Trim (' ');
if (config.Length <= 2)
return false;
if (config [0] != '\'' || config [config.Length - 1] != '\'')
return false;
config = config.Substring (1, config.Length - 2);
return config.IndexOf ('\'') == -1;
}
ProjectConfiguration LoadConfiguration (ProgressMonitor monitor, ConfigData cgrp, string conf, string platform)
{
ProjectConfiguration config = null;
if (platform == "AnyCPU")
platform = "";
string id = string.IsNullOrEmpty (platform) ? conf : conf + "|" + platform;
if (IsReevaluating)
config = Configurations.OfType<ProjectConfiguration> ().FirstOrDefault (c => c.Id == id);
if (config == null)
config = CreateConfiguration (id);
if (cgrp.Group != null)
config.MainPropertyGroup = (MSBuildPropertyGroup) cgrp.Group;
config.MainPropertyGroup.ResetIsNewFlags ();
InitConfiguration (config);
projectExtension.OnReadConfiguration (monitor, config, config.Properties);
return config;
}
MSBuildProjectInstance CreateProjectInstaceForConfiguration (string conf, string platform, bool onlyEvaluateProperties = true)
{
var pi = PrepareProjectInstaceForConfiguration (conf, platform, onlyEvaluateProperties);
pi.Evaluate ();
return pi;
}
async Task<MSBuildProjectInstance> CreateProjectInstaceForConfigurationAsync (string conf, string platform, bool onlyEvaluateProperties = true)
{
var pi = PrepareProjectInstaceForConfiguration (conf, platform, onlyEvaluateProperties);
await pi.EvaluateAsync ();
return pi;
}
MSBuildProjectInstance PrepareProjectInstaceForConfiguration (string conf, string platform, bool onlyEvaluateProperties)
{
var pi = sourceProject.CreateInstance ();
pi.SetGlobalProperty ("BuildingInsideVisualStudio", "true");
if (conf != null)
pi.SetGlobalProperty ("Configuration", conf);
if (platform != null) {
if (platform == string.Empty)
pi.SetGlobalProperty ("Platform", "AnyCPU");
else
pi.SetGlobalProperty ("Platform", platform);
}
pi.OnlyEvaluateProperties = onlyEvaluateProperties;
return pi;
}
protected override SolutionItemConfiguration OnCreateConfiguration (string id, ConfigurationKind kind = ConfigurationKind.Blank)
{
return new ProjectConfiguration (id);
}
protected virtual void OnReadConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IPropertySet grp)
{
config.Read (grp);
}
void GetRunConfigData (List<ConfigData> configData, MSBuildProject msproject, bool includeEvaluated)
{
if (msproject == null)
return;
foreach (MSBuildPropertyGroup cgrp in msproject.PropertyGroups) {
string configName;
if (ParseRunConfigurationCondition (cgrp.Condition, out configName)) {
// If a group for this configuration already was found, set the new group. If there are changes we want to modify the last group.
var existing = configData.FirstOrDefault (cd => cd.Config == configName);
if (existing == null)
configData.Add (new ConfigData (configName, null, cgrp));
else
existing.Group = cgrp;
}
}
if (includeEvaluated) {
var configValues = msproject.ConditionedProperties.GetAllPropertyValues ("RunConfiguration");
foreach (var c in configValues) {
if (!configData.Any (cd => cd.Config == c))
configData.Add (new ConfigData (c, "", null));
}
}
}
bool ParseRunConfigurationCondition (string cond, out string configName)
{
configName = null;
int i = cond.IndexOf ("==", StringComparison.Ordinal);
if (i == -1)
return false;
if (cond.Substring (0, i).Trim () == "'$(RunConfiguration)'")
return ExtractConfigName (cond.Substring (i + 2), out configName);
return false;
}
ProjectRunConfiguration LoadRunConfiguration (ProgressMonitor monitor, ConfigData cgrp, string configName)
{
ProjectRunConfiguration runConfig = null;
if (IsReevaluating)
runConfig = runConfigurations.FirstOrDefault (c => c.Id == configName);
if (runConfig == null)
runConfig = CreateUninitializedRunConfiguration (configName);
if (cgrp.Group != null) {
runConfig.MainPropertyGroup = cgrp.Group;
runConfig.StoreInUserFile = cgrp.Group.ParentProject == userProject;
}
runConfig.MainPropertyGroup.ResetIsNewFlags ();
InitRunConfiguration (runConfig);
projectExtension.OnReadRunConfiguration (monitor, runConfig, runConfig.Properties);
return runConfig;
}
void InitRunConfiguration (ProjectRunConfiguration config)
{
var pi = CreateProjectInstaceForRunConfiguration (config.Name);
config.Properties = pi.GetPropertiesLinkedToGroup (config.MainPropertyGroup);
config.ProjectInstance = pi;
}
MSBuildProjectInstance CreateProjectInstaceForRunConfiguration (string name, bool onlyEvaluateProperties = true)
{
var pi = PrepareProjectInstaceForRunConfiguration (name, onlyEvaluateProperties);
pi.Evaluate ();
return pi;
}
async Task<MSBuildProjectInstance> CreateProjectInstaceForRunConfigurationAsync (string name, bool onlyEvaluateProperties = true)
{
var pi = PrepareProjectInstaceForRunConfiguration (name, onlyEvaluateProperties);
await pi.EvaluateAsync ();
return pi;
}
MSBuildProjectInstance PrepareProjectInstaceForRunConfiguration (string name, bool onlyEvaluateProperties)
{
var pi = sourceProject.CreateInstance ();
pi.SetGlobalProperty ("BuildingInsideVisualStudio", "true");
pi.SetGlobalProperty ("RunConfiguration", name);
pi.OnlyEvaluateProperties = onlyEvaluateProperties;
return pi;
}
protected virtual ProjectRunConfiguration OnCreateRunConfiguration (string name)
{
return new ProjectRunConfiguration (name);
}
protected virtual void OnReadRunConfiguration (ProgressMonitor monitor, ProjectRunConfiguration runConfig, IPropertySet grp)
{
runConfig.Read (grp);
}
internal void OnRunConfigurationsAdded (IEnumerable<SolutionItemRunConfiguration> items)
{
// Initialize the property group only if the project is not being loaded (in which case it will
// be initialized by the ReadProject method) or if the project is new (because it will be initialized
// after the project is fully written, since only then all imports are in place
if (!Loading && !sourceProject.IsNewProject) {
foreach (var s in items)
InitRunConfiguration ((ProjectRunConfiguration)s);
}
}
internal void OnRunConfigurationRemoved (IEnumerable<SolutionItemRunConfiguration> items)
{
}
internal void LoadProjectItems (MSBuildProject msproject, ProjectItemFlags flags, HashSet<MSBuildItem> loadedItems)
{
if (loadedItems != null)
loadedItems.Clear ();
HashSet<ProjectItem> unusedItems = null;
LookupTable<(string Name, string Include), ProjectItem> lookupItems = null;
ImmutableList<ProjectItem>.Builder newItems = null;
if (IsReevaluating) {
unusedItems = new HashSet<ProjectItem> (Items);
lookupItems = new LookupTable<(string Name, string Include), ProjectItem> ();
newItems = ImmutableList.CreateBuilder<ProjectItem> ();
// Improve ReadItem performance by creating a dictionary of items that can be
// searched faster than using Items.FirstOrDefault. Building this dictionary takes ~17ms
foreach (var it in Items) {
if (it.BackingItem != null && it.BackingEvalItem != null) {
lookupItems.Add (GetProjectItemLookupKey (it.BackingEvalItem), it);
}
}
}
var localItems = new List<ProjectItem> ();
foreach (var buildItem in msproject.EvaluatedItemsIgnoringCondition) {
if (buildItem.IsImported && !ProjectExtension.OnGetSupportsImportedItem (buildItem))
continue;
if (BuildAction.ReserverIdeActions.Contains (buildItem.Name))
continue;
var result = ReadItem (buildItem, lookupItems);
if (result.Item == null)
continue;
result.Item.Flags = flags;
localItems.Add (result.Item);
if (result.IsNew) {
newItems?.Add (result.Item);
} else {
unusedItems?.Remove (result.Item);
}
if (loadedItems != null) {
foreach (var item in buildItem.SourceItems) {
loadedItems.Add (item);
}
}
}
if (IsReevaluating) {
if (itemsAddedDuringReevaluation != null) {
// Handle new items added whilst re-evaluating the MSBuildProject.
foreach (var item in itemsAddedDuringReevaluation) {
unusedItems.Remove (item);
localItems.Add (item);
}
}
Items.SetItems (localItems, newItems, unusedItems);
} else
Items.AddRange (localItems);
}
static (string Name, string Include) GetProjectItemLookupKey (IMSBuildItemEvaluated item)
{
return (item.Name, item.Include);
}
protected override void OnSetFormat (MSBuildFileFormat format)
{
base.OnSetFormat (format);
InitFormatProperties ();
}
void InitFormatProperties ()
{
ToolsVersion = FileFormat.DefaultToolsVersion;
schemaVersion = FileFormat.DefaultSchemaVersion;
// Don't change the product version if it is already set. We don't really use this,
// and we can avoid unnecessary changes in the proj file.
if (string.IsNullOrEmpty (productVersion))
productVersion = FileFormat.DefaultProductVersion;
}
internal (ProjectItem Item, bool IsNew) ReadItem (IMSBuildItemEvaluated buildItem, LookupTable<(string Name, string Include), ProjectItem> lookupItems)
{
if (IsReevaluating) {
// If this item already exists in the current collection of items, reuse it
var key = GetProjectItemLookupKey (buildItem);
foreach (var eit in lookupItems.GetItems (key)) {
if (ItemsAreEqual (buildItem, eit)) {
lookupItems.Remove (key, eit);
eit.BackingItem = buildItem.SourceItem;
eit.BackingEvalItem = buildItem;
return (eit, false);
}
}
if (itemsRemovedDuringReevaluation != null) {
// Handle items removed whilst re-evaluating the MSBuildProject.
ProjectItem matchedRemovedItem = null;
foreach (var removedItem in itemsRemovedDuringReevaluation) {
if (ItemsAreEqual (buildItem, removedItem.BackingEvalItem) || CheckProjectReferenceItemsAreEqual (buildItem, removedItem)) {
matchedRemovedItem = removedItem;
break;
}
}
if (matchedRemovedItem != null) {
itemsRemovedDuringReevaluation.Remove (matchedRemovedItem);
if (usedMSBuildItems != null) {
foreach (var sourceItem in buildItem.SourceItems) {
usedMSBuildItems.Add (sourceItem);
}
}
return (null, false);
}
}
}
var item = CreateProjectItem (buildItem);
item.Read (this, buildItem);
item.BackingItem = buildItem.SourceItem;
item.BackingEvalItem = buildItem;
return (item, true);
}
bool ItemsAreEqual (IMSBuildItemEvaluated buildItem, ProjectItem item)
{
return ItemsAreEqual (buildItem, item.BackingEvalItem) || CheckProjectReferenceItemsAreEqual (buildItem, item);
}
/// <summary>
/// Special case ProjectReference items when checking for a match for ReadItem. The underlying build
/// items may not have matching metadata properties but the ProjectReference.Equals method may
/// indicate a match. This is tested for in the ProjectReevaluationTests
/// ReevaluateNewProjectReferencesAfterSave test.
/// </summary>
bool CheckProjectReferenceItemsAreEqual (IMSBuildItemEvaluated buildItem, ProjectItem item)
{
if (!(item is ProjectReference existingProjectReference))
return false;
var newProjectReference = CreateProjectItem (buildItem) as ProjectReference;
if (newProjectReference != null) {
newProjectReference.Read (this, buildItem);
return item.Equals (newProjectReference);
}
return false;
}
readonly struct MergedPropertyValue
{
public readonly string XmlValue;
public readonly MSBuildValueType ValueType;
public readonly bool IsDefault;
public MergedPropertyValue (string xmlValue, MSBuildValueType valueType, bool isDefault)
{
this.XmlValue = xmlValue;
this.ValueType = valueType;
this.IsDefault = isDefault;
}
}
protected virtual void OnWriteProjectHeader (ProgressMonitor monitor, MSBuildProject msproject)
{
if (string.IsNullOrEmpty (sourceProject.DefaultTargets) && SupportsBuild ())
sourceProject.DefaultTargets = "Build";
IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup ();
if (globalGroup == null)
globalGroup = msproject.AddNewPropertyGroup (false);
if (Configurations.Count > 0) {
// Set the default configuration of the project.
// First of all get the properties that define the default configuration and platform
var defaultConfProp = globalGroup.GetProperties ().FirstOrDefault (p => p.Name == "Configuration" && IsDefaultSetter (p));
var defaultPlatProp = globalGroup.GetProperties ().FirstOrDefault (p => p.Name == "Platform" && IsDefaultSetter (p));
if (msproject.IsNewProject || (defaultConfProp != null && defaultPlatProp != null)) {
// If there is no config property, or if the config doesn't exist anymore, give it a new value
if (defaultConfProp == null || !Configurations.Any<SolutionItemConfiguration> (c => c.Name == defaultConfProp.UnevaluatedValue)) {
ItemConfiguration conf = Configurations.FirstOrDefault<ItemConfiguration> (c => c.Name == "Debug");
if (conf == null) conf = Configurations [0];
string platform = conf.Platform.Length == 0 ? "AnyCPU" : conf.Platform;
globalGroup.SetValue ("Configuration", conf.Name, condition: " '$(Configuration)' == '' ");
globalGroup.SetValue ("Platform", platform, condition: " '$(Platform)' == '' ");
} else if (defaultPlatProp == null || !Configurations.Any<SolutionItemConfiguration> (c => c.Name == defaultConfProp.UnevaluatedValue && c.Platform == defaultPlatProp.UnevaluatedValue)) {
ItemConfiguration conf = Configurations.FirstOrDefault<ItemConfiguration> (c => c.Name == defaultConfProp.UnevaluatedValue);
string platform = conf.Platform.Length == 0 ? "AnyCPU" : conf.Platform;
globalGroup.SetValue ("Platform", platform, condition: " '$(Platform)' == '' ");
}
}
}
/* if (runConfigurations.Count > 0) {
// Set the default configuration of the project.
// First of the properties that defines the default run configuration
var defaultConfProp = globalGroup.GetProperties ().FirstOrDefault (p => p.Name == "RunConfiguration" && IsDefaultSetter (p));
if (msproject.IsNewProject || (defaultConfProp != null)) {
// If there is no run configuration property, or if the configuration doesn't exist anymore, give it a new value
if (defaultConfProp == null || !runConfigurations.Any (c => c.Name == defaultConfProp.UnevaluatedValue)) {
var runConfig = runConfigurations.FirstOrDefault (c => c.Name == "Default") ?? runConfigurations [0];
globalGroup.SetValue ("RunConfiguration", runConfig.Name, condition: " '$(RunConfiguration)' == '' ");
}
}
}*/
if (TypeGuid == MSBuildProjectService.GenericItemGuid) {
DataType dt = MSBuildProjectService.DataContext.GetConfigurationDataType (GetType ());
globalGroup.SetValue ("ItemType", dt.Name);
}
globalGroup.SetValue ("ProductVersion", productVersion);
globalGroup.SetValue ("SchemaVersion", schemaVersion);
globalGroup.SetValue ("ProjectGuid", ItemId, valueType:MSBuildValueType.Guid);
if (flavorGuids.Length > 0) {
string gg = string.Join (";", flavorGuids);
gg += ";" + TypeGuid;
globalGroup.SetValue ("ProjectTypeGuids", gg.ToUpper (), preserveExistingCase:true);
} else if (!string.Equals (globalGroup.GetValue ("ProjectTypeGuids"), TypeGuid, StringComparison.OrdinalIgnoreCase)) {
// Keep the property if it already was there with the same value, remove otherwise
globalGroup.RemoveProperty ("ProjectTypeGuids");
}
// having no ToolsVersion is equivalent to 2.0, roundtrip that correctly
if (ToolsVersion != "2.0")
msproject.ToolsVersion = ToolsVersion;
else if (string.IsNullOrEmpty (msproject.ToolsVersion))
msproject.ToolsVersion = null;
else
msproject.ToolsVersion = "2.0";
msproject.GetGlobalPropertyGroup ().SetValue ("Description", Description, "");
msproject.GetGlobalPropertyGroup ().SetValue ("BaseIntermediateOutputPath", BaseIntermediateOutputPath, defaultValue:BaseDirectory.Combine ("obj"), relativeToProject:true);
msproject.GetGlobalPropertyGroup ().SetValue ("DisableFastUpToDateCheck", disableFastUpToDateCheck, false);
globalGroup.WriteObjectProperties (this, GetType (), true);
}
protected virtual void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject)
{
IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup ();
writeTimer.Trace ("Writing configurations");
WriteConfigurations (monitor, msproject, globalGroup);
writeTimer.Trace ("Done writing configurations");
writeTimer.Trace ("Writing run configurations");
WriteRunConfigurations (monitor, msproject, globalGroup);
writeTimer.Trace ("Done writing run configurations");
writeTimer.Trace ("Saving project items");
SaveProjectItems (monitor, msproject, usedMSBuildItems);
writeTimer.Trace ("Done saving project items");
if (msproject.IsNewProject) {
foreach (var im in DefaultImports)
msproject.AddNewImport (im);
}
foreach (var im in importsAdded) {
if (msproject.GetImport (im.Name, im.Condition) == null)
msproject.AddNewImport (im.Name, im.Condition);
}
foreach (var im in importsRemoved) {
var i = msproject.GetImport (im.Name, im.Condition);
if (i != null)
msproject.RemoveImport (i);
}
importsAdded.Clear ();
importsRemoved.Clear ();
writeTimer.Trace ("Writing external properties");
msproject.WriteExternalProjectProperties (this, GetType (), true);
writeTimer.Trace ("Done writing external properties");
}
void WriteConfigurations (ProgressMonitor monitor, MSBuildProject msproject, IMSBuildPropertySet globalGroup)
{
if (Configurations.Count > 0) {
List<ConfigData> configData = GetConfigData (msproject, false);
// Write configuration data, creating new property groups if necessary
foreach (ProjectConfiguration conf in Configurations) {
MSBuildPropertyGroup pg = conf.MainPropertyGroup;
ConfigData cdata = configData.FirstOrDefault (cd => cd.Group == pg);
if (cdata == null) {
// Try to keep the groups in the same order as the config list
MSBuildObject nextConf = null;
int i = Configurations.IndexOf (conf);
if (i != -1 && i + 1 < Configurations.Count)
nextConf = ((ProjectConfiguration)Configurations [i + 1]).MainPropertyGroup;
msproject.AddPropertyGroup (pg, true, nextConf);
pg.Condition = BuildConfigCondition (conf.Name, conf.Platform);
cdata = new ConfigData (conf.Name, conf.Platform, pg);
cdata.IsNew = true;
configData.Add (cdata);
} else {
// The configuration name may have changed
if (cdata.Config != conf.Name || cdata.Platform != conf.Platform) {
((MSBuildPropertyGroup)cdata.Group).Condition = BuildConfigCondition (conf.Name, conf.Platform);
cdata.Config = conf.Name;
cdata.Platform = conf.Platform;
}
}
cdata.Exists = true;
ProjectExtension.OnWriteConfiguration (monitor, conf, conf.Properties);
}
// Find the properties in all configurations that have the MergeToProject flag set
var mergeToProjectProperties = new HashSet<MergedProperty> (GetMergeToProjectProperties (configData));
var mergeToProjectPropertyValues = new Dictionary<string, MergedPropertyValue> ();
foreach (ProjectConfiguration conf in Configurations) {
ConfigData cdata = FindPropertyGroup (configData, conf);
var propGroup = (MSBuildPropertyGroup)cdata.Group;
// Get properties with the MergeToProject flag, and check that the value they have matches the
// value all the other groups have so far. If one of the groups have a different value for
// the same property, then the property is discarded as mergeable to parent.
CollectMergetoprojectProperties (propGroup, mergeToProjectProperties, mergeToProjectPropertyValues);
// Remove properties that have been modified and have the default value. Usually such properties
// would be removed when assigning the value, but we set IgnoreDefaultValues=false so that
// we can collect MergeToProject properties, so in this case properties are not removed.
propGroup.PurgeDefaultProperties ();
}
// Move properties with common values from configurations to the main
// property group
foreach (KeyValuePair<string, MergedPropertyValue> prop in mergeToProjectPropertyValues) {
if (!prop.Value.IsDefault)
globalGroup.SetValue (prop.Key, prop.Value.XmlValue, valueType: prop.Value.ValueType);
else {
// if the value is default, only remove the property if it was not already the default to avoid unnecessary project file churn
globalGroup.SetValue (prop.Key, prop.Value.XmlValue, defaultValue: prop.Value.XmlValue, valueType: prop.Value.ValueType);
}
}
foreach (SolutionItemConfiguration conf in Configurations) {
var propGroup = FindPropertyGroup (configData, conf).Group;
foreach (string mp in mergeToProjectPropertyValues.Keys)
propGroup.RemoveProperty (mp);
}
// Remove groups corresponding to configurations that have been removed
// or groups which don't have any property and did not already exist
foreach (ConfigData cd in configData) {
if (!cd.Exists || (cd.IsNew && !cd.Group.GetProperties ().Any ()))
msproject.Remove ((MSBuildPropertyGroup)cd.Group);
}
foreach (ProjectConfiguration config in Configurations)
config.MainPropertyGroup.ResetIsNewFlags ();
// For properties that have changed in the main group, set the
// dirty flag for the corresponding properties in the evaluated
// project instances. The evaluated values of those properties
// can't be used anymore to decide wether or not a property
// needs to be saved. The ideal solution would be to re-evaluate
// the instance and get the new evaluated values, but that
// would have a high impact in performance.
foreach (var p in globalGroup.GetProperties ()) {
if (p.Modified) {
foreach (ProjectConfiguration config in Configurations)
if (config.ProjectInstance != null)
config.ProjectInstance.SetPropertyValueStale (p.Name);
}
}
}
}
ProjectRunConfiguration defaultBlankRunConfiguration;
void WriteRunConfigurations (ProgressMonitor monitor, MSBuildProject msproject, IMSBuildPropertySet globalGroup)
{
List<ConfigData> configData = new List<ConfigData> ();
GetRunConfigData (configData, msproject, false);
GetRunConfigData (configData, userProject, false);
if (RunConfigurations.Count > 0) {
// Write configuration data, creating new property groups if necessary
// Create the default configuration just once, and reuse it for comparing in subsequent writes
if (defaultBlankRunConfiguration == null)
defaultBlankRunConfiguration = CreateRunConfigurationInternal ("Default");
foreach (ProjectRunConfiguration runConfig in RunConfigurations) {
MSBuildPropertyGroup pg = runConfig.MainPropertyGroup;
ConfigData cdata = configData.FirstOrDefault (cd => cd.Group == pg);
var targetProject = runConfig.StoreInUserFile ? userProject : msproject;
if (runConfig.IsDefaultConfiguration && runConfig.Equals (defaultBlankRunConfiguration)) {
// If the default configuration has the default values, then there is no need to save it.
// If this configuration was added after loading the project, we are not adding it to the msproject and we are done.
// If this configuration was loaded from the project and later modified to the default values, we dont set cdata.Exists=true,
// so it will be removed from the msproject below.
continue;
}
// Create the user project file if it doesn't yet exist
if (targetProject == null)
targetProject = userProject = CreateUserProject (msproject);
if (cdata == null) {
// Try to keep the groups in the same order as the config list
MSBuildObject nextConfig = null;
int i = runConfigurations.IndexOf (runConfig);
if (i != -1 && i + 1 < runConfigurations.Count)
nextConfig = runConfigurations.Skip (i).Cast<ProjectRunConfiguration> ().FirstOrDefault (s => s.MainPropertyGroup.ParentProject == targetProject)?.MainPropertyGroup;
targetProject.AddPropertyGroup (pg, true, nextConfig);
pg.Condition = BuildRunConfigurationCondition (runConfig.Name);
cdata = new ConfigData (runConfig.Name, null, pg);
cdata.IsNew = true;
configData.Add (cdata);
} else {
// The configuration name may have changed
if (cdata.Config != runConfig.Name) {
((MSBuildPropertyGroup)cdata.Group).Condition = BuildRunConfigurationCondition (runConfig.Name);
cdata.Config = runConfig.Name;
}
var groupInUserProject = cdata.Group.ParentProject == userProject;
if (groupInUserProject != runConfig.StoreInUserFile) {
cdata.Group.ParentProject.Remove (cdata.Group);
targetProject.AddPropertyGroup (cdata.Group);
}
}
cdata.Exists = true;
ProjectExtension.OnWriteRunConfiguration (monitor, runConfig, runConfig.Properties);
runConfig.MainPropertyGroup.PurgeDefaultProperties ();
}
}
// Remove groups corresponding to configurations that have been removed
foreach (ConfigData cd in configData) {
if (!cd.Exists)
cd.Group.ParentProject.Remove (cd.Group);
}
foreach (ProjectRunConfiguration runConfig in runConfigurations)
runConfig.MainPropertyGroup.ResetIsNewFlags ();
}
MSBuildProject CreateUserProject (MSBuildProject msproject)
{
var p = new MSBuildProject (msproject.EngineManager);
// Remove the main property group
p.Remove (p.PropertyGroups.First ());
p.FileName = msproject.FileName + ".user";
return p;
}
protected virtual void OnWriteConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IPropertySet pset)
{
config.Write (pset);
}
protected virtual void OnWriteRunConfiguration (ProgressMonitor monitor, ProjectRunConfiguration config, IPropertySet pset)
{
config.Write (pset);
}
IEnumerable<MergedProperty> GetMergeToProjectProperties (List<ConfigData> configData)
{
Dictionary<string,MergedProperty> mergeProps = new Dictionary<string, MergedProperty> ();
foreach (var cd in configData) {
foreach (var prop in cd.Group.GetProperties ()) {
if (!prop.MergeToMainGroup) {
mergeProps [prop.Name] = null;
} else if (!mergeProps.ContainsKey (prop.Name))
mergeProps [prop.Name] = prop.CreateMergedProperty ();
}
}
return mergeProps.Values.Where (p => p != null);
}
void CollectMergetoprojectProperties (IMSBuildPropertySet pgroup, HashSet<MergedProperty> properties, Dictionary<string,MergedPropertyValue> mergeToProjectProperties)
{
// This method checks every property in pgroup which has the MergeToProject flag.
// If the value of this property is the same as the one stored in mergeToProjectProperties
// it means that the property can be merged to the main project property group (so far).
foreach (var pinfo in new List<MergedProperty> (properties)) {
MSBuildProperty prop = pgroup.GetProperty (pinfo.Name);
MergedPropertyValue mvalue;
if (!mergeToProjectProperties.TryGetValue (pinfo.Name, out mvalue)) {
if (prop != null) {
// This is the first time the value is checked. Just assign it.
mergeToProjectProperties.Add (pinfo.Name, new MergedPropertyValue (prop.Value, pinfo.ValueType, pinfo.IsDefault));
continue;
}
// If there is no value, it can't be merged
}
else if (prop != null && mvalue.ValueType.Equals (prop.Value, mvalue.XmlValue))
// Same value. It can be merged.
continue;
// The property can't be merged because different configurations have different
// values for it. Remove it from the list.
properties.Remove (pinfo);
mergeToProjectProperties.Remove (pinfo.Name);
}
}
bool IsDefaultSetter (MSBuildProperty prop)
{
var val = prop.Condition;
int i = val.IndexOf ("==");
if (i == -1)
return false;
return val.Substring (0, i).Trim () == "'$(" + prop.Name + ")'" && val.Substring (i + 2).Trim () == "''";
}
class ExpandedItemList: List<ExpandedItemInfo>
{
public bool Modified { get; set; }
}
class ExpandedItemInfo
{
public ProjectItem ProjectItem;
public MSBuildItem MSBuildItem;
public ExpandedItemAction Action;
}
enum ExpandedItemAction
{
None,
Exclude,
AddUpdateItem
}
/// <summary>
/// When set to true, the project will make use of improved globbing logic to avoid expanding glob in multiple items when
/// there are changes. Requires the latest version of msbuild to work.
/// </summary>
public bool UseAdvancedGlobSupport { get; set; }
/// <summary>
/// When set to true if new file is added to a project that does not have
/// the metadata properties defined by a update glob item then the item will
/// not be excluded but will be treated as though it had these metadata properties
/// with the same values.
/// </summary>
public bool UseDefaultMetadataForExcludedExpandedItems { get; set; }
HashSet<MSBuildItem> usedMSBuildItems = new HashSet<MSBuildItem> ();
HashSet<ProjectItem> loadedProjectItems = new HashSet<ProjectItem> ();
HashSet<(MSBuildItem MSBuildItem, FilePath FilePath)> newMSBuildRemoveItems = new HashSet<(MSBuildItem MSBuildItem, FilePath FilePath)> ();
internal virtual void SaveProjectItems (ProgressMonitor monitor, MSBuildProject msproject, HashSet<MSBuildItem> loadedItems, string pathPrefix = null)
{
HashSet<MSBuildItem> unusedItems = new HashSet<MSBuildItem> (loadedItems);
Dictionary<MSBuildItem,ExpandedItemList> expandedItems = new Dictionary<MSBuildItem, ExpandedItemList> ();
// Add the new items
foreach (ProjectItem ob in Items.Where (it => !it.Flags.HasFlag (ProjectItemFlags.DontPersist)))
SaveProjectItem (monitor, msproject, ob, expandedItems, unusedItems, loadedItems, pathPrefix);
// Process items generated from wildcards
foreach (var itemInfo in expandedItems) {
var expandedList = itemInfo.Value;
var globItem = itemInfo.Key;
if (expandedList.Modified || loadedProjectItems.Where (i => i.WildcardItem == globItem).Count () != expandedList.Count) {
if (UseAdvancedGlobSupport) {
// Add remove items if necessary
foreach (var removed in loadedProjectItems.Where (i => i.WildcardItem == globItem && !expandedList.Any (newItem => newItem.ProjectItem.Include == i.Include))) {
var file = removed as ProjectFile;
if (file == null || File.Exists (file.FilePath)) {
var removeItem = new MSBuildItem (removed.ItemName) { Remove = removed.Include };
msproject.AddItem (removeItem);
if (file != null)
newMSBuildRemoveItems.Add ((removeItem, file.FilePath));
}
unusedItems.UnionWith (FindUpdateItemsForItem (globItem, removed.Include));
}
// Exclude modified items
foreach (var it in expandedList) {
if (it.Action == ExpandedItemAction.Exclude) {
globItem.AddExclude (it.ProjectItem.Include);
it.ProjectItem.BackingItem = it.MSBuildItem;
it.ProjectItem.BackingEvalItem = CreateFakeEvaluatedItem (msproject, it.MSBuildItem, it.MSBuildItem.Include, null);
msproject.AddItem (it.MSBuildItem);
} else if (it.Action == ExpandedItemAction.AddUpdateItem) {
msproject.AddItem (it.MSBuildItem);
}
}
} else {
// Expand the list
unusedItems.Add (globItem);
foreach (var it in expandedList) {
it.ProjectItem.BackingItem = it.MSBuildItem;
it.ProjectItem.BackingEvalItem = CreateFakeEvaluatedItem (msproject, it.MSBuildItem, it.MSBuildItem.Include, null);
msproject.AddItem (it.MSBuildItem);
}
}
}
}
// Remove unused items
foreach (var it in unusedItems) {
if (it.ParentGroup != null) { // It may already have been deleted
// Remove wildcard item if it is not imported.
if ((!it.IsWildcardItem && it.ParentProject == msproject) || it.ParentProject == msproject) {
msproject.RemoveItem (it);
if (!UseAdvancedGlobSupport)
continue;
var file = loadedProjectItems.FirstOrDefault (i => {
return i.ItemName == it.Name && (i.Include == it.Include || i.Include == it.Update);
}) as ProjectFile;
if (file != null && !file.IsLink) {
if (File.Exists (file.FilePath)) {
AddRemoveItemIfMissing (msproject, file);
} else if (!string.IsNullOrEmpty (it.Include)) {
// Remove any "Remove" items that match if the file has been deleted.
var toRemove = msproject.GetAllItems ().Where (i => i.Remove == it.Include).ToList ();
foreach (var item in toRemove) {
msproject.RemoveItem (item);
}
}
}
} else if (it.IsWildcardItem && UseAdvancedGlobSupport) {
// Add "Remove" items if the file is not deleted.
foreach (var file in loadedProjectItems.Where (i => i.WildcardItem == it).OfType<ProjectFile> ()) {
if (File.Exists (file.FilePath)) {
AddRemoveItemIfMissing (msproject, file);
}
// Ensure "Update" items are removed from the project. If there are no
// files left in the project for the glob then the "Update" item will
// not have been removed.
RemoveUpdateItemsForFile (msproject, it, file);
}
}
}
loadedItems.Remove (it);
}
// Remove any unused MSBuild Remove items that were added in memory only. These may have been added
// when an MSBuild target was run whilst a file was being deleted from a project.
foreach (var removeItem in newMSBuildRemoveItems) {
if (!File.Exists (removeItem.FilePath))
msproject.RemoveItem (removeItem.MSBuildItem);
}
loadedProjectItems = new HashSet<ProjectItem> (Items);
}
void SaveProjectItem (ProgressMonitor monitor, MSBuildProject msproject, ProjectItem item, Dictionary<MSBuildItem,ExpandedItemList> expandedItems, HashSet<MSBuildItem> unusedItems, HashSet<MSBuildItem> loadedItems, string pathPrefix = null)
{
if (item.IsFromWildcardItem && item.ItemName == item.WildcardItem.Name) {
var globItem = item.WildcardItem;
// Store the item in the list of expanded items
ExpandedItemList items;
if (!expandedItems.TryGetValue (globItem, out items))
items = expandedItems [globItem] = new ExpandedItemList ();
// We need to check if the item has changed, in which case all the items included by the wildcard
// must be individually included
var bitem = msproject.CreateItem (item.ItemName, GetPrefixedInclude (pathPrefix, item.Include));
item.Write (this, bitem);
var einfo = new ExpandedItemInfo {
ProjectItem = item,
MSBuildItem = bitem
};
items.Add (einfo);
foreach (var it in item.BackingEvalItem.SourceItems)
unusedItems.Remove (it);
if (UseAdvancedGlobSupport) {
einfo.Action = GenerateItemDiff (globItem, bitem, item.BackingEvalItem);
if (einfo.Action != ExpandedItemAction.None)
items.Modified = true;
} else if (!items.Modified && (item.Metadata.PropertyCountHasChanged || !ItemsAreEqual (bitem, item.BackingEvalItem))) {
items.Modified = true;
}
return;
}
var include = GetPrefixedInclude (pathPrefix, item.UnevaluatedInclude ?? item.Include);
MSBuildItem buildItem = null;
IEnumerable<MSBuildItem> sourceItems = null;
MSBuildEvaluationContext context = null;
if (item.BackingItem?.ParentObject != null && item.BackingItem.Name == item.ItemName) {
buildItem = item.BackingItem;
sourceItems = item.BackingEvalItem.SourceItems;
} else {
if (UseAdvancedGlobSupport) {
// It is a new item. Before adding it, check if there is a Remove for the item. If there is, it is likely the file was excluded from a glob.
var toRemove = msproject.GetAllItems ().Where (it => it.Name == item.ItemName && it.Remove == include).ToList ();
if (toRemove.Count > 0) {
// Remove the "Remove" items
foreach (var it in toRemove)
msproject.RemoveItem (it);
}
// Check if the file is included in a glob.
var matchingGlobItems = msproject.FindGlobItemsIncludingFile (item.Include).ToList ();
var globItem = matchingGlobItems.FirstOrDefault (gi => gi.Name == item.ItemName);
if (globItem != null) {
var updateGlobItems = msproject.FindUpdateGlobItemsIncludingFile (item.Include, globItem).ToList ();
// Globbing magic can only be done if there is no metadata (for now)
if (globItem.Metadata.GetProperties ().Count () == 0 && !updateGlobItems.Any ()) {
var it = new MSBuildItem (item.ItemName);
var itemDefinitionProps = msproject.GetEvaluatedItemDefinitionProperties (it.Name);
if (itemDefinitionProps != null) {
var propertiesAlreadySet = new HashSet<string> ();
item.Write (this, it);
AddEmptyItemDefinitionProperties (it, itemDefinitionProps);
PurgeItemDefinitionProperties (it, itemDefinitionProps, propertiesAlreadySet);
} else {
item.Write (this, it);
}
if (it.Metadata.GetProperties ().Count () == 0)
buildItem = globItem;
// Add an expanded item so a Remove item does not
// get added back again.
ExpandedItemList items;
if (!expandedItems.TryGetValue (globItem, out items))
items = expandedItems [globItem] = new ExpandedItemList ();
var einfo = new ExpandedItemInfo {
ProjectItem = item,
MSBuildItem = it
};
items.Add (einfo);
if (buildItem == null && item.BackingItem != null && globItem.Name != item.BackingItem.Name) {
it.Update = item.Include;
sourceItems = new [] { globItem };
item.BackingItem = globItem;
item.BackingEvalItem = CreateFakeEvaluatedItem (msproject, it, globItem.Include, sourceItems);
einfo.Action = ExpandedItemAction.AddUpdateItem;
items.Modified = true;
return;
} else if (buildItem == null) {
buildItem = new MSBuildItem (item.ItemName) { Update = item.Include };
msproject.AddItem (buildItem);
}
} else if (updateGlobItems.Any ()) {
// Multiple update items not supported yet.
buildItem = updateGlobItems [0];
sourceItems = new [] { globItem, buildItem };
context = CreateEvaluationContext (item);
} else {
buildItem = globItem;
}
} else if (item.IsFromWildcardItem && item.ItemName != item.WildcardItem.Name) {
include = item.Include;
var removeItem = new MSBuildItem (item.WildcardItem.Name) { Remove = include };
msproject.AddItem (removeItem);
}
// Add remove item if file is included in a glob with a different MSBuild item type.
// But do not add the remove item if the item is already removed with another glob.
var removeGlobItem = matchingGlobItems.FirstOrDefault (gi => gi.Name != item.ItemName);
var alreadyRemovedGlobItem = matchingGlobItems.FirstOrDefault (gi => gi.Name == item.ItemName);
if (removeGlobItem != null && alreadyRemovedGlobItem == null) {
// Do not add the remove item if one already exists or if the Items contains
// an include for the item.
if (!msproject.GetAllItems ().Any (it => it.Name == removeGlobItem.Name && it.Remove == item.Include) &&
!Items.Any (it => it.ItemName == removeGlobItem.Name && it.Include == item.Include)) {
var removeItem = new MSBuildItem (removeGlobItem.Name) { Remove = item.Include };
msproject.AddItem (removeItem);
}
}
}
if (buildItem == null)
buildItem = msproject.AddNewItem (item.ItemName, include);
item.BackingItem = buildItem;
item.BackingEvalItem = CreateFakeEvaluatedItem (msproject, buildItem, include, sourceItems, context);
}
loadedItems.Add (buildItem);
unusedItems.Remove (buildItem);
if (sourceItems != null) {
foreach (var sourceItem in sourceItems) {
loadedItems.Add (sourceItem);
unusedItems.Remove (sourceItem);
}
}
if (!buildItem.IsWildcardItem) {
if (buildItem.IsUpdate) {
var itemDefinitionProps = msproject.GetEvaluatedItemDefinitionProperties (buildItem.Name);
var propertiesAlreadySet = new HashSet<string> (buildItem.Metadata.GetProperties ().Select (p => p.Name));
item.Write (this, buildItem);
if (itemDefinitionProps != null) {
AddEmptyItemDefinitionProperties (buildItem, itemDefinitionProps);
PurgeItemDefinitionProperties (buildItem, itemDefinitionProps, propertiesAlreadySet);
}
PurgeUpdatePropertiesSetInSourceItems (buildItem, item.BackingEvalItem.SourceItems, propertiesAlreadySet);
} else {
var itemDefinitionProps = msproject.GetEvaluatedItemDefinitionProperties (buildItem.Name);
if (itemDefinitionProps != null) {
var propertiesAlreadySet = new HashSet<string> (buildItem.Metadata.GetProperties ().Select (p => p.Name));
item.Write (this, buildItem);
AddEmptyItemDefinitionProperties (buildItem, itemDefinitionProps);
PurgeItemDefinitionProperties (buildItem, itemDefinitionProps, propertiesAlreadySet);
} else {
item.Write (this, buildItem);
}
if (buildItem.Include != include)
buildItem.Include = include;
}
}
}
static void AddRemoveItemIfMissing (MSBuildProject msproject, ProjectFile file)
{
if (!msproject.GetAllItems ().Where (i => i.Remove == file.Include).Any ()) {
var removeItem = new MSBuildItem (file.ItemName) { Remove = file.Include };
msproject.AddItem (removeItem);
}
}
void RemoveUpdateItemsForFile (MSBuildProject msproject, MSBuildItem globItem, ProjectFile file)
{
foreach (var updateItem in FindUpdateItemsForItem (globItem, file.Include).ToList ()) {
if (updateItem.ParentGroup != null) {
msproject.RemoveItem (updateItem);
}
}
}
void PurgeUpdatePropertiesSetInSourceItems (MSBuildItem buildItem, IEnumerable<MSBuildItem> sourceItems, HashSet<string> propertiesAlreadySet)
{
// When the project item is saved to an Update item, it will write values that were set by the Include item and other Update items defined before this Update item.
// We need to go back to those items and check if any of the values they set is the same that has
// been written. In that case, the property doesn't need to be set again in the Update item, and can be removed.
// We ignore properties that were already set in the original file. We always set those.
var itemsToCheck = sourceItems.ToList ();
List<string> propsToRemove = null;
foreach (var p in buildItem.Metadata.GetProperties ().Where (pr => !propertiesAlreadySet.Contains (pr.Name))) {
// The last item of the sourceItems list is supposed to be buildItem, so we need to skip it.
// Also traverse in reverse order, so we check the last property value set.
for (int n = itemsToCheck.Count - 2; n >= 0; n++) {
var it = itemsToCheck [n];
var prop = it.Metadata.GetProperty (p.Name);
if (prop != null) {
if (p.ValueType.Equals (p.Value, prop.Value)) {
// This item defines the same metadata, so that metadata doesn't need to be set in the Update item
if (propsToRemove == null)
propsToRemove = new List<string> ();
propsToRemove.Add (p.Name);
}
break;
}
}
}
if (propsToRemove != null) {
foreach (var name in propsToRemove)
buildItem.Metadata.RemoveProperty (name);
}
}
/// <summary>
/// If the MSBuildItem does not define the property defined by its ItemDefinition then we need to set an empty
/// string for the metadata property value. Otherwise the property information for a new file will be incorrect
/// in the IDE.
/// </summary>
void AddEmptyItemDefinitionProperties (MSBuildItem buildItem, IMSBuildPropertyGroupEvaluated itemDefinitionProps)
{
foreach (var p in itemDefinitionProps.GetProperties ()) {
if (!buildItem.Metadata.HasProperty (p.Name))
buildItem.Metadata.SetValue (p.Name, string.Empty);
}
}
void PurgeItemDefinitionProperties (MSBuildItem buildItem, IMSBuildPropertyGroupEvaluated itemDefinitionProps, HashSet<string> propertiesAlreadySet)
{
List<string> propsToRemove = null;
foreach (var p in buildItem.Metadata.GetProperties ().Where (pr => !propertiesAlreadySet.Contains (pr.Name))) {
var prop = itemDefinitionProps.GetProperty (p.Name);
if (prop != null) {
if (p.ValueType.Equals (p.Value, prop.Value)) {
// This item definition defines the same metadata, so that metadata does not need to be set in the MSBuild item
if (propsToRemove == null)
propsToRemove = new List<string> ();
propsToRemove.Add (p.Name);
}
}
}
if (propsToRemove != null) {
foreach (var name in propsToRemove)
buildItem.Metadata.RemoveProperty (name);
}
}
bool ItemsAreEqual (MSBuildItem item, IMSBuildItemEvaluated evalItem)
{
// Compare only metadata, since item name and include can't change
var n = 0;
foreach (var p in item.Metadata.GetProperties ()) {
var p2 = evalItem.Metadata.GetProperty (p.Name);
if (p2 == null)
return false;
if (!p.ValueType.Equals (p.Value, p2.UnevaluatedValue)) {
if (p2.UnevaluatedValue != null && p2.UnevaluatedValue.Contains ('%')) {
// Check evaluated value is a match.
if (!p.ValueType.Equals (p.Value, p2.Value))
return false;
} else
return false;
}
n++;
}
if (evalItem.Metadata.GetProperties ().Count () != n)
return false;
return true;
}
ExpandedItemAction GenerateItemDiff (MSBuildItem globItem, MSBuildItem item, IMSBuildItemEvaluated evalItem)
{
// This method compares the evaluated item that was used to load a project item with the msbuild
// item that has now been saved. If there are changes, it saves the changes in an item with Update
// attribute.
MSBuildItem updateItem = null;
HashSet<MSBuildItem> itemsToDelete = null;
List <MSBuildItem> updateItems = null;
List<MSBuildProperty> unchangedProperties = null;
bool generateNewUpdateItem = false;
foreach (var p in item.Metadata.GetProperties ()) {
var p2 = evalItem.Metadata.GetProperty (p.Name);
if (p2 == null || !p.ValueType.Equals (p.Value, p2.UnevaluatedValue)) {
if (generateNewUpdateItem)
continue;
if (p2?.UnevaluatedValue != null && p2.UnevaluatedValue.Contains ('%') && p.ValueType.Equals (p.Value, p2.Value))
continue;
if (updateItem == null) {
updateItems = FindUpdateItemsForItem (globItem, item.Include).ToList ();
updateItem = updateItems.LastOrDefault ();
if (updateItem == null) {
if (UpdateGlobHasMatchingPropertyValue (p, evalItem))
continue;
// There is no existing update item. A new one will be generated.
generateNewUpdateItem = true;
continue;
}
}
var globProp = globItem.Metadata.GetProperty (p.Name);
if (globProp != null && p.ValueType.Equals (globProp.Value, p.Value)) {
// The custom value of the item is defined in the glob item that creates it,
// so we are actually reverting a custom metadata value. The update item
// can probably be removed.
foreach (var upi in updateItems) {
upi.Metadata.RemoveProperty (p.Name);
if (!upi.Metadata.GetProperties ().Any ()) {
if (itemsToDelete == null)
itemsToDelete = new HashSet<MSBuildItem> ();
itemsToDelete.Add (upi);
}
}
continue;
}
updateItem.Metadata.SetValue (p.Name, p.Value);
if (itemsToDelete != null)
itemsToDelete.Remove (updateItem);
} else {
if (unchangedProperties == null)
unchangedProperties = new List<MSBuildProperty> ();
unchangedProperties.Add (p);
}
}
if (generateNewUpdateItem) {
// Convert the item into an update item
item.Update = item.Include;
item.Include = "";
if (unchangedProperties != null) {
// Remove properties that have not changed, so they don't have to
// be included in the update item.
foreach (var p in unchangedProperties)
item.Metadata.RemoveProperty (p.Name);
}
return ExpandedItemAction.AddUpdateItem;
}
if (itemsToDelete != null) {
foreach (var it in itemsToDelete)
it.ParentProject.RemoveItem (it);
}
foreach (var p in evalItem.Metadata.GetProperties ()) {
var p2 = item.Metadata.GetProperty (p.Name);
if (p2 == null) {
// The evaluated item has a property that the msbuild item doesn't have. If that metadata is
// set by the glob item, the only option is to exclude it from the glob. If the metadata was set by
// an update item, we have to remove that metadata definition
if (updateItems == null)
updateItems = FindUpdateItemsForItem (globItem, item.Include).ToList ();
foreach (var it in updateItems.Where (i => i.ParentNode != null)) {
if (it.Metadata.RemoveProperty (p.Name) && !it.Metadata.GetProperties ().Any ())
it.ParentProject.RemoveItem (it);
}
// If this metadata is defined in the glob item, the only option is to exclude the item from the glob.
if (globItem.Metadata.HasProperty (p.Name) && !UseDefaultMetadataForExcludedExpandedItems) {
// Get rid of all update items, not needed anymore since a full new item will be added
foreach (var it in updateItems) {
if (it.ParentNode != null)
it.ParentGroup.RemoveItem (it);
}
return ExpandedItemAction.Exclude;
}
}
}
if (!evalItem.Metadata.GetProperties ().Any () && !item.Metadata.GetProperties ().Any ()) {
updateItems = FindUpdateItemsForItem (globItem, item.Include).ToList ();
foreach (var it in updateItems) {
if (it.ParentNode != null)
it.ParentProject.RemoveItem (it);
}
}
return ExpandedItemAction.None;
}
IEnumerable<MSBuildItem> FindUpdateItemsForItem (MSBuildItem globItem, string include)
{
bool globItemFound = false;
foreach (var it in globItem.ParentProject.GetAllItems ()) {
if (!globItemFound)
globItemFound = (it == globItem);
else {
if (it.Update == include)
yield return it;
}
}
if (globItemFound && globItem.ParentProject != MSBuildProject) {
foreach (var it in MSBuildProject.GetAllItems ()) {
if (it.Update == include)
yield return it;
}
}
}
bool UpdateGlobHasMatchingPropertyValue (MSBuildProperty p, IMSBuildItemEvaluated evalItem)
{
MSBuildEvaluationContext context = null;
foreach (var updateItem in evalItem.SourceItems) {
if (!updateItem.IsUpdate)
continue;
var p2 = updateItem.Metadata.GetProperty (p.Name);
if (p2 != null) {
if (context == null) {
context = new MSBuildEvaluationContext ();
context.InitEvaluation (MSBuildProject);
}
string value = context.Evaluate (p.UnevaluatedValue);
return p.ValueType.Equals (p.Value, value);
}
}
return false;
}
bool ItemsAreEqual (IMSBuildItemEvaluated item1, IMSBuildItemEvaluated item2)
{
// Compare only metadata, since item name and include can't change
if (item1.SourceItem == null || item2.SourceItem == null || item1.Metadata.GetProperties ().Count () != item2.Metadata.GetProperties ().Count ())
return false;
foreach (var p1 in item1.Metadata.GetProperties ()) {
var p2 = item2.Metadata.GetProperty (p1.Name);
if (p2 == null || p2 == null)
return false;
if (p1.Value != p2.Value)
return false;
}
return true;
}
MSBuildEvaluationContext CreateEvaluationContext (ProjectItem item)
{
if (item is ProjectFile file) {
var context = new MSBuildEvaluationContext ();
context.SetItemContext (item.Include, file.FilePath, null);
return context;
}
return null;
}
IMSBuildItemEvaluated CreateFakeEvaluatedItem (MSBuildProject msproject, MSBuildItem item, string include, IEnumerable<MSBuildItem> sourceItems, MSBuildEvaluationContext context = null)
{
// Create the item
var eit = new MSBuildItemEvaluated (msproject, item.Name, item.Include, include);
// Copy the metadata
var md = new Dictionary<string, IMSBuildPropertyEvaluated> ();
var col = (MSBuildPropertyGroupEvaluated)eit.Metadata;
foreach (var p in item.Metadata.GetProperties ()) {
// Use evaluated value for value and unevaluated value. Otherwise
// an Update item will be generated for a '%(FileName)' property
// when GenerateItemDiff is called since it compares the value with
// the unevaluated value. If the project file is loaded from disk
// the unevaluated value would be the evaluated filename.
string evaluatedValue = context?.EvaluateString (p.Value) ?? p.Value;
md [p.Name] = new MSBuildPropertyEvaluated (msproject, p.Name, evaluatedValue, evaluatedValue);
}
((MSBuildPropertyGroupEvaluated)eit.Metadata).SetProperties (md);
if (sourceItems != null) {
foreach (var s in sourceItems)
eit.AddSourceItem (s);
} else
eit.AddSourceItem (item);
return eit;
}
string GetPrefixedInclude (string pathPrefix, string include)
{
if (pathPrefix != null && !include.StartsWith (pathPrefix))
return pathPrefix + include;
else
return include;
}
ConfigData FindPropertyGroup (List<ConfigData> configData, SolutionItemConfiguration config)
{
foreach (ConfigData data in configData) {
if (data.Config == config.Name && data.Platform == config.Platform)
return data;
}
return null;
}
ConfigData FindPropertyGroup (List<ConfigData> configData, ProjectRunConfiguration config)
{
foreach (ConfigData data in configData) {
if (data.Config == config.Name)
return data;
}
return null;
}
string BuildConfigCondition (string config, string platform)
{
if (platform.Length == 0)
platform = "AnyCPU";
return " '$(Configuration)|$(Platform)' == '" + config + "|" + platform + "' ";
}
string BuildRunConfigurationCondition (string name)
{
return " '$(RunConfiguration)' == '" + name + "' ";
}
bool IsMergeToProjectProperty (ItemProperty prop)
{
foreach (object at in prop.CustomAttributes) {
if (at is MergeToProjectAttribute)
return true;
}
return false;
}
/// <summary>
/// Reevaluates the MSBuild project
/// </summary>
/// <remarks>
/// Reevaluates the underlying msbuild project and updates the project information acording to the new items and properties.
/// </remarks>
public Task ReevaluateProject (ProgressMonitor monitor)
{
return ReevaluateProject (monitor, true);
}
/// <summary>
/// Reevaluates the MSBuild project and optionally resets the cached compile items
/// taken from CoreCompileDependsOn.
/// </summary>
Task ReevaluateProject (ProgressMonitor monitor, bool resetCachedCompileItems)
{
return BindTask (ct => Runtime.RunInMainThread (async () => {
using (await writeProjectLock.EnterAsync ()) {
if (modifiedInMemory) {
await Task.Run (() => WriteProject (monitor, inMemoryOnly: true));
modifiedInMemory = false;
}
var oldCapabilities = new HashSet<string> (projectCapabilities);
bool oldSupportsExecute = SupportsExecute ();
var solutionStartupProjectRunConfig = GetSolutionStartupProjectRunConfigurationForThisProject ();
try {
IsReevaluating = true;
// Re-evaluating may change MSBuild items and cause the custom tool generator to run. If a
// custom MSBuild target is run it may run before the project builder is refreshed so the
// target may not available. To avoid this shutdown the project builder before re-evaluating.
ShutdownProjectBuilder ();
// Reevaluate the msbuild project
monitorItemsModifiedDuringReevaluation = true;
await sourceProject.EvaluateAsync ();
monitorItemsModifiedDuringReevaluation = false;
// Loads minimal data required to instantiate extensions and prepare for project loading
InitBeforeProjectExtensionLoad ();
// Activate / deactivate extensions based on the new status
RefreshExtensions ();
await ProjectExtension.OnReevaluateProject (monitor);
} finally {
IsReevaluating = false;
monitorItemsModifiedDuringReevaluation = false;
itemsAddedDuringReevaluation = null;
itemsRemovedDuringReevaluation = null;
}
if (resetCachedCompileItems)
compileEvaluator.ResetCachedCompileItems ();
if (!oldCapabilities.SetEquals (projectCapabilities))
NotifyProjectCapabilitiesChanged ();
NotifyExecutionTargetsChanged (); // Maybe...
if (oldSupportsExecute != SupportsExecute ()) {
OnSupportsExecuteChanged (!oldSupportsExecute);
}
if (solutionStartupProjectRunConfig != null && !runConfigurations.Contains (solutionStartupProjectRunConfig)) {
// Need to refresh solution startup run configuration since the re-evaluation
// removed it from the project's run configurations but the solution still refers
// to the old project run configuration.
ParentSolution.RefreshStartupConfiguration ();
}
}
}));
}
/// <summary>
/// If the solution's startup run configuration is a run configuration for this
/// project then the project run configuration will be returned.
/// </summary>
SolutionItemRunConfiguration GetSolutionStartupProjectRunConfigurationForThisProject ()
{
var config = ParentSolution?.StartupConfiguration as SingleItemSolutionRunConfiguration;
if (config == null)
return null;
if (runConfigurations.Contains (config.RunConfiguration))
return config.RunConfiguration;
return null;
}
/// <summary>
/// If the project's SupportsExecute has changed then check if the solution's startup
/// configuration needs to be refreshed. If the solution has no startup item and
/// the project can now be executed then refresh the startup configuration since a
/// startup item can now be set for the solution. If the solution's startup item is
/// this project and can no longer be executed then refresh the startup configuration
/// so another startup item can be selected.
/// </summary>
void OnSupportsExecuteChanged (bool supportsExecute)
{
if (ParentSolution == null)
return;
if ((!supportsExecute && ParentSolution.StartupItem == this) ||
(supportsExecute && ParentSolution.StartupConfiguration == null)) {
ParentSolution.RefreshStartupConfiguration ();
}
}
protected virtual async Task OnReevaluateProject (ProgressMonitor monitor)
{
await LoadAsync (monitor);
}
public bool IsReevaluating { get; private set; }
/// <summary>
/// Checks if a file is included in any project item glob, and in this case it adds the require project files.
/// </summary>
/// <returns><c>true</c>, if any item was added, <c>false</c> otherwise.</returns>
/// <param name="file">File path</param>
/// <remarks>This method is useful to add items for a file that has been created in the project directory,
/// when the file is included in a glob defined by a project item.
/// Project items that define custom metadata will be ignored.</remarks>
public IEnumerable<ProjectItem> AddItemsForFileIncludedInGlob (FilePath file)
{
var include = MSBuildProjectService.ToMSBuildPath (ItemDirectory, file);
foreach (var it in sourceProject.FindGlobItemsIncludingFile (include).Where (it => it.Metadata.GetProperties ().Count () == 0)) {
var eit = CreateFakeEvaluatedItem (sourceProject, it, include, null);
var pi = CreateProjectItem (eit);
pi.Read (this, eit);
Items.Add (pi);
yield return pi;
}
}
public void AddImportIfMissing (string name, string condition)
{
importsAdded.Add (new DotNetProjectImport (name, condition));
}
public void RemoveImport (string name)
{
importsRemoved.Add (new DotNetProjectImport (name));
}
List <DotNetProjectImport> importsAdded = new List<DotNetProjectImport> ();
internal IList<DotNetProjectImport> ImportsAdded {
get { return importsAdded; }
}
List <DotNetProjectImport> importsRemoved = new List<DotNetProjectImport> ();
internal IList<DotNetProjectImport> ImportsRemoved {
get { return importsRemoved; }
}
bool useFileWatcher;
/// <summary>
/// When set to true with UseAdvancedGlobSupport also true then changes made to files inside the project externally
/// will be monitored and used to update the project.
/// </summary>
public bool UseFileWatcher {
get { return useFileWatcher; }
set {
if (useFileWatcher != value) {
useFileWatcher = value;
// File watcher will be created in OnEndLoad.
if (Loading) {
if (!useFileWatcher) {
DisposeFileWatcher ();
}
} else {
OnUseFileWatcherChanged ();
}
}
}
}
void OnUseFileWatcherChanged ()
{
if (useFileWatcher && UseAdvancedGlobSupport) {
CreateFileWatcher ();
} else {
DisposeFileWatcher ();
}
}
void InitializeFileWatcher ()
{
if (useFileWatcher) {
OnUseFileWatcherChanged ();
}
}
void CreateFileWatcher ()
{
DisposeFileWatcher ();
if (!Directory.Exists (BaseDirectory))
return;
// Use FileService.AsyncEvents for file created event since this does not run on the UI thread. This
// avoids blocking the UI thread when many files are created.
FileService.AsyncEvents.FileCreated += OnFileCreated;
// Use FileService.AsyncEvents for file deleted events to be consistent. Without this a deletion event
// would not update the Solution window until the IDE gets focus again.
FileService.AsyncEvents.FileRemoved += OnFileDeleted;
// Use FileService.AsyncEvents for file renamed events since generating the FileService.FileRenamed event
// would result in non SDK style projects renaming files in the project if changed externally.
FileService.AsyncEvents.FileRenamed += OnFileRenamed;
}
void DisposeFileWatcher ()
{
FileService.AsyncEvents.FileCreated -= OnFileCreated;
FileService.AsyncEvents.FileRemoved -= OnFileDeleted;
FileService.AsyncEvents.FileRenamed -= OnFileRenamed;
}
void OnFileRenamed (object sender, FileCopyEventArgs e)
{
foreach (FileEventInfo info in e) {
OnFileRenamed (info.SourceFile, info.TargetFile);
}
}
void OnFileRenamed (FilePath sourceFile, FilePath targetFile)
{
if (Runtime.IsMainThread)
return;
try {
if (Directory.Exists (targetFile)) {
OnDirectoryRenamedExternally (sourceFile, targetFile);
return;
}
} catch (Exception ex) {
LoggingService.LogError ("OnFileRenamed error.", ex);
}
Runtime.RunInMainThread (() => {
OnFileCreatedExternally (targetFile);
OnFileDeletedExternally (sourceFile);
});
}
void OnFileCreated (object sender, FileEventArgs e)
{
if (Runtime.IsMainThread)
return;
foreach (FileEventInfo info in e) {
OnFileCreated (info.FileName);
}
}
void OnFileCreated (FilePath filePath)
{
if (Runtime.IsMainThread)
return;
try {
if (Directory.Exists (filePath))
return;
if (filePath.FileName == ".DS_Store")
return;
// Ignore temporary files created when saving a file in the editor.
if (filePath.FileName.StartsWith (".#", StringComparison.OrdinalIgnoreCase))
return;
OnFileCreatedExternally (filePath);
} catch (Exception ex) {
LoggingService.LogError ("OnFileCreated error.", ex);
}
}
void OnFileDeleted (object sender, FileEventArgs e)
{
if (Runtime.IsMainThread)
return;
Runtime.RunInMainThread (() => {
foreach (FileEventInfo info in e) {
OnFileDeletedExternally (info.FileName);
}
});
}
/// <summary>
/// Move all project files in the old directory to the new directory.
/// </summary>
void OnDirectoryRenamedExternally (FilePath oldDirectory, FilePath newDirectory)
{
bool isOldDirectoryInsideProject = oldDirectory.IsChildPathOf (BaseDirectory);
bool isNewDirectoryInsideProject = newDirectory.IsChildPathOf (BaseDirectory);
if (!isOldDirectoryInsideProject && !isNewDirectoryInsideProject) {
// Ignore directories outside project directory.
return;
}
if (!isOldDirectoryInsideProject) {
OnDirectoryMovedIntoProject (newDirectory);
return;
}
if (isNewDirectoryInsideProject) {
Runtime.RunInMainThread (() => {
FileService.NotifyDirectoryRenamed (oldDirectory, newDirectory);
}).Ignore ();
return;
}
OnDirectoryMovedOutOfProject (oldDirectory);
}
void OnDirectoryMovedIntoProject (FilePath newDirectory)
{
foreach (string file in Directory.EnumerateFiles (newDirectory, "*", SearchOption.AllDirectories)) {
OnFileCreatedExternally (file);
}
}
void OnDirectoryMovedOutOfProject (FilePath oldDirectory)
{
// Directory moved outside project directory. Remove files from project.
var projectFilesInDirectory = Files.GetFilesInPath (oldDirectory);
if (!projectFilesInDirectory.Any ())
return;
Runtime.RunInMainThread (() => {
foreach (ProjectFile file in projectFilesInDirectory)
Files.Remove (file);
});
}
void OnFileCreatedExternally (FilePath fileName)
{
if (sourceProject == null) {
// sometimes this method is called after disposing this class.
// (i.e. when quitting MD or creating a new project.)
LoggingService.LogWarning ("File created externally not processed. {0}", fileName);
return;
}
// Check file is inside the project directory. The file globs would exclude the file anyway
// if the relative path starts with "..\" but checking here avoids checking the file globs.
if (!fileName.IsChildPathOf (BaseDirectory))
return;
if (Files.Any (file => file.FilePath == fileName)) {
// File exists in project. This can happen if the file was added
// in the IDE and not externally.
return;
}
string include = MSBuildProjectService.ToMSBuildPath (ItemDirectory, fileName);
var globItems = sourceProject.FindGlobItemsIncludingFile (include);
if (globItems == null) {
// If the MSBuildEngine no glob items can be found.
LoggingService.LogWarning ("File created externally not processed. {0}", fileName);
return;
}
if (!UseAdvancedGlobSupport)
globItems = globItems.Where (it => it.Metadata.GetProperties ().Count () == 0);
foreach (var it in globItems) {
var eit = CreateFakeEvaluatedItem (sourceProject, it, include, null);
var pi = CreateProjectItem (eit);
pi.Read (this, eit);
if (Runtime.IsMainThread) {
Items.Add (pi);
} else {
Runtime.RunInMainThread (() => {
// Double check the file has not been added on the UI thread by the IDE.
if (!Files.Any (file => file.FilePath == fileName)) {
Items.Add (pi);
}
}).Ignore ();
}
}
}
void OnFileDeletedExternally (string fileName)
{
if (File.Exists (fileName) || Directory.Exists (fileName)) {
// File has not been deleted. The delete event could have been due to
// the file being saved. Saving with TextFileUtility will result in
// FileService.SystemRename being called to move a temporary file
// to the file being saved which deletes and then creates the file.
return;
}
Files.Remove (fileName);
}
internal void NotifyFileRenamedInProject (ProjectFileRenamedEventArgs args)
{
NotifyModified ("Files");
OnFileRenamedInProject (args);
}
/// <summary>
/// Raises the FileRemovedFromProject event.
/// </summary>
protected virtual void OnFileRemovedFromProject (ProjectFileEventArgs e)
{
ProjectExtension.OnFileRemovedFromProject (e);
}
void DoOnFileRemovedFromProject (ProjectFileEventArgs e)
{
buildActions = null;
if (FileRemovedFromProject != null) {
FileRemovedFromProject (this, e);
}
}
/// <summary>
/// Raises the FileAddedToProject event.
/// </summary>
protected virtual void OnFileAddedToProject (ProjectFileEventArgs e)
{
ProjectExtension.OnFileAddedToProject (e);
}
void DoOnFileAddedToProject (ProjectFileEventArgs e)
{
buildActions = null;
if (FileAddedToProject != null) {
FileAddedToProject (this, e);
}
}
/// <summary>
/// Raises the FileChangedInProject event.
/// </summary>
protected virtual void OnFileChangedInProject (ProjectFileEventArgs e)
{
ProjectExtension.OnFileChangedInProject (e);
}
void DoOnFileChangedInProject (ProjectFileEventArgs e)
{
if (FileChangedInProject != null) {
FileChangedInProject (this, e);
}
}
/// <summary>
/// Raises the FilePropertyChangedInProject event.
/// </summary>
protected virtual void OnFilePropertyChangedInProject (ProjectFileEventArgs e)
{
ProjectExtension.OnFilePropertyChangedInProject (e);
}
void DoOnFilePropertyChangedInProject (ProjectFileEventArgs e)
{
buildActions = null;
if (FilePropertyChangedInProject != null) {
FilePropertyChangedInProject (this, e);
}
}
/// <summary>
/// Raises the FileRenamedInProject event.
/// </summary>
protected virtual void OnFileRenamedInProject (ProjectFileRenamedEventArgs e)
{
ProjectExtension.OnFileRenamedInProject (e);
}
void DoOnFileRenamedInProject (ProjectFileRenamedEventArgs e)
{
if (FileRenamedInProject != null) {
FileRenamedInProject (this, e);
}
}
public event EventHandler<ProjectItemEventArgs> ProjectItemAdded;
public event EventHandler<ProjectItemEventArgs> ProjectItemRemoved;
/// <summary>
/// Occurs when a file is removed from this project.
/// </summary>
public event ProjectFileEventHandler FileRemovedFromProject;
/// <summary>
/// Occurs when a file is added to this project.
/// </summary>
public event ProjectFileEventHandler FileAddedToProject;
/// <summary>
/// Occurs when a file of this project has been modified
/// </summary>
public event ProjectFileEventHandler FileChangedInProject;
/// <summary>
/// Occurs when a property of a file of this project has changed
/// </summary>
public event ProjectFileEventHandler FilePropertyChangedInProject;
/// <summary>
/// Occurs when a file of this project has been renamed
/// </summary>
public event ProjectFileRenamedEventHandler FileRenamedInProject;
class DefaultMSBuildProjectExtension: ProjectExtension
{
internal protected override bool SupportsFlavor (string guid)
{
return false;
}
internal protected override bool OnGetIsCompileable (string fileName)
{
return Project.OnGetIsCompileable (fileName);
}
internal protected override bool OnGetIsCompileBuildAction (string buildAction)
{
return Project.OnGetIsCompileBuildAction (buildAction);
}
internal protected override void OnGetTypeTags (HashSet<string> types)
{
Project.OnGetTypeTags (types);
}
internal protected override ProjectRunConfiguration OnCreateRunConfiguration (string name)
{
return Project.OnCreateRunConfiguration (name);
}
internal protected override void OnReadRunConfiguration (ProgressMonitor monitor, ProjectRunConfiguration runConfig, IPropertySet properties)
{
Project.OnReadRunConfiguration (monitor, runConfig, properties);
}
internal protected override void OnWriteRunConfiguration (ProgressMonitor monitor, ProjectRunConfiguration runConfig, IPropertySet properties)
{
Project.OnWriteRunConfiguration (monitor, runConfig, properties);
}
internal protected override TargetEvaluationContext OnConfigureTargetEvaluationContext (string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
return Project.OnConfigureTargetEvaluationContext (target, configuration, context);
}
internal protected override Task<TargetEvaluationResult> OnRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context)
{
return Project.DoRunTarget (monitor, target, configuration, context);
}
internal protected override bool OnGetSupportsTarget (string target)
{
return Project.OnGetSupportsTarget (target);
}
internal protected override string OnGetDefaultBuildAction (string fileName)
{
return Project.OnGetDefaultBuildAction (fileName);
}
internal protected override IEnumerable<string> OnGetStandardBuildActions ()
{
return Project.OnGetStandardBuildActions ();
}
internal protected override IList<string> OnGetCommonBuildActions ()
{
return Project.OnGetCommonBuildActions ();
}
internal protected override bool OnGetFileSupportsBuildAction (string fileName, string buildAction)
{
return Project.OnGetFileSupportsBuildAction (fileName, buildAction);
}
internal protected override ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item)
{
return Project.OnCreateProjectItem (item);
}
[Obsolete]
internal protected override void OnPopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration)
{
Project.DoPopulateSupportFileList (list, configuration);
}
[Obsolete]
internal protected override void OnPopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration)
{
Project.DoPopulateOutputFileList (list, configuration);
}
internal protected override FilePath OnGetOutputFileName (ConfigurationSelector configuration)
{
return Project.OnGetOutputFileName (configuration);
}
internal protected override string[] SupportedLanguages {
get {
return Project.OnGetSupportedLanguages ();
}
}
internal protected override void OnFileRemovedFromProject (ProjectFileEventArgs e)
{
Project.DoOnFileRemovedFromProject (e);
}
internal protected override void OnFileAddedToProject (ProjectFileEventArgs e)
{
Project.DoOnFileAddedToProject (e);
}
internal protected override void OnFileChangedInProject (ProjectFileEventArgs e)
{
Project.DoOnFileChangedInProject (e);
}
internal protected override void OnFilePropertyChangedInProject (ProjectFileEventArgs e)
{
Project.DoOnFilePropertyChangedInProject (e);
}
internal protected override void OnFileRenamedInProject (ProjectFileRenamedEventArgs e)
{
Project.DoOnFileRenamedInProject (e);
}
internal protected override void OnReadProjectHeader (ProgressMonitor monitor, MSBuildProject msproject)
{
Project.OnReadProjectHeader (monitor, msproject);
}
internal protected override void OnReadProject (ProgressMonitor monitor, MSBuildProject msproject)
{
Project.OnReadProject (monitor, msproject);
}
internal protected override void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject)
{
Project.OnWriteProject (monitor, msproject);
}
internal protected override void OnReadConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IPropertySet grp)
{
Project.OnReadConfiguration (monitor, config, grp);
}
internal protected override void OnWriteConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IPropertySet grp)
{
Project.OnWriteConfiguration (monitor, config, grp);
}
internal protected override Task OnReevaluateProject (ProgressMonitor monitor)
{
return Project.OnReevaluateProject (monitor);
}
internal protected override void OnGetDefaultImports (List<string> imports)
{
Project.OnGetDefaultImports (imports);
}
internal protected override void OnPrepareForEvaluation (MSBuildProject project)
{
Project.OnPrepareForEvaluation (project);
}
#pragma warning disable 672, 618
internal protected override bool OnFastCheckNeedsBuild (ConfigurationSelector configuration)
{
return Project.OnFastCheckNeedsBuild (configuration);
}
#pragma warning restore 672, 618
internal protected override bool OnFastCheckNeedsBuild (ConfigurationSelector configuration, TargetEvaluationContext context)
{
return Project.OnFastCheckNeedsBuild (configuration, context);
}
internal protected override Task<ImmutableArray<FilePath>> OnGetAnalyzerFiles (ProgressMonitor monitor, ConfigurationSelector configuration)
{
return Project.OnGetAnalyzerFiles (monitor, configuration);
}
internal protected override Task<ImmutableArray<ProjectFile>> OnGetSourceFiles (ProgressMonitor monitor, ConfigurationSelector configuration)
{
return Project.OnGetSourceFiles (monitor, configuration);
}
internal protected override bool OnGetSupportsImportedItem (IMSBuildItemEvaluated buildItem)
{
return Project.OnGetSupportsImportedItem (buildItem);
}
internal protected override void OnItemsAdded (IEnumerable<ProjectItem> objs)
{
Project.OnItemsAdded (objs);
}
internal protected override void OnItemsRemoved (IEnumerable<ProjectItem> objs)
{
Project.OnItemsRemoved (objs);
}
}
}
public delegate void ProjectEventHandler (Object sender, ProjectEventArgs e);
public class ProjectEventArgs : EventArgs
{
public ProjectEventArgs (Project project)
{
this.project = project;
}
private Project project;
public Project Project {
get { return project; }
}
}
class UnresolvedFileCollection
{
// Holds a dictionary of files that depend on other files, and for which the dependency
// has not yet been resolved. The key of the dictionary is the path to a parent
// file to be resolved, and the value can be a ProjectFile object or a List<ProjectFile>
// (This may happen if several files depend on the same parent file)
Dictionary<FilePath,object> unresolvedDeps = new Dictionary<FilePath, object> ();
public void Remove (ProjectFile file)
{
Remove (file, null);
}
public void Remove (ProjectFile file, FilePath dependencyPath)
{
if (dependencyPath.IsNullOrEmpty) {
if (string.IsNullOrEmpty (file.DependsOn))
return;
dependencyPath = file.DependencyPath;
}
object depFile;
if (unresolvedDeps.TryGetValue (dependencyPath, out depFile)) {
if ((depFile is ProjectFile) && ((ProjectFile)depFile == file))
unresolvedDeps.Remove (dependencyPath);
else if (depFile is List<ProjectFile>) {
var list = (List<ProjectFile>) depFile;
list.Remove (file);
if (list.Count == 1)
unresolvedDeps [dependencyPath] = list[0];
}
}
}
public void Add (ProjectFile file)
{
object depFile;
if (unresolvedDeps.TryGetValue (file.DependencyPath, out depFile)) {
if (depFile is ProjectFile) {
if ((ProjectFile)depFile != file) {
var list = new List<ProjectFile> ();
list.Add ((ProjectFile)depFile);
list.Add (file);
unresolvedDeps [file.DependencyPath] = list;
}
}
else if (depFile is List<ProjectFile>) {
var list = (List<ProjectFile>) depFile;
if (!list.Contains (file))
list.Add (file);
}
} else
unresolvedDeps [file.DependencyPath] = file;
}
public IEnumerable<ProjectFile> GetUnresolvedFilesForPath (FilePath filePath)
{
object depFile;
if (unresolvedDeps.TryGetValue (filePath, out depFile)) {
if (depFile is ProjectFile)
yield return (ProjectFile) depFile;
else {
foreach (var f in (List<ProjectFile>) depFile)
yield return f;
}
}
}
}
public static class ProjectExtensions
{
/// <summary>
/// Given a project, if the project implements the specified flavor type, this
/// method returns the flavor instance. It returns null if the project is null or
/// if the project doesn't implement the flavor.
/// </summary>
public static T AsFlavor<T> (this Project project) where T:ProjectExtension
{
return project != null ? project.GetFlavor<T> () : null;
}
}
}
|