Skip to content

Commit

Permalink
Removed zap (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
germanosin authored Jul 26, 2024
1 parent 291c38e commit 00eae86
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 74 deletions.
2 changes: 1 addition & 1 deletion cmd/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func NewEvalCmd(appConfig *app.AppConfig) *cobra.Command {
cmd.Context(),
pkl.WithProject(appConfig.Project()),
pkl.PreconfiguredOptions,
pklutils.WithVals(appConfig.Logger),
pklutils.WithVals(),
func(opts *pkl.EvaluatorOptions) {
opts.CacheDir = appConfig.CacheDir
if appConfig.RootDir != "" {
Expand Down
5 changes: 2 additions & 3 deletions cmd/package.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"errors"
"os/exec"

"github.com/spf13/cobra"
Expand All @@ -13,8 +14,6 @@ func NewPackageCmd(appConfig *app.AppConfig) *cobra.Command {
Short: "Package hpkl project",
RunE: func(cmd *cobra.Command, args []string) error {

sugar := appConfig.Logger.Sugar()

pklCmd := exec.Command(
"pkl",
"project",
Expand All @@ -29,7 +28,7 @@ func NewPackageCmd(appConfig *app.AppConfig) *cobra.Command {

if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
sugar.Error(string(ee.Stderr))
return errors.New(string(ee.Stderr))
}
return err
}
Expand Down
8 changes: 3 additions & 5 deletions cmd/publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ import (

func NewPublishCmd(appConfig *app.AppConfig) *cobra.Command {

logger := appConfig.Logger

cmd := &cobra.Command{
Use: "publish",
Short: "publish package to oci registry",
RunE: func(cmd *cobra.Command, args []string) error {

sugar := appConfig.Logger.Sugar()

name := appConfig.Project().Package.Name
version := appConfig.Project().Package.Version
baseUri := appConfig.Project().Package.BaseUri
Expand All @@ -36,15 +36,13 @@ func NewPublishCmd(appConfig *app.AppConfig) *cobra.Command {
return err
}

sugar.Infof("generated", "ref", ref)

pushResult, err := client.Push(archivePath, metadataPath, ref, appConfig.Project())

if err != nil {
return err
}

sugar.Infow("got", "pushResult", pushResult)
logger.Info("Publish result: %+v", pushResult)

return nil
},
Expand Down
4 changes: 3 additions & 1 deletion cmd/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@ import (

func NewResolveCmd(appConfig *app.AppConfig) *cobra.Command {

logger := appConfig.Logger

cmd := &cobra.Command{
Use: "resolve",
Short: "Resolve all dependencies from pkl project",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
for _, v := range args {
appConfig.Logger.Sugar().Infow("Resolving", "path", v)
logger.Info("Resolving path: %s", v)
appConfig.WorkingDir = v
appConfig.Reset()
err := Resolve(appConfig)
Expand Down
7 changes: 5 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ func Execute() {
}

func init() {
// TODO: context?
appConfig, err := app.NewAppConfig(context.Background())
appConfig, err := app.NewAppConfig(
context.Background(),
rootCmd.OutOrStdout(),
rootCmd.OutOrStderr(),
)

if err != nil {
log.Fatal("Error starting app: ", err)
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ require (
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.8.0
go.szostok.io/version v1.2.0
go.uber.org/zap v1.27.0
oras.land/oras-go v1.2.5
)

Expand Down
12 changes: 4 additions & 8 deletions pkg/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package app

import (
"context"
"io"
"path"

"github.com/apple/pkl-go/pkl"
"go.uber.org/zap"
)

type AppConfig struct {
Logger *zap.Logger
Logger *Logger
project *pkl.Project
ctx context.Context
PlainHttp bool
Expand Down Expand Up @@ -42,13 +42,9 @@ func (a *AppConfig) Reset() {
a.project = nil
}

func NewAppConfig(ctx context.Context) (*AppConfig, error) {
func NewAppConfig(ctx context.Context, outWriter io.Writer, errWriter io.Writer) (*AppConfig, error) {

logger, err := NewLogger()

if err != nil {
return nil, err
}
logger := NewLogger(outWriter, errWriter)

return &AppConfig{
Logger: logger,
Expand Down
46 changes: 21 additions & 25 deletions pkg/app/logger.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
package app

import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"fmt"
"io"
)

func NewLogger() (*zap.Logger, error) {
return newConfig().Build()
type Logger struct {
out io.Writer
err io.Writer
}

func newConfig() zap.Config {
return zap.Config{
Level: zap.NewAtomicLevelAt(zap.InfoLevel),
Development: false,
Encoding: "console",
EncoderConfig: zapcore.EncoderConfig{
TimeKey: "ts",
LevelKey: "level",
NameKey: "logger",
CallerKey: zapcore.OmitKey,
FunctionKey: zapcore.OmitKey,
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
},
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
func NewLogger(outWriter io.Writer, errWriter io.Writer) *Logger {
return &Logger{
out: outWriter,
err: errWriter,
}
}

func (l *Logger) Log(def io.Writer, s string, a ...any) {
fmt.Fprintln(def, fmt.Sprintf(s, a...))
}

func (l *Logger) Info(s string, a ...any) {
l.Log(l.out, s, a...)
}

func (l *Logger) Error(s string, a ...any) {
l.Log(l.err, s, a...)
}
42 changes: 21 additions & 21 deletions pkg/app/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"path"
"strings"

"go.uber.org/zap"
"hpkl.io/hpkl/pkg/pklutils"
"hpkl.io/hpkl/pkg/registry"
)
Expand Down Expand Up @@ -47,7 +46,7 @@ type (
httpResolver *HttpResolver
basePath string
cache map[string]*Metadata
appConfig *AppConfig
config *AppConfig
}

DependencyResolver interface {
Expand All @@ -58,12 +57,12 @@ type (
OciResolver struct {
client *registry.Client
plainClient *registry.Client
logger *zap.Logger
config *AppConfig
}

HttpResolver struct {
config *AppConfig
plainHttp bool
logger *zap.Logger
}

ResolvedDependency struct {
Expand Down Expand Up @@ -100,27 +99,26 @@ func NewResolver(appConfig *AppConfig) (*Resolver, error) {
ociResolver: oci,
httpResolver: http,
basePath: path.Join(appConfig.CacheDir, "package-2"),
appConfig: appConfig,
config: appConfig,
cache: make(map[string]*Metadata),
}, nil
}

func (r *Resolver) Resolve(dependencies map[string]Dependency) (map[string]*Metadata, error) {
logger := r.config.Logger
result := make(map[string]*Metadata)

logger := r.appConfig.Logger.Sugar()

for _, dependency := range dependencies {
metadata, ok := r.cache[dependency.Uri]
dependencyName := dependency.Name
if !ok {
var resolver DependencyResolver

if strings.HasSuffix(dependencyName, ".oci") {
logger.Infow("Resolving", "name", dependencyName, "as", dependency, "proto", "oci")
logger.Info("Resolving: %s as %+v proto: oci", dependencyName, dependency)
resolver = r.ociResolver
} else {
logger.Infow("Resolving", "name", dependencyName, "as", dependency, "proto", "http")
logger.Info("Resolving: %s as %+v proto: http", dependencyName, dependency)
resolver = r.httpResolver
}

Expand All @@ -134,7 +132,7 @@ func (r *Resolver) Resolve(dependencies map[string]Dependency) (map[string]*Meta
}

if err != nil {
logger.Errorw("Metadata resolving error", "name", dependencyName, "value", dependency)
logger.Error("Metadata resolving error: %s - %+v", dependencyName, dependency)
return nil, err
}

Expand Down Expand Up @@ -182,7 +180,9 @@ func (r *Resolver) Exists(metadata *Metadata) (bool, error) {
}

func (r *Resolver) Download(dependencies map[string]*Metadata) error {
logger := r.appConfig.Logger.Sugar()

logger := r.config.Logger

for u, m := range dependencies {
e, err := r.Exists(m)

Expand All @@ -194,10 +194,10 @@ func (r *Resolver) Download(dependencies map[string]*Metadata) error {
var resolver DependencyResolver

if m.ResolverType == OCI {
logger.Infow("Downloading", "name", u, "as", m, "proto", "oci")
logger.Info("Downloading %s as %+v proto: oci", u, m)
resolver = r.ociResolver
} else {
logger.Infow("Resolving", "name", u, "as", m, "proto", "http")
logger.Info("Downloading %s as %+v proto: http", u, m)
resolver = r.httpResolver
}

Expand Down Expand Up @@ -254,7 +254,7 @@ func NewOciResolver(appConfig *AppConfig) (*OciResolver, error) {
return nil, err
}

return &OciResolver{client: client, plainClient: plainClient, logger: appConfig.Logger}, nil
return &OciResolver{client: client, plainClient: plainClient, config: appConfig}, nil
}

func (r *OciResolver) ResolveMetadata(uri string, plainHttp bool) (*Metadata, error) {
Expand Down Expand Up @@ -307,15 +307,16 @@ func (r *OciResolver) ResolveArchive(metadata *Metadata) ([]byte, error) {
}

func NewHttpResolver(appConfig *AppConfig) *HttpResolver {
return &HttpResolver{plainHttp: appConfig.PlainHttp, logger: appConfig.Logger}
return &HttpResolver{plainHttp: appConfig.PlainHttp, config: appConfig}
}

func (r *HttpResolver) ResolveMetadata(uri string, plainHttp bool) (*Metadata, error) {
logger := r.logger.Sugar()

u, err := url.Parse(uri)
logger := r.config.Logger

if err != nil {
logger.Errorw("Parsing error", "uri", uri)
logger.Error("Parsing error %s", uri)
return nil, err
}

Expand All @@ -328,21 +329,20 @@ func (r *HttpResolver) ResolveMetadata(uri string, plainHttp bool) (*Metadata, e
resp, err := http.Get(u.String())

if err != nil {
logger.Errorw("Http get error", "uri", u.String())
logger.Error("Http get error %s", u.String())
return nil, err
}

if resp.StatusCode > 300 {
logger.Errorw("Http error", "resp", resp.Status)
return nil, fmt.Errorf("Http get Error")
return nil, fmt.Errorf("Http get Error status: %s", resp.Status)
}

defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)

var metadata *Metadata
if err := json.Unmarshal(body, &metadata); err != nil {
logger.Errorw("Json unmarshal error", "data", body)
logger.Error("Json unmarshal error: %s", body)
return nil, err
}

Expand Down
5 changes: 2 additions & 3 deletions pkg/pklutils/vals.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ package pklutils

import (
"github.com/apple/pkl-go/pkl"
"go.uber.org/zap"
"hpkl.io/hpkl/pkg/vals"
)

func WithVals(logger *zap.Logger) func(options *pkl.EvaluatorOptions) {
valsReader, err := vals.NewValsReader(logger)
func WithVals() func(options *pkl.EvaluatorOptions) {
valsReader, err := vals.NewValsReader()

if err != nil {
panic(err)
Expand Down
5 changes: 1 addition & 4 deletions pkg/vals/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import (

"github.com/apple/pkl-go/pkl"
"github.com/helmfile/vals"
"go.uber.org/zap"
)

func NewValsReader(logger *zap.Logger) (*ValsReader, error) {
func NewValsReader() (*ValsReader, error) {
runtime, err := ValsInstance()

if err != nil {
Expand All @@ -17,13 +16,11 @@ func NewValsReader(logger *zap.Logger) (*ValsReader, error) {

return &ValsReader{
Runtime: runtime,
Logger: logger,
}, nil
}

type ValsReader struct {
Runtime *vals.Runtime
Logger *zap.Logger
}

func (r *ValsReader) Read(url url.URL) ([]byte, error) {
Expand Down

0 comments on commit 00eae86

Please sign in to comment.