main.go 2.32 KB
Newer Older
1 2 3 4
package main

import (
	"archive/zip"
5
	"context"
6
	"errors"
7 8 9 10
	"flag"
	"fmt"
	"io"
	"os"
11

12 13
	"gitlab.com/gitlab-org/labkit/mask"

Jacob Vosmaer's avatar
Jacob Vosmaer committed
14
	"gitlab.com/gitlab-org/gitlab-workhorse/internal/zipartifacts"
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
)

const progName = "gitlab-zip-cat"

var Version = "unknown"

var printVersion = flag.Bool("version", false, "Print version and exit")

func main() {
	flag.Parse()

	version := fmt.Sprintf("%s %s", progName, Version)
	if *printVersion {
		fmt.Println(version)
		os.Exit(0)
	}

32 33 34 35 36 37 38
	archivePath := os.Getenv("ARCHIVE_PATH")
	encodedFileName := os.Getenv("ENCODED_FILE_NAME")

	if len(os.Args) != 1 || archivePath == "" || encodedFileName == "" {
		fmt.Fprintf(os.Stderr, "Usage: %s\n", progName)
		fmt.Fprintf(os.Stderr, "Env: ARCHIVE_PATH=https://path.to/archive.zip or /path/to/archive.zip\n")
		fmt.Fprintf(os.Stderr, "Env: ENCODED_FILE_NAME=base64-encoded-file-name\n")
39 40 41
		os.Exit(1)
	}

42
	scrubbedArchivePath := mask.URL(archivePath)
Jacob Vosmaer's avatar
Jacob Vosmaer committed
43

44
	fileName, err := zipartifacts.DecodeFileEntry(encodedFileName)
Jacob Vosmaer's avatar
Jacob Vosmaer committed
45
	if err != nil {
46
		fatalError(fmt.Errorf("decode entry %q", encodedFileName), err)
Jacob Vosmaer's avatar
Jacob Vosmaer committed
47 48
	}

49 50 51 52 53
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	archive, err := zipartifacts.OpenArchive(ctx, archivePath)
	if err != nil {
54
		fatalError(errors.New("open archive"), err)
55
	}
56

57
	file := findFileInZip(fileName, archive)
58
	if file == nil {
59
		fatalError(fmt.Errorf("find %q in %q: not found", fileName, scrubbedArchivePath), zipartifacts.ErrorCode[zipartifacts.CodeEntryNotFound])
60 61 62 63
	}
	// Start decompressing the file
	reader, err := file.Open()
	if err != nil {
64
		fatalError(fmt.Errorf("open %q in %q", fileName, scrubbedArchivePath), err)
65 66
	}
	defer reader.Close()
67 68

	if _, err := fmt.Printf("%d\n", file.UncompressedSize64); err != nil {
69
		fatalError(fmt.Errorf("write file size invalid"), err)
70 71
	}

72
	if _, err := io.Copy(os.Stdout, reader); err != nil {
73
		fatalError(fmt.Errorf("write %q from %q to stdout", fileName, scrubbedArchivePath), err)
74 75 76 77 78 79 80 81 82 83 84 85
	}
}

func findFileInZip(fileName string, archive *zip.Reader) *zip.File {
	for _, file := range archive.File {
		if file.Name == fileName {
			return file
		}
	}
	return nil
}

86 87
func fatalError(contextErr error, statusErr error) {
	code := zipartifacts.ExitCodeByError(statusErr)
88

89
	fmt.Fprintf(os.Stderr, "%s error: %v - %v, code: %d\n", progName, statusErr, contextErr, code)
90

91 92 93 94 95
	if code > 0 {
		os.Exit(code)
	} else {
		os.Exit(1)
	}
96
}