code.gitea.io/gitea@v1.19.3/modules/private/restore_repo.go (about)

     1  // Copyright 2020 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package private
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"io"
    10  	"net/http"
    11  	"time"
    12  
    13  	"code.gitea.io/gitea/modules/json"
    14  	"code.gitea.io/gitea/modules/setting"
    15  )
    16  
    17  // RestoreParams structure holds a data for restore repository
    18  type RestoreParams struct {
    19  	RepoDir    string
    20  	OwnerName  string
    21  	RepoName   string
    22  	Units      []string
    23  	Validation bool
    24  }
    25  
    26  // RestoreRepo calls the internal RestoreRepo function
    27  func RestoreRepo(ctx context.Context, repoDir, ownerName, repoName string, units []string, validation bool) (int, string) {
    28  	reqURL := setting.LocalURL + "api/internal/restore_repo"
    29  
    30  	req := newInternalRequest(ctx, reqURL, "POST")
    31  	req.SetTimeout(3*time.Second, 0) // since the request will spend much time, don't timeout
    32  	req = req.Header("Content-Type", "application/json")
    33  	jsonBytes, _ := json.Marshal(RestoreParams{
    34  		RepoDir:    repoDir,
    35  		OwnerName:  ownerName,
    36  		RepoName:   repoName,
    37  		Units:      units,
    38  		Validation: validation,
    39  	})
    40  	req.Body(jsonBytes)
    41  	resp, err := req.Response()
    42  	if err != nil {
    43  		return http.StatusInternalServerError, fmt.Sprintf("Unable to contact gitea: %v, could you confirm it's running?", err.Error())
    44  	}
    45  	defer resp.Body.Close()
    46  
    47  	if resp.StatusCode != http.StatusOK {
    48  		ret := struct {
    49  			Err string `json:"err"`
    50  		}{}
    51  		body, err := io.ReadAll(resp.Body)
    52  		if err != nil {
    53  			return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error())
    54  		}
    55  		if err := json.Unmarshal(body, &ret); err != nil {
    56  			return http.StatusInternalServerError, fmt.Sprintf("Response body Unmarshal error: %v", err.Error())
    57  		}
    58  		return http.StatusInternalServerError, ret.Err
    59  	}
    60  
    61  	return http.StatusOK, fmt.Sprintf("Restore repo %s/%s successfully", ownerName, repoName)
    62  }