nix-amer/internal/buildfile/reader.go

85 lines
1.7 KiB
Go
Raw Normal View History

package buildfile
import (
"bufio"
"errors"
"fmt"
2018-11-09 21:37:05 +00:00
"git.xdrm.io/xdrm-brackets/nix-amer/internal/instruction"
"io"
"strings"
)
var ErrNullContext = errors.New("null context")
// Reader is the buildfile reader
type Reader struct {
// Context is the linux distribution-specified execution context (package manager, service manager, etc)
Context *instruction.ExecutionContext
// Content is the instruction list
Content []instruction.T
}
// NewReader creates a new reader for the specified build file and linux distribution
func NewReader(ctx *instruction.ExecutionContext, buildfile io.Reader) (*Reader, error) {
// fail on null context
if ctx == nil {
return nil, ErrNullContext
}
r := &Reader{
Context: ctx,
Content: make([]instruction.T, 0),
}
2018-11-09 21:37:05 +00:00
// add each line as instruction
l, reader := 0, bufio.NewReader(buildfile)
for {
l++
2018-11-09 21:37:05 +00:00
// read line until end
line, err := reader.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, LineError{l, err}
}
line = strings.Trim(line, " \t\r\n")
// ignore newline & comments
if len(line) < 1 || line[0] == '[' {
continue
}
2018-11-09 21:37:05 +00:00
// turn into instruction
inst, err := instruction.Parse(line)
if err != nil {
return nil, LineError{l, err}
}
2018-11-09 21:37:05 +00:00
// add to list
r.Content = append(r.Content, inst)
}
return r, nil
}
// Execute the current buildfile instruction by instruction
func (r *Reader) Execute() error {
// 1. update package list
err := r.Context.PackageManager.Fetch()
if err != nil {
return fmt.Errorf("cannot fetch packages | %s", err)
}
// 2. upgrade packages
err = r.Context.PackageManager.Upgrade()
if err != nil {
return fmt.Errorf("cannot upgrade | %s", err)
}
return nil
}