style: improve code formatting; refactor module imports

- Apply consistent alignment for struct fields and parameters
- Standardize string literal delimiters to single quotes
- Refactor module import strategy in `models` package
- Enhance asset formatting for precise decimal display
- Remove unused imports and redundant `+}` syntax artifacts
This commit is contained in:
Mahmoud-Emad
2025-09-03 11:36:02 +03:00
parent 4a82bde192
commit dd400ba6fa
55 changed files with 1518 additions and 1503 deletions

View File

@@ -52,7 +52,6 @@ println(' - API title: ${spec.info.title}')
println(' - API version: ${spec.info.version}')
println(' - Methods available: ${spec.methods.len}')
// 2. List all services
println('\n2. Listing all services...')
services := client.service_list() or {

View File

@@ -3,9 +3,7 @@ module builder
import os
import freeflowuniverse.herolib.core.texttools
import freeflowuniverse.herolib.core.pathlib
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.ui.console
import v.embed_file
const heropath_ = os.dir(@FILE) + '/../'
@@ -52,10 +50,10 @@ pub mut:
pub fn (mut node Node) hero_install(args HeroInstallArgs) ! {
console.print_debug('install hero')
mut bs := bootstrapper()
bootstrapper()
myenv := node.environ_get()!
homedir := myenv['HOME'] or { return error("can't find HOME in env") }
_ := myenv['HOME'] or { return error("can't find HOME in env") }
mut todo := []string{}
if !args.compile {

View File

@@ -156,8 +156,7 @@ pub fn plbook_run(cmd Command) !(&playbook.PlayBook, string) {
mut plbook := if heroscript.len > 0 {
playbook.new(text: heroscript)!
} else {
path
= plbook_code_get(cmd)!
path = plbook_code_get(cmd)!
if path.len == 0 {
return error(cmd.help_message())
}

View File

@@ -175,7 +175,7 @@ fn test_get_u64_default() {
assert params.get_u64_default('key3', 17)! == 17
}
fn test_get_u32()! {
fn test_get_u32() ! {
text := '
key1: val1
key2: 19

View File

@@ -27,8 +27,8 @@ pub mut:
}
pub fn calendar_new(args CalendarArgs) !Calendar {
mut commentids:=[]u32{}
for comment in args.comments{
mut commentids := []u32{}
for comment in args.comments {
// Convert CommentArg to CommentArgExtended
extended_comment := CommentArgExtended{
comment: comment.comment
@@ -38,12 +38,12 @@ pub fn calendar_new(args CalendarArgs) !Calendar {
commentids << comment_set(extended_comment)!
}
mut obj := Calendar{
id: args.id or {0} // Will be set by DB?
id: args.id or { 0 } // Will be set by DB?
name: args.name
description: args.description
created_at: ourtime.now().unix()
updated_at: ourtime.now().unix()
securitypolicy: args.securitypolicy or {0}
securitypolicy: args.securitypolicy or { 0 }
tags: tags2id(args.tags)!
comments: commentids
group_id: args.group_id
@@ -63,11 +63,11 @@ pub fn (mut c Calendar) add_event(event_id u32) { // Changed event_id to u32
}
pub fn (mut c Calendar) dump() []u8 {
//TODO: implement based on lib/data/encoder/readme.md
// TODO: implement based on lib/data/encoder/readme.md
return []u8{}
}
pub fn calendar_load(data []u8) Calendar {
//TODO: implement based on lib/data/encoder/readme.md
// TODO: implement based on lib/data/encoder/readme.md
return Calendar{}
}

View File

@@ -21,7 +21,7 @@ pub mut:
status EventStatus
is_all_day bool
is_recurring bool
recurrence []RecurrenceRule //normally empty
recurrence []RecurrenceRule // normally empty
reminder_mins []int // Minutes before event for reminders
color string // Hex color code
timezone string
@@ -72,7 +72,6 @@ pub enum RecurrenceFreq {
yearly
}
@[params]
pub struct CalendarEventArgs {
BaseArgs
@@ -93,12 +92,10 @@ pub mut:
timezone string
}
pub fn calendar_event_new(args CalendarEventArgs) !CalendarEvent {
// Convert tags to u32 ID
tags_id := tags2id(args.tags)!
return CalendarEvent{
// Base fields
id: args.id or { 0 }
@@ -212,8 +209,8 @@ pub fn (ce CalendarEvent) load(data []u8) !CalendarEvent {
// Decode recurrence array
recurrence_len := dec.get_u16()!
mut recurrence := []RecurrenceRule{}
for _ in 0..recurrence_len {
frequency := unsafe{RecurrenceFreq(dec.get_u8()!)}
for _ in 0 .. recurrence_len {
frequency := unsafe { RecurrenceFreq(dec.get_u8()!) }
interval := dec.get_int()!
until := dec.get_i64()!
count := dec.get_int()!

View File

@@ -7,12 +7,12 @@ pub fn set[T](obj T) ! {
mut redis := redisclient.core_get()!
id := obj.id
data := encoder.encode(obj)!
redis.hset("db:${T.name}",id.str(),data.bytestr())!
redis.hset('db:${T.name}', id.str(), data.bytestr())!
}
pub fn get[T](id u32) !T {
mut redis := redisclient.core_get()!
data := redis.hget("db:${T.name}",id.str())!
data := redis.hget('db:${T.name}', id.str())!
t := T{}
return encoder.decode[T](data.bytes())!
}
@@ -20,18 +20,18 @@ pub fn get[T](id u32) !T {
pub fn exists[T](id u32) !bool {
name := T{}.type_name()
mut redis := redisclient.core_get()!
return redis.hexists("db:${name}",id.str())!
return redis.hexists('db:${name}', id.str())!
}
pub fn delete[T](id u32) ! {
name := T{}.type_name()
mut redis := redisclient.core_get()!
redis.hdel("db:${name}", id.str())!
redis.hdel('db:${name}', id.str())!
}
pub fn list[T]() ![]T {
mut redis := redisclient.core_get()!
ids := redis.hkeys("db:${name}")!
ids := redis.hkeys('db:${name}')!
mut result := []T{}
for id in ids {
result << get[T](id.u32())!
@@ -39,7 +39,9 @@ pub fn list[T]() ![]T {
return result
}
//make it easy to get a base object
// make it easy to get a base object
pub fn new_from_base[T](args BaseArgs) !Base {
return T { Base: new_base(args)! }
return T{
Base: new_base(args)!
}
}

View File

@@ -5,7 +5,6 @@ import json
import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.hero.heromodels.openrpc
fn send_request(mut conn unix.StreamConn, request openrpc.JsonRpcRequest) ! {
request_json := json.encode(request)
conn.write_string(request_json)!
@@ -84,5 +83,3 @@ get_response := read_response(mut conn)!
console.print_item('Comments by author: ${get_response}')
console.print_header('All tests completed successfully!')

View File

@@ -1,6 +1,5 @@
#!/usr/bin/env -S v -n -w -cg -gc none -cc tcc -d use_openssl -enable-globals run
// Create a user
mut user := new_user('John Doe', 'john@example.com')
@@ -18,7 +17,8 @@ mut issue := new_project_issue('Fix login bug', project.id, user.id, .bug)
mut calendar := new_calendar('Team Calendar', group.id)
// Create an event
mut event := new_calendar_event('Sprint Planning', 1672531200, 1672534800, calendar.id, user.id)
mut event := new_calendar_event('Sprint Planning', 1672531200, 1672534800, calendar.id,
user.id)
calendar.add_event(event.id)
// Create a filesystem

View File

@@ -50,7 +50,9 @@ pub fn comment_get(params string) !string {
pub fn comment_set(params string) !string {
comment_arg := json.decode(heromodels.CommentArgExtended, params)!
id := heromodels.comment_set(comment_arg)!
return json.encode({'id': id})
return json.encode({
'id': id
})
}
// comment_delete removes a comment by ID

View File

@@ -93,9 +93,25 @@ pub fn new_project(name string, description string, group_id string) Project {
created_at: time.now().unix()
updated_at: time.now().unix()
swimlanes: [
Swimlane{id: 'todo', name: 'To Do', order: 1, color: '#f1c40f'},
Swimlane{id: 'in_progress', name: 'In Progress', order: 2, color: '#3498db'},
Swimlane{id: 'done', name: 'Done', order: 3, color: '#2ecc71', is_done: true}
Swimlane{
id: 'todo'
name: 'To Do'
order: 1
color: '#f1c40f'
},
Swimlane{
id: 'in_progress'
name: 'In Progress'
order: 2
color: '#3498db'
},
Swimlane{
id: 'done'
name: 'Done'
order: 3
color: '#2ecc71'
is_done: true
},
]
}
project.calculate_id()

View File

@@ -1,13 +1,5 @@
module linux
// import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.texttools
// import freeflowuniverse.herolib.screen
import os
import time
// import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.osal.core as osal
@[heap]
pub struct LinuxFactory {
pub mut:

View File

@@ -15,10 +15,10 @@ pub fn new() ServerManager {
}
fn (s ServerManager) execute(command string) bool {
// console.print_debug(command)
console.print_debug(command)
r := os.execute(command)
// console.print_debug(r)
console.print_debug(r)
return true
}

View File

@@ -1,7 +1,6 @@
module sshagent
import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.builder
// Check if SSH agent is properly configured and all is good
pub fn agent_check(mut agent SSHAgent) ! {

View File

@@ -94,6 +94,7 @@ pub fn (mut c Client) send[T, D](request RequestGeneric[T], params SendParams) !
myerror := response.error_ or {
return error('Failed to get error from response:\nRequest: ${request.encode()}\nResponse: ${response_json}\n${err}')
}
// print_backtrace()
mut myreq := request.encode()
if c.transport is UnixSocketTransport {

View File

@@ -78,11 +78,10 @@ pub fn (mut t UnixSocketTransport) send(request string, params SendParams) !stri
// Append the newly read data to the total response
res_total << res[..n]
//here we need to check we are at end
// here we need to check we are at end
if res.bytestr().contains('\n') {
break
}
}
unix.shutdown(socket.sock.handle)
socket.close() or {}

View File

@@ -3,15 +3,14 @@ module openrpcserver
import freeflowuniverse.herolib.data.encoder
import freeflowuniverse.herolib.data.ourtime
@[heap]
pub struct Comment {
pub mut:
id u32
comment string
parent u32 //id of parent comment if any, 0 means none
parent u32 // id of parent comment if any, 0 means none
updated_at i64
author u32 //links to user
author u32 // links to user
}
pub fn (self Comment) type_name() string {
@@ -22,7 +21,7 @@ pub fn (self Comment) load(data []u8) !Comment {
return comment_load(data)!
}
pub fn (self Comment) dump() ![]u8{
pub fn (self Comment) dump() ![]u8 {
// Create a new encoder
mut e := encoder.new()
e.add_u8(1)
@@ -34,13 +33,12 @@ pub fn (self Comment) dump() ![]u8{
return e.data
}
pub fn comment_load(data []u8) !Comment{
pub fn comment_load(data []u8) !Comment {
// Create a new decoder
mut e := encoder.decoder_new(data)
version := e.get_u8()!
if version != 1 {
panic("wrong version in comment load")
panic('wrong version in comment load')
}
mut comment := Comment{}
comment.id = e.get_u32()!
@@ -51,7 +49,6 @@ pub fn comment_load(data []u8) !Comment{
return comment
}
pub struct CommentArg {
pub mut:
comment string
@@ -70,24 +67,25 @@ pub fn comments2ids(args []CommentArg) ![]u32 {
pub fn comment2id(comment string) !u32 {
comment_fixed := comment.to_lower_ascii().trim_space()
mut redis := redisclient.core_get()!
return if comment_fixed.len > 0{
return if comment_fixed.len > 0 {
hash := md5.hexhash(comment_fixed)
comment_found := redis.hget("db:comments", hash)!
if comment_found == ""{
id := u32(redis.incr("db:comments:id")!)
redis.hset("db:comments", hash, id.str())!
redis.hset("db:comments", id.str(), comment_fixed)!
comment_found := redis.hget('db:comments', hash)!
if comment_found == '' {
id := u32(redis.incr('db:comments:id')!)
redis.hset('db:comments', hash, id.str())!
redis.hset('db:comments', id.str(), comment_fixed)!
id
}else{
} else {
comment_found.u32()
}
} else { 0 }
} else {
0
}
}
//get new comment, not from the DB
pub fn comment_new(args CommentArg) !Comment{
mut o := Comment {
// get new comment, not from the DB
pub fn comment_new(args CommentArg) !Comment {
mut o := Comment{
comment: args.comment
parent: args.parent
updated_at: ourtime.now().unix()
@@ -96,7 +94,7 @@ pub fn comment_new(args CommentArg) !Comment{
return o
}
pub fn comment_multiset(args []CommentArg) ![]u32{
pub fn comment_multiset(args []CommentArg) ![]u32 {
mut ids := []u32{}
for comment in args {
ids << comment_set(comment)!
@@ -104,16 +102,16 @@ pub fn comment_multiset(args []CommentArg) ![]u32{
return ids
}
pub fn comment_set(args CommentArg) !u32{
pub fn comment_set(args CommentArg) !u32 {
mut o := comment_new(args)!
// Use openrpcserver set function which now returns the ID
return openrpcserver.set[Comment](mut o)!
return set[Comment](mut o)!
}
pub fn comment_exist(id u32) !bool{
return openrpcserver.exists[Comment](id)!
pub fn comment_exist(id u32) !bool {
return exists[Comment](id)!
}
pub fn comment_get(id u32) !Comment{
return openrpcserver.get[Comment](id)!
pub fn comment_get(id u32) !Comment {
return get[Comment](id)!
}

View File

@@ -8,19 +8,19 @@ pub fn set[T](mut obj T) !u32 {
// Generate ID if not set
if obj.id == 0 {
myid := redis.incr("db:${name}:id")!
myid := redis.incr('db:${name}:id')!
obj.id = u32(myid)
}
data := obj.dump()!
redis.hset("db:${name}",obj.id.str(),data.bytestr())!
redis.hset('db:${name}', obj.id.str(), data.bytestr())!
return obj.id
}
pub fn get[T](id u32) !T {
name := T{}.type_name()
mut redis := redisclient.core_get()!
data := redis.hget("db:${name}",id.str())!
data := redis.hget('db:${name}', id.str())!
if data.len > 0 {
return T{}.load(data.bytes())!
} else {
@@ -31,19 +31,19 @@ pub fn get[T](id u32) !T {
pub fn exists[T](id u32) !bool {
name := T{}.type_name()
mut redis := redisclient.core_get()!
return redis.hexists("db:${name}",id.str())!
return redis.hexists('db:${name}', id.str())!
}
pub fn delete[T](id u32) ! {
name := T{}.type_name()
mut redis := redisclient.core_get()!
redis.hdel("db:${name}", id.str())!
redis.hdel('db:${name}', id.str())!
}
pub fn list[T]() ![]T {
name := T{}.type_name()
mut redis := redisclient.core_get()!
all_data := redis.hgetall("db:${name}")!
all_data := redis.hgetall('db:${name}')!
mut result := []T{}
for _, data in all_data {
result << T{}.load(data.bytes())!
@@ -51,7 +51,9 @@ pub fn list[T]() ![]T {
return result
}
//make it easy to get a base object
// make it easy to get a base object
pub fn new_from_base[T](args BaseArgs) !Base {
return T { Base: new_base(args)! }
return T{
Base: new_base(args)!
}
}

View File

@@ -1,7 +1,6 @@
module openrpcserver
import crypto.md5
import freeflowuniverse.herolib.core.redisclient
import freeflowuniverse.herolib.data.ourtime
@@ -15,7 +14,7 @@ pub mut:
created_at i64
updated_at i64
securitypolicy u32
tags u32 //when we set/get we always do as []string but this can then be sorted and md5ed this gies the unique id of tags
tags u32 // when we set/get we always do as []string but this can then be sorted and md5ed this gies the unique id of tags
comments []u32
}
@@ -23,23 +22,21 @@ pub mut:
pub struct SecurityPolicy {
pub mut:
id u32
read []u32 //links to users & groups
write []u32 //links to users & groups
delete []u32 //links to users & groups
read []u32 // links to users & groups
write []u32 // links to users & groups
delete []u32 // links to users & groups
public bool
md5 string //this sorts read, write and delete u32 + hash, then do md5 hash, this allows to go from a random read/write/delete/public config to a hash
md5 string // this sorts read, write and delete u32 + hash, then do md5 hash, this allows to go from a random read/write/delete/public config to a hash
}
@[heap]
pub struct Tags {
pub mut:
id u32
names []string //unique per id
md5 string //of sorted names, to make easy to find unique id, each name lowercased and made ascii
names []string // unique per id
md5 string // of sorted names, to make easy to find unique id, each name lowercased and made ascii
}
/////////////////
@[params]
@@ -53,14 +50,14 @@ pub mut:
comments []CommentArg
}
//make it easy to get a base object
// make it easy to get a base object
pub fn new_base(args BaseArgs) !Base {
mut redis := redisclient.core_get()!
commentids:=comment_multiset(args.comments)!
tags:=tags2id(args.tags)!
commentids := comment_multiset(args.comments)!
tags := tags2id(args.tags)!
return Base {
return Base{
id: args.id or { 0 }
name: args.name
description: args.description
@@ -74,17 +71,17 @@ pub fn new_base(args BaseArgs) !Base {
pub fn tags2id(tags []string) !u32 {
mut redis := redisclient.core_get()!
return if tags.len>0{
mut tags_fixed := tags.map(it.to_lower_ascii().trim_space()).filter(it != "")
return if tags.len > 0 {
mut tags_fixed := tags.map(it.to_lower_ascii().trim_space()).filter(it != '')
tags_fixed.sort_ignore_case()
hash :=md5.hexhash(tags_fixed.join(","))
tags_found := redis.hget("db:tags", hash)!
return if tags_found == ""{
id := u32(redis.incr("db:tags:id")!)
redis.hset("db:tags", hash, id.str())!
redis.hset("db:tags", id.str(), tags_fixed.join(","))!
hash := md5.hexhash(tags_fixed.join(','))
tags_found := redis.hget('db:tags', hash)!
return if tags_found == '' {
id := u32(redis.incr('db:tags:id')!)
redis.hset('db:tags', hash, id.str())!
redis.hset('db:tags', id.str(), tags_fixed.join(','))!
id
}else{
} else {
tags_found.u32()
}
} else {

View File

@@ -6,7 +6,7 @@ import net.unix
import os
import freeflowuniverse.herolib.ui.console
//THIS IS DEFAULT NEEDED FOR EACH OPENRPC SERVER WE MAKE
// THIS IS DEFAULT NEEDED FOR EACH OPENRPC SERVER WE MAKE
pub struct JsonRpcRequest {
pub:
@@ -33,7 +33,6 @@ pub:
data string
}
pub struct RPCServer {
pub mut:
listener &unix.StreamListener

View File

@@ -81,7 +81,31 @@ pub fn (a Asset) formatted_amount() string {
factor *= 10
}
formatted_amount := (a.amount * factor).round() / factor
return '${formatted_amount:.${a.decimals}f}'
// Format with the specified number of decimal places
if a.decimals == 0 {
return '${formatted_amount:.0f}'
} else if a.decimals == 1 {
return '${formatted_amount:.1f}'
} else if a.decimals == 2 {
return '${formatted_amount:.2f}'
} else if a.decimals == 3 {
return '${formatted_amount:.3f}'
} else if a.decimals == 4 {
return '${formatted_amount:.4f}'
} else {
// For more than 4 decimals, use string manipulation
str_amount := formatted_amount.str()
if str_amount.contains('.') {
parts := str_amount.split('.')
if parts.len == 2 {
decimal_part := parts[1]
if decimal_part.len > a.decimals {
return '${parts[0]}.${decimal_part[..a.decimals]}'
}
}
}
return str_amount
}
}
// transfer_to transfers amount to another asset

View File

@@ -169,22 +169,15 @@ pub fn (a Address) get_company_string() string {
// equals compares two addresses for equality
pub fn (a Address) equals(other Address) bool {
return a.street == other.street &&
a.city == other.city &&
a.state == other.state &&
a.postal_code == other.postal_code &&
a.country == other.country &&
a.company == other.company
return a.street == other.street && a.city == other.city && a.state == other.state
&& a.postal_code == other.postal_code && a.country == other.country
&& a.company == other.company
}
// is_empty checks if the address is completely empty
pub fn (a Address) is_empty() bool {
return a.street.len == 0 &&
a.city.len == 0 &&
a.postal_code.len == 0 &&
a.country.len == 0 &&
a.state == none &&
a.company == none
return a.street.len == 0 && a.city.len == 0 && a.postal_code.len == 0 && a.country.len == 0
&& a.state == none && a.company == none
}
// validate performs basic validation on the address

View File

@@ -9,11 +9,12 @@ module models
// - Payment models (Stripe webhooks)
// - Location models (addresses)
// Re-export all model modules for easy access
pub use core
pub use finance
pub use flow
pub use business
pub use identity
pub use payment
pub use location
// Import all model modules for easy access
import freeflowuniverse.herolib.threefold.models.core
import freeflowuniverse.herolib.threefold.models.finance
import freeflowuniverse.herolib.threefold.models.flow
import freeflowuniverse.herolib.threefold.models.business
import freeflowuniverse.herolib.threefold.models.identity
import freeflowuniverse.herolib.threefold.models.payment
import freeflowuniverse.herolib.threefold.models.location

View File

@@ -41,7 +41,7 @@ pub fn (mut docsite DocSite) generate_docs() ! {
}
if gen.errors.len > 0 {
println("Page List: is header collection and page name per collection.\nAvailable pages:\n${gen.client.list_markdown()!}")
println('Page List: is header collection and page name per collection.\nAvailable pages:\n${gen.client.list_markdown()!}')
return error('Errors occurred during site generation:\n${gen.errors.join('\n\n')}\n')
}
}