Skip to content

Commit

Permalink
feat: deduplicate commands and remove prune command + throw nushell e…
Browse files Browse the repository at this point in the history
…rrors when erroring instead of logging
  • Loading branch information
tulilirockz committed Aug 12, 2024
1 parent 4eca2db commit 25401c4
Show file tree
Hide file tree
Showing 18 changed files with 306 additions and 252 deletions.
2 changes: 2 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
packages = with pkgs; [
nushell
gitFull
scdoc
scd2html
];
};
});
Expand Down
9 changes: 6 additions & 3 deletions src/lib/compose.nu
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ export def --env "main compose up" [
continue
}
} catch {
logger error $"[($machine.name)] Failure checking if machine has already been initialized"
error make -u {
msg: "Failed checking if machine already exists or not in storage"
help: $"Make sure to have access to the ($storage_root) folder"
}
continue
}

Expand Down Expand Up @@ -80,13 +83,13 @@ export def --env "main compose up" [
continue
}
} catch {
logger error $"[($machine.name)] Failure checking if machine configuration is applied"
logger warning $"[($machine.name)] Failure checking if machine configuration is applied"
continue
}
logger info $"[($machine.name)] Writing inline configuration"
let return = ($machine.inline_config | save -f $machine_config_path | complete)
if ($return.exit_code != 0) {
logger error $"[($machine.name)] Failure writing inline configuration\n($return.stderr)"
logger warning $"[($machine.name)] Failure writing inline configuration\n($return.stderr)"
continue
}
}
Expand Down
55 changes: 34 additions & 21 deletions src/lib/config.nu
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,20 @@ export def "main config apply" [
}
}
} catch {
logger error "Failure checking if machine exists due to permission errors"
error make -u {
msg: "Failed checking if machine already exists or not in storage"
help: $"Make sure to have access to the ($config_root) folder"
}
return
}

try {
mkdir ($config_root | path dirname)
} catch {
logger error "Failure creating configuration path due to permission errors."
error make -u {
msg: "Failed creating configuration root folder"
help: $"Make sure to have access to the ($config_root) parent folder"
}
return
}

Expand All @@ -51,17 +57,23 @@ export def "main config apply" [
}

if ($target_config_path | path exists) and (not $force) {
logger error $"Not overriding existing configuration in ($target_config_path)"
error make -u {
msg: "The configuration file already exists"
help: $"If this was intentional, rerun with the --force argument"
}
return
}

try {
cp -f $configuration $target_config_path
} catch {
logger error "Failure when applying configuration to machine"
error make -u {
msg: "Failed applying configuration to machine"
help: $"Make sure to have access to the ($config_root) folder"
}
return
}
logger success $"[($machine)] Applied configuration to machine"
logger success $"Applied configuration to machine ($machine)"
}
}
# Modify machine configuration
Expand All @@ -84,7 +96,10 @@ export def --env "main config edit" [
}
run-external $editor $target_config_path
} catch {
logger error $"Failure when editing configuration file, check if configuration exists in ($target_config_path)"
error make -u {
msg: "Failed opening configuration file for editing, make sure it exists"
help: $"Also make sure to have access to the ($config_root) folder"
}
return
}

Expand All @@ -100,7 +115,7 @@ export def "main config remove" [
let target_config_path = (get_config_path $config_root $machine)

if not ( $target_config_path | path exists) {
logger error $"[($machine)] Could not find configuration file for machine"
logger warning $"[($machine)] Could not find configuration file for machine"
continue
}

Expand All @@ -117,28 +132,24 @@ export def "main config remove" [
try {
rm -rvf $target_config_path
} catch {
logger error $"Failure when deleting configuration ($target_config_path)"
continue
logger warning $"Failed deleting configuration file for machine ($config_root)"
return
}
}
}
# List all existing configurations
export def "main config list" [
--config-root: path = $MACHINE_CONFIG_PATH # Path where machine configurations are stored
prefix: string = "" # Prefix for machines that will be shown
] {
try {
mkdir ($config_root | path dirname)
ls -l $config_root | where {|e| ($e.type == "file") and ($e.name | str ends-with $".($CONFIG_EXTENSION)")}
} catch {
logger error "Failure creating configuration path due to permission errors."
error make -u {
msg: $"Failed listing configuration files"
help: $"Make sure to have access to the ($config_root) folder"
}
return
}

try {
ls -l $config_root | where {|e| ($e.type == "file") and ($e.name | str ends-with $".($CONFIG_EXTENSION)") and ($e.name | str starts-with $prefix)}
} catch {
logger error $"Failed listing configurations due to permission errors"
}
}
# Show configuration for a machine
export def "main config show" [
Expand All @@ -149,8 +160,6 @@ export def "main config show" [
for machine in $machines {
let target_config_path = (get_config_path $config_root $machine)

try { mkdir ($target_config_path | path dirname) }

logger info $"[($machine)] Configuration in ($target_config_path)"
try {
if $machinectl {
Expand All @@ -159,7 +168,11 @@ export def "main config show" [
}
print (open $target_config_path | lines | str trim)
} catch {
logger error "Failure reading configuration due to permission errors."
error make -u {
msg: $"Failed reading configuration file"
help: $"Make sure to have access to the ($config_root) folder"
}
return
}
}
}
34 changes: 19 additions & 15 deletions src/lib/enter.nu
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use start.nu ["main stop"]
export def --env "main enter" [
--storage-root: path = $MACHINE_STORAGE_PATH # Path where machines are stored
--no-set-xdg # Set XDG variables by default
--extra-bind: string # Extra paths for binding to the container (comma separated list of paths)
--ro-binds # Set the binds to be read-only
--ro-overlays # Set the overlays to be read-only
--extra-bind: string # Extra paths for binding to the container (comma separated list of paths)
--extra-overlay: string # Extra overlay paths for the container (comma separated list of paths)
--extra-env: string # Extra environment variables to pass to the container (comma separated list)
--machinectl (-m) = false # Use machinectl for operations instead of machinectl
--boot # Force booting for machine when not using machinectl
Expand All @@ -22,7 +25,8 @@ export def --env "main enter" [
--hostname: string # Hostname that the machine will get
--type: string = "tar" # Type of the machine (change this if running into checking errors) can be one of "raw" | "image" or "tar" | "directory"
--runner: string = "nspawn" # Runner of the machine: nspawn or vmspawn
--kill = true # Kill machine if it is already running
--no-kill # Do not kill machine preemptively before running launcher command
--yes # Do not print any confirmation prompts
machine: string # Name of the target to be logged into (either a directory, machine name, or image name)
...args: string
] {
Expand All @@ -34,26 +38,25 @@ export def --env "main enter" [
# sudo does not work properly if you dont set this in the nspawn runner
let hostname = (if $hostname != null { $hostname } else { $"(run-external hostname | complete | get stdout | str trim).($machine)" })

if not (machine_exists $machine --storage-root=($storage_root) -t "tar") {
let yesno = (input $"(ansi blue_bold)[($NAME)] Machine does not seem to be initialized, do you want to initialize a default ($DEFAULT_MACHINE) ($DEFAULT_RELEASE) machine? [Y/n]: (ansi reset)")
if not (machine_exists $machine --machinectl=true --storage-root=($storage_root) -t "tar") {
let yesno = if $yes { "Y"} else {(input $"(ansi blue_bold)[($NAME)] Machine does not seem to be initialized, do you want to initialize a default ($DEFAULT_MACHINE) ($DEFAULT_RELEASE) machine? [Y/n]: (ansi reset)")}

match $yesno {
Y|Yes|yes|y => { }
_ => { return }
}

(main
init
pull
--override=true
--override-config=true
--machinectl=true
--machinectl=($machinectl)
--name=($machine)
$DEFAULT_MACHINE
$DEFAULT_RELEASE)
return
}

if $kill {
if not $no_kill {
NUSPAWN_LOG=0 main stop --machinectl=($machinectl) $machine
}

Expand All @@ -79,25 +82,23 @@ export def --env "main enter" [
"--set-credential=firstboot.locale:C.UTF-8"
"--set-credential=passwd.hashed-password.root:"
$"--set-credential=passwd.hashed-password.($user):"
$"--machine=($machine)"
$"--hostname=($hostname)"
$"--private-users=(if $no_user_bind { "no" } else { "pick" })"
$"--private-users-ownership=auto"
"--keep-unit"
"--resolv-conf=replace-stub"
(if $boot { "--boot" } else { $"--chdir=($env.PWD? | default "/home")" } )
(if not $no_user_bind { $"--bind-user=($user)" } else { "--private-users=no" })
...($args)
]

# These only run when explicit values are set due to the "machine" type (the default thing, without explicit values) interpreting paths in /var/lib/machines.
# If someone is setting the type to these explicit ones, they want the path parsing instead of --machine parsing.
if ($type == "directory") {

$final_args = ($final_args | append [$"--directory=($machine)"])
} else if ($type == "image") {

$final_args = ($final_args | append [$"--image=($machine)"])
} else if ($type == "tar" or $type == "raw") {

$final_args = ($final_args | append [$"--machine=($machine)"])
}

if ($run_user) {
Expand Down Expand Up @@ -132,12 +133,15 @@ export def --env "main enter" [
}

if ($extra_bind != "" and $extra_bind != null) {
$final_args = ($final_args | append ($extra_bind | split row "," | each {|e| $"--bind=($e)"}))
$final_args = ($final_args | append ($extra_bind | split row "," | each {|e| $"--bind(if $ro_binds {"-ro"} else {""})=($e)"}))
}
if ($extra_env != "" and $extra_env != null) {
$final_args = ($final_args | append ($extra_env | split row "," | each {|e| $"--setenv=($e)"}))
}
if ($extra_overlay != "" and $extra_overlay != null) {
$final_args = ($final_args | append ($extra_overlay | split row "," | each {|e| $"--overlay(if $ro_overlays {"-ro"} else {""})=($e)"}))
}

logger debug $"($final_args)"
privileged_run ...($final_args)
privileged_run ...($final_args) ...($args)
}
16 changes: 16 additions & 0 deletions src/lib/export.nu
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Export programs from a machine by writing scripts and desktop files for exported apps
export def "main export" [] {}

export def "main export bin" [
--extra-flags: string # Flags for the exported binary
machine: string
] {
let script = "
#!/bin/sh
nuspawn enter ($machine) --
"

}
export def "main export app" [] {}
64 changes: 0 additions & 64 deletions src/lib/init.nu

This file was deleted.

19 changes: 12 additions & 7 deletions src/lib/list.nu
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,29 @@ export def "main remote list" [
| uniq
| each { |e| $e | str trim }
} catch {
logger error $"Failed fetching current image information from ($NSPAWNHUB_LIST)"
error make -u {
msg: $"Failed fetching the latest image list from ($nspawnhub_url)"
help: "If this keeps happening when you have a network connection there might be an error with this program itself, make a bug report"
}
return
}
}
# List local storage machines
export def "main list" [
--storage-root: path = $MACHINE_STORAGE_PATH # Path where machines are stored
--machinectl (-m) = true # Use machinectl for operations
] -> table? {
try {
let images = (
if $machinectl { machinectl --output=json list-images | from json }
else { ls -l $storage_root | select name readonly type created })
else {
ls -l $storage_root | select name readonly type created })

if ($images | length) == 0 {
logger error "No images found."
error make -u {
msg: $"Could not find any images"
help: $"You can fetch new images with the \"pull\" or \"oci pull\" commands"
}
return
}
$images
} catch {
logger error "Failure listing machines due to permission issues"
}
}
1 change: 1 addition & 0 deletions src/lib/logger.nu
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export def "logger info" [...data: string] {
export def "logger success" [...data: string] {
logger raw (ansi green_bold) ...$data
}
# Prefer "error make" instead of this due to the possibility of using "try { }" blocks in the code!
export def "logger error" [...data: string] {
logger raw (ansi red_bold) ...$data
}
Expand Down
Loading

0 comments on commit 25401c4

Please sign in to comment.