Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2148: Add dotnet nuget push command and arguments #2229

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/app/Fake.DotNet.Cli/DotNet.fs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module DotNet =
open Fake.Core
open Fake.IO
open Fake.IO.FileSystemOperators
open Fake.DotNet.NuGet
open System
open System.IO
open System.Security.Cryptography
Expand Down Expand Up @@ -1435,3 +1436,46 @@ module DotNet =
execWithBinLog project param.Common "test" args param.MSBuildParams
__.MarkSuccess()

let internal buildNugetPushArgs (param : NuGet.NuGetPushParams) =
[
param.DisableBuffering |> argOption "disable-buffering"
param.ApiKey |> Option.toList |> argList2 "api-key"
param.NoSymbols |> argOption "no-symbols"
param.NoServiceEndpoint |> argOption "no-service-endpoint"
param.Source |> Option.toList |> argList2 "source"
param.SymbolApiKey |> Option.toList |> argList2 "symbol-api-key"
param.SymbolSource |> Option.toList |> argList2 "symbol-source"
param.Timeout |> Option.map (fun t -> t.TotalSeconds |> int |> string) |> Option.toList |> argList2 "timeout"
]
|> List.concat
|> List.filter (not << String.IsNullOrEmpty)

type NuGetPushOptions =
{ Common: Options
PushParams: NuGet.NuGetPushParams }
static member Create() =
{ Common = Options.Create()
PushParams = NuGet.NuGetPushParams.Create() }
member this.WithCommon (common : Options) =
{ this with Common = common }
member this.WithPushParams (options : NuGet.NuGetPushParams) =
{ this with PushParams = options }

/// Execute dotnet nuget push command
/// ## Parameters
///
/// - 'setParams' - set nuget push command parameters
/// - 'nupkg' - nupkg to publish
let rec nugetPush setParams nupkg =
use __ = Trace.traceTask "DotNet:nuget:push" nupkg
let param = NuGetPushOptions.Create() |> setParams
let pushParams = param.PushParams
let args = Args.toWindowsCommandLine (nupkg :: buildNugetPushArgs pushParams)
let result = exec (fun _ -> param.Common) "nuget push" args

if result.OK then
__.MarkSuccess()
elif pushParams.PushTrials > 0 then
nugetPush (fun _ -> param.WithPushParams { pushParams with PushTrials = pushParams.PushTrials - 1 }) nupkg
else
failwithf "dotnet nuget push failed with code %i" result.ExitCode
1 change: 1 addition & 0 deletions src/app/Fake.DotNet.Cli/Fake.DotNet.Cli.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<ProjectReference Include="..\Fake.Core.Trace\Fake.Core.Trace.fsproj" />
<ProjectReference Include="..\Fake.Core.Process\Fake.Core.Process.fsproj" />
<ProjectReference Include="..\Fake.Core.String\Fake.Core.String.fsproj" />
<ProjectReference Include="..\Fake.DotNet.NuGet\Fake.DotNet.NuGet.fsproj" />
<ProjectReference Include="..\Fake.IO.FileSystem\Fake.IO.FileSystem.fsproj" />
<ProjectReference Include="..\Fake.DotNet.MSBuild\Fake.DotNet.MSBuild.fsproj" />
</ItemGroup>
Expand Down
3 changes: 2 additions & 1 deletion src/app/Fake.DotNet.Cli/VisibleTo.fs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ namespace System
open System.Runtime.CompilerServices

[<assembly: InternalsVisibleTo("Fake.Core.IntegrationTests")>]
do ()
[<assembly: InternalsVisibleTo("Fake.Core.UnitTests")>]
do ()
138 changes: 108 additions & 30 deletions src/app/Fake.DotNet.NuGet/NuGet.fs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,18 @@ type NugetSymbolPackage =
/// Build a symbol package using the nuspec file
| Nuspec = 2

type internal ToolOptions =
{ ToolPath : string
Command : string
WorkingDir : string
IsFullFramework : bool }

static member Create toolPath command workingDir isFullFramework =
{ ToolPath = toolPath
Command = command
WorkingDir = workingDir
IsFullFramework = isFullFramework }

/// Nuget parameter type
type NuGetParams =
{ ToolPath : string
Expand Down Expand Up @@ -315,40 +327,106 @@ let private pack parameters nuspecFile =
parameters.Version outputPath nuspecFile packageAnalysis defaultExcludes includeReferencedProjects properties basePath
|> execute

/// push package (and try again if something fails)
let rec private publish parameters =
TraceSecrets.register parameters.AccessKey "<NuGetKey>"
TraceSecrets.register parameters.SymbolAccessKey "<NuGetSymbolKey>"
// Newer NuGet requires source to be always specified, so if PublishUrl is empty,
// ignore symbol source - the produced source is broken anyway.
let normalize str = if String.isNullOrEmpty str then None else Some str
let source = match parameters.PublishUrl |> normalize, parameters.SymbolPublishUrl |> normalize with
| None, _ -> ""
| Some source, None -> sprintf "-source %s" source
| Some source, Some symSource -> sprintf "-source %s -SymbolSource %s -SymbolApiKey %s"
source symSource parameters.SymbolAccessKey

let args = sprintf "push \"%s\" %s %s" (parameters.OutputPath @@ packageFileName parameters |> Path.getFullName)
parameters.AccessKey source
Trace.tracefn "%s %s in WorkingDir: %s Trials left: %d" parameters.ToolPath args
(Path.getFullName parameters.WorkingDir) parameters.PublishTrials
/// dotnet nuget push command options
type NuGetPushParams =
{ /// Disables buffering when pushing to an HTTP(S) server to reduce memory usage.
DisableBuffering: bool
/// The API key for the server
ApiKey: string option
/// Doesn't push symbols (even if present).
NoSymbols: bool
/// Doesn't append "api/v2/package" to the source URL.
NoServiceEndpoint: bool
/// Specifies the server URL. This option is required unless DefaultPushSource config value is set in the NuGet config file.
Source: string option
/// The API key for the symbol server.
SymbolApiKey: string option
/// Specifies the symbol server URL.
SymbolSource: string option
/// Specifies the timeout for pushing to a server.
Timeout: TimeSpan option
/// Number of times to retry pushing the package
PushTrials: int}

static member Create() =
{ DisableBuffering = false
ApiKey = None
NoSymbols = false
NoServiceEndpoint = false
Source = None
SymbolApiKey = None
SymbolSource = None
Timeout = None
PushTrials = 5 }

type NuGetParams with
member internal x.NuGetPushOptions =
let normalize str = if String.isNullOrEmpty str then None else Some str

{ DisableBuffering = false
ApiKey = normalize x.AccessKey
NoSymbols = false
NoServiceEndpoint = false
Source = normalize x.PublishUrl
SymbolApiKey = normalize x.SymbolAccessKey
SymbolSource = normalize x.SymbolPublishUrl
Timeout = Some x.TimeOut
PushTrials = x.PublishTrials }

member internal x.ToolOptions = ToolOptions.Create x.ToolPath "push" x.WorkingDir true
member internal x.Nupkg = (x.OutputPath @@ packageFileName x |> Path.getFullName)

let private toPushCliArgs param =
let ifTrue x b =
if b then Some x
else None

[
param.ApiKey
param.DisableBuffering |> ifTrue "-DisableBuffering"
param.NoSymbols |> ifTrue "-NoSymbols"
param.NoServiceEndpoint |> ifTrue "-NoServiceEndpoint"
param.Source |> Option.map (sprintf "-Source %s")
param.SymbolApiKey |> Option.map (sprintf "-SymbolApiKey %s")
param.SymbolSource |> Option.map (sprintf "-SymbolSource %s")
param.Timeout |> Option.map string |> Option.map (sprintf "-Timeout %s")
]
|> List.choose id
|> Arguments.ofList

let rec private push (options : ToolOptions) (parameters : NuGetPushParams) nupkg =
parameters.ApiKey |> Option.iter (fun key -> TraceSecrets.register key "<NuGetKey>")
parameters.SymbolApiKey |> Option.iter (fun key -> TraceSecrets.register key "<NuGetSymbolKey>")

let args =
sprintf "%s \"%s\" %s" options.Command nupkg (toPushCliArgs parameters).ToWindowsCommandLine

sprintf "%s %s in WorkingDir: %s Trials left: %d" options.ToolPath args (Path.getFullName options.WorkingDir) parameters.PushTrials
|> TraceSecrets.guardMessage
|> Trace.trace

try
let result =
let tracing = Process.shouldEnableProcessTracing()
try
Process.setEnableProcessTracing false
Process.execSimple ((fun info ->
{ info with
FileName = parameters.ToolPath
WorkingDirectory = Path.getFullName parameters.WorkingDir
Arguments = args }) >> Process.withFramework) parameters.TimeOut
finally Process.setEnableProcessTracing tracing
if result <> 0 then
sprintf "Error during NuGet push. %s %s" parameters.ToolPath args
CreateProcess.fromRawCommandLine options.ToolPath args
|> CreateProcess.withWorkingDirectory options.WorkingDir
|> CreateProcess.withTimeout (parameters.Timeout |> Option.defaultValue (TimeSpan.FromMinutes 5.0))
|> (fun p ->
if options.IsFullFramework then
p |> CreateProcess.withFramework
else
p)
|> Proc.run

if result.ExitCode <> 0 then
sprintf "Error during NuGet push. %s %s" options.ToolPath args
|> TraceSecrets.guardMessage
|> failwith
with exn when parameters.PublishTrials > 0 ->
publish { parameters with PublishTrials = parameters.PublishTrials - 1 }

with _ when parameters.PushTrials > 0 ->
push options { parameters with PushTrials = parameters.PushTrials - 1 } nupkg

let private publish (parameters : NuGetParams) =
push parameters.ToolOptions parameters.NuGetPushOptions parameters.Nupkg

/// push package to symbol server (and try again if something fails)
let rec private publishSymbols parameters =
Expand Down
44 changes: 37 additions & 7 deletions src/test/Fake.Core.UnitTests/Fake.DotNet.Cli.fs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,41 @@ open Expecto

[<Tests>]
let tests =
testList "Fake.DotNet.Cli.Tests" [
testCase "Test that we can use Process-Helpers on Cli Paramters" <| fun _ ->
let cli =
DotNet.Options.Create()
|> Process.setEnvironmentVariable "Somevar" "someval"
testList "Fake.DotNet.Cli.Tests" [
testCase "Test that we can use Process-Helpers on Cli Paramters" <| fun _ ->
let cli =
DotNet.Options.Create()
|> Process.setEnvironmentVariable "Somevar" "someval"

Expect.equal cli.Environment.["Somevar"] "someval" "Retrieving the correct environment variable failed."
]
Expect.equal cli.Environment.["Somevar"] "someval" "Retrieving the correct environment variable failed."

testCase "Test that the default dotnet nuget push arguments returns empty string" <| fun _ ->
let cli =
DotNet.NuGetPushOptions.Create().PushParams
|> DotNet.buildNugetPushArgs
|> Args.toWindowsCommandLine

Expect.isEmpty cli "Empty push args."

testCase "Test that the dotnet nuget push arguments with all params setreturns correct string" <| fun _ ->
let param =
{ DotNet.NuGetPushOptions.Create().PushParams with
DisableBuffering = true
ApiKey = Some "abc123"
NoSymbols = true
NoServiceEndpoint = true
Source = Some "MyNuGetSource"
SymbolApiKey = Some "MySymbolApiKey"
SymbolSource = Some "MySymbolSource"
Timeout = Some <| System.TimeSpan.FromMinutes 5.0
PushTrials = 5 }

let cli =
param
|> DotNet.buildNugetPushArgs
|> Args.toWindowsCommandLine

let expected = "--disable-buffering --api-key abc123 --no-symbols --no-service-endpoint --source MyNuGetSource --symbol-api-key MySymbolApiKey --symbol-source MySymbolSource --timeout 300"

Expect.equal cli expected "Push args generated correctly."
]