Debian Codegraph @

caddyconfig/caddyfile/importgraph.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyfile
16
17 import (
18 "fmt"
19 "slices"
20 )
21
22 type adjacency map[string][]string
23
24 type importGraph struct {
25 nodes map[string]struct{}
26 edges adjacency
27 }
28
29 func (i *importGraph) addNode(name string) {
30 if i.nodes == nil {
31 i.nodes = make(map[string]struct{})
32 }
33 if _, exists := i.nodes[name]; exists {
34 return
35 }
36 i.nodes[name] = struct{}{}
37 }
38
39 func (i *importGraph) addNodes(names []string) {
40 for _, name := range names {
41 i.addNode(name)
42 }
43 }
44
45 func (i *importGraph) removeNode(name string) {
46 delete(i.nodes, name)
47 }
48
49 func (i *importGraph) removeNodes(names []string) {
50 for _, name := range names {
51 i.removeNode(name)
52 }
53 }
54
55 func (i *importGraph) addEdge(from, to string) error {
56 if !i.exists(from) || !i.exists(to) {
57 return fmt.Errorf("one of the nodes does not exist")
58 }
59
60 if i.willCycle(to, from) {
61 return fmt.Errorf("a cycle of imports exists between %s and %s", from, to)
62 }
63
64 if i.areConnected(from, to) {
65 // if connected, there's nothing to do
66 return nil
67 }
68
69 if i.nodes == nil {
70 i.nodes = make(map[string]struct{})
71 }
72 if i.edges == nil {
73 i.edges = make(adjacency)
74 }
75
76 i.edges[from] = append(i.edges[from], to)
77 return nil
78 }
79
80 func (i *importGraph) addEdges(from string, tos []string) error {
81 for _, to := range tos {
82 err := i.addEdge(from, to)
83 if err != nil {
84 return err
85 }
86 }
87 return nil
88 }
89
90 func (i *importGraph) areConnected(from, to string) bool {
91 al, ok := i.edges[from]
92 if !ok {
93 return false
94 }
95 return slices.Contains(al, to)
96 }
97
98 func (i *importGraph) willCycle(from, to string) bool {
99 collector := make(map[string]bool)
100
101 var visit func(string)
102 visit = func(start string) {
103 if !collector[start] {
104 collector[start] = true
105 for _, v := range i.edges[start] {
106 visit(v)
107 }
108 }
109 }
110
111 for _, v := range i.edges[from] {
112 visit(v)
113 }
114 for k := range collector {
115 if to == k {
116 return true
117 }
118 }
119
120 return false
121 }
122
123 func (i *importGraph) exists(key string) bool {
124 _, exists := i.nodes[key]
125 return exists
126 }