2014-11-14 22:07:41 +00:00
// Copyright 2014 The Gogs Authors. All rights reserved.
2020-01-26 02:46:38 +00:00
// Copyright 2020 The Gitea Authors. All rights reserved.
2014-11-14 22:07:41 +00:00
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
2015-08-26 14:34:27 +01:00
package gitea
2014-11-14 22:07:41 +00:00
import (
2020-09-15 17:21:40 +01:00
"context"
2014-11-14 22:07:41 +00:00
"encoding/json"
"errors"
2018-02-04 01:30:41 +00:00
"fmt"
2014-11-14 22:07:41 +00:00
"io"
"io/ioutil"
"net/http"
2021-03-21 20:20:32 +00:00
"net/url"
2014-11-14 22:07:41 +00:00
"strings"
2020-01-27 06:20:49 +00:00
"sync"
"github.com/hashicorp/go-version"
2014-11-14 22:07:41 +00:00
)
2019-05-11 16:38:52 +01:00
var jsonHeader = http . Header { "content-type" : [ ] string { "application/json" } }
2016-11-10 09:44:00 +00:00
// Version return the library version
2014-11-14 22:07:41 +00:00
func Version ( ) string {
2020-09-15 21:46:08 +01:00
return "0.14.0"
2014-11-14 22:07:41 +00:00
}
2021-03-04 20:19:55 +00:00
// Client represents a thread-safe Gitea API client.
2014-11-14 22:07:41 +00:00
type Client struct {
2020-11-13 01:03:33 +00:00
url string
accessToken string
username string
password string
otp string
sudo string
debug bool
client * http . Client
ctx context . Context
2021-03-04 20:19:55 +00:00
mutex sync . RWMutex
2020-11-13 01:03:33 +00:00
serverVersion * version . Version
getVersionOnce sync . Once
2014-11-14 22:07:41 +00:00
}
2020-09-14 03:37:09 +01:00
// Response represents the gitea response
type Response struct {
* http . Response
}
2014-11-14 22:07:41 +00:00
// NewClient initializes and returns a API client.
2021-03-04 20:19:55 +00:00
// Usage of all gitea.Client methods is concurrency-safe.
2020-09-15 17:21:40 +01:00
func NewClient ( url string , options ... func ( * Client ) ) ( * Client , error ) {
client := & Client {
url : strings . TrimSuffix ( url , "/" ) ,
client : & http . Client { } ,
ctx : context . Background ( ) ,
2014-11-14 22:07:41 +00:00
}
2020-09-15 17:21:40 +01:00
for _ , opt := range options {
opt ( client )
}
2020-11-12 20:59:04 +00:00
if err := client . checkServerVersionGreaterThanOrEqual ( version1_11_0 ) ; err != nil {
2020-09-15 17:55:31 +01:00
return nil , err
}
2020-09-15 17:21:40 +01:00
return client , nil
2014-11-14 22:07:41 +00:00
}
2019-04-14 21:29:52 +01:00
// NewClientWithHTTP creates an API client with a custom http client
2020-09-15 17:21:40 +01:00
// Deprecated use SetHTTPClient option
2019-10-30 14:43:01 +00:00
func NewClientWithHTTP ( url string , httpClient * http . Client ) * Client {
2020-09-15 17:21:40 +01:00
client , _ := NewClient ( url , SetHTTPClient ( httpClient ) )
2019-10-30 14:43:01 +00:00
return client
2019-04-14 21:29:52 +01:00
}
2020-09-15 17:21:40 +01:00
// SetHTTPClient is an option for NewClient to set custom http client
func SetHTTPClient ( httpClient * http . Client ) func ( client * Client ) {
return func ( client * Client ) {
2021-03-04 20:19:55 +00:00
client . SetHTTPClient ( httpClient )
2020-09-15 17:21:40 +01:00
}
}
2021-03-04 20:19:55 +00:00
// SetHTTPClient replaces default http.Client with user given one.
func ( c * Client ) SetHTTPClient ( client * http . Client ) {
c . mutex . Lock ( )
c . client = client
c . mutex . Unlock ( )
}
2020-09-15 17:21:40 +01:00
// SetToken is an option for NewClient to set token
func SetToken ( token string ) func ( client * Client ) {
return func ( client * Client ) {
2021-03-04 20:19:55 +00:00
client . mutex . Lock ( )
2020-09-15 17:21:40 +01:00
client . accessToken = token
2021-03-04 20:19:55 +00:00
client . mutex . Unlock ( )
2020-09-15 17:21:40 +01:00
}
}
// SetBasicAuth is an option for NewClient to set username and password
func SetBasicAuth ( username , password string ) func ( client * Client ) {
return func ( client * Client ) {
client . SetBasicAuth ( username , password )
}
}
// SetBasicAuth sets username and password
2020-01-13 17:17:54 +00:00
func ( c * Client ) SetBasicAuth ( username , password string ) {
2021-03-04 20:19:55 +00:00
c . mutex . Lock ( )
2020-01-13 17:17:54 +00:00
c . username , c . password = username , password
2021-03-04 20:19:55 +00:00
c . mutex . Unlock ( )
2020-01-13 17:17:54 +00:00
}
2020-09-15 17:21:40 +01:00
// SetOTP is an option for NewClient to set OTP for 2FA
func SetOTP ( otp string ) func ( client * Client ) {
return func ( client * Client ) {
client . SetOTP ( otp )
}
}
2020-05-19 23:16:37 +01:00
// SetOTP sets OTP for 2FA
func ( c * Client ) SetOTP ( otp string ) {
2021-03-04 20:19:55 +00:00
c . mutex . Lock ( )
2020-05-19 23:16:37 +01:00
c . otp = otp
2021-03-04 20:19:55 +00:00
c . mutex . Unlock ( )
2020-05-19 23:16:37 +01:00
}
2020-09-15 17:21:40 +01:00
// SetContext is an option for NewClient to set context
func SetContext ( ctx context . Context ) func ( client * Client ) {
return func ( client * Client ) {
client . SetContext ( ctx )
}
}
// SetContext set context witch is used for http requests
func ( c * Client ) SetContext ( ctx context . Context ) {
2021-03-04 20:19:55 +00:00
c . mutex . Lock ( )
2020-09-15 17:21:40 +01:00
c . ctx = ctx
2021-03-04 20:19:55 +00:00
c . mutex . Unlock ( )
2015-10-22 22:42:42 +01:00
}
2020-09-15 17:21:40 +01:00
// SetSudo is an option for NewClient to set sudo header
func SetSudo ( sudo string ) func ( client * Client ) {
return func ( client * Client ) {
client . SetSudo ( sudo )
}
}
2019-02-15 22:32:08 +00:00
// SetSudo sets username to impersonate.
func ( c * Client ) SetSudo ( sudo string ) {
2021-03-04 20:19:55 +00:00
c . mutex . Lock ( )
2019-02-15 22:32:08 +00:00
c . sudo = sudo
2021-03-04 20:19:55 +00:00
c . mutex . Unlock ( )
2019-02-15 22:32:08 +00:00
}
2020-09-19 16:23:16 +01:00
// SetDebugMode is an option for NewClient to enable debug mode
func SetDebugMode ( ) func ( client * Client ) {
return func ( client * Client ) {
2021-03-04 20:19:55 +00:00
client . mutex . Lock ( )
2020-09-19 16:23:16 +01:00
client . debug = true
2021-03-04 20:19:55 +00:00
client . mutex . Unlock ( )
2020-09-19 16:23:16 +01:00
}
}
2020-09-14 03:37:09 +01:00
func ( c * Client ) getWebResponse ( method , path string , body io . Reader ) ( [ ] byte , * Response , error ) {
2021-03-04 20:19:55 +00:00
c . mutex . RLock ( )
debug := c . debug
if debug {
2020-09-19 16:23:16 +01:00
fmt . Printf ( "%s: %s\nBody: %v\n" , method , c . url + path , body )
}
2020-09-15 17:21:40 +01:00
req , err := http . NewRequestWithContext ( c . ctx , method , c . url + path , body )
2021-03-04 20:19:55 +00:00
client := c . client // client ref can change from this point on so safe it
c . mutex . RUnlock ( )
2020-09-07 04:17:54 +01:00
if err != nil {
2020-09-14 03:37:09 +01:00
return nil , nil , err
2020-09-07 04:17:54 +01:00
}
2021-03-04 20:19:55 +00:00
resp , err := client . Do ( req )
2020-09-07 04:17:54 +01:00
if err != nil {
2020-09-14 03:37:09 +01:00
return nil , nil , err
2020-09-07 04:17:54 +01:00
}
defer resp . Body . Close ( )
2020-09-14 03:37:09 +01:00
data , err := ioutil . ReadAll ( resp . Body )
2021-03-04 20:19:55 +00:00
if debug {
2020-09-19 16:23:16 +01:00
fmt . Printf ( "Response: %v\n\n" , resp )
}
2020-09-14 03:37:09 +01:00
return data , & Response { resp } , nil
2020-09-07 04:17:54 +01:00
}
2020-09-14 03:37:09 +01:00
func ( c * Client ) doRequest ( method , path string , header http . Header , body io . Reader ) ( * Response , error ) {
2021-03-04 20:19:55 +00:00
c . mutex . RLock ( )
debug := c . debug
if debug {
2020-09-19 16:23:16 +01:00
fmt . Printf ( "%s: %s\nHeader: %v\nBody: %s\n" , method , c . url + "/api/v1" + path , header , body )
}
2020-09-15 17:21:40 +01:00
req , err := http . NewRequestWithContext ( c . ctx , method , c . url + "/api/v1" + path , body )
2014-11-14 22:07:41 +00:00
if err != nil {
2021-03-04 20:19:55 +00:00
c . mutex . RUnlock ( )
2014-11-14 22:07:41 +00:00
return nil , err
}
2019-04-14 21:29:52 +01:00
if len ( c . accessToken ) != 0 {
req . Header . Set ( "Authorization" , "token " + c . accessToken )
}
2020-05-19 23:16:37 +01:00
if len ( c . otp ) != 0 {
req . Header . Set ( "X-GITEA-OTP" , c . otp )
}
2020-01-13 17:17:54 +00:00
if len ( c . username ) != 0 {
req . SetBasicAuth ( c . username , c . password )
}
2020-05-19 23:16:37 +01:00
if len ( c . sudo ) != 0 {
2019-02-15 22:32:08 +00:00
req . Header . Set ( "Sudo" , c . sudo )
}
2021-03-04 20:19:55 +00:00
client := c . client // client ref can change from this point on so safe it
c . mutex . RUnlock ( )
2014-11-14 22:07:41 +00:00
for k , v := range header {
req . Header [ k ] = v
}
2021-03-04 20:19:55 +00:00
resp , err := client . Do ( req )
2020-09-14 03:37:09 +01:00
if err != nil {
return nil , err
}
2021-03-04 20:19:55 +00:00
if debug {
2020-09-19 16:23:16 +01:00
fmt . Printf ( "Response: %v\n\n" , resp )
}
2020-09-14 03:37:09 +01:00
return & Response { resp } , nil
2016-08-26 18:52:08 +01:00
}
2021-01-17 17:14:07 +00:00
// Converts a response for a HTTP status code indicating an error condition
// (non-2XX) to a well-known error value and response body. For non-problematic
// (2XX) status codes nil will be returned. Note that on a non-2XX response, the
// response body stream will have been read and, hence, is closed on return.
func statusCodeToErr ( resp * Response ) ( body [ ] byte , err error ) {
// no error
if resp . StatusCode / 100 == 2 {
return nil , nil
2014-11-14 22:07:41 +00:00
}
2021-01-17 17:14:07 +00:00
//
// error: body will be read for details
//
defer resp . Body . Close ( )
2014-11-14 22:07:41 +00:00
data , err := ioutil . ReadAll ( resp . Body )
if err != nil {
2021-01-17 17:14:07 +00:00
return nil , fmt . Errorf ( "body read on HTTP error %d: %v" , resp . StatusCode , err )
2014-11-14 22:07:41 +00:00
}
2014-12-13 01:29:51 +00:00
switch resp . StatusCode {
case 403 :
2021-01-17 17:14:07 +00:00
return data , errors . New ( "403 Forbidden" )
2014-12-13 01:29:51 +00:00
case 404 :
2021-01-17 17:14:07 +00:00
return data , errors . New ( "404 Not Found" )
2018-12-04 21:57:38 +00:00
case 409 :
2021-01-17 17:14:07 +00:00
return data , errors . New ( "409 Conflict" )
2018-02-04 01:30:41 +00:00
case 422 :
2021-01-17 17:14:07 +00:00
return data , fmt . Errorf ( "422 Unprocessable Entity: %s" , string ( data ) )
}
path := resp . Request . URL . Path
method := resp . Request . Method
header := resp . Request . Header
errMap := make ( map [ string ] interface { } )
if err = json . Unmarshal ( data , & errMap ) ; err != nil {
// when the JSON can't be parsed, data was probably empty or a
// plain string, so we try to return a helpful error anyway
return data , fmt . Errorf ( "Unknown API Error: %d\nRequest: '%s' with '%s' method '%s' header and '%s' body" , resp . StatusCode , path , method , header , string ( data ) )
}
return data , errors . New ( errMap [ "message" ] . ( string ) )
}
func ( c * Client ) getResponse ( method , path string , header http . Header , body io . Reader ) ( [ ] byte , * Response , error ) {
resp , err := c . doRequest ( method , path , header , body )
if err != nil {
return nil , nil , err
2014-11-14 22:07:41 +00:00
}
2021-01-17 17:14:07 +00:00
defer resp . Body . Close ( )
2014-11-14 22:07:41 +00:00
2021-01-17 17:14:07 +00:00
// check for errors
data , err := statusCodeToErr ( resp )
if err != nil {
return data , resp , err
}
// success (2XX), read body
data , err = ioutil . ReadAll ( resp . Body )
if err != nil {
return nil , resp , err
2014-11-14 22:07:41 +00:00
}
2020-09-14 03:37:09 +01:00
return data , resp , nil
2014-11-14 22:07:41 +00:00
}
2020-09-14 03:37:09 +01:00
func ( c * Client ) getParsedResponse ( method , path string , header http . Header , body io . Reader , obj interface { } ) ( * Response , error ) {
data , resp , err := c . getResponse ( method , path , header , body )
2014-11-14 22:07:41 +00:00
if err != nil {
2020-09-29 15:19:31 +01:00
return resp , err
2014-11-14 22:07:41 +00:00
}
2020-09-14 03:37:09 +01:00
return resp , json . Unmarshal ( data , obj )
2014-11-14 22:07:41 +00:00
}
2016-10-11 20:52:07 +01:00
2020-09-14 03:37:09 +01:00
func ( c * Client ) getStatusCode ( method , path string , header http . Header , body io . Reader ) ( int , * Response , error ) {
2016-10-11 20:52:07 +01:00
resp , err := c . doRequest ( method , path , header , body )
if err != nil {
2020-09-14 03:37:09 +01:00
return - 1 , resp , err
2016-10-11 20:52:07 +01:00
}
defer resp . Body . Close ( )
2020-09-14 03:37:09 +01:00
return resp . StatusCode , resp , nil
2016-10-11 20:52:07 +01:00
}
2021-03-21 20:20:32 +00:00
// pathEscapeSegments escapes segments of a path while not escaping forward slash
func pathEscapeSegments ( path string ) string {
slice := strings . Split ( path , "/" )
for index := range slice {
slice [ index ] = url . PathEscape ( slice [ index ] )
}
escapedPath := strings . Join ( slice , "/" )
return escapedPath
}
// escapeValidatePathSegments is a help function to validate and encode url path segments
func escapeValidatePathSegments ( seg ... * string ) error {
for i := range seg {
if seg [ i ] == nil || len ( * seg [ i ] ) == 0 {
return fmt . Errorf ( "path segment [%d] is empty" , i )
}
* seg [ i ] = url . PathEscape ( * seg [ i ] )
}
return nil
}