Skip to content

Instantly share code, notes, and snippets.

@pgbytes
Created April 11, 2018 13:35
Show Gist options
  • Save pgbytes/ce377e1a9bfd7ea661c631be73765b87 to your computer and use it in GitHub Desktop.
Save pgbytes/ce377e1a9bfd7ea661c631be73765b87 to your computer and use it in GitHub Desktop.
Generate an xml file, write to file and load it from file.
package models
import (
"encoding/xml"
"errors"
"io/ioutil"
"os"
"gopkg.in/resty.v1"
"crypto/tls"
"encoding/json"
"encoding/base64"
"fmt"
)
var defaultXMLNS = "http://maven.apache.org/POM/4.0.0"
var defaultXSI = "http://www.w3.org/2001/XMLSchema-instance"
var defaultSchemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
type Pom struct {
XMLName xml.Name `xml:"project"`
XMLNS string `xml:"xmlns,attr"`
XSI string `xml:"xmlns:xsi,attr"`
SchemaLocation string `xml:"xsi:schemaLocation,attr"`
ModelVersion string `xml:"modelVersion"`
GroupId string `xml:"groupId,omitempty"`
ArtifactId string `xml:"artifactId"`
Version string `xml:"version"`
Description string `xml:"description,omitempty"`
Packaging string `xml:"packaging,omitempty"`
Parent *Unit `xml:"parent,omitempty"`
Modules *[]string `xml:"modules>module"`
Dependencies *[]Unit `xml:"dependencies>dependency"`
}
type Unit struct {
GroupId string `xml:"groupId,omitempty"`
ArtifactId string `xml:"artifactId,omitempty"`
Version string `xml:"version,omitempty"`
Scope string `xml:"scope,omitempty"`
Type string `xml:"type,omitempty"`
RelativePath string `xml:"relativePath,omitempty"`
}
func LoadPomFromFile(pomFilePath string) (*Pom, error) {
pomFileBytes, err := ioutil.ReadFile(pomFilePath)
if err != nil {
return nil, errors.New("error reading pom file: " + pomFilePath + " error: " + err.Error())
}
pom, err := parsePom(pomFileBytes)
if err != nil {
return nil, errors.New("error parsing pom file: " + pomFilePath + " error: " + err.Error())
}
return pom, nil
}
func NewPom(groupId string, artifactId string, version string) (*Pom, error) {
return &Pom{
XMLNS: defaultXMLNS,
XSI: defaultXSI,
SchemaLocation: defaultSchemaLocation,
ModelVersion: "4.0.0",
GroupId: groupId,
ArtifactId: artifactId,
Version: version,
}, nil
}
func (p *Pom) ToByteArray() ([]byte, error) {
b, err := xml.MarshalIndent(p, " ", " ")
if err == nil {
b = []byte(xml.Header + string(b))
return b, nil
}
return nil, err
}
func (p *Pom) WriteToFile(filePath string) error {
if filePath == "" {
filePath = "pom.xml"
}
bytes, err := p.ToByteArray()
if err != nil {
return err
}
return ioutil.WriteFile(filePath, bytes, os.ModePerm)
}
func parsePom(pomContentBytes []byte) (*Pom, error) {
pomContent := Pom{}
pomParseErr := xml.Unmarshal(pomContentBytes, &pomContent)
return &pomContent, pomParseErr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment