From f0fdf146a893c10ee7d60dd09c38bd82d2777df2 Mon Sep 17 00:00:00 2001 From: mariobassem Date: Mon, 30 Dec 2024 17:36:22 +0200 Subject: [PATCH] formatting --- examples/builder/remote_executor/toexec.v | 5 +- examples/builder/simple.vsh | 1 - examples/builder/simple_ip4.vsh | 2 +- examples/builder/simple_ip6.vsh | 2 +- examples/data/encoder.vsh | 7 +- examples/data/heroencoder_example.vsh | 52 ++- .../data/params/paramsfilter/paramsfilter.vsh | 2 +- examples/develop/gittools/example3.vsh | 8 +- .../develop/gittools/gittools_example.vsh | 1 - .../develop/gittools/gittools_example2.vsh | 32 +- examples/develop/juggler/v_example.vsh | 6 +- examples/develop/juggler/v_example2.vsh | 10 +- examples/develop/luadns/example.vsh | 40 +- examples/develop/openai/openai_example.vsh | 20 +- examples/hero/alpine_example.vsh | 3 +- .../generation/blank_generation/example_2.vsh | 2 +- .../openapi_generation/example_actor/actor.v | 30 +- .../example_actor/actor_test.v | 6 +- .../openapi_generation/example_actor/handle.v | 4 +- examples/hero/openapi/actor.vsh | 293 +++++++------- examples/hero/openapi/server.vsh | 215 +++++----- examples/installers/actrunner.vsh | 2 +- examples/installers/coredns.vsh | 2 - examples/installers/dagu.vsh | 4 +- examples/installers/dagu_server.vsh | 35 +- examples/installers/gitea.vsh | 8 +- examples/installers/griddriver.vsh | 1 + examples/installers/hero_install.vsh | 2 +- examples/installers/herocontainers.vsh | 7 +- examples/installers/installers.vsh | 2 - examples/installers/mycelium.vsh | 1 + examples/installers/postgresql.vsh | 4 +- examples/installers/youki.vsh | 3 +- examples/lang/python/pythonexample.vsh | 35 +- examples/osal/download/download_example.vsh | 8 +- examples/osal/ping/portforward.vsh | 18 +- .../osal/process/process_bash/processtest.v | 35 +- .../osal/process/process_python/processtest.v | 86 ++-- .../osal/sandbox/examples/sandbox_example.v | 6 +- examples/osal/sshagent/sshagent_example.v | 9 +- examples/osal/startup_manager.vsh | 14 +- examples/osal/systemd.vsh | 5 +- examples/osal/ufw.vsh | 4 +- examples/osal/ufw_play.vsh | 2 +- examples/osal/zinit/simple/zinit.vsh | 2 +- .../grid/deploy/create_update_deployments.vsh | 64 +-- .../threefold/grid/deploy/deploy_gw_fqdn.vsh | 12 +- .../threefold/grid/deploy/deploy_gw_name.vsh | 12 +- examples/threefold/grid/deploy/deploy_vm.vsh | 36 +- .../grid/deploy/deploy_vm_high_level.vsh | 2 +- examples/threefold/grid/deploy/deploy_zdb.vsh | 12 +- .../threefold/grid/deploy/holochain_vm.vsh | 55 ++- .../threefold/grid/deploy/vm_with_gw_name.vsh | 72 ++-- .../threefold/grid/utils/cancel_contract.vsh | 18 +- .../threefold/grid/utils/tfgrid_config.vsh | 8 +- examples/threefold/grid/utils/zos_version.vsh | 2 +- examples/threefold/grid/vm_example.vsh | 39 +- examples/threefold/grid/webgw_example.vsh | 18 +- examples/threefold/gridproxy/bill.vsh | 4 +- examples/threefold/gridproxy/contract.vsh | 10 +- examples/threefold/gridproxy/farm.vsh | 10 +- examples/threefold/gridproxy/gateway.vsh | 12 +- examples/threefold/gridproxy/grid.vsh | 2 +- examples/threefold/gridproxy/node.vsh | 29 +- examples/threefold/gridproxy/stats.vsh | 8 +- examples/threefold/gridproxy/twin.vsh | 8 +- .../holochain/holochain_deployer.vsh | 49 ++- .../threefold/holochain/holochain_vms.vsh | 6 +- .../threefold/holochain/tasker_example.vsh | 55 ++- .../threefold/holochain/tasker_example2.vsh | 27 +- .../tfgrid3deployer_example.vsh | 8 +- examples/ui/console/flow1/flow1.v | 4 +- examples/ui/flow1.v | 6 +- examples/ui/silence.vsh | 8 +- examples/ui/telegram/flow1.v | 6 +- examples/virt/docker/presearch_docker.vsh | 2 +- examples/virt/docker/tf_dashboard.vsh | 1 + examples/virt/hetzner/hetzner_example.vsh | 18 +- examples/virt/lima/lima_example.vsh | 9 +- .../virt/podman_buildah/buildah_example.vsh | 22 +- examples/virt/podman_buildah/buildah_run.vsh | 25 +- .../virt/podman_buildah/buildah_run_clean.vsh | 6 +- .../podman_buildah/buildah_run_mdbook.vsh | 7 +- examples/virt/windows/cloudhypervisor.vsh | 7 +- examples/webdav/webdav.vsh | 7 +- lib/builder/bootstrapper.v | 96 ++--- lib/builder/executor.v | 4 +- lib/builder/executor_local.v | 20 +- lib/builder/executor_ssh.v | 26 +- lib/builder/executor_ssh_test.v | 4 +- lib/builder/node.v | 2 +- lib/builder/node_commands.v | 2 +- lib/builder/node_executor.v | 4 +- lib/builder/node_factory.v | 8 +- lib/clients/meilisearch/meilisearch_model.v | 1 - lib/clients/rclone/config.v | 2 +- lib/clients/rclone/rclone_model.v | 12 +- lib/core/playcmds/_archive/play_juggler.v | 4 +- lib/core/playcmds/factory.v | 16 +- lib/core/playcmds/play_dagu_test.v | 2 +- lib/core/playcmds/play_doctree.v | 5 +- lib/core/playcmds/play_git.v | 18 +- lib/core/playcmds/play_mdbook.v | 26 +- lib/core/playcmds/play_zola.v | 26 +- lib/hero/baobab/action/error.v | 34 +- lib/hero/baobab/action/procedure.v | 8 +- lib/hero/baobab/action/reflection_openapi.v | 140 +++---- lib/hero/baobab/actor/client.v | 4 +- lib/hero/baobab/example_actor/actor.v | 30 +- lib/hero/baobab/example_actor/actor_test.v | 6 +- lib/hero/baobab/example_actor/handle.v | 4 +- .../baobab/example_actor/interface_command.v | 26 +- lib/hero/baobab/generator/generate_actor.v | 45 ++- .../baobab/generator/generate_actor_test.v | 266 +++++++------ lib/hero/baobab/generator/generate_clients.v | 36 +- lib/hero/baobab/generator/generate_command.v | 20 +- lib/hero/baobab/generator/generate_handle.v | 14 +- lib/hero/baobab/generator/generate_methods.v | 22 +- lib/hero/baobab/generator/generate_objects.v | 1 - lib/hero/baobab/generator/generate_openrpc.v | 30 +- .../baobab/generator/generate_openrpc_test.v | 10 +- .../baobab/generator/write_object_methods.v | 162 ++++---- .../generator/write_object_methods_test.v | 8 +- .../baobab/generator/write_object_tests.v | 30 +- lib/hero/baobab/osis/factory.v | 2 +- lib/hero/baobab/osis/indexer.v | 10 +- lib/hero/baobab/osis/indexer_generic.v | 4 +- lib/hero/baobab/osis/indexer_generic_test.v | 64 ++- lib/hero/baobab/osis/indexer_identifier.v | 14 +- lib/hero/baobab/osis/indexer_test.v | 12 +- lib/hero/baobab/osis/model.v | 8 +- lib/hero/baobab/osis/root_object.v | 51 ++- lib/hero/baobab/osis/storer.v | 18 +- lib/hero/baobab/osis/storer_generic.v | 4 +- lib/hero/baobab/specification/model.v | 22 +- lib/hero/baobab/specification/openapi.v | 206 +++++----- lib/hero/baobab/specification/openapi_test.v | 372 +++++++++--------- lib/hero/baobab/specification/openrpc.v | 11 +- lib/hero/bootstrap/alpine.v | 12 +- lib/installers/lang/golang/golang_actions.v | 2 +- .../threefold/griddriver/griddriver_actions.v | 4 +- 141 files changed, 1850 insertions(+), 1882 deletions(-) diff --git a/examples/builder/remote_executor/toexec.v b/examples/builder/remote_executor/toexec.v index 7d06c678..aa6697a5 100644 --- a/examples/builder/remote_executor/toexec.v +++ b/examples/builder/remote_executor/toexec.v @@ -4,15 +4,14 @@ import freeflowuniverse.herolib.osal import freeflowuniverse.herolib.installers.base fn do() ! { - //base.uninstall_brew()! - //println("something") + // base.uninstall_brew()! + // println("something") if osal.is_osx() { println('IS OSX') } // mut job2 := osal.exec(cmd: 'ls /')! // println(job2) - } fn main() { diff --git a/examples/builder/simple.vsh b/examples/builder/simple.vsh index d790293e..72c6eb92 100755 --- a/examples/builder/simple.vsh +++ b/examples/builder/simple.vsh @@ -4,7 +4,6 @@ import freeflowuniverse.herolib.builder import freeflowuniverse.herolib.core.pathlib import os - fn do1() ! { mut b := builder.new()! mut n := b.node_new(ipaddr: 'root@195.192.213.2')! diff --git a/examples/builder/simple_ip4.vsh b/examples/builder/simple_ip4.vsh index d5cc4559..f4da05d8 100755 --- a/examples/builder/simple_ip4.vsh +++ b/examples/builder/simple_ip4.vsh @@ -10,7 +10,7 @@ mut n := b.node_new(ipaddr: 'root@51.195.61.5')! println(n) -r:=n.exec(cmd:"ls /")! +r := n.exec(cmd: 'ls /')! println(r) // n.upload(source: myexamplepath, dest: '/tmp/myexamplepath2')! diff --git a/examples/builder/simple_ip6.vsh b/examples/builder/simple_ip6.vsh index 151e4a89..10d38683 100755 --- a/examples/builder/simple_ip6.vsh +++ b/examples/builder/simple_ip6.vsh @@ -7,7 +7,7 @@ import os mut b := builder.new()! mut n := b.node_new(ipaddr: 'root@302:1d81:cef8:3049:ad01:796d:a5da:9c6')! -r:=n.exec(cmd:"ls /")! +r := n.exec(cmd: 'ls /')! println(r) // n.upload(source: myexamplepath, dest: '/tmp/myexamplepath2')! diff --git a/examples/data/encoder.vsh b/examples/data/encoder.vsh index e1487f6c..4ebb9771 100755 --- a/examples/data/encoder.vsh +++ b/examples/data/encoder.vsh @@ -14,7 +14,7 @@ mut: _, privkey := ed25519.generate_key()! mut a := AStruct{ items: ['a', 'b'] - nr: 10 + nr: 10 // privkey: []u8{len: 5, init: u8(0xf8)} privkey: privkey } @@ -36,10 +36,9 @@ aa.privkey = d.get_bytes() assert a == aa - a = AStruct{ - items: ['a', 'b'] - nr: 10 + items: ['a', 'b'] + nr: 10 privkey: []u8{len: 5, init: u8(0xf8)} } diff --git a/examples/data/heroencoder_example.vsh b/examples/data/heroencoder_example.vsh index 8714ef51..7628722c 100755 --- a/examples/data/heroencoder_example.vsh +++ b/examples/data/heroencoder_example.vsh @@ -1,31 +1,33 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run + import freeflowuniverse.herolib.data.encoderhero import freeflowuniverse.herolib.core.base -//this is docu at top -@[name:"teststruct " ; params] +// this is docu at top +@[name: 'teststruct '] +@[params] pub struct TestStruct { -//this is docu at mid + // this is docu at mid pub mut: - id int @[hi] - descr string - secret string @[secret] - number int = 1 @[min:1 ;max:10] + id int @[hi] + descr string + secret string @[secret] + number int = 1 @[max: 10; min: 1] yesno bool liststr []string listint []int - ss SubStruct - ss2 []SubStruct + ss SubStruct + ss2 []SubStruct } pub struct SubStruct { pub mut: color string - size int + size int } -fn (self TestStruct) heroscript()!string { - mut out:="" +fn (self TestStruct) heroscript() !string { + mut out := '' mut p := encoderhero.encode[TestStruct](self)! // out += "!!hr.teststruct_define " + p.heroscript() + "\n" // p = paramsparser.encode[SubStruct](self.ss)! @@ -39,10 +41,9 @@ fn (self TestStruct) heroscript()!string { return p } - mut t := TestStruct{ - id:100 - descr: ' + id: 100 + descr: ' test muliline s @@ -50,15 +51,24 @@ mut t := TestStruct{ muliline test muliline - ' - number: 2 - yesno: true + ' + number: 2 + yesno: true liststr: ['one', 'two+two'] listint: [1, 2] - ss:SubStruct{color:"red",size:10} + ss: SubStruct{ + color: 'red' + size: 10 + } +} +t.ss2 << SubStruct{ + color: 'red1' + size: 11 +} +t.ss2 << SubStruct{ + color: 'red2' + size: 12 } -t.ss2<< SubStruct{color:"red1",size:11} -t.ss2<< SubStruct{color:"red2",size:12} println(t.heroscript()!) diff --git a/examples/data/params/paramsfilter/paramsfilter.vsh b/examples/data/params/paramsfilter/paramsfilter.vsh index 8a6fdbe6..9136ff58 100755 --- a/examples/data/params/paramsfilter/paramsfilter.vsh +++ b/examples/data/params/paramsfilter/paramsfilter.vsh @@ -1,7 +1,7 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run import freeflowuniverse.herolib.data.paramsparser { Params, parse } -import time { Duration, sleep } +import time totalnr := 1000000 diff --git a/examples/develop/gittools/example3.vsh b/examples/develop/gittools/example3.vsh index a0b5cacb..1cf1bcee 100755 --- a/examples/develop/gittools/example3.vsh +++ b/examples/develop/gittools/example3.vsh @@ -8,17 +8,19 @@ mut silent := false coderoot := if 'CODEROOT' in os.environ() { os.environ()['CODEROOT'] -} else {os.join_path(os.home_dir(), 'code')} +} else { + os.join_path(os.home_dir(), 'code') +} mut gs := gittools.get()! if coderoot.len > 0 { - //is a hack for now + // is a hack for now gs = gittools.new(coderoot: coderoot)! } mypath := gs.do( recursive: true - cmd: 'list' + cmd: 'list' )! timer := performance.new('gittools') diff --git a/examples/develop/gittools/gittools_example.vsh b/examples/develop/gittools/gittools_example.vsh index 04df1a7a..d9e39f27 100755 --- a/examples/develop/gittools/gittools_example.vsh +++ b/examples/develop/gittools/gittools_example.vsh @@ -4,7 +4,6 @@ import freeflowuniverse.herolib.develop.gittools import freeflowuniverse.herolib.osal import time - mut gs_default := gittools.new()! println(gs_default) diff --git a/examples/develop/gittools/gittools_example2.vsh b/examples/develop/gittools/gittools_example2.vsh index ff0431a4..ece58866 100755 --- a/examples/develop/gittools/gittools_example2.vsh +++ b/examples/develop/gittools/gittools_example2.vsh @@ -5,7 +5,7 @@ import freeflowuniverse.herolib.osal import time // Creates a new file in the specified repository path and returns its name. -fn create_new_file(repo_path string, runtime i64)! string { +fn create_new_file(repo_path string, runtime i64) !string { coded_now := time.now().unix() file_name := 'hello_world_${coded_now}.py' println('Creating a new ${file_name} file.') @@ -29,8 +29,8 @@ mut repo := gs_default.get_repo(name: 'repo3')! // mut repo := gs_default.get_repo(name: 'repo3' clone: true, url: 'https://github.com/Mahmoud-Emad/repo2.git')! runtime := time.now().unix() -branch_name := "branch_${runtime}" -tag_name := "tag_${runtime}" +branch_name := 'branch_${runtime}' +tag_name := 'tag_${runtime}' repo_path := repo.get_path()! mut file_name := create_new_file(repo_path, runtime)! @@ -51,36 +51,28 @@ repo.checkout(branch_name: branch_name, pull: false) or { // Check for changes and stage them if present. if repo.has_changes()! { println('Adding the changes...') - repo.add_changes() or { - error('Cannot add the changes due to: ${err}') - } + repo.add_changes() or { error('Cannot add the changes due to: ${err}') } } // Check if a commit is needed and commit changes if necessary. if repo.need_commit()! { commit_msg := 'feat: Added ${file_name} file.' println('Committing the changes, Commit message: ${commit_msg}.') - repo.commit(msg: commit_msg) or { - error('Cannot commit the changes due to: ${err}') - } + repo.commit(msg: commit_msg) or { error('Cannot commit the changes due to: ${err}') } } // Push changes to the remote repository if necessary. if repo.need_push()! { println('Pushing the changes...') - repo.push() or { - error('Cannot push the changes due to: ${err}') - } + repo.push() or { error('Cannot push the changes due to: ${err}') } } if repo.need_pull()! { println('Pulling the changes.') - repo.pull() or { - error('Cannot pull the changes due to: ${err}') - } + repo.pull() or { error('Cannot pull the changes due to: ${err}') } } -// Checkout to the base branch +// Checkout to the base branch repo.checkout(checkout_to_base_branch: true, pull: true) or { error("Couldn't checkout to branch ${branch_name} due to: ${err}") } @@ -93,12 +85,8 @@ repo.create_tag(tag_name: tag_name, checkout: false) or { // Push the created tag. println('Pushing the tag...') -repo.push(push_tag: true) or { - error('Cannot push the tag due to: ${err}') -} +repo.push(push_tag: true) or { error('Cannot push the tag due to: ${err}') } // Check if the created tag exists. println('Check if the created tag exists...') -repo.is_tag_exists(tag_name: tag_name) or { - println("Tag isn't exists.") -} +repo.is_tag_exists(tag_name: tag_name) or { println("Tag isn't exists.") } diff --git a/examples/develop/juggler/v_example.vsh b/examples/develop/juggler/v_example.vsh index efdad4fc..23a6106a 100755 --- a/examples/develop/juggler/v_example.vsh +++ b/examples/develop/juggler/v_example.vsh @@ -8,16 +8,16 @@ import veb osal.load_env_file('${os.dir(@FILE)}/.env')! mut j := juggler.configure( - url: 'https://git.ourworld.tf/projectmycelium/itenv' + url: 'https://git.ourworld.tf/projectmycelium/itenv' username: os.getenv('JUGGLER_USERNAME') password: os.getenv('JUGGLER_PASSWORD') - reset: true + reset: true )! spawn j.run(8000) println(j.info()) -for{} +for {} // TODO // - automate caddy install/start diff --git a/examples/develop/juggler/v_example2.vsh b/examples/develop/juggler/v_example2.vsh index add77abf..120868b4 100755 --- a/examples/develop/juggler/v_example2.vsh +++ b/examples/develop/juggler/v_example2.vsh @@ -5,11 +5,13 @@ import os mut sm := startupmanager.get()! sm.start( - name: 'juggler' - cmd: 'hero juggler -secret planetfirst -u https://git.ourworld.tf/projectmycelium/itenv -reset true' - env: {'HOME': os.home_dir()} + name: 'juggler' + cmd: 'hero juggler -secret planetfirst -u https://git.ourworld.tf/projectmycelium/itenv -reset true' + env: { + 'HOME': os.home_dir() + } restart: true -) or {panic('failed to start sm ${err}')} +) or { panic('failed to start sm ${err}') } // TODO // - automate caddy install/start diff --git a/examples/develop/luadns/example.vsh b/examples/develop/luadns/example.vsh index d0d83267..582225c7 100644 --- a/examples/develop/luadns/example.vsh +++ b/examples/develop/luadns/example.vsh @@ -3,26 +3,26 @@ import freeflowuniverse.herolib.develop.luadns fn main() { - mut lua_dns := luadns.load('https://github.com/Incubaid/dns') or { - eprintln('Failed to parse LuaDNS files: $err') - return - } + mut lua_dns := luadns.load('https://github.com/Incubaid/dns') or { + eprintln('Failed to parse LuaDNS files: ${err}') + return + } - lua_dns.set_domain('test.protocol.me', '65.21.132.119') or { - eprintln('Failed to set domain: $err') - return - } + lua_dns.set_domain('test.protocol.me', '65.21.132.119') or { + eprintln('Failed to set domain: ${err}') + return + } - lua_dns.set_domain('example.protocol.me', '65.21.132.119') or { - eprintln('Failed to set domain: $err') - return - } - - for config in lua_dns.configs { - println(config) - } - - for config in lua_dns.configs { - println(config) - } + lua_dns.set_domain('example.protocol.me', '65.21.132.119') or { + eprintln('Failed to set domain: ${err}') + return + } + + for config in lua_dns.configs { + println(config) + } + + for config in lua_dns.configs { + println(config) + } } diff --git a/examples/develop/openai/openai_example.vsh b/examples/develop/openai/openai_example.vsh index e81c20a3..c48599c3 100644 --- a/examples/develop/openai/openai_example.vsh +++ b/examples/develop/openai/openai_example.vsh @@ -5,7 +5,7 @@ import freeflowuniverse.herolib.clients.openai as op mut ai_cli := op.new()! mut msg := []op.Message{} msg << op.Message{ - role: op.RoleType.user + role: op.RoleType.user content: 'Say this is a test!' } mut msgs := op.Messages{ @@ -19,26 +19,26 @@ models := ai_cli.list_models()! model := ai_cli.get_model(models.data[0].id)! print(model) images_created := ai_cli.create_image(op.ImageCreateArgs{ - prompt: 'Calm weather' + prompt: 'Calm weather' num_images: 2 - size: op.ImageSize.size_512_512 - format: op.ImageRespType.url + size: op.ImageSize.size_512_512 + format: op.ImageRespType.url })! print(images_created) images_updated := ai_cli.create_edit_image(op.ImageEditArgs{ image_path: '/path/to/image.png' - mask_path: '/path/to/mask.png' - prompt: 'Calm weather' + mask_path: '/path/to/mask.png' + prompt: 'Calm weather' num_images: 2 - size: op.ImageSize.size_512_512 - format: op.ImageRespType.url + size: op.ImageSize.size_512_512 + format: op.ImageRespType.url })! print(images_updated) images_variatons := ai_cli.create_variation_image(op.ImageVariationArgs{ image_path: '/path/to/image.png' num_images: 2 - size: op.ImageSize.size_512_512 - format: op.ImageRespType.url + size: op.ImageSize.size_512_512 + format: op.ImageRespType.url })! print(images_variatons) diff --git a/examples/hero/alpine_example.vsh b/examples/hero/alpine_example.vsh index d69aefce..994a1a7b 100755 --- a/examples/hero/alpine_example.vsh +++ b/examples/hero/alpine_example.vsh @@ -1,8 +1,7 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run - import freeflowuniverse.herolib.hero.bootstrap -mut al:=bootstrap.new_alpine_loader() +mut al := bootstrap.new_alpine_loader() al.start()! diff --git a/examples/hero/generation/blank_generation/example_2.vsh b/examples/hero/generation/blank_generation/example_2.vsh index 60c00e14..dbdbed32 100644 --- a/examples/hero/generation/blank_generation/example_2.vsh +++ b/examples/hero/generation/blank_generation/example_2.vsh @@ -3,6 +3,6 @@ import freeflowuniverse.herolib.hero.generation generation.generate_actor( - name: 'Example' + name: 'Example' interfaces: [] ) diff --git a/examples/hero/generation/openapi_generation/example_actor/actor.v b/examples/hero/generation/openapi_generation/example_actor/actor.v index 02bed1c5..bd294826 100644 --- a/examples/hero/generation/openapi_generation/example_actor/actor.v +++ b/examples/hero/generation/openapi_generation/example_actor/actor.v @@ -1,7 +1,7 @@ module example_actor import os -import freeflowuniverse.herolib.hero.baobab.actor {IActor, RunParams} +import freeflowuniverse.herolib.hero.baobab.actor { IActor, RunParams } import freeflowuniverse.herolib.web.openapi import time @@ -10,27 +10,25 @@ const openapi_spec_json = os.read_file(openapi_spec_path) or { panic(err) } const openapi_specification = openapi.json_decode(openapi_spec_json)! struct ExampleActor { - actor.Actor + actor.Actor } fn new() !ExampleActor { - return ExampleActor{ - actor.new('example') - } + return ExampleActor{actor.new('example')} } pub fn run() ! { - mut a_ := new()! - mut a := IActor(a_) - a.run()! + mut a_ := new()! + mut a := IActor(a_) + a.run()! } pub fn run_server(params RunParams) ! { - mut a := new()! - mut server := actor.new_server( - redis_url: 'localhost:6379' - redis_queue: a.name - openapi_spec: openapi_specification - )! - server.run(params) -} \ No newline at end of file + mut a := new()! + mut server := actor.new_server( + redis_url: 'localhost:6379' + redis_queue: a.name + openapi_spec: openapi_specification + )! + server.run(params) +} diff --git a/examples/hero/generation/openapi_generation/example_actor/actor_test.v b/examples/hero/generation/openapi_generation/example_actor/actor_test.v index cab2e268..d07f5d25 100644 --- a/examples/hero/generation/openapi_generation/example_actor/actor_test.v +++ b/examples/hero/generation/openapi_generation/example_actor/actor_test.v @@ -3,9 +3,7 @@ module example_actor const test_port = 8101 pub fn test_new() ! { - new() or { - return error('Failed to create actor:\n${err}') - } + new() or { return error('Failed to create actor:\n${err}') } } pub fn test_run() ! { @@ -14,4 +12,4 @@ pub fn test_run() ! { pub fn test_run_server() ! { spawn run_server(port: test_port) -} \ No newline at end of file +} diff --git a/examples/hero/generation/openapi_generation/example_actor/handle.v b/examples/hero/generation/openapi_generation/example_actor/handle.v index dfc067ef..889fce52 100644 --- a/examples/hero/generation/openapi_generation/example_actor/handle.v +++ b/examples/hero/generation/openapi_generation/example_actor/handle.v @@ -1,5 +1,5 @@ module example_actor pub fn (mut a ExampleActor) handle(method string, data string) !string { - return data -} \ No newline at end of file + return data +} diff --git a/examples/hero/openapi/actor.vsh b/examples/hero/openapi/actor.vsh index 6e72e7b9..c7426b64 100755 --- a/examples/hero/openapi/actor.vsh +++ b/examples/hero/openapi/actor.vsh @@ -6,210 +6,229 @@ import veb import json import x.json2 import net.http -import freeflowuniverse.herolib.web.openapi {Server, Context, Request, Response} -import freeflowuniverse.herolib.hero.processor {Processor, ProcedureCall, ProcedureResponse, ProcessParams} +import freeflowuniverse.herolib.web.openapi +import freeflowuniverse.herolib.hero.processor import freeflowuniverse.herolib.clients.redisclient @[heap] struct Actor { mut: - rpc redisclient.RedisRpc - data_store DataStore + rpc redisclient.RedisRpc + data_store DataStore } pub struct DataStore { mut: - pets map[int]Pet - orders map[int]Order - users map[int]User + pets map[int]Pet + orders map[int]Order + users map[int]User } struct Pet { - id int - name string - tag string + id int + name string + tag string } struct Order { - id int - pet_id int - quantity int - ship_date string - status string - complete bool + id int + pet_id int + quantity int + ship_date string + status string + complete bool } struct User { - id int - username string - email string - phone string + id int + username string + email string + phone string } // Entry point for the actor fn main() { - mut redis := redisclient.new('localhost:6379') or {panic(err)} - mut rpc := redis.rpc_get('procedure_queue') + mut redis := redisclient.new('localhost:6379') or { panic(err) } + mut rpc := redis.rpc_get('procedure_queue') - mut actor := Actor{ - rpc: rpc - data_store: DataStore{} - } + mut actor := Actor{ + rpc: rpc + data_store: DataStore{} + } - actor.listen() or {panic(err)} + actor.listen() or { panic(err) } } // Actor listens to the Redis queue for method invocations fn (mut actor Actor) listen() ! { - println('Actor started and listening for tasks...') - for { - actor.rpc.process(actor.handle_method)! - time.sleep(time.millisecond * 100) // Prevent CPU spinning - } + println('Actor started and listening for tasks...') + for { + actor.rpc.process(actor.handle_method)! + time.sleep(time.millisecond * 100) // Prevent CPU spinning + } } // Handle method invocations fn (mut actor Actor) handle_method(cmd string, data string) !string { - println('debugzo received rpc ${cmd}:${data}') - param_anys := json2.raw_decode(data)!.arr() - match cmd { - 'listPets' { - pets := if param_anys.len == 0 { - actor.data_store.list_pets() - } else { - params := json.decode(ListPetParams, param_anys[0].str())! - actor.data_store.list_pets(params) - } - return json.encode(pets) - } - 'createPet' { - response := if param_anys.len == 0 { - return error('at least data expected') - } else if param_anys.len == 1 { - payload := json.decode(NewPet, param_anys[0].str())! - actor.data_store.create_pet(payload) - } else { - return error('expected 1 param, found too many') - } - // data := json.decode(NewPet, data) or { return error('Invalid pet data: $err') } - // created_pet := actor.data_store.create_pet(pet) - return json.encode(response) - } - 'getPet' { - response := if param_anys.len == 0 { - return error('at least data expected') - } else if param_anys.len == 1 { - payload := param_anys[0].int() - actor.data_store.get_pet(payload)! - } else { - return error('expected 1 param, found too many') - } - - return json.encode(response) - } - 'deletePet' { - params := json.decode(map[string]int, data) or { return error('Invalid params: $err') } - actor.data_store.delete_pet(params['petId']) or { return error('Pet not found: $err') } - return json.encode({'message': 'Pet deleted'}) - } - 'listOrders' { - orders := actor.data_store.list_orders() - return json.encode(orders) - } - 'getOrder' { - params := json.decode(map[string]int, data) or { return error('Invalid params: $err') } - order := actor.data_store.get_order(params['orderId']) or { - return error('Order not found: $err') - } - return json.encode(order) - } - 'deleteOrder' { - params := json.decode(map[string]int, data) or { return error('Invalid params: $err') } - actor.data_store.delete_order(params['orderId']) or { - return error('Order not found: $err') - } - return json.encode({'message': 'Order deleted'}) - } - 'createUser' { - user := json.decode(NewUser, data) or { return error('Invalid user data: $err') } - created_user := actor.data_store.create_user(user) - return json.encode(created_user) - } - else { - return error('Unknown method: $cmd') - } - } + println('debugzo received rpc ${cmd}:${data}') + param_anys := json2.raw_decode(data)!.arr() + match cmd { + 'listPets' { + pets := if param_anys.len == 0 { + actor.data_store.list_pets() + } else { + params := json.decode(ListPetParams, param_anys[0].str())! + actor.data_store.list_pets(params) + } + return json.encode(pets) + } + 'createPet' { + response := if param_anys.len == 0 { + return error('at least data expected') + } else if param_anys.len == 1 { + payload := json.decode(NewPet, param_anys[0].str())! + actor.data_store.create_pet(payload) + } else { + return error('expected 1 param, found too many') + } + // data := json.decode(NewPet, data) or { return error('Invalid pet data: $err') } + // created_pet := actor.data_store.create_pet(pet) + return json.encode(response) + } + 'getPet' { + response := if param_anys.len == 0 { + return error('at least data expected') + } else if param_anys.len == 1 { + payload := param_anys[0].int() + actor.data_store.get_pet(payload)! + } else { + return error('expected 1 param, found too many') + } + + return json.encode(response) + } + 'deletePet' { + params := json.decode(map[string]int, data) or { + return error('Invalid params: ${err}') + } + actor.data_store.delete_pet(params['petId']) or { + return error('Pet not found: ${err}') + } + return json.encode({ + 'message': 'Pet deleted' + }) + } + 'listOrders' { + orders := actor.data_store.list_orders() + return json.encode(orders) + } + 'getOrder' { + params := json.decode(map[string]int, data) or { + return error('Invalid params: ${err}') + } + order := actor.data_store.get_order(params['orderId']) or { + return error('Order not found: ${err}') + } + return json.encode(order) + } + 'deleteOrder' { + params := json.decode(map[string]int, data) or { + return error('Invalid params: ${err}') + } + actor.data_store.delete_order(params['orderId']) or { + return error('Order not found: ${err}') + } + return json.encode({ + 'message': 'Order deleted' + }) + } + 'createUser' { + user := json.decode(NewUser, data) or { return error('Invalid user data: ${err}') } + created_user := actor.data_store.create_user(user) + return json.encode(created_user) + } + else { + return error('Unknown method: ${cmd}') + } + } } @[params] pub struct ListPetParams { - limit u32 + limit u32 } // DataStore methods for managing data fn (mut store DataStore) list_pets(params ListPetParams) []Pet { - if params.limit > 0 { - if params.limit >= store.pets.values().len { - return store.pets.values() - } - return store.pets.values()[..params.limit] - } - return store.pets.values() + if params.limit > 0 { + if params.limit >= store.pets.values().len { + return store.pets.values() + } + return store.pets.values()[..params.limit] + } + return store.pets.values() } fn (mut store DataStore) create_pet(new_pet NewPet) Pet { - id := store.pets.keys().len + 1 - pet := Pet{id: id, name: new_pet.name, tag: new_pet.tag} - store.pets[id] = pet - return pet + id := store.pets.keys().len + 1 + pet := Pet{ + id: id + name: new_pet.name + tag: new_pet.tag + } + store.pets[id] = pet + return pet } fn (mut store DataStore) get_pet(id int) !Pet { - return store.pets[id] or { - return error('Pet with id ${id} not found.') - } + return store.pets[id] or { return error('Pet with id ${id} not found.') } } fn (mut store DataStore) delete_pet(id int) ! { - if id in store.pets { - store.pets.delete(id) - return - } - return error('Pet not found') + if id in store.pets { + store.pets.delete(id) + return + } + return error('Pet not found') } fn (mut store DataStore) list_orders() []Order { - return store.orders.values() + return store.orders.values() } fn (mut store DataStore) get_order(id int) !Order { - return store.orders[id] or { none } + return store.orders[id] or { none } } fn (mut store DataStore) delete_order(id int) ! { - if id in store.orders { - store.orders.delete(id) - return - } - return error('Order not found') + if id in store.orders { + store.orders.delete(id) + return + } + return error('Order not found') } fn (mut store DataStore) create_user(new_user NewUser) User { - id := store.users.keys().len + 1 - user := User{id: id, username: new_user.username, email: new_user.email, phone: new_user.phone} - store.users[id] = user - return user + id := store.users.keys().len + 1 + user := User{ + id: id + username: new_user.username + email: new_user.email + phone: new_user.phone + } + store.users[id] = user + return user } // NewPet struct for creating a pet struct NewPet { - name string - tag string + name string + tag string } // NewUser struct for creating a user struct NewUser { - username string - email string - phone string + username string + email string + phone string } diff --git a/examples/hero/openapi/server.vsh b/examples/hero/openapi/server.vsh index 04b6406d..3cbeb6f0 100755 --- a/examples/hero/openapi/server.vsh +++ b/examples/hero/openapi/server.vsh @@ -4,11 +4,11 @@ import os import time import veb import json -import x.json2 {Any} +import x.json2 { Any } import net.http -import freeflowuniverse.herolib.data.jsonschema {Schema} -import freeflowuniverse.herolib.web.openapi {Server, Context, Request, Response} -import freeflowuniverse.herolib.hero.processor {Processor, ProcedureCall, ProcedureResponse, ProcessParams} +import freeflowuniverse.herolib.data.jsonschema { Schema } +import freeflowuniverse.herolib.web.openapi { Context, Request, Response, Server } +import freeflowuniverse.herolib.hero.processor { ProcedureCall, ProcessParams, Processor } import freeflowuniverse.herolib.clients.redisclient const spec_path = '${os.dir(@FILE)}/data/openapi.json' @@ -16,126 +16,123 @@ const spec_json = os.read_file(spec_path) or { panic(err) } // Main function to start the server fn main() { - // Initialize the Redis client and RPC mechanism - mut redis := redisclient.new('localhost:6379')! - mut rpc := redis.rpc_get('procedure_queue') + // Initialize the Redis client and RPC mechanism + mut redis := redisclient.new('localhost:6379')! + mut rpc := redis.rpc_get('procedure_queue') - // Initialize the server - mut server := &Server{ - specification: openapi.json_decode(spec_json)! - handler: Handler{ - processor: Processor{ - rpc: rpc - } - } - } + // Initialize the server + mut server := &Server{ + specification: openapi.json_decode(spec_json)! + handler: Handler{ + processor: Processor{ + rpc: rpc + } + } + } - // Start the server - veb.run[Server, Context](mut server, 8080) + // Start the server + veb.run[Server, Context](mut server, 8080) } pub struct Handler { - mut: - processor Processor +mut: + processor Processor } fn (mut handler Handler) handle(request Request) !Response { - // Convert incoming OpenAPI request to a procedure call - mut params := []string{} + // Convert incoming OpenAPI request to a procedure call + mut params := []string{} - if request.arguments.len > 0 { - params = request.arguments.values().map(it.str()).clone() - } + if request.arguments.len > 0 { + params = request.arguments.values().map(it.str()).clone() + } - if request.body != '' { - params << request.body - } + if request.body != '' { + params << request.body + } - if request.parameters.len != 0 { - mut param_map := map[string]Any{} // Store parameters with correct types + if request.parameters.len != 0 { + mut param_map := map[string]Any{} // Store parameters with correct types - for param_name, param_value in request.parameters { - operation_param := request.operation.parameters.filter(it.name == param_name) - if operation_param.len > 0 { - param_schema := operation_param[0].schema as Schema - param_type := param_schema.typ - param_format := param_schema.format + for param_name, param_value in request.parameters { + operation_param := request.operation.parameters.filter(it.name == param_name) + if operation_param.len > 0 { + param_schema := operation_param[0].schema as Schema + param_type := param_schema.typ + param_format := param_schema.format - // Convert parameter value to corresponding type - match param_type { - 'integer' { - match param_format { - 'int32' { - param_map[param_name] = param_value.int() // Convert to int - } - 'int64' { - param_map[param_name] = param_value.i64() // Convert to i64 - } - else { - param_map[param_name] = param_value.int() // Default to int - } - } - } - 'string' { - param_map[param_name] = param_value // Already a string - } - 'boolean' { - param_map[param_name] = param_value.bool() // Convert to bool - } - 'number' { - match param_format { - 'float' { - param_map[param_name] = param_value.f32() // Convert to float - } - 'double' { - param_map[param_name] = param_value.f64() // Convert to double - } - else { - param_map[param_name] = param_value.f64() // Default to double - } - } - } - else { - param_map[param_name] = param_value // Leave as string for unknown types - } - } - } else { - // If the parameter is not defined in the OpenAPI operation, skip or log it - println('Unknown parameter: $param_name') - } - } + // Convert parameter value to corresponding type + match param_type { + 'integer' { + match param_format { + 'int32' { + param_map[param_name] = param_value.int() // Convert to int + } + 'int64' { + param_map[param_name] = param_value.i64() // Convert to i64 + } + else { + param_map[param_name] = param_value.int() // Default to int + } + } + } + 'string' { + param_map[param_name] = param_value // Already a string + } + 'boolean' { + param_map[param_name] = param_value.bool() // Convert to bool + } + 'number' { + match param_format { + 'float' { + param_map[param_name] = param_value.f32() // Convert to float + } + 'double' { + param_map[param_name] = param_value.f64() // Convert to double + } + else { + param_map[param_name] = param_value.f64() // Default to double + } + } + } + else { + param_map[param_name] = param_value // Leave as string for unknown types + } + } + } else { + // If the parameter is not defined in the OpenAPI operation, skip or log it + println('Unknown parameter: ${param_name}') + } + } - // Encode the parameter map to JSON if needed - params << json.encode(param_map.str()) - } + // Encode the parameter map to JSON if needed + params << json.encode(param_map.str()) + } - call := ProcedureCall{ - method: request.operation.operation_id - params: "[${params.join(',')}]" // Keep as a string since ProcedureCall expects a string - } + call := ProcedureCall{ + method: request.operation.operation_id + params: '[${params.join(',')}]' // Keep as a string since ProcedureCall expects a string + } - // Process the procedure call - procedure_response := handler.processor.process( - call, - ProcessParams{ - timeout: 30 // Set timeout in seconds - } - ) or { - // Handle ProcedureError - if err is processor.ProcedureError { - return Response{ - status: http.status_from_int(err.code()) // Map ProcedureError reason to HTTP status code - body: json.encode({ - 'error': err.msg() - }) - } - } - return error('Unexpected error: $err') - } + // Process the procedure call + procedure_response := handler.processor.process(call, ProcessParams{ + timeout: 30 // Set timeout in seconds + }) or { + // Handle ProcedureError + if err is processor.ProcedureError { + return Response{ + status: http.status_from_int(err.code()) // Map ProcedureError reason to HTTP status code + body: json.encode({ + 'error': err.msg() + }) + } + } + return error('Unexpected error: ${err}') + } - // Convert returned procedure response to OpenAPI response - return Response{ - status: http.Status.ok // Assuming success if no error - body: procedure_response.result - } + // Convert returned procedure response to OpenAPI response + return Response{ + status: http.Status.ok // Assuming success if no error + body: procedure_response.result + } } diff --git a/examples/installers/actrunner.vsh b/examples/installers/actrunner.vsh index 86bc33ca..0b718ca8 100755 --- a/examples/installers/actrunner.vsh +++ b/examples/installers/actrunner.vsh @@ -4,4 +4,4 @@ import freeflowuniverse.herolib.installers.sysadmintools.actrunner import freeflowuniverse.herolib.installers.virt.herocontainers actrunner.install()! -//herocontainers.start()! +// herocontainers.start()! diff --git a/examples/installers/coredns.vsh b/examples/installers/coredns.vsh index 2dbe032c..7ead086d 100755 --- a/examples/installers/coredns.vsh +++ b/examples/installers/coredns.vsh @@ -1,7 +1,5 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run - import freeflowuniverse.herolib.installers.infra.coredns as coredns_installer - coredns_installer.install()! diff --git a/examples/installers/dagu.vsh b/examples/installers/dagu.vsh index b0c9ee76..d586c380 100755 --- a/examples/installers/dagu.vsh +++ b/examples/installers/dagu.vsh @@ -3,8 +3,8 @@ import freeflowuniverse.herolib.installers.sysadmintools.daguserver import freeflowuniverse.herolib.installers.infra.zinit -//make sure zinit is there and running, will restart it if needed -mut z:=zinit.get()! +// make sure zinit is there and running, will restart it if needed +mut z := zinit.get()! z.destroy()! z.start()! diff --git a/examples/installers/dagu_server.vsh b/examples/installers/dagu_server.vsh index ef763053..f9604090 100755 --- a/examples/installers/dagu_server.vsh +++ b/examples/installers/dagu_server.vsh @@ -2,16 +2,15 @@ import freeflowuniverse.herolib.installers.sysadmintools.daguserver -//will call the installer underneith +// will call the installer underneith -mut dserver:=daguserver.new()! +mut dserver := daguserver.new()! dserver.install()! dserver.restart()! -println("DAGU installed & running") - -mut dagucl:=dserver.client()! +println('DAGU installed & running') +mut dagucl := dserver.client()! // name string // The name of the DAG, which is optional. The default name is the name of the file. // description ?string // A brief description of the DAG. @@ -23,9 +22,8 @@ mut dagucl:=dserver.client()! // max_active_runs ?int // The maximum number of parallel running steps. // max_cleanup_time_sec ?int // The maximum time to wait after sending a TERM signal to running steps before killing them. - -mut mydag:=dagucl.dag_new( - nameswhere:"test11" +mut mydag := dagucl.dag_new( + nameswhere: 'test11' ) // nr int @[required] @@ -43,19 +41,18 @@ mut mydag:=dagucl.dag_new( // retry_interval int = 5 mydag.step_add( - script : "ls /tmp" - retry_interval:1 - retry_nr:3 - )! + script: 'ls /tmp' + retry_interval: 1 + retry_nr: 3 +)! mydag.step_add( - script : "ls /root" - retry_interval:1 - retry_nr:3 - )! + script: 'ls /root' + retry_interval: 1 + retry_nr: 3 +)! - -dagresult:=dagucl.dag_register(mydag,start:true)! +dagresult := dagucl.dag_register(mydag, start: true)! println(dagresult) -println("DAGU should have new steps") +println('DAGU should have new steps') diff --git a/examples/installers/gitea.vsh b/examples/installers/gitea.vsh index 7f52cbcf..346c3037 100755 --- a/examples/installers/gitea.vsh +++ b/examples/installers/gitea.vsh @@ -3,11 +3,11 @@ import freeflowuniverse.herolib.installers.gitea mut g := gitea.new( - passwd: '123' - postgresql_path: '/tmp/db' + passwd: '123' + postgresql_path: '/tmp/db' postgresql_reset: true - domain: 'git.meet.tf' - appname: 'ourworld' + domain: 'git.meet.tf' + appname: 'ourworld' )! // postgresql will be same passwd g.restart()! diff --git a/examples/installers/griddriver.vsh b/examples/installers/griddriver.vsh index 9f996080..6535ec13 100755 --- a/examples/installers/griddriver.vsh +++ b/examples/installers/griddriver.vsh @@ -1,5 +1,6 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run import freeflowuniverse.herolib.installers.threefold.griddriver + mut griddriver_installer := griddriver.get()! griddriver_installer.install()! diff --git a/examples/installers/hero_install.vsh b/examples/installers/hero_install.vsh index 277d2b13..a2a483ed 100755 --- a/examples/installers/hero_install.vsh +++ b/examples/installers/hero_install.vsh @@ -5,4 +5,4 @@ import freeflowuniverse.herolib.installers.sysadmintools.daguserver import freeflowuniverse.herolib.installers.sysadmintools.b2 as b2_installer vlang.v_analyzer_install()! -daguserver.new()! //will install & start a daguserver +daguserver.new()! // will install & start a daguserver diff --git a/examples/installers/herocontainers.vsh b/examples/installers/herocontainers.vsh index 3917c6cb..531d1623 100755 --- a/examples/installers/herocontainers.vsh +++ b/examples/installers/herocontainers.vsh @@ -2,14 +2,13 @@ import freeflowuniverse.herolib.osal import freeflowuniverse.herolib.installers.lang.golang - import freeflowuniverse.herolib.installers.virt.podman as podman_installer import freeflowuniverse.herolib.installers.virt.buildah as buildah_installer -mut podman_installer0:= podman_installer.get()! -mut buildah_installer0:= buildah_installer.get()! +mut podman_installer0 := podman_installer.get()! +mut buildah_installer0 := buildah_installer.get()! -//podman_installer0.destroy()! //will remove all +// podman_installer0.destroy()! //will remove all podman_installer0.install()! buildah_installer0.install()! diff --git a/examples/installers/installers.vsh b/examples/installers/installers.vsh index 6d3c63ba..8f1c5565 100755 --- a/examples/installers/installers.vsh +++ b/examples/installers/installers.vsh @@ -20,10 +20,8 @@ mycelium_installer.install()! // mut screens:=screen.new()! // println(screens) - // dagu_installer.check(secret:"1234")! - vlang.v_analyzer_install()! // b2_installer.install()! diff --git a/examples/installers/mycelium.vsh b/examples/installers/mycelium.vsh index 5cd2ecfc..50791b0e 100755 --- a/examples/installers/mycelium.vsh +++ b/examples/installers/mycelium.vsh @@ -1,4 +1,5 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run import freeflowuniverse.herolib.installers.net.mycelium as mycelium_installer + mycelium_installer.start()! diff --git a/examples/installers/postgresql.vsh b/examples/installers/postgresql.vsh index 6d25764e..adabfdec 100755 --- a/examples/installers/postgresql.vsh +++ b/examples/installers/postgresql.vsh @@ -1,11 +1,9 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run - import time - import freeflowuniverse.herolib.installers.db.postgresql -mut db:= postgresql.get()! +mut db := postgresql.get()! // db.destroy()! db.start()! diff --git a/examples/installers/youki.vsh b/examples/installers/youki.vsh index bac214b0..d23fa428 100755 --- a/examples/installers/youki.vsh +++ b/examples/installers/youki.vsh @@ -1,8 +1,7 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run - import freeflowuniverse.herolib.installers.virt.youki -mut youki_installer:= youki.get()! +mut youki_installer := youki.get()! youki_installer.install()! diff --git a/examples/lang/python/pythonexample.vsh b/examples/lang/python/pythonexample.vsh index 30509da8..40ee55ed 100755 --- a/examples/lang/python/pythonexample.vsh +++ b/examples/lang/python/pythonexample.vsh @@ -1,33 +1,28 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run - import freeflowuniverse.herolib.lang.python -import json - +import json pub struct Person { - name string - age int - is_member bool - skills []string + name string + age int + is_member bool + skills []string } +mut py := python.new(name: 'test')! // a python env with name test +// py.update()! +py.pip('ipython')! -mut py:=python.new(name:'test')! //a python env with name test -//py.update()! -py.pip("ipython")! +nrcount := 5 +cmd := $tmpl('pythonexample.py') - -nrcount:=5 -cmd:=$tmpl("pythonexample.py") - -mut res:="" -for i in 0..5{ +mut res := '' +for i in 0 .. 5 { println(i) - res=py.exec(cmd:cmd)! - + res = py.exec(cmd: cmd)! } -//res:=py.exec(cmd:cmd)! +// res:=py.exec(cmd:cmd)! -person:=json.decode(Person,res)! +person := json.decode(Person, res)! println(person) diff --git a/examples/osal/download/download_example.vsh b/examples/osal/download/download_example.vsh index 0130ad10..0ae2d2e1 100755 --- a/examples/osal/download/download_example.vsh +++ b/examples/osal/download/download_example.vsh @@ -3,10 +3,10 @@ import freeflowuniverse.herolib.osal { download } mut p := download( - url: 'https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/@name' - name: 'echarts.min.js' - reset: false - dest: '/tmp/@name' + url: 'https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/@name' + name: 'echarts.min.js' + reset: false + dest: '/tmp/@name' minsize_kb: 1000 maxsize_kb: 5000 )! diff --git a/examples/osal/ping/portforward.vsh b/examples/osal/ping/portforward.vsh index 0a8b5a62..9fb73241 100755 --- a/examples/osal/ping/portforward.vsh +++ b/examples/osal/ping/portforward.vsh @@ -6,6 +6,18 @@ import freeflowuniverse.herolib.builder // address string @[required] // remote_port int @[required] -builder.portforward_to_local(name:"holo1",address:"[302:1d81:cef8:3049:fbe1:69ba:bd8c:52ec]",remote_port:45579)! -builder.portforward_to_local(name:"holo2",address:"[302:1d81:cef8:3049:fbe1:69ba:bd8c:52ec]",remote_port:34639)! -builder.portforward_to_local(name:"holoui",address:"[302:1d81:cef8:3049:fbe1:69ba:bd8c:52ec]",remote_port:8282)! +builder.portforward_to_local( + name: 'holo1' + address: '[302:1d81:cef8:3049:fbe1:69ba:bd8c:52ec]' + remote_port: 45579 +)! +builder.portforward_to_local( + name: 'holo2' + address: '[302:1d81:cef8:3049:fbe1:69ba:bd8c:52ec]' + remote_port: 34639 +)! +builder.portforward_to_local( + name: 'holoui' + address: '[302:1d81:cef8:3049:fbe1:69ba:bd8c:52ec]' + remote_port: 8282 +)! diff --git a/examples/osal/process/process_bash/processtest.v b/examples/osal/process/process_bash/processtest.v index 43a1b08a..d070580c 100644 --- a/examples/osal/process/process_bash/processtest.v +++ b/examples/osal/process/process_bash/processtest.v @@ -8,9 +8,8 @@ fn main() { } fn do1() ! { - - mut p := os.new_process("/bin/bash") - p.set_work_folder("/tmp") + mut p := os.new_process('/bin/bash') + p.set_work_folder('/tmp') p.set_redirect_stdio() p.use_stdio_ctl = true p.use_pgroup = true @@ -18,9 +17,9 @@ fn do1() ! { p.run() // p.set_args("") // time.sleep(100 * time.millisecond) - println( "alive: ${p.is_alive()}") + println('alive: ${p.is_alive()}') assert p.is_alive() - + defer { p.wait() p.close() @@ -33,32 +32,28 @@ fn do1() ! { // println(p.stderr_slurp()) // println(3) // } - mut counter:=0 + mut counter := 0 for { - counter+=1 + counter += 1 println(counter) - out:=p.pipe_read(.stdout) or {""} - if out.len>0{ - println("o") + out := p.pipe_read(.stdout) or { '' } + if out.len > 0 { + println('o') println(out) } - err:=p.pipe_read(.stderr) or {""} - if err.len>0{ - println("e") + err := p.pipe_read(.stderr) or { '' } + if err.len > 0 { + println('e') println(err) } time.sleep(100 * time.millisecond) - if counter==2{ + if counter == 2 { p.stdin_write("echo '111'\n") // os.fd_close(p.stdio_fd[0]) } - if counter==20{ + if counter == 20 { p.stdin_write("echo '2222'\n") // os.fd_close(p.stdio_fd[0]) - } + } } } - - - - diff --git a/examples/osal/process/process_python/processtest.v b/examples/osal/process/process_python/processtest.v index 555a66a4..c2e165f3 100644 --- a/examples/osal/process/process_python/processtest.v +++ b/examples/osal/process/process_python/processtest.v @@ -8,19 +8,18 @@ fn main() { } fn do1() ! { - - mut p := os.new_process("/opt/homebrew/bin/python3") - p.set_work_folder("/tmp") + mut p := os.new_process('/opt/homebrew/bin/python3') + p.set_work_folder('/tmp') p.set_redirect_stdio() p.use_stdio_ctl = true p.use_pgroup = true - p.set_args(['-i','-q']) + p.set_args(['-i', '-q']) p.run() // p.set_args("") // time.sleep(100 * time.millisecond) - println( "alive: ${p.is_alive()}") + println('alive: ${p.is_alive()}') assert p.is_alive() - + defer { p.wait() p.close() @@ -33,99 +32,88 @@ fn do1() ! { // println(p.stderr_slurp()) // println(3) // } - mut counter:=0 + mut counter := 0 for { - counter+=1 + counter += 1 println(counter) - out:=p.pipe_read(.stdout) or {""} - if out.len>0{ - println("o") + out := p.pipe_read(.stdout) or { '' } + if out.len > 0 { + println('o') println(out) } - err:=p.pipe_read(.stderr) or {""} - if err.len>0{ - println("e") + err := p.pipe_read(.stderr) or { '' } + if err.len > 0 { + println('e') println(err) } time.sleep(100 * time.millisecond) - if counter==2{ + if counter == 2 { p.stdin_write("print('something')\n\n\n") // os.fd_close(p.stdio_fd[0]) } - if counter==20{ + if counter == 20 { p.stdin_write("print('something else')\n\n\n") // os.fd_close(p.stdio_fd[0]) - } + } } } - - - - - fn do2() ! { - - mut p := os.new_process("/opt/homebrew/bin/python3") - p.set_work_folder("/tmp") + mut p := os.new_process('/opt/homebrew/bin/python3') + p.set_work_folder('/tmp') p.set_redirect_stdio() p.use_stdio_ctl = true p.use_pgroup = true p.run() // p.set_args("") // time.sleep(100 * time.millisecond) - println( "alive: ${p.is_alive()}") + println('alive: ${p.is_alive()}') assert p.is_alive() - + defer { p.wait() p.close() } for { - fdi:=p.stdio_fd[0] - fdo:=p.stdio_fd[1] - fde:=p.stdio_fd[2] + fdi := p.stdio_fd[0] + fdo := p.stdio_fd[1] + fde := p.stdio_fd[2] println(1) - if os.fd_is_pending(fdo){ + if os.fd_is_pending(fdo) { println(1.1) println(os.fd_slurp(fdo)) } println(2) - if os.fd_is_pending(fde){ + if os.fd_is_pending(fde) { println(2.1) println(os.fd_slurp(fde)) - } + } println(3) time.sleep(100 * time.millisecond) } - mut counter:=0 + mut counter := 0 for { - counter+=1 + counter += 1 println(counter) - out:=p.pipe_read(.stdout) or {""} - if out.len>0{ - println("o") + out := p.pipe_read(.stdout) or { '' } + if out.len > 0 { + println('o') println(out) } - err:=p.pipe_read(.stderr) or {""} - if err.len>0{ - println("e") + err := p.pipe_read(.stderr) or { '' } + if err.len > 0 { + println('e') println(err) } time.sleep(100 * time.millisecond) - if counter==2{ + if counter == 2 { p.stdin_write("print('something')\n\n\n") os.fd_close(p.stdio_fd[0]) } - if counter==20{ + if counter == 20 { p.stdin_write("print('something else')\n\n\n") os.fd_close(p.stdio_fd[0]) - } + } } } - - - - - diff --git a/examples/osal/sandbox/examples/sandbox_example.v b/examples/osal/sandbox/examples/sandbox_example.v index 09b3046c..05330121 100644 --- a/examples/osal/sandbox/examples/sandbox_example.v +++ b/examples/osal/sandbox/examples/sandbox_example.v @@ -11,10 +11,10 @@ fn do() ! { // get 2 bootstraps to work from f.debootstrap(imagename: 'debian', reset: false)! // if reset then will download again f.debootstrap( - imagename: 'ubuntu22' + imagename: 'ubuntu22' repository: 'http://de.archive.ubuntu.com/ubuntu' - release: 'jammy' - reset: false + release: 'jammy' + reset: false )! // mut c := f.container_new(startcmd: ["ls", "/", "/proc"])! diff --git a/examples/osal/sshagent/sshagent_example.v b/examples/osal/sshagent/sshagent_example.v index ca7cbf94..d8d418a2 100644 --- a/examples/osal/sshagent/sshagent_example.v +++ b/examples/osal/sshagent/sshagent_example.v @@ -3,12 +3,12 @@ module main import freeflowuniverse.herolib.osal.sshagent fn do1() ! { - mut agent:=sshagent.new()! + mut agent := sshagent.new()! println(agent) - k:=agent.get(name:"kds") or {panic("notgound")} + k := agent.get(name: 'kds') or { panic('notgound') } println(k) - mut k2:=agent.get(name:"books") or {panic("notgound")} + mut k2 := agent.get(name: 'books') or { panic('notgound') } k2.load()! println(k2.agent) @@ -18,11 +18,8 @@ fn do1() ! { println(k2.agent) // println(agent) - } - - fn main() { do1() or { panic(err) } } diff --git a/examples/osal/startup_manager.vsh b/examples/osal/startup_manager.vsh index dadb055c..1d068238 100755 --- a/examples/osal/startup_manager.vsh +++ b/examples/osal/startup_manager.vsh @@ -3,21 +3,21 @@ import freeflowuniverse.herolib.installers.infra.zinit as zinitinstaller import freeflowuniverse.herolib.sysadmin.startupmanager -mut z:=zinitinstaller.get()! +mut z := zinitinstaller.get()! z.destroy()! z.install()! -println("zinit installed") +println('zinit installed') -cmd:= '/usr/local/bin/zinit init' -name:= 'zinit' +cmd := '/usr/local/bin/zinit init' +name := 'zinit' mut sm := startupmanager.get()! println(sm.list()!) sm.new( - name: name - cmd: cmd - start:false + name: name + cmd: cmd + start: false )! println(sm.list()!) diff --git a/examples/osal/systemd.vsh b/examples/osal/systemd.vsh index 19deb873..becb9d1f 100755 --- a/examples/osal/systemd.vsh +++ b/examples/osal/systemd.vsh @@ -2,13 +2,12 @@ import freeflowuniverse.herolib.osal.systemd - mut systemdfactory := systemd.new()! // mut systemdprocess := systemdfactory.new( // cmd: '/usr/local/bin/zinit init' // name: 'zinit' // description: 'a super easy to use startup manager.' // )! -l:=systemd.process_list()! +l := systemd.process_list()! println(l) -systemdfactory.destroy("zinit")! +systemdfactory.destroy('zinit')! diff --git a/examples/osal/ufw.vsh b/examples/osal/ufw.vsh index 1fb4c980..ad602a78 100755 --- a/examples/osal/ufw.vsh +++ b/examples/osal/ufw.vsh @@ -29,8 +29,8 @@ ruleset.deny( ruleset.deny( port: 21 from: '2001:db8::1' - udp: true - tcp: false + udp: true + tcp: false ipv6: true ) diff --git a/examples/osal/ufw_play.vsh b/examples/osal/ufw_play.vsh index 3d22829d..ebdc5822 100755 --- a/examples/osal/ufw_play.vsh +++ b/examples/osal/ufw_play.vsh @@ -35,5 +35,5 @@ heroscript := " " mut plbook := playbook.new(text: heroscript)! -rs:=ufw.play(mut plbook)! +rs := ufw.play(mut plbook)! println(rs) diff --git a/examples/osal/zinit/simple/zinit.vsh b/examples/osal/zinit/simple/zinit.vsh index 92efc6db..68abaa41 100644 --- a/examples/osal/zinit/simple/zinit.vsh +++ b/examples/osal/zinit/simple/zinit.vsh @@ -18,7 +18,7 @@ mut z := zinit.new()! p := z.process_new( name: 'test' - cmd: '/bin/bash' + cmd: '/bin/bash' )! println(p) diff --git a/examples/threefold/grid/deploy/create_update_deployments.vsh b/examples/threefold/grid/deploy/create_update_deployments.vsh index 86df90c9..cc1d41a8 100755 --- a/examples/threefold/grid/deploy/create_update_deployments.vsh +++ b/examples/threefold/grid/deploy/create_update_deployments.vsh @@ -17,23 +17,23 @@ fn test_create_and_update_deployment() ! { twin_id := deployer.client.get_user_twin()! println('your wireguard privatekey is ${user_privkey[0]}') mut network := models.Znet{ - ip_range: '10.1.0.0/16' - subnet: '10.1.1.0/24' + ip_range: '10.1.0.0/16' + subnet: '10.1.1.0/24' wireguard_private_key: node_privkey[0] // node private key wireguard_listen_port: 3012 - peers: [ + peers: [ models.Peer{ - subnet: '10.1.2.0/24' + subnet: '10.1.2.0/24' wireguard_public_key: user_privkey[1] // user public key - allowed_ips: ['10.1.2.0/24', '100.64.1.2/32'] + allowed_ips: ['10.1.2.0/24', '100.64.1.2/32'] }, ] } mut znet_workload := models.Workload{ - version: 0 - name: 'networkaa' - type_: models.workload_types.network - data: json.encode_pretty(network) + version: 0 + name: 'networkaa' + type_: models.workload_types.network + data: json.encode_pretty(network) description: 'test network2' } @@ -44,7 +44,7 @@ fn test_create_and_update_deployment() ! { zmount_workload := zmount.to_workload(name: disk_name) mount := models.Mount{ - name: disk_name + name: disk_name mountpoint: '/disk1' } @@ -55,39 +55,39 @@ fn test_create_and_update_deployment() ! { ip_workload := ip.to_workload(name: public_ip_name) zmachine := models.Zmachine{ - flist: 'https://hub.grid.tf/tf-official-apps/base:latest.flist' - entrypoint: '/sbin/zinit init' - network: models.ZmachineNetwork{ - public_ip: public_ip_name + flist: 'https://hub.grid.tf/tf-official-apps/base:latest.flist' + entrypoint: '/sbin/zinit init' + network: models.ZmachineNetwork{ + public_ip: public_ip_name interfaces: [ models.ZNetworkInterface{ network: 'networkaa' - ip: '10.1.1.3' + ip: '10.1.1.3' }, ] - planetary: true + planetary: true } compute_capacity: models.ComputeCapacity{ - cpu: 1 + cpu: 1 memory: i64(1024) * 1024 * 1024 * 2 } - env: { + env: { 'SSH_KEY': pubkey } - mounts: [mount] + mounts: [mount] } mut zmachine_workload := models.Workload{ - version: 0 - name: 'vm2' - type_: models.workload_types.zmachine - data: json.encode(zmachine) + version: 0 + name: 'vm2' + type_: models.workload_types.zmachine + data: json.encode(zmachine) description: 'zmachine test' } zlogs := models.ZLogs{ zmachine: 'vm2' - output: 'wss://example_ip.com:9000' + output: 'wss://example_ip.com:9000' } zlogs_workload := zlogs.to_workload(name: 'myzlogswl') @@ -98,17 +98,17 @@ fn test_create_and_update_deployment() ! { zdb_workload := zdb.to_workload(name: 'myzdb') mut deployment := models.Deployment{ - version: 0 - twin_id: twin_id - description: 'zm kjasdf1nafvbeaf1234t21' - workloads: [znet_workload, zmount_workload, zmachine_workload, zlogs_workload, zdb_workload, - ip_workload] + version: 0 + twin_id: twin_id + description: 'zm kjasdf1nafvbeaf1234t21' + workloads: [znet_workload, zmount_workload, zmachine_workload, zlogs_workload, + zdb_workload, ip_workload] signature_requirement: models.SignatureRequirement{ weight_required: 1 - requests: [ + requests: [ models.SignatureRequest{ twin_id: twin_id - weight: 1 + weight: 1 }, ] } @@ -133,7 +133,7 @@ fn test_create_and_update_deployment() ! { } gw_name := models.GatewayNameProxy{ - name: 'mygwname1' + name: 'mygwname1' backends: ['http://[${zmachine_planetary_ip}]:9000'] } gw_name_wl := gw_name.to_workload(name: 'mygwname1') diff --git a/examples/threefold/grid/deploy/deploy_gw_fqdn.vsh b/examples/threefold/grid/deploy/deploy_gw_fqdn.vsh index 9b231e49..d6b12e46 100755 --- a/examples/threefold/grid/deploy/deploy_gw_fqdn.vsh +++ b/examples/threefold/grid/deploy/deploy_gw_fqdn.vsh @@ -17,8 +17,8 @@ fn main() { gw := models.GatewayFQDNProxy{ tls_passthrough: false - backends: ['http://1.1.1.1:9000'] - fqdn: 'domaind.gridtesting.xyz' + backends: ['http://1.1.1.1:9000'] + fqdn: 'domaind.gridtesting.xyz' } wl := gw.to_workload(name: 'mywlname') node_id := u32(14) @@ -30,16 +30,16 @@ fn main() { logger.info('preparing the deployment..') signature_requirement := models.SignatureRequirement{ weight_required: 1 - requests: [ + requests: [ models.SignatureRequest{ twin_id: deployer.twin_id - weight: 1 + weight: 1 }, ] } mut deployment := models.new_deployment( - twin_id: deployer.twin_id - workloads: [wl] + twin_id: deployer.twin_id + workloads: [wl] signature_requirement: signature_requirement ) diff --git a/examples/threefold/grid/deploy/deploy_gw_name.vsh b/examples/threefold/grid/deploy/deploy_gw_name.vsh index 3f5fb6f1..86923384 100755 --- a/examples/threefold/grid/deploy/deploy_gw_name.vsh +++ b/examples/threefold/grid/deploy/deploy_gw_name.vsh @@ -17,8 +17,8 @@ fn main() { gw := models.GatewayNameProxy{ tls_passthrough: false - backends: ['http://1.1.1.1'] - name: 'hamada_gw' + backends: ['http://1.1.1.1'] + name: 'hamada_gw' } wl := gw.to_workload(name: 'hamada_gw') @@ -28,17 +28,17 @@ fn main() { signature_requirement := models.SignatureRequirement{ weight_required: 1 - requests: [ + requests: [ models.SignatureRequest{ twin_id: deployer.twin_id - weight: 1 + weight: 1 }, ] } mut deployment := models.new_deployment( - twin_id: deployer.twin_id - workloads: [wl] + twin_id: deployer.twin_id + workloads: [wl] signature_requirement: signature_requirement ) diff --git a/examples/threefold/grid/deploy/deploy_vm.vsh b/examples/threefold/grid/deploy/deploy_vm.vsh index 12b16d28..f6aa4e5e 100755 --- a/examples/threefold/grid/deploy/deploy_vm.vsh +++ b/examples/threefold/grid/deploy/deploy_vm.vsh @@ -17,38 +17,38 @@ fn main() { network_name := 'network1' wg_port := deployer.assign_wg_port(node_id)! mut network := models.Znet{ - ip_range: '10.1.0.0/16' - subnet: '10.1.1.0/24' + ip_range: '10.1.0.0/16' + subnet: '10.1.1.0/24' wireguard_private_key: 'GDU+cjKrHNJS9fodzjFDzNFl5su3kJXTZ3ipPgUjOUE=' wireguard_listen_port: wg_port - peers: [ + peers: [ models.Peer{ - subnet: '10.1.2.0/24' + subnet: '10.1.2.0/24' wireguard_public_key: '4KTvZS2KPWYfMr+GbiUUly0ANVg8jBC7xP9Bl79Z8zM=' - allowed_ips: ['10.1.2.0/24', '100.64.1.2/32'] + allowed_ips: ['10.1.2.0/24', '100.64.1.2/32'] }, ] } mut znet_workload := network.to_workload(name: network_name, description: 'test_network1') zmachine := models.Zmachine{ - flist: 'https://hub.grid.tf/tf-official-apps/threefoldtech-ubuntu-22.04.flist' - network: models.ZmachineNetwork{ - public_ip: '' + flist: 'https://hub.grid.tf/tf-official-apps/threefoldtech-ubuntu-22.04.flist' + network: models.ZmachineNetwork{ + public_ip: '' interfaces: [ models.ZNetworkInterface{ network: network_name - ip: '10.1.1.3' + ip: '10.1.1.3' }, ] - planetary: true + planetary: true } - entrypoint: '/sbin/zinit init' + entrypoint: '/sbin/zinit init' compute_capacity: models.ComputeCapacity{ - cpu: 1 + cpu: 1 memory: i64(1024) * 1024 * 1024 * 2 } - env: { + env: { 'SSH_KEY': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTwULSsUubOq3VPWL6cdrDvexDmjfznGydFPyaNcn7gAL9lRxwFbCDPMj7MbhNSpxxHV2+/iJPQOTVJu4oc1N7bPP3gBCnF51rPrhTpGCt5pBbTzeyNweanhedkKDsCO2mIEh/92Od5Hg512dX4j7Zw6ipRWYSaepapfyoRnNSriW/s3DH/uewezVtL5EuypMdfNngV/u2KZYWoeiwhrY/yEUykQVUwDysW/xUJNP5o+KSTAvNSJatr3FbuCFuCjBSvageOLHePTeUwu6qjqe+Xs4piF1ByO/6cOJ8bt5Vcx0bAtI8/MPApplUU/JWevsPNApvnA/ntffI+u8DCwgP' } } @@ -56,18 +56,18 @@ fn main() { signature_requirement := models.SignatureRequirement{ weight_required: 1 - requests: [ + requests: [ models.SignatureRequest{ twin_id: deployer.twin_id - weight: 1 + weight: 1 }, ] } mut deployment := models.new_deployment( - twin_id: deployer.twin_id - description: 'test deployment' - workloads: [znet_workload, zmachine_workload] + twin_id: deployer.twin_id + description: 'test deployment' + workloads: [znet_workload, zmachine_workload] signature_requirement: signature_requirement ) deployment.add_metadata('vm', 'SimpleVM') diff --git a/examples/threefold/grid/deploy/deploy_vm_high_level.vsh b/examples/threefold/grid/deploy/deploy_vm_high_level.vsh index 0e4c8426..1bdfb99d 100755 --- a/examples/threefold/grid/deploy/deploy_vm_high_level.vsh +++ b/examples/threefold/grid/deploy/deploy_vm_high_level.vsh @@ -15,7 +15,7 @@ fn test_deploy_vm_hight_level(node_id u32) ! { mut deployer := tfgrid.new_deployer(mnemonics, chain_network, mut logger)! vm := models.VM{ - name: 'vm1' + name: 'vm1' env_vars: { 'SSH_KEY': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTwULSsUubOq3VPWL6cdrDvexDmjfznGydFPyaNcn7gAL9lRxwFbCDPMj7MbhNSpxxHV2+/iJPQOTVJu4oc1N7bPP3gBCnF51rPrhTpGCt5pBbTzeyNweanhedkKDsCO2mIEh/92Od5Hg512dX4j7Zw6ipRWYSaepapfyoRnNSriW/s3DH/uewezVtL5EuypMdfNngV/u2KZYWoeiwhrY/yEUykQVUwDysW/xUJNP5o+KSTAvNSJatr3FbuCFuCjBSvageOLHePTeUwu6qjqe+Xs4piF1ByO/6cOJ8bt5Vcx0bAtI8/MPApplUU/JWevsPNApvnA/ntffI+u8DCwgP' } diff --git a/examples/threefold/grid/deploy/deploy_zdb.vsh b/examples/threefold/grid/deploy/deploy_zdb.vsh index c3ff3a24..c6c8d180 100755 --- a/examples/threefold/grid/deploy/deploy_zdb.vsh +++ b/examples/threefold/grid/deploy/deploy_zdb.vsh @@ -16,8 +16,8 @@ fn main() { mut deployer := tfgrid.new_deployer(mnemonics, chain_network, mut logger)! zdb := models.Zdb{ - size: u64(2) * 1024 * 1024 - mode: 'user' + size: u64(2) * 1024 * 1024 + mode: 'user' password: 'pass' } @@ -25,17 +25,17 @@ fn main() { signature_requirement := models.SignatureRequirement{ weight_required: 1 - requests: [ + requests: [ models.SignatureRequest{ twin_id: deployer.twin_id - weight: 1 + weight: 1 }, ] } mut deployment := models.new_deployment( - twin_id: deployer.twin_id - workloads: [wl] + twin_id: deployer.twin_id + workloads: [wl] signature_requirement: signature_requirement ) diff --git a/examples/threefold/grid/deploy/holochain_vm.vsh b/examples/threefold/grid/deploy/holochain_vm.vsh index 03a9b32a..7288285a 100755 --- a/examples/threefold/grid/deploy/holochain_vm.vsh +++ b/examples/threefold/grid/deploy/holochain_vm.vsh @@ -29,7 +29,7 @@ fn main() { chain_net_enum := get_chain_network(chain_network)! mut deployer := tfgrid.new_deployer(mnemonics, chain_net_enum, mut logger)! - + mut workloads := []models.Workload{} node_id := get_node_id(chain_net_enum, memory, disk, cpu, public_ip)! // node_id := u32(150) @@ -38,20 +38,19 @@ fn main() { network_name := 'net_${rand.string(5).to_lower()}' // autocreate a network wg_port := deployer.assign_wg_port(node_id)! mut network := models.Znet{ - ip_range: '10.1.0.0/16' // auto-assign - subnet: '10.1.1.0/24' // auto-assign + ip_range: '10.1.0.0/16' // auto-assign + subnet: '10.1.1.0/24' // auto-assign wireguard_private_key: 'GDU+cjKrHNJS9fodzjFDzNFl5su3kJXTZ3ipPgUjOUE=' // autocreate wireguard_listen_port: wg_port - mycelium: models.Mycelium{ + mycelium: models.Mycelium{ hex_key: rand.string(32).bytes().hex() } - } - + workloads << network.to_workload(name: network_name, description: 'test_network1') mut public_ip_name := '' - if public_ip{ + if public_ip { public_ip_name = rand.string(5).to_lower() workloads << models.PublicIP{ v4: true @@ -59,52 +58,52 @@ fn main() { } zmachine := models.Zmachine{ - flist: 'https://hub.grid.tf/mariobassem1.3bot/threefolddev-holochain-latest.flist' // from user or default to ubuntu - network: models.ZmachineNetwork{ + flist: 'https://hub.grid.tf/mariobassem1.3bot/threefolddev-holochain-latest.flist' // from user or default to ubuntu + network: models.ZmachineNetwork{ interfaces: [ models.ZNetworkInterface{ network: network_name - ip: '10.1.1.3' + ip: '10.1.1.3' }, ] - public_ip: public_ip_name - planetary: true - mycelium: models.MyceliumIP{ - network: network_name + public_ip: public_ip_name + planetary: true + mycelium: models.MyceliumIP{ + network: network_name hex_seed: rand.string(6).bytes().hex() } } - entrypoint: '/sbin/zinit init' // from user or default + entrypoint: '/sbin/zinit init' // from user or default compute_capacity: models.ComputeCapacity{ - cpu: u8(cpu) + cpu: u8(cpu) memory: i64(memory) * 1024 * 1024 * 1024 } - size: u64(disk) * 1024 * 1024 * 1024 - env: { + size: u64(disk) * 1024 * 1024 * 1024 + env: { 'SSH_KEY': ssh_key 'CODE_SERVER_PASSWORD': code_server_pass } } workloads << zmachine.to_workload( - name: 'vm_${rand.string(5).to_lower()}' + name: 'vm_${rand.string(5).to_lower()}' description: 'zmachine_test' ) signature_requirement := models.SignatureRequirement{ weight_required: 1 - requests: [ + requests: [ models.SignatureRequest{ twin_id: deployer.twin_id - weight: 1 + weight: 1 }, ] } mut deployment := models.new_deployment( - twin_id: deployer.twin_id - description: 'holochain deployment' - workloads: workloads + twin_id: deployer.twin_id + description: 'holochain deployment' + workloads: workloads signature_requirement: signature_requirement ) deployment.add_metadata('vm', 'SimpleVM') @@ -147,7 +146,7 @@ fn get_chain_network(network string) !tfgrid.ChainNetwork { return chain_net_enum } -fn get_node_id(network tfgrid.ChainNetwork, memory int, disk int, cpu int, public_ip bool) !u32{ +fn get_node_id(network tfgrid.ChainNetwork, memory int, disk int, cpu int, public_ip bool) !u32 { gp_net := match network { .dev { gridproxy.TFGridNet.dev } .qa { gridproxy.TFGridNet.qa } @@ -157,15 +156,15 @@ fn get_node_id(network tfgrid.ChainNetwork, memory int, disk int, cpu int, publi mut gridproxy_client := gridproxy.get(gp_net, false)! mut free_ips := u64(0) - if public_ip{ + if public_ip { free_ips = 1 } mut node_it := gridproxy_client.get_nodes_has_resources( free_mru_gb: u64(memory) free_sru_gb: u64(disk) - free_cpu: u64(cpu) - free_ips: free_ips + free_cpu: u64(cpu) + free_ips: free_ips ) nodes := node_it.next() mut node_id := u32(0) // get from user or use gridproxy to get nodeid diff --git a/examples/threefold/grid/deploy/vm_with_gw_name.vsh b/examples/threefold/grid/deploy/vm_with_gw_name.vsh index 328974bf..a606479d 100755 --- a/examples/threefold/grid/deploy/vm_with_gw_name.vsh +++ b/examples/threefold/grid/deploy/vm_with_gw_name.vsh @@ -3,7 +3,7 @@ import freeflowuniverse.herolib.threefold.grid.models import freeflowuniverse.herolib.threefold.grid as tfgrid import freeflowuniverse.herolib.threefold.gridproxy -import freeflowuniverse.herolib.threefold.gridproxy.model {NodeFilter} +import freeflowuniverse.herolib.threefold.gridproxy.model { NodeFilter } import rand import log import os @@ -44,7 +44,7 @@ fn get_chain_network(network string) !tfgrid.ChainNetwork { return chain_net_enum } -fn get_node_id(network tfgrid.ChainNetwork, memory int, disk int, cpu int, public_ip bool, has_domain bool, available_for u64) !u32{ +fn get_node_id(network tfgrid.ChainNetwork, memory int, disk int, cpu int, public_ip bool, has_domain bool, available_for u64) !u32 { gp_net := match network { .dev { gridproxy.TFGridNet.dev } .qa { gridproxy.TFGridNet.qa } @@ -54,24 +54,24 @@ fn get_node_id(network tfgrid.ChainNetwork, memory int, disk int, cpu int, publi mut gridproxy_client := gridproxy.get(gp_net, false)! mut free_ips := u64(0) - if public_ip{ + if public_ip { free_ips = 1 } mut filter_ := NodeFilter{ - free_ips: free_ips - free_mru: u64(memory) * (1204 * 1204 * 1204) - free_sru: u64(disk) * (1204 * 1204 * 1204) - total_cru: u64(cpu) - domain: has_domain + free_ips: free_ips + free_mru: u64(memory) * (1204 * 1204 * 1204) + free_sru: u64(disk) * (1204 * 1204 * 1204) + total_cru: u64(cpu) + domain: has_domain available_for: available_for - status: 'up' - randomize: true - size: u64(1) + status: 'up' + randomize: true + size: u64(1) } nodes := gridproxy_client.get_nodes(filter_)! - if nodes.len != 1{ + if nodes.len != 1 { return error('cannot find a suitable node matching your specs') } @@ -105,8 +105,8 @@ logger.info('deploying on node: ${node_id}') network_name := 'net_${rand.string(5).to_lower()}' // autocreate a network wg_port := deployer.assign_wg_port(node_id)! mut network := models.Znet{ - ip_range: '10.1.0.0/16' // auto-assign - subnet: '10.1.1.0/24' // auto-assign + ip_range: '10.1.0.0/16' // auto-assign + subnet: '10.1.1.0/24' // auto-assign wireguard_private_key: 'GDU+cjKrHNJS9fodzjFDzNFl5su3kJXTZ3ipPgUjOUE=' // autocreate wireguard_listen_port: wg_port // mycelium: models.Mycelium{ @@ -117,7 +117,7 @@ mut network := models.Znet{ workloads << network.to_workload(name: network_name, description: 'test_network1') mut public_ip_name := '' -if public_ip{ +if public_ip { public_ip_name = rand.string(5).to_lower() workloads << models.PublicIP{ v4: true @@ -125,51 +125,51 @@ if public_ip{ } zmachine := models.Zmachine{ - flist: 'https://hub.grid.tf/tf-official-apps/base:latest.flist' - network: models.ZmachineNetwork{ + flist: 'https://hub.grid.tf/tf-official-apps/base:latest.flist' + network: models.ZmachineNetwork{ interfaces: [ models.ZNetworkInterface{ network: network_name - ip: '10.1.1.3' + ip: '10.1.1.3' }, ] - public_ip: public_ip_name - planetary: true + public_ip: public_ip_name + planetary: true // mycelium: models.MyceliumIP{ // network: network_name // hex_seed: rand.string(6).bytes().hex() // } } - entrypoint: '/sbin/zinit init' // from user or default + entrypoint: '/sbin/zinit init' // from user or default compute_capacity: models.ComputeCapacity{ - cpu: u8(cpu) + cpu: u8(cpu) memory: i64(memory) * 1024 * 1024 * 1024 } - size: u64(disk) * 1024 * 1024 * 1024 - env: { - 'SSH_KEY': ssh_key + size: u64(disk) * 1024 * 1024 * 1024 + env: { + 'SSH_KEY': ssh_key } } workloads << zmachine.to_workload( - name: 'vm_${rand.string(5).to_lower()}' + name: 'vm_${rand.string(5).to_lower()}' description: 'zmachine_test' ) signature_requirement := models.SignatureRequirement{ weight_required: 1 - requests: [ + requests: [ models.SignatureRequest{ twin_id: deployer.twin_id - weight: 1 + weight: 1 }, ] } mut deployment := models.new_deployment( - twin_id: deployer.twin_id - description: 'vm with gateway' - workloads: workloads + twin_id: deployer.twin_id + description: 'vm with gateway' + workloads: workloads signature_requirement: signature_requirement ) deployment.add_metadata('vm', 'SimpleVM') @@ -187,11 +187,11 @@ dl := deployer.get_deployment(contract_id, node_id) or { machine_res := get_machine_result(dl)! logger.info('zmachine result: ${machine_res}') -gw_name := rand.string(5).to_lower() +gw_name := rand.string(5).to_lower() gw := models.GatewayNameProxy{ tls_passthrough: false - backends: ['http://[${machine_res.planetary_ip}]:9000'] - name: gw_name + backends: ['http://[${machine_res.planetary_ip}]:9000'] + name: gw_name } gw_workload := gw.to_workload(name: gw_name) @@ -200,8 +200,8 @@ name_contract_id := deployer.client.create_name_contract(gw_name)! logger.info('name contract ${gw_workload.name} created with id ${name_contract_id}') mut gw_deployment := models.new_deployment( - twin_id: deployer.twin_id - workloads: [gw_workload] + twin_id: deployer.twin_id + workloads: [gw_workload] signature_requirement: signature_requirement ) diff --git a/examples/threefold/grid/utils/cancel_contract.vsh b/examples/threefold/grid/utils/cancel_contract.vsh index fe665a4d..a4056524 100755 --- a/examples/threefold/grid/utils/cancel_contract.vsh +++ b/examples/threefold/grid/utils/cancel_contract.vsh @@ -5,22 +5,22 @@ import log // Mock implementation for testing struct MockDeployer { mut: - logger &log.Log + logger &log.Log } fn (mut d MockDeployer) cancel_contract(contract_id u64) ! { - d.logger.info('Mock: Canceling contract ${contract_id}') + d.logger.info('Mock: Canceling contract ${contract_id}') } fn test_cancel_contract(contract_id u64) ! { - mut logger := &log.Log{} - logger.set_level(.debug) - mut deployer := MockDeployer{ - logger: logger - } - deployer.cancel_contract(contract_id)! + mut logger := &log.Log{} + logger.set_level(.debug) + mut deployer := MockDeployer{ + logger: logger + } + deployer.cancel_contract(contract_id)! } fn main() { - test_cancel_contract(u64(119497)) or { println('error happened: ${err}') } + test_cancel_contract(u64(119497)) or { println('error happened: ${err}') } } diff --git a/examples/threefold/grid/utils/tfgrid_config.vsh b/examples/threefold/grid/utils/tfgrid_config.vsh index 250ecd23..867f35fd 100755 --- a/examples/threefold/grid/utils/tfgrid_config.vsh +++ b/examples/threefold/grid/utils/tfgrid_config.vsh @@ -2,14 +2,14 @@ import freeflowuniverse.herolib.threefold.grid as tfgrid -mut cl := tfgrid.get("my_config")! +mut cl := tfgrid.get('my_config')! mut cfg := cl.config()! println(cl.instance) cfg = cl.config()! println(cfg) -if cfg.mnemonics == "" { +if cfg.mnemonics == '' { // will ask questions if not filled in yet cl.config_interactive()! } @@ -27,11 +27,11 @@ println(cl.instance) cfg = cl.config()! println(cfg) -cl = tfgrid.get("empty_config")! +cl = tfgrid.get('empty_config')! println(cl.instance) cfg = cl.config()! println(cfg) -// TO CONFIGURE NEW +// TO CONFIGURE NEW // cl.config_delete()! diff --git a/examples/threefold/grid/utils/zos_version.vsh b/examples/threefold/grid/utils/zos_version.vsh index e23aeee4..eadce80b 100755 --- a/examples/threefold/grid/utils/zos_version.vsh +++ b/examples/threefold/grid/utils/zos_version.vsh @@ -1,7 +1,7 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run import freeflowuniverse.herolib.threefold.grid as tfgrid -import freeflowuniverse.herolib.threefold.griddriver { Client } +import freeflowuniverse.herolib.threefold.griddriver import freeflowuniverse.herolib.ui.console import log diff --git a/examples/threefold/grid/vm_example.vsh b/examples/threefold/grid/vm_example.vsh index e91a2bf7..219d0fb5 100644 --- a/examples/threefold/grid/vm_example.vsh +++ b/examples/threefold/grid/vm_example.vsh @@ -1,40 +1,33 @@ - - -struct VMSpecs{ +struct VMSpecs { deployment_name string - name string - nodeid string - pub_sshkeys []string - flist string //if any, if used then ostype not used - ostype OSType + name string + nodeid string + pub_sshkeys []string + flist string // if any, if used then ostype not used + ostype OSType } -enum OSType{ +enum OSType { ubuntu_22_04 ubuntu_24_04 arch alpine } -struct VMDeployed{ - name string +struct VMDeployed { + name string nodeid string - //size .. - guid string + // size .. + guid string yggdrasil_ip string - mycelium_ip string - + mycelium_ip string } - pub fn (vm VMDeployed) builder_node() builder.Node { - } -//only connect to yggdrasil and mycelium +// only connect to yggdrasil and mycelium // -fn vm_deploy(args_ VMSpecs) VMDeployed{ - - deploymentstate_db.set(args.deployment_name,"vm_${args.name}",VMDeployed.json) - -} \ No newline at end of file +fn vm_deploy(args_ VMSpecs) VMDeployed { + deploymentstate_db.set(args.deployment_name, 'vm_${args.name}', VMDeployed.json) +} diff --git a/examples/threefold/grid/webgw_example.vsh b/examples/threefold/grid/webgw_example.vsh index 29316058..12120d00 100644 --- a/examples/threefold/grid/webgw_example.vsh +++ b/examples/threefold/grid/webgw_example.vsh @@ -1,18 +1,8 @@ - - - - - -struct WebGWArgs{ +struct WebGWArgs { deployment_name string //... - - } - - -//connect domain name, or exising to it -fn webgateway_rule_deploy(args_ WebGWArgs) []VMDeployed{ - -} \ No newline at end of file +// connect domain name, or exising to it +fn webgateway_rule_deploy(args_ WebGWArgs) []VMDeployed { +} diff --git a/examples/threefold/gridproxy/bill.vsh b/examples/threefold/gridproxy/bill.vsh index 99abd5cb..99de7f33 100755 --- a/examples/threefold/gridproxy/bill.vsh +++ b/examples/threefold/gridproxy/bill.vsh @@ -4,7 +4,7 @@ import freeflowuniverse.herolib.threefold.gridproxy import freeflowuniverse.herolib.ui.console contract_id := u64(119450) -mut gp_client := gridproxy.new(net:.dev, cache:false)! +mut gp_client := gridproxy.new(net: .dev, cache: false)! bills := gp_client.get_contract_hourly_bill(contract_id)! -console.print_debug("${bills}") +console.print_debug('${bills}') diff --git a/examples/threefold/gridproxy/contract.vsh b/examples/threefold/gridproxy/contract.vsh index 6bd9106e..67b97da9 100755 --- a/examples/threefold/gridproxy/contract.vsh +++ b/examples/threefold/gridproxy/contract.vsh @@ -11,10 +11,10 @@ fn get_contracts_example() ! { myfilter.contract_type = 'node' myfilter.twin_id = u64(5191) - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mycontracts := gp_client.get_contracts(myfilter)! - console.print_debug("${mycontracts}") + console.print_debug('${mycontracts}') } fn get_contract_by_id_example(contract_id u64) ! { @@ -22,10 +22,10 @@ fn get_contract_by_id_example(contract_id u64) ! { myfilter.contract_id = contract_id - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mycontracts := gp_client.get_contracts(myfilter)! - console.print_debug("${mycontracts}") + console.print_debug('${mycontracts}') } fn get_my_contracts_example() ! { @@ -37,7 +37,7 @@ fn get_my_contracts_example() ! { myfilter.twin_id = u64(deployer.twin_id) myfilter.state = 'created' - mut gp_client := gridproxy.new(net:.dev, cache:false)! + mut gp_client := gridproxy.new(net: .dev, cache: false)! mycontracts := gp_client.get_contracts(myfilter)! console.print_debug('${mycontracts}') diff --git a/examples/threefold/gridproxy/farm.vsh b/examples/threefold/gridproxy/farm.vsh index 5cf55a47..a7b68d6b 100755 --- a/examples/threefold/gridproxy/farm.vsh +++ b/examples/threefold/gridproxy/farm.vsh @@ -9,10 +9,10 @@ fn get_farms_example() ! { myfilter.country = 'Egypt' myfilter.total_ips = u64(10) - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! myfarms := gp_client.get_farms(myfilter)! - console.print_debug("${myfarms}") + console.print_debug('${myfarms}') } fn get_farm_by_name_example(farm_name string) ! { @@ -20,11 +20,11 @@ fn get_farm_by_name_example(farm_name string) ! { myfilter.name = farm_name - mut gp_client := gridproxy.new(net:.main, cache:true)! + mut gp_client := gridproxy.new(net: .main, cache: true)! myfarms := gp_client.get_farms(myfilter)! - console.print_debug("${myfarms}") + console.print_debug('${myfarms}') } get_farms_example()! -get_farm_by_name_example("freefarm")! +get_farm_by_name_example('freefarm')! diff --git a/examples/threefold/gridproxy/gateway.vsh b/examples/threefold/gridproxy/gateway.vsh index 88cfa4d7..d7968147 100755 --- a/examples/threefold/gridproxy/gateway.vsh +++ b/examples/threefold/gridproxy/gateway.vsh @@ -8,11 +8,11 @@ fn get_gateway_nodes_example() ! { myfilter.status = 'up' - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mygateways := gp_client.get_gateways(myfilter)! - - console.print_debug("${mygateways}") - console.print_debug("${mygateways.len}") + + console.print_debug('${mygateways}') + console.print_debug('${mygateways.len}') } fn get_gateway_by_id_example(node_id u64) ! { @@ -20,10 +20,10 @@ fn get_gateway_by_id_example(node_id u64) ! { myfilter.node_id = node_id - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mygateways := gp_client.get_gateways(myfilter)! - console.print_debug("${mygateways}") + console.print_debug('${mygateways}') } get_gateway_nodes_example()! diff --git a/examples/threefold/gridproxy/grid.vsh b/examples/threefold/gridproxy/grid.vsh index 31ed6b87..01c26f95 100755 --- a/examples/threefold/gridproxy/grid.vsh +++ b/examples/threefold/gridproxy/grid.vsh @@ -3,7 +3,7 @@ import freeflowuniverse.herolib.threefold.gridproxy import freeflowuniverse.herolib.ui.console -mut gp_client := gridproxy.new(net:.test, cache:true)! +mut gp_client := gridproxy.new(net: .test, cache: true)! // get twin list twins := gp_client.get_twins()! diff --git a/examples/threefold/gridproxy/node.vsh b/examples/threefold/gridproxy/node.vsh index 2db5d381..4107464d 100755 --- a/examples/threefold/gridproxy/node.vsh +++ b/examples/threefold/gridproxy/node.vsh @@ -9,10 +9,10 @@ fn get_nodes_example() ! { myfilter.status = 'up' myfilter.country = 'belgium' - mut gp_client := gridproxy.new(net:.main, cache:true)! + mut gp_client := gridproxy.new(net: .main, cache: true)! mynodes := gp_client.get_nodes(myfilter)! - console.print_debug("${mynodes}") + console.print_debug('${mynodes}') } fn get_node_by_id_example(node_id u64) ! { @@ -20,22 +20,22 @@ fn get_node_by_id_example(node_id u64) ! { myfilter.node_id = node_id - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mynodes := gp_client.get_nodes(myfilter)! - console.print_debug("${mynodes}") + console.print_debug('${mynodes}') // get node available resources node_available_resources := mynodes[0].calc_available_resources() - console.print_debug("${node_available_resources}") + console.print_debug('${node_available_resources}') } fn get_node_stats_by_id_example(node_id u64) ! { - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! node_stats := gp_client.get_node_stats_by_id(node_id)! - console.print_debug("${node_stats}") + console.print_debug('${node_stats}') } fn get_node_by_available_capacity_example() ! { @@ -43,15 +43,15 @@ fn get_node_by_available_capacity_example() ! { // minimum free capacity myfilter.free_mru = u64(0) - myfilter.free_sru = u64(1024) // 1 tb + myfilter.free_sru = u64(1024) // 1 tb myfilter.free_hru = u64(0) myfilter.free_ips = u64(1) // init gridproxy client on devnet with redis cash - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mynodes := gp_client.get_nodes(myfilter)! - console.print_debug("${mynodes}") + console.print_debug('${mynodes}') } fn get_node_by_city_country_example() ! { @@ -60,10 +60,10 @@ fn get_node_by_city_country_example() ! { myfilter.city = 'Rio de Janeiro' myfilter.country = 'Brazil' - mut gp_client := gridproxy.new(net:.main, cache:false)! + mut gp_client := gridproxy.new(net: .main, cache: false)! mynodes := gp_client.get_nodes(myfilter)! - console.print_debug("${mynodes}") + console.print_debug('${mynodes}') } fn get_node_box_poc_example() ! { @@ -71,10 +71,10 @@ fn get_node_box_poc_example() ! { myfilter.status = 'up' - mut gp_client := gridproxy.new(net:.main, cache:true)! + mut gp_client := gridproxy.new(net: .main, cache: true)! mynodes := gp_client.get_nodes(myfilter)! - for node in mynodes{ + for node in mynodes { console.print_debug('${node}') console.print_debug('${node.capacity.total_resources.hru.to_gigabytes()}') @@ -83,7 +83,6 @@ fn get_node_box_poc_example() ! { node_stats := gp_client.get_node_stats_by_id(node.node_id)! console.print_debug('${node_stats}') - } } diff --git a/examples/threefold/gridproxy/stats.vsh b/examples/threefold/gridproxy/stats.vsh index d9ab9389..f8b164d6 100755 --- a/examples/threefold/gridproxy/stats.vsh +++ b/examples/threefold/gridproxy/stats.vsh @@ -9,10 +9,10 @@ fn get_online_grid_stats_example() ! { myfilter.status = NodeStatus.online - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mystats := gp_client.get_stats(myfilter)! - console.print_debug("${mystats}") + console.print_debug('${mystats}') } fn get_all_grid_stats_example() ! { @@ -20,10 +20,10 @@ fn get_all_grid_stats_example() ! { myfilter.status = NodeStatus.all - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mystats := gp_client.get_stats(myfilter)! - console.print_debug("${mystats}") + console.print_debug('${mystats}') } get_online_grid_stats_example()! diff --git a/examples/threefold/gridproxy/twin.vsh b/examples/threefold/gridproxy/twin.vsh index 1f8af844..4e74d5b4 100755 --- a/examples/threefold/gridproxy/twin.vsh +++ b/examples/threefold/gridproxy/twin.vsh @@ -4,10 +4,10 @@ import freeflowuniverse.herolib.threefold.gridproxy import freeflowuniverse.herolib.ui.console fn get_all_twins_example() ! { - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mytwins := gp_client.get_twins()! - console.print_debug("${mytwins}") + console.print_debug('${mytwins}') } fn get_twin_by_id_example(twin_id u64) ! { @@ -15,10 +15,10 @@ fn get_twin_by_id_example(twin_id u64) ! { myfilter.twin_id = twin_id - mut gp_client := gridproxy.new(net:.dev, cache:true)! + mut gp_client := gridproxy.new(net: .dev, cache: true)! mytwins := gp_client.get_twins(myfilter)! - console.print_debug("${mytwins}") + console.print_debug('${mytwins}') } get_all_twins_example()! diff --git a/examples/threefold/holochain/holochain_deployer.vsh b/examples/threefold/holochain/holochain_deployer.vsh index cc834fa4..d3e6ebb8 100755 --- a/examples/threefold/holochain/holochain_deployer.vsh +++ b/examples/threefold/holochain/holochain_deployer.vsh @@ -4,60 +4,59 @@ import freeflowuniverse.herolib.threefold.tfrobot import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.clients.dagu -console.print_header("Deploy test of vmachines on TFGrid using TFRobot.") +console.print_header('Deploy test of vmachines on TFGrid using TFRobot.') mut bot := tfrobot.new()! mut deploy_config := tfrobot.DeployConfig{ - name: 'holotest2' - network: .main - debug: true + name: 'holotest2' + network: .main + debug: true node_groups: [ tfrobot.NodeGroup{ - name: 'hologroup2' + name: 'hologroup2' nodes_count: 20 - free_cpu: 8 - free_mru: 8 - free_ssd: 100 + free_cpu: 8 + free_mru: 8 + free_ssd: 100 // region:"europe" }, ] - vms: [ + vms: [ tfrobot.VMConfig{ - name: 'myvm' - vms_count: 5 - cpu: 1 - mem: 1 + name: 'myvm' + vms_count: 5 + cpu: 1 + mem: 1 entry_point: '/sbin/zinit init' // flist: 'https://hub.grid.tf/mariobassem1.3bot/threefolddev-holochain-latest.flist' - flist: 'https://hub.grid.tf/ashraf.3bot/threefolddev-holochain-latest.flist' - env_vars: { - 'CODE_SERVER_PASSWORD': 'planetfirst' + flist: 'https://hub.grid.tf/ashraf.3bot/threefolddev-holochain-latest.flist' + env_vars: { + 'CODE_SERVER_PASSWORD': 'planetfirst' 'DAGU_BASICAUTH_USERNAME': 'admin' 'DAGU_BASICAUTH_PASSWORD': 'planetfirst' } public_ip4: false - root_size: 50 - planetary: true + root_size: 50 + planetary: true }, ] } -//ssh-key is not specified, first key will be chosen +// ssh-key is not specified, first key will be chosen -//DEAL WITH SSH KEYS +// DEAL WITH SSH KEYS tfrobot.sshagent_keys_add(mut deploy_config)! -console.print_header("nr of ssh keys in ssh-agent:${deploy_config.ssh_keys.len}") +console.print_header('nr of ssh keys in ssh-agent:${deploy_config.ssh_keys.len}') res := bot.deploy(deploy_config)! - console.print_header("Get VM's and ssh into it.") -for vm in tfrobot.vms_get('holotest')!{ +for vm in tfrobot.vms_get('holotest')! { console.print_debug(vm.str()) - mut node:=vm.node()! - r:=node.exec(cmd:"ls /")! + mut node := vm.node()! + r := node.exec(cmd: 'ls /')! println(r) } diff --git a/examples/threefold/holochain/holochain_vms.vsh b/examples/threefold/holochain/holochain_vms.vsh index 196b0591..2fa435e9 100755 --- a/examples/threefold/holochain/holochain_vms.vsh +++ b/examples/threefold/holochain/holochain_vms.vsh @@ -5,9 +5,9 @@ import freeflowuniverse.herolib.ui.console console.print_header("Get VM's.") -for vm in tfrobot.vms_get('holotest2')!{ +for vm in tfrobot.vms_get('holotest2')! { console.print_debug(vm.str()) - mut node:=vm.node()! - r:=node.exec(cmd:"ls /")! + mut node := vm.node()! + r := node.exec(cmd: 'ls /')! println(r) } diff --git a/examples/threefold/holochain/tasker_example.vsh b/examples/threefold/holochain/tasker_example.vsh index 927e6ecd..e342b290 100755 --- a/examples/threefold/holochain/tasker_example.vsh +++ b/examples/threefold/holochain/tasker_example.vsh @@ -3,44 +3,43 @@ import freeflowuniverse.herolib.threefold.tfrobot import freeflowuniverse.herolib.ui.console -console.print_header("Tasker Example.") +console.print_header('Tasker Example.') -mut vm := tfrobot.vm_get('holotest','test2')! +mut vm := tfrobot.vm_get('holotest', 'test2')! -//get a set of tasks as we want to execute on the vm -mut tasks:=vm.tasks_new(name:'holochain_scaffold') +// get a set of tasks as we want to execute on the vm +mut tasks := vm.tasks_new(name: 'holochain_scaffold') tasks.step_add( - nr:1 - name: 'Verify installation' - command: 'nix run --refresh -j0 -v github:holochain/holochain#hc-scaffold -- --version' - )! + nr: 1 + name: 'Verify installation' + command: 'nix run --refresh -j0 -v github:holochain/holochain#hc-scaffold -- --version' +)! tasks.step_add( - nr:2 - name: 'Create working directory' - command: 'mkdir -p /root/Holochain' - depends: "1" - )! + nr: 2 + name: 'Create working directory' + command: 'mkdir -p /root/Holochain' + depends: '1' +)! tasks.step_add( - nr:3 - name: 'Scaffold application' - description: 'Scaffold a simple "Hello, World!" Holochain application' - dir: '/root/Holochain' - script: 'nix run github:holochain/holochain#hc-scaffold -- example hello-world || true' - depends: "2" - continue_on_error: true - )! + nr: 3 + name: 'Scaffold application' + description: 'Scaffold a simple "Hello, World!" Holochain application' + dir: '/root/Holochain' + script: 'nix run github:holochain/holochain#hc-scaffold -- example hello-world || true' + depends: '2' + continue_on_error: true +)! tasks.step_add( - nr:4 - name: 'Run Application' - dir: '/root/Holochain/hello-world' - command: 'nix develop --command bash -c "npm install && npm run start" && exit' - depends: "3" - )! - + nr: 4 + name: 'Run Application' + dir: '/root/Holochain/hello-world' + command: 'nix develop --command bash -c "npm install && npm run start" && exit' + depends: '3' +)! vm.tasks_run(tasks)! vm.tasks_see(tasks)! diff --git a/examples/threefold/holochain/tasker_example2.vsh b/examples/threefold/holochain/tasker_example2.vsh index 9a321e30..9777bd0f 100755 --- a/examples/threefold/holochain/tasker_example2.vsh +++ b/examples/threefold/holochain/tasker_example2.vsh @@ -3,26 +3,25 @@ import freeflowuniverse.herolib.threefold.tfrobot import freeflowuniverse.herolib.ui.console -console.print_header("Tasker Example 2.") +console.print_header('Tasker Example 2.') -mut vm := tfrobot.vm_get('holotest','test1')! +mut vm := tfrobot.vm_get('holotest', 'test1')! -//get a set of tasks as we want to execute on the vm -mut tasks:=vm.tasks_new(name:'sysadmin') +// get a set of tasks as we want to execute on the vm +mut tasks := vm.tasks_new(name: 'sysadmin') tasks.step_add( - nr:1 - name: 'ls' - command: 'ls /' - )! + nr: 1 + name: 'ls' + command: 'ls /' +)! tasks.step_add( - nr:2 - name: 'install something' - command: 'nix-env --install mc' - depends: "1" - )! - + nr: 2 + name: 'install something' + command: 'nix-env --install mc' + depends: '1' +)! vm.tasks_run(tasks)! vm.tasks_see(tasks)! diff --git a/examples/threefold/tfgrid3deployer/tfgrid3deployer_example.vsh b/examples/threefold/tfgrid3deployer/tfgrid3deployer_example.vsh index ba6c6ea8..272eaa3e 100755 --- a/examples/threefold/tfgrid3deployer/tfgrid3deployer_example.vsh +++ b/examples/threefold/tfgrid3deployer/tfgrid3deployer_example.vsh @@ -5,9 +5,8 @@ import freeflowuniverse.herolib.threefold.tfgrid3deployer import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.installers.threefold.griddriver - -fn main(){ - mut installer:= griddriver.get()! +fn main() { + mut installer := griddriver.get()! installer.install()! // v := tfgrid3deployer.get()! @@ -52,7 +51,7 @@ fn main(){ // vm1 := deployment.vm_get("my_vm1")! // reachable := vm1.healthcheck()! // println("vm reachable: ${reachable}") - + // if !reachable { // deployment.vm_delete()! // deployment.vm_deploy()! @@ -63,7 +62,6 @@ fn main(){ // vm1.deploy()! // } - /* TODO: Agreed on diff --git a/examples/ui/console/flow1/flow1.v b/examples/ui/console/flow1/flow1.v index d3f5b59d..fc1ed438 100644 --- a/examples/ui/console/flow1/flow1.v +++ b/examples/ui/console/flow1/flow1.v @@ -12,8 +12,8 @@ pub mut: fn (mut f RoomOrderFlow) room_choice() ! { i := f.ui.ask_dropdown( description: 'Which type of room do you want?' - items: ['penthouse', 'normal', 'single', 'appartment_room'] - warning: 'Please select your right type of room' + items: ['penthouse', 'normal', 'single', 'appartment_room'] + warning: 'Please select your right type of room' )! println(i) diff --git a/examples/ui/flow1.v b/examples/ui/flow1.v index b2db9377..6fe0c49b 100644 --- a/examples/ui/flow1.v +++ b/examples/ui/flow1.v @@ -10,9 +10,9 @@ struct RoomOrderFlow { fn (mut f RoomOrderFlow) room_select() ! { i := f.ui.ask_dropdown_int( description: 'Which type of room do you want?' - items: ['penthouse', 'normal', 'single', 'appartment_room'] - warning: 'Please select your right type of room' - reset: true + items: ['penthouse', 'normal', 'single', 'appartment_room'] + warning: 'Please select your right type of room' + reset: true ) // match smoker := f.ui.ask_yesno(description: 'Are you a smoker?') diff --git a/examples/ui/silence.vsh b/examples/ui/silence.vsh index d3d03487..c58733f2 100755 --- a/examples/ui/silence.vsh +++ b/examples/ui/silence.vsh @@ -4,10 +4,10 @@ import freeflowuniverse.herolib.osal import freeflowuniverse.herolib.ui.console console.silent_set() -mut job2 := osal.exec(cmd: 'ls /',debug:true)! -println("I got nothing above") +mut job2 := osal.exec(cmd: 'ls /', debug: true)! +println('I got nothing above') console.silent_unset() -println("now I will get output") +println('now I will get output') -osal.exec(cmd: 'ls /',debug:true)! +osal.exec(cmd: 'ls /', debug: true)! diff --git a/examples/ui/telegram/flow1.v b/examples/ui/telegram/flow1.v index 6b0773fe..5e39c426 100644 --- a/examples/ui/telegram/flow1.v +++ b/examples/ui/telegram/flow1.v @@ -10,9 +10,9 @@ struct RoomOrderFlow { fn (mut f RoomOrderFlow) room_choice() ! { i := ui.ask_dropdown( description: 'Which type of room do you want?' - items: ['penthouse', 'normal', 'single', 'appartment_room'] - warning: 'Please select your right type of room' - reset: true + items: ['penthouse', 'normal', 'single', 'appartment_room'] + warning: 'Please select your right type of room' + reset: true ) // match diff --git a/examples/virt/docker/presearch_docker.vsh b/examples/virt/docker/presearch_docker.vsh index fcb3d412..e56c2388 100644 --- a/examples/virt/docker/presearch_docker.vsh +++ b/examples/virt/docker/presearch_docker.vsh @@ -18,7 +18,7 @@ presearch_node.volume_add('/presearch-node-storage', '/app/node')! presearch_node.env_add('REGISTRATION_CODE', '${registration_code}') mut presearch_updater := recipe.service_new( - name: 'presearch_updater' + name: 'presearch_updater' image: 'presearch/auto-updater' )! presearch_updater.volume_add('/var/run/docker.sock', '/var/run/docker.sock')! diff --git a/examples/virt/docker/tf_dashboard.vsh b/examples/virt/docker/tf_dashboard.vsh index 1fe44d47..01bbd0c1 100644 --- a/examples/virt/docker/tf_dashboard.vsh +++ b/examples/virt/docker/tf_dashboard.vsh @@ -1,4 +1,5 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run + import freeflowuniverse.herolib.virt.docker mut engine := docker.new(prefix: '', localonly: true)! diff --git a/examples/virt/hetzner/hetzner_example.vsh b/examples/virt/hetzner/hetzner_example.vsh index a8463676..adef3363 100755 --- a/examples/virt/hetzner/hetzner_example.vsh +++ b/examples/virt/hetzner/hetzner_example.vsh @@ -5,24 +5,23 @@ import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.core.base import freeflowuniverse.herolib.builder import time - import os -console.print_header("Hetzner login.") +console.print_header('Hetzner login.') -//USE IF YOU WANT TO CONFIGURE THE HETZNER, ONLY DO THIS ONCE -//hetzner.configure("test")! +// USE IF YOU WANT TO CONFIGURE THE HETZNER, ONLY DO THIS ONCE +// hetzner.configure("test")! -mut cl:=hetzner.get("test")! +mut cl := hetzner.get('test')! -for i in 0..5{ - println("test cache, first time slow then fast") +for i in 0 .. 5 { + println('test cache, first time slow then fast') cl.servers_list()! } println(cl.servers_list()!) -mut serverinfo:= cl.server_info_get(name:"kristof2")! +mut serverinfo := cl.server_info_get(name: 'kristof2')! println(serverinfo) @@ -30,13 +29,12 @@ println(serverinfo) // cl.server_rescue(name:"kristof2",wait:true)! -console.print_header("SSH login") +console.print_header('SSH login') mut b := builder.new()! mut n := b.node_new(ipaddr: serverinfo.server_ip)! // n.hero_install()! // n.hero_compile_debug()! - // mut ks:=cl.keys_get()! // println(ks) diff --git a/examples/virt/lima/lima_example.vsh b/examples/virt/lima/lima_example.vsh index c037a004..ac2203d4 100755 --- a/examples/virt/lima/lima_example.vsh +++ b/examples/virt/lima/lima_example.vsh @@ -8,17 +8,16 @@ import os limainstaller.install()! -mut virtmanager:=lima.new()! +mut virtmanager := lima.new()! virtmanager.vm_delete_all()! // virtmanager.vm_new(reset:true,template:.alpine,name:'alpine',install_hero:false)! +// virtmanager.vm_new(reset:true,template:.arch,name:'arch',install_hero:true)! -//virtmanager.vm_new(reset:true,template:.arch,name:'arch',install_hero:true)! - -virtmanager.vm_new(reset:true,template:.ubuntucloud,name:'hero',install_hero:false)! -mut vm:=virtmanager.vm_get('hero')! +virtmanager.vm_new(reset: true, template: .ubuntucloud, name: 'hero', install_hero: false)! +mut vm := virtmanager.vm_get('hero')! println(vm) diff --git a/examples/virt/podman_buildah/buildah_example.vsh b/examples/virt/podman_buildah/buildah_example.vsh index a9d0e6f7..3f6823aa 100755 --- a/examples/virt/podman_buildah/buildah_example.vsh +++ b/examples/virt/podman_buildah/buildah_example.vsh @@ -4,30 +4,26 @@ import freeflowuniverse.herolib.virt.herocontainers import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.core.base import freeflowuniverse.herolib.osal - import freeflowuniverse.herolib.installers.virt.pacman +mut installer := pacman.get()! -mut installer:= pacman.get()! +// installer.destroy()! +// installer.install()! -//installer.destroy()! -//installer.install()! +// exit(0) -//exit(0) +// interative means will ask for login/passwd -//interative means will ask for login/passwd - -mut engine:=herocontainers.new(install:true,herocompile:false)! +mut engine := herocontainers.new(install: true, herocompile: false)! engine.reset_all()! mut builder_gorust := engine.builder_go_rust()! -//will build nodejs, python build & herolib, hero -//mut builder_hero := engine.builder_hero(reset:true)! - -//mut builder_web := engine.builder_heroweb(reset:true)! - +// will build nodejs, python build & herolib, hero +// mut builder_hero := engine.builder_hero(reset:true)! +// mut builder_web := engine.builder_heroweb(reset:true)! builder_gorust.shell()! diff --git a/examples/virt/podman_buildah/buildah_run.vsh b/examples/virt/podman_buildah/buildah_run.vsh index 60e2d3df..c3c7f2f9 100755 --- a/examples/virt/podman_buildah/buildah_run.vsh +++ b/examples/virt/podman_buildah/buildah_run.vsh @@ -5,20 +5,16 @@ import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.core.base // import freeflowuniverse.herolib.builder import time - import os +mut pm := herocontainers.new(herocompile: true, install: false)! -mut pm:=herocontainers.new(herocompile:true,install:false)! - -mut mybuildcontainer := pm.builder_get("builder_heroweb")! - -//bash & python can be executed directly in build container - -//any of the herocommands can be executed like this -mybuildcontainer.run(cmd:"installers -n heroweb",runtime:.herocmd)! +mut mybuildcontainer := pm.builder_get('builder_heroweb')! +// bash & python can be executed directly in build container +// any of the herocommands can be executed like this +mybuildcontainer.run(cmd: 'installers -n heroweb', runtime: .herocmd)! // //following will execute heroscript in the buildcontainer // mybuildcontainer.run( @@ -31,11 +27,10 @@ mybuildcontainer.run(cmd:"installers -n heroweb",runtime:.herocmd)! // ", // runtime:.heroscript)! -//there are also shortcuts for this +// there are also shortcuts for this -//mybuildcontainer.hero_copy()! -//mybuildcontainer.shell()! +// mybuildcontainer.hero_copy()! +// mybuildcontainer.shell()! - -//mut b2:=pm.builder_get("builderv")! -//b2.shell()! +// mut b2:=pm.builder_get("builderv")! +// b2.shell()! diff --git a/examples/virt/podman_buildah/buildah_run_clean.vsh b/examples/virt/podman_buildah/buildah_run_clean.vsh index ed43a2f0..3eada9d3 100755 --- a/examples/virt/podman_buildah/buildah_run_clean.vsh +++ b/examples/virt/podman_buildah/buildah_run_clean.vsh @@ -5,13 +5,11 @@ import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.core.base // import freeflowuniverse.herolib.builder import time - import os +mut pm := herocontainers.new(herocompile: false)! -mut pm:=herocontainers.new(herocompile:false)! - -mut b:=pm.builder_new()! +mut b := pm.builder_new()! println(b) diff --git a/examples/virt/podman_buildah/buildah_run_mdbook.vsh b/examples/virt/podman_buildah/buildah_run_mdbook.vsh index 5a9b649e..23ffca50 100755 --- a/examples/virt/podman_buildah/buildah_run_mdbook.vsh +++ b/examples/virt/podman_buildah/buildah_run_mdbook.vsh @@ -2,7 +2,6 @@ import os import flag - import freeflowuniverse.herolib.virt.herocontainers import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.core.base @@ -21,13 +20,13 @@ additional_args := fp.finalize() or { return } -mut pm:=herocontainers.new(herocompile:true,install:false)! +mut pm := herocontainers.new(herocompile: true, install: false)! -mut mybuildcontainer := pm.builder_get("builder_heroweb")! +mut mybuildcontainer := pm.builder_get('builder_heroweb')! // //bash & python can be executed directly in build container // //any of the herocommands can be executed like this -mybuildcontainer.run(cmd:"installers -n heroweb",runtime:.herocmd)! +mybuildcontainer.run(cmd: 'installers -n heroweb', runtime: .herocmd)! mybuildcontainer.run(cmd: 'hero mdbook -u ${url} -o', runtime: .bash)! diff --git a/examples/virt/windows/cloudhypervisor.vsh b/examples/virt/windows/cloudhypervisor.vsh index e5ea0da0..ce457359 100755 --- a/examples/virt/windows/cloudhypervisor.vsh +++ b/examples/virt/windows/cloudhypervisor.vsh @@ -1,16 +1,15 @@ #!/usr/bin/env -S v -n -w -gc none -no-retry-compilation -cc tcc -d use_openssl -enable-globals run import freeflowuniverse.herolib.installers.virt.cloudhypervisor as cloudhypervisor_installer - import freeflowuniverse.herolib.virt.cloudhypervisor import freeflowuniverse.herolib.core.texttools import freeflowuniverse.herolib.ui.console import os -mut ci:=cloudhypervisor_installer.get()! -ci.install(reset:true)! +mut ci := cloudhypervisor_installer.get()! +ci.install(reset: true)! -//mut vmm:=cloudhypervisor.new()! +// mut vmm:=cloudhypervisor.new()! // virtmanager.vm_delete_all()! // virtmanager.vm_new(reset:true,template:.alpine,name:'alpine',install_hero:true)! diff --git a/examples/webdav/webdav.vsh b/examples/webdav/webdav.vsh index 04d1fc4b..6ca1acb2 100755 --- a/examples/webdav/webdav.vsh +++ b/examples/webdav/webdav.vsh @@ -9,8 +9,8 @@ import encoding.base64 file_name := 'newfile.txt' root_dir := '/tmp/webdav' -username := "omda" -password := "password" +username := 'omda' +password := 'password' hashed_password := base64.encode_str('${username}:${password}') mut app := webdav.new_app(root_dir: root_dir, username: username, password: password) or { @@ -24,6 +24,7 @@ time.sleep(1 * time.second) mut p := pathlib.get_file(path: '${root_dir}/${file_name}', create: true)! p.write('my new file')! -mut req := http.new_request(.get, 'http://localhost:${app.server_port}/${file_name}', '') +mut req := http.new_request(.get, 'http://localhost:${app.server_port}/${file_name}', + '') req.add_custom_header('Authorization', 'Basic ${hashed_password}')! req.do()! diff --git a/lib/builder/bootstrapper.v b/lib/builder/bootstrapper.v index 9821deae..3c2552e7 100644 --- a/lib/builder/bootstrapper.v +++ b/lib/builder/bootstrapper.v @@ -56,9 +56,9 @@ pub fn (mut node Node) upgrade() ! { install_base_content := install_base_content_.to_string() cmd := '${install_base_content}\n' node.exec_cmd( - cmd: cmd - period: 48 * 3600 - reset: false + cmd: cmd + period: 48 * 3600 + reset: false description: 'upgrade operating system packages' )! } @@ -100,45 +100,45 @@ pub mut: reset bool } -pub fn (mut node Node) hero_install(args HeroInstallArgs) ! { - mut bs := bootstrapper() - install_base_content_ := bs.embedded_files['install_base.sh'] or { panic('bug') } - install_base_content := install_base_content_.to_string() +// pub fn (mut node Node) hero_install(args HeroInstallArgs) ! { +// mut bs := bootstrapper() +// install_base_content_ := bs.embedded_files['install_base.sh'] or { panic('bug') } +// install_base_content := install_base_content_.to_string() - if args.reset { - console.clear() - console.print_debug('') - console.print_stderr('will remove: .vmodules, hero lib code and ~/hero') - console.print_debug('') - mut myui := ui.new()! - toinstall := myui.ask_yesno( - question: 'Ok to reset?' - default: true - )! - if !toinstall { - exit(1) - } - os.rmdir_all('${os.home_dir()}/.vmodules')! - os.rmdir_all('${os.home_dir()}/hero')! - os.rmdir_all('${os.home_dir()}/code/github/freeflowuniverse/herolib')! - os.rmdir_all('${os.home_dir()}/code/github/freeflowuniverse/webcomponents')! - } +// if args.reset { +// console.clear() +// console.print_debug('') +// console.print_stderr('will remove: .vmodules, hero lib code and ~/hero') +// console.print_debug('') +// mut myui := ui.new()! +// toinstall := myui.ask_yesno( +// question: 'Ok to reset?' +// default: true +// )! +// if !toinstall { +// exit(1) +// } +// os.rmdir_all('${os.home_dir()}/.vmodules')! +// os.rmdir_all('${os.home_dir()}/hero')! +// os.rmdir_all('${os.home_dir()}/code/github/freeflowuniverse/herolib')! +// os.rmdir_all('${os.home_dir()}/code/github/freeflowuniverse/webcomponents')! +// } - cmd := ' - ${install_base_content} - - rm -f /usr/local/bin/hero - freeflow_dev_env_install +// cmd := ' +// ${install_base_content} - ~/code/github/freeflowuniverse/herolib/install.sh - - echo HERO, V, CRYSTAL ALL INSTALL OK - echo WE ARE READY TO HERO... - - ' - console.print_debug('executing cmd ${cmd}') - node.exec_cmd(cmd: cmd)! -} +// rm -f /usr/local/bin/hero +// freeflow_dev_env_install + +// ~/code/github/freeflowuniverse/herolib/install.sh + +// echo HERO, V, CRYSTAL ALL INSTALL OK +// echo WE ARE READY TO HERO... + +// ' +// console.print_debug('executing cmd ${cmd}') +// node.exec_cmd(cmd: cmd)! +// } @[params] pub struct HeroUpdateArgs { @@ -162,10 +162,10 @@ pub fn (mut node Node) hero_update(args_ HeroUpdateArgs) ! { if args.sync_from_local { if args.sync_full { - node.sync_code('hero', builder.heropath_ + '/..', '~/code/github/freeflowuniverse/herolib', + node.sync_code('hero', heropath_ + '/..', '~/code/github/freeflowuniverse/herolib', args.sync_fast)! } else { - node.sync_code('hero_lib', builder.heropath_, '~/code/github/freeflowuniverse/herolib/herolib', + node.sync_code('hero_lib', heropath_, '~/code/github/freeflowuniverse/herolib/herolib', args.sync_fast)! } return @@ -202,15 +202,15 @@ pub fn (mut node Node) hero_update(args_ HeroUpdateArgs) ! { pub fn (mut node Node) sync_code(name string, src_ string, dest string, fast_rsync bool) ! { mut src := pathlib.get_dir(path: os.abs_path(src_), create: false)! node.upload( - source: src.path - dest: dest - ignore: [ + source: src.path + dest: dest + ignore: [ '.git/*', '_archive', '.vscode', 'examples', ] - delete: true + delete: true fast_rsync: fast_rsync )! } @@ -254,9 +254,9 @@ pub fn (mut node Node) vscript(args_ VScriptArgs) ! { mut args := args_ node.hero_update( sync_from_local: args.sync_from_local - git_reset: args.git_reset - git_pull: args.git_pull - branch: args.branch + git_reset: args.git_reset + git_pull: args.git_pull + branch: args.branch )! mut p := pathlib.get_file(path: args.path, create: false)! diff --git a/lib/builder/executor.v b/lib/builder/executor.v index 13d91ce3..2029dd46 100644 --- a/lib/builder/executor.v +++ b/lib/builder/executor.v @@ -42,8 +42,8 @@ fn executor_new(args_ ExecutorNewArguments) !Executor { } mut e := ExecutorSSH{ ipaddr: ipaddr - user: args.user - debug: args.debug + user: args.user + debug: args.debug } e.init()! return e diff --git a/lib/builder/executor_local.v b/lib/builder/executor_local.v index f8583b08..cec96271 100644 --- a/lib/builder/executor_local.v +++ b/lib/builder/executor_local.v @@ -75,12 +75,12 @@ pub fn (mut executor ExecutorLocal) info() map[string]string { // upload from local FS to executor FS pub fn (mut executor ExecutorLocal) upload(args SyncArgs) ! { mut rsargs := rsync.RsyncArgs{ - source: args.source - dest: args.dest - delete: args.delete - ignore: args.ignore + source: args.source + dest: args.dest + delete: args.delete + ignore: args.ignore ignore_default: args.ignore_default - stdout: args.stdout + stdout: args.stdout } rsync.rsync(rsargs)! } @@ -88,12 +88,12 @@ pub fn (mut executor ExecutorLocal) upload(args SyncArgs) ! { // download from executor FS to local FS pub fn (mut executor ExecutorLocal) download(args SyncArgs) ! { mut rsargs := rsync.RsyncArgs{ - source: args.source - dest: args.dest - delete: args.delete - ignore: args.ignore + source: args.source + dest: args.dest + delete: args.delete + ignore: args.ignore ignore_default: args.ignore_default - stdout: args.stdout + stdout: args.stdout } rsync.rsync(rsargs)! } diff --git a/lib/builder/executor_ssh.v b/lib/builder/executor_ssh.v index 66b4b7cd..cd38b454 100644 --- a/lib/builder/executor_ssh.v +++ b/lib/builder/executor_ssh.v @@ -125,13 +125,13 @@ pub fn (mut executor ExecutorSSH) download(args SyncArgs) ! { addr = '\'${executor.user}@[${executor.ipaddr.addr}]\':${executor.ipaddr.port}' } mut rsargs := rsync.RsyncArgs{ - source: args.source - dest: args.dest - delete: args.delete - ipaddr_src: addr - ignore: args.ignore + source: args.source + dest: args.dest + delete: args.delete + ipaddr_src: addr + ignore: args.ignore ignore_default: args.ignore_default - stdout: args.stdout + stdout: args.stdout } rsync.rsync(rsargs)! } @@ -173,14 +173,14 @@ pub fn (mut executor ExecutorSSH) upload(args SyncArgs) ! { } mut rsargs := rsync.RsyncArgs{ - source: args.source - dest: args.dest - delete: args.delete - ipaddr_dst: addr - ignore: args.ignore + source: args.source + dest: args.dest + delete: args.delete + ipaddr_dst: addr + ignore: args.ignore ignore_default: args.ignore_default - stdout: args.stdout - fast_rsync: args.fast_rsync + stdout: args.stdout + fast_rsync: args.fast_rsync } rsync.rsync(rsargs)! } diff --git a/lib/builder/executor_ssh_test.v b/lib/builder/executor_ssh_test.v index 20f8861e..5736877c 100644 --- a/lib/builder/executor_ssh_test.v +++ b/lib/builder/executor_ssh_test.v @@ -34,7 +34,7 @@ fn test_file_operations() { e.ipaddr = IPAddress{ addr: '127.0.0.1' port: 22 - cat: .ipv4 + cat: .ipv4 } mut filepath := '/tmp/${rand.uuid_v4()}' e.file_write(filepath, 'ssh')! @@ -54,7 +54,7 @@ fn test_environ_get() { e.ipaddr = IPAddress{ addr: '127.0.0.1' port: 22 - cat: .ipv4 + cat: .ipv4 } mut env := e.environ_get()! console.print_debug(env) diff --git a/lib/builder/node.v b/lib/builder/node.v index 81f27526..bf924337 100644 --- a/lib/builder/node.v +++ b/lib/builder/node.v @@ -28,7 +28,7 @@ mut: factory &BuilderFactory @[skip; str: skip] pub mut: name string = 'unknown' - executor Executor @[skip; str: skip] + executor Executor @[skip; str: skip] platform PlatformType cputype CPUType done map[string]string diff --git a/lib/builder/node_commands.v b/lib/builder/node_commands.v index 741fdcc9..8d129948 100644 --- a/lib/builder/node_commands.v +++ b/lib/builder/node_commands.v @@ -16,7 +16,7 @@ pub struct NodeExecCmd { pub mut: name string = 'default' cmd string - period int // period in which we check when this was done last, if 0 then period is indefinite + period int // period in which we check when this was done last, if 0 then period is indefinite reset bool = true // means do again or not remove_installer bool = true // delete the installer description string diff --git a/lib/builder/node_executor.v b/lib/builder/node_executor.v index 4ba7607a..729b6d51 100644 --- a/lib/builder/node_executor.v +++ b/lib/builder/node_executor.v @@ -44,9 +44,9 @@ pub fn (mut node Node) exec(args ExecArgs) !string { pub struct ExecRetryArgs { pub: cmd string - retrymax int = 10 // how may times maximum to retry + retrymax int = 10 // how may times maximum to retry period_milli int = 100 // sleep in between retry in milliseconds - timeout int = 2 // timeout for al the tries together + timeout int = 2 // timeout for al the tries together stdout bool = true } diff --git a/lib/builder/node_factory.v b/lib/builder/node_factory.v index 7b2e39b9..b5d661c1 100644 --- a/lib/builder/node_factory.v +++ b/lib/builder/node_factory.v @@ -50,14 +50,14 @@ pub fn (mut bldr BuilderFactory) node_new(args_ NodeArguments) !&Node { eargs := ExecutorNewArguments{ ipaddr: args.ipaddr - user: args.user - debug: args.debug + user: args.user + debug: args.debug } mut executor := executor_new(eargs)! mut node := Node{ - name: args.name + name: args.name executor: executor - factory: &bldr + factory: &bldr } if node.name == '' { diff --git a/lib/clients/meilisearch/meilisearch_model.v b/lib/clients/meilisearch/meilisearch_model.v index 81bb6786..a7f55125 100644 --- a/lib/clients/meilisearch/meilisearch_model.v +++ b/lib/clients/meilisearch/meilisearch_model.v @@ -18,7 +18,6 @@ pub fn heroscript_default() !string { return heroscript } - pub struct MeilisearchClient { pub mut: name string = 'default' diff --git a/lib/clients/rclone/config.v b/lib/clients/rclone/config.v index 6d8e782c..91f1215d 100644 --- a/lib/clients/rclone/config.v +++ b/lib/clients/rclone/config.v @@ -19,7 +19,7 @@ const configfile = '${os.home_dir()}/.config/rclone/rclone.conf' //``` pub fn configure() ! { mut plbook := playbook.new( - path: rclone.configfile + path: configfile // actor_filter: ['config'] // action_filter: [ // 's3server_define', diff --git a/lib/clients/rclone/rclone_model.v b/lib/clients/rclone/rclone_model.v index 44acf3c5..a43ad437 100644 --- a/lib/clients/rclone/rclone_model.v +++ b/lib/clients/rclone/rclone_model.v @@ -34,7 +34,7 @@ pub fn heroscript_default() !string { pub struct RCloneClient { pub mut: name string = 'default' - type_ string = 's3' // remote type (s3, sftp, etc) + type_ string = 's3' // remote type (s3, sftp, etc) provider string = 'aws' // provider for s3 (aws, minio, etc) access_key string // access key for authentication secret_key string // secret key for authentication @@ -44,13 +44,13 @@ pub mut: fn cfg_play(p paramsparser.Params) ! { mut mycfg := RCloneClient{ - name: p.get_default('name', 'default')! - type_: p.get_default('type', 's3')! - provider: p.get_default('provider', 'aws')! + name: p.get_default('name', 'default')! + type_: p.get_default('type', 's3')! + provider: p.get_default('provider', 'aws')! access_key: p.get('access_key')! secret_key: p.get('secret_key')! - region: p.get_default('region', 'us-east-1')! - endpoint: p.get_default('endpoint', '')! + region: p.get_default('region', 'us-east-1')! + endpoint: p.get_default('endpoint', '')! } set(mycfg)! } diff --git a/lib/core/playcmds/_archive/play_juggler.v b/lib/core/playcmds/_archive/play_juggler.v index 6d5fbd2c..58943c5d 100644 --- a/lib/core/playcmds/_archive/play_juggler.v +++ b/lib/core/playcmds/_archive/play_juggler.v @@ -27,10 +27,10 @@ pub fn play_juggler(mut plbook playbook.PlayBook) ! { port := p.get_int_default('port', 8000)! j = juggler.configure( - url: 'https://git.ourworld.tf/projectmycelium/itenv' + url: 'https://git.ourworld.tf/projectmycelium/itenv' username: username password: password - reset: true + reset: true )! config_actions[0].done = true } diff --git a/lib/core/playcmds/factory.v b/lib/core/playcmds/factory.v index d075a35a..e3105969 100644 --- a/lib/core/playcmds/factory.v +++ b/lib/core/playcmds/factory.v @@ -3,11 +3,11 @@ module playcmds import freeflowuniverse.herolib.ui.console import freeflowuniverse.herolib.core.playbook import freeflowuniverse.herolib.virt.hetzner -//import freeflowuniverse.herolib.clients.b2 +// import freeflowuniverse.herolib.clients.b2 import freeflowuniverse.herolib.biz.bizmodel import freeflowuniverse.herolib.hero.publishing import freeflowuniverse.herolib.threefold.grid4.gridsimulator -//import freeflowuniverse.herolib.installers.sysadmintools.daguserver +// import freeflowuniverse.herolib.installers.sysadmintools.daguserver import freeflowuniverse.herolib.threefold.grid4.farmingsimulator import freeflowuniverse.herolib.web.components.slides // import freeflowuniverse.herolib.installers.base as base_install @@ -22,12 +22,12 @@ pub fn run(mut plbook playbook.PlayBook, dagu bool) ! { play_core(mut plbook)! play_ssh(mut plbook)! play_git(mut plbook)! - //play_zola(mut plbook)! - //play_caddy(mut plbook)! - //play_juggler(mut plbook)! - //play_luadns(mut plbook)! + // play_zola(mut plbook)! + // play_caddy(mut plbook)! + // play_juggler(mut plbook)! + // play_luadns(mut plbook)! hetzner.heroplay(mut plbook)! - //b2.heroplay(mut plbook)! + // b2.heroplay(mut plbook)! farmingsimulator.play(mut plbook)! gridsimulator.play(mut plbook)! @@ -38,7 +38,7 @@ pub fn run(mut plbook playbook.PlayBook, dagu bool) ! { publishing.play(mut plbook)! - //plbook.empty_check()! + // plbook.empty_check()! console.print_header('Actions concluded succesfully.') } diff --git a/lib/core/playcmds/play_dagu_test.v b/lib/core/playcmds/play_dagu_test.v index 61512d5b..5e45be25 100644 --- a/lib/core/playcmds/play_dagu_test.v +++ b/lib/core/playcmds/play_dagu_test.v @@ -25,7 +25,7 @@ const dagu_script = " " fn test_play_dagu() ! { - mut plbook := playbook.new(text: playcmds.dagu_script)! + mut plbook := playbook.new(text: dagu_script)! play_dagu(mut plbook)! panic('s') } diff --git a/lib/core/playcmds/play_doctree.v b/lib/core/playcmds/play_doctree.v index ad89a101..e7dfe16a 100644 --- a/lib/core/playcmds/play_doctree.v +++ b/lib/core/playcmds/play_doctree.v @@ -5,7 +5,6 @@ import freeflowuniverse.herolib.core.playbook import os pub fn play_doctree(mut plbook playbook.PlayBook) ! { - // check if any actions for doctree, if not then nothing to do here // dtactions := plbook.find(filter: 'doctree.')! // if dtactions.len == 0 { @@ -55,8 +54,8 @@ pub fn play_doctree(mut plbook playbook.PlayBook) ! { tree.export( destination: build_path - reset: reset2 - toreplace: toreplace + reset: reset2 + toreplace: toreplace )! action.done = true } diff --git a/lib/core/playcmds/play_git.v b/lib/core/playcmds/play_git.v index a1bba04c..19a440ca 100644 --- a/lib/core/playcmds/play_git.v +++ b/lib/core/playcmds/play_git.v @@ -35,16 +35,16 @@ pub fn play_git_action(action playbook.Action) !playbook.Action { } gitpath := gs.do( - cmd: cmd - filter: action.params.get_default('filter', '')! - repo: repo - account: account + cmd: cmd + filter: action.params.get_default('filter', '')! + repo: repo + account: account provider: provider - script: action.params.get_default_false('script') - reset: action.params.get_default_false('reset') - pull: action.params.get_default_false('pull') - msg: action.params.get_default('message', '')! - url: url + script: action.params.get_default_false('script') + reset: action.params.get_default_false('reset') + pull: action.params.get_default_false('pull') + msg: action.params.get_default('message', '')! + url: url )! console.print_debug('play git action: ${cmd} ${account}:${repo} path:${gitpath}') mut action2 := action diff --git a/lib/core/playcmds/play_mdbook.v b/lib/core/playcmds/play_mdbook.v index 9262de89..8f3227de 100644 --- a/lib/core/playcmds/play_mdbook.v +++ b/lib/core/playcmds/play_mdbook.v @@ -71,11 +71,11 @@ pub fn play_mdbook(mut plbook playbook.PlayBook) ! { } tree.scan( - path: path - git_url: url + path: path + git_url: url git_reset: reset - git_root: coderoot - git_pull: pull + git_root: coderoot + git_pull: pull )! action.done = true } @@ -90,8 +90,8 @@ pub fn play_mdbook(mut plbook playbook.PlayBook) ! { tree.export( destination: build_path - reset: reset2 - toreplace: toreplace + reset: reset2 + toreplace: toreplace )! action.done = true } @@ -121,15 +121,15 @@ pub fn play_mdbook(mut plbook playbook.PlayBook) ! { cfg.path_publish = publishroot mdbooks.generate( - name: name - title: title + name: name + title: title summary_path: summary_path publish_path: publish_path - build_path: build_path - printbook: printbook - foldlevel: foldlevel - production: production - collections: collections + build_path: build_path + printbook: printbook + foldlevel: foldlevel + production: production + collections: collections )! action.done = true } diff --git a/lib/core/playcmds/play_zola.v b/lib/core/playcmds/play_zola.v index 930d0e96..d73e8bab 100644 --- a/lib/core/playcmds/play_zola.v +++ b/lib/core/playcmds/play_zola.v @@ -35,10 +35,10 @@ pub fn play_zola(mut plbook playbook.PlayBook) ! { config_actions[0].done = true } mut websites := zola.new( - path_build: buildroot + path_build: buildroot path_publish: publishroot - install: install - reset: reset + install: install + reset: reset )! mut ws := WebsiteItem{} @@ -118,11 +118,11 @@ pub fn play_zola(mut plbook playbook.PlayBook) ! { } site_.person_add( - name: name + name: name collection: collection - file: file - page: page - pointer: pointer + file: file + page: page + pointer: pointer )! } else if action.name == 'people_add' { console.print_debug('website.people_add') @@ -136,9 +136,9 @@ pub fn play_zola(mut plbook playbook.PlayBook) ! { sort_by := zola.SortBy.from(sort_by_)! site_.people_add( - name: name - title: p.get_default('title', '')! - sort_by: sort_by + name: name + title: p.get_default('title', '')! + sort_by: sort_by description: description )! } else if action.name == 'blog_add' { @@ -153,9 +153,9 @@ pub fn play_zola(mut plbook playbook.PlayBook) ! { sort_by := zola.SortBy.from(sort_by_)! site_.blog_add( - name: name - title: p.get_default('title', '')! - sort_by: sort_by + name: name + title: p.get_default('title', '')! + sort_by: sort_by description: description )! } else if action.name == 'news_add' { diff --git a/lib/hero/baobab/action/error.v b/lib/hero/baobab/action/error.v index 02b52eb0..a035079f 100644 --- a/lib/hero/baobab/action/error.v +++ b/lib/hero/baobab/action/error.v @@ -2,32 +2,32 @@ module action // Error struct for error handling pub struct ActionError { - reason ErrorReason + reason ErrorReason } // Enum for different error reasons pub enum ErrorReason { - timeout - serialization_failed - deserialization_failed + timeout + serialization_failed + deserialization_failed enqueue_failed } pub fn (err ActionError) code() int { - return match err.reason { - .timeout { 408 } // HTTP 408 Request Timeout - .serialization_failed { 500 } // HTTP 500 Internal Server Error - .deserialization_failed { 500 } // HTTP 500 Internal Server Error - .enqueue_failed { 503 } // HTTP 503 Service Unavailable - } + return match err.reason { + .timeout { 408 } // HTTP 408 Request Timeout + .serialization_failed { 500 } // HTTP 500 Internal Server Error + .deserialization_failed { 500 } // HTTP 500 Internal Server Error + .enqueue_failed { 503 } // HTTP 503 Service Unavailable + } } pub fn (err ActionError) msg() string { - explanation := match err.reason { - .timeout { 'The procedure call timed out.' } - .serialization_failed { 'Failed to serialize the procedure call.' } - .deserialization_failed { 'Failed to deserialize the procedure response.' } - .enqueue_failed { 'Failed to enqueue the procedure response.' } - } - return 'Procedure failed: $explanation' + explanation := match err.reason { + .timeout { 'The procedure call timed out.' } + .serialization_failed { 'Failed to serialize the procedure call.' } + .deserialization_failed { 'Failed to deserialize the procedure response.' } + .enqueue_failed { 'Failed to enqueue the procedure response.' } + } + return 'Procedure failed: ${explanation}' } diff --git a/lib/hero/baobab/action/procedure.v b/lib/hero/baobab/action/procedure.v index 89f02985..64a7f763 100644 --- a/lib/hero/baobab/action/procedure.v +++ b/lib/hero/baobab/action/procedure.v @@ -3,13 +3,13 @@ module action // ProcedureResponse struct representing the result of a procedure call pub struct ProcedureResponse { pub: - result string // Response data - error string // Internal error message (if any) + result string // Response data + error string // Internal error message (if any) } // Parameters for processing a procedure call @[params] pub struct ProcessParams { pub: - timeout int // Timeout in seconds -} \ No newline at end of file + timeout int // Timeout in seconds +} diff --git a/lib/hero/baobab/action/reflection_openapi.v b/lib/hero/baobab/action/reflection_openapi.v index a7beefcc..6a3c1d39 100644 --- a/lib/hero/baobab/action/reflection_openapi.v +++ b/lib/hero/baobab/action/reflection_openapi.v @@ -4,86 +4,86 @@ import json import os import time import veb -import x.json2 {Any} +import x.json2 { Any } import net.http -import freeflowuniverse.herolib.data.jsonschema {Schema} +import freeflowuniverse.herolib.data.jsonschema { Schema } // import freeflowuniverse.herolib.hero.processor {Processor, ProcedureCall, ProcedureResponse, ProcessParams} import freeflowuniverse.herolib.clients.redisclient -import freeflowuniverse.herolib.web.openapi {Request} +import freeflowuniverse.herolib.web.openapi { Request } pub fn openapi_request_to_action(request Request) Action { - // Convert incoming OpenAPI request to a procedure call - mut params := []string{} + // Convert incoming OpenAPI request to a procedure call + mut params := []string{} - if request.arguments.len > 0 { - params = request.arguments.values().map(it.str()).clone() - } + if request.arguments.len > 0 { + params = request.arguments.values().map(it.str()).clone() + } - if request.body != '' { - params << request.body - } + if request.body != '' { + params << request.body + } - if request.parameters.len != 0 { - mut param_map := map[string]Any{} // Store parameters with correct types + if request.parameters.len != 0 { + mut param_map := map[string]Any{} // Store parameters with correct types - for param_name, param_value in request.parameters { - operation_param := request.operation.parameters.filter(it.name == param_name) - if operation_param.len > 0 { - param_schema := operation_param[0].schema as Schema - param_type := param_schema.typ - param_format := param_schema.format + for param_name, param_value in request.parameters { + operation_param := request.operation.parameters.filter(it.name == param_name) + if operation_param.len > 0 { + param_schema := operation_param[0].schema as Schema + param_type := param_schema.typ + param_format := param_schema.format - // Convert parameter value to corresponding type - match param_type { - 'integer' { - match param_format { - 'int32' { - param_map[param_name] = param_value.int() // Convert to int - } - 'int64' { - param_map[param_name] = param_value.i64() // Convert to i64 - } - else { - param_map[param_name] = param_value.int() // Default to int - } - } - } - 'string' { - param_map[param_name] = param_value // Already a string - } - 'boolean' { - param_map[param_name] = param_value.bool() // Convert to bool - } - 'number' { - match param_format { - 'float' { - param_map[param_name] = param_value.f32() // Convert to float - } - 'double' { - param_map[param_name] = param_value.f64() // Convert to double - } - else { - param_map[param_name] = param_value.f64() // Default to double - } - } - } - else { - param_map[param_name] = param_value // Leave as string for unknown types - } - } - } else { - // If the parameter is not defined in the OpenAPI operation, skip or log it - println('Unknown parameter: $param_name') - } - } + // Convert parameter value to corresponding type + match param_type { + 'integer' { + match param_format { + 'int32' { + param_map[param_name] = param_value.int() // Convert to int + } + 'int64' { + param_map[param_name] = param_value.i64() // Convert to i64 + } + else { + param_map[param_name] = param_value.int() // Default to int + } + } + } + 'string' { + param_map[param_name] = param_value // Already a string + } + 'boolean' { + param_map[param_name] = param_value.bool() // Convert to bool + } + 'number' { + match param_format { + 'float' { + param_map[param_name] = param_value.f32() // Convert to float + } + 'double' { + param_map[param_name] = param_value.f64() // Convert to double + } + else { + param_map[param_name] = param_value.f64() // Default to double + } + } + } + else { + param_map[param_name] = param_value // Leave as string for unknown types + } + } + } else { + // If the parameter is not defined in the OpenAPI operation, skip or log it + println('Unknown parameter: ${param_name}') + } + } - // Encode the parameter map to JSON if needed - params << json.encode(param_map.str()) - } + // Encode the parameter map to JSON if needed + params << json.encode(param_map.str()) + } - call := Action{ - method: request.operation.operation_id - params: "[${params.join(',')}]" // Keep as a string since ProcedureCall expects a string - } + call := Action{ + method: request.operation.operation_id + params: '[${params.join(',')}]' // Keep as a string since ProcedureCall expects a string + } return call -} \ No newline at end of file +} diff --git a/lib/hero/baobab/actor/client.v b/lib/hero/baobab/actor/client.v index e4036b41..14d3a25c 100644 --- a/lib/hero/baobab/actor/client.v +++ b/lib/hero/baobab/actor/client.v @@ -41,11 +41,11 @@ pub fn (mut p Client) monologue(call ProcedureCall, params Params) ! { timeout: u64(params.timeout * 1000) // Convert seconds to milliseconds wait: true })! - // TODO: check error type + // TODO: check error type } // Process the procedure call -pub fn (mut p Client) call_to_action (action Procedure, params Params) !ProcedureResponse { +pub fn (mut p Client) call_to_action(action Procedure, params Params) !ProcedureResponse { // Use RedisRpc's `call` to send the call and wait for the response response_data := p.rpc.call(redisclient.RPCArgs{ cmd: call.method diff --git a/lib/hero/baobab/example_actor/actor.v b/lib/hero/baobab/example_actor/actor.v index 02bed1c5..bd294826 100644 --- a/lib/hero/baobab/example_actor/actor.v +++ b/lib/hero/baobab/example_actor/actor.v @@ -1,7 +1,7 @@ module example_actor import os -import freeflowuniverse.herolib.hero.baobab.actor {IActor, RunParams} +import freeflowuniverse.herolib.hero.baobab.actor { IActor, RunParams } import freeflowuniverse.herolib.web.openapi import time @@ -10,27 +10,25 @@ const openapi_spec_json = os.read_file(openapi_spec_path) or { panic(err) } const openapi_specification = openapi.json_decode(openapi_spec_json)! struct ExampleActor { - actor.Actor + actor.Actor } fn new() !ExampleActor { - return ExampleActor{ - actor.new('example') - } + return ExampleActor{actor.new('example')} } pub fn run() ! { - mut a_ := new()! - mut a := IActor(a_) - a.run()! + mut a_ := new()! + mut a := IActor(a_) + a.run()! } pub fn run_server(params RunParams) ! { - mut a := new()! - mut server := actor.new_server( - redis_url: 'localhost:6379' - redis_queue: a.name - openapi_spec: openapi_specification - )! - server.run(params) -} \ No newline at end of file + mut a := new()! + mut server := actor.new_server( + redis_url: 'localhost:6379' + redis_queue: a.name + openapi_spec: openapi_specification + )! + server.run(params) +} diff --git a/lib/hero/baobab/example_actor/actor_test.v b/lib/hero/baobab/example_actor/actor_test.v index cab2e268..d07f5d25 100644 --- a/lib/hero/baobab/example_actor/actor_test.v +++ b/lib/hero/baobab/example_actor/actor_test.v @@ -3,9 +3,7 @@ module example_actor const test_port = 8101 pub fn test_new() ! { - new() or { - return error('Failed to create actor:\n${err}') - } + new() or { return error('Failed to create actor:\n${err}') } } pub fn test_run() ! { @@ -14,4 +12,4 @@ pub fn test_run() ! { pub fn test_run_server() ! { spawn run_server(port: test_port) -} \ No newline at end of file +} diff --git a/lib/hero/baobab/example_actor/handle.v b/lib/hero/baobab/example_actor/handle.v index dfc067ef..889fce52 100644 --- a/lib/hero/baobab/example_actor/handle.v +++ b/lib/hero/baobab/example_actor/handle.v @@ -1,5 +1,5 @@ module example_actor pub fn (mut a ExampleActor) handle(method string, data string) !string { - return data -} \ No newline at end of file + return data +} diff --git a/lib/hero/baobab/example_actor/interface_command.v b/lib/hero/baobab/example_actor/interface_command.v index 3a7c110e..79200cb8 100644 --- a/lib/hero/baobab/example_actor/interface_command.v +++ b/lib/hero/baobab/example_actor/interface_command.v @@ -7,32 +7,32 @@ import freeflowuniverse.herolib.ui.console pub fn cmd_example_actor() Command { mut cmd := Command{ - name: 'example_actor' - usage: '' - description: 'create, edit, show mdbooks' + name: 'example_actor' + usage: '' + description: 'create, edit, show mdbooks' required_args: 0 - execute: cmd_example_actor_execute + execute: cmd_example_actor_execute } mut cmd_list := Command{ - sort_flags: true - name: 'list_books' - execute: cmd_publisher_list_books + sort_flags: true + name: 'list_books' + execute: cmd_publisher_list_books description: 'will list existing mdbooks' pre_execute: pre_func } mut cmd_open := Command{ - name: 'open' - execute: cmd_publisher_open + name: 'open' + execute: cmd_publisher_open description: 'will open the publication with the provided name' pre_execute: pre_func } cmd_open.add_flag(Flag{ - flag: .string - name: 'name' - abbrev: 'n' + flag: .string + name: 'name' + abbrev: 'n' description: 'name of the publication.' }) @@ -80,4 +80,4 @@ fn publisher_help(cmd Command) { console.print_lf(1) console.print_stdout(cmd.help_message()) console.print_lf(5) -} \ No newline at end of file +} diff --git a/lib/hero/baobab/generator/generate_actor.v b/lib/hero/baobab/generator/generate_actor.v index 99904f15..c8d37b88 100644 --- a/lib/hero/baobab/generator/generate_actor.v +++ b/lib/hero/baobab/generator/generate_actor.v @@ -1,26 +1,26 @@ module generator -import freeflowuniverse.herolib.core.codemodel { Folder, IFile, VFile, CodeItem, File, Function, Import, Module, Struct, CustomCode } +import freeflowuniverse.herolib.core.codemodel { CustomCode, File, Folder, IFile, Module, VFile } import freeflowuniverse.herolib.core.texttools import freeflowuniverse.herolib.core.codeparser import freeflowuniverse.herolib.data.markdownparser -import freeflowuniverse.herolib.data.markdownparser.elements { Header } +import freeflowuniverse.herolib.data.markdownparser.elements import freeflowuniverse.herolib.rpc.openrpc import freeflowuniverse.herolib.core.pathlib -import freeflowuniverse.herolib.hero.baobab.specification {ActorMethod, ActorSpecification} +import freeflowuniverse.herolib.hero.baobab.specification { ActorSpecification } import os import json pub fn generate_actor_module(spec ActorSpecification) !Module { mut files := []IFile{} - + files = [ generate_readme_file(spec)!, generate_actor_file(spec)!, generate_actor_test_file(spec)!, generate_handle_file(spec)!, - generate_methods_file(spec)! - generate_client_file(spec)! + generate_methods_file(spec)!, + generate_client_file(spec)!, ] mut docs_files := []IFile{} @@ -31,14 +31,14 @@ pub fn generate_actor_module(spec ActorSpecification) !Module { .openrpc { // convert actor spec to openrpc spec openrpc_spec := spec.to_openrpc() - + // generate openrpc code files files << generate_openrpc_client_file(openrpc_spec)! files << generate_openrpc_client_test_file(openrpc_spec)! // add openrpc.json to docs docs_files << generate_openrpc_file(openrpc_spec)! - } + } .command { files << generate_command_file(spec)! } @@ -49,25 +49,25 @@ pub fn generate_actor_module(spec ActorSpecification) !Module { } // folder with docs - docs_folder := Folder { - name: 'docs' + docs_folder := Folder{ + name: 'docs' files: docs_files } - + // create module with code files and docs folder name_fixed := texttools.name_fix_snake(spec.name) return codemodel.new_module( - name: '${name_fixed}_actor' - files: files + name: '${name_fixed}_actor' + files: files folders: [docs_folder] ) } fn generate_readme_file(spec ActorSpecification) !File { return File{ - name: 'README' + name: 'README' extension: 'md' - content: '# ${spec.name}\n${spec.description}' + content: '# ${spec.name}\n${spec.description}' } } @@ -76,8 +76,8 @@ fn generate_actor_file(spec ActorSpecification) !VFile { actor_name_snake := texttools.name_fix_snake(spec.name) actor_name_pascal := texttools.name_fix_snake_to_pascal(spec.name) code := $tmpl('./templates/actor.v.template') - return VFile { - name: 'actor' + return VFile{ + name: 'actor' items: [CustomCode{code}] } } @@ -87,19 +87,18 @@ fn generate_actor_test_file(spec ActorSpecification) !VFile { actor_name_snake := texttools.name_fix_snake(spec.name) actor_name_pascal := texttools.name_fix_snake_to_pascal(spec.name) code := $tmpl('./templates/actor_test.v.template') - return VFile { - name: 'actor_test' + return VFile{ + name: 'actor_test' items: [CustomCode{code}] } } - pub fn generate_openapi_file(spec ActorSpecification) !File { openapi_spec := spec.to_openapi() openapi_json := json.encode(openapi_spec) return File{ - name: 'openapi' + name: 'openapi' extension: 'json' - content: openapi_json + content: openapi_json } -} \ No newline at end of file +} diff --git a/lib/hero/baobab/generator/generate_actor_test.v b/lib/hero/baobab/generator/generate_actor_test.v index b286ac2f..d6350257 100644 --- a/lib/hero/baobab/generator/generate_actor_test.v +++ b/lib/hero/baobab/generator/generate_actor_test.v @@ -7,130 +7,156 @@ import freeflowuniverse.herolib.core.pathlib import os const actor_spec = specification.ActorSpecification{ - name: 'Pet Store' - description: 'A sample API for a pet store' - interfaces: [.openrpc, .command] - methods: [specification.ActorMethod{ - name: 'listPets' - description: 'List all pets' - func: codemodel.Function{ - name: 'listPets' - params: [codemodel.Param{ - description: 'Maximum number of pets to return' - name: 'limit' - typ: codemodel.Type{ - symbol: 'int' - } - }] - } - }, specification.ActorMethod{ - name: 'createPet' - description: 'Create a new pet' - func: codemodel.Function{ - name: 'createPet' - } - }, specification.ActorMethod{ - name: 'getPet' - description: 'Get a pet by ID' - func: codemodel.Function{ - name: 'getPet' - params: [codemodel.Param{ - required: true - description: 'ID of the pet to retrieve' - name: 'petId' - typ: codemodel.Type{ - symbol: 'int' - } - }] - } - }, specification.ActorMethod{ - name: 'deletePet' - description: 'Delete a pet by ID' - func: codemodel.Function{ - name: 'deletePet' - params: [codemodel.Param{ - required: true - description: 'ID of the pet to delete' - name: 'petId' - typ: codemodel.Type{ - symbol: 'int' - } - }] - } - }, specification.ActorMethod{ - name: 'listOrders' - description: 'List all orders' - func: codemodel.Function{ - name: 'listOrders' - } - }, specification.ActorMethod{ - name: 'getOrder' - description: 'Get an order by ID' - func: codemodel.Function{ - name: 'getOrder' - params: [codemodel.Param{ - required: true - description: 'ID of the order to retrieve' - name: 'orderId' - typ: codemodel.Type{ - symbol: 'int' - } - }] - } - }, specification.ActorMethod{ - name: 'deleteOrder' - description: 'Delete an order by ID' - func: codemodel.Function{ - name: 'deleteOrder' - params: [codemodel.Param{ - required: true - description: 'ID of the order to delete' - name: 'orderId' - typ: codemodel.Type{ - symbol: 'int' - } - }] - } - }, specification.ActorMethod{ - name: 'createUser' - description: 'Create a user' - func: codemodel.Function{ - name: 'createUser' - } - }] - objects: [specification.BaseObject{ - structure: codemodel.Struct{ - name: 'Pet' - } - }, specification.BaseObject{ - structure: codemodel.Struct{ - name: 'NewPet' - } - }, specification.BaseObject{ - structure: codemodel.Struct{ - name: 'Pets' - } - }, specification.BaseObject{ - structure: codemodel.Struct{ - name: 'Order' - } - }, specification.BaseObject{ - structure: codemodel.Struct{ - name: 'User' - } - }, specification.BaseObject{ - structure: codemodel.Struct{ - name: 'NewUser' - } - }] + name: 'Pet Store' + description: 'A sample API for a pet store' + interfaces: [.openrpc, .command] + methods: [ + specification.ActorMethod{ + name: 'listPets' + description: 'List all pets' + func: codemodel.Function{ + name: 'listPets' + params: [ + codemodel.Param{ + description: 'Maximum number of pets to return' + name: 'limit' + typ: codemodel.Type{ + symbol: 'int' + } + }, + ] + } + }, + specification.ActorMethod{ + name: 'createPet' + description: 'Create a new pet' + func: codemodel.Function{ + name: 'createPet' + } + }, + specification.ActorMethod{ + name: 'getPet' + description: 'Get a pet by ID' + func: codemodel.Function{ + name: 'getPet' + params: [ + codemodel.Param{ + required: true + description: 'ID of the pet to retrieve' + name: 'petId' + typ: codemodel.Type{ + symbol: 'int' + } + }, + ] + } + }, + specification.ActorMethod{ + name: 'deletePet' + description: 'Delete a pet by ID' + func: codemodel.Function{ + name: 'deletePet' + params: [ + codemodel.Param{ + required: true + description: 'ID of the pet to delete' + name: 'petId' + typ: codemodel.Type{ + symbol: 'int' + } + }, + ] + } + }, + specification.ActorMethod{ + name: 'listOrders' + description: 'List all orders' + func: codemodel.Function{ + name: 'listOrders' + } + }, + specification.ActorMethod{ + name: 'getOrder' + description: 'Get an order by ID' + func: codemodel.Function{ + name: 'getOrder' + params: [ + codemodel.Param{ + required: true + description: 'ID of the order to retrieve' + name: 'orderId' + typ: codemodel.Type{ + symbol: 'int' + } + }, + ] + } + }, + specification.ActorMethod{ + name: 'deleteOrder' + description: 'Delete an order by ID' + func: codemodel.Function{ + name: 'deleteOrder' + params: [ + codemodel.Param{ + required: true + description: 'ID of the order to delete' + name: 'orderId' + typ: codemodel.Type{ + symbol: 'int' + } + }, + ] + } + }, + specification.ActorMethod{ + name: 'createUser' + description: 'Create a user' + func: codemodel.Function{ + name: 'createUser' + } + }, + ] + objects: [ + specification.BaseObject{ + structure: codemodel.Struct{ + name: 'Pet' + } + }, + specification.BaseObject{ + structure: codemodel.Struct{ + name: 'NewPet' + } + }, + specification.BaseObject{ + structure: codemodel.Struct{ + name: 'Pets' + } + }, + specification.BaseObject{ + structure: codemodel.Struct{ + name: 'Order' + } + }, + specification.BaseObject{ + structure: codemodel.Struct{ + name: 'User' + } + }, + specification.BaseObject{ + structure: codemodel.Struct{ + name: 'NewUser' + } + }, + ] } const destination = '${os.dir(@FILE)}/testdata' fn test_generate_actor_module() { actor_module := generate_actor_module(actor_spec)! - actor_module.write(destination, - format: true - overwrite: true - )! + actor_module.write(destination, + format: true + overwrite: true + )! } diff --git a/lib/hero/baobab/generator/generate_clients.v b/lib/hero/baobab/generator/generate_clients.v index 58d66be6..ecfa2a98 100644 --- a/lib/hero/baobab/generator/generate_clients.v +++ b/lib/hero/baobab/generator/generate_clients.v @@ -1,23 +1,23 @@ module generator -import freeflowuniverse.herolib.core.codemodel { Folder, IFile, VFile, CodeItem, File, Function, Import, Module, Struct, CustomCode } +import freeflowuniverse.herolib.core.codemodel { CodeItem, CustomCode, Import, VFile } import freeflowuniverse.herolib.core.texttools import freeflowuniverse.herolib.core.codeparser import freeflowuniverse.herolib.data.markdownparser -import freeflowuniverse.herolib.data.markdownparser.elements { Header } +import freeflowuniverse.herolib.data.markdownparser.elements import freeflowuniverse.herolib.rpc.openrpc import freeflowuniverse.herolib.core.pathlib -import freeflowuniverse.herolib.hero.baobab.specification {ActorMethod, ActorSpecification} +import freeflowuniverse.herolib.hero.baobab.specification { ActorMethod, ActorSpecification } import os import json pub fn generate_client_file(spec ActorSpecification) !VFile { actor_name_snake := texttools.name_fix_snake(spec.name) actor_name_pascal := texttools.name_fix_snake_to_pascal(spec.name) - + mut items := []CodeItem{} - items << CustomCode {' + items << CustomCode{' pub struct Client { actor.Client } @@ -25,22 +25,22 @@ pub fn generate_client_file(spec ActorSpecification) !VFile { fn new_client() Client { return Client{} }'} - + for method in spec.methods { items << CustomCode{generate_client_method(method)!} } - - return VFile { + + return VFile{ imports: [ Import{ mod: 'freeflowuniverse.herolib.data.paramsparser' }, Import{ mod: 'freeflowuniverse.herolib.hero.baobab.actor' - } + }, ] - name: 'client' - items: items + name: 'client' + items: items } } @@ -49,17 +49,21 @@ pub fn generate_client_method(method ActorMethod) !string { mut handler := '// Method for ${name_fixed}\n' params := if method.func.params.len > 0 { method.func.params.map(it.vgen()).join(', ') - } else {''} + } else { + '' + } call_params := if method.func.params.len > 0 { method.func.params.map(it.name).join(', ') - } else {''} + } else { + '' + } - handler += "fn (mut client Client) ${name_fixed}(${params}) ! { + handler += 'fn (mut client Client) ${name_fixed}(${params}) ! { client.call_to_action( method: ${name_fixed} params: paramsparser.encode(${call_params}) ) - }" + }' return handler -} \ No newline at end of file +} diff --git a/lib/hero/baobab/generator/generate_command.v b/lib/hero/baobab/generator/generate_command.v index 58c56c99..af1c3522 100644 --- a/lib/hero/baobab/generator/generate_command.v +++ b/lib/hero/baobab/generator/generate_command.v @@ -1,8 +1,8 @@ module generator -import freeflowuniverse.herolib.core.codemodel { Folder, IFile, VFile, CodeItem, File, Function, Import, Module, Struct, CustomCode } +import freeflowuniverse.herolib.core.codemodel { CodeItem, CustomCode, Import, VFile } import freeflowuniverse.herolib.core.texttools -import freeflowuniverse.herolib.hero.baobab.specification {ActorMethod, ActorSpecification} +import freeflowuniverse.herolib.hero.baobab.specification { ActorMethod, ActorSpecification } pub fn generate_command_file(spec ActorSpecification) !VFile { mut items := []CodeItem{} @@ -10,21 +10,21 @@ pub fn generate_command_file(spec ActorSpecification) !VFile { for i in spec.methods { items << CustomCode{generate_method_cmd_function(spec.name, i)} } - return VFile { - name: 'command' + return VFile{ + name: 'command' imports: [ Import{ mod: 'freeflowuniverse.herolib.ui.console' }, Import{ - mod: 'cli' + mod: 'cli' types: ['Command', 'Flag'] - } + }, ] - items: items + items: items } } - + pub fn generate_cmd_function(spec ActorSpecification) string { actor_name_snake := texttools.name_fix_snake(spec.name) mut cmd_function := " @@ -36,7 +36,7 @@ pub fn generate_cmd_function(spec ActorSpecification) string { execute: cmd_execute } " - + mut method_cmds := []string{} for method in spec.methods { method_cmds << generate_method_cmd(method) @@ -65,7 +65,7 @@ pub fn generate_method_cmd_function(actor_name string, method ActorMethod) strin actor_name_snake := texttools.name_fix_snake(actor_name) method_name_snake := texttools.name_fix_snake(method.name) - + method_call := if method.func.result.typ.symbol == '' { '${actor_name_snake}.${method_name_snake}()!' } else { diff --git a/lib/hero/baobab/generator/generate_handle.v b/lib/hero/baobab/generator/generate_handle.v index f7bd17e4..7a3dc623 100644 --- a/lib/hero/baobab/generator/generate_handle.v +++ b/lib/hero/baobab/generator/generate_handle.v @@ -1,13 +1,13 @@ module generator -import freeflowuniverse.herolib.core.codemodel { Folder, IFile, VFile, CodeItem, File, Function, Import, Module, Struct, CustomCode } +import freeflowuniverse.herolib.core.codemodel { CodeItem, CustomCode, VFile } import freeflowuniverse.herolib.core.texttools import freeflowuniverse.herolib.core.codeparser import freeflowuniverse.herolib.data.markdownparser -import freeflowuniverse.herolib.data.markdownparser.elements { Header } +import freeflowuniverse.herolib.data.markdownparser.elements import freeflowuniverse.herolib.rpc.openrpc import freeflowuniverse.herolib.core.pathlib -import freeflowuniverse.herolib.hero.baobab.specification {ActorMethod, ActorSpecification} +import freeflowuniverse.herolib.hero.baobab.specification { ActorMethod, ActorSpecification } import os import json @@ -17,8 +17,8 @@ fn generate_handle_file(spec ActorSpecification) !VFile { for method in spec.methods { items << CustomCode{generate_method_handle(spec.name, method)!} } - return VFile { - name: 'act' + return VFile{ + name: 'act' items: items } } @@ -57,7 +57,7 @@ pub fn generate_method_handle(actor_name string, method ActorMethod) !string { actor_name_pascal := texttools.name_fix_snake_to_pascal(actor_name) name_fixed := texttools.name_fix_snake(method.name) mut handler := '// Handler for ${name_fixed}\n' - handler += "fn (mut actor ${actor_name_pascal}Actor) handle_${name_fixed}(data string) !string {\n" + handler += 'fn (mut actor ${actor_name_pascal}Actor) handle_${name_fixed}(data string) !string {\n' if method.func.params.len > 0 { handler += ' params := json.decode(${method.func.params[0].typ.symbol}, data) or { return error("Invalid input data: \${err}") }\n' handler += ' result := actor.${name_fixed}(params)\n' @@ -79,4 +79,4 @@ fn generate_route_case(method string, operation_id string) string { case_block += '\n return Response{ status: http.Status.ok, body: response }' case_block += '\n }' return case_block -} \ No newline at end of file +} diff --git a/lib/hero/baobab/generator/generate_methods.v b/lib/hero/baobab/generator/generate_methods.v index 6cd64d7e..502f103b 100644 --- a/lib/hero/baobab/generator/generate_methods.v +++ b/lib/hero/baobab/generator/generate_methods.v @@ -1,27 +1,27 @@ module generator -import freeflowuniverse.herolib.core.codemodel { Folder, IFile, VFile, CodeItem, File, Function, Import, Module, Struct, CustomCode } +import freeflowuniverse.herolib.core.codemodel { CodeItem, CustomCode, VFile } import freeflowuniverse.herolib.core.texttools import freeflowuniverse.herolib.core.codeparser import freeflowuniverse.herolib.data.markdownparser -import freeflowuniverse.herolib.data.markdownparser.elements { Header } +import freeflowuniverse.herolib.data.markdownparser.elements import freeflowuniverse.herolib.rpc.openrpc import freeflowuniverse.herolib.core.pathlib -import freeflowuniverse.herolib.hero.baobab.specification {ActorMethod, ActorSpecification} +import freeflowuniverse.herolib.hero.baobab.specification { ActorMethod, ActorSpecification } import os import json pub fn generate_methods_file(spec ActorSpecification) !VFile { actor_name_snake := texttools.name_fix_snake(spec.name) actor_name_pascal := texttools.name_fix_snake_to_pascal(spec.name) - + mut items := []CodeItem{} for method in spec.methods { items << CustomCode{generate_method_function(spec.name, method)!} } - - return VFile { - name: 'methods' + + return VFile{ + name: 'methods' items: items } } @@ -32,7 +32,9 @@ pub fn generate_method_function(actor_name string, method ActorMethod) !string { mut handler := '// Method for ${name_fixed}\n' params := if method.func.params.len > 0 { method.func.params.map(it.vgen()).join(', ') - } else {''} - handler += "fn (mut actor ${actor_name_pascal}Actor) ${name_fixed}(${params}) ! {}" + } else { + '' + } + handler += 'fn (mut actor ${actor_name_pascal}Actor) ${name_fixed}(${params}) ! {}' return handler -} \ No newline at end of file +} diff --git a/lib/hero/baobab/generator/generate_objects.v b/lib/hero/baobab/generator/generate_objects.v index 7398f70d..b1bba238 100644 --- a/lib/hero/baobab/generator/generate_objects.v +++ b/lib/hero/baobab/generator/generate_objects.v @@ -36,7 +36,6 @@ module generator // return file // } - // pub fn (a Actor) generate_model_files() ![]VFile { // structs := a.objects.map(it.structure) // return a.objects.map(codemodel.new_file( diff --git a/lib/hero/baobab/generator/generate_openrpc.v b/lib/hero/baobab/generator/generate_openrpc.v index a7dfd9b6..6af53480 100644 --- a/lib/hero/baobab/generator/generate_openrpc.v +++ b/lib/hero/baobab/generator/generate_openrpc.v @@ -1,19 +1,19 @@ module generator import json -import freeflowuniverse.herolib.core.codemodel { VFile, File, Function, Module, Struct } +import freeflowuniverse.herolib.core.codemodel { File, Function, Struct, VFile } import freeflowuniverse.herolib.core.pathlib import freeflowuniverse.herolib.core.texttools -import freeflowuniverse.herolib.hero.baobab.specification {ActorSpecification} -import freeflowuniverse.herolib.rpc.openrpc { Components, OpenRPC } -import freeflowuniverse.herolib.data.jsonschema { SchemaRef } +import freeflowuniverse.herolib.hero.baobab.specification +import freeflowuniverse.herolib.rpc.openrpc { OpenRPC } +import freeflowuniverse.herolib.data.jsonschema pub fn generate_openrpc_file(spec OpenRPC) !File { - return File { - name: 'openrpc' + return File{ + name: 'openrpc' extension: 'json' - content: json.encode(spec) - } + content: json.encode(spec) + } } pub fn generate_openrpc_client_file(spec OpenRPC) !VFile { @@ -22,12 +22,12 @@ pub fn generate_openrpc_client_file(spec OpenRPC) !VFile { // objects_map[object.structure.name] = object.structure // } client_file := spec.generate_client_file(objects_map)! - return VFile { - ...client_file, + return VFile{ + ...client_file name: 'client_openrpc' - } + } } - + pub fn generate_openrpc_client_test_file(spec OpenRPC) !VFile { mut objects_map := map[string]Struct{} // for object in spec.objects { @@ -38,10 +38,10 @@ pub fn generate_openrpc_client_test_file(spec OpenRPC) !VFile { // methods_map[method.func.name] = method.func // } file := spec.generate_client_test_file(methods_map, objects_map)! - return VFile { - ...file, + return VFile{ + ...file name: 'client_openrpc_test' - } + } } // pub fn (actor Actor) generate_openrpc_code() !Module { diff --git a/lib/hero/baobab/generator/generate_openrpc_test.v b/lib/hero/baobab/generator/generate_openrpc_test.v index 321cbc10..8533cfec 100644 --- a/lib/hero/baobab/generator/generate_openrpc_test.v +++ b/lib/hero/baobab/generator/generate_openrpc_test.v @@ -3,15 +3,15 @@ module generator import freeflowuniverse.herolib.core.codemodel { Function, Param, Result, Struct, Type } import freeflowuniverse.herolib.rpc.openrpc -const test_actor_specification = ActorSpecification { +const test_actor_specification = ActorSpecification{ methods: [ ActorMethod{ func: Function{ - name: 'get_object' + name: 'get_object' params: [ Param{ name: 'id' - typ: Type{ + typ: Type{ symbol: 'int' } }, @@ -32,9 +32,7 @@ const test_actor_specification = ActorSpecification { } pub fn test_generate_openrpc() ! { - actor := Actor{ - - } + actor := Actor{} object := generate_openrpc(actor) panic(object.encode()!) } diff --git a/lib/hero/baobab/generator/write_object_methods.v b/lib/hero/baobab/generator/write_object_methods.v index 93decefa..57968ce0 100644 --- a/lib/hero/baobab/generator/write_object_methods.v +++ b/lib/hero/baobab/generator/write_object_methods.v @@ -1,14 +1,14 @@ module generator -import freeflowuniverse.herolib.hero.baobab.specification {BaseObject} -import freeflowuniverse.herolib.core.codemodel { VFile, CodeItem, Function, Import, Param, Result, Struct, StructField, Type } +import freeflowuniverse.herolib.hero.baobab.specification { BaseObject } +import freeflowuniverse.herolib.core.codemodel { CodeItem, Function, Import, Param, Result, Struct, StructField, Type, VFile } import freeflowuniverse.herolib.core.codeparser import freeflowuniverse.herolib.core.texttools import os const id_param = Param{ name: 'id' - typ: Type{ + typ: Type{ symbol: 'u32' } } @@ -24,19 +24,19 @@ pub fn generate_object_code(actor Struct, object BaseObject) VFile { items << generate_object_methods(actor, object) mut file := codemodel.new_file( - mod: texttools.name_fix(actor.name) - name: obj_name + mod: texttools.name_fix(actor.name) + name: obj_name imports: [ Import{ - mod: object.structure.mod + mod: object.structure.mod types: [object_type] }, Import{ - mod: 'freeflowuniverse.herolib.baobab.backend' + mod: 'freeflowuniverse.herolib.baobab.backend' types: ['FilterParams'] }, ] - items: items + items: items ) if object.structure.fields.any(it.attrs.any(it.name == 'index')) { @@ -55,23 +55,23 @@ fn generate_get_method(actor Struct, object BaseObject) Function { object_type := object.structure.name get_method := Function{ - name: 'get_${object_name}' + name: 'get_${object_name}' description: 'gets the ${object_name} with the given object id' - receiver: Param{ + receiver: Param{ mutable: true - name: 'actor' - typ: Type{ + name: 'actor' + typ: Type{ symbol: actor.name } } - params: [generator.id_param] - result: Result{ - typ: Type{ + params: [id_param] + result: Result{ + typ: Type{ symbol: object.structure.name } result: true } - body: 'return actor.backend.get[${object_type}](id)!' + body: 'return actor.backend.get[${object_type}](id)!' } return get_method } @@ -82,33 +82,33 @@ fn generate_set_method(actor Struct, object BaseObject) Function { object_type := object.structure.name param_getters := generate_param_getters( - structure: object.structure - prefix: '' + structure: object.structure + prefix: '' only_mutable: true ) body := 'actor.backend.set[${object_type}](${object_name})!' get_method := Function{ - name: 'set_${object_name}' + name: 'set_${object_name}' description: 'updates the ${object.structure.name} with the given object id' - receiver: Param{ + receiver: Param{ mutable: true - name: 'actor' - typ: Type{ + name: 'actor' + typ: Type{ symbol: actor.name } } - params: [ + params: [ Param{ name: object_name - typ: Type{ + typ: Type{ symbol: object_type } }, ] - result: Result{ + result: Result{ result: true } - body: body + body: body } return get_method } @@ -120,20 +120,20 @@ fn generate_delete_method(actor Struct, object BaseObject) Function { body := 'actor.backend.delete[${object_type}](id)!' get_method := Function{ - name: 'delete_${object_name}' + name: 'delete_${object_name}' description: 'deletes the ${object.structure.name} with the given object id' - receiver: Param{ + receiver: Param{ mutable: true - name: 'actor' - typ: Type{ + name: 'actor' + typ: Type{ symbol: actor.name } } - params: [generator.id_param] - result: Result{ + params: [id_param] + result: Result{ result: true } - body: body + body: body } return get_method } @@ -144,36 +144,36 @@ fn generate_new_method(actor Struct, object BaseObject) Function { object_type := object.structure.name param_getters := generate_param_getters( - structure: object.structure - prefix: '' + structure: object.structure + prefix: '' only_mutable: false ) body := 'return actor.backend.new[${object_type}](${object_name})!' new_method := Function{ - name: 'new_${object_name}' + name: 'new_${object_name}' description: 'news the ${object.structure.name} with the given object id' - receiver: Param{ - name: 'actor' - typ: Type{ + receiver: Param{ + name: 'actor' + typ: Type{ symbol: actor.name } mutable: true } - params: [ + params: [ Param{ name: object_name - typ: Type{ + typ: Type{ symbol: object_type } }, ] - result: Result{ + result: Result{ result: true - typ: Type{ + typ: Type{ symbol: 'u32' } } - body: body + body: body } return new_method } @@ -183,12 +183,12 @@ fn generate_list_result_struct(actor Struct, object BaseObject) Struct { object_name := texttools.name_fix_pascal_to_snake(object.structure.name) object_type := object.structure.name return Struct{ - name: '${object_type}List' + name: '${object_type}List' is_pub: true fields: [ StructField{ name: 'items' - typ: Type{ + typ: Type{ symbol: '[]${object_type}' } }, @@ -202,11 +202,11 @@ fn generate_list_method(actor Struct, object BaseObject) Function { object_type := object.structure.name list_struct := Struct{ - name: '${object_type}List' + name: '${object_type}List' fields: [ StructField{ name: 'items' - typ: Type{ + typ: Type{ symbol: '[]${object_type}' } }, @@ -214,8 +214,8 @@ fn generate_list_method(actor Struct, object BaseObject) Function { } param_getters := generate_param_getters( - structure: object.structure - prefix: '' + structure: object.structure + prefix: '' only_mutable: false ) body := 'return ${object_type}List{items:actor.backend.list[${object_type}]()!}' @@ -225,18 +225,18 @@ fn generate_list_method(actor Struct, object BaseObject) Function { result.typ.symbol = result.structure.name result.result = true new_method := Function{ - name: 'list_${object_name}' + name: 'list_${object_name}' description: 'lists all of the ${object_name} objects' - receiver: Param{ - name: 'actor' - typ: Type{ + receiver: Param{ + name: 'actor' + typ: Type{ symbol: actor.name } mutable: true } - params: [] - result: result - body: body + params: [] + result: result + body: body } return new_method } @@ -247,24 +247,24 @@ fn generate_filter_params(actor Struct, object BaseObject) []Struct { return [ Struct{ - name: 'Filter${object_type}Params' + name: 'Filter${object_type}Params' fields: [ StructField{ name: 'filter' - typ: Type{ + typ: Type{ symbol: '${object_type}Filter' } }, StructField{ name: 'params' - typ: Type{ + typ: Type{ symbol: 'FilterParams' } }, ] }, Struct{ - name: '${object_type}Filter' + name: '${object_type}Filter' fields: object.structure.fields.filter(it.attrs.any(it.name == 'index')) }, ] @@ -276,37 +276,37 @@ fn generate_filter_method(actor Struct, object BaseObject) Function { object_type := object.structure.name param_getters := generate_param_getters( - structure: object.structure - prefix: '' + structure: object.structure + prefix: '' only_mutable: false ) params_type := 'Filter${object_type}Params' body := 'return actor.backend.filter[${object_type}, ${object_type}Filter](filter.filter, filter.params)!' return Function{ - name: 'filter_${object_name}' + name: 'filter_${object_name}' description: 'lists all of the ${object_name} objects' - receiver: Param{ - name: 'actor' - typ: Type{ + receiver: Param{ + name: 'actor' + typ: Type{ symbol: actor.name } mutable: true } - params: [ + params: [ Param{ name: 'filter' - typ: Type{ + typ: Type{ symbol: params_type } }, ] - result: Result{ - typ: Type{ + result: Result{ + typ: Type{ symbol: '[]${object_type}' } result: true } - body: body + body: body } } @@ -319,24 +319,24 @@ fn generate_object_methods(actor Struct, object BaseObject) []Function { for method in object.methods { mut params := [Param{ name: 'id' - typ: Type{ + typ: Type{ symbol: 'u32' } }] params << method.params funcs << Function{ - name: method.name + name: method.name description: method.description - receiver: Param{ - name: 'actor' - typ: Type{ + receiver: Param{ + name: 'actor' + typ: Type{ symbol: actor.name } mutable: true } - params: params - result: method.result - body: 'obj := actor.backend.get[${method.receiver.typ.symbol}](id)! + params: params + result: method.result + body: 'obj := actor.backend.get[${method.receiver.typ.symbol}](id)! obj.${method.name}(${method.params.map(it.name).join(',')}) actor.backend.set[${method.receiver.typ.symbol}](obj)! ' @@ -365,7 +365,7 @@ fn generate_param_getters(params GenerateParamGetters) []string { subgetters := generate_param_getters(GenerateParamGetters{ ...params structure: field.structure - prefix: '${field.name}_' + prefix: '${field.name}_' }) // name of the tested object, used for param declaration // ex: fruits []Fruit becomes fruit_name diff --git a/lib/hero/baobab/generator/write_object_methods_test.v b/lib/hero/baobab/generator/write_object_methods_test.v index 6746af95..f201e65b 100644 --- a/lib/hero/baobab/generator/write_object_methods_test.v +++ b/lib/hero/baobab/generator/write_object_methods_test.v @@ -19,11 +19,11 @@ import freeflowuniverse.herolib.ui.console pub fn test_generate_get_method() { generator := ActorGenerator{'test'} actor_struct := codemodel.Struct{ - name: 'TestActor' + name: 'TestActor' fields: [ codemodel.StructField{ name: 'test_struct_map' - typ: codemodel.Type{ + typ: codemodel.Type{ symbol: 'map[string]&TestStruct' } }, @@ -35,11 +35,11 @@ pub fn test_generate_get_method() { } field := get_child_field( parent: actor_struct - child: test_struct + child: test_struct ) method := generator.generate_get_method( - actor_name: actor_struct.name + actor_name: actor_struct.name actor_field: field root_struct: test_struct ) diff --git a/lib/hero/baobab/generator/write_object_tests.v b/lib/hero/baobab/generator/write_object_tests.v index f86dfac1..c55850f5 100644 --- a/lib/hero/baobab/generator/write_object_tests.v +++ b/lib/hero/baobab/generator/write_object_tests.v @@ -1,8 +1,8 @@ module generator -import freeflowuniverse.herolib.core.codemodel { VFile, CustomCode, Function, Import, Struct } +import freeflowuniverse.herolib.core.codemodel { CustomCode, Function, Import, Struct, VFile } import freeflowuniverse.herolib.core.codeparser -import freeflowuniverse.herolib.hero.baobab.specification {BaseObject} +import freeflowuniverse.herolib.hero.baobab.specification { BaseObject } import rand import freeflowuniverse.herolib.core.texttools import os @@ -30,18 +30,18 @@ pub fn generate_object_test_code(actor Struct, object BaseObject) !VFile { // TODO: support modules outside of hero mut file := VFile{ - name: '${object_name}_test' - mod: texttools.name_fix(actor_name) + name: '${object_name}_test' + mod: texttools.name_fix(actor_name) imports: [ Import{ mod: 'os' }, Import{ - mod: '${object.structure.mod}' + mod: '${object.structure.mod}' types: [object_type] }, ] - items: [ + items: [ consts, testsuite_begin, testsuite_end, @@ -77,12 +77,12 @@ fn generate_new_method_test(actor Struct, object BaseObject) !Function { ${object_name}_id = actor.new_${object_name}(${object_type}{${fields.join(',')}})! assert ${object_name}_id == 2' return Function{ - name: 'test_new_${object_name}' + name: 'test_new_${object_name}' description: 'news the ${object_type} with the given object id' - result: codemodel.Result{ + result: codemodel.Result{ result: true } - body: body + body: body } } @@ -103,12 +103,12 @@ fn generate_get_method_test(actor Struct, object BaseObject) !Function { ${object_name}.id = actor.new_${object_name}(${object_name})! assert ${object_name} == actor.get_${object_name}(${object_name}.id)!' return Function{ - name: 'test_get_${object_name}' + name: 'test_get_${object_name}' description: 'news the ${object_type} with the given object id' - result: codemodel.Result{ + result: codemodel.Result{ result: true } - body: body + body: body } } @@ -141,12 +141,12 @@ fn generate_filter_test(actor Struct, object BaseObject) !Function { \n${index_tests.join('\n\n')}' return Function{ - name: 'test_filter_${object_name}' + name: 'test_filter_${object_name}' description: 'news the ${object_type} with the given object id' - result: codemodel.Result{ + result: codemodel.Result{ result: true } - body: body + body: body } } diff --git a/lib/hero/baobab/osis/factory.v b/lib/hero/baobab/osis/factory.v index 25377a3a..17931303 100644 --- a/lib/hero/baobab/osis/factory.v +++ b/lib/hero/baobab/osis/factory.v @@ -9,6 +9,6 @@ import freeflowuniverse.herolib.data.encoderhero pub fn new(config OSISConfig) !OSIS { return OSIS{ indexer: new_indexer()! - storer: new_storer()! + storer: new_storer()! } } diff --git a/lib/hero/baobab/osis/indexer.v b/lib/hero/baobab/osis/indexer.v index 05c01e2a..a444f1c4 100644 --- a/lib/hero/baobab/osis/indexer.v +++ b/lib/hero/baobab/osis/indexer.v @@ -15,7 +15,7 @@ pub struct Indexer { @[params] pub struct IndexerConfig { db_path string - reset bool + reset bool } pub fn new_indexer(config IndexerConfig) !Indexer { @@ -54,7 +54,7 @@ pub fn (mut backend Indexer) set(obj RootObject) ! { for i in 0 .. indices.len { sql_stmts << '${indices[i]}=${values[i]}' } - backend.db.exec("update ${table_name} set ${sql_stmts.join(' ')} where id=${obj.id}")! + backend.db.exec('update ${table_name} set ${sql_stmts.join(' ')} where id=${obj.id}')! } // save the session to redis & mem @@ -124,7 +124,7 @@ pub fn (mut backend Indexer) filter(filter RootObject, params FilterParams) ![]s if field.typ == .text { matchers << "${field.name} == '${field.value}'" } else if field.typ == .number { - matchers << "${field.name} == ${field.value}" + matchers << '${field.name} == ${field.value}' } } matchers_str := if params.matches_all { @@ -147,7 +147,7 @@ fn (mut backend Indexer) create_root_object_table(object RootObject) ! { } // deletes an indexer table belonging to a root object -fn (mut backend Indexer) delete_table(object RootObject)! { +fn (mut backend Indexer) delete_table(object RootObject) ! { table_name := get_table_name(object) delete_query := 'delete table ${table_name}' backend.db.exec(delete_query)! @@ -175,4 +175,4 @@ fn get_table_name(object RootObject) string { mut table_name := texttools.name_fix(object.name) table_name = table_name.replace('.', '_') return table_name -} \ No newline at end of file +} diff --git a/lib/hero/baobab/osis/indexer_generic.v b/lib/hero/baobab/osis/indexer_generic.v index 7a1e990b..3afd3538 100644 --- a/lib/hero/baobab/osis/indexer_generic.v +++ b/lib/hero/baobab/osis/indexer_generic.v @@ -45,7 +45,7 @@ fn (mut indexer Indexer) generic_create_root_object_table[T]() ! { } // deletes an indexer table belonging to a base object -fn (mut indexer Indexer) generic_delete_table[T]()! { +fn (mut indexer Indexer) generic_delete_table[T]() ! { table_name := generic_get_table_name[T]() delete_query := 'delete table ${table_name}' indexer.db.exec(delete_query)! @@ -65,4 +65,4 @@ fn generic_get_table_name[T]() string { table_name = texttools.name_fix(table_name) table_name = table_name.replace('.', '_') return table_name -} \ No newline at end of file +} diff --git a/lib/hero/baobab/osis/indexer_generic_test.v b/lib/hero/baobab/osis/indexer_generic_test.v index 9e816fff..334ccdd3 100644 --- a/lib/hero/baobab/osis/indexer_generic_test.v +++ b/lib/hero/baobab/osis/indexer_generic_test.v @@ -9,14 +9,14 @@ const db_dir = '${os.dir(@FILE)}/testdata/db' fn testsuite_begin() { pathlib.get_dir( - path: db_dir + path: db_dir empty: true )! } fn testsuite_end() { mut dir := pathlib.get_dir( - path: db_dir + path: db_dir delete: true )! } @@ -25,16 +25,16 @@ fn db_path(db_name string) string { return '${db_dir}/${db_name}.db' } -const pgconfig := pg.Config { - dbname: 'default' - user: 'admin' +const pgconfig = pg.Config{ + dbname: 'default' + user: 'admin' password: 'test' } fn test_new_indexer() ! { - sqlite_db := sqlite.connect(db_path(@FN))! + sqlite_db := sqlite.connect(db_path(@FN))! sqlite_indexer := new_indexer(sqlite_db: sqlite_db)! - + postgres_db := pg.connect(pgconfig)! postgres_indexer := new_indexer(postgres_db: postgres_db)! } @@ -44,8 +44,8 @@ fn test_reset() ! { } pub struct TestStruct { - text string @[index] - number int @[index] + text string @[index] + number int @[index] } fn test_indexer_new() ! { @@ -73,7 +73,7 @@ fn test_indexer_new() ! { mut postgres_indexer := new_indexer(postgres_db: postgres_db)! postgres_indexer.generic_new(TestStruct{ - text: 'test_text' + text: 'test_text' number: 41 })! @@ -81,7 +81,7 @@ fn test_indexer_new() ! { assert list.len == 1 postgres_indexer.generic_new(TestStruct{ - text: 'test_text2' + text: 'test_text2' number: 42 })! @@ -90,43 +90,35 @@ fn test_indexer_new() ! { } pub struct TestStructFilter { - text string + text string number int } fn test_indexer_filter() ! { - sqlite_db := sqlite.connect(db_path(@FN))! + sqlite_db := sqlite.connect(db_path(@FN))! mut sqlite_indexer := new_indexer(sqlite_db: sqlite_db)! - + sqlite_indexer.generic_new(TestStruct{ - text: 'test_text' + text: 'test_text' number: 41 })! - mut list := sqlite_indexer.generic_filter[TestStruct, TestStructFilter]( - TestStructFilter { - text: 'test_tex' - } - )! + mut list := sqlite_indexer.generic_filter[TestStruct, TestStructFilter](TestStructFilter{ + text: 'test_tex' + })! assert list.len == 0 - list = sqlite_indexer.generic_filter[TestStruct, TestStructFilter]( - TestStructFilter { - text: 'test_text' - } - )! + list = sqlite_indexer.generic_filter[TestStruct, TestStructFilter](TestStructFilter{ + text: 'test_text' + })! - list = sqlite_indexer.generic_filter[TestStruct, TestStructFilter]( - TestStructFilter { - number: 40 - } - )! + list = sqlite_indexer.generic_filter[TestStruct, TestStructFilter](TestStructFilter{ + number: 40 + })! assert list.len == 0 - list = sqlite_indexer.generic_filter[TestStruct, TestStructFilter]( - TestStructFilter { - number: 41 - } - )! + list = sqlite_indexer.generic_filter[TestStruct, TestStructFilter](TestStructFilter{ + number: 41 + })! assert list.len == 1 -} \ No newline at end of file +} diff --git a/lib/hero/baobab/osis/indexer_identifier.v b/lib/hero/baobab/osis/indexer_identifier.v index b1c22b25..e3f14e31 100644 --- a/lib/hero/baobab/osis/indexer_identifier.v +++ b/lib/hero/baobab/osis/indexer_identifier.v @@ -3,21 +3,23 @@ module osis import db.pg struct BaseObject { - id int @[primary; sql: serial] - object string + id int @[primary; sql: serial] + object string } pub fn (mut i Indexer) init() ! { sql i.db { - create table BaseObject + create table BaseObject }! } pub fn (mut i Indexer) new_id(object string) !u32 { - obj := BaseObject{object:object} + obj := BaseObject{ + object: object + } id := sql i.db { insert obj into BaseObject - } or {return err} + } or { return err } return u32(id) } @@ -26,4 +28,4 @@ pub fn (i Indexer) get_id(id u32) !string { select from BaseObject where id == id }! return obj[0].object -} \ No newline at end of file +} diff --git a/lib/hero/baobab/osis/indexer_test.v b/lib/hero/baobab/osis/indexer_test.v index 05098503..e6fb072f 100644 --- a/lib/hero/baobab/osis/indexer_test.v +++ b/lib/hero/baobab/osis/indexer_test.v @@ -9,14 +9,14 @@ const db_dir = '${os.dir(@FILE)}/testdata/db' fn testsuite_begin() { pathlib.get_dir( - path: db_dir + path: db_dir empty: true )! } fn testsuite_end() { mut dir := pathlib.get_dir( - path: db_dir + path: db_dir delete: true )! } @@ -28,7 +28,7 @@ fn db_path(db_name string) string { // fn test_new_indexer() ! { // sqlite_db := sqlite.connect(db_path(@FN))! // sqlite_indexer := new_indexer(sqlite_db: sqlite_db)! - + // postgres_db := pg.connect(dbname: 'default')! // postgres_indexer := new_indexer(postgres_db: postgres_db)! // } @@ -46,7 +46,7 @@ fn db_path(db_name string) string { // sqlite_db := sqlite.connect(db_path(@FN))! // mut sqlite_indexer := new_indexer(sqlite_db: sqlite_db)! // // mut postgres_indexer := new_indexer(new_db(@FN, PostgresConfig{})!)! - + // sqlite_indexer.new(TestStruct{ // text: 'test_text' // number: 41 @@ -72,7 +72,7 @@ fn db_path(db_name string) string { // fn test_indexer_filter() ! { // sqlite_db := sqlite.connect(db_path(@FN))! // mut sqlite_indexer := new_indexer(sqlite_db: sqlite_db)! - + // sqlite_indexer.new(TestStruct{ // text: 'test_text' // number: 41 @@ -104,4 +104,4 @@ fn db_path(db_name string) string { // } // )! // assert list.len == 1 -// } \ No newline at end of file +// } diff --git a/lib/hero/baobab/osis/model.v b/lib/hero/baobab/osis/model.v index 46257519..851610aa 100644 --- a/lib/hero/baobab/osis/model.v +++ b/lib/hero/baobab/osis/model.v @@ -9,16 +9,16 @@ import freeflowuniverse.herolib.data.encoderhero pub struct OSIS { pub mut: indexer Indexer // storing indeces - storer Storer + storer Storer } @[params] pub struct OSISConfig { pub: directory string - name string - secret string - reset bool + name string + secret string + reset bool } pub fn (mut backend OSIS) reset_all() ! { diff --git a/lib/hero/baobab/osis/root_object.v b/lib/hero/baobab/osis/root_object.v index 5282888c..824579a0 100644 --- a/lib/hero/baobab/osis/root_object.v +++ b/lib/hero/baobab/osis/root_object.v @@ -2,30 +2,29 @@ module osis import x.json2 - // describes a root object pub struct RootObject { pub mut: - id string - name string // Story + id string + name string // Story fields []FieldDescription } pub struct FieldDescription { pub mut: - name string // name of field - typ FieldType - value string // value of field - is_secret bool // whether field should be encrypted upon storage - is_index bool // whether object is searchable by field - fts_enabled bool // whether full text search on field is enabled + name string // name of field + typ FieldType + value string // value of field + is_secret bool // whether field should be encrypted upon storage + is_index bool // whether object is searchable by field + fts_enabled bool // whether full text search on field is enabled } // returns the sql type name of the field pub fn (field FieldDescription) sql_type() string { return match field.typ { - .text {'TEXT'} - .number {'INTEGER'} + .text { 'TEXT' } + .number { 'INTEGER' } } } @@ -35,7 +34,7 @@ pub enum FieldType { } pub fn (obj RootObject) to_json() string { - mut obj_map := map[string]json2.Any + mut obj_map := map[string]json2.Any{} for field in obj.fields { obj_map[field.name] = field.value } @@ -43,7 +42,6 @@ pub fn (obj RootObject) to_json() string { return obj_map.str() } - // returns the lists of the indices of a root objects db table, and corresponding values pub fn (obj RootObject) sql_indices_values() ([]string, []string) { obj_encoded := obj.to_json() @@ -56,7 +54,7 @@ pub fn (obj RootObject) sql_indices_values() ([]string, []string) { for field in obj.fields { if field.name == 'id' { indices << '${field.name}' - values << "${field.value}" + values << '${field.value}' } if field.typ == .text { @@ -67,13 +65,12 @@ pub fn (obj RootObject) sql_indices_values() ([]string, []string) { } else if field.typ == .number { if field.is_index { indices << '${field.name}' - values << "${field.value}" + values << '${field.value}' } } } println('debugzoni ${indices} ${values}') return indices, values - } // return the description of a given generic @@ -89,17 +86,16 @@ pub fn root_object[T](object T) RootObject { } fields << FieldDescription{ - name: field.name - typ: typ - value: object.$(field.name).str() - is_index: field.attrs.contains('index') - is_secret: field.attrs.contains('secret') + name: field.name + typ: typ + value: object.$(field.name).str() + is_index: field.attrs.contains('index') + is_secret: field.attrs.contains('secret') fts_enabled: field.attrs.contains('fts_enabled') } } - - return RootObject { - name: typeof[T]() + return RootObject{ + name: typeof[T]() fields: fields } } @@ -129,12 +125,11 @@ pub fn root_object_from_json(json string) !RootObject { mut obj := RootObject{} for key, val in obj_map { - obj.fields << FieldDescription { - name: key + obj.fields << FieldDescription{ + name: key value: val.str() } } return obj - -} \ No newline at end of file +} diff --git a/lib/hero/baobab/osis/storer.v b/lib/hero/baobab/osis/storer.v index 73d7000e..9ae1ae86 100644 --- a/lib/hero/baobab/osis/storer.v +++ b/lib/hero/baobab/osis/storer.v @@ -6,24 +6,24 @@ import os pub struct Storer { pub: - directory string + directory string db_filesystem dbfs.DBCollection - db_sqlite sqlite.DB + db_sqlite sqlite.DB } @[params] pub struct StorerConfig { context_id u32 - secret string - directory string = '${os.home_dir()}/hero/baobab/storer' // Directory of the storer + secret string + directory string = '${os.home_dir()}/hero/baobab/storer' // Directory of the storer } pub fn new_storer(config StorerConfig) !Storer { - return Storer { - directory: config.directory + return Storer{ + directory: config.directory db_filesystem: dbfs.get( - dbpath: '${config.directory}/dbfs/${config.context_id}' - secret: config.secret + dbpath: '${config.directory}/dbfs/${config.context_id}' + secret: config.secret contextid: config.context_id )! } @@ -53,4 +53,4 @@ pub fn (mut storer Storer) delete(id u32, params StorageParams) ! { pub fn (mut storer Storer) list(ids []u32, params StorageParams) ![]RootObject { panic('implement') -} \ No newline at end of file +} diff --git a/lib/hero/baobab/osis/storer_generic.v b/lib/hero/baobab/osis/storer_generic.v index 19fb1e7c..e423327b 100644 --- a/lib/hero/baobab/osis/storer_generic.v +++ b/lib/hero/baobab/osis/storer_generic.v @@ -38,8 +38,8 @@ fn (mut storer Storer) generic_create_root_object_table[T]() ! { } // deletes an storer table belonging to a base object -fn (mut storer Storer) generic_delete_table[T]()! { +fn (mut storer Storer) generic_delete_table[T]() ! { table_name := generic_get_table_name[T]() delete_query := 'delete table ${table_name}' storer.db.exec(delete_query)! -} \ No newline at end of file +} diff --git a/lib/hero/baobab/specification/model.v b/lib/hero/baobab/specification/model.v index 70f2a479..d053040c 100644 --- a/lib/hero/baobab/specification/model.v +++ b/lib/hero/baobab/specification/model.v @@ -1,15 +1,15 @@ module specification -import freeflowuniverse.herolib.core.codemodel { Struct, Function } +import freeflowuniverse.herolib.core.codemodel { Function, Struct } pub struct ActorSpecification { pub mut: - name string @[omitempty] - description string @[omitempty] - structure Struct @[omitempty] - interfaces []ActorInterface @[omitempty] - methods []ActorMethod @[omitempty] - objects []BaseObject @[omitempty] + name string @[omitempty] + description string @[omitempty] + structure Struct @[omitempty] + interfaces []ActorInterface @[omitempty] + methods []ActorMethod @[omitempty] + objects []BaseObject @[omitempty] } pub enum ActorInterface { @@ -28,7 +28,7 @@ pub: pub struct BaseObject { pub: - structure Struct @[omitempty] - methods []Function @[omitempty] - children []Struct @[omitempty] -} \ No newline at end of file + structure Struct @[omitempty] + methods []Function @[omitempty] + children []Struct @[omitempty] +} diff --git a/lib/hero/baobab/specification/openapi.v b/lib/hero/baobab/specification/openapi.v index 71b854e0..0859caa3 100644 --- a/lib/hero/baobab/specification/openapi.v +++ b/lib/hero/baobab/specification/openapi.v @@ -1,16 +1,16 @@ module specification -import freeflowuniverse.herolib.web.openapi { OpenAPI, Info, ServerSpec, Components, Operation, PathItem, PathRef, Parameter } -import freeflowuniverse.herolib.core.codemodel { Struct, Function, Param } +import freeflowuniverse.herolib.web.openapi { Components, Info, OpenAPI, Operation, Parameter, PathItem, ServerSpec } +import freeflowuniverse.herolib.core.codemodel { Function, Param, Struct } import freeflowuniverse.herolib.data.jsonschema { SchemaRef } // Helper function: Convert OpenAPI parameter to codemodel Param fn openapi_param_to_param(param Parameter) Param { return Param{ - name: param.name, - typ: param.schema.to_code() or {panic(err)}, // Assuming the schema defines the parameter type - required: param.required, - description: param.description, + name: param.name + typ: param.schema.to_code() or { panic(err) } // Assuming the schema defines the parameter type + required: param.required + description: param.description } } @@ -22,17 +22,17 @@ fn openapi_operation_to_function(op Operation, method_name string, path string) } return Function{ - name: method_name, - params: params, + name: method_name + params: params // receiver.mutable: op.request_body != none, // POST, PUT, etc., generally imply mutable operations - description: op.description, + description: op.description } } // Helper function: Convert OpenAPI schema to codemodel Struct fn openapi_schema_to_struct(name string, schema SchemaRef) Struct { return Struct{ - name: name, + name: name // Add field mapping if schema properties are available } } @@ -42,79 +42,87 @@ pub fn from_openapi(spec OpenAPI) !ActorSpecification { mut methods := []ActorMethod{} mut objects := []BaseObject{} -// Extract methods from OpenAPI paths -for path, item in spec.paths { - if item.get.operation_id != '' { - methods << ActorMethod{ - name: item.get.operation_id, - description: item.get.summary, - func: openapi_operation_to_function(item.get, item.get.operation_id, path), + // Extract methods from OpenAPI paths + for path, item in spec.paths { + if item.get.operation_id != '' { + methods << ActorMethod{ + name: item.get.operation_id + description: item.get.summary + func: openapi_operation_to_function(item.get, item.get.operation_id, + path) + } + } + if item.post.operation_id != '' { + methods << ActorMethod{ + name: item.post.operation_id + description: item.post.summary + func: openapi_operation_to_function(item.post, item.post.operation_id, + path) + } + } + if item.put.operation_id != '' { + methods << ActorMethod{ + name: item.put.operation_id + description: item.put.summary + func: openapi_operation_to_function(item.put, item.put.operation_id, + path) + } + } + if item.delete.operation_id != '' { + methods << ActorMethod{ + name: item.delete.operation_id + description: item.delete.summary + func: openapi_operation_to_function(item.delete, item.delete.operation_id, + path) + } + } + if item.patch.operation_id != '' { + methods << ActorMethod{ + name: item.patch.operation_id + description: item.patch.summary + func: openapi_operation_to_function(item.patch, item.patch.operation_id, + path) + } + } + if item.head.operation_id != '' { + methods << ActorMethod{ + name: item.head.operation_id + description: item.head.summary + func: openapi_operation_to_function(item.head, item.head.operation_id, + path) + } + } + if item.options.operation_id != '' { + methods << ActorMethod{ + name: item.options.operation_id + description: item.options.summary + func: openapi_operation_to_function(item.options, item.options.operation_id, + path) + } + } + if item.trace.operation_id != '' { + methods << ActorMethod{ + name: item.trace.operation_id + description: item.trace.summary + func: openapi_operation_to_function(item.trace, item.trace.operation_id, + path) + } } } - if item.post.operation_id != '' { - methods << ActorMethod{ - name: item.post.operation_id, - description: item.post.summary, - func: openapi_operation_to_function(item.post, item.post.operation_id, path), - } - } - if item.put.operation_id != '' { - methods << ActorMethod{ - name: item.put.operation_id, - description: item.put.summary, - func: openapi_operation_to_function(item.put, item.put.operation_id, path), - } - } - if item.delete.operation_id != '' { - methods << ActorMethod{ - name: item.delete.operation_id, - description: item.delete.summary, - func: openapi_operation_to_function(item.delete, item.delete.operation_id, path), - } - } - if item.patch.operation_id != '' { - methods << ActorMethod{ - name: item.patch.operation_id, - description: item.patch.summary, - func: openapi_operation_to_function(item.patch, item.patch.operation_id, path), - } - } - if item.head.operation_id != '' { - methods << ActorMethod{ - name: item.head.operation_id, - description: item.head.summary, - func: openapi_operation_to_function(item.head, item.head.operation_id, path), - } - } - if item.options.operation_id != '' { - methods << ActorMethod{ - name: item.options.operation_id, - description: item.options.summary, - func: openapi_operation_to_function(item.options, item.options.operation_id, path), - } - } - if item.trace.operation_id != '' { - methods << ActorMethod{ - name: item.trace.operation_id, - description: item.trace.summary, - func: openapi_operation_to_function(item.trace, item.trace.operation_id, path), - } - } -} // Extract objects from OpenAPI components.schemas for name, schema in spec.components.schemas { objects << BaseObject{ - structure: openapi_schema_to_struct(name, schema), - methods: []Function{}, // Add related methods if applicable - children: []Struct{}, // Add children if schemas define nested structures + structure: openapi_schema_to_struct(name, schema) + methods: []Function{} // Add related methods if applicable + children: []Struct{} // Add children if schemas define nested structures } } return ActorSpecification{ - name: spec.info.title, - description: spec.info.description, - methods: methods, - objects: objects, + name: spec.info.title + description: spec.info.description + methods: methods + objects: objects } } @@ -125,47 +133,51 @@ pub fn (s ActorSpecification) to_openapi() OpenAPI { // Map ActorMethods to paths for method in s.methods { mut op := Operation{ - summary: method.description, - operation_id: method.name, + summary: method.description + operation_id: method.name } // Set parameters and other fields based on the codemodel Function for param in method.func.params { op.parameters << Parameter{ - name: param.name, - in_: 'query', // Default location; adjust based on actual function context - description: param.description, - required: param.required, - schema: jsonschema.param_to_schema(param) + name: param.name + in_: 'query' // Default location; adjust based on actual function context + description: param.description + required: param.required + schema: jsonschema.param_to_schema(param) } } // Assign operation to corresponding HTTP method if method.func.receiver.mutable { - paths['/${method.name}'] = PathItem{post: op} + paths['/${method.name}'] = PathItem{ + post: op + } } else { - paths['/${method.name}'] = PathItem{get: op} + paths['/${method.name}'] = PathItem{ + get: op + } } } return OpenAPI{ - openapi: '3.0.0', - info: Info{ - title: s.name, - summary: s.description, - description: s.description, - version: '1.0.0', - }, - servers: [ + openapi: '3.0.0' + info: Info{ + title: s.name + summary: s.description + description: s.description + version: '1.0.0' + } + servers: [ ServerSpec{ - url: 'http://localhost:8080', - description: 'Default server', + url: 'http://localhost:8080' + description: 'Default server' }, - ], - paths: paths, + ] + paths: paths components: Components{ // Assuming the `objects` in ActorSpecification can be converted to schemas // schemas: s.objects.map(it.structure.name => SchemaRef{name: it.structure.name}), - }, + } } -} \ No newline at end of file +} diff --git a/lib/hero/baobab/specification/openapi_test.v b/lib/hero/baobab/specification/openapi_test.v index dacde25b..3d28d4ad 100644 --- a/lib/hero/baobab/specification/openapi_test.v +++ b/lib/hero/baobab/specification/openapi_test.v @@ -1,46 +1,46 @@ module specification -import freeflowuniverse.herolib.web.openapi { OpenAPI, Info, ServerSpec, Components, Operation, PathItem, PathRef } -import freeflowuniverse.herolib.data.jsonschema {Schema, Reference, SchemaRef} +import freeflowuniverse.herolib.web.openapi { Components, Info, OpenAPI, Operation, PathItem, ServerSpec } +import freeflowuniverse.herolib.data.jsonschema { Reference, Schema, SchemaRef } -const openapi_spec = openapi.OpenAPI{ - openapi: '3.0.3' - info: openapi.Info{ - title: 'Pet Store API' +const openapi_spec = OpenAPI{ + openapi: '3.0.3' + info: Info{ + title: 'Pet Store API' description: 'A sample API for a pet store' - version: '1.0.0' + version: '1.0.0' } - servers: [ - openapi.ServerSpec{ - url: 'https://api.petstore.example.com/v1' + servers: [ + ServerSpec{ + url: 'https://api.petstore.example.com/v1' description: 'Production server' }, - openapi.ServerSpec{ - url: 'https://staging.petstore.example.com/v1' + ServerSpec{ + url: 'https://staging.petstore.example.com/v1' description: 'Staging server' - } + }, ] - paths: { - '/pets': openapi.PathItem{ - get: openapi.Operation{ - summary: 'List all pets' + paths: { + '/pets': PathItem{ + get: Operation{ + summary: 'List all pets' operation_id: 'listPets' - parameters: [ + parameters: [ openapi.Parameter{ - name: 'limit' - in_: 'query' + name: 'limit' + in_: 'query' description: 'Maximum number of pets to return' - required: false - schema: Schema{ - typ: 'integer' + required: false + schema: Schema{ + typ: 'integer' format: 'int32' } - } + }, ] - responses: { + responses: { '200': openapi.ResponseSpec{ description: 'A paginated list of pets' - content: { + content: { 'application/json': openapi.MediaType{ schema: Reference{ ref: '#/components/schemas/Pets' @@ -53,12 +53,12 @@ const openapi_spec = openapi.OpenAPI{ } } } - post: openapi.Operation{ - summary: 'Create a new pet' + post: Operation{ + summary: 'Create a new pet' operation_id: 'createPet' request_body: openapi.RequestBody{ required: true - content: { + content: { 'application/json': openapi.MediaType{ schema: Reference{ ref: '#/components/schemas/NewPet' @@ -66,10 +66,10 @@ const openapi_spec = openapi.OpenAPI{ } } } - responses: { + responses: { '201': openapi.ResponseSpec{ description: 'Pet created' - content: { + content: { 'application/json': openapi.MediaType{ schema: Reference{ ref: '#/components/schemas/Pet' @@ -83,26 +83,26 @@ const openapi_spec = openapi.OpenAPI{ } } } - '/pets/{petId}': openapi.PathItem{ - get: openapi.Operation{ - summary: 'Get a pet by ID' + '/pets/{petId}': PathItem{ + get: Operation{ + summary: 'Get a pet by ID' operation_id: 'getPet' - parameters: [ + parameters: [ openapi.Parameter{ - name: 'petId' - in_: 'path' + name: 'petId' + in_: 'path' description: 'ID of the pet to retrieve' - required: true - schema: Schema{ - typ: 'integer' + required: true + schema: Schema{ + typ: 'integer' format: 'int64' } - } + }, ] - responses: { + responses: { '200': openapi.ResponseSpec{ description: 'A pet' - content: { + content: { 'application/json': openapi.MediaType{ schema: Reference{ ref: '#/components/schemas/Pet' @@ -115,22 +115,22 @@ const openapi_spec = openapi.OpenAPI{ } } } - delete: openapi.Operation{ - summary: 'Delete a pet by ID' + delete: Operation{ + summary: 'Delete a pet by ID' operation_id: 'deletePet' - parameters: [ + parameters: [ openapi.Parameter{ - name: 'petId' - in_: 'path' + name: 'petId' + in_: 'path' description: 'ID of the pet to delete' - required: true - schema: Schema{ - typ: 'integer' + required: true + schema: Schema{ + typ: 'integer' format: 'int64' } - } + }, ] - responses: { + responses: { '204': openapi.ResponseSpec{ description: 'Pet deleted' } @@ -140,17 +140,17 @@ const openapi_spec = openapi.OpenAPI{ } } } - '/orders': openapi.PathItem{ - get: openapi.Operation{ - summary: 'List all orders' + '/orders': PathItem{ + get: Operation{ + summary: 'List all orders' operation_id: 'listOrders' - responses: { + responses: { '200': openapi.ResponseSpec{ description: 'A list of orders' - content: { + content: { 'application/json': openapi.MediaType{ schema: Schema{ - typ: 'array' + typ: 'array' items: SchemaRef(Reference{ ref: '#/components/schemas/Order' }) @@ -161,26 +161,26 @@ const openapi_spec = openapi.OpenAPI{ } } } - '/orders/{orderId}': openapi.PathItem{ - get: openapi.Operation{ - summary: 'Get an order by ID' + '/orders/{orderId}': PathItem{ + get: Operation{ + summary: 'Get an order by ID' operation_id: 'getOrder' - parameters: [ + parameters: [ openapi.Parameter{ - name: 'orderId' - in_: 'path' + name: 'orderId' + in_: 'path' description: 'ID of the order to retrieve' - required: true - schema: Schema{ - typ: 'integer' + required: true + schema: Schema{ + typ: 'integer' format: 'int64' } - } + }, ] - responses: { + responses: { '200': openapi.ResponseSpec{ description: 'An order' - content: { + content: { 'application/json': openapi.MediaType{ schema: Reference{ ref: '#/components/schemas/Order' @@ -193,22 +193,22 @@ const openapi_spec = openapi.OpenAPI{ } } } - delete: openapi.Operation{ - summary: 'Delete an order by ID' + delete: Operation{ + summary: 'Delete an order by ID' operation_id: 'deleteOrder' - parameters: [ + parameters: [ openapi.Parameter{ - name: 'orderId' - in_: 'path' + name: 'orderId' + in_: 'path' description: 'ID of the order to delete' - required: true - schema: Schema{ - typ: 'integer' + required: true + schema: Schema{ + typ: 'integer' format: 'int64' } - } + }, ] - responses: { + responses: { '204': openapi.ResponseSpec{ description: 'Order deleted' } @@ -218,13 +218,13 @@ const openapi_spec = openapi.OpenAPI{ } } } - '/users': openapi.PathItem{ - post: openapi.Operation{ - summary: 'Create a user' + '/users': PathItem{ + post: Operation{ + summary: 'Create a user' operation_id: 'createUser' request_body: openapi.RequestBody{ required: true - content: { + content: { 'application/json': openapi.MediaType{ schema: Reference{ ref: '#/components/schemas/NewUser' @@ -232,10 +232,10 @@ const openapi_spec = openapi.OpenAPI{ } } } - responses: { + responses: { '201': openapi.ResponseSpec{ description: 'User created' - content: { + content: { 'application/json': openapi.MediaType{ schema: Reference{ ref: '#/components/schemas/User' @@ -247,110 +247,110 @@ const openapi_spec = openapi.OpenAPI{ } } } - components: openapi.Components{ - schemas: { - 'Pet': SchemaRef(Schema{ - typ: 'object' - required: ['id', 'name'] - properties: { - 'id': SchemaRef(Schema{ - typ: 'integer' - format: 'int64' - }) - 'name': SchemaRef(Schema{ - typ: 'string' - }) - 'tag': SchemaRef(Schema{ - typ: 'string' - }) - } - }) - 'NewPet': SchemaRef(Schema{ - typ: 'object' - required: ['name'] - properties: { - 'name': SchemaRef(Schema{ - typ: 'string' - }) - 'tag': SchemaRef(Schema{ - typ: 'string' - }) - } - }) - 'Pets': SchemaRef(Schema{ - typ: 'array' - items: SchemaRef(Reference{ - ref: '#/components/schemas/Pet' + components: Components{ + schemas: { + 'Pet': SchemaRef(Schema{ + typ: 'object' + required: ['id', 'name'] + properties: { + 'id': SchemaRef(Schema{ + typ: 'integer' + format: 'int64' + }) + 'name': SchemaRef(Schema{ + typ: 'string' + }) + 'tag': SchemaRef(Schema{ + typ: 'string' + }) + } }) - }) - 'Order': SchemaRef(Schema{ - typ: 'object' - required: ['id', 'petId', 'quantity', 'shipDate'] - properties: { - 'id': SchemaRef(Schema{ - typ: 'integer' - format: 'int64' + 'NewPet': SchemaRef(Schema{ + typ: 'object' + required: ['name'] + properties: { + 'name': SchemaRef(Schema{ + typ: 'string' + }) + 'tag': SchemaRef(Schema{ + typ: 'string' + }) + } + }) + 'Pets': SchemaRef(Schema{ + typ: 'array' + items: SchemaRef(Reference{ + ref: '#/components/schemas/Pet' }) - 'petId': SchemaRef(Schema{ - typ: 'integer' - format: 'int64' - }) - 'quantity': SchemaRef(Schema{ - typ: 'integer' - format: 'int32' - }) - 'shipDate': SchemaRef(Schema{ - typ: 'string' - format: 'date-time' - }) - 'status': SchemaRef(Schema{ - typ: 'string' - enum_: ['placed', 'approved', 'delivered'] - }) - 'complete': SchemaRef(Schema{ - typ: 'boolean' - }) - } - }) - 'User': SchemaRef(Schema{ - typ: 'object' - required: ['id', 'username'] - properties: { - 'id': SchemaRef(Schema{ - typ: 'integer' - format: 'int64' - }) - 'username': SchemaRef(Schema{ - typ: 'string' - }) - 'email': SchemaRef(Schema{ - typ: 'string' - }) - 'phone': SchemaRef(Schema{ - typ: 'string' - }) - } - }) - 'NewUser': SchemaRef(Schema{ - typ: 'object' - required: ['username'] - properties: { - 'username': SchemaRef(Schema{ - typ: 'string' - }) - 'email': SchemaRef(Schema{ - typ: 'string' - }) - 'phone': SchemaRef(Schema{ - typ: 'string' - }) - } - }) + }) + 'Order': SchemaRef(Schema{ + typ: 'object' + required: ['id', 'petId', 'quantity', 'shipDate'] + properties: { + 'id': SchemaRef(Schema{ + typ: 'integer' + format: 'int64' + }) + 'petId': SchemaRef(Schema{ + typ: 'integer' + format: 'int64' + }) + 'quantity': SchemaRef(Schema{ + typ: 'integer' + format: 'int32' + }) + 'shipDate': SchemaRef(Schema{ + typ: 'string' + format: 'date-time' + }) + 'status': SchemaRef(Schema{ + typ: 'string' + enum_: ['placed', 'approved', 'delivered'] + }) + 'complete': SchemaRef(Schema{ + typ: 'boolean' + }) + } + }) + 'User': SchemaRef(Schema{ + typ: 'object' + required: ['id', 'username'] + properties: { + 'id': SchemaRef(Schema{ + typ: 'integer' + format: 'int64' + }) + 'username': SchemaRef(Schema{ + typ: 'string' + }) + 'email': SchemaRef(Schema{ + typ: 'string' + }) + 'phone': SchemaRef(Schema{ + typ: 'string' + }) + } + }) + 'NewUser': SchemaRef(Schema{ + typ: 'object' + required: ['username'] + properties: { + 'username': SchemaRef(Schema{ + typ: 'string' + }) + 'email': SchemaRef(Schema{ + typ: 'string' + }) + 'phone': SchemaRef(Schema{ + typ: 'string' + }) + } + }) + } } } -} pub fn test_from_openapi() ! { actor_spec := from_openapi(openapi_spec)! panic(actor_spec) -} \ No newline at end of file +} diff --git a/lib/hero/baobab/specification/openrpc.v b/lib/hero/baobab/specification/openrpc.v index 8b60d07c..2cf21940 100644 --- a/lib/hero/baobab/specification/openrpc.v +++ b/lib/hero/baobab/specification/openrpc.v @@ -1,9 +1,9 @@ module specification -import freeflowuniverse.herolib.rpc.openrpc {OpenRPC} -import freeflowuniverse.herolib.web.openapi {OpenAPI} +import freeflowuniverse.herolib.rpc.openrpc { OpenRPC } +import freeflowuniverse.herolib.web.openapi -pub fn from_openrpc(spec openrpc.OpenRPC) !ActorSpecification { +pub fn from_openrpc(spec OpenRPC) !ActorSpecification { // Extract Actor metadata from OpenRPC info // actor_name := openrpc_doc.info.title // actor_description := openrpc_doc.info.description @@ -38,11 +38,8 @@ pub fn from_openrpc(spec openrpc.OpenRPC) !ActorSpecification { } } - pub fn (s ActorSpecification) to_openrpc() OpenRPC { - return OpenRPC { - - } + return OpenRPC{} } // pub fn (actor Actor) generate_openrpc() OpenRPC { diff --git a/lib/hero/bootstrap/alpine.v b/lib/hero/bootstrap/alpine.v index ac66869b..5b412868 100644 --- a/lib/hero/bootstrap/alpine.v +++ b/lib/hero/bootstrap/alpine.v @@ -63,10 +63,10 @@ pub fn (mut self AlpineLoader) start(args_ AlpineLaunchArgs) ! { mut url := self.alpine_url[cpu_name] mut iso_path0 := osal.download( - reset: args.reset - url: url + reset: args.reset + url: url minsize_kb: 90000 - dest: '/tmp/alpine_std_${cpu_name}.iso' + dest: '/tmp/alpine_std_${cpu_name}.iso' )! iso_path := iso_path0.path @@ -101,7 +101,7 @@ pub fn (mut self AlpineLoader) start(args_ AlpineLaunchArgs) ! { mkfifo /tmp/alpine.in /tmp/alpine.out' )! osal.exec( - cmd: ' + cmd: ' qemu-system-x86_64 -m 1024 -cdrom "${iso_path}" -drive file="${hdd_path}",index=0,media=disk,format=qcow2 -boot c -enable-kvm -smp cores=2,maxcpus=2 -net nic -net user,hostfwd=tcp::2225-:22 -virtfs local,path="${SHARED_DIR}",mount_tag="${TAG}",security_model=mapped,id=shared -serial pipe:/tmp/alpine -qmp unix:/tmp/qmp-sock,server,nowait -vnc :0,password=on -monitor stdio ' debug: true @@ -132,7 +132,7 @@ pub fn (mut self AlpineLoader) start(args_ AlpineLaunchArgs) ! { } else if line_str.contains('localhost:~#') { console_input.writeln('setup-alpine')! } else if line_str.contains(' [localhost]') { - console_input.writeln(bootstrap.hostname)! + console_input.writeln(hostname)! } else if line_str.contains(' [eth0]') { console_input.writeln('')! } else if line_str.contains(' [dhcp]') { @@ -166,7 +166,7 @@ pub fn (mut self AlpineLoader) start(args_ AlpineLaunchArgs) ! { console_input.writeln('y')! } else if line_str.contains('Installation is complete.') { console_input.writeln('reboot')! - } else if line_str.contains('${bootstrap.hostname} login:') { + } else if line_str.contains('${hostname} login:') { console.print_debug('[+] ====================================================================') console.print_debug('[+] virtual machine configured, up and running, root password: root') console.print_debug('[+] you can ssh this machine with the local reverse port:') diff --git a/lib/installers/lang/golang/golang_actions.v b/lib/installers/lang/golang/golang_actions.v index 4e4df300..4b3505f2 100644 --- a/lib/installers/lang/golang/golang_actions.v +++ b/lib/installers/lang/golang/golang_actions.v @@ -51,7 +51,7 @@ fn install() ! { // the downloader is cool, it will check the download succeeds and also check the minimum size _ = osal.download( - url: url + url: url minsize_kb: 40000 expand_dir: expand_dir )! diff --git a/lib/installers/threefold/griddriver/griddriver_actions.v b/lib/installers/threefold/griddriver/griddriver_actions.v index a07f7b24..3ffc94e7 100644 --- a/lib/installers/threefold/griddriver/griddriver_actions.v +++ b/lib/installers/threefold/griddriver/griddriver_actions.v @@ -41,9 +41,9 @@ fn build() ! { url := 'https://github.com/threefoldtech/web3gw/tree/development_integration/griddriver' mut repo := gs.get_repo( - url: url + url: url reset: true - pull: true + pull: true )! mut path := repo.get_path()!