Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

nushell/modules/work_scope.nu

Raw
const GENERATED_FILE = "90-work-scope.nu"

use lib.nu save-if-changed

def quote [value: string] {
    $value | to nuon
}

def validate-command-name [name: string] {
    if not ($name =~ '^[A-Za-z0-9_.+-]+$') {
        print -e $"work_scope refuses invalid command name: ($name)"
        exit 1
    }
}

def existing-definitions [name: string] {
    let prefix = $"($name) "
    let commands = (
        scope commands
        | where {|cmd| $cmd.name == $name or ($cmd.name | str starts-with $prefix)}
        | get name
    )
    let aliases = (
        scope aliases
        | where {|alias| $alias.name == $name}
        | get name
    )

    {commands: $commands, aliases: $aliases}
}

def assert-unwrapped [name: string] {
    validate-command-name $name
    let existing = (existing-definitions $name)

    if (($existing.commands | length) > 0) or (($existing.aliases | length) > 0) {
        print -e $"work_scope refuses to wrap ($name); existing Nu definitions: commands=($existing.commands | to nuon), aliases=($existing.aliases | to nuon)"
        exit 1
    }
}

def wrapper-source [name: string, slice: string] {
    let quoted_name = (quote $name)
    let quoted_slice = (quote $slice)

    [
        "# generated by work_scope.nu; edit work_scope.nuon instead"
        ""
        "@complete external"
        $"def --wrapped ($quoted_name) [...args] {"
        $"    let command = ($quoted_name)"
        $"    let slice = ($quoted_slice)"
        ""
        '    if $nu.os-info.family == "unix" and (which systemd-run | is-not-empty) {'
        '        ^systemd-run --user --scope --same-dir --collect --quiet $"--slice=($slice)" $command ...$args'
        "    } else {"
        "        run-external $command ...$args"
        "    }"
        "}"
    ] | str join (char nl)
}

export def generate [] {
    let config_path = ($nu.default-config-dir | path join modules work_scope.nuon)
    if not ($config_path | path exists) {
        print -e $"work_scope config missing: ($config_path)"
        exit 1
    }

    let config = (open $config_path)
    let commands = ($config.commands? | default [])
    let slice = ($config.slice? | default "work.slice")
    let autoload_dir = ($nu.user-autoload-dirs | last)
    let generated_path = ($autoload_dir | path join $GENERATED_FILE)

    for command in $commands {
        assert-unwrapped $command
    }

    mkdir $autoload_dir

    let body = (
        $commands
        | each {|command| wrapper-source $command $slice}
        | str join (char nl)
    )

    save-if-changed $generated_path $body
}