This file is indexed.

/usr/lib/python3/dist-packages/gitlab/v4/objects.py is in python3-gitlab 1:1.3.0-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2017 Gauvain Pocentek <gauvain@pocentek.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function
from __future__ import absolute_import
import base64

from gitlab.base import *  # noqa
from gitlab import cli
from gitlab.exceptions import *  # noqa
from gitlab.mixins import *  # noqa
from gitlab import utils

VISIBILITY_PRIVATE = 'private'
VISIBILITY_INTERNAL = 'internal'
VISIBILITY_PUBLIC = 'public'

ACCESS_GUEST = 10
ACCESS_REPORTER = 20
ACCESS_DEVELOPER = 30
ACCESS_MASTER = 40
ACCESS_OWNER = 50


class SidekiqManager(RESTManager):
    """Manager for the Sidekiq methods.

    This manager doesn't actually manage objects but provides helper fonction
    for the sidekiq metrics API.
    """

    @cli.register_custom_action('SidekiqManager')
    @exc.on_http_error(exc.GitlabGetError)
    def queue_metrics(self, **kwargs):
        """Return the registred queues information.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the information couldn't be retrieved

        Returns:
            dict: Information about the Sidekiq queues
        """
        return self.gitlab.http_get('/sidekiq/queue_metrics', **kwargs)

    @cli.register_custom_action('SidekiqManager')
    @exc.on_http_error(exc.GitlabGetError)
    def process_metrics(self, **kwargs):
        """Return the registred sidekiq workers.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the information couldn't be retrieved

        Returns:
            dict: Information about the register Sidekiq worker
        """
        return self.gitlab.http_get('/sidekiq/process_metrics', **kwargs)

    @cli.register_custom_action('SidekiqManager')
    @exc.on_http_error(exc.GitlabGetError)
    def job_stats(self, **kwargs):
        """Return statistics about the jobs performed.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the information couldn't be retrieved

        Returns:
            dict: Statistics about the Sidekiq jobs performed
        """
        return self.gitlab.http_get('/sidekiq/job_stats', **kwargs)

    @cli.register_custom_action('SidekiqManager')
    @exc.on_http_error(exc.GitlabGetError)
    def compound_metrics(self, **kwargs):
        """Return all available metrics and statistics.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the information couldn't be retrieved

        Returns:
            dict: All available Sidekiq metrics and statistics
        """
        return self.gitlab.http_get('/sidekiq/compound_metrics', **kwargs)


class Event(RESTObject):
    _id_attr = None
    _short_print_attr = 'target_title'


class EventManager(ListMixin, RESTManager):
    _path = '/events'
    _obj_cls = Event
    _list_filters = ('action', 'target_type', 'before', 'after', 'sort')


class UserActivities(RESTObject):
    _id_attr = 'username'


class UserActivitiesManager(ListMixin, RESTManager):
    _path = '/user/activities'
    _obj_cls = UserActivities


class UserCustomAttribute(ObjectDeleteMixin, RESTObject):
    _id_attr = 'key'


class UserCustomAttributeManager(RetrieveMixin, SetMixin, DeleteMixin,
                                 RESTManager):
    _path = '/users/%(user_id)s/custom_attributes'
    _obj_cls = UserCustomAttribute
    _from_parent_attrs = {'user_id': 'id'}


class UserEmail(ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'email'


class UserEmailManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager):
    _path = '/users/%(user_id)s/emails'
    _obj_cls = UserEmail
    _from_parent_attrs = {'user_id': 'id'}
    _create_attrs = (('email', ), tuple())


class UserEvent(Event):
    pass


class UserEventManager(EventManager):
    _path = '/users/%(user_id)s/events'
    _obj_cls = UserEvent
    _from_parent_attrs = {'user_id': 'id'}


class UserGPGKey(ObjectDeleteMixin, RESTObject):
    pass


class UserGPGKeyManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager):
    _path = '/users/%(user_id)s/gpg_keys'
    _obj_cls = UserGPGKey
    _from_parent_attrs = {'user_id': 'id'}
    _create_attrs = (('key',), tuple())


class UserKey(ObjectDeleteMixin, RESTObject):
    pass


class UserKeyManager(GetFromListMixin, CreateMixin, DeleteMixin, RESTManager):
    _path = '/users/%(user_id)s/keys'
    _obj_cls = UserKey
    _from_parent_attrs = {'user_id': 'id'}
    _create_attrs = (('title', 'key'), tuple())


class UserImpersonationToken(ObjectDeleteMixin, RESTObject):
    pass


class UserImpersonationTokenManager(NoUpdateMixin, RESTManager):
    _path = '/users/%(user_id)s/impersonation_tokens'
    _obj_cls = UserImpersonationToken
    _from_parent_attrs = {'user_id': 'id'}
    _create_attrs = (('name', 'scopes'), ('expires_at',))
    _list_filters = ('state',)


class UserProject(RESTObject):
    pass


class UserProjectManager(ListMixin, CreateMixin, RESTManager):
    _path = '/projects/user/%(user_id)s'
    _obj_cls = UserProject
    _from_parent_attrs = {'user_id': 'id'}
    _create_attrs = (
        ('name', ),
        ('default_branch', 'issues_enabled', 'wall_enabled',
         'merge_requests_enabled', 'wiki_enabled', 'snippets_enabled',
         'public', 'visibility', 'description', 'builds_enabled',
         'public_builds', 'import_url', 'only_allow_merge_if_build_succeeds')
    )
    _list_filters = ('archived', 'visibility', 'order_by', 'sort', 'search',
                     'simple', 'owned', 'membership', 'starred', 'statistics',
                     'with_issues_enabled', 'with_merge_requests_enabled')

    def list(self, **kwargs):
        """Retrieve a list of objects.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Returns:
            list: The list of objects, or a generator if `as_list` is False

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the server cannot perform the request
        """

        path = '/users/%s/projects' % self._parent.id
        return ListMixin.list(self, path=path, **kwargs)


class User(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'username'
    _managers = (
        ('customattributes', 'UserCustomAttributeManager'),
        ('emails', 'UserEmailManager'),
        ('events', 'UserEventManager'),
        ('gpgkeys', 'UserGPGKeyManager'),
        ('impersonationtokens', 'UserImpersonationTokenManager'),
        ('keys', 'UserKeyManager'),
        ('projects', 'UserProjectManager'),
    )

    @cli.register_custom_action('User')
    @exc.on_http_error(exc.GitlabBlockError)
    def block(self, **kwargs):
        """Block the user.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabBlockError: If the user could not be blocked

        Returns:
            bool: Whether the user status has been changed
        """
        path = '/users/%s/block' % self.id
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        if server_data is True:
            self._attrs['state'] = 'blocked'
        return server_data

    @cli.register_custom_action('User')
    @exc.on_http_error(exc.GitlabUnblockError)
    def unblock(self, **kwargs):
        """Unblock the user.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUnblockError: If the user could not be unblocked

        Returns:
            bool: Whether the user status has been changed
        """
        path = '/users/%s/unblock' % self.id
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        if server_data is True:
            self._attrs['state'] = 'active'
        return server_data


class UserManager(CRUDMixin, RESTManager):
    _path = '/users'
    _obj_cls = User

    _list_filters = ('active', 'blocked', 'username', 'extern_uid', 'provider',
                     'external', 'search', 'custom_attributes')
    _create_attrs = (
        tuple(),
        ('email', 'username', 'name', 'password', 'reset_password', 'skype',
         'linkedin', 'twitter', 'projects_limit', 'extern_uid', 'provider',
         'bio', 'admin', 'can_create_group', 'website_url',
         'skip_confirmation', 'external', 'organization', 'location')
    )
    _update_attrs = (
        ('email', 'username', 'name'),
        ('password', 'skype', 'linkedin', 'twitter', 'projects_limit',
         'extern_uid', 'provider', 'bio', 'admin', 'can_create_group',
         'website_url', 'skip_confirmation', 'external', 'organization',
         'location')
    )

    def _sanitize_data(self, data, action):
        new_data = data.copy()
        if 'confirm' in data:
            new_data['confirm'] = str(new_data['confirm']).lower()
        return new_data


class CurrentUserEmail(ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'email'


class CurrentUserEmailManager(RetrieveMixin, CreateMixin, DeleteMixin,
                              RESTManager):
    _path = '/user/emails'
    _obj_cls = CurrentUserEmail
    _create_attrs = (('email', ), tuple())


class CurrentUserGPGKey(ObjectDeleteMixin, RESTObject):
    pass


class CurrentUserGPGKeyManager(RetrieveMixin, CreateMixin, DeleteMixin,
                               RESTManager):
    _path = '/user/gpg_keys'
    _obj_cls = CurrentUserGPGKey
    _create_attrs = (('key',), tuple())


class CurrentUserKey(ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'title'


class CurrentUserKeyManager(RetrieveMixin, CreateMixin, DeleteMixin,
                            RESTManager):
    _path = '/user/keys'
    _obj_cls = CurrentUserKey
    _create_attrs = (('title', 'key'), tuple())


class CurrentUser(RESTObject):
    _id_attr = None
    _short_print_attr = 'username'
    _managers = (
        ('emails', 'CurrentUserEmailManager'),
        ('gpgkeys', 'CurrentUserGPGKeyManager'),
        ('keys', 'CurrentUserKeyManager'),
    )


class CurrentUserManager(GetWithoutIdMixin, RESTManager):
    _path = '/user'
    _obj_cls = CurrentUser


class ApplicationSettings(SaveMixin, RESTObject):
    _id_attr = None


class ApplicationSettingsManager(GetWithoutIdMixin, UpdateMixin, RESTManager):
    _path = '/application/settings'
    _obj_cls = ApplicationSettings
    _update_attrs = (
        tuple(),
        ('after_sign_out_path', 'container_registry_token_expire_delay',
         'default_branch_protection', 'default_project_visibility',
         'default_projects_limit', 'default_snippet_visibility',
         'domain_blacklist', 'domain_blacklist_enabled', 'domain_whitelist',
         'enabled_git_access_protocol', 'gravatar_enabled', 'home_page_url',
         'max_attachment_size', 'repository_storage',
         'restricted_signup_domains', 'restricted_visibility_levels',
         'session_expire_delay', 'sign_in_text', 'signin_enabled',
         'signup_enabled', 'twitter_sharing_enabled',
         'user_oauth_applications')
    )

    def _sanitize_data(self, data, action):
        new_data = data.copy()
        if 'domain_whitelist' in data and data['domain_whitelist'] is None:
            new_data.pop('domain_whitelist')
        return new_data


class BroadcastMessage(SaveMixin, ObjectDeleteMixin, RESTObject):
    pass


class BroadcastMessageManager(CRUDMixin, RESTManager):
    _path = '/broadcast_messages'
    _obj_cls = BroadcastMessage

    _create_attrs = (('message', ), ('starts_at', 'ends_at', 'color', 'font'))
    _update_attrs = (tuple(), ('message', 'starts_at', 'ends_at', 'color',
                               'font'))


class DeployKey(RESTObject):
    pass


class DeployKeyManager(GetFromListMixin, RESTManager):
    _path = '/deploy_keys'
    _obj_cls = DeployKey


class NotificationSettings(SaveMixin, RESTObject):
    _id_attr = None


class NotificationSettingsManager(GetWithoutIdMixin, UpdateMixin, RESTManager):
    _path = '/notification_settings'
    _obj_cls = NotificationSettings

    _update_attrs = (
        tuple(),
        ('level', 'notification_email', 'new_note', 'new_issue',
         'reopen_issue', 'close_issue', 'reassign_issue', 'new_merge_request',
         'reopen_merge_request', 'close_merge_request',
         'reassign_merge_request', 'merge_merge_request')
    )


class Dockerfile(RESTObject):
    _id_attr = 'name'


class DockerfileManager(RetrieveMixin, RESTManager):
    _path = '/templates/dockerfiles'
    _obj_cls = Dockerfile


class Feature(RESTObject):
    _id_attr = 'name'


class FeatureManager(ListMixin, RESTManager):
    _path = '/features/'
    _obj_cls = Feature

    @exc.on_http_error(exc.GitlabSetError)
    def set(self, name, value, feature_group=None, user=None, **kwargs):
        """Create or update the object.

        Args:
            name (str): The value to set for the object
            value (bool/int): The value to set for the object
            feature_group (str): A feature group name
            user (str): A GitLab username
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabSetError: If an error occured

        Returns:
            obj: The created/updated attribute
        """
        path = '%s/%s' % (self.path, name.replace('/', '%2F'))
        data = {'value': value, 'feature_group': feature_group, 'user': user}
        server_data = self.gitlab.http_post(path, post_data=data, **kwargs)
        return self._obj_cls(self, server_data)


class Gitignore(RESTObject):
    _id_attr = 'name'


class GitignoreManager(RetrieveMixin, RESTManager):
    _path = '/templates/gitignores'
    _obj_cls = Gitignore


class Gitlabciyml(RESTObject):
    _id_attr = 'name'


class GitlabciymlManager(RetrieveMixin, RESTManager):
    _path = '/templates/gitlab_ci_ymls'
    _obj_cls = Gitlabciyml


class GroupAccessRequest(AccessRequestMixin, ObjectDeleteMixin, RESTObject):
    pass


class GroupAccessRequestManager(GetFromListMixin, CreateMixin, DeleteMixin,
                                RESTManager):
    _path = '/groups/%(group_id)s/access_requests'
    _obj_cls = GroupAccessRequest
    _from_parent_attrs = {'group_id': 'id'}


class GroupCustomAttribute(ObjectDeleteMixin, RESTObject):
    _id_attr = 'key'


class GroupCustomAttributeManager(RetrieveMixin, SetMixin, DeleteMixin,
                                  RESTManager):
    _path = '/groups/%(group_id)s/custom_attributes'
    _obj_cls = GroupCustomAttribute
    _from_parent_attrs = {'group_id': 'id'}


class GroupIssue(RESTObject):
    pass


class GroupIssueManager(GetFromListMixin, RESTManager):
    _path = '/groups/%(group_id)s/issues'
    _obj_cls = GroupIssue
    _from_parent_attrs = {'group_id': 'id'}
    _list_filters = ('state', 'labels', 'milestone', 'order_by', 'sort')


class GroupMember(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'username'


class GroupMemberManager(GetFromListMixin, CreateMixin, UpdateMixin,
                         DeleteMixin, RESTManager):
    _path = '/groups/%(group_id)s/members'
    _obj_cls = GroupMember
    _from_parent_attrs = {'group_id': 'id'}
    _create_attrs = (('access_level', 'user_id'), ('expires_at', ))
    _update_attrs = (('access_level', ), ('expires_at', ))


class GroupMergeRequest(RESTObject):
    pass


class GroupMergeRequestManager(RESTManager):
    pass


class GroupMilestone(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'title'

    @cli.register_custom_action('GroupMilestone')
    @exc.on_http_error(exc.GitlabListError)
    def issues(self, **kwargs):
        """List issues related to this milestone.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: The list of issues
        """

        path = '%s/%s/issues' % (self.manager.path, self.get_id())
        data_list = self.manager.gitlab.http_list(path, as_list=False,
                                                  **kwargs)
        manager = GroupIssueManager(self.manager.gitlab,
                                    parent=self.manager._parent)
        # FIXME(gpocentek): the computed manager path is not correct
        return RESTObjectList(manager, GroupIssue, data_list)

    @cli.register_custom_action('GroupMilestone')
    @exc.on_http_error(exc.GitlabListError)
    def merge_requests(self, **kwargs):
        """List the merge requests related to this milestone.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: The list of merge requests
        """
        path = '%s/%s/merge_requests' % (self.manager.path, self.get_id())
        data_list = self.manager.gitlab.http_list(path, as_list=False,
                                                  **kwargs)
        manager = GroupIssueManager(self.manager.gitlab,
                                    parent=self.manager._parent)
        # FIXME(gpocentek): the computed manager path is not correct
        return RESTObjectList(manager, GroupMergeRequest, data_list)


class GroupMilestoneManager(CRUDMixin, RESTManager):
    _path = '/groups/%(group_id)s/milestones'
    _obj_cls = GroupMilestone
    _from_parent_attrs = {'group_id': 'id'}
    _create_attrs = (('title', ), ('description', 'due_date', 'start_date'))
    _update_attrs = (tuple(), ('title', 'description', 'due_date',
                               'start_date', 'state_event'))
    _list_filters = ('iids', 'state', 'search')


class GroupNotificationSettings(NotificationSettings):
    pass


class GroupNotificationSettingsManager(NotificationSettingsManager):
    _path = '/groups/%(group_id)s/notification_settings'
    _obj_cls = GroupNotificationSettings
    _from_parent_attrs = {'group_id': 'id'}


class GroupProject(RESTObject):
    pass


class GroupProjectManager(GetFromListMixin, RESTManager):
    _path = '/groups/%(group_id)s/projects'
    _obj_cls = GroupProject
    _from_parent_attrs = {'group_id': 'id'}
    _list_filters = ('archived', 'visibility', 'order_by', 'sort', 'search',
                     'ci_enabled_first')


class GroupSubgroup(RESTObject):
    pass


class GroupSubgroupManager(GetFromListMixin, RESTManager):
    _path = '/groups/%(group_id)s/subgroups'
    _obj_cls = GroupSubgroup
    _from_parent_attrs = {'group_id': 'id'}
    _list_filters = ('skip_groups', 'all_available', 'search', 'order_by',
                     'sort', 'statistics', 'owned')


class GroupVariable(SaveMixin, ObjectDeleteMixin, RESTObject):
    _id_attr = 'key'


class GroupVariableManager(CRUDMixin, RESTManager):
    _path = '/groups/%(group_id)s/variables'
    _obj_cls = GroupVariable
    _from_parent_attrs = {'group_id': 'id'}
    _create_attrs = (('key', 'value'), ('protected',))
    _update_attrs = (('key', 'value'), ('protected',))


class Group(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'name'
    _managers = (
        ('accessrequests', 'GroupAccessRequestManager'),
        ('customattributes', 'GroupCustomAttributeManager'),
        ('issues', 'GroupIssueManager'),
        ('members', 'GroupMemberManager'),
        ('milestones', 'GroupMilestoneManager'),
        ('notificationsettings', 'GroupNotificationSettingsManager'),
        ('projects', 'GroupProjectManager'),
        ('subgroups', 'GroupSubgroupManager'),
        ('variables', 'GroupVariableManager'),
    )

    @cli.register_custom_action('Group', ('to_project_id', ))
    @exc.on_http_error(exc.GitlabTransferProjectError)
    def transfer_project(self, to_project_id, **kwargs):
        """Transfer a project to this group.

        Args:
            to_project_id (int): ID of the project to transfer
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabTransferProjectError: If the project could not be transfered
        """
        path = '/groups/%d/projects/%d' % (self.id, to_project_id)
        self.manager.gitlab.http_post(path, **kwargs)


class GroupManager(CRUDMixin, RESTManager):
    _path = '/groups'
    _obj_cls = Group
    _list_filters = ('skip_groups', 'all_available', 'search', 'order_by',
                     'sort', 'statistics', 'owned', 'custom_attributes')
    _create_attrs = (
        ('name', 'path'),
        ('description', 'visibility', 'parent_id', 'lfs_enabled',
         'request_access_enabled')
    )
    _update_attrs = (
        tuple(),
        ('name', 'path', 'description', 'visibility', 'lfs_enabled',
         'request_access_enabled')
    )


class Hook(ObjectDeleteMixin, RESTObject):
    _url = '/hooks'
    _short_print_attr = 'url'


class HookManager(NoUpdateMixin, RESTManager):
    _path = '/hooks'
    _obj_cls = Hook
    _create_attrs = (('url', ), tuple())


class Issue(RESTObject):
    _url = '/issues'
    _short_print_attr = 'title'


class IssueManager(GetFromListMixin, RESTManager):
    _path = '/issues'
    _obj_cls = Issue
    _list_filters = ('state', 'labels', 'order_by', 'sort')


class License(RESTObject):
    _id_attr = 'key'


class LicenseManager(RetrieveMixin, RESTManager):
    _path = '/templates/licenses'
    _obj_cls = License
    _list_filters = ('popular', )
    _optional_get_attrs = ('project', 'fullname')


class Snippet(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'title'

    @cli.register_custom_action('Snippet')
    @exc.on_http_error(exc.GitlabGetError)
    def content(self, streamed=False, action=None, chunk_size=1024, **kwargs):
        """Return the content of a snippet.

        Args:
            streamed (bool): If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment.
            action (callable): Callable responsible of dealing with chunk of
                data
            chunk_size (int): Size of each chunk
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the content could not be retrieved

        Returns:
            str: The snippet content
        """
        path = '/snippets/%s/raw' % self.get_id()
        result = self.manager.gitlab.http_get(path, streamed=streamed,
                                              **kwargs)
        return utils.response_content(result, streamed, action, chunk_size)


class SnippetManager(CRUDMixin, RESTManager):
    _path = '/snippets'
    _obj_cls = Snippet
    _create_attrs = (('title', 'file_name', 'content'),
                     ('lifetime', 'visibility'))
    _update_attrs = (tuple(),
                     ('title', 'file_name', 'content', 'visibility'))

    @cli.register_custom_action('SnippetManager')
    def public(self, **kwargs):
        """List all the public snippets.

        Args:
            all (bool): If True the returned object will be a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: A generator for the snippets list
        """
        return self.list(path='/snippets/public', **kwargs)


class Namespace(RESTObject):
    pass


class NamespaceManager(GetFromListMixin, RESTManager):
    _path = '/namespaces'
    _obj_cls = Namespace
    _list_filters = ('search', )


class PagesDomain(RESTObject):
    _id_attr = 'domain'


class PagesDomainManager(ListMixin, RESTManager):
    _path = '/pages/domains'
    _obj_cls = PagesDomain


class ProjectBoardList(SaveMixin, ObjectDeleteMixin, RESTObject):
    pass


class ProjectBoardListManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/boards/%(board_id)s/lists'
    _obj_cls = ProjectBoardList
    _from_parent_attrs = {'project_id': 'project_id',
                          'board_id': 'id'}
    _create_attrs = (('label_id', ), tuple())
    _update_attrs = (('position', ), tuple())


class ProjectBoard(RESTObject):
    _managers = (('lists', 'ProjectBoardListManager'), )


class ProjectBoardManager(GetFromListMixin, RESTManager):
    _path = '/projects/%(project_id)s/boards'
    _obj_cls = ProjectBoard
    _from_parent_attrs = {'project_id': 'id'}


class ProjectBranch(ObjectDeleteMixin, RESTObject):
    _id_attr = 'name'

    @cli.register_custom_action('ProjectBranch', tuple(),
                                ('developers_can_push',
                                 'developers_can_merge'))
    @exc.on_http_error(exc.GitlabProtectError)
    def protect(self, developers_can_push=False, developers_can_merge=False,
                **kwargs):
        """Protect the branch.

        Args:
            developers_can_push (bool): Set to True if developers are allowed
                                        to push to the branch
            developers_can_merge (bool): Set to True if developers are allowed
                                         to merge to the branch
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabProtectError: If the branch could not be protected
        """
        path = '%s/%s/protect' % (self.manager.path, self.get_id())
        post_data = {'developers_can_push': developers_can_push,
                     'developers_can_merge': developers_can_merge}
        self.manager.gitlab.http_put(path, post_data=post_data, **kwargs)
        self._attrs['protected'] = True

    @cli.register_custom_action('ProjectBranch')
    @exc.on_http_error(exc.GitlabProtectError)
    def unprotect(self, **kwargs):
        """Unprotect the branch.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabProtectError: If the branch could not be unprotected
        """
        path = '%s/%s/unprotect' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_put(path, **kwargs)
        self._attrs['protected'] = False


class ProjectBranchManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/repository/branches'
    _obj_cls = ProjectBranch
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('branch', 'ref'), tuple())


class ProjectCustomAttribute(ObjectDeleteMixin, RESTObject):
    _id_attr = 'key'


class ProjectCustomAttributeManager(RetrieveMixin, SetMixin, DeleteMixin,
                                    RESTManager):
    _path = '/projects/%(project_id)s/custom_attributes'
    _obj_cls = ProjectCustomAttribute
    _from_parent_attrs = {'project_id': 'id'}


class ProjectJob(RESTObject):
    @cli.register_custom_action('ProjectJob')
    @exc.on_http_error(exc.GitlabJobCancelError)
    def cancel(self, **kwargs):
        """Cancel the job.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabJobCancelError: If the job could not be canceled
        """
        path = '%s/%s/cancel' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

    @cli.register_custom_action('ProjectJob')
    @exc.on_http_error(exc.GitlabJobRetryError)
    def retry(self, **kwargs):
        """Retry the job.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabJobRetryError: If the job could not be retried
        """
        path = '%s/%s/retry' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

    @cli.register_custom_action('ProjectJob')
    @exc.on_http_error(exc.GitlabJobPlayError)
    def play(self, **kwargs):
        """Trigger a job explicitly.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabJobPlayError: If the job could not be triggered
        """
        path = '%s/%s/play' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

    @cli.register_custom_action('ProjectJob')
    @exc.on_http_error(exc.GitlabJobEraseError)
    def erase(self, **kwargs):
        """Erase the job (remove job artifacts and trace).

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabJobEraseError: If the job could not be erased
        """
        path = '%s/%s/erase' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

    @cli.register_custom_action('ProjectJob')
    @exc.on_http_error(exc.GitlabCreateError)
    def keep_artifacts(self, **kwargs):
        """Prevent artifacts from being deleted when expiration is set.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the request could not be performed
        """
        path = '%s/%s/artifacts/keep' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

    @cli.register_custom_action('ProjectJob')
    @exc.on_http_error(exc.GitlabGetError)
    def artifacts(self, streamed=False, action=None, chunk_size=1024,
                  **kwargs):
        """Get the job artifacts.

        Args:
            streamed (bool): If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action (callable): Callable responsible of dealing with chunk of
                data
            chunk_size (int): Size of each chunk
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the artifacts could not be retrieved

        Returns:
            str: The artifacts if `streamed` is False, None otherwise.
        """
        path = '%s/%s/artifacts' % (self.manager.path, self.get_id())
        result = self.manager.gitlab.http_get(path, streamed=streamed,
                                              **kwargs)
        return utils.response_content(result, streamed, action, chunk_size)

    @cli.register_custom_action('ProjectJob')
    @exc.on_http_error(exc.GitlabGetError)
    def trace(self, streamed=False, action=None, chunk_size=1024, **kwargs):
        """Get the job trace.

        Args:
            streamed (bool): If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action (callable): Callable responsible of dealing with chunk of
                data
            chunk_size (int): Size of each chunk
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the artifacts could not be retrieved

        Returns:
            str: The trace
        """
        path = '%s/%s/trace' % (self.manager.path, self.get_id())
        result = self.manager.gitlab.http_get(path, streamed=streamed,
                                              **kwargs)
        return utils.response_content(result, streamed, action, chunk_size)


class ProjectJobManager(RetrieveMixin, RESTManager):
    _path = '/projects/%(project_id)s/jobs'
    _obj_cls = ProjectJob
    _from_parent_attrs = {'project_id': 'id'}


class ProjectCommitStatus(RESTObject):
    pass


class ProjectCommitStatusManager(GetFromListMixin, CreateMixin, RESTManager):
    _path = ('/projects/%(project_id)s/repository/commits/%(commit_id)s'
             '/statuses')
    _obj_cls = ProjectCommitStatus
    _from_parent_attrs = {'project_id': 'project_id', 'commit_id': 'id'}
    _create_attrs = (('state', ),
                     ('description', 'name', 'context', 'ref', 'target_url',
                      'coverage'))

    def create(self, data, **kwargs):
        """Create a new object.

        Args:
            data (dict): Parameters to send to the server to create the
                         resource
            **kwargs: Extra data to send to the Gitlab server (e.g. sudo or
                      'ref_name', 'stage', 'name', 'all'.

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server cannot perform the request

        Returns:
            RESTObject: A new instance of the manage object class build with
                        the data sent by the server
        """
        path = '/projects/%(project_id)s/statuses/%(commit_id)s'
        computed_path = self._compute_path(path)
        return CreateMixin.create(self, data, path=computed_path, **kwargs)


class ProjectCommitComment(RESTObject):
    _id_attr = None


class ProjectCommitCommentManager(ListMixin, CreateMixin, RESTManager):
    _path = ('/projects/%(project_id)s/repository/commits/%(commit_id)s'
             '/comments')
    _obj_cls = ProjectCommitComment
    _from_parent_attrs = {'project_id': 'project_id', 'commit_id': 'id'}
    _create_attrs = (('note', ), ('path', 'line', 'line_type'))


class ProjectCommit(RESTObject):
    _short_print_attr = 'title'
    _managers = (
        ('comments', 'ProjectCommitCommentManager'),
        ('statuses', 'ProjectCommitStatusManager'),
    )

    @cli.register_custom_action('ProjectCommit')
    @exc.on_http_error(exc.GitlabGetError)
    def diff(self, **kwargs):
        """Generate the commit diff.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the diff could not be retrieved

        Returns:
            list: The changes done in this commit
        """
        path = '%s/%s/diff' % (self.manager.path, self.get_id())
        return self.manager.gitlab.http_get(path, **kwargs)

    @cli.register_custom_action('ProjectCommit', ('branch',))
    @exc.on_http_error(exc.GitlabCherryPickError)
    def cherry_pick(self, branch, **kwargs):
        """Cherry-pick a commit into a branch.

        Args:
            branch (str): Name of target branch
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCherryPickError: If the cherry-pick could not be performed
        """
        path = '%s/%s/cherry_pick' % (self.manager.path, self.get_id())
        post_data = {'branch': branch}
        self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)


class ProjectCommitManager(RetrieveMixin, CreateMixin, RESTManager):
    _path = '/projects/%(project_id)s/repository/commits'
    _obj_cls = ProjectCommit
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('branch', 'commit_message', 'actions'),
                     ('author_email', 'author_name'))


class ProjectEnvironment(SaveMixin, ObjectDeleteMixin, RESTObject):
    pass


class ProjectEnvironmentManager(GetFromListMixin, CreateMixin, UpdateMixin,
                                DeleteMixin, RESTManager):
    _path = '/projects/%(project_id)s/environments'
    _obj_cls = ProjectEnvironment
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('name', ), ('external_url', ))
    _update_attrs = (tuple(), ('name', 'external_url'))


class ProjectKey(ObjectDeleteMixin, RESTObject):
    pass


class ProjectKeyManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/deploy_keys'
    _obj_cls = ProjectKey
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('title', 'key'), tuple())

    @cli.register_custom_action('ProjectKeyManager', ('key_id',))
    @exc.on_http_error(exc.GitlabProjectDeployKeyError)
    def enable(self, key_id, **kwargs):
        """Enable a deploy key for a project.

        Args:
            key_id (int): The ID of the key to enable
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabProjectDeployKeyError: If the key could not be enabled
        """
        path = '%s/%s/enable' % (self.path, key_id)
        self.gitlab.http_post(path, **kwargs)


class ProjectEvent(Event):
    pass


class ProjectEventManager(EventManager):
    _path = '/projects/%(project_id)s/events'
    _obj_cls = ProjectEvent
    _from_parent_attrs = {'project_id': 'id'}


class ProjectFork(RESTObject):
    pass


class ProjectForkManager(CreateMixin, RESTManager):
    _path = '/projects/%(project_id)s/fork'
    _obj_cls = ProjectFork
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (tuple(), ('namespace', ))


class ProjectHook(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'url'


class ProjectHookManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/hooks'
    _obj_cls = ProjectHook
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (
        ('url', ),
        ('push_events', 'issues_events', 'note_events',
         'merge_requests_events', 'tag_push_events', 'build_events',
         'enable_ssl_verification', 'token', 'pipeline_events')
    )
    _update_attrs = (
        ('url', ),
        ('push_events', 'issues_events', 'note_events',
         'merge_requests_events', 'tag_push_events', 'build_events',
         'enable_ssl_verification', 'token', 'pipeline_events')
    )


class ProjectIssueAwardEmoji(ObjectDeleteMixin, RESTObject):
    pass


class ProjectIssueAwardEmojiManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/issues/%(issue_iid)s/award_emoji'
    _obj_cls = ProjectIssueAwardEmoji
    _from_parent_attrs = {'project_id': 'project_id', 'issue_iid': 'iid'}
    _create_attrs = (('name', ), tuple())


class ProjectIssueNoteAwardEmoji(ObjectDeleteMixin, RESTObject):
    pass


class ProjectIssueNoteAwardEmojiManager(NoUpdateMixin, RESTManager):
    _path = ('/projects/%(project_id)s/issues/%(issue_iid)s'
             '/notes/%(note_id)s/award_emoji')
    _obj_cls = ProjectIssueNoteAwardEmoji
    _from_parent_attrs = {'project_id': 'project_id',
                          'issue_iid': 'issue_iid',
                          'note_id': 'id'}
    _create_attrs = (('name', ), tuple())


class ProjectIssueNote(SaveMixin, ObjectDeleteMixin, RESTObject):
    _managers = (('awardemojis', 'ProjectIssueNoteAwardEmojiManager'),)


class ProjectIssueNoteManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/issues/%(issue_iid)s/notes'
    _obj_cls = ProjectIssueNote
    _from_parent_attrs = {'project_id': 'project_id', 'issue_iid': 'iid'}
    _create_attrs = (('body', ), ('created_at', ))
    _update_attrs = (('body', ), tuple())


class ProjectIssue(SubscribableMixin, TodoMixin, TimeTrackingMixin, SaveMixin,
                   ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'title'
    _id_attr = 'iid'
    _managers = (
        ('notes', 'ProjectIssueNoteManager'),
        ('awardemojis', 'ProjectIssueAwardEmojiManager'),
    )

    @cli.register_custom_action('ProjectIssue')
    @exc.on_http_error(exc.GitlabUpdateError)
    def user_agent_detail(self, **kwargs):
        """Get user agent detail.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the detail could not be retrieved
        """
        path = '%s/%s/user_agent_detail' % (self.manager.path, self.get_id())
        return self.manager.gitlab.http_get(path, **kwargs)

    @cli.register_custom_action('ProjectIssue', ('to_project_id',))
    @exc.on_http_error(exc.GitlabUpdateError)
    def move(self, to_project_id, **kwargs):
        """Move the issue to another project.

        Args:
            to_project_id(int): ID of the target project
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUpdateError: If the issue could not be moved
        """
        path = '%s/%s/move' % (self.manager.path, self.get_id())
        data = {'to_project_id': to_project_id}
        server_data = self.manager.gitlab.http_post(path, post_data=data,
                                                    **kwargs)
        self._update_attrs(server_data)


class ProjectIssueManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/issues/'
    _obj_cls = ProjectIssue
    _from_parent_attrs = {'project_id': 'id'}
    _list_filters = ('state', 'labels', 'milestone', 'order_by', 'sort')
    _create_attrs = (('title', ),
                     ('description', 'assignee_id', 'milestone_id', 'labels',
                      'created_at', 'due_date'))
    _update_attrs = (tuple(), ('title', 'description', 'assignee_id',
                               'milestone_id', 'labels', 'created_at',
                               'updated_at', 'state_event', 'due_date'))

    def _sanitize_data(self, data, action):
        new_data = data.copy()
        if 'labels' in data:
            new_data['labels'] = ','.join(data['labels'])
        return new_data


class ProjectMember(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'username'


class ProjectMemberManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/members'
    _obj_cls = ProjectMember
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('access_level', 'user_id'), ('expires_at', ))
    _update_attrs = (('access_level', ), ('expires_at', ))


class ProjectNote(RESTObject):
    pass


class ProjectNoteManager(RetrieveMixin, RESTManager):
    _path = '/projects/%(project_id)s/notes'
    _obj_cls = ProjectNote
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('body', ), tuple())


class ProjectNotificationSettings(NotificationSettings):
    pass


class ProjectNotificationSettingsManager(NotificationSettingsManager):
    _path = '/projects/%(project_id)s/notification_settings'
    _obj_cls = ProjectNotificationSettings
    _from_parent_attrs = {'project_id': 'id'}


class ProjectPagesDomain(SaveMixin, ObjectDeleteMixin, RESTObject):
    _id_attr = 'domain'


class ProjectPagesDomainManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/pages/domains'
    _obj_cls = ProjectPagesDomain
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('domain', ), ('certificate', 'key'))
    _update_attrs = (tuple(), ('certificate', 'key'))


class ProjectTag(ObjectDeleteMixin, RESTObject):
    _id_attr = 'name'
    _short_print_attr = 'name'

    @cli.register_custom_action('ProjectTag', ('description', ))
    def set_release_description(self, description, **kwargs):
        """Set the release notes on the tag.

        If the release doesn't exist yet, it will be created. If it already
        exists, its description will be updated.

        Args:
            description (str): Description of the release.
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server fails to create the release
            GitlabUpdateError: If the server fails to update the release
        """
        id = self.get_id().replace('/', '%2F')
        path = '%s/%s/release' % (self.manager.path, id)
        data = {'description': description}
        if self.release is None:
            try:
                server_data = self.manager.gitlab.http_post(path,
                                                            post_data=data,
                                                            **kwargs)
            except exc.GitlabHttpError as e:
                raise exc.GitlabCreateError(e.response_code, e.error_message)
        else:
            try:
                server_data = self.manager.gitlab.http_put(path,
                                                           post_data=data,
                                                           **kwargs)
            except exc.GitlabHttpError as e:
                raise exc.GitlabUpdateError(e.response_code, e.error_message)
        self.release = server_data


class ProjectTagManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/repository/tags'
    _obj_cls = ProjectTag
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('tag_name', 'ref'), ('message',))


class ProjectMergeRequestAwardEmoji(ObjectDeleteMixin, RESTObject):
    pass


class ProjectMergeRequestAwardEmojiManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/merge_requests/%(mr_iid)s/award_emoji'
    _obj_cls = ProjectMergeRequestAwardEmoji
    _from_parent_attrs = {'project_id': 'project_id', 'mr_iid': 'iid'}
    _create_attrs = (('name', ), tuple())


class ProjectMergeRequestDiff(RESTObject):
    pass


class ProjectMergeRequestDiffManager(RetrieveMixin, RESTManager):
    _path = '/projects/%(project_id)s/merge_requests/%(mr_iid)s/versions'
    _obj_cls = ProjectMergeRequestDiff
    _from_parent_attrs = {'project_id': 'project_id', 'mr_iid': 'iid'}


class ProjectMergeRequestNoteAwardEmoji(ObjectDeleteMixin, RESTObject):
    pass


class ProjectMergeRequestNoteAwardEmojiManager(NoUpdateMixin, RESTManager):
    _path = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s'
             '/notes/%(note_id)s/award_emoji')
    _obj_cls = ProjectMergeRequestNoteAwardEmoji
    _from_parent_attrs = {'project_id': 'project_id',
                          'mr_iid': 'issue_iid',
                          'note_id': 'id'}
    _create_attrs = (('name', ), tuple())


class ProjectMergeRequestNote(SaveMixin, ObjectDeleteMixin, RESTObject):
    _managers = (('awardemojis', 'ProjectMergeRequestNoteAwardEmojiManager'),)


class ProjectMergeRequestNoteManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/merge_requests/%(mr_iid)s/notes'
    _obj_cls = ProjectMergeRequestNote
    _from_parent_attrs = {'project_id': 'project_id', 'mr_iid': 'iid'}
    _create_attrs = (('body', ), tuple())
    _update_attrs = (('body', ), tuple())


class ProjectMergeRequest(SubscribableMixin, TodoMixin, TimeTrackingMixin,
                          SaveMixin, ObjectDeleteMixin, RESTObject):
    _id_attr = 'iid'

    _managers = (
        ('awardemojis', 'ProjectMergeRequestAwardEmojiManager'),
        ('diffs', 'ProjectMergeRequestDiffManager'),
        ('notes', 'ProjectMergeRequestNoteManager'),
    )

    @cli.register_custom_action('ProjectMergeRequest')
    @exc.on_http_error(exc.GitlabMROnBuildSuccessError)
    def cancel_merge_when_pipeline_succeeds(self, **kwargs):
        """Cancel merge when the pipeline succeeds.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabMROnBuildSuccessError: If the server could not handle the
                request
        """

        path = ('%s/%s/cancel_merge_when_pipeline_succeeds' %
                (self.manager.path, self.get_id()))
        server_data = self.manager.gitlab.http_put(path, **kwargs)
        self._update_attrs(server_data)

    @cli.register_custom_action('ProjectMergeRequest')
    @exc.on_http_error(exc.GitlabListError)
    def closes_issues(self, **kwargs):
        """List issues that will close on merge."

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: List of issues
        """
        path = '%s/%s/closes_issues' % (self.manager.path, self.get_id())
        data_list = self.manager.gitlab.http_list(path, as_list=False,
                                                  **kwargs)
        manager = ProjectIssueManager(self.manager.gitlab,
                                      parent=self.manager._parent)
        return RESTObjectList(manager, ProjectIssue, data_list)

    @cli.register_custom_action('ProjectMergeRequest')
    @exc.on_http_error(exc.GitlabListError)
    def commits(self, **kwargs):
        """List the merge request commits.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: The list of commits
        """

        path = '%s/%s/commits' % (self.manager.path, self.get_id())
        data_list = self.manager.gitlab.http_list(path, as_list=False,
                                                  **kwargs)
        manager = ProjectCommitManager(self.manager.gitlab,
                                       parent=self.manager._parent)
        return RESTObjectList(manager, ProjectCommit, data_list)

    @cli.register_custom_action('ProjectMergeRequest')
    @exc.on_http_error(exc.GitlabListError)
    def changes(self, **kwargs):
        """List the merge request changes.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: List of changes
        """
        path = '%s/%s/changes' % (self.manager.path, self.get_id())
        return self.manager.gitlab.http_get(path, **kwargs)

    @cli.register_custom_action('ProjectMergeRequest', tuple(),
                                ('merge_commit_message',
                                 'should_remove_source_branch',
                                 'merge_when_pipeline_succeeds'))
    @exc.on_http_error(exc.GitlabMRClosedError)
    def merge(self, merge_commit_message=None,
              should_remove_source_branch=False,
              merge_when_pipeline_succeeds=False,
              **kwargs):
        """Accept the merge request.

        Args:
            merge_commit_message (bool): Commit message
            should_remove_source_branch (bool): If True, removes the source
                                                branch
            merge_when_pipeline_succeeds (bool): Wait for the build to succeed,
                                                 then merge
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabMRClosedError: If the merge failed
        """
        path = '%s/%s/merge' % (self.manager.path, self.get_id())
        data = {}
        if merge_commit_message:
            data['merge_commit_message'] = merge_commit_message
        if should_remove_source_branch:
            data['should_remove_source_branch'] = True
        if merge_when_pipeline_succeeds:
            data['merge_when_pipeline_succeeds'] = True

        server_data = self.manager.gitlab.http_put(path, post_data=data,
                                                   **kwargs)
        self._update_attrs(server_data)

    @cli.register_custom_action('ProjectMergeRequest')
    @exc.on_http_error(exc.GitlabListError)
    def participants(self, **kwargs):
        """List the merge request participants.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: The list of participants
        """

        path = '%s/%s/participants' % (self.manager.path, self.get_id())
        return self.manager.gitlab.http_get(path, **kwargs)


class ProjectMergeRequestManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/merge_requests'
    _obj_cls = ProjectMergeRequest
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (
        ('source_branch', 'target_branch', 'title'),
        ('assignee_id', 'description', 'target_project_id', 'labels',
         'milestone_id', 'remove_source_branch')
    )
    _update_attrs = (tuple(), ('target_branch', 'assignee_id', 'title',
                               'description', 'state_event', 'labels',
                               'milestone_id'))
    _list_filters = ('iids', 'state', 'order_by', 'sort')

    def _sanitize_data(self, data, action):
        new_data = data.copy()
        if 'labels' in data:
            new_data['labels'] = ','.join(data['labels'])
        return new_data


class ProjectMilestone(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'title'

    @cli.register_custom_action('ProjectMilestone')
    @exc.on_http_error(exc.GitlabListError)
    def issues(self, **kwargs):
        """List issues related to this milestone.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: The list of issues
        """

        path = '%s/%s/issues' % (self.manager.path, self.get_id())
        data_list = self.manager.gitlab.http_list(path, as_list=False,
                                                  **kwargs)
        manager = ProjectIssueManager(self.manager.gitlab,
                                      parent=self.manager._parent)
        # FIXME(gpocentek): the computed manager path is not correct
        return RESTObjectList(manager, ProjectIssue, data_list)

    @cli.register_custom_action('ProjectMilestone')
    @exc.on_http_error(exc.GitlabListError)
    def merge_requests(self, **kwargs):
        """List the merge requests related to this milestone.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the list could not be retrieved

        Returns:
            RESTObjectList: The list of merge requests
        """
        path = '%s/%s/merge_requests' % (self.manager.path, self.get_id())
        data_list = self.manager.gitlab.http_list(path, as_list=False,
                                                  **kwargs)
        manager = ProjectMergeRequestManager(self.manager.gitlab,
                                             parent=self.manager._parent)
        # FIXME(gpocentek): the computed manager path is not correct
        return RESTObjectList(manager, ProjectMergeRequest, data_list)


class ProjectMilestoneManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/milestones'
    _obj_cls = ProjectMilestone
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('title', ), ('description', 'due_date', 'start_date',
                                   'state_event'))
    _update_attrs = (tuple(), ('title', 'description', 'due_date',
                               'start_date', 'state_event'))
    _list_filters = ('iids', 'state', 'search')


class ProjectLabel(SubscribableMixin, SaveMixin, ObjectDeleteMixin,
                   RESTObject):
    _id_attr = 'name'

    # Update without ID, but we need an ID to get from list.
    @exc.on_http_error(exc.GitlabUpdateError)
    def save(self, **kwargs):
        """Saves the changes made to the object to the server.

        The object is updated to match what the server returns.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct.
            GitlabUpdateError: If the server cannot perform the request.
        """
        updated_data = self._get_updated_data()

        # call the manager
        server_data = self.manager.update(None, updated_data, **kwargs)
        self._update_attrs(server_data)


class ProjectLabelManager(GetFromListMixin, CreateMixin, UpdateMixin,
                          DeleteMixin, RESTManager):
    _path = '/projects/%(project_id)s/labels'
    _obj_cls = ProjectLabel
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('name', 'color'), ('description', 'priority'))
    _update_attrs = (('name', ),
                     ('new_name', 'color', 'description', 'priority'))

    # Delete without ID.
    @exc.on_http_error(exc.GitlabDeleteError)
    def delete(self, name, **kwargs):
        """Delete a Label on the server.

        Args:
            name: The name of the label
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct.
            GitlabDeleteError: If the server cannot perform the request.
        """
        self.gitlab.http_delete(self.path, query_data={'name': name}, **kwargs)


class ProjectFile(SaveMixin, ObjectDeleteMixin, RESTObject):
    _id_attr = 'file_path'
    _short_print_attr = 'file_path'

    def decode(self):
        """Returns the decoded content of the file.

        Returns:
            (str): the decoded content.
        """
        return base64.b64decode(self.content)

    def save(self, branch, commit_message, **kwargs):
        """Save the changes made to the file to the server.

        The object is updated to match what the server returns.

        Args:
            branch (str): Branch in which the file will be updated
            commit_message (str): Message to send with the commit
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUpdateError: If the server cannot perform the request
        """
        self.branch = branch
        self.commit_message = commit_message
        self.file_path = self.file_path.replace('/', '%2F')
        super(ProjectFile, self).save(**kwargs)

    def delete(self, branch, commit_message, **kwargs):
        """Delete the file from the server.

        Args:
            branch (str): Branch from which the file will be removed
            commit_message (str): Commit message for the deletion
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server cannot perform the request
        """
        file_path = self.get_id().replace('/', '%2F')
        self.manager.delete(file_path, branch, commit_message, **kwargs)


class ProjectFileManager(GetMixin, CreateMixin, UpdateMixin, DeleteMixin,
                         RESTManager):
    _path = '/projects/%(project_id)s/repository/files'
    _obj_cls = ProjectFile
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('file_path', 'branch', 'content', 'commit_message'),
                     ('encoding', 'author_email', 'author_name'))
    _update_attrs = (('file_path', 'branch', 'content', 'commit_message'),
                     ('encoding', 'author_email', 'author_name'))

    @cli.register_custom_action('ProjectFileManager', ('file_path', 'ref'))
    def get(self, file_path, ref, **kwargs):
        """Retrieve a single file.

        Args:
            file_path (str): Path of the file to retrieve
            ref (str): Name of the branch, tag or commit
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the file could not be retrieved

        Returns:
            object: The generated RESTObject
        """
        file_path = file_path.replace('/', '%2F')
        return GetMixin.get(self, file_path, ref=ref, **kwargs)

    @cli.register_custom_action('ProjectFileManager',
                                ('file_path', 'branch', 'content',
                                 'commit_message'),
                                ('encoding', 'author_email', 'author_name'))
    @exc.on_http_error(exc.GitlabCreateError)
    def create(self, data, **kwargs):
        """Create a new object.

        Args:
            data (dict): parameters to send to the server to create the
                         resource
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Returns:
            RESTObject: a new instance of the managed object class built with
                the data sent by the server

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server cannot perform the request
        """

        self._check_missing_create_attrs(data)
        new_data = data.copy()
        file_path = new_data.pop('file_path').replace('/', '%2F')
        path = '%s/%s' % (self.path, file_path)
        server_data = self.gitlab.http_post(path, post_data=new_data, **kwargs)
        return self._obj_cls(self, server_data)

    @exc.on_http_error(exc.GitlabUpdateError)
    def update(self, file_path, new_data={}, **kwargs):
        """Update an object on the server.

        Args:
            id: ID of the object to update (can be None if not required)
            new_data: the update data for the object
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Returns:
            dict: The new object data (*not* a RESTObject)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUpdateError: If the server cannot perform the request
        """

        data = new_data.copy()
        file_path = file_path.replace('/', '%2F')
        data['file_path'] = file_path
        path = '%s/%s' % (self.path, file_path)
        self._check_missing_update_attrs(data)
        return self.gitlab.http_put(path, post_data=data, **kwargs)

    @cli.register_custom_action('ProjectFileManager', ('file_path', 'branch',
                                                       'commit_message'))
    @exc.on_http_error(exc.GitlabDeleteError)
    def delete(self, file_path, branch, commit_message, **kwargs):
        """Delete a file on the server.

        Args:
            file_path (str): Path of the file to remove
            branch (str): Branch from which the file will be removed
            commit_message (str): Commit message for the deletion
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server cannot perform the request
        """
        path = '%s/%s' % (self.path, file_path.replace('/', '%2F'))
        data = {'branch': branch, 'commit_message': commit_message}
        self.gitlab.http_delete(path, query_data=data, **kwargs)

    @cli.register_custom_action('ProjectFileManager', ('file_path', 'ref'))
    @exc.on_http_error(exc.GitlabGetError)
    def raw(self, file_path, ref, streamed=False, action=None, chunk_size=1024,
            **kwargs):
        """Return the content of a file for a commit.

        Args:
            ref (str): ID of the commit
            filepath (str): Path of the file to return
            streamed (bool): If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action (callable): Callable responsible of dealing with chunk of
                data
            chunk_size (int): Size of each chunk
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the file could not be retrieved

        Returns:
            str: The file content
        """
        file_path = file_path.replace('/', '%2F').replace('.', '%2E')
        path = '%s/%s/raw' % (self.path, file_path)
        query_data = {'ref': ref}
        result = self.gitlab.http_get(path, query_data=query_data,
                                      streamed=streamed, **kwargs)
        return utils.response_content(result, streamed, action, chunk_size)


class ProjectPipelineJob(ProjectJob):
    pass


class ProjectPipelineJobsManager(ListMixin, RESTManager):
    _path = '/projects/%(project_id)s/pipelines/%(pipeline_id)s/jobs'
    _obj_cls = ProjectPipelineJob
    _from_parent_attrs = {'project_id': 'project_id',
                          'pipeline_id': 'id'}
    _list_filters = ('scope',)


class ProjectPipeline(RESTObject):
    _managers = (('jobs', 'ProjectPipelineJobManager'), )

    @cli.register_custom_action('ProjectPipeline')
    @exc.on_http_error(exc.GitlabPipelineCancelError)
    def cancel(self, **kwargs):
        """Cancel the job.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabPipelineCancelError: If the request failed
        """
        path = '%s/%s/cancel' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

    @cli.register_custom_action('ProjectPipeline')
    @exc.on_http_error(exc.GitlabPipelineRetryError)
    def retry(self, **kwargs):
        """Retry the job.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabPipelineRetryError: If the request failed
        """
        path = '%s/%s/retry' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)


class ProjectPipelineManager(RetrieveMixin, CreateMixin, RESTManager):
    _path = '/projects/%(project_id)s/pipelines'
    _obj_cls = ProjectPipeline
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('ref', ), tuple())

    def create(self, data, **kwargs):
        """Creates a new object.

        Args:
            data (dict): Parameters to send to the server to create the
                         resource
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server cannot perform the request

        Returns:
            RESTObject: A new instance of the managed object class build with
                the data sent by the server
        """
        path = self.path[:-1]  # drop the 's'
        return CreateMixin.create(self, data, path=path, **kwargs)


class ProjectPipelineScheduleVariable(SaveMixin, ObjectDeleteMixin,
                                      RESTObject):
    _id_attr = 'key'


class ProjectPipelineScheduleVariableManager(CreateMixin, UpdateMixin,
                                             DeleteMixin, RESTManager):
    _path = ('/projects/%(project_id)s/pipeline_schedules/'
             '%(pipeline_schedule_id)s/variables')
    _obj_cls = ProjectPipelineScheduleVariable
    _from_parent_attrs = {'project_id': 'project_id',
                          'pipeline_schedule_id': 'id'}
    _create_attrs = (('key', 'value'), tuple())
    _update_attrs = (('key', 'value'), tuple())


class ProjectPipelineSchedule(SaveMixin, ObjectDeleteMixin, RESTObject):
    _managers = (('variables', 'ProjectPipelineScheduleVariableManager'),)

    @cli.register_custom_action('ProjectPipelineSchedule')
    @exc.on_http_error(exc.GitlabOwnershipError)
    def take_ownership(self, **kwargs):
        """Update the owner of a pipeline schedule.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabOwnershipError: If the request failed
        """
        path = '%s/%s/take_ownership' % (self.manager.path, self.get_id())
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        self._update_attrs(server_data)


class ProjectPipelineScheduleManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/pipeline_schedules'
    _obj_cls = ProjectPipelineSchedule
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('description', 'ref', 'cron'),
                     ('cron_timezone', 'active'))
    _update_attrs = (tuple(),
                     ('description', 'ref', 'cron', 'cron_timezone', 'active'))


class ProjectPipelineJob(ProjectJob):
    pass


class ProjectPipelineJobManager(GetFromListMixin, RESTManager):
    _path = '/projects/%(project_id)s/pipelines/%(pipeline_id)s/jobs'
    _obj_cls = ProjectPipelineJob
    _from_parent_attrs = {'project_id': 'project_id', 'pipeline_id': 'id'}


class ProjectSnippetNoteAwardEmoji(ObjectDeleteMixin, RESTObject):
    pass


class ProjectSnippetNoteAwardEmojiManager(NoUpdateMixin, RESTManager):
    _path = ('/projects/%(project_id)s/snippets/%(snippet_id)s'
             '/notes/%(note_id)s/award_emoji')
    _obj_cls = ProjectSnippetNoteAwardEmoji
    _from_parent_attrs = {'project_id': 'project_id',
                          'snippet_id': 'snippet_id',
                          'note_id': 'id'}
    _create_attrs = (('name', ), tuple())


class ProjectSnippetNote(SaveMixin, ObjectDeleteMixin, RESTObject):
    _managers = (('awardemojis', 'ProjectSnippetNoteAwardEmojiManager'),)


class ProjectSnippetNoteManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/snippets/%(snippet_id)s/notes'
    _obj_cls = ProjectSnippetNote
    _from_parent_attrs = {'project_id': 'project_id',
                          'snippet_id': 'id'}
    _create_attrs = (('body', ), tuple())
    _update_attrs = (('body', ), tuple())


class ProjectSnippetAwardEmoji(ObjectDeleteMixin, RESTObject):
    pass


class ProjectSnippetAwardEmojiManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/snippets/%(snippet_id)s/award_emoji'
    _obj_cls = ProjectSnippetAwardEmoji
    _from_parent_attrs = {'project_id': 'project_id', 'snippet_id': 'id'}
    _create_attrs = (('name', ), tuple())


class ProjectSnippet(SaveMixin, ObjectDeleteMixin, RESTObject):
    _url = '/projects/%(project_id)s/snippets'
    _short_print_attr = 'title'
    _managers = (
        ('awardemojis', 'ProjectSnippetAwardEmojiManager'),
        ('notes', 'ProjectSnippetNoteManager'),
    )

    @cli.register_custom_action('ProjectSnippet')
    @exc.on_http_error(exc.GitlabGetError)
    def content(self, streamed=False, action=None, chunk_size=1024, **kwargs):
        """Return the content of a snippet.

        Args:
            streamed (bool): If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment.
            action (callable): Callable responsible of dealing with chunk of
                data
            chunk_size (int): Size of each chunk
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the content could not be retrieved

        Returns:
            str: The snippet content
        """
        path = "%s/%s/raw" % (self.manager.path, self.get_id())
        result = self.manager.gitlab.http_get(path, streamed=streamed,
                                              **kwargs)
        return utils.response_content(result, streamed, action, chunk_size)


class ProjectSnippetManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/snippets'
    _obj_cls = ProjectSnippet
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('title', 'file_name', 'code'),
                     ('lifetime', 'visibility'))
    _update_attrs = (tuple(), ('title', 'file_name', 'code', 'visibility'))


class ProjectTrigger(SaveMixin, ObjectDeleteMixin, RESTObject):
    @cli.register_custom_action('ProjectTrigger')
    @exc.on_http_error(exc.GitlabOwnershipError)
    def take_ownership(self, **kwargs):
        """Update the owner of a trigger.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabOwnershipError: If the request failed
        """
        path = '%s/%s/take_ownership' % (self.manager.path, self.get_id())
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        self._update_attrs(server_data)


class ProjectTriggerManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/triggers'
    _obj_cls = ProjectTrigger
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('description', ), tuple())
    _update_attrs = (('description', ), tuple())


class ProjectUser(RESTObject):
    pass


class ProjectUserManager(ListMixin, RESTManager):
    _path = '/projects/%(project_id)s/users'
    _obj_cls = ProjectUser
    _from_parent_attrs = {'project_id': 'id'}
    _list_filters = ('search',)


class ProjectVariable(SaveMixin, ObjectDeleteMixin, RESTObject):
    _id_attr = 'key'


class ProjectVariableManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/variables'
    _obj_cls = ProjectVariable
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('key', 'value'), tuple())
    _update_attrs = (('key', 'value'), tuple())


class ProjectService(SaveMixin, ObjectDeleteMixin, RESTObject):
    pass


class ProjectServiceManager(GetMixin, UpdateMixin, DeleteMixin, RESTManager):
    _path = '/projects/%(project_id)s/services'
    _from_parent_attrs = {'project_id': 'id'}
    _obj_cls = ProjectService

    _service_attrs = {
        'asana': (('api_key', ), ('restrict_to_branch', )),
        'assembla': (('token', ), ('subdomain', )),
        'bamboo': (('bamboo_url', 'build_key', 'username', 'password'),
                   tuple()),
        'buildkite': (('token', 'project_url'), ('enable_ssl_verification', )),
        'campfire': (('token', ), ('subdomain', 'room')),
        'custom-issue-tracker': (('new_issue_url', 'issues_url',
                                  'project_url'),
                                 ('description', 'title')),
        'drone-ci': (('token', 'drone_url'), ('enable_ssl_verification', )),
        'emails-on-push': (('recipients', ), ('disable_diffs',
                                              'send_from_committer_email')),
        'builds-email': (('recipients', ), ('add_pusher',
                                            'notify_only_broken_builds')),
        'pipelines-email': (('recipients', ), ('add_pusher',
                                               'notify_only_broken_builds')),
        'external-wiki': (('external_wiki_url', ), tuple()),
        'flowdock': (('token', ), tuple()),
        'gemnasium': (('api_key', 'token', ), tuple()),
        'hipchat': (('token', ), ('color', 'notify', 'room', 'api_version',
                                  'server')),
        'irker': (('recipients', ), ('default_irc_uri', 'server_port',
                                     'server_host', 'colorize_messages')),
        'jira': (('url', 'project_key'),
                 ('new_issue_url', 'project_url', 'issues_url', 'api_url',
                  'description', 'username', 'password',
                  'jira_issue_transition_id')),
        'mattermost': (('webhook',), ('username', 'channel')),
        'pivotaltracker': (('token', ), tuple()),
        'pushover': (('api_key', 'user_key', 'priority'), ('device', 'sound')),
        'redmine': (('new_issue_url', 'project_url', 'issues_url'),
                    ('description', )),
        'slack': (('webhook', ), ('username', 'channel')),
        'teamcity': (('teamcity_url', 'build_type', 'username', 'password'),
                     tuple())
    }

    def get(self, id, **kwargs):
        """Retrieve a single object.

        Args:
            id (int or str): ID of the object to retrieve
            lazy (bool): If True, don't request the server, but create a
                         shallow object giving access to the managers. This is
                         useful if you want to avoid useless calls to the API.
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Returns:
            object: The generated RESTObject.

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the server cannot perform the request
        """
        obj = super(ProjectServiceManager, self).get(id, **kwargs)
        obj.id = id
        return obj

    def update(self, id=None, new_data={}, **kwargs):
        """Update an object on the server.

        Args:
            id: ID of the object to update (can be None if not required)
            new_data: the update data for the object
            **kwargs: Extra options to send to the Gitlab server (e.g. sudo)

        Returns:
            dict: The new object data (*not* a RESTObject)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUpdateError: If the server cannot perform the request
        """
        super(ProjectServiceManager, self).update(id, new_data, **kwargs)
        self.id = id

    @cli.register_custom_action('ProjectServiceManager')
    def available(self, **kwargs):
        """List the services known by python-gitlab.

        Returns:
            list (str): The list of service code names.
        """
        return list(self._service_attrs.keys())


class ProjectAccessRequest(AccessRequestMixin, ObjectDeleteMixin, RESTObject):
    pass


class ProjectAccessRequestManager(GetFromListMixin, CreateMixin, DeleteMixin,
                                  RESTManager):
    _path = '/projects/%(project_id)s/access_requests'
    _obj_cls = ProjectAccessRequest
    _from_parent_attrs = {'project_id': 'id'}


class ProjectDeployment(RESTObject):
    pass


class ProjectDeploymentManager(RetrieveMixin, RESTManager):
    _path = '/projects/%(project_id)s/deployments'
    _obj_cls = ProjectDeployment
    _from_parent_attrs = {'project_id': 'id'}


class ProjectProtectedBranch(ObjectDeleteMixin, RESTObject):
    _id_attr = 'name'


class ProjectProtectedBranchManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/protected_branches'
    _obj_cls = ProjectProtectedBranch
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('name', ), ('push_access_level', 'merge_access_level'))


class ProjectRunner(ObjectDeleteMixin, RESTObject):
    pass


class ProjectRunnerManager(NoUpdateMixin, RESTManager):
    _path = '/projects/%(project_id)s/runners'
    _obj_cls = ProjectRunner
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('runner_id', ), tuple())


class ProjectWiki(SaveMixin, ObjectDeleteMixin, RESTObject):
    _id_attr = 'slug'
    _short_print_attr = 'slug'


class ProjectWikiManager(CRUDMixin, RESTManager):
    _path = '/projects/%(project_id)s/wikis'
    _obj_cls = ProjectWiki
    _from_parent_attrs = {'project_id': 'id'}
    _create_attrs = (('title', 'content'), ('format', ))
    _update_attrs = (tuple(), ('title', 'content', 'format'))
    _list_filters = ('with_content', )


class Project(SaveMixin, ObjectDeleteMixin, RESTObject):
    _short_print_attr = 'path'
    _managers = (
        ('accessrequests', 'ProjectAccessRequestManager'),
        ('boards', 'ProjectBoardManager'),
        ('branches', 'ProjectBranchManager'),
        ('jobs', 'ProjectJobManager'),
        ('commits', 'ProjectCommitManager'),
        ('customattributes', 'ProjectCustomAttributeManager'),
        ('deployments', 'ProjectDeploymentManager'),
        ('environments', 'ProjectEnvironmentManager'),
        ('events', 'ProjectEventManager'),
        ('files', 'ProjectFileManager'),
        ('forks', 'ProjectForkManager'),
        ('hooks', 'ProjectHookManager'),
        ('keys', 'ProjectKeyManager'),
        ('issues', 'ProjectIssueManager'),
        ('labels', 'ProjectLabelManager'),
        ('members', 'ProjectMemberManager'),
        ('mergerequests', 'ProjectMergeRequestManager'),
        ('milestones', 'ProjectMilestoneManager'),
        ('notes', 'ProjectNoteManager'),
        ('notificationsettings', 'ProjectNotificationSettingsManager'),
        ('pagesdomains', 'ProjectPagesDomainManager'),
        ('pipelines', 'ProjectPipelineManager'),
        ('protectedbranches', 'ProjectProtectedBranchManager'),
        ('pipelineschedules', 'ProjectPipelineScheduleManager'),
        ('runners', 'ProjectRunnerManager'),
        ('services', 'ProjectServiceManager'),
        ('snippets', 'ProjectSnippetManager'),
        ('tags', 'ProjectTagManager'),
        ('users', 'ProjectUserManager'),
        ('triggers', 'ProjectTriggerManager'),
        ('variables', 'ProjectVariableManager'),
        ('wikis', 'ProjectWikiManager'),
    )

    @cli.register_custom_action('Project', tuple(), ('path', 'ref'))
    @exc.on_http_error(exc.GitlabGetError)
    def repository_tree(self, path='', ref='', **kwargs):
        """Return a list of files in the repository.

        Args:
            path (str): Path of the top folder (/ by default)
            ref (str): Reference to a commit or branch
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the server failed to perform the request

        Returns:
            list: The representation of the tree
        """
        gl_path = '/projects/%s/repository/tree' % self.get_id()
        query_data = {}
        if path:
            query_data['path'] = path
        if ref:
            query_data['ref'] = ref
        return self.manager.gitlab.http_list(gl_path, query_data=query_data,
                                             **kwargs)

    @cli.register_custom_action('Project', ('sha', ))
    @exc.on_http_error(exc.GitlabGetError)
    def repository_blob(self, sha, **kwargs):
        """Return a file by blob SHA.

        Args:
            sha(str): ID of the blob
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the server failed to perform the request

        Returns:
            dict: The blob content and metadata
        """

        path = '/projects/%s/repository/blobs/%s' % (self.get_id(), sha)
        return self.manager.gitlab.http_get(path, **kwargs)

    @cli.register_custom_action('Project', ('sha', ))
    @exc.on_http_error(exc.GitlabGetError)
    def repository_raw_blob(self, sha, streamed=False, action=None,
                            chunk_size=1024, **kwargs):
        """Return the raw file contents for a blob.

        Args:
            sha(str): ID of the blob
            streamed (bool): If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action (callable): Callable responsible of dealing with chunk of
                data
            chunk_size (int): Size of each chunk
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the server failed to perform the request

        Returns:
            str: The blob content if streamed is False, None otherwise
        """
        path = '/projects/%s/repository/blobs/%s/raw' % (self.get_id(), sha)
        result = self.manager.gitlab.http_get(path, streamed=streamed,
                                              **kwargs)
        return utils.response_content(result, streamed, action, chunk_size)

    @cli.register_custom_action('Project', ('from_', 'to'))
    @exc.on_http_error(exc.GitlabGetError)
    def repository_compare(self, from_, to, **kwargs):
        """Return a diff between two branches/commits.

        Args:
            from_(str): Source branch/SHA
            to(str): Destination branch/SHA
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the server failed to perform the request

        Returns:
            str: The diff
        """
        path = '/projects/%s/repository/compare' % self.get_id()
        query_data = {'from': from_, 'to': to}
        return self.manager.gitlab.http_get(path, query_data=query_data,
                                            **kwargs)

    @cli.register_custom_action('Project')
    @exc.on_http_error(exc.GitlabGetError)
    def repository_contributors(self, **kwargs):
        """Return a list of contributors for the project.

        Args:
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the server failed to perform the request

        Returns:
            list: The contributors
        """
        path = '/projects/%s/repository/contributors' % self.get_id()
        return self.manager.gitlab.http_list(path, **kwargs)

    @cli.register_custom_action('Project', tuple(), ('sha', ))
    @exc.on_http_error(exc.GitlabListError)
    def repository_archive(self, sha=None, streamed=False, action=None,
                           chunk_size=1024, **kwargs):
        """Return a tarball of the repository.

        Args:
            sha (str): ID of the commit (default branch by default)
            streamed (bool): If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action (callable): Callable responsible of dealing with chunk of
                data
            chunk_size (int): Size of each chunk
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the server failed to perform the request

        Returns:
            str: The binary data of the archive
        """
        path = '/projects/%s/repository/archive' % self.get_id()
        query_data = {}
        if sha:
            query_data['sha'] = sha
        result = self.manager.gitlab.http_get(path, query_data=query_data,
                                              streamed=streamed, **kwargs)
        return utils.response_content(result, streamed, action, chunk_size)

    @cli.register_custom_action('Project', ('forked_from_id', ))
    @exc.on_http_error(exc.GitlabCreateError)
    def create_fork_relation(self, forked_from_id, **kwargs):
        """Create a forked from/to relation between existing projects.

        Args:
            forked_from_id (int): The ID of the project that was forked from
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the relation could not be created
        """
        path = '/projects/%s/fork/%s' % (self.get_id(), forked_from_id)
        self.manager.gitlab.http_post(path, **kwargs)

    @cli.register_custom_action('Project')
    @exc.on_http_error(exc.GitlabDeleteError)
    def delete_fork_relation(self, **kwargs):
        """Delete a forked relation between existing projects.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server failed to perform the request
        """
        path = '/projects/%s/fork' % self.get_id()
        self.manager.gitlab.http_delete(path, **kwargs)

    @cli.register_custom_action('Project')
    @exc.on_http_error(exc.GitlabCreateError)
    def star(self, **kwargs):
        """Star a project.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server failed to perform the request
        """
        path = '/projects/%s/star' % self.get_id()
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        self._update_attrs(server_data)

    @cli.register_custom_action('Project')
    @exc.on_http_error(exc.GitlabDeleteError)
    def unstar(self, **kwargs):
        """Unstar a project.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server failed to perform the request
        """
        path = '/projects/%s/unstar' % self.get_id()
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        self._update_attrs(server_data)

    @cli.register_custom_action('Project')
    @exc.on_http_error(exc.GitlabCreateError)
    def archive(self, **kwargs):
        """Archive a project.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server failed to perform the request
        """
        path = '/projects/%s/archive' % self.get_id()
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        self._update_attrs(server_data)

    @cli.register_custom_action('Project')
    @exc.on_http_error(exc.GitlabDeleteError)
    def unarchive(self, **kwargs):
        """Unarchive a project.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server failed to perform the request
        """
        path = '/projects/%s/unarchive' % self.get_id()
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        self._update_attrs(server_data)

    @cli.register_custom_action('Project', ('group_id', 'group_access'),
                                ('expires_at', ))
    @exc.on_http_error(exc.GitlabCreateError)
    def share(self, group_id, group_access, expires_at=None, **kwargs):
        """Share the project with a group.

        Args:
            group_id (int): ID of the group.
            group_access (int): Access level for the group.
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server failed to perform the request
        """
        path = '/projects/%s/share' % self.get_id()
        data = {'group_id': group_id,
                'group_access': group_access,
                'expires_at': expires_at}
        self.manager.gitlab.http_post(path, post_data=data, **kwargs)

    # variables not supported in CLI
    @cli.register_custom_action('Project', ('ref', 'token'))
    @exc.on_http_error(exc.GitlabCreateError)
    def trigger_pipeline(self, ref, token, variables={}, **kwargs):
        """Trigger a CI build.

        See https://gitlab.com/help/ci/triggers/README.md#trigger-a-build

        Args:
            ref (str): Commit to build; can be a branch name or a tag
            token (str): The trigger token
            variables (dict): Variables passed to the build script
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server failed to perform the request
        """
        path = '/projects/%s/trigger/pipeline' % self.get_id()
        post_data = {'ref': ref, 'token': token, 'variables': variables}
        attrs = self.manager.gitlab.http_post(
            path, post_data=post_data, **kwargs)
        return ProjectPipeline(self.pipelines, attrs)

    @cli.register_custom_action('Project')
    @exc.on_http_error(exc.GitlabHousekeepingError)
    def housekeeping(self, **kwargs):
        """Start the housekeeping task.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabHousekeepingError: If the server failed to perform the
                                     request
        """
        path = '/projects/%s/housekeeping' % self.get_id()
        self.manager.gitlab.http_post(path, **kwargs)

    # see #56 - add file attachment features
    @cli.register_custom_action('Project', ('filename', 'filepath'))
    @exc.on_http_error(exc.GitlabUploadError)
    def upload(self, filename, filedata=None, filepath=None, **kwargs):
        """Upload the specified file into the project.

        .. note::

            Either ``filedata`` or ``filepath`` *MUST* be specified.

        Args:
            filename (str): The name of the file being uploaded
            filedata (bytes): The raw data of the file being uploaded
            filepath (str): The path to a local file to upload (optional)

        Raises:
            GitlabConnectionError: If the server cannot be reached
            GitlabUploadError: If the file upload fails
            GitlabUploadError: If ``filedata`` and ``filepath`` are not
                specified
            GitlabUploadError: If both ``filedata`` and ``filepath`` are
                specified

        Returns:
            dict: A ``dict`` with the keys:
                * ``alt`` - The alternate text for the upload
                * ``url`` - The direct url to the uploaded file
                * ``markdown`` - Markdown for the uploaded file
        """
        if filepath is None and filedata is None:
            raise GitlabUploadError("No file contents or path specified")

        if filedata is not None and filepath is not None:
            raise GitlabUploadError("File contents and file path specified")

        if filepath is not None:
            with open(filepath, "rb") as f:
                filedata = f.read()

        url = ('/projects/%(id)s/uploads' % {
            'id': self.id,
        })
        file_info = {
            'file': (filename, filedata),
        }
        data = self.manager.gitlab.http_post(url, files=file_info)

        return {
            "alt": data['alt'],
            "url": data['url'],
            "markdown": data['markdown']
        }


class ProjectManager(CRUDMixin, RESTManager):
    _path = '/projects'
    _obj_cls = Project
    _create_attrs = (
        ('name', ),
        ('path', 'namespace_id', 'description', 'issues_enabled',
         'merge_requests_enabled', 'jobs_enabled', 'wiki_enabled',
         'snippets_enabled', 'container_registry_enabled',
         'shared_runners_enabled', 'visibility', 'import_url', 'public_jobs',
         'only_allow_merge_if_build_succeeds',
         'only_allow_merge_if_all_discussions_are_resolved', 'lfs_enabled',
         'request_access_enabled', 'printing_merge_request_link_enabled')
    )
    _update_attrs = (
        tuple(),
        ('name', 'path', 'default_branch', 'description', 'issues_enabled',
         'merge_requests_enabled', 'jobs_enabled', 'wiki_enabled',
         'snippets_enabled', 'container_registry_enabled',
         'shared_runners_enabled', 'visibility', 'import_url', 'public_jobs',
         'only_allow_merge_if_build_succeeds',
         'only_allow_merge_if_all_discussions_are_resolved', 'lfs_enabled',
         'request_access_enabled', 'printing_merge_request_link_enabled')
    )
    _list_filters = ('search', 'owned', 'starred', 'archived', 'visibility',
                     'order_by', 'sort', 'simple', 'membership', 'statistics',
                     'with_issues_enabled', 'with_merge_requests_enabled',
                     'custom_attributes')


class Runner(SaveMixin, ObjectDeleteMixin, RESTObject):
    pass


class RunnerManager(RetrieveMixin, UpdateMixin, DeleteMixin, RESTManager):
    _path = '/runners'
    _obj_cls = Runner
    _update_attrs = (tuple(), ('description', 'active', 'tag_list'))
    _list_filters = ('scope', )

    @cli.register_custom_action('RunnerManager', tuple(), ('scope', ))
    @exc.on_http_error(exc.GitlabListError)
    def all(self, scope=None, **kwargs):
        """List all the runners.

        Args:
            scope (str): The scope of runners to show, one of: specific,
                shared, active, paused, online
            all (bool): If True, return all the items, without pagination
            per_page (int): Number of items to retrieve per request
            page (int): ID of the page to return (starts with page 1)
            as_list (bool): If set to False and no pagination option is
                defined, return a generator instead of a list
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError: If the server failed to perform the request

        Returns:
            list(Runner): a list of runners matching the scope.
        """
        path = '/runners/all'
        query_data = {}
        if scope is not None:
            query_data['scope'] = scope
        return self.gitlab.http_list(path, query_data, **kwargs)


class Todo(ObjectDeleteMixin, RESTObject):
    @cli.register_custom_action('Todo')
    @exc.on_http_error(exc.GitlabTodoError)
    def mark_as_done(self, **kwargs):
        """Mark the todo as done.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabTodoError: If the server failed to perform the request
        """
        path = '%s/%s/mark_as_done' % (self.manager.path, self.id)
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        self._update_attrs(server_data)


class TodoManager(GetFromListMixin, DeleteMixin, RESTManager):
    _path = '/todos'
    _obj_cls = Todo
    _list_filters = ('action', 'author_id', 'project_id', 'state', 'type')

    @cli.register_custom_action('TodoManager')
    @exc.on_http_error(exc.GitlabTodoError)
    def mark_all_as_done(self, **kwargs):
        """Mark all the todos as done.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabTodoError: If the server failed to perform the request

        Returns:
            int: The number of todos maked done
        """
        result = self.gitlab.http_post('/todos/mark_as_done', **kwargs)
        try:
            return int(result)
        except ValueError:
            return 0