Two Wrongs

Referencing Nuget Packages in F# Interactive

Referencing Nuget Packages in F# Interactive

With .NET Core, the platform has moved away from using a central, well-known location where external libraries and the like are stored 11 In Microsoft lingo, a Global Assembly Cache, or gac.. This means even if we install a library with nuget, we have to type in the full path to its assembly when we reference it e.g. in F# Interactive (the F# repl).

At some point, I got tired of figuring this full path out manually. I created a little helper script called nufsi, which is used like this:

$ nufsi FSharpPlus
To load this package into F# Interactive, paste this:

#r "/home/mr/.nuget/packages/fsharpplus/1.0.0/lib/netstandard2.0/FSharpPlus.dll" ;;

If the package is not installed, it asks me if it should be installed, then prints the reference directive. Very simple, yet incredibly helpful. Here’s the entire script file, in case anyone else finds it useful:

#!/bin/sh

# lowercase package name (nuget is case insensitive, but stores
# using lowercase on disk)
package=$(echo "$1" | tr '[:upper:]' '[:lower:]')


package_dll_paths() {
    find ~/.nuget -path "*${package}*dll"
}

# fsharpi executable comes from Mono, meaning netcoreapp
# is not an option
package_best_framework() {
    grep -E "net[0-9][0-9]|netstandard[0-9].[0-9]" | sort -k 9 -t /
}

package_best_version() {
    sort -V -s -k 7 -t / | tail -n 1
}

package_fsharpi_reference() {
    sed -E 's/^(.*)$/#r "\1" ;;/'
}

package_show_reference() {
    echo "To load this package into F# Interactive, paste this:"
    echo ""
    package_dll_paths \
        | package_best_framework | package_best_version \
        | package_fsharpi_reference
}

package_nuget_install() {
    nuget install "$package"
    echo ""
    echo "Install complete."
}

package_verify_installed() {
    if [ -z "$(package_dll_paths)" ]; then
        echo "Package not installed. Install it now? [y/N]"
        read -r answer
        if [ "$answer" != y ]; then
            return 1
        else
            package_nuget_install
        fi
    fi
}

if package_verify_installed; then
    package_show_reference
fi