Skip to content

Commit f2cd4c2

Browse files
committed
testserver: add artifact mock server
1 parent 384bf9f commit f2cd4c2

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

internal/testserver/artifact.go

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/*
2+
Copyright 2020 The Flux CD contributors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package testserver
18+
19+
import (
20+
"archive/tar"
21+
"compress/gzip"
22+
"crypto/sha1"
23+
"errors"
24+
"fmt"
25+
"os"
26+
"path"
27+
"path/filepath"
28+
)
29+
30+
func NewTempArtifactServer() (*ArtifactServer, error) {
31+
server, err := NewTempHTTPServer()
32+
if err != nil {
33+
return nil, err
34+
}
35+
artifact := &ArtifactServer{server}
36+
return artifact, nil
37+
}
38+
39+
type ArtifactServer struct {
40+
*HTTPServer
41+
}
42+
43+
type File struct {
44+
Name string
45+
Body string
46+
}
47+
48+
// ArtifactFromBytes creates a tar.gz artifact from the given files and
49+
// returns the file name of the artifact.
50+
func (s *ArtifactServer) ArtifactFromBytes(files []File) (string, error) {
51+
fileName := calculateArtifactName(files)
52+
filePath := filepath.Join(s.docroot, fileName)
53+
gzFile, err := os.Create(filePath)
54+
if err != nil {
55+
return "", err
56+
}
57+
defer gzFile.Close()
58+
59+
gw := gzip.NewWriter(gzFile)
60+
defer gw.Close()
61+
62+
tw := tar.NewWriter(gw)
63+
defer tw.Close()
64+
65+
for _, file := range files {
66+
hdr := &tar.Header{
67+
Name: file.Name,
68+
Mode: 0600,
69+
Size: int64(len(file.Body)),
70+
}
71+
if err := tw.WriteHeader(hdr); err != nil {
72+
return "", err
73+
}
74+
if _, err := tw.Write([]byte(file.Body)); err != nil {
75+
return "", err
76+
}
77+
}
78+
return fileName, nil
79+
}
80+
81+
// URLForFile returns the URL the given file path can be reached at or
82+
// an error if the server has not been started.
83+
func (s *ArtifactServer) URLForFile(file string) (string, error) {
84+
if s.URL() == "" {
85+
return "", errors.New("server must be started to be able to determine the URL of the given file")
86+
}
87+
return path.Join(s.URL(), file), nil
88+
}
89+
90+
func calculateArtifactName(files []File) string {
91+
h := sha1.New()
92+
for _, f := range files {
93+
h.Write([]byte(f.Body))
94+
}
95+
return fmt.Sprintf("%x.tar.gz", h.Sum(nil))
96+
}

0 commit comments

Comments
 (0)