summaryrefslogtreecommitdiff
path: root/gitlab/v4/objects/projects.py
blob: 3c26935d3089863fbac6978fada8c7ea5cea564c (plain)
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
from typing import Any, Callable, cast, Dict, List, Optional, TYPE_CHECKING, Union

import requests

from gitlab import cli, client
from gitlab import exceptions as exc
from gitlab import types, utils
from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import (
    CreateMixin,
    CRUDMixin,
    ListMixin,
    ObjectDeleteMixin,
    RefreshMixin,
    SaveMixin,
    UpdateMixin,
)

from .access_requests import ProjectAccessRequestManager  # noqa: F401
from .audit_events import ProjectAuditEventManager  # noqa: F401
from .badges import ProjectBadgeManager  # noqa: F401
from .boards import ProjectBoardManager  # noqa: F401
from .branches import ProjectBranchManager, ProjectProtectedBranchManager  # noqa: F401
from .clusters import ProjectClusterManager  # noqa: F401
from .commits import ProjectCommitManager  # noqa: F401
from .container_registry import ProjectRegistryRepositoryManager  # noqa: F401
from .custom_attributes import ProjectCustomAttributeManager  # noqa: F401
from .deploy_keys import ProjectKeyManager  # noqa: F401
from .deploy_tokens import ProjectDeployTokenManager  # noqa: F401
from .deployments import ProjectDeploymentManager  # noqa: F401
from .environments import ProjectEnvironmentManager  # noqa: F401
from .events import ProjectEventManager  # noqa: F401
from .export_import import ProjectExportManager, ProjectImportManager  # noqa: F401
from .files import ProjectFileManager  # noqa: F401
from .hooks import ProjectHookManager  # noqa: F401
from .issues import ProjectIssueManager  # noqa: F401
from .jobs import ProjectJobManager  # noqa: F401
from .labels import ProjectLabelManager  # noqa: F401
from .members import ProjectMemberAllManager, ProjectMemberManager  # noqa: F401
from .merge_request_approvals import (  # noqa: F401
    ProjectApprovalManager,
    ProjectApprovalRuleManager,
)
from .merge_requests import ProjectMergeRequestManager  # noqa: F401
from .merge_trains import ProjectMergeTrainManager  # noqa: F401
from .milestones import ProjectMilestoneManager  # noqa: F401
from .notes import ProjectNoteManager  # noqa: F401
from .notification_settings import ProjectNotificationSettingsManager  # noqa: F401
from .packages import GenericPackageManager, ProjectPackageManager  # noqa: F401
from .pages import ProjectPagesDomainManager  # noqa: F401
from .pipelines import (  # noqa: F401
    ProjectPipeline,
    ProjectPipelineManager,
    ProjectPipelineScheduleManager,
)
from .project_access_tokens import ProjectAccessTokenManager  # noqa: F401
from .push_rules import ProjectPushRulesManager  # noqa: F401
from .releases import ProjectReleaseManager  # noqa: F401
from .repositories import RepositoryMixin
from .runners import ProjectRunnerManager  # noqa: F401
from .services import ProjectServiceManager  # noqa: F401
from .snippets import ProjectSnippetManager  # noqa: F401
from .statistics import (  # noqa: F401
    ProjectAdditionalStatisticsManager,
    ProjectIssuesStatisticsManager,
)
from .tags import ProjectProtectedTagManager, ProjectTagManager  # noqa: F401
from .triggers import ProjectTriggerManager  # noqa: F401
from .users import ProjectUserManager  # noqa: F401
from .variables import ProjectVariableManager  # noqa: F401
from .wikis import ProjectWikiManager  # noqa: F401

__all__ = [
    "GroupProject",
    "GroupProjectManager",
    "Project",
    "ProjectManager",
    "ProjectFork",
    "ProjectForkManager",
    "ProjectRemoteMirror",
    "ProjectRemoteMirrorManager",
]


class GroupProject(RESTObject):
    pass


class GroupProjectManager(ListMixin, RESTManager):
    _path = "/groups/{group_id}/projects"
    _obj_cls = GroupProject
    _from_parent_attrs = {"group_id": "id"}
    _list_filters = (
        "archived",
        "visibility",
        "order_by",
        "sort",
        "search",
        "simple",
        "owned",
        "starred",
        "with_custom_attributes",
        "include_subgroups",
        "with_issues_enabled",
        "with_merge_requests_enabled",
        "with_shared",
        "min_access_level",
        "with_security_reports",
    )


class ProjectGroup(RESTObject):
    pass


class ProjectGroupManager(ListMixin, RESTManager):
    _path = "/projects/{project_id}/groups"
    _obj_cls = ProjectGroup
    _from_parent_attrs = {"project_id": "id"}
    _list_filters = (
        "search",
        "skip_groups",
        "with_shared",
        "shared_min_access_level",
        "shared_visible_only",
    )
    _types = {"skip_groups": types.ListAttribute}


class Project(RefreshMixin, SaveMixin, ObjectDeleteMixin, RepositoryMixin, RESTObject):
    _short_print_attr = "path"

    access_tokens: ProjectAccessTokenManager
    accessrequests: ProjectAccessRequestManager
    additionalstatistics: ProjectAdditionalStatisticsManager
    approvalrules: ProjectApprovalRuleManager
    approvals: ProjectApprovalManager
    audit_events: ProjectAuditEventManager
    badges: ProjectBadgeManager
    boards: ProjectBoardManager
    branches: ProjectBranchManager
    clusters: ProjectClusterManager
    commits: ProjectCommitManager
    customattributes: ProjectCustomAttributeManager
    deployments: ProjectDeploymentManager
    deploytokens: ProjectDeployTokenManager
    environments: ProjectEnvironmentManager
    events: ProjectEventManager
    exports: ProjectExportManager
    files: ProjectFileManager
    forks: "ProjectForkManager"
    generic_packages: GenericPackageManager
    groups: ProjectGroupManager
    hooks: ProjectHookManager
    imports: ProjectImportManager
    issues: ProjectIssueManager
    issues_statistics: ProjectIssuesStatisticsManager
    jobs: ProjectJobManager
    keys: ProjectKeyManager
    labels: ProjectLabelManager
    members: ProjectMemberManager
    members_all: ProjectMemberAllManager
    mergerequests: ProjectMergeRequestManager
    merge_trains: ProjectMergeTrainManager
    milestones: ProjectMilestoneManager
    notes: ProjectNoteManager
    notificationsettings: ProjectNotificationSettingsManager
    packages: ProjectPackageManager
    pagesdomains: ProjectPagesDomainManager
    pipelines: ProjectPipelineManager
    pipelineschedules: ProjectPipelineScheduleManager
    protectedbranches: ProjectProtectedBranchManager
    protectedtags: ProjectProtectedTagManager
    pushrules: ProjectPushRulesManager
    releases: ProjectReleaseManager
    remote_mirrors: "ProjectRemoteMirrorManager"
    repositories: ProjectRegistryRepositoryManager
    runners: ProjectRunnerManager
    services: ProjectServiceManager
    snippets: ProjectSnippetManager
    tags: ProjectTagManager
    triggers: ProjectTriggerManager
    users: ProjectUserManager
    variables: ProjectVariableManager
    wikis: ProjectWikiManager

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

        Args:
            forked_from_id: 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 = f"/projects/{self.get_id()}/fork/{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: Any) -> None:
        """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 = f"/projects/{self.get_id()}/fork"
        self.manager.gitlab.http_delete(path, **kwargs)

    @cli.register_custom_action("Project")
    @exc.on_http_error(exc.GitlabGetError)
    def languages(self, **kwargs: Any) -> Union[Dict[str, Any], requests.Response]:
        """Get languages used in the project with percentage value.

        Args:
            **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
        """
        path = f"/projects/{self.get_id()}/languages"
        return self.manager.gitlab.http_get(path, **kwargs)

    @cli.register_custom_action("Project")
    @exc.on_http_error(exc.GitlabCreateError)
    def star(self, **kwargs: Any) -> None:
        """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 = f"/projects/{self.get_id()}/star"
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(server_data, dict)
        self._update_attrs(server_data)

    @cli.register_custom_action("Project")
    @exc.on_http_error(exc.GitlabDeleteError)
    def unstar(self, **kwargs: Any) -> None:
        """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 = f"/projects/{self.get_id()}/unstar"
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(server_data, dict)
        self._update_attrs(server_data)

    @cli.register_custom_action("Project")
    @exc.on_http_error(exc.GitlabCreateError)
    def archive(self, **kwargs: Any) -> None:
        """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 = f"/projects/{self.get_id()}/archive"
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(server_data, dict)
        self._update_attrs(server_data)

    @cli.register_custom_action("Project")
    @exc.on_http_error(exc.GitlabDeleteError)
    def unarchive(self, **kwargs: Any) -> None:
        """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 = f"/projects/{self.get_id()}/unarchive"
        server_data = self.manager.gitlab.http_post(path, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(server_data, dict)
        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: int,
        group_access: int,
        expires_at: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        """Share the project with a group.

        Args:
            group_id: ID of the group.
            group_access: 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 = f"/projects/{self.get_id()}/share"
        data = {
            "group_id": group_id,
            "group_access": group_access,
            "expires_at": expires_at,
        }
        self.manager.gitlab.http_post(path, post_data=data, **kwargs)

    @cli.register_custom_action("Project", ("group_id",))
    @exc.on_http_error(exc.GitlabDeleteError)
    def unshare(self, group_id: int, **kwargs: Any) -> None:
        """Delete a shared project link within a group.

        Args:
            group_id: ID of the group.
            **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 = f"/projects/{self.get_id()}/share/{group_id}"
        self.manager.gitlab.http_delete(path, **kwargs)

    # variables not supported in CLI
    @cli.register_custom_action("Project", ("ref", "token"))
    @exc.on_http_error(exc.GitlabCreateError)
    def trigger_pipeline(
        self,
        ref: str,
        token: str,
        variables: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> ProjectPipeline:
        """Trigger a CI build.

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

        Args:
            ref: Commit to build; can be a branch name or a tag
            token: The trigger token
            variables: 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
        """
        variables = variables or {}
        path = f"/projects/{self.get_id()}/trigger/pipeline"
        post_data = {"ref": ref, "token": token, "variables": variables}
        attrs = self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(attrs, dict)
        return ProjectPipeline(self.pipelines, attrs)

    @cli.register_custom_action("Project")
    @exc.on_http_error(exc.GitlabHousekeepingError)
    def housekeeping(self, **kwargs: Any) -> None:
        """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 = f"/projects/{self.get_id()}/housekeeping"
        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: str,
        filedata: Optional[bytes] = None,
        filepath: Optional[str] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Upload the specified file into the project.

        .. note::

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

        Args:
            filename: The name of the file being uploaded
            filedata: The raw data of the file being uploaded
            filepath: 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:
            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 exc.GitlabUploadError("No file contents or path specified")

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

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

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

        if TYPE_CHECKING:
            assert isinstance(data, dict)
        return {"alt": data["alt"], "url": data["url"], "markdown": data["markdown"]}

    @cli.register_custom_action("Project", optional=("wiki",))
    @exc.on_http_error(exc.GitlabGetError)
    def snapshot(
        self,
        wiki: bool = False,
        streamed: bool = False,
        action: Optional[Callable] = None,
        chunk_size: int = 1024,
        **kwargs: Any,
    ) -> Optional[bytes]:
        """Return a snapshot of the repository.

        Args:
            wiki: If True return the wiki repository
            streamed: If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment.
            action: Callable responsible of dealing with chunk of
                data
            chunk_size: 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:
            The uncompressed tar archive of the repository
        """
        path = f"/projects/{self.get_id()}/snapshot"
        result = self.manager.gitlab.http_get(
            path, streamed=streamed, raw=True, **kwargs
        )
        if TYPE_CHECKING:
            assert isinstance(result, requests.Response)
        return utils.response_content(result, streamed, action, chunk_size)

    @cli.register_custom_action("Project", ("scope", "search"))
    @exc.on_http_error(exc.GitlabSearchError)
    def search(
        self, scope: str, search: str, **kwargs: Any
    ) -> Union[client.GitlabList, List[Dict[str, Any]]]:
        """Search the project resources matching the provided string.'

        Args:
            scope: Scope of the search
            search: Search string
            **kwargs: Extra options to send to the server (e.g. sudo)

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

        Returns:
            A list of dicts describing the resources found.
        """
        data = {"scope": scope, "search": search}
        path = f"/projects/{self.get_id()}/search"
        return self.manager.gitlab.http_list(path, query_data=data, **kwargs)

    @cli.register_custom_action("Project")
    @exc.on_http_error(exc.GitlabCreateError)
    def mirror_pull(self, **kwargs: Any) -> None:
        """Start the pull mirroring process for the 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 = f"/projects/{self.get_id()}/mirror/pull"
        self.manager.gitlab.http_post(path, **kwargs)

    @cli.register_custom_action("Project", ("to_namespace",))
    @exc.on_http_error(exc.GitlabTransferProjectError)
    def transfer_project(self, to_namespace: str, **kwargs: Any) -> None:
        """Transfer a project to the given namespace ID

        Args:
            to_namespace: ID or path of the namespace to transfer the
            project to
            **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 transferred
        """
        path = f"/projects/{self.id}/transfer"
        self.manager.gitlab.http_put(
            path, post_data={"namespace": to_namespace}, **kwargs
        )

    @cli.register_custom_action("Project", ("ref_name", "job"), ("job_token",))
    @exc.on_http_error(exc.GitlabGetError)
    def artifacts(
        self,
        ref_name: str,
        job: str,
        streamed: bool = False,
        action: Optional[Callable] = None,
        chunk_size: int = 1024,
        **kwargs: Any,
    ) -> Optional[bytes]:
        """Get the job artifacts archive from a specific tag or branch.

        Args:
            ref_name: Branch or tag name in repository. HEAD or SHA references
            are not supported.
            artifact_path: Path to a file inside the artifacts archive.
            job: The name of the job.
            job_token: Job token for multi-project pipeline triggers.
            streamed: If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action: Callable responsible of dealing with chunk of
                data
            chunk_size: 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:
            The artifacts if `streamed` is False, None otherwise.
        """
        path = f"/projects/{self.get_id()}/jobs/artifacts/{ref_name}/download"
        result = self.manager.gitlab.http_get(
            path, job=job, streamed=streamed, raw=True, **kwargs
        )
        if TYPE_CHECKING:
            assert isinstance(result, requests.Response)
        return utils.response_content(result, streamed, action, chunk_size)

    @cli.register_custom_action("Project", ("ref_name", "artifact_path", "job"))
    @exc.on_http_error(exc.GitlabGetError)
    def artifact(
        self,
        ref_name: str,
        artifact_path: str,
        job: str,
        streamed: bool = False,
        action: Optional[Callable] = None,
        chunk_size: int = 1024,
        **kwargs: Any,
    ) -> Optional[bytes]:
        """Download a single artifact file from a specific tag or branch from within the job’s artifacts archive.

        Args:
            ref_name: Branch or tag name in repository. HEAD or SHA references are not supported.
            artifact_path: Path to a file inside the artifacts archive.
            job: The name of the job.
            streamed: If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action: Callable responsible of dealing with chunk of
                data
            chunk_size: 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:
            The artifacts if `streamed` is False, None otherwise.
        """

        path = f"/projects/{self.get_id()}/jobs/artifacts/{ref_name}/raw/{artifact_path}?job={job}"
        result = self.manager.gitlab.http_get(
            path, streamed=streamed, raw=True, **kwargs
        )
        if TYPE_CHECKING:
            assert isinstance(result, requests.Response)
        return utils.response_content(result, streamed, action, chunk_size)


class ProjectManager(CRUDMixin, RESTManager):
    _path = "/projects"
    _obj_cls = Project
    # Please keep these _create_attrs in same order as they are at:
    # https://docs.gitlab.com/ee/api/projects.html#create-project
    _create_attrs = RequiredOptional(
        optional=(
            "name",
            "path",
            "allow_merge_on_skipped_pipeline",
            "analytics_access_level",
            "approvals_before_merge",
            "auto_cancel_pending_pipelines",
            "auto_devops_deploy_strategy",
            "auto_devops_enabled",
            "autoclose_referenced_issues",
            "avatar",
            "build_coverage_regex",
            "build_git_strategy",
            "build_timeout",
            "builds_access_level",
            "ci_config_path",
            "container_expiration_policy_attributes",
            "container_registry_enabled",
            "default_branch",
            "description",
            "emails_disabled",
            "external_authorization_classification_label",
            "forking_access_level",
            "group_with_project_templates_id",
            "import_url",
            "initialize_with_readme",
            "issues_access_level",
            "issues_enabled",
            "jobs_enabled",
            "lfs_enabled",
            "merge_method",
            "merge_requests_access_level",
            "merge_requests_enabled",
            "mirror_trigger_builds",
            "mirror",
            "namespace_id",
            "operations_access_level",
            "only_allow_merge_if_all_discussions_are_resolved",
            "only_allow_merge_if_pipeline_succeeds",
            "packages_enabled",
            "pages_access_level",
            "requirements_access_level",
            "printing_merge_request_link_enabled",
            "public_builds",
            "remove_source_branch_after_merge",
            "repository_access_level",
            "repository_storage",
            "request_access_enabled",
            "resolve_outdated_diff_discussions",
            "shared_runners_enabled",
            "show_default_award_emojis",
            "snippets_access_level",
            "snippets_enabled",
            "tag_list",
            "template_name",
            "template_project_id",
            "use_custom_template",
            "visibility",
            "wiki_access_level",
            "wiki_enabled",
        ),
    )
    # Please keep these _update_attrs in same order as they are at:
    # https://docs.gitlab.com/ee/api/projects.html#edit-project
    _update_attrs = RequiredOptional(
        optional=(
            "allow_merge_on_skipped_pipeline",
            "analytics_access_level",
            "approvals_before_merge",
            "auto_cancel_pending_pipelines",
            "auto_devops_deploy_strategy",
            "auto_devops_enabled",
            "autoclose_referenced_issues",
            "avatar",
            "build_coverage_regex",
            "build_git_strategy",
            "build_timeout",
            "builds_access_level",
            "ci_config_path",
            "ci_default_git_depth",
            "ci_forward_deployment_enabled",
            "container_expiration_policy_attributes",
            "container_registry_enabled",
            "default_branch",
            "description",
            "emails_disabled",
            "external_authorization_classification_label",
            "forking_access_level",
            "import_url",
            "issues_access_level",
            "issues_enabled",
            "jobs_enabled",
            "lfs_enabled",
            "merge_method",
            "merge_requests_access_level",
            "merge_requests_enabled",
            "mirror_overwrites_diverged_branches",
            "mirror_trigger_builds",
            "mirror_user_id",
            "mirror",
            "name",
            "operations_access_level",
            "only_allow_merge_if_all_discussions_are_resolved",
            "only_allow_merge_if_pipeline_succeeds",
            "only_mirror_protected_branches",
            "packages_enabled",
            "pages_access_level",
            "requirements_access_level",
            "restrict_user_defined_variables",
            "path",
            "public_builds",
            "remove_source_branch_after_merge",
            "repository_access_level",
            "repository_storage",
            "request_access_enabled",
            "resolve_outdated_diff_discussions",
            "service_desk_enabled",
            "shared_runners_enabled",
            "show_default_award_emojis",
            "snippets_access_level",
            "snippets_enabled",
            "suggestion_commit_message",
            "tag_list",
            "visibility",
            "wiki_access_level",
            "wiki_enabled",
            "issues_template",
            "merge_requests_template",
        ),
    )
    _list_filters = (
        "archived",
        "id_after",
        "id_before",
        "last_activity_after",
        "last_activity_before",
        "membership",
        "min_access_level",
        "order_by",
        "owned",
        "repository_checksum_failed",
        "repository_storage",
        "search_namespaces",
        "search",
        "simple",
        "sort",
        "starred",
        "statistics",
        "topic",
        "visibility",
        "wiki_checksum_failed",
        "with_custom_attributes",
        "with_issues_enabled",
        "with_merge_requests_enabled",
        "with_programming_language",
    )
    _types = {"avatar": types.ImageAttribute, "topic": types.ListAttribute}

    def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> Project:
        return cast(Project, super().get(id=id, lazy=lazy, **kwargs))

    def import_project(
        self,
        file: str,
        path: str,
        name: Optional[str] = None,
        namespace: Optional[str] = None,
        overwrite: bool = False,
        override_params: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Union[Dict[str, Any], requests.Response]:
        """Import a project from an archive file.

        Args:
            file: Data or file object containing the project
            path: Name and path for the new project
            namespace: The ID or path of the namespace that the project
                will be imported to
            overwrite: If True overwrite an existing project with the
                same path
            override_params: Set the specific settings for the project
            **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:
            A representation of the import status.
        """
        files = {"file": ("file.tar.gz", file, "application/octet-stream")}
        data = {"path": path, "overwrite": str(overwrite)}
        if override_params:
            for k, v in override_params.items():
                data[f"override_params[{k}]"] = v
        if name is not None:
            data["name"] = name
        if namespace:
            data["namespace"] = namespace
        return self.gitlab.http_post(
            "/projects/import", post_data=data, files=files, **kwargs
        )

    def import_bitbucket_server(
        self,
        bitbucket_server_url: str,
        bitbucket_server_username: str,
        personal_access_token: str,
        bitbucket_server_project: str,
        bitbucket_server_repo: str,
        new_name: Optional[str] = None,
        target_namespace: Optional[str] = None,
        **kwargs: Any,
    ) -> Union[Dict[str, Any], requests.Response]:
        """Import a project from BitBucket Server to Gitlab (schedule the import)

        This method will return when an import operation has been safely queued,
        or an error has occurred. After triggering an import, check the
        ``import_status`` of the newly created project to detect when the import
        operation has completed.

        .. note::
            This request may take longer than most other API requests.
            So this method will specify a 60 second default timeout if none is specified.
            A timeout can be specified via kwargs to override this functionality.

        Args:
            bitbucket_server_url: Bitbucket Server URL
            bitbucket_server_username: Bitbucket Server Username
            personal_access_token: Bitbucket Server personal access
                token/password
            bitbucket_server_project: Bitbucket Project Key
            bitbucket_server_repo: Bitbucket Repository Name
            new_name: New repository name (Optional)
            target_namespace: Namespace to import repository into.
                Supports subgroups like /namespace/subgroup (Optional)
            **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:
            A representation of the import status.

        Example:

        .. code-block:: python

            gl = gitlab.Gitlab_from_config()
            print("Triggering import")
            result = gl.projects.import_bitbucket_server(
                bitbucket_server_url="https://some.server.url",
                bitbucket_server_username="some_bitbucket_user",
                personal_access_token="my_password_or_access_token",
                bitbucket_server_project="my_project",
                bitbucket_server_repo="my_repo",
                new_name="gl_project_name",
                target_namespace="gl_project_path"
            )
            project = gl.projects.get(ret['id'])
            print("Waiting for import to complete")
            while project.import_status == u'started':
                time.sleep(1.0)
                project = gl.projects.get(project.id)
            print("BitBucket import complete")

        """
        data = {
            "bitbucket_server_url": bitbucket_server_url,
            "bitbucket_server_username": bitbucket_server_username,
            "personal_access_token": personal_access_token,
            "bitbucket_server_project": bitbucket_server_project,
            "bitbucket_server_repo": bitbucket_server_repo,
        }
        if new_name:
            data["new_name"] = new_name
        if target_namespace:
            data["target_namespace"] = target_namespace
        if (
            "timeout" not in kwargs
            or self.gitlab.timeout is None
            or self.gitlab.timeout < 60.0
        ):
            # Ensure that this HTTP request has a longer-than-usual default timeout
            # The base gitlab object tends to have a default that is <10 seconds,
            # and this is too short for this API command, typically.
            # On the order of 24 seconds has been measured on a typical gitlab instance.
            kwargs["timeout"] = 60.0
        result = self.gitlab.http_post(
            "/import/bitbucket_server", post_data=data, **kwargs
        )
        return result

    def import_github(
        self,
        personal_access_token: str,
        repo_id: int,
        target_namespace: str,
        new_name: Optional[str] = None,
        **kwargs: Any,
    ) -> Union[Dict[str, Any], requests.Response]:
        """Import a project from Github to Gitlab (schedule the import)

        This method will return when an import operation has been safely queued,
        or an error has occurred. After triggering an import, check the
        ``import_status`` of the newly created project to detect when the import
        operation has completed.

        .. note::
            This request may take longer than most other API requests.
            So this method will specify a 60 second default timeout if none is specified.
            A timeout can be specified via kwargs to override this functionality.

        Args:
            personal_access_token: GitHub personal access token
            repo_id: Github repository ID
            target_namespace: Namespace to import repo into
            new_name: New repo name (Optional)
            **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:
            A representation of the import status.

        Example:

        .. code-block:: python

            gl = gitlab.Gitlab_from_config()
            print("Triggering import")
            result = gl.projects.import_github(ACCESS_TOKEN,
                                               123456,
                                               "my-group/my-subgroup")
            project = gl.projects.get(ret['id'])
            print("Waiting for import to complete")
            while project.import_status == u'started':
                time.sleep(1.0)
                project = gl.projects.get(project.id)
            print("Github import complete")

        """
        data = {
            "personal_access_token": personal_access_token,
            "repo_id": repo_id,
            "target_namespace": target_namespace,
        }
        if new_name:
            data["new_name"] = new_name
        if (
            "timeout" not in kwargs
            or self.gitlab.timeout is None
            or self.gitlab.timeout < 60.0
        ):
            # Ensure that this HTTP request has a longer-than-usual default timeout
            # The base gitlab object tends to have a default that is <10 seconds,
            # and this is too short for this API command, typically.
            # On the order of 24 seconds has been measured on a typical gitlab instance.
            kwargs["timeout"] = 60.0
        result = self.gitlab.http_post("/import/github", post_data=data, **kwargs)
        return result


class ProjectFork(RESTObject):
    pass


class ProjectForkManager(CreateMixin, ListMixin, RESTManager):
    _path = "/projects/{project_id}/forks"
    _obj_cls = ProjectFork
    _from_parent_attrs = {"project_id": "id"}
    _list_filters = (
        "archived",
        "visibility",
        "order_by",
        "sort",
        "search",
        "simple",
        "owned",
        "membership",
        "starred",
        "statistics",
        "with_custom_attributes",
        "with_issues_enabled",
        "with_merge_requests_enabled",
    )
    _create_attrs = RequiredOptional(optional=("namespace",))

    def create(
        self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
    ) -> ProjectFork:
        """Creates a new object.

        Args:
            data: 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:
            A new instance of the managed object class build with
                the data sent by the server
        """
        if TYPE_CHECKING:
            assert self.path is not None
        path = self.path[:-1]  # drop the 's'
        return cast(ProjectFork, CreateMixin.create(self, data, path=path, **kwargs))


class ProjectRemoteMirror(SaveMixin, RESTObject):
    pass


class ProjectRemoteMirrorManager(ListMixin, CreateMixin, UpdateMixin, RESTManager):
    _path = "/projects/{project_id}/remote_mirrors"
    _obj_cls = ProjectRemoteMirror
    _from_parent_attrs = {"project_id": "id"}
    _create_attrs = RequiredOptional(
        required=("url",), optional=("enabled", "only_protected_branches")
    )
    _update_attrs = RequiredOptional(optional=("enabled", "only_protected_branches"))