Skip to content

Instantly share code, notes, and snippets.

@goswinr
Forked from toburger/PackageManagement.fsx
Last active January 3, 2019 20:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goswinr/818266c1730cd116644b9a9a01fadea1 to your computer and use it in GitHub Desktop.
Save goswinr/818266c1730cd116644b9a9a01fadea1 to your computer and use it in GitHub Desktop.

https://tobivnext.wordpress.com/2014/03/26/import-nuget-packages-to-fs-interactive/

alternative:

https://gist.github.com/dsyme/9b18608b78dccf92ba33 from(https://fslang.uservoice.com/forums/245727-f-language/suggestions/5670137--package-directive-to-import-nuget-packages-in-f)

The MIT License

Copyright (c) 2014 Tobias Burger

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

ipr "Microsoft.AspNet.WebApi.Client";;
(*
Attempting to resolve dependency 'Newtonsoft.Json (≥ 4.5.11)'.
Attempting to resolve dependency 'Microsoft.Net.Http (≥ 2.2.13)'.
Attempting to resolve dependency 'Microsoft.Bcl (≥ 1.1.3)'.
Attempting to resolve dependency 'Microsoft.Bcl.Build (≥ 1.0.10)'.
'Microsoft.AspNet.WebApi.Client 5.1.1' already installed.
#r @"D:\NugetLibs\Newtonsoft.Json\lib\net45\Newtonsoft.Json.dll"
#r @"D:\NugetLibs\Microsoft.Bcl\lib\net40\System.IO.dll"
#r @"D:\NugetLibs\Microsoft.Bcl\lib\net40\System.Runtime.dll"
#r @"D:\NugetLibs\Microsoft.Bcl\lib\net40\System.Threading.Tasks.dll"
#r @"D:\NugetLibs\Microsoft.Net.Http\lib\net40\System.Net.Http.dll"
#r @"D:\NugetLibs\Microsoft.Net.Http\lib\net45\System.Net.Http.Extensions.dll"
#r @"D:\NugetLibs\Microsoft.Net.Http\lib\net45\System.Net.Http.Primitives.dll"
#r @"D:\NugetLibs\Microsoft.Net.Http\lib\net40\System.Net.Http.WebRequest.dll"
#r @"D:\NugetLibs\Microsoft.AspNet.WebApi.Client\lib\net45\System.Net.Http.Formatting.dll"
val it : unit = ()
*)
#I __SOURCE_DIRECTORY__
#r "libs/NuGet.Core.dll"
#r "System.Xml.Linq"
open NuGet
open System
open System.IO
module NuGet =
let useSideBySidePaths = false
let packageSourceUrl = "https://go.microsoft.com/fwlink/?LinkID=206669"
// offline source
//let packageSourceUrl = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Cache")
let packageSource = PackageSource(packageSourceUrl)
let repositoryFactory = PackageRepositoryFactory()
let repository = repositoryFactory.CreateRepository packageSource.Source
let targetFramework =
let version = NuGet.VersionUtility.DefaultTargetFramework
if version.Version = Version("4.0.0.0") && Type.GetType("System.Reflection.ReflectionContext", false) <> null then
System.Runtime.Versioning.FrameworkName(version.Identifier, Version("4.5"), version.Profile)
else version
let mgr (packagesPath: string) =
PackageManager(repository,
DefaultPackagePathResolver(packagesPath, useSideBySidePaths = useSideBySidePaths),
PhysicalFileSystem(packagesPath),
Logger = { new ILogger with
member self.Log(level, message, ps) = System.Console.WriteLine(message, ps)
member self.ResolveFileConflict(message) =
printfn "File conflict: %s" message
FileConflictResolution.Ignore })
let enumPackages path =
Directory.EnumerateDirectories(path)
|> Seq.map (fun path -> Path.GetFileName path)
|> Seq.filter (fun packageId -> packageId <> "packages")
let rec findPackageAssemblies packagesPath packageId =
seq {
let repo = LocalPackageRepository(packagesPath)
let package = repo.FindPackage(packageId)
let getAssemblyReferences (package: IPackage) =
query {
for ref in package.AssemblyReferences do
where (VersionUtility.IsCompatible(targetFramework, ref.SupportedFrameworks)) // check framework version
// where (query { for fw in ref.SupportedFrameworks do
// where (VersionUtility.DefaultTargetFramework.Identifier = fw.Identifier)
// count } <> 0)
where (ref.Name <> "_._") // some refs have such a name e.g. ExcelTypeProvider
groupBy (ref.Name) into g
select (package, query {
for ref in g do
where (ref.TargetFramework <> null)
sortByDescending ref.TargetFramework.Version
select (Some ref)
headOrDefault
})
} |> Seq.choose (fun (p, r) -> match r with Some r -> Some (p, r) | None -> None)
yield!
package.DependencySets
|> Seq.collect (fun ds -> ds.Dependencies)
|> Seq.collect (fun p -> findPackageAssemblies packagesPath p.Id)
yield!
match getAssemblyReferences package with
| refs when refs.IsEmpty() -> package.AssemblyReferences |> Seq.map (fun ref -> package, ref)
| refs -> refs
}
|> Seq.distinctBy snd
let packageFolderName (package: IPackage) =
if useSideBySidePaths then
sprintf "%s.%O" package.Id package.Version
else package.Id
open NuGet
let installPackage packagesPath (packageId: string) =
let mgr = NuGet.mgr packagesPath
try
mgr.InstallPackage(packageId, null, false, false)
with e ->
printfn "Error installing package %s: %s" packageId e.Message
let updatePackage packagesPath (packageId: string) =
let mgr = NuGet.mgr packagesPath
try
mgr.UpdatePackage(packageId, true, false)
with e ->
printfn "Error updating package %s: %s" packageId e.Message
let updatePackages packagesPath =
let mgr = NuGet.mgr packagesPath
enumPackages packagesPath
|> Seq.iter (updatePackage packagesPath)
let uninstallPackage packagesPath (packageId: string) =
let mgr = NuGet.mgr packagesPath
try
mgr.UninstallPackage(packageId)
with e ->
printfn " Error uninstalling package %s: %s" packageId e.Message
#r "System.Windows.Forms"
let copyPackageReferences packagesPath packageId =
let rs =
NuGet.findPackageAssemblies packagesPath packageId
|> Seq.map (fun (package, file) ->
sprintf "#r @\"%s\"" (Path.Combine(packagesPath, Path.Combine(packageFolderName package, file.Path))))
|> String.concat "\n"
System.Windows.Forms.Clipboard.SetData("Text", rs)
printfn "%s" rs
let installPackageAndCopyReferences packagesPath packageId =
installPackage packagesPath packageId
copyPackageReferences packagesPath packageId
let nugetLibDir =
let fallbackNugetLibDir = "D:\NugetLibs"
match System.Environment.GetEnvironmentVariable("NugetLibDir") with
| null -> fallbackNugetLibDir
| dir -> dir
let ipr packageId =
installPackageAndCopyReferences nugetLibDir packageId
//==========================================
// Working fully self-contained getting-started example for Suave Web Server scripting
//
// Note you don't need to have _anything_ installed before starting with this script. Nothing
// but F# Interactive and this script.
//
// This script fetches the Paket.exe component which is referenced later in the script.
// Initially the #r "paket.exe" reference is shown as unresolved. Once it has been
// downloaded by the user (by executing the first part of the script) the reference
// shows as resolved and can be used.
//
// Paket is then used to fetch a set of F# packages, which are then used later inn the script.
//
//------------------------------------------
// Step 0. Boilerplate to get the paket.exe tool
open System
open System.IO
Environment.CurrentDirectory <- __SOURCE_DIRECTORY__
if not (File.Exists "paket.exe") then
let url = "https://github.com/fsprojects/Paket/releases/download/0.26.3/paket.exe"
use wc = new Net.WebClient() in let tmp = Path.GetTempFileName() in wc.DownloadFile(url, tmp); File.Move(tmp,Path.GetFileName url)
// Step 1. Resolve and install the packages
#r "paket.exe"
Paket.Dependencies.Install """
source https://nuget.org/api/v2
nuget Suave 0.16.0
nuget FSharp.Data
nuget FSharp.Charting
""";;
// Step 2. Use the packages
#r "packages/Suave/lib/Suave.dll"
#r "packages/FSharp.Data/lib/net40/FSharp.Data.dll"
#r "packages/FSharp.Charting/lib/net40/FSharp.Charting.dll"
let ctxt = FSharp.Data.WorldBankData.GetDataContext()
let data = ctxt.Countries.Algeria.Indicators.``GDP (current US$)``
open Suave // always open suave
open Suave.Http.Successful // for OK-result
open Suave.Web // for config
web_server default_config (OK (sprintf "Hello World! In 2010 Algeria earned %f " data.[2010]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment