3 @qhcu@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 j!ej j"eeee eefd d!d"Z#ej j!ej j$dSee eeeed$d%d&Z%ej j!ej j&eeeefd'd(d)Z'ej j!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 j!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|_|jd|_d|j| f|_||_d|i|_||_ ||_ ||_ ||_ ||_ ||_|j| pxtj|_| |_| |_| |_|jdkrtd|jdddl}|jj}||_|j||_|j||_|j||_ |j!||_"|j#||_$|j%||_&|j'||_(|j)||_*|j+||_,|j-||_.|j/||_0|j1||_2|j3||_4|j5||_6|j7||_8|j9||_:|j;||_<|j=||_>|j?||_@|jA||_B|jC||_D|jE||_F|jG||_H|jI||_J|jK||_L|jM||_N|jO||_P|jQ||_R|jS||_T|jU||_V|jW||_X|jY||_Z|j[||_\dS) N/z %s/api/v%sz User-Agentr zgitlab.v%s.objects)namer)r )]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)selfrrrrrrrrrrrrrrgitlabr-r9L/home/ec2-user/environment/venv/lib/python3.6/dist-packages/gitlab/client.py__init__9sr                                     zGitlab.__init__)rcCs|S)Nr9)r7r9r9r: __enter__szGitlab.__enter__)argsrcGs|jjdS)N)rclose)r7r=r9r9r:__exit__szGitlab.__exit__cCs|jj}|jd|S)Nr.)__dict__copypop)r7stater9r9r: __getstate__s  zGitlab.__getstate__)rCrcCs<|jj||jdkr&td|jdddl}|jj|_dS)Nr zgitlab.v%s.objects)rr)r )r@updater r*r+r,r-r.)r7rCr8r9r9r: __setstate__s   zGitlab.__setstate__cCs|jS)zThe user-provided server URL.)r$)r7r9r9r:rsz Gitlab.urlcCs|jS)zThe computed API base URL.)r%)r7r9r9r:api_urlszGitlab.api_urlcCs|jS)zThe API version used (4 only).)r )r7r9r9r: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. )rHrI) rrrrrrrrrrrr)r8configZGitlabConfigParserrrrrrrrrrrrrr)clsrHrIrJr9r9r: from_configs  zGitlab.from_configcCs|jj|j|_dS)zPerforms an authentication using private token. The `user` attribute will hold a `gitlab.objects.CurrentUser` object on success. N)r.ZCurrentUserManagergetuser)r7r9r9r:authsz Gitlab.authc Cs~|jdkrfy:|jd}t|tr6|d|_|d|_n d|_d|_Wn tk rdd|_d|_YnXtt|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)r7datar9r9r:rPs       zGitlab.version)contentkwargsrcKsFd|i}|jdd|i|}tr2t|tj s2t|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 rX/ci/lint post_datastatusZvaliderrors)rZ) http_postrrTr(ResponseAssertionError)r7rXrYr[rWr9r9r:lints z Gitlab.lintF)textgfmprojectrYrcKsL||d}|dk r||d<|jdd|i|}trDt|tj sDt|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. )rbrcNrd /markdownr[html)re)r^rrTr(r_r`)r7rbrcrdrYr[rWr9r9r:markdown3s zGitlab.markdown)rYrcKs|jd|}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)rh)rSrTrU)r7rYresultr9r9r: get_licensePs  zGitlab.get_license)licenserYrcKs6d|i}|jdd|i|}tr2t|tj s2t|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 rk/licenser[)rl)r^rrTr(r_r`)r7rkrYrWrir9r9r: set_licensecs zGitlab.set_licensecCsdd|j|j|jgD}t|dkr.td|jr<|j sJ|j rR|jrRtd|jrf|jrftdd|_|jr|jj dd|j|jd<|jj d d|jrd |j|jd<|jj dd|jj d d|jr|jj dd|jj dd|j|jd <|jrt j j |j|j|_dS) NcSsg|] }|r|qSr9r9).0tokenr9r9r: zsz)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&rBr(rO HTTPBasicAuth)r7tokensr9r9r:r'xs8    zGitlab._set_auth_infocCsRddl}ddlm}d|_|j|jj|j|jd}|j|jd|_dS)Nr)HTTPConnectionrqzrequests.packages.urllib3T) logging http.clientrx debuglevel basicConfig getLoggersetLevelDEBUG propagate)r7ryrxZ requests_logr9r9r: enable_debugs   zGitlab.enable_debugcCs|jj|j|j|jdS)N)r&rOrverify)r&rArurr)r7r9r9r:_get_session_optsszGitlab._get_session_opts)pathrcCs*|jds|jdr|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://zhttps://z%s%sN) startswithr%)r7rr9r9r: _build_urls zGitlab._build_url)rircCsh|jrd|jjdrdxP|jD]F}|jdkr*q|jjdkr8q|jjdd}|r|jdrtj j t qWdS)Nzhttp:-.GETZLocationzhttps://)rr) historyr$r status_coderequestmethodr&rMr8 exceptionsZ RedirectError REDIRECT_MSG)r7riitemlocationr9r9r:_check_redirectss   zGitlab._check_redirects)filesr[rawrcCs|rr|dkri}n0x.|jD]"\}}t|trtt|||<qW|jd|d<|jd|d<t|}d||jfS|r|rd|dfS|ddfS)NfileZavatarzapplication/octet-streamzapplication/json)itemsrTboolrintrMr content_type)r7rr[rkvrWr9r9r:_prepare_send_datas    zGitlab._prepare_send_data ) verbr query_datar[rstreamedrrobey_rate_limitretry_transient_errors max_retriesrYrc  KsR|pi}|j|} i}tj||d| kr^tj|| dx.dD]}|| kr@| |||<q@Wn tj|| |j}|jd}|jd}|dkr|}|j|||\}}}||dd<tj|| f|||d |}|jj |}tj |j |_ |jj |j i||d}d }xH|jj |fd|i|}|j|d |jko>d knrJ|Sd |jkr\| sn|jdkr| r| dks|| krd|d}d|jkrt|jd}|d7}tj|q|j}y.|j}x dD]}||kr||}qWWntttfk rYnX|jdkr2tjj|j||jdtjj|j||jdqWdS)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_parametersrpagerrNr&z Content-type)jsonrWparamsri,irqg?z Retry-Aftermessageerrori)Z response_code error_messageZ response_body)rr)rrrr)rr)rr Z copy_dictrrBrr(Requestrprepare_requestZ sanitized_urlrmerge_environment_settingssendrrr&rtimesleeprXrKeyErrorrt TypeErrorr8rZGitlabAuthenticationErrorZGitlabHttpError)r7rrrr[rrrrrrrrYrrargoptsrZ opts_timeoutrrWrreqZpreppedr3Z cur_retriesriZ wait_timerZ error_jsonrr9r9r: http_requestsl,                zGitlab.http_request)rrrrrYrcKs|pi}|jd|f||d|}|jddkrz| rz| rzy|jStk rv}ztjjdd|WYdd}~Xq~Xn|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 rM)rrz Content-Typezapplication/jsonz"Failed to parse the server message)rN)rr&rrVr8rGitlabParsingError)r7rrrrrYrier9r9r:rSzszGitlab.http_get GitlabList)rras_listrYrcKs|pi}|dkrdn|}|jdd}|j|}|jd}|dkr\|dkr\tt|||f|S|sh|dkrtt|||fddi|St|||f|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)rBrrMlistr)r7rrrrYget_allrrr9r9r: http_lists    zGitlab.http_list)rrr[rrrYrc Ks|pi}|pi}|jd|f|||d|}y|jjdddkrH|jSWn2tk r|}ztjjdd|WYdd}~XnX|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)rr[rz Content-TypeNzapplication/jsonz"Failed to parse the server message)r)rr&rMrrVr8rr) r7rrr[rrrYrirr9r9r:r^s" zGitlab.http_postc Ksn|pi}|pi}|jd|f||||d|}y|jStk rh}ztjjdd|WYdd}~XnXdS)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)rr[rrz"Failed to parse the server message)rN)rrrVr8rr) r7rrr[rrrYrirr9r9r:http_puts zGitlab.http_put)rrYrcKs|jd|f|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)r7rrYr9r9r: http_delete7szGitlab.http_delete)scopesearchrYrcKs||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)r7rrrYrWr9r9r:rGs z Gitlab.search)NN)FN)NNF) NNFFNNTFr)NFF)NN)NNFN)NNFN)9__name__ __module__ __qualname____doc__r8constZ USER_AGENTrrr rfloatr(r)rr;r<rr?rrDrFpropertyrrGr classmethodrrLrOrrPrZ on_http_errorZGitlabVerifyErrorraZGitlabMarkdownErrorrgZGitlabLicenseErrorrjrmr'rrrr_rr rrrSrr^rrZGitlabSearchErrorrr9r9r9r:r %sVj   ,  @x *",0 ,0 '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)glrrrrYrcKs:||_|j|_|j||f|j||_|jjdddS)Nr)_glrA_kwargs_query _get_nextrB)r7rrrrrYr9r9r:r;ds  zGitlabList.__init__)rrrYrcKs|pi}|jjd|fd|i|}y<|j}|r<|dd}ntjj|jddd}||_Wntk rxd|_YnX|jj d|_ |jj d|_ |jj d |_ |jj d |_ |jj d |_|jj d |_y|j|_Wn4tk r}ztjjd d|WYdd}~XnXd|_dS)NrMrnextrlinksrzX-Pagez X-Prev-Pagez X-Next-Pagez X-Per-Pagez X-Total-PageszX-Totalz"Failed to parse the server message)r)rrrr(r parse_header_linksr& _next_urlrrM _current_page _prev_page _next_page _per_page _total_pages_totalr_datarVr8rr_current)r7rrrYrirZnext_urlrr9r9r:rws4  zGitlabList._query)rcCstr|jdk stt|jS)zThe current page number.N)rrr`r)r7r9r9r: current_pageszGitlabList.current_pagecCs|jrt|jSdS)zSThe previous page number. If None, the current page is the first. N)rr)r7r9r9r: prev_pageszGitlabList.prev_pagecCs|jrt|jSdS)zNThe next page number. If None, the current page is the last. N)rr)r7r9r9r: next_pageszGitlabList.next_pagecCstr|jdk stt|jS)zThe number of items per page.N)rrr`r)r7r9r9r:rszGitlabList.per_pagecCstr|jdk stt|jS)zThe total number of pages.N)rrr`r)r7r9r9r: total_pagesszGitlabList.total_pagescCstr|jdk stt|jS)zThe total number of items.N)rrr`r)r7r9r9r:totalszGitlabList.totalcCs|S)Nr9)r7r9r9r:__iter__szGitlabList.__iter__cCs|jdkrdSt|jS)Nr)rr)r7r9r9r:__len__s zGitlabList.__len__cCs|jS)N)r)r7r9r9r:__next__szGitlabList.__next__c Csfy|j|j}|jd7_|Stk r2YnX|jr^|jdkr^|j|jf|j|jStdS)NrqT) rr IndexErrorrrrrr StopIteration)r7rr9r9r:rs zGitlabList.next)T)N)rrrrr rrrrr;rrrrrrrrrrrrrrr9r9r9r:r]s,  r)rrtypingrrrrrrrr r(Zrequests.utilsZ#requests_toolbelt.multipart.encoderr Z gitlab.configr8Z gitlab.constZgitlab.exceptionsr robjectr rr9r9r9r:s$(  >