forked from Azure/azure-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdocker.go
75 lines (68 loc) · 1.75 KB
/
docker.go
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package appdetect
import (
"bufio"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
func detectDockerInDirectory(path string, entries []fs.DirEntry) (*Docker, error) {
for _, entry := range entries {
if strings.ToLower(entry.Name()) == "dockerfile" {
dockerFilePath := filepath.Join(path, entry.Name())
return AnalyzeDocker(dockerFilePath)
}
}
return nil, nil
}
// AnalyzeDocker analyzes the Dockerfile and returns the Docker result.
func AnalyzeDocker(dockerFilePath string) (*Docker, error) {
file, err := os.Open(dockerFilePath)
if err != nil {
return nil, fmt.Errorf("reading Dockerfile at %s: %w", dockerFilePath, err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var ports []Port
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "EXPOSE") {
parsedPorts, err := parsePortsInLine(line[len("EXPOSE"):])
if err != nil {
log.Printf("parsing Dockerfile at %s: %v", dockerFilePath, err)
}
ports = append(ports, parsedPorts...)
}
}
return &Docker{
Path: dockerFilePath,
Ports: ports,
}, nil
}
func parsePortsInLine(s string) ([]Port, error) {
var ports []Port
portSpecs := strings.Fields(s)
for _, portSpec := range portSpecs {
var portString string
var protocol string
if strings.Contains(portSpec, "/") {
parts := strings.Split(portSpec, "/")
portString = parts[0]
protocol = parts[1]
} else {
portString = portSpec
protocol = "tcp"
}
portNumber, err := strconv.Atoi(portString)
if err != nil {
return nil, fmt.Errorf("parsing port number: %w", err)
}
ports = append(ports, Port{portNumber, protocol})
}
return ports, nil
}