GetPorts retrieves all the exported ports from a dockerfile
(filename string)
| 43 | |
| 44 | // GetPorts retrieves all the exported ports from a dockerfile |
| 45 | func GetPorts(filename string) ([]int, error) { |
| 46 | data, err := os.ReadFile(filename) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | |
| 51 | data = NormalizeNewlines(data) |
| 52 | lines := strings.Split(string(data), "\n") |
| 53 | ports := []int{} |
| 54 | |
| 55 | for _, line := range lines { |
| 56 | match := findExposePortsRegEx.FindStringSubmatch(line) |
| 57 | if match == nil || len(match) != 2 { |
| 58 | continue |
| 59 | } |
| 60 | |
| 61 | portStrings := strings.Split(match[1], " ") |
| 62 | |
| 63 | OUTER: |
| 64 | for _, port := range portStrings { |
| 65 | if port == "" { |
| 66 | continue |
| 67 | } |
| 68 | |
| 69 | intPort, err := strconv.Atoi(strings.Split(port, "/")[0]) |
| 70 | if err != nil { |
| 71 | return nil, err |
| 72 | } |
| 73 | |
| 74 | // Check if port already exists |
| 75 | for _, existingPort := range ports { |
| 76 | if existingPort == intPort { |
| 77 | continue OUTER |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | ports = append(ports, intPort) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | return ports, nil |
| 86 | } |
| 87 | |
| 88 | // NormalizeNewlines normalizes \r\n (windows) and \r (mac) |
| 89 | // into \n (unix) |