use std

let nurcmd = "./../target/release/nur"

# Tests

def "nur test-env" [] {
    std assert (($env.PWD | path join ".nur" "scripts") in $env.NU_LIB_DIRS)
}

def "nur test-config" [] {
    std assert ($env.config | is-not-empty)
}

def "nur test-nu" [] {
    std assert ($nu.config-path == ($env.PWD | path join ".nur" "config.nu"))
    std assert ($nu.env-path == ($env.PWD | path join ".nur" "env.nu"))
    if (is-windows) {
        std assert (($nu.current-exe | path basename) == "nur.exe")
    } else {
        std assert (($nu.current-exe | path basename) == "nur")
    }
}

def "nur test-nur" [] {
    std assert ($nur.task-name == "test-nur")
    std assert ($nur.run-path == $env.PWD)
    std assert ($nur.project-path == $env.PWD)
    std assert ($nur.default-lib-dir == ($env.PWD | path join ".nur" "scripts"))
}

def "nur exec-stdin" [] {
    lines | each { |it| print $"BEFORE ($it) AFTER" }
}
def "nur test-stdin" [] {
    std assert ("inner" | run-nur --stdin exec-stdin | str contains "BEFORE inner AFTER")
}

def "nur should-fail" [] {
    if (is-windows) {
        cmd /c "exit 1"
    } else {
        ^false
    }
}
def "nur test-failed-execution" [] {
    try {
        run-nur should-fail
        error make {"msg": "Did not fail, this is an error"}
    } catch {
        # all ok
    }
}

# Utils and other commands

def is-windows [] {
    $nu.os-info.name == "windows"
}

def --wrapped run-nur [
    ...args
] {
    ^$nurcmd --quiet ...$args
}

def "nur prepare" [] {
    cargo build --release
}

def "nur run-all" [] {
    let tests = (scope commands | filter { |it| $it.name starts-with "nur test-" } | each { |it| $it.name | split row " " })

    $tests | each {
        |it|
        $it | str join " " | print
        run-nur $it.1
    }

    null
}
