github.com/jfrog/jfrog-cli-go@v1.22.1-0.20200318093948-4826ef344ffd/artifactory/utils/dependenciestree/dependencies.go (about)

     1  package dependenciestree
     2  
     3  import (
     4  	"encoding/json"
     5  	"github.com/jfrog/jfrog-client-go/artifactory/buildinfo"
     6  )
     7  
     8  // Dependency tree
     9  type Tree interface {
    10  	MarshalJSON() ([]byte, error)
    11  }
    12  
    13  type Root []*DependenciesTree
    14  
    15  type DependenciesTree struct {
    16  	Dependency         *buildinfo.Dependency `json:"dependencies,omitempty"`
    17  	DirectDependencies []*DependenciesTree
    18  	Id                 string
    19  }
    20  
    21  func (r Root) MarshalJSON() ([]byte, error) {
    22  	type Alias Root
    23  	return json.Marshal(Alias(r))
    24  }
    25  
    26  func (t DependenciesTree) MarshalJSON() ([]byte, error) {
    27  	type Alias []*DependenciesTree
    28  	return json.Marshal(&struct {
    29  		*buildinfo.Dependency
    30  		Alias `json:"dependencies,omitempty"`
    31  	}{
    32  		Dependency: t.Dependency,
    33  		Alias:      t.DirectDependencies,
    34  	})
    35  }
    36  
    37  // Add children nodes for a dependency
    38  func (t *DependenciesTree) AddChildren(allDependencies map[string]*buildinfo.Dependency, children map[string][]string) {
    39  	for _, child := range children[t.Id] {
    40  		if _, ok := allDependencies[child]; !ok {
    41  			//No such child, skip...
    42  			continue
    43  		}
    44  		childTree := &DependenciesTree{Id: child, Dependency: allDependencies[child]}
    45  		childTree.AddChildren(allDependencies, children)
    46  		t.DirectDependencies = append(t.DirectDependencies, childTree)
    47  	}
    48  }
    49  
    50  // Create dependency tree using the data received from the extractors.
    51  func CreateDependencyTree(rootDependencies []string, allDependencies map[string]*buildinfo.Dependency, childrenMap map[string][]string) Root {
    52  	var rootTree Root
    53  	for _, root := range rootDependencies {
    54  		if _, ok := allDependencies[root]; !ok {
    55  			//No such root, skip...
    56  			continue
    57  		}
    58  		subTree := &DependenciesTree{Id: root, Dependency: allDependencies[root]}
    59  		subTree.AddChildren(allDependencies, childrenMap)
    60  		rootTree = append(rootTree, subTree)
    61  	}
    62  	return rootTree
    63  }