a *Nau@sdZddlZddlmZmZmZmZmZmZm Z m Z ddl Z ddl Z ddl mZddlZddlZddlZddlmZdZGdddeZGd d d eZdS) zWrapper for the GitLab API.N)AnycastDictListOptionalTuple TYPE_CHECKINGUnion)MultipartEncoder)utilszupython-gitlab detected an http to https redirection. You must update your GitLab URL to use https:// to avoid issues.c@sdeZdZdZddddddddddddejjf eeeeeeee e efeeeeee eee j eeeeeeeddddZddd d Zedd d d ZeeefdddZeeefddddZeedddZeedddZeedddZedReeeeeddddZddddZeeefdddZej !ej j"eeee eefd d!d"Z#ej !ej j$dSee eeeed$d%d&Z%ej !ej j&eeeefd'd(d)Z'ej !ej j&eeeeefd*d+d,Z(ddd-d.Z)ddd/d0Z*eeefdd1d2Z+eed3d4d5Z,e j-dd6d7d8Z.dTeeeefeeeefe eeeeefee eeefe/fefd9d:d;Z0dUeeeeeefeeeefe e eeeefee e e eee j-d= d>d?Z1dVeeeeefe e ee eeefe j-fd@dAdBZ2dWeeeeefee ee dCeeeeffdDdEdFZ3dXeeeeefeeeefe eeeefee eeefe j-fdGdHdIZ4dYeeeeefeeeefe eeeefee eeefe j-fdGdJdKZ5eee j-dLdMdNZ6ej !ej j7eeee dCeeeeffdOdPdQZ8dS)ZGitlabaRepresents a GitLab server connection. Args: url (str): The URL of the GitLab server. private_token (str): The user private token oauth_token (str): An oauth token job_token (str): A CI job token ssl_verify (bool|str): Whether SSL certificates should be validated. If the value is a string, it is the path to a CA file used for certificate validation. timeout (float): Timeout to use for requests to the GitLab server. http_username (str): Username for HTTP authentication http_password (str): Password for HTTP authentication api_version (str): Gitlab API version to use (support for 4 only) pagination (str): Can be set to 'keyset' to use keyset pagination order_by (str): Set order_by globally user_agent (str): A custom user agent to use for making HTTP requests. NT4)url private_token oauth_token job_token ssl_verify http_username http_passwordtimeout api_versionsessionper_page paginationorder_by user_agentreturncCsNt| |_d|_d|_|d|_d|j| f|_||_d|i|_||_ ||_ ||_ ||_ ||_ ||_|| pxt|_| |_| |_| |_|jdvrtd|jdddl}|jj}||_|||_|||_|||_ |!||_"|#||_$|%||_&|'||_(|)||_*|+||_,|-||_.|/||_0|1||_2|3||_4|5||_6|7||_8|9||_:|;||_<|=||_>|?||_@|A||_B|C||_D|E||_F|G||_H|I||_J|K||_L|M||_N|O||_P|Q||_R|S||_T|U||_V|W||_X|Y||_Z|[||_\dS)N/z %s/api/v%sz User-Agentr gitlab.v%s.objectsnamer)]str _api_version_server_version_server_revisionrstrip _base_url_urlrheadersrrrrrr_set_auth_inforequestsSessionrrrrModuleNotFoundErrorgitlab.v4.objectsv4objects_objectsZBroadcastMessageManagerZbroadcastmessagesZDeployKeyManagerZ deploykeysZDeployTokenManagerZ deploytokensZGeoNodeManagerZgeonodesZGitlabciymlManagerZ gitlabciymlsZGitignoreManagerZ gitignoresZ GroupManagergroupsZ HookManagerhooksZ IssueManagerZissuesZIssuesStatisticsManagerZissues_statisticsZ KeyManagerkeysZLDAPGroupManagerZ ldapgroupsZLicenseManagerZlicensesZNamespaceManager namespacesZMergeRequestManagerZ mergerequestsZNotificationSettingsManagerZnotificationsettingsZProjectManagerZprojectsZ RunnerManagerZrunnersZApplicationSettingsManagersettingsZApplicationAppearanceManagerZ appearanceZSidekiqManagerZsidekiqZSnippetManagerZsnippetsZ UserManagerZusersZ TodoManagerZtodosZDockerfileManagerZ dockerfilesZ EventManagereventsZAuditEventManagerZ audit_eventsZFeatureManagerfeaturesZPagesDomainManagerZ pagesdomainsZUserActivitiesManagerZuser_activitiesZApplicationManagerZ applicationsZVariableManager variablesZPersonalAccessTokenManagerZpersonal_access_tokens)selfrrrrrrrrrrrrrrgitlabr0r<h/private/var/folders/js/6pj4vh5d4zd0k6bxv74qrbhr0000gr/T/pip-target-22xwyzbs/lib/python/gitlab/client.py__init__9sr                                     zGitlab.__init__rcCs|SNr<r:r<r<r= __enter__szGitlab.__enter__)argsrcGs|jdSr@)rclose)r:rCr<r<r=__exit__szGitlab.__exit__cCs|j}|d|S)Nr1)__dict__copypop)r:stater<r<r= __getstate__s  zGitlab.__getstate__)rIrcCs<|j||jdvr&td|jdddl}|jj|_dS)Nrrr r)rFupdater#r-r.r/r0r1)r:rIr;r<r<r= __setstate__s   zGitlab.__setstate__cCs|jS)zThe user-provided server URL.)r'rAr<r<r=rsz Gitlab.urlcCs|jS)zThe computed API base URL.)r(rAr<r<r=api_urlszGitlab.api_urlcCs|jS)zThe API version used (4 only).)r#rAr<r<r=rszGitlab.api_version) gitlab_id config_filesrcCsLtjj||d}||j|j|j|j|j|j|j |j |j |j |j |j|jd S)ayCreate a Gitlab connection from configuration files. Args: gitlab_id (str): ID of the configuration section. config_files list[str]: List of paths to configuration files. Returns: (gitlab.Gitlab): A Gitlab connection. Raises: gitlab.config.GitlabDataError: If the configuration is not correct. )rNrO) rrrrrrrrrrrr)r;configZGitlabConfigParserrrrrrrrrrrrrr)clsrNrOrPr<r<r= from_configs$zGitlab.from_configcCs|j||_dS)zPerforms an authentication using private token. The `user` attribute will hold a `gitlab.objects.CurrentUser` object on success. N)r1ZCurrentUserManagergetuserrAr<r<r=authsz Gitlab.authcCs||jdurdz:|d}t|tr6|d|_|d|_n d|_d|_Wntybd|_d|_Yn0tt|jtt|jfS)arReturns the version and revision of the gitlab server. Note that self.version and self.revision will be set on the gitlab object. Returns: tuple (str, str): The server version and server revision. ('unknown', 'unknwown') if the server doesn't perform as expected. Nz/versionversionrevisionunknown)r$http_get isinstancedictr% Exceptionrr")r:datar<r<r=rVs        zGitlab.version)contentkwargsrcKsDd|i}|jdd|i|}tr0t|tjr0J|ddk|dfS)aValidate a gitlab CI configuration. Args: content (txt): The .gitlab-ci.yml content **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabVerifyError: If the validation could not be done Returns: tuple: (True, []) if the file is valid, (False, errors(list)) otherwise r^/ci/lint post_datastatusZvaliderrors)r` http_postrrZr+Response)r:r^r_rar]r<r<r=lints z Gitlab.lintF)textgfmprojectr_rcKsJ||d}|dur||d<|jdd|i|}trBt|tjrBJ|dS)apRender an arbitrary Markdown document. Args: text (str): The markdown text to render gfm (bool): Render text using GitLab Flavored Markdown. Default is False project (str): Full path of a project used a context when `gfm` is True **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabMarkdownError: If the server cannot perform the request Returns: str: The HTML rendering of the markdown text. )rhriNrj /markdownrahtml)rkrd)r:rhrirjr_rar]r<r<r=markdown3s zGitlab.markdown)r_rcKs"|jdi|}t|tr|SiS)aoRetrieve information about the current license. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabGetError: If the server cannot perform the request Returns: dict: The current license information /license)rn)rYrZr[)r:r_resultr<r<r= get_licensePs zGitlab.get_license)licenser_rcKs4d|i}|jdd|i|}tr0t|tjr0J|S)a}Add a new license. Args: license (str): The license string **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabPostError: If the server cannot perform the request Returns: dict: The new license information rqrnra)rnrd)r:rqr_r]ror<r<r= set_licensecs zGitlab.set_licensecCsdd|j|j|jfD}t|dkr.td|jr:|jrF|jsN|jrNtd|jrb|jrbtdd|_|jr|j dd|j|jd<|j d d|jrd |j|jd<|j dd|j d d|jr|j dd|j dd|j|jd <|jrt j |j|j|_dS) NcSsg|] }|r|qSr<r<).0tokenr<r<r= ysz)Gitlab._set_auth_info..zEOnly one of private_token, oauth_token or job_token should be definedz6Both http_username and http_password should be definedzIOnly one of oauth authentication or http authentication should be defined Authorizationz PRIVATE-TOKENz JOB-TOKENz Bearer %s) rrrlen ValueErrorrr _http_authr)rHr+rU HTTPBasicAuth)r:tokensr<r<r=r*xsH     zGitlab._set_auth_infocCsRddl}ddlm}d|_|||j|d}||jd|_dS)Nr)HTTPConnectionrvzrequests.packages.urllib3T) logging http.clientr} debuglevel basicConfig getLoggersetLevelDEBUG propagate)r:r~r}Z requests_logr<r<r= enable_debugs   zGitlab.enable_debugcCs|j|j|j|jdS)N)r)rUrverify)r)rGrzrrrAr<r<r=_get_session_optss zGitlab._get_session_opts)pathrcCs*|ds|dr|Sd|j|fSdS)zReturns the full url from path. If path is already a url, return it unchanged. If it's a path, append it to the stored url. Returns: str: The full URL zhttp://https://z%s%sN) startswithr()r:rr<r<r= _build_urls zGitlab._build_url)rorcCsd|jr`|jdr`|jD]F}|jdvr(q|jjdkr6q|jdd}|r|drtj t qdS)Nzhttp:)i-i.GETZLocationr) historyr'r status_coderequestmethodr)rSr; exceptionsZ RedirectError REDIRECT_MSG)r:roitemlocationr<r<r=_check_redirectss   zGitlab._check_redirects)filesrarawrcCs|rn|duri}n,|D]"\}}t|trtt|||<q|d|d<|d|d<t|}d||jfS|r|rd|dfS|ddfS)NfileZavatarzapplication/octet-streamapplication/json)itemsrZboolr"intrSr content_type)r:rrarkvr]r<r<r=_prepare_send_datas    zGitlab._prepare_send_data ) verbr query_datararstreamedrrobey_rate_limitretry_transient_errors max_retriesr_rc  Ks>|pi}||} i}t||d| vrZt|| ddD]}|| vr>| |||<q>n t|| |}|d}|d}|dur|}||||\}}}||dd<tj|| f|||d|}|j |}t |j |_ |j |j i||d}d }|jj |fd|i|}||d |jkr:d krBnn|Sd |jkrT| sf|jd vr| r| dksz|| krd|d}d|jvrt|jd}|d7}t|q|j}z*|}dD]}||vr||}qWntttfyYn0|jdkr"tjj|j||jdtjj|j||jdqdS)aMake an HTTP request to the Gitlab server. Args: verb (str): The HTTP method to call ('get', 'post', 'put', 'delete') path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projecs') query_data (dict): Data to send as query parameters post_data (dict): Data to send in the body (will be converted to json by default) raw (bool): If True, do not convert post_data to json streamed (bool): Whether the data should be streamed files (dict): The files to send to the server timeout (float): The timeout, in seconds, for the request obey_rate_limit (bool): Whether to obey 429 Too Many Request responses. Defaults to True. retry_transient_errors (bool): Whether to retry after 500, 502, 503, or 504 responses. Defaults to False. max_retries (int): Max retries after 429 or transient errors, set to -1 to retry forever. Defaults to 10. **kwargs: Extra options to send to the server (e.g. sudo) Returns: A requests result object. Raises: GitlabHttpError: When the return code is not 2xx query_parameters)rpagerrNr)z Content-type)jsonr]paramsri,i)iiiig?z Retry-Afterrv)messageerrori)Z response_code error_messageZ response_body)rr Z copy_dictrrHrr+Requestrprepare_requestZ sanitized_urlrmerge_environment_settingssendrrr)rtimesleepr^rKeyErrorry TypeErrorr;rZGitlabAuthenticationErrorZGitlabHttpError)r:rrrrarrrrrrrr_rrargoptsrZ opts_timeoutrr]rreqZpreppedr6Z cur_retriesroZ wait_timerZ error_jsonrr<r<r= http_requestsv,              zGitlab.http_request)rrrrr_rc Ks|pi}|jd|f||d|}|jddkrz|sz|szz |WStyv}ztjjdd|WYd}~q~d}~00n|SdS)aMake a GET request to the Gitlab server. Args: path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projecs') query_data (dict): Data to send as query parameters streamed (bool): Whether the data should be streamed raw (bool): If True do not try to parse the output as json **kwargs: Extra options to send to the server (e.g. sudo) Returns: A requests result object is streamed is True or the content type is not json. The parsed json data otherwise. Raises: GitlabHttpError: When the return code is not 2xx GitlabParsingError: If the json data could not be parsed rS)rr Content-Typer"Failed to parse the server messagerN)rr)rr\r;rGitlabParsingError)r:rrrrr_roer<r<r=rYzs.  zGitlab.http_get GitlabList)rras_listr_rcKs|pi}|durdn|}|dd}||}|d}|dur`|dur`tt|||fi|S|sl|durtt|||fddi|St|||fi|S)aMake a GET request to the Gitlab server for list-oriented queries. Args: path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projects') query_data (dict): Data to send as query parameters **kwargs: Extra options to send to the server (e.g. sudo, page, per_page) Returns: list: A list of the objects returned by the server. If `as_list` is False and no pagination-related arguments (`page`, `per_page`, `all`) are defined then a GitlabList object (generator) is returned instead. This object will make API calls when needed to fetch the next items from the server. Raises: GitlabHttpError: When the return code is not 2xx GitlabParsingError: If the json data could not be parsed NTallFrget_next)rHrrSlistr)r:rrrr_get_allrrr<r<r= http_lists    zGitlab.http_list)rrrarrr_rc Ks|pi}|pi}|jd|f|||d|}z |jdddkrJ|WSWn4ty}ztjjdd|WYd}~n d}~00|S)aGMake a POST request to the Gitlab server. Args: path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projecs') query_data (dict): Data to send as query parameters post_data (dict): Data to send in the body (will be converted to json by default) raw (bool): If True, do not convert post_data to json files (dict): The files to send to the server **kwargs: Extra options to send to the server (e.g. sudo) Returns: The parsed json returned by the server if json is return, else the raw content Raises: GitlabHttpError: When the return code is not 2xx GitlabParsingError: If the json data could not be parsed post)rrarrNrrr)rr)rSrr\r;rr r:rrrarrr_rorr<r<r=res,zGitlab.http_postc Ksr|pi}|pi}|jd|f||||d|}z |WStyl}ztjjdd|WYd}~n d}~00dS)aMake a PUT request to the Gitlab server. Args: path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projecs') query_data (dict): Data to send as query parameters post_data (dict): Data to send in the body (will be converted to json by default) raw (bool): If True, do not convert post_data to json files (dict): The files to send to the server **kwargs: Extra options to send to the server (e.g. sudo) Returns: The parsed json returned by the server. Raises: GitlabHttpError: When the return code is not 2xx GitlabParsingError: If the json data could not be parsed put)rrarrrrN)rrr\r;rrrr<r<r=http_puts*  zGitlab.http_put)rr_rcKs|jd|fi|S)aMake a DELETE request to the Gitlab server. Args: path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projecs') **kwargs: Extra options to send to the server (e.g. sudo) Returns: The requests object. Raises: GitlabHttpError: When the return code is not 2xx delete)r)r:rr_r<r<r= http_delete7szGitlab.http_delete)scopesearchr_rcKs||d}|jdd|i|S)aSearch GitLab resources matching the provided string.' Args: scope (str): Scope of the search search (str): 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: GitlabList: A list of dicts describing the resources found. )rr/searchr)r)r)r:rrr_r]r<r<r=rGs z Gitlab.search)NN)FN)NNF) NNFFNNTFr)NFF)NN)NNFN)NNFN)9__name__ __module__ __qualname____doc__r;constZ USER_AGENTr"rr rfloatr+r,rr>rBrrErrJrLpropertyrrMr classmethodrrRrUrrVrZ on_http_errorZGitlabVerifyErrorrgZGitlabMarkdownErrorrmZGitlabLicenseErrorrprrr*rrrrfrr rrrYrrerrZGitlabSearchErrorrr<r<r<r=r %s8  z "  ,  "  1 2 4 /r c@seZdZdZdeeeeefeeddddZ d ee eeefedddd Z e e d d d Ze e e d d dZe e e d ddZe e d ddZe e d ddZe e d ddZdd ddZe d ddZeeefd ddZeeefd ddZdS)!rzGenerator representing a list of remote objects. The object handles the links returned by a query to the API, and will call the API again when needed. TN)glrrrr_rcKs>||_||_|j||fi|j||_|jdddS)Nr)_glrG_kwargs_query _get_nextrH)r:rrrrr_r<r<r=r>ds  zGitlabList.__init__)rrr_rc Ks|pi}|jjd|fd|i|}z<|j}|r<|dd}ntj|jddd}||_Wntyvd|_Yn0|j d|_ |j d|_ |j d |_ |j d |_ |j d |_|j d |_z||_Wn6ty}ztjjd d|WYd}~n d}~00d|_dS)NrSrnextrlinksrzX-Pagez X-Prev-Pagez X-Next-Pagez X-Per-Pagez X-Total-PageszX-Totalrr)rrrr+r parse_header_linksr) _next_urlrrS _current_page _prev_page _next_page _per_page _total_pages_totalr_datar\r;rr_current)r:rrr_rorZnext_urlrr<r<r=rws>   zGitlabList._queryr?cCstr|jdusJt|jS)zThe current page number.N)rrrrAr<r<r= current_pageszGitlabList.current_pagecCs|jrt|jSdS)zSThe previous page number. If None, the current page is the first. N)rrrAr<r<r= prev_pageszGitlabList.prev_pagecCs|jrt|jSdS)zNThe next page number. If None, the current page is the last. N)rrrAr<r<r= next_pageszGitlabList.next_pagecCstr|jdusJt|jS)zThe number of items per page.N)rrrrAr<r<r=rszGitlabList.per_pagecCstr|jdusJt|jS)zThe total number of pages.N)rrrrAr<r<r= total_pagesszGitlabList.total_pagescCstr|jdusJt|jS)zThe total number of items.N)rrrrAr<r<r=totalszGitlabList.totalcCs|Sr@r<rAr<r<r=__iter__szGitlabList.__iter__cCs|jdurdSt|jS)Nr)rrrAr<r<r=__len__s zGitlabList.__len__cCs|Sr@)rrAr<r<r=__next__szGitlabList.__next__cCsjz |j|j}|jd7_|WSty2Yn0|jrb|jdurb|j|jfi|j|StdS)NrvT) rr IndexErrorrrrrr StopIteration)r:rr<r<r=rs  zGitlabList.next)T)N)rrrrr r"rrrr>rrrrrrrrrrrrrrr<r<r<r=r]s>    "r)rrtypingrrrrrrrr r+Zrequests.utilsZ#requests_toolbelt.multipart.encoderr Z gitlab.configr;Z gitlab.constZgitlab.exceptionsr robjectr rr<r<r<r=s&(  >