Skip to content

Commit

Permalink
Add --- prefix to trace level in logger
Browse files Browse the repository at this point in the history
  • Loading branch information
jwillp committed Aug 29, 2024
1 parent acdd5f7 commit 45c04e4
Show file tree
Hide file tree
Showing 8 changed files with 135 additions and 100 deletions.
14 changes: 2 additions & 12 deletions artifactregistry.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ func (r *InMemoryArtifactRegistry) Load() error { return nil }

func (r *InMemoryArtifactRegistry) Save() error { return nil }

const DefaultJSONArtifactRegistryFileName = ".specter.json"

type JsonArtifactRegistryEntry struct {
ArtifactID ArtifactID `json:"artifactId"`
Metadata map[string]any `json:"metadata"`
Expand Down Expand Up @@ -178,18 +180,6 @@ func (r *JSONArtifactRegistry) FindAll(processorName string) ([]ArtifactRegistry
return entries, nil
}

// NewJSONArtifactRegistry returns a new artifact file registry.
func NewJSONArtifactRegistry(fileName string, fs FileSystem) *JSONArtifactRegistry {
return &JSONArtifactRegistry{
Entries: make(map[string][]JsonArtifactRegistryEntry),
FilePath: fileName,
CurrentTimeProvider: func() time.Time {
return time.Now()
},
FileSystem: fs,
}
}

func (r *JSONArtifactRegistry) Load() error {
r.mu.Lock()
defer r.mu.Unlock()
Expand Down
101 changes: 101 additions & 0 deletions assembly.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package specter

import (
"os"
"time"
)

// New allows creating a new specter instance using the provided options.
func New(opts ...Option) *Specter {
s := &Specter{
Logger: NewDefaultLogger(DefaultLoggerConfig{DisableColors: true, Writer: os.Stdout}),
ExecutionMode: FullMode,
}
for _, o := range opts {
o(s)
}
return s
}

// Option represents an option to configure a specter instance.
type Option func(s *Specter)

// WithLogger configures the Logger of a Specter instance.
func WithLogger(l Logger) Option {
return func(s *Specter) {
s.Logger = l
}
}

// WithSourceLoaders configures the SourceLoader of a Specter instance.
func WithSourceLoaders(loaders ...SourceLoader) Option {
return func(s *Specter) {
s.SourceLoaders = append(s.SourceLoaders, loaders...)
}
}

// WithLoaders configures the SpecificationLoader of a Specter instance.
func WithLoaders(loaders ...SpecificationLoader) Option {
return func(s *Specter) {
s.Loaders = append(s.Loaders, loaders...)
}
}

// WithProcessors configures the SpecProcess of a Specter instance.
func WithProcessors(processors ...SpecificationProcessor) Option {
return func(s *Specter) {
s.Processors = append(s.Processors, processors...)
}
}

// WithArtifactProcessors configures the ArtifactProcessor of a Specter instance.
func WithArtifactProcessors(processors ...ArtifactProcessor) Option {
return func(s *Specter) {
s.ArtifactProcessors = append(s.ArtifactProcessors, processors...)
}
}

// WithExecutionMode configures the ExecutionMode of a Specter instance.
func WithExecutionMode(m ExecutionMode) Option {
return func(s *Specter) {
s.ExecutionMode = m
}
}
func WithArtifactRegistry(r ArtifactRegistry) Option {
return func(s *Specter) {
s.ArtifactRegistry = r
}
}

// DEFAULTS SPECTER OPTIONS

func WithDefaultLogger() Option {
return WithLogger(NewDefaultLogger(DefaultLoggerConfig{DisableColors: false, Writer: os.Stdout}))
}

func WithJSONArtifactRegistry(fileName string, fs FileSystem) Option {
return WithArtifactRegistry(NewJSONArtifactRegistry(fileName, fs))
}

// NewFileSystemLoader FileSystem
func NewFileSystemLoader(fs FileSystem) *FileSystemLoader {
return &FileSystemLoader{fs: fs}
}

func NewLocalFileSourceLoader() FileSystemLoader {
return FileSystemLoader{fs: LocalFileSystem{}}
}

// ARTIFACT REGISTRIES

// NewJSONArtifactRegistry returns a new artifact file registry.
func NewJSONArtifactRegistry(fileName string, fs FileSystem) *JSONArtifactRegistry {
return &JSONArtifactRegistry{
Entries: make(map[string][]JsonArtifactRegistryEntry),
FilePath: fileName,
CurrentTimeProvider: func() time.Time {
return time.Now()
},
FileSystem: fs,
}
}
21 changes: 16 additions & 5 deletions fileartifactprocessor.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,13 +153,13 @@ func (p FileArtifactProcessor) processFileArtifact(ctx ArtifactProcessingContext

if fa.IsDir() {
ctx.Logger.Info(fmt.Sprintf("Creating directory %q ...", filePath))
ctx.Logger.Trace(fmt.Sprintf("making directory %q for %q ...", filePath, fa.ID()))
ctx.Logger.Trace(fmt.Sprintf("making directory %q for %q ...", filePath, fa.ID()))
if err := p.FileSystem.WriteFile(filePath, fa.Data, os.ModePerm); err != nil {
return err
}
} else {
ctx.Logger.Info(fmt.Sprintf("Writing file %q ...", filePath))
ctx.Logger.Trace(fmt.Sprintf("creating directory %q for %q ...", filePath, fa.ID()))
ctx.Logger.Trace(fmt.Sprintf("creating file %q for %q ...", filePath, fa.ID()))
if err := p.FileSystem.WriteFile(filePath, fa.Data, os.ModePerm); err != nil {
return err
}
Expand All @@ -183,20 +183,28 @@ func (p FileArtifactProcessor) cleanRegistry(ctx ArtifactProcessingContext) erro
var wg sync.WaitGroup
var errs errors.Group

ctx.Logger.Info(fmt.Sprintf("Cleaning file artifacts ..."))
entries, err := ctx.ArtifactRegistry.FindAll()
if err != nil {
return err
}

for _, entry := range entries {
if entry.Metadata == nil {
continue // TODO Error (?)
ctx.Logger.Trace(fmt.Sprintf("invalid registry entry %q: no metadata", entry.ArtifactID))
continue
}

writeMode, ok := entry.Metadata["writeMode"]
if !ok || writeMode != RecreateMode {
if ok {
ctx.Logger.Trace(fmt.Sprintf("invalid registry entry %q: no write mode", entry.ArtifactID))
continue
}

if writeMode != RecreateMode {
continue
}

wg.Add(1)
go func(entry ArtifactRegistryEntry) {
defer wg.Done()
Expand All @@ -214,13 +222,16 @@ func (p FileArtifactProcessor) cleanRegistry(ctx ArtifactProcessingContext) erro

func (p FileArtifactProcessor) cleanArtifact(ctx ArtifactProcessingContext, entry ArtifactRegistryEntry) error {
if entry.Metadata == nil {
return nil // TODO Error (?)
ctx.Logger.Trace(fmt.Sprintf("invalid registry entry %q: no metadata", entry.ArtifactID))
return nil
}
path, ok := entry.Metadata["path"].(string)
if !ok || path == "" {
ctx.Logger.Trace(fmt.Sprintf("invalid registry entry %q: no path", entry.ArtifactID))
return nil
}

ctx.Logger.Info(fmt.Sprintf(fmt.Sprintf("cleaning file artifact %q ...", entry.ArtifactID)))
if err := p.FileSystem.Remove(path); err != nil {
return err
}
Expand Down
13 changes: 8 additions & 5 deletions hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (l HCLGenericSpecLoader) Load(s Source) ([]Specification, error) {
}

file, diags := l.ParseHCL(s.Data, s.Location)
if diags.HasErrors() {
if diags != nil && diags.HasErrors() {
return nil, errors.Wrap(diags, InvalidHCLErrorCode)
}

Expand Down Expand Up @@ -115,7 +115,7 @@ func (l HCLGenericSpecLoader) extractAttributesFromBlock(ctx *hcl.EvalContext, b
// Detect attributes in current block.
for _, a := range block.Body.Attributes {
value, d := a.Expr.Value(ctx)
if d.HasErrors() {
if d != nil && d.HasErrors() {
d = append(diags, d...)
continue
}
Expand Down Expand Up @@ -206,7 +206,7 @@ func (l HCLSpecLoader) Load(s Source) ([]Specification, error) {
for _, b := range body.Blocks {
if b.Type == "const" {
v, d := b.Body.Attributes["value"].Expr.Value(ctx)
if d.HasErrors() {
if d != nil && d.HasErrors() {
diags = append(diags, d...)
} else {
ctx.Variables[b.Labels[0]] = v
Expand All @@ -219,11 +219,14 @@ func (l HCLSpecLoader) Load(s Source) ([]Specification, error) {
err := hclsimple.Decode(s.Location, s.Data, ctx, fileConf)

if err != nil {
d := err.(hcl.Diagnostics)
var d hcl.Diagnostics
if !errors.As(err, &d) {
return nil, err
}
diags = append(diags, d...)
}

if diags.HasErrors() {
if diags != nil && diags.HasErrors() {
return nil, diags
}

Expand Down
2 changes: 1 addition & 1 deletion logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func NewDefaultLogger(c DefaultLoggerConfig) *DefaultLogger {
}

func (l *DefaultLogger) Trace(msg string) {
l.Log(l.color.Faint(msg).String())
l.Log(l.color.Faint(fmt.Sprintf("--- %s", msg)).String())
}

func (l *DefaultLogger) Info(msg string) {
Expand Down
2 changes: 1 addition & 1 deletion logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func TestDefaultLogger_Trace(t *testing.T) {
})

logger.Trace("hello world")
assert.Equal(t, aurora.Faint("hello world").String()+"\n", string(buffer.Bytes()))
assert.Equal(t, aurora.Faint("--- hello world").String()+"\n", string(buffer.Bytes()))
}

func TestDefaultLogger_Info(t *testing.T) {
Expand Down
3 changes: 0 additions & 3 deletions source.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,6 @@ type FileSystemLoader struct {
fs FileSystem
}

func NewLocalFileSourceLoader() FileSystemLoader {
return FileSystemLoader{fs: LocalFileSystem{}}
}
func (l FileSystemLoader) Supports(target string) bool {
if target == "" {
return false
Expand Down
79 changes: 6 additions & 73 deletions specter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"github.com/morebec/go-errors/errors"
"os"
"time"
)

Expand Down Expand Up @@ -239,6 +238,12 @@ func (s Specter) ProcessArtifacts(ctx context.Context, specifications []Specific
return fmt.Errorf("failed loading artifact registry: %w", err)
}

defer func() {
if err := s.ArtifactRegistry.Save(); err != nil {
s.Logger.Error(fmt.Errorf("failed saving artifact registry: %w", err).Error())
}
}()

for _, p := range s.ArtifactProcessors {
if err := CheckContextDone(ctx); err != nil {
return err
Expand All @@ -262,78 +267,6 @@ func (s Specter) ProcessArtifacts(ctx context.Context, specifications []Specific
}
}

if err := s.ArtifactRegistry.Save(); err != nil {
return fmt.Errorf("failed saving artifact registry: %w", err)
}

s.Logger.Success("FindAll processed successfully.")
return nil
}

// New allows creating a new specter instance using the provided options.
func New(opts ...Option) *Specter {
s := &Specter{
Logger: NewDefaultLogger(DefaultLoggerConfig{DisableColors: true, Writer: os.Stdout}),
ExecutionMode: FullMode,
}
for _, o := range opts {
o(s)
}
return s
}

// Option represents an option to configure a specter instance.
type Option func(s *Specter)

// WithLogger configures the Logger of a Specter instance.
func WithLogger(l Logger) Option {
return func(s *Specter) {
s.Logger = l
}
}

// WithSourceLoaders configures the SourceLoader of a Specter instance.
func WithSourceLoaders(loaders ...SourceLoader) Option {
return func(s *Specter) {
s.SourceLoaders = append(s.SourceLoaders, loaders...)
}
}

// WithLoaders configures the SpecificationLoader of a Specter instance.
func WithLoaders(loaders ...SpecificationLoader) Option {
return func(s *Specter) {
s.Loaders = append(s.Loaders, loaders...)
}
}

// WithProcessors configures the SpecProcess of a Specter instance.
func WithProcessors(processors ...SpecificationProcessor) Option {
return func(s *Specter) {
s.Processors = append(s.Processors, processors...)
}
}

// WithArtifactProcessors configures the ArtifactProcessor of a Specter instance.
func WithArtifactProcessors(processors ...ArtifactProcessor) Option {
return func(s *Specter) {
s.ArtifactProcessors = append(s.ArtifactProcessors, processors...)
}
}

// WithExecutionMode configures the ExecutionMode of a Specter instance.
func WithExecutionMode(m ExecutionMode) Option {
return func(s *Specter) {
s.ExecutionMode = m
}
}
func WithArtifactRegistry(r ArtifactRegistry) Option {
return func(s *Specter) {
s.ArtifactRegistry = r
}
}

// Defaults

func WithDefaultLogger() Option {
return WithLogger(NewDefaultLogger(DefaultLoggerConfig{DisableColors: false, Writer: os.Stdout}))
}

0 comments on commit 45c04e4

Please sign in to comment.