<commit_before>/// [omit]
module Paket.Program

open System
open System.Diagnostics
open System.Reflection
open System.IO

open Paket.Logging
open Paket.Commands
open Paket.Releases

open Argu
open PackageSources

let private stopWatch = new Stopwatch()
stopWatch.Start()

let filterGlobalArgs args =
    let error = ref None
    let verbose = args |> Array.exists (fun x -> x = "--verbose" || x = "-v")
    let logFile = args |> Array.tryFindIndex (fun x -> x = "--log-file") |> Option.bind (fun i -> if args.Length - 1 > i then Some args.[i+1] else error := Some "--log-file was specifed, but no log file was given"; None)

    let rest =
        match logFile with
        | Some file -> args |> Array.filter (fun a -> a <> "--log-file" && a <> file)
        | None -> args |> Array.filter (fun a -> a <> "--log-file")

    let rest =
        if verbose then rest |> Array.filter (fun a -> a <> "-v" && a <> "--verbose")
        else rest

    error,verbose, logFile, rest

let globalError,v, logFile, args = filterGlobalArgs (Environment.GetCommandLineArgs().[1..])
let silent = args |> Array.exists (fun a -> a = "-s" || a = "--silent")

let processWithValidation<'T when 'T :> IArgParserTemplate> validateF commandF command
    args =
    let parser = ArgumentParser.Create<'T>()
    let results =
        parser.Parse
            (inputs = args, raiseOnUsage = false, ignoreMissing = true,
             errorHandler = ProcessExiter())

    let resultsValid = validateF (results)
    if results.IsUsageRequested || not resultsValid || !globalError <> None then
        if !globalError <> None then
            traceError (!globalError).Value
            Environment.ExitCode <- 1
        elif not resultsValid then
            traceError "Command was:"
            traceError ("  " + String.Join(" ",Environment.GetCommandLineArgs()))
            parser.Usage(Commands.cmdLineUsageMessage command parser) |> traceError
            Environment.ExitCode <- 1
        else
            parser.Usage(Commands.cmdLineUsageMessage command parser) |> trace
    else
        commandF results
        let elapsedTime = Utils.TimeSpanToReadableString stopWatch.Elapsed
        if not silent then
            tracefn "%s - ready." elapsedTime

let processCommand<'T when 'T :> IArgParserTemplate> (commandF : ParseResults<'T> -> unit) =
    processWithValidation (fun _ -> true) commandF

Logging.verbose <- v

let add (results : ParseResults<_>) =
    let packageName = results.GetResult <@ AddArgs.Nuget @>
    let version = defaultArg (results.TryGetResult <@ AddArgs.Version @>) ""
    let force = results.Contains <@ AddArgs.Force @>
    let redirects = results.Contains <@ AddArgs.Redirects @>
    let createNewBindingFiles = results.Contains <@ AddArgs.CreateNewBindingFiles @>
    let cleanBindingRedirects = results.Contains <@ AddArgs.Clean_Redirects @>
    let group = results.TryGetResult <@ AddArgs.Group @>
    let noInstall = results.Contains <@ AddArgs.No_Install @>
    let semVerUpdateMode =
        if results.Contains <@ AddArgs.Keep_Patch @> then SemVerUpdateMode.KeepPatch else
        if results.Contains <@ AddArgs.Keep_Minor @> then SemVerUpdateMode.KeepMinor else
        if results.Contains <@ AddArgs.Keep_Major @> then SemVerUpdateMode.KeepMajor else
        SemVerUpdateMode.NoRestriction
    let touchAffectedRefs = results.Contains <@ AddArgs.Touch_Affected_Refs @>

    match results.TryGetResult <@ AddArgs.Project @> with
    | Some projectName ->
        Dependencies.Locate().AddToProject(group, packageName, version, force, redirects, cleanBindingRedirects, createNewBindingFiles, projectName, noInstall |> not, semVerUpdateMode, touchAffectedRefs)
    | None ->
        let interactive = results.Contains <@ AddArgs.Interactive @>
        Dependencies.Locate().Add(group, packageName, version, force, redirects, cleanBindingRedirects, createNewBindingFiles, interactive, noInstall |> not, semVerUpdateMode, touchAffectedRefs)

let validateConfig (results : ParseResults<_>) =
    let credential = results.Contains <@ ConfigArgs.AddCredentials @>
    let token = results.Contains <@ ConfigArgs.AddToken @>
    match credential, token with
    | true, _ -> results.GetResults <@ ConfigArgs.AddCredentials @> |> List.isEmpty |> not
    | _, true -> results.GetResults <@ ConfigArgs.AddToken @> |> List.isEmpty |> not
    | _ -> false

let config (results : ParseResults<_>) =
    let credentials = results.Contains <@ ConfigArgs.AddCredentials @>
    let token = results.Contains <@ ConfigArgs.AddToken @>
    match credentials, token with
    | true, _ -> 
      let args = results.GetResults <@ ConfigArgs.AddCredentials @>
      let source = args.Item 0
      let username, password = results.GetResult (<@ ConfigArgs.Username @>, ""), results.GetResult (<@ ConfigArgs.Password @>, "") 
            
      Dependencies.Locate().AddCredentials(source, username, password)
    | _, true ->
      let args = results.GetResults <@ ConfigArgs.AddToken @>
      let source, token = args.Item 0
      Dependencies.Locate().AddToken(source, token)
    | _ -> ()

let validateAutoRestore (results : ParseResults<_>) =
    results.GetAllResults().Length = 1
<commit_msg>paket config should be able to run everywhere<commit_after>/// [omit]
module Paket.Program

open System
open System.Diagnostics
open System.Reflection
open System.IO

open Paket.Logging
open Paket.Commands
open Paket.Releases

open Argu
open PackageSources

let private stopWatch = new Stopwatch()
stopWatch.Start()

let filterGlobalArgs args =
    let error = ref None
    let verbose = args |> Array.exists (fun x -> x = "--verbose" || x = "-v")
    let logFile = args |> Array.tryFindIndex (fun x -> x = "--log-file") |> Option.bind (fun i -> if args.Length - 1 > i then Some args.[i+1] else error := Some "--log-file was specifed, but no log file was given"; None)

    let rest =
        match logFile with
        | Some file -> args |> Array.filter (fun a -> a <> "--log-file" && a <> file)
        | None -> args |> Array.filter (fun a -> a <> "--log-file")

    let rest =
        if verbose then rest |> Array.filter (fun a -> a <> "-v" && a <> "--verbose")
        else rest

    error,verbose, logFile, rest

let globalError,v, logFile, args = filterGlobalArgs (Environment.GetCommandLineArgs().[1..])
let silent = args |> Array.exists (fun a -> a = "-s" || a = "--silent")

let processWithValidation<'T when 'T :> IArgParserTemplate> validateF commandF command
    args =
    let parser = ArgumentParser.Create<'T>()
    let results =
        parser.Parse
            (inputs = args, raiseOnUsage = false, ignoreMissing = true,
             errorHandler = ProcessExiter())

    let resultsValid = validateF (results)
    if results.IsUsageRequested || not resultsValid || !globalError <> None then
        if !globalError <> None then
            traceError (!globalError).Value
            Environment.ExitCode <- 1
        elif not resultsValid then
            traceError "Command was:"
            traceError ("  " + String.Join(" ",Environment.GetCommandLineArgs()))
            parser.Usage(Commands.cmdLineUsageMessage command parser) |> traceError
            Environment.ExitCode <- 1
        else
            parser.Usage(Commands.cmdLineUsageMessage command parser) |> trace
    else
        commandF results
        let elapsedTime = Utils.TimeSpanToReadableString stopWatch.Elapsed
        if not silent then
            tracefn "%s - ready." elapsedTime

let processCommand<'T when 'T :> IArgParserTemplate> (commandF : ParseResults<'T> -> unit) =
    processWithValidation (fun _ -> true) commandF

Logging.verbose <- v

let add (results : ParseResults<_>) =
    let packageName = results.GetResult <@ AddArgs.Nuget @>
    let version = defaultArg (results.TryGetResult <@ AddArgs.Version @>) ""
    let force = results.Contains <@ AddArgs.Force @>
    let redirects = results.Contains <@ AddArgs.Redirects @>
    let createNewBindingFiles = results.Contains <@ AddArgs.CreateNewBindingFiles @>
    let cleanBindingRedirects = results.Contains <@ AddArgs.Clean_Redirects @>
    let group = results.TryGetResult <@ AddArgs.Group @>
    let noInstall = results.Contains <@ AddArgs.No_Install @>
    let semVerUpdateMode =
        if results.Contains <@ AddArgs.Keep_Patch @> then SemVerUpdateMode.KeepPatch else
        if results.Contains <@ AddArgs.Keep_Minor @> then SemVerUpdateMode.KeepMinor else
        if results.Contains <@ AddArgs.Keep_Major @> then SemVerUpdateMode.KeepMajor else
        SemVerUpdateMode.NoRestriction
    let touchAffectedRefs = results.Contains <@ AddArgs.Touch_Affected_Refs @>

    match results.TryGetResult <@ AddArgs.Project @> with
    | Some projectName ->
        Dependencies.Locate().AddToProject(group, packageName, version, force, redirects, cleanBindingRedirects, createNewBindingFiles, projectName, noInstall |> not, semVerUpdateMode, touchAffectedRefs)
    | None ->
        let interactive = results.Contains <@ AddArgs.Interactive @>
        Dependencies.Locate().Add(group, packageName, version, force, redirects, cleanBindingRedirects, createNewBindingFiles, interactive, noInstall |> not, semVerUpdateMode, touchAffectedRefs)

let validateConfig (results : ParseResults<_>) =
    let credential = results.Contains <@ ConfigArgs.AddCredentials @>
    let token = results.Contains <@ ConfigArgs.AddToken @>
    match credential, token with
    | true, _ -> results.GetResults <@ ConfigArgs.AddCredentials @> |> List.isEmpty |> not
    | _, true -> results.GetResults <@ ConfigArgs.AddToken @> |> List.isEmpty |> not
    | _ -> false

let config (results : ParseResults<_>) =
    let credentials = results.Contains <@ ConfigArgs.AddCredentials @>
    let token = results.Contains <@ ConfigArgs.AddToken @>
    match credentials, token with
    | true, _ -> 
      let args = results.GetResults <@ ConfigArgs.AddCredentials @>
      let source = args.Item 0
      let username, password = results.GetResult (<@ ConfigArgs.Username @>, ""), results.GetResult (<@ ConfigArgs.Password @>, "") 
            
      Dependencies(".").AddCredentials(source, username, password)
    | _, true ->
      let args = results.GetResults <@ ConfigArgs.AddToken @>
      let source, token = args.Item 0
      Dependencies(".").AddToken(source, token)
    | _ -> ()

let validateAutoRestore (results : ParseResults<_>) =
    results.GetAllResults().Length = 1

{'fraction_non_alphanumeric': 0.11450528338136408, 'fraction_numerical': 0.001536983669548511, 'mean_word_length': 3.1878519710378117, 'pattern_counts': {'":': 0, '<': 87, '<?xml version=': 0, '>': 155, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '471379', 'n_tokens_mistral': 2998, 'n_tokens_neox': 2929, 'n_words': 809}