Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cfg and stepper packages. #1

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/testing-push.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Testing push
on:
push:

jobs:
test-app:
name: Test Application
runs-on: ubuntu-latest
steps:
- name: Clone repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Test application
run: go test -v -race ./...
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2024 Kubefirst
Copyright (c) 2024 Konstruct

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.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# cli-utils
A collection of CLI utilities for Konstruct applications

A collection of CLI utilities for Konstruct applications.
218 changes: 218 additions & 0 deletions cfg/cfg.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
package cfg

import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sync"
)

// Config holds the configuration data and manages concurrent access.
type Config struct {
mu sync.RWMutex
data map[string]interface{}
file *os.File
path string
}

// New creates a new Config instance. If a file exists at the given path, it
// will be read and loaded into the Config instance.
func New(path string) (*Config, error) {
c := &Config{
path: path,
}

if err := c.readFromFile(); err != nil {
return nil, err
}

return c, nil
}

// readFromFile reads the configuration data from the file.
func (c *Config) readFromFile() error {
file, err := os.OpenFile(c.path, os.O_RDWR|os.O_CREATE, 0o644)
if err != nil {
return fmt.Errorf("unable to open config file: %w", err)
}

stat, err := file.Stat()
if err != nil {
file.Close()
return fmt.Errorf("unable to stat config file: %w", err)
}

var data map[string]interface{}
if stat.Size() > 0 {
if err := json.NewDecoder(file).Decode(&data); err != nil && err != io.EOF {
file.Close()
return fmt.Errorf("unable to decode config file as JSON: %w", err)
}
} else {
data = make(map[string]interface{})
}

// Move file pointer back to start
if _, err := file.Seek(0, 0); err != nil {
file.Close()
return fmt.Errorf("unable to seek config file: %w", err)
}

c.mu.Lock()
c.data = data
c.file = file
c.mu.Unlock()

return nil
}

// GetString returns a string value for the given key and a boolean indicating
// if the key exists.
func (c *Config) GetString(key string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()

val, ok := c.data[key]
if !ok {
return "", false
}
s, ok := val.(string)
return s, ok
}

// GetInt returns an int value for the given key and a boolean indicating
// if the key exists.
func (c *Config) GetInt(key string) (int, bool) {
c.mu.RLock()
defer c.mu.RUnlock()

val, ok := c.data[key]
if !ok {
return 0, false
}

var i int
switch v := val.(type) {
case float64:
i = int(v)
case int:
i = v
default:
return 0, false
}

return i, true
}

// GetFloat64 returns a float64 value for the given key and a boolean indicating
// if the key exists.
func (c *Config) GetFloat64(key string) (float64, bool) {
c.mu.RLock()
defer c.mu.RUnlock()

val, ok := c.data[key]
if !ok {
return 0.0, false
}

v, ok := val.(float64)
return v, ok
}

// GetBool returns a bool value for the given key and a boolean indicating
// if the key exists.
func (c *Config) GetBool(key string) (bool, bool) {
c.mu.RLock()
defer c.mu.RUnlock()

val, ok := c.data[key]
if !ok {
return false, false
}

v, ok := val.(bool)
return v, ok
}

// Set stores a value and flushes changes immediately to disk.
func (c *Config) Set(key string, value interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()

// Normalize ints/floats to float64 for consistency
switch v := value.(type) {
case int:
value = float64(v)
case int32:
value = float64(v)
case int64:
value = float64(v)
case float32:
value = float64(v)
case string, bool, float64:
// All supported types
default:
return fmt.Errorf("unsupported type: %T", value)
}

c.data[key] = value
return c.flushUnsafeLocked()
}

// Finish flushes (if needed) and closes the file.
func (c *Config) Finish() error {
c.mu.Lock()
defer c.mu.Unlock()

if c.file == nil {
return errors.New("config file already closed")
}

if err := c.flushUnsafeLocked(); err != nil {
return fmt.Errorf("failed to flush config: %w", err)
}

if err := c.file.Close(); err != nil {
return fmt.Errorf("failed to close config file: %w", err)
}
c.file = nil

return nil
}

// flushUnsafeLocked writes the current data to disk.
// Call with c.mu.Lock() held.
func (c *Config) flushUnsafeLocked() error {
if c.file == nil {
return errors.New("config file not available")
}
if err := c.file.Truncate(0); err != nil {
return err
}
if _, err := c.file.Seek(0, 0); err != nil {
return err
}

if err := json.NewEncoder(c.file).Encode(c.data); err != nil {
return err
}
return c.file.Sync()
}

// GetAll returns a copy of the configuration data.
func (c *Config) GetAll() (map[string]interface{}, error) {
if err := c.readFromFile(); err != nil {
return nil, err
}

returned := make(map[string]interface{}, len(c.data))
c.mu.RLock()
for k, v := range c.data {
returned[k] = v
}
c.mu.RUnlock()

return returned, nil
}
Loading
Loading