code.gitea.io/gitea@v1.19.3/modules/git/repo_archive.go (about)

     1  // Copyright 2015 The Gogs Authors. All rights reserved.
     2  // Copyright 2020 The Gitea Authors. All rights reserved.
     3  // SPDX-License-Identifier: MIT
     4  
     5  package git
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"io"
    11  	"path/filepath"
    12  	"strings"
    13  )
    14  
    15  // ArchiveType archive types
    16  type ArchiveType int
    17  
    18  const (
    19  	// ZIP zip archive type
    20  	ZIP ArchiveType = iota + 1
    21  	// TARGZ tar gz archive type
    22  	TARGZ
    23  	// BUNDLE bundle archive type
    24  	BUNDLE
    25  )
    26  
    27  // String converts an ArchiveType to string
    28  func (a ArchiveType) String() string {
    29  	switch a {
    30  	case ZIP:
    31  		return "zip"
    32  	case TARGZ:
    33  		return "tar.gz"
    34  	case BUNDLE:
    35  		return "bundle"
    36  	}
    37  	return "unknown"
    38  }
    39  
    40  func ToArchiveType(s string) ArchiveType {
    41  	switch s {
    42  	case "zip":
    43  		return ZIP
    44  	case "tar.gz":
    45  		return TARGZ
    46  	case "bundle":
    47  		return BUNDLE
    48  	}
    49  	return 0
    50  }
    51  
    52  // CreateArchive create archive content to the target path
    53  func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, target io.Writer, usePrefix bool, commitID string) error {
    54  	if format.String() == "unknown" {
    55  		return fmt.Errorf("unknown format: %v", format)
    56  	}
    57  
    58  	cmd := NewCommand(ctx, "archive")
    59  	if usePrefix {
    60  		cmd.AddOptionFormat("--prefix=%s", filepath.Base(strings.TrimSuffix(repo.Path, ".git"))+"/")
    61  	}
    62  	cmd.AddOptionFormat("--format=%s", format.String())
    63  	cmd.AddDynamicArguments(commitID)
    64  
    65  	var stderr strings.Builder
    66  	err := cmd.Run(&RunOpts{
    67  		Dir:    repo.Path,
    68  		Stdout: target,
    69  		Stderr: &stderr,
    70  	})
    71  	if err != nil {
    72  		return ConcatenateError(err, stderr.String())
    73  	}
    74  	return nil
    75  }