File: main.go

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (80 lines) | stat: -rw-r--r-- 2,058 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"os"

	"gitlab.com/gitlab-org/gitlab/workhorse/cmd/gitlab-zip-metadata/limit"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/config"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/zipartifacts"
)

const progName = "gitlab-zip-metadata"

var Version = "unknown"

var printVersion = flag.Bool("version", false, "Print version and exit")
var zipReaderLimitBytes = flag.Int64("zip-reader-limit", config.DefaultMetadataConfig.ZipReaderLimitBytes, "The optional number of bytes to limit the zip reader to")

func main() {
	flag.Parse()

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

	if len(flag.Args()) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: %s FILE.ZIP\n", progName)
		os.Exit(1)
	}

	readerFunc := func(reader io.ReaderAt, size int64) io.ReaderAt {
		zipReaderLimit := sizeToLimit(size, *zipReaderLimitBytes)

		return limit.NewLimitedReaderAt(reader, zipReaderLimit, func(read int64) {
			fmt.Fprintf(os.Stderr, "%s: zip archive limit exceeded after reading %d bytes\n", progName, read)

			fatalError(zipartifacts.ErrorCode[zipartifacts.CodeLimitsReached])
		})
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	archive, err := zipartifacts.OpenArchiveWithReaderFunc(ctx, flag.Args()[0], readerFunc)
	if err != nil {
		fatalError(err)
	}

	if err := zipartifacts.GenerateZipMetadata(os.Stdout, archive); err != nil {
		fatalError(err)
	}
}

func fatalError(err error) {
	code := zipartifacts.ExitCodeByError(err)

	fmt.Fprintf(os.Stderr, "%s error: %v, code: %d\n", progName, err, code)

	if code > 0 {
		os.Exit(code)
	} else {
		os.Exit(1)
	}
}

// sizeToLimit tries to dermine an appropriate limit in bytes for an archive of
// a given size. If the size is less than 1 gigabyte we always limit a reader
// to 100 megabytes, otherwise the limit is 10% of a given size.
func sizeToLimit(size, defaultSize int64) int64 {
	if size <= 1024*config.Megabyte {
		return defaultSize
	}

	return size / 10
}