github.com/vchain-us/vcn@v0.9.11-0.20210921212052-a2484d23c0b3/pkg/extractor/javacom/javacom.go (about)

     1  /*
     2   * Copyright (c) 2018-2020 vChain, Inc. All Rights Reserved.
     3   * This software is released under GPL3.
     4   * The full license information can be found under:
     5   * https://www.gnu.org/licenses/gpl-3.0.en.html
     6   *
     7   */
     8  
     9  package javacom
    10  
    11  import (
    12  	"crypto/sha256"
    13  	"encoding/hex"
    14  	"encoding/xml"
    15  	"io"
    16  	"io/ioutil"
    17  	"os"
    18  	"strings"
    19  
    20  	"github.com/vchain-us/vcn/pkg/api"
    21  	"github.com/vchain-us/vcn/pkg/bom/artifact"
    22  	"github.com/vchain-us/vcn/pkg/bom/java"
    23  	"github.com/vchain-us/vcn/pkg/extractor"
    24  	"github.com/vchain-us/vcn/pkg/uri"
    25  )
    26  
    27  // Scheme for java component
    28  const Scheme = "javacom"
    29  
    30  // Artifact returns a file *api.Artifact from a given u
    31  func Artifact(u *uri.URI, options ...extractor.Option) ([]*api.Artifact, error) {
    32  
    33  	if u.Scheme != Scheme {
    34  		return nil, nil
    35  	}
    36  
    37  	path := strings.TrimPrefix(u.Opaque, "//")
    38  
    39  	pomPath, err := java.GetPOM(path)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	f, err := os.Open(pomPath)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	defer f.Close()
    49  
    50  	h := sha256.New()
    51  	if _, err := io.Copy(h, f); err != nil {
    52  		return nil, err
    53  	}
    54  	checksum := h.Sum(nil)
    55  
    56  	pb, err := ioutil.ReadFile(pomPath)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	var project Pom
    62  	if err := xml.Unmarshal(pb, &project); err != nil {
    63  		return nil, err
    64  	}
    65  
    66  	return []*api.Artifact{artifact.ToApiArtifact(java.AssetType, project.Name, project.Parent.Version, hex.EncodeToString(checksum), artifact.HashSHA256)}, nil
    67  }
    68  
    69  type Pom struct {
    70  	XMLName      xml.Name `xml:"project"`
    71  	ModelVersion string   `xml:"modelVersion"`
    72  	Parent       Parent   `xml:"parent"`
    73  	Version      string   `xml:"version"`
    74  	Name         string   `xml:"name"`
    75  	Modules      []string `xml:"modules>module"`
    76  }
    77  
    78  type Parent struct {
    79  	Version string `xml:"version"`
    80  }