Skip to content

Commit

Permalink
🎉 (SETUP) The first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitor Hugo committed Sep 7, 2023
0 parents commit 849dc25
Show file tree
Hide file tree
Showing 7 changed files with 416 additions and 0 deletions.
9 changes: 9 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# MIT License

Copyright (c) 2023 Vitor Hugo de O. Vargas

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# 🌩 Zeus - Simple Dependency Injection Container

`Zeus` is a sleek and efficient dependency injection container for Go. Easily register "factories" (functions that create instances of types) and let zeus resolve those dependencies at runtime.

## 🌟 Features

### 🚀 Simple to Use

With a minimalist API, integrating zeus into any Go project is a breeze.

### 🔍 Dependency Resolution

Register your dependencies and let zeus handle the rest.

### ⚠️ Cyclic Dependency Detection

Zeus detects and reports cycles in your dependencies to prevent runtime errors.

## 🚀 Getting Started

### Installation

```bash
go get -u github.com/otoru/zeus
```

### Register Dependencies

```go
package main

import "github.com/otoru/zeus"

c := zeus.New()

c.Provide(func() int {
return 42
})

c.Provide(func(i int) string {
return fmt.Sprintf("Number: %d", i)
})
```

### Resolve & Run Functions

```go
err := c.Run(func(s string) error {
fmt.Println(s) // Outputs: Number: 42
return nil
})
```

## 🤝 Contributing

Contributions are warmly welcomed! Please open a PR or an issue if you find any problems or have enhancement suggestions.
117 changes: 117 additions & 0 deletions container.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package zeus

import (
"reflect"

"golang.org/x/exp/slices"
)

type Container struct {
providers map[reflect.Type]reflect.Value
}

func (c *Container) Provide(factory interface{}) error {
factoryType := reflect.TypeOf(factory)

if factoryType.Kind() != reflect.Func {
return NotAFunctionError{}
}

if numOut := factoryType.NumOut(); numOut < 1 || numOut > 2 {
return InvalidFactoryReturnError{NumReturns: numOut}
}

if factoryType.NumOut() == 2 && factoryType.Out(1).Name() != "error" {
return UnexpectedReturnTypeError{TypeName: factoryType.Out(1).Name()}
}

serviceType := factoryType.Out(0)

if _, exists := c.providers[serviceType]; exists {
return FactoryAlreadyProvidedError{TypeName: serviceType.Name()}
}

c.providers[serviceType] = reflect.ValueOf(factory)

return nil
}

func (c *Container) resolve(t reflect.Type, stack []reflect.Type) (reflect.Value, error) {
if slices.Contains(stack, t) {
return reflect.Value{}, CyclicDependencyError{TypeName: t.Name()}
}

provider, ok := c.providers[t]

if !ok {
return reflect.Value{}, DependencyResolutionError{TypeName: t.Name()}
}

providerType := provider.Type()
dependencies := make([]reflect.Value, providerType.NumIn())

for i := range dependencies {
argType := providerType.In(i)
argValue, err := c.resolve(argType, append(stack, t))

if err != nil {
return reflect.Value{}, err
}

dependencies[i] = argValue
}

results := provider.Call(dependencies)

if len(results) == 2 && !results[1].IsNil() {
return reflect.Value{}, results[1].Interface().(error)
}

return results[0], nil
}

func (c *Container) Run(fn interface{}) error {
fnType := reflect.TypeOf(fn)

if fnType.Kind() != reflect.Func {
return NotAFunctionError{}
}

if numOut := fnType.NumOut(); numOut > 1 {
return InvalidFactoryReturnError{NumReturns: numOut}
}

if fnType.NumOut() == 1 && fnType.Out(0).Name() != "error" {
return UnexpectedReturnTypeError{TypeName: fnType.Out(0).Name()}
}

dependencies := make([]reflect.Value, fnType.NumIn())

for i := range dependencies {
argType := fnType.In(i)
argValue, err := c.resolve(argType, nil)

if err != nil {
return err
}

dependencies[i] = argValue
}

results := reflect.ValueOf(fn).Call(dependencies)

if fnType.NumOut() == 1 && !results[0].IsNil() {
return results[0].Interface().(error)
}

return nil
}

func New() *Container {
providers := make(map[reflect.Type]reflect.Value, 0)

container := new(Container)
container.providers = providers

return container
}
169 changes: 169 additions & 0 deletions container_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package zeus

import (
"fmt"
"reflect"
"testing"

"gotest.tools/v3/assert"
)

func TestContainer(t *testing.T) {
t.Parallel()

t.Run("Provide", func(t *testing.T) {
t.Run("Not a function", func(t *testing.T) {
c := New()
got := c.Provide("string")
expected := NotAFunctionError{}
assert.ErrorIs(t, got, expected)
})

t.Run("Invalid return count", func(t *testing.T) {
c := New()
got := c.Provide(func() (int, string, error) { return 0, "", nil })
expected := InvalidFactoryReturnError{NumReturns: 3}

assert.ErrorIs(t, got, expected)
})

t.Run("Second return value not is a error", func(t *testing.T) {
c := New()
got := c.Provide(func() (int, string) { return 0, "" })
expected := UnexpectedReturnTypeError{TypeName: "string"}

assert.ErrorIs(t, got, expected)
})

t.Run("Valid factory", func(t *testing.T) {
c := New()
err := c.Provide(func() int { return 0 })

assert.NilError(t, err)
})

t.Run("Duplicated factory", func(t *testing.T) {
c := New()
c.Provide(func() int { return 0 })
got := c.Provide(func() int { return 1 })
expected := FactoryAlreadyProvidedError{TypeName: "int"}

assert.ErrorIs(t, got, expected)
})
})

t.Run("resolve", func(t *testing.T) {
t.Run("Cyclic dependency", func(t *testing.T) {
c := New()
c.Provide(func(s string) string { return s })
_, err := c.resolve(reflect.TypeOf(""), []reflect.Type{reflect.TypeOf("")})
expected := CyclicDependencyError{TypeName: "string"}

assert.ErrorIs(t, err, expected)
})

t.Run("Unresolved dependency", func(t *testing.T) {
c := New()
_, err := c.resolve(reflect.TypeOf(0.0), nil)
expected := DependencyResolutionError{TypeName: "float64"}

assert.ErrorIs(t, err, expected)
})

t.Run("Successful resolution", func(t *testing.T) {
c := New()
c.Provide(func() int { return 42 })
c.Provide(func(i int) string { return "Hello" })
val, err := c.resolve(reflect.TypeOf(""), nil)

assert.NilError(t, err)
assert.Equal(t, val.String(), "Hello")
})

t.Run("Recursive Call Error - Unresolved Dependency", func(t *testing.T) {
c := New()
c.Provide(func(f float64) int { return int(f) })
_, err := c.resolve(reflect.TypeOf(0), nil)
expected := DependencyResolutionError{TypeName: "float64"}

assert.ErrorIs(t, err, expected)
})

t.Run("Recursive call error - cyclic dependency", func(t *testing.T) {
c := New()
c.Provide(func(s string) int { return len(s) })
c.Provide(func(i int) string { return fmt.Sprint(i) })
_, err := c.resolve(reflect.TypeOf(0), nil)
expected := CyclicDependencyError{TypeName: "int"}

assert.ErrorIs(t, err, expected)
})

t.Run("Factory returns a error", func(t *testing.T) {
c := New()
c.Provide(func() (int, error) { return 0, fmt.Errorf("some error") })
_, err := c.resolve(reflect.TypeOf(0), nil)

assert.ErrorContains(t, err, "some error")
})
})

t.Run("Run", func(t *testing.T) {
t.Run("Not a function", func(t *testing.T) {
c := New()
err := c.Run("not a function")
expected := NotAFunctionError{}

assert.ErrorIs(t, err, expected)
})

t.Run("Invalid return", func(t *testing.T) {
c := New()
err := c.Run(func() (int, string) { return 0, "" })
expected := InvalidFactoryReturnError{NumReturns: 2}

assert.ErrorIs(t, err, expected)
})

t.Run("Function returns a non-error value", func(t *testing.T) {
c := New()
err := c.Run(func() int { return 42 })
expected := UnexpectedReturnTypeError{TypeName: "int"}

assert.ErrorIs(t, err, expected)
})

t.Run("Successful execution", func(t *testing.T) {
c := New()
c.Provide(func() int { return 42 })

err := c.Run(func(i int) error {
if i != 42 {
return fmt.Errorf("expected 42, got %d", i)
}
return nil
})

assert.NilError(t, err)
})

t.Run("Function returns a error", func(t *testing.T) {
c := New()
c.Provide(func() int { return 42 })
err := c.Run(func(i int) error {
return fmt.Errorf("some error")
})

assert.ErrorContains(t, err, "some error")
})

t.Run("Dependency resolution error", func(t *testing.T) {
c := New()
err := c.Run(func(f float64) error { return nil })
expected := DependencyResolutionError{TypeName: "float64"}

assert.ErrorIs(t, err, expected)
})

})
}
Loading

0 comments on commit 849dc25

Please sign in to comment.