# Example, just for fun

# Just tell anybody or the "world" hello
def "nur hello" [
    name: string = "world"  # The name to say hello to
] {
    print $"hello ($name)"
}

# Actual useful tasks

# Run cargo
def --wrapped "nur cargo" [...args: string] {
    cargo ...$args
}

# Run cargo build
def --wrapped "nur build" [...args: string] {
    cargo "build" ...$args
}

# Run cargo run
def --wrapped "nur run" [...args: string] {
    cargo "run" ...$args
}

# Run tests
def "nur test" [
    --coverage
] {
    if $coverage {
        cargo tarpaulin
    } else {
        cargo test
    }
}

# Run linter (clippy)
def --wrapped "nur lint" [
    ...args
] {
    cargo clippy ...$args
}

# Update version in Cargo.toml
def "nur version" [
    version: string
] {
    let parsed_version = $version | parse --regex '^(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<patch>[0-9]+)(-rc(?P<rc>[0-9]+))?$'
    if ($parsed_version | is-empty) {
        error make { msg: "No valid version string provided" }
    }
    cargo set-version $version
}

# Publish to crates.io
def "nur publish" [] {
    cargo publish
}

# Update version and release to crates.io
def "nur release" [
    version: string
] {
    print $"Updating to version ($version)"
    nur version $version

    git add Cargo.toml Cargo.lock
    git commit -m $"release: 🔖 v($version)"
    git tag $"v($version)"

    print "Publishing to crates.io"
    nur publish
}

# Update nu dependencies to version
def "nur upgrade-nu" [
    version: string
] {
    open Cargo.toml | get dependencies | transpose key value | each {
        |it| if ($it.key starts-with "nu-") {
            try {
                cargo add $"($it.key)@($version)" (if $it.value.optional {"--optional"})
            } catch {
                cargo add $"($it.key)@($version)"
            }
        }
    }
}
