From 5284c604dc40d60dac597941c9e669314826d982 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Tue, 15 Jun 2021 08:13:15 +0200 Subject: [PATCH 01/62] start the initial implementation of a set proxy script. added git support. --- samples/basic.proxy.config.json | 6 +++ src/Set-ProxyConfigurtion.ps1 | 88 +++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 samples/basic.proxy.config.json create mode 100644 src/Set-ProxyConfigurtion.ps1 diff --git a/samples/basic.proxy.config.json b/samples/basic.proxy.config.json new file mode 100644 index 0000000..97d2570 --- /dev/null +++ b/samples/basic.proxy.config.json @@ -0,0 +1,6 @@ +{ + "ProxyAddress": "http://proxy.codez.one:8080", + "BypassList": [ + "https://git.codez.one" + ] +} \ No newline at end of file diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 new file mode 100644 index 0000000..9109d5f --- /dev/null +++ b/src/Set-ProxyConfigurtion.ps1 @@ -0,0 +1,88 @@ +function Set-ProxyConfiguration { + param ( + [string] + $ConfigPath + ) + if((Test-Path $ConfigPath) -eq $false){ + Write-Error "The config path doesn't exsists." -ErrorAction Stop; + } + [ProxySetting] $proxySettings = [ProxySetting] (Get-Content -Raw -Path $ConfigPath | ConvertFrom-Json); + Write-Debug $proxySettings; + if($proxySettings.UseSystemProxyAddress -and [string]::IsNullOrWhiteSpace($proxySettings.ProxyAddress)){ + if($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows){ + $proxySettings.ProxyAddress = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer; + }else{ + # TODO: find a good way to get linux system proxy. For now throw exception + Write-Error "Currently we don't support linux, to read out the system proxy. Please configure it manualy" -ErrorAction Stop; + } + if($null -eq $proxySettings.ProxyCredentials){ + Write-Warning "You don't have set proxy credentials. If your system is configured with proxy credentials we can't read them."; + } + } + Set-GitProxyConfiguration -Settings $proxySettings; +} + +function Set-GitProxyConfiguration { + param ( + [ProxySetting] + $Settings + ) + if ($null -eq (Get-Command "git" -ErrorAction SilentlyContinue)) + { + Write-Debug "Unable to find git on your system. Skip configuration"; + return; + } + . "git" "config" "--global" "http.proxy" "$($Settings.ProxyAddress)"; + . "git" "config" "--global" "https.proxy" "$($Settings.ProxyAddress)"; + + # only git version 2.13 or higher supports hostname wildcards + $supportsWildcardHostnames = ((((git version) -split ' ')[2] -split '\.')[0] -ge 2) -and ((((git version) -split ' ')[2] -split '\.')[1] -ge 13); + # set all new entries + $Settings.BypassList | ForEach-Object{ + if($_ -contains '*' -and $supportsWildcardHostnames -eq $false){ + Write-Warning "Your git version is to old to support wild card hostnames. You must have version 2.13 or higher. We skip the hostname $_"; + }else{ + if($_.StartsWith("https")){ + . "git" "config" "--global" "https.$_.proxy" '""'; + }else{ + . "git" "config" "--global" "http.$_.proxy" '""'; + } + } + + } + # remove old entries: + # http + . "git" "config" "--global" "--get-regexp" "http\.http" | ForEach-Object{ + $bypasskey = $_.Trim(); + if ($bypasskey -match "(http\.)(http.*)(\.proxy)") { + $bypassedUrl = $matches[2].Trim(); + $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object{$_ -like $bypassedUrl}); + if($shouldBeRemoved){ + Write-Warning "Remove '$bypassedUrl' from git bypass list"; + . "git" "config" "--global" "--unset" "$bypasskey"; + } + } + } + + # https + . "git" "config" "--global" "--get-regexp" "https\.https"| ForEach-Object{ + $bypasskey = $_.Trim(); + if ($bypasskey -match "(https\.)(https.*)(\.proxy)") { + $bypassedUrl = $matches[2].Trim(); + $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object{$_ -like $bypassedUrl}); + if($shouldBeRemoved){ + Write-Warning "Remove '$bypassedUrl' from git bypass list"; + . "git" "config" "--global" "--unset" "$bypasskey"; + } + } + } +} + + +class ProxySetting { + # TODO: implement http and https proxies can be different! 💣 + [string] $ProxyAddress = $null; + [pscredential] $ProxyCredentials = $null; + [bool] $UseSystemProxyAddress = $false; + [string[]] $BypassList; +} \ No newline at end of file From c8ff956675eda5f499a6d83dcb4d6c557d9fb04f Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Tue, 15 Jun 2021 20:59:07 +0200 Subject: [PATCH 02/62] add npm support --- src/Set-ProxyConfigurtion.ps1 | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 9109d5f..fc9f66c 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -1,4 +1,5 @@ function Set-ProxyConfiguration { + [CmdletBinding()] param ( [string] $ConfigPath @@ -20,9 +21,11 @@ function Set-ProxyConfiguration { } } Set-GitProxyConfiguration -Settings $proxySettings; + Set-NpmProxyConfiguration -Settings $proxySettings; } function Set-GitProxyConfiguration { + [CmdletBinding()] param ( [ProxySetting] $Settings @@ -32,6 +35,7 @@ function Set-GitProxyConfiguration { Write-Debug "Unable to find git on your system. Skip configuration"; return; } + # set base address . "git" "config" "--global" "http.proxy" "$($Settings.ProxyAddress)"; . "git" "config" "--global" "https.proxy" "$($Settings.ProxyAddress)"; @@ -78,11 +82,33 @@ function Set-GitProxyConfiguration { } } +function Set-NpmProxyConfiguration { + [CmdletBinding()] + param ( + [ProxySetting] + $Settings + ) + if ($null -eq (Get-Command "npm" -ErrorAction SilentlyContinue)) + { + Write-Debug "Unable to find npm on your system. Skip configuration"; + return; + } + # set base address + . "npm" "config" "set" "proxy" "$($Settings.ProxyAddress)"; + . "npm" "config" "set" "https-proxy" "$($Settings.ProxyAddress)"; + + $bypasstring = $(($Settings.BypassList -join ',').Trim()); + . "npm" "config" "set" "noproxy" $bypasstring; # this is for npm verison >= 6.4.1 + . "npm" "config" "set" "no-proxy" "$bypasstring"; # this is for npm version < 6.4.1 +} + class ProxySetting { # TODO: implement http and https proxies can be different! 💣 [string] $ProxyAddress = $null; + # TODO: how to handle credentials [pscredential] $ProxyCredentials = $null; + # TODO: are we allowed to override system proxy. (important for all .net applications, because they normaly use the system settings) [bool] $UseSystemProxyAddress = $false; [string[]] $BypassList; } \ No newline at end of file From 64623e1f3bb992c4fcc0d197ff002f386513a52a Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Tue, 15 Jun 2021 21:06:45 +0200 Subject: [PATCH 03/62] fixes a wired bug with npm --- src/Set-ProxyConfigurtion.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index fc9f66c..764b9c9 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -98,8 +98,8 @@ function Set-NpmProxyConfiguration { . "npm" "config" "set" "https-proxy" "$($Settings.ProxyAddress)"; $bypasstring = $(($Settings.BypassList -join ',').Trim()); - . "npm" "config" "set" "noproxy" $bypasstring; # this is for npm verison >= 6.4.1 . "npm" "config" "set" "no-proxy" "$bypasstring"; # this is for npm version < 6.4.1 + . "npm" "config" "set" "noproxy" $bypasstring; # this is for npm verison >= 6.4.1 } From 46dd92fe91fba3ad2e0ea68459b53e97a492f45a Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 15:53:31 +0200 Subject: [PATCH 04/62] add apt configuration --- src/Set-ProxyConfigurtion.ps1 | 79 ++++++++++++++++++++++++++--------- 1 file changed, 59 insertions(+), 20 deletions(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 764b9c9..2899d92 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -4,24 +4,27 @@ function Set-ProxyConfiguration { [string] $ConfigPath ) - if((Test-Path $ConfigPath) -eq $false){ + if ((Test-Path $ConfigPath) -eq $false) { Write-Error "The config path doesn't exsists." -ErrorAction Stop; } [ProxySetting] $proxySettings = [ProxySetting] (Get-Content -Raw -Path $ConfigPath | ConvertFrom-Json); Write-Debug $proxySettings; - if($proxySettings.UseSystemProxyAddress -and [string]::IsNullOrWhiteSpace($proxySettings.ProxyAddress)){ - if($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows){ + if ($proxySettings.UseSystemProxyAddress -and [string]::IsNullOrWhiteSpace($proxySettings.ProxyAddress)) { + if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { $proxySettings.ProxyAddress = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer; - }else{ + } + else { # TODO: find a good way to get linux system proxy. For now throw exception Write-Error "Currently we don't support linux, to read out the system proxy. Please configure it manualy" -ErrorAction Stop; } - if($null -eq $proxySettings.ProxyCredentials){ + if ($null -eq $proxySettings.ProxyCredentials) { Write-Warning "You don't have set proxy credentials. If your system is configured with proxy credentials we can't read them."; } } + # TODO: exclude this to make my machine working while im testing. Set-GitProxyConfiguration -Settings $proxySettings; Set-NpmProxyConfiguration -Settings $proxySettings; + Set-AptProxyConfiguration -Settings $proxySettings } function Set-GitProxyConfiguration { @@ -30,8 +33,7 @@ function Set-GitProxyConfiguration { [ProxySetting] $Settings ) - if ($null -eq (Get-Command "git" -ErrorAction SilentlyContinue)) - { + if ($null -eq (Get-Command "git" -ErrorAction SilentlyContinue)) { Write-Debug "Unable to find git on your system. Skip configuration"; return; } @@ -42,13 +44,15 @@ function Set-GitProxyConfiguration { # only git version 2.13 or higher supports hostname wildcards $supportsWildcardHostnames = ((((git version) -split ' ')[2] -split '\.')[0] -ge 2) -and ((((git version) -split ' ')[2] -split '\.')[1] -ge 13); # set all new entries - $Settings.BypassList | ForEach-Object{ - if($_ -contains '*' -and $supportsWildcardHostnames -eq $false){ + $Settings.BypassList | ForEach-Object { + if ($_ -contains '*' -and $supportsWildcardHostnames -eq $false) { Write-Warning "Your git version is to old to support wild card hostnames. You must have version 2.13 or higher. We skip the hostname $_"; - }else{ - if($_.StartsWith("https")){ + } + else { + if ($_.StartsWith("https")) { . "git" "config" "--global" "https.$_.proxy" '""'; - }else{ + } + else { . "git" "config" "--global" "http.$_.proxy" '""'; } } @@ -56,12 +60,12 @@ function Set-GitProxyConfiguration { } # remove old entries: # http - . "git" "config" "--global" "--get-regexp" "http\.http" | ForEach-Object{ + . "git" "config" "--global" "--get-regexp" "http\.http" | ForEach-Object { $bypasskey = $_.Trim(); if ($bypasskey -match "(http\.)(http.*)(\.proxy)") { $bypassedUrl = $matches[2].Trim(); - $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object{$_ -like $bypassedUrl}); - if($shouldBeRemoved){ + $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object { $_ -like $bypassedUrl }); + if ($shouldBeRemoved) { Write-Warning "Remove '$bypassedUrl' from git bypass list"; . "git" "config" "--global" "--unset" "$bypasskey"; } @@ -69,12 +73,12 @@ function Set-GitProxyConfiguration { } # https - . "git" "config" "--global" "--get-regexp" "https\.https"| ForEach-Object{ + . "git" "config" "--global" "--get-regexp" "https\.https" | ForEach-Object { $bypasskey = $_.Trim(); if ($bypasskey -match "(https\.)(https.*)(\.proxy)") { $bypassedUrl = $matches[2].Trim(); - $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object{$_ -like $bypassedUrl}); - if($shouldBeRemoved){ + $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object { $_ -like $bypassedUrl }); + if ($shouldBeRemoved) { Write-Warning "Remove '$bypassedUrl' from git bypass list"; . "git" "config" "--global" "--unset" "$bypasskey"; } @@ -88,8 +92,7 @@ function Set-NpmProxyConfiguration { [ProxySetting] $Settings ) - if ($null -eq (Get-Command "npm" -ErrorAction SilentlyContinue)) - { + if ($null -eq (Get-Command "npm" -ErrorAction SilentlyContinue)) { Write-Debug "Unable to find npm on your system. Skip configuration"; return; } @@ -98,10 +101,46 @@ function Set-NpmProxyConfiguration { . "npm" "config" "set" "https-proxy" "$($Settings.ProxyAddress)"; $bypasstring = $(($Settings.BypassList -join ',').Trim()); + # TODO: only set the right format . "npm" "config" "set" "no-proxy" "$bypasstring"; # this is for npm version < 6.4.1 . "npm" "config" "set" "noproxy" $bypasstring; # this is for npm verison >= 6.4.1 } +function Set-AptProxyConfiguration { + param ( + [ProxySetting] + $Settings + ) + if ($null -eq (Get-Command "apt" -ErrorAction SilentlyContinue)) { + Write-Debug "Unable to find apt on your system. Skip configuration"; + return; + } + if ((Test-Path "/etc/apt/apt.conf") -eq $false) { + # just write the proxy into the file if it doesn't exsists + "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Set-Content "/etc/apt/apt.conf"; + } + else { + $isAProxyAlreadConfigured = $null -ne (. "apt-config" "dump" "Acquire::http::proxy"); + if ($isAProxyAlreadConfigured) { + $aptConfig = Get-Content "/etc/apt/apt.conf"; + $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"; + Write-Verbose "$aptConfig"; + $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}Proxy `"$($Settings.ProxyAddress)`";`${5}"; + + # replace the file with new content + $aptConfig | Set-Content "/etc/apt/apt.conf"; + } + else { + # if no proxy is configured just append the line + "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"| Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; + } + } + + if ($null -ne $Settings.BypassList -and $Settings.BypassList.Count -ne 0) { + Write-Warning "apt-get don't support bypass list. To bypassing the proxy config for a given command starts the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; + } + +} class ProxySetting { # TODO: implement http and https proxies can be different! 💣 From 22057d18650210ec049ac1533b0985a795117205 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 16:16:23 +0200 Subject: [PATCH 05/62] make the apt and npm implementation for linux more robust --- src/Set-ProxyConfigurtion.ps1 | 66 +++++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 23 deletions(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 2899d92..973a9ec 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -2,7 +2,9 @@ function Set-ProxyConfiguration { [CmdletBinding()] param ( [string] - $ConfigPath + $ConfigPath, + [switch] + $NoRoot ) if ((Test-Path $ConfigPath) -eq $false) { Write-Error "The config path doesn't exsists." -ErrorAction Stop; @@ -24,7 +26,7 @@ function Set-ProxyConfiguration { # TODO: exclude this to make my machine working while im testing. Set-GitProxyConfiguration -Settings $proxySettings; Set-NpmProxyConfiguration -Settings $proxySettings; - Set-AptProxyConfiguration -Settings $proxySettings + Set-AptProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; } function Set-GitProxyConfiguration { @@ -92,10 +94,16 @@ function Set-NpmProxyConfiguration { [ProxySetting] $Settings ) - if ($null -eq (Get-Command "npm" -ErrorAction SilentlyContinue)) { + $npmCommand = (Get-Command "npm" -ErrorAction SilentlyContinue); + if ($null -eq $npmCommand) { Write-Debug "Unable to find npm on your system. Skip configuration"; return; } + if($npmCommand.Path.StartsWith('/mnt/c/Program Files/')){ + Write-Warning ("In WSL2 you must override your environment variables to the linux version of NPM. " + ` + "We can't currently configure NPM for you."); + return; + } # set base address . "npm" "config" "set" "proxy" "$($Settings.ProxyAddress)"; . "npm" "config" "set" "https-proxy" "$($Settings.ProxyAddress)"; @@ -109,36 +117,48 @@ function Set-NpmProxyConfiguration { function Set-AptProxyConfiguration { param ( [ProxySetting] - $Settings + $Settings, + [switch] + $NoRoot ) if ($null -eq (Get-Command "apt" -ErrorAction SilentlyContinue)) { Write-Debug "Unable to find apt on your system. Skip configuration"; return; } - if ((Test-Path "/etc/apt/apt.conf") -eq $false) { - # just write the proxy into the file if it doesn't exsists - "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Set-Content "/etc/apt/apt.conf"; - } - else { - $isAProxyAlreadConfigured = $null -ne (. "apt-config" "dump" "Acquire::http::proxy"); - if ($isAProxyAlreadConfigured) { - $aptConfig = Get-Content "/etc/apt/apt.conf"; - $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"; - Write-Verbose "$aptConfig"; - $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}Proxy `"$($Settings.ProxyAddress)`";`${5}"; - - # replace the file with new content - $aptConfig | Set-Content "/etc/apt/apt.conf"; + try{ + if ((Test-Path "/etc/apt/apt.conf") -eq $false) { + # just write the proxy into the file if it doesn't exsists + "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Set-Content "/etc/apt/apt.conf"; } else { - # if no proxy is configured just append the line - "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"| Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; + $isAProxyAlreadConfigured = $null -ne (. "apt-config" "dump" "Acquire::http::proxy"); + if ($isAProxyAlreadConfigured) { + $aptConfig = Get-Content "/etc/apt/apt.conf"; + $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"; + + $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}Proxy `"$($Settings.ProxyAddress)`";`${5}"; + + # replace the file with new content + $aptConfig | Set-Content "/etc/apt/apt.conf"; + } + else { + # if no proxy is configured just append the line + "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"| Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; + } + } + if ($null -ne $Settings.BypassList -and $Settings.BypassList.Count -ne 0) { + Write-Warning "apt-get don't support bypass list. To bypassing the proxy config for a given command starts the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; + } + }catch [System.UnauthorizedAccessException]{ + if($NoRoot){ + Write-Debug "Skip APT configuration because NORoot."; + return; + }else{ + Write-Error "You must be root to change APT settings." -TargetObject $_ -RecommendedAction "Run powershell as root or specify the `NoRoot` switch."; + return; } } - if ($null -ne $Settings.BypassList -and $Settings.BypassList.Count -ne 0) { - Write-Warning "apt-get don't support bypass list. To bypassing the proxy config for a given command starts the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; - } } From 9838be1963278459433044f2b19c312faada4b06 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 17:50:47 +0200 Subject: [PATCH 06/62] add docker config - also make the git stuff more able to handle hostnames. --- samples/basic.proxy.config.json | 2 +- src/Set-ProxyConfigurtion.ps1 | 49 +++++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/samples/basic.proxy.config.json b/samples/basic.proxy.config.json index 97d2570..36d6971 100644 --- a/samples/basic.proxy.config.json +++ b/samples/basic.proxy.config.json @@ -1,6 +1,6 @@ { "ProxyAddress": "http://proxy.codez.one:8080", "BypassList": [ - "https://git.codez.one" + "git.codez.one" ] } \ No newline at end of file diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 973a9ec..a46a5ef 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -27,6 +27,7 @@ function Set-ProxyConfiguration { Set-GitProxyConfiguration -Settings $proxySettings; Set-NpmProxyConfiguration -Settings $proxySettings; Set-AptProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; + Set-DockerProxyConfiguration -Settings $proxySettings; } function Set-GitProxyConfiguration { @@ -54,8 +55,11 @@ function Set-GitProxyConfiguration { if ($_.StartsWith("https")) { . "git" "config" "--global" "https.$_.proxy" '""'; } - else { + elseif($_.StartsWith("http")) { . "git" "config" "--global" "http.$_.proxy" '""'; + }else{ + . "git" "config" "--global" "http.http://$_.proxy" '""'; + . "git" "config" "--global" "https.https://$_.proxy" '""'; } } @@ -78,7 +82,7 @@ function Set-GitProxyConfiguration { . "git" "config" "--global" "--get-regexp" "https\.https" | ForEach-Object { $bypasskey = $_.Trim(); if ($bypasskey -match "(https\.)(https.*)(\.proxy)") { - $bypassedUrl = $matches[2].Trim(); + $bypassedUrl = $Matches[2].Trim(); $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object { $_ -like $bypassedUrl }); if ($shouldBeRemoved) { Write-Warning "Remove '$bypassedUrl' from git bypass list"; @@ -162,6 +166,47 @@ function Set-AptProxyConfiguration { } +function Set-DockerProxyConfiguration { + param ( + [ProxySetting] + $Settings + ) + if ($null -eq (Get-Command "docker" -ErrorAction SilentlyContinue)) { + Write-Debug "Unable to find docker on your system. Skip configuration"; + #return; + } + $json = '{ + "proxies": + { + "default": + { + "httpProxy": "' + $Settings.ProxyAddress + '", + "httpsProxy": "' + $Settings.ProxyAddress + '", + "noProxy": "' + ($Settings.ProxyAddress -join ',')+ '" + } + } + }'; + Write-Verbose "$json"; + $proxyConfig = ConvertFrom-Json $json; + if((Test-Path "~/.docker/config.json")){ + $dockerConfig = (Get-Content "~/.docker/config.json" -Raw | ConvertFrom-Json); + if($false -eq [bool]($dockerConfig.PSobject.Properties.name -match "proxies")){ + $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig -TypeName $json; + }elseif($false -eq [bool]($dockerConfig.proxies.PSobject.Properties.name -match "default")){ + $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig.proxies -TypeName $json; + }else{ + $dockerConfig.proxies.default | Add-Member -NotePropertyName "httpProxy" -NotePropertyValue $Settings.ProxyAddress -Force + $dockerConfig.proxies.default | Add-Member -NotePropertyName "httpsProxy" -NotePropertyValue $Settings.ProxyAddress -Force + $dockerConfig.proxies.default | Add-Member -NotePropertyName "noProxy" -NotePropertyValue ($Settings.BypassList -join ',') -Force + } + ConvertTo-Json $dockerConfig | Set-Content "~/.docker/config.json"; + }else{ + New-Item "~/.docker" -Force -ItemType Directory | Out-Null; + + ConvertTo-Json $proxyConfig | Set-Content "~/.docker/config.json" -Force; + } +} + class ProxySetting { # TODO: implement http and https proxies can be different! 💣 [string] $ProxyAddress = $null; From eece8bc609a989fe83109fafa862130115300810 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 21:36:26 +0200 Subject: [PATCH 07/62] add powershell configuration --- src/Set-ProxyConfigurtion.ps1 | 156 ++++++++++++++++++++++++++++++---- 1 file changed, 140 insertions(+), 16 deletions(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index a46a5ef..7185bbf 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -28,6 +28,7 @@ function Set-ProxyConfiguration { Set-NpmProxyConfiguration -Settings $proxySettings; Set-AptProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; Set-DockerProxyConfiguration -Settings $proxySettings; + Set-PowerShellProxyConfiguration -Settings $proxySettings; } function Set-GitProxyConfiguration { @@ -55,9 +56,10 @@ function Set-GitProxyConfiguration { if ($_.StartsWith("https")) { . "git" "config" "--global" "https.$_.proxy" '""'; } - elseif($_.StartsWith("http")) { + elseif ($_.StartsWith("http")) { . "git" "config" "--global" "http.$_.proxy" '""'; - }else{ + } + else { . "git" "config" "--global" "http.http://$_.proxy" '""'; . "git" "config" "--global" "https.https://$_.proxy" '""'; } @@ -103,9 +105,9 @@ function Set-NpmProxyConfiguration { Write-Debug "Unable to find npm on your system. Skip configuration"; return; } - if($npmCommand.Path.StartsWith('/mnt/c/Program Files/')){ + if ($npmCommand.Path.StartsWith('/mnt/c/Program Files/')) { Write-Warning ("In WSL2 you must override your environment variables to the linux version of NPM. " + ` - "We can't currently configure NPM for you."); + "We can't currently configure NPM for you."); return; } # set base address @@ -129,7 +131,7 @@ function Set-AptProxyConfiguration { Write-Debug "Unable to find apt on your system. Skip configuration"; return; } - try{ + try { if ((Test-Path "/etc/apt/apt.conf") -eq $false) { # just write the proxy into the file if it doesn't exsists "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Set-Content "/etc/apt/apt.conf"; @@ -147,17 +149,19 @@ function Set-AptProxyConfiguration { } else { # if no proxy is configured just append the line - "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"| Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; + "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; } } if ($null -ne $Settings.BypassList -and $Settings.BypassList.Count -ne 0) { Write-Warning "apt-get don't support bypass list. To bypassing the proxy config for a given command starts the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; } - }catch [System.UnauthorizedAccessException]{ - if($NoRoot){ + } + catch [System.UnauthorizedAccessException] { + if ($NoRoot) { Write-Debug "Skip APT configuration because NORoot."; return; - }else{ + } + else { Write-Error "You must be root to change APT settings." -TargetObject $_ -RecommendedAction "Run powershell as root or specify the `NoRoot` switch."; return; } @@ -173,7 +177,7 @@ function Set-DockerProxyConfiguration { ) if ($null -eq (Get-Command "docker" -ErrorAction SilentlyContinue)) { Write-Debug "Unable to find docker on your system. Skip configuration"; - #return; + return; } $json = '{ "proxies": @@ -182,31 +186,151 @@ function Set-DockerProxyConfiguration { { "httpProxy": "' + $Settings.ProxyAddress + '", "httpsProxy": "' + $Settings.ProxyAddress + '", - "noProxy": "' + ($Settings.ProxyAddress -join ',')+ '" + "noProxy": "' + ($Settings.ProxyAddress -join ',') + '" } } }'; Write-Verbose "$json"; $proxyConfig = ConvertFrom-Json $json; - if((Test-Path "~/.docker/config.json")){ + if ((Test-Path "~/.docker/config.json")) { $dockerConfig = (Get-Content "~/.docker/config.json" -Raw | ConvertFrom-Json); - if($false -eq [bool]($dockerConfig.PSobject.Properties.name -match "proxies")){ + if ($false -eq [bool]($dockerConfig.PSobject.Properties.name -match "proxies")) { $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig -TypeName $json; - }elseif($false -eq [bool]($dockerConfig.proxies.PSobject.Properties.name -match "default")){ + } + elseif ($false -eq [bool]($dockerConfig.proxies.PSobject.Properties.name -match "default")) { $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig.proxies -TypeName $json; - }else{ + } + else { $dockerConfig.proxies.default | Add-Member -NotePropertyName "httpProxy" -NotePropertyValue $Settings.ProxyAddress -Force $dockerConfig.proxies.default | Add-Member -NotePropertyName "httpsProxy" -NotePropertyValue $Settings.ProxyAddress -Force $dockerConfig.proxies.default | Add-Member -NotePropertyName "noProxy" -NotePropertyValue ($Settings.BypassList -join ',') -Force } ConvertTo-Json $dockerConfig | Set-Content "~/.docker/config.json"; - }else{ + } + else { New-Item "~/.docker" -Force -ItemType Directory | Out-Null; ConvertTo-Json $proxyConfig | Set-Content "~/.docker/config.json" -Force; } } +function Set-PowerShellProxyConfiguration { + param ( + [ProxySetting] + $Settings, + [switch] + $NoRoot + ) + if ($NoRoot) { + Write-Verbose "You can't set a proxy for powershell 5 / 7 without admin / root rights. On Windows try to set IE Settings if this is possible."; + return; + } + $proxyConfig = ' + + + + + '+ ( + (($Settings.BypassList | ForEach-Object { " " }) -join [System.Environment]::NewLine) + ) + ' + + + + '; + Write-Debug "$proxyConfig"; + $powershellConfigExtension = [xml]$proxyConfig; + function Update-PowerShellConfig { + [CmdletBinding()] + param ( + [Parameter()] + [string] + $powershellPath + ) + + $configPath = "$powershellPath.config"; + if ((Test-Path $configPath) -eq $false) { + # set acls for windows + if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { + $installDir = (Get-Item $powershellPath).Directory.FullName; + # allow write access to the config file and save the file + $defaultAcl = Get-Acl "$installDir"; + $aclForPowerShellFile = Get-Acl "$installDir"; + $AdministratorsSID = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; + $newRule = New-Object System.Security.AccessControl.FileSystemAccessRule($AdministratorsSID, @("Write"), "None", "InheritOnly", "Allow") ; + $aclForPowerShellFile.AddAccessRule($newRule); + Set-Acl -Path "$installDir" $aclForPowerShellFile; + } + New-Item $configPath -ItemType File | Out-Null; + if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { + #revoke access to default: + Set-Acl -Path "$installDir" $defaultAcl | Out-Null; + } + } + + if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { + # allow write access to the config file and save the file + $defaultAcl = Get-Acl "$configPath"; + $aclForPowerShellFile = Get-Acl "$configPath"; + $AdministratorsSID = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; + $newRule = New-Object System.Security.AccessControl.FileSystemAccessRule($AdministratorsSID, @("Write"), "None", "InheritOnly", "Allow") ; + $aclForPowerShellFile.AddAccessRule($newRule); + Set-Acl -Path "$configPath" $aclForPowerShellFile; + } + $powershellConfig = [xml](Get-Content "$configPath"); + if ($null -eq $powershellConfig) { + $proxyConfig | Set-Content $configPath; + } + elseif ($null -eq $powershellConfig.configuration) { + $extensionNode = $powershellConfig.ImportNode($powershellConfigExtension.configuration, $true); + $powershellConfig.AppendChild($extensionNode) | Out-Null; + } + elseif ($null -eq $powershellConfig.configuration.'system.net') { + $extensionNode = $powershellConfig.configuration.OwnerDocument.ImportNode($powershellConfigExtension.configuration.'system.net', $true); + $powershellConfig.configuration.AppendChild($extensionNode) | Out-Null; + } + else { + # remove old proxy config + $configuredDefaultProxy = $powershellConfig.configuration.GetElementsByTagName('system.net')[0].GetElementsByTagName("defaultProxy"); + if ($null -ne $configuredDefaultProxy -and $configuredDefaultProxy.Count -gt 0) { + $powershellConfig.configuration.GetElementsByTagName('system.net')[0].RemoveChild($configuredDefaultProxy[0]) | Out-Null; + } + # add new proxy config + $extensionNode = $powershellConfig.configuration.GetElementsByTagName('system.net')[0].OwnerDocument.ImportNode($powershellConfigExtension.configuration.'system.net'.defaultProxy, $true); + $powershellConfig.configuration.GetElementsByTagName('system.net')[0].AppendChild($extensionNode) | Out-Null; + } + if ($null -ne $powershellConfig) { + $powershellConfig.Save("$configPath") | Out-Null; + } + if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { + #revoke access to default: + Set-Acl -Path "$configPath" $defaultAcl | Out-Null; + } + } + + # pwsh core + $powershell = (Get-Command "pwsh" -ErrorAction SilentlyContinue); + if ($null -eq $powershell) { + Write-Debug "Unable to find PowerShell 7 on your system. Skip configuration"; + } + else { + Update-PowerShellConfig -powershellPath ($powershell.Path); + } + + #Win powershell + $winPowershell = (Get-Command "powershell" -ErrorAction SilentlyContinue); + if ($null -eq $winPowershell) { + Write-Debug "Unable to find PowerShell < 6 on your system. Skip configuration"; + } + else { + Update-PowerShellConfig -powershellPath ($winPowershell.Path); + } + +} + class ProxySetting { # TODO: implement http and https proxies can be different! 💣 [string] $ProxyAddress = $null; From 7cdf657e1736f04340dae592306344ee28451ac3 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 21:37:57 +0200 Subject: [PATCH 08/62] add comment --- src/Set-ProxyConfigurtion.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 7185bbf..032e48a 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -271,6 +271,7 @@ function Set-PowerShellProxyConfiguration { } } + # set acls for windows if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { # allow write access to the config file and save the file $defaultAcl = Get-Acl "$configPath"; From 5e78f388c3cf60bc43981c74ab060f5c87549cd4 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 21:38:31 +0200 Subject: [PATCH 09/62] add noroot switch --- src/Set-ProxyConfigurtion.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 032e48a..6f4655b 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -28,7 +28,7 @@ function Set-ProxyConfiguration { Set-NpmProxyConfiguration -Settings $proxySettings; Set-AptProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; Set-DockerProxyConfiguration -Settings $proxySettings; - Set-PowerShellProxyConfiguration -Settings $proxySettings; + Set-PowerShellProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; } function Set-GitProxyConfiguration { From 75d49d399c3a61f1ccc90fe6f59eddcfb7d74755 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 22:08:27 +0200 Subject: [PATCH 10/62] add environment configuration --- src/Set-ProxyConfigurtion.ps1 | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 6f4655b..906813a 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -29,6 +29,7 @@ function Set-ProxyConfiguration { Set-AptProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; Set-DockerProxyConfiguration -Settings $proxySettings; Set-PowerShellProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; + Set-EnvironmentProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; } function Set-GitProxyConfiguration { @@ -332,6 +333,48 @@ function Set-PowerShellProxyConfiguration { } +function Set-EnvironmentProxyConfiguration { + [CmdletBinding()] + param ( + [Parameter()] + [ProxySetting] + $Settings, + [switch] + $NoRoot + ) + if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { + # set the process to, to avoid the user must restart the process. + [Environment]::SetEnvironmentVariable("HTTP_PROXY", $Settings.ProxyAddress, [EnvironmentVariableTarget]::Process) + [Environment]::SetEnvironmentVariable("HTTPS_PROXY", $Settings.ProxyAddress, [EnvironmentVariableTarget]::Process) + [Environment]::SetEnvironmentVariable("NO_PROXY", $($Settings.BypassList -join ','), [EnvironmentVariableTarget]::Process) + if ($NoRoot) { + [Environment]::SetEnvironmentVariable("HTTPS_PROXY", $Settings.ProxyAddress, [EnvironmentVariableTarget]::User) + [Environment]::SetEnvironmentVariable("HTTP_PROXY", $Settings.ProxyAddress, [EnvironmentVariableTarget]::User) + [Environment]::SetEnvironmentVariable("NO_PROXY", $($Settings.BypassList -join ','), [EnvironmentVariableTarget]::User) + } + else { + # Set environment for all users + [Environment]::SetEnvironmentVariable("HTTP_PROXY", $Settings.ProxyAddress, [EnvironmentVariableTarget]::Machine); + [Environment]::SetEnvironmentVariable("HTTPS_PROXY", $Settings.ProxyAddress, [EnvironmentVariableTarget]::Machine); + [Environment]::SetEnvironmentVariable("NO_PROXY", $($Settings.BypassList -join ','), [EnvironmentVariableTarget]::Machine) + } + + } + else { + if ($NoRoot) { + Write-Warning "Currently to set the environment this script needs root rights. Didn't change any environment varables."; + } + else { + # Set environment for all users + "export http_proxy=`"$($Settings.ProxyAddress)`" + export no_proxy=`"$($Settings.BypassList -join ',')`" + export HTTP_PROXY=$($Settings.ProxyAddress) + export https_proxy=$($Settings.ProxyAddress) + export HTTPS_PROXY=$($Settings.ProxyAddress)" | Set-Content /etc/profile.d/proxy.sh; + } + } +} + class ProxySetting { # TODO: implement http and https proxies can be different! 💣 [string] $ProxyAddress = $null; From da4dabe0920aeee9066d8efbd58eedabb6f17d90 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 22:35:38 +0200 Subject: [PATCH 11/62] unset proxy if there is no proxy address is defined --- src/Set-ProxyConfigurtion.ps1 | 59 ++++++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index 906813a..bfb380a 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -134,6 +134,10 @@ function Set-AptProxyConfiguration { } try { if ((Test-Path "/etc/apt/apt.conf") -eq $false) { + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { + # do nothing if no proxy should be configured and the config file don't exsists. + return; + } # just write the proxy into the file if it doesn't exsists "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Set-Content "/etc/apt/apt.conf"; } @@ -141,16 +145,29 @@ function Set-AptProxyConfiguration { $isAProxyAlreadConfigured = $null -ne (. "apt-config" "dump" "Acquire::http::proxy"); if ($isAProxyAlreadConfigured) { $aptConfig = Get-Content "/etc/apt/apt.conf"; - $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"; - - $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}Proxy `"$($Settings.ProxyAddress)`";`${5}"; - + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { + # delete proxy config + $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', ""; + $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}`${5}"; + } + else { + # add proxy config + $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"; + $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}Proxy `"$($Settings.ProxyAddress)`";`${5}"; + } # replace the file with new content $aptConfig | Set-Content "/etc/apt/apt.conf"; } else { - # if no proxy is configured just append the line - "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { + # it's okay if no proxy is configured + return; + } + else { + # if no proxy is configured just append the line + "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; + } + } } if ($null -ne $Settings.BypassList -and $Settings.BypassList.Count -ne 0) { @@ -195,10 +212,14 @@ function Set-DockerProxyConfiguration { $proxyConfig = ConvertFrom-Json $json; if ((Test-Path "~/.docker/config.json")) { $dockerConfig = (Get-Content "~/.docker/config.json" -Raw | ConvertFrom-Json); - if ($false -eq [bool]($dockerConfig.PSobject.Properties.name -match "proxies")) { + if([string]::IsNullOrWhiteSpace($Settings.ProxyAddress) -and [bool]($dockerConfig.PSobject.Properties.name -match "proxies")){ + $dockerConfig.PSobject.Properties.Remove('proxies'); + } + elseif ($false -eq [bool]($dockerConfig.PSobject.Properties.name -match "proxies")) { $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig -TypeName $json; } elseif ($false -eq [bool]($dockerConfig.proxies.PSobject.Properties.name -match "default")) { + $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig.proxies -TypeName $json; } else { @@ -209,8 +230,11 @@ function Set-DockerProxyConfiguration { ConvertTo-Json $dockerConfig | Set-Content "~/.docker/config.json"; } else { + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { + # no proxy should be configured. + return; + } New-Item "~/.docker" -Force -ItemType Directory | Out-Null; - ConvertTo-Json $proxyConfig | Set-Content "~/.docker/config.json" -Force; } } @@ -284,13 +308,18 @@ function Set-PowerShellProxyConfiguration { } $powershellConfig = [xml](Get-Content "$configPath"); if ($null -eq $powershellConfig) { - $proxyConfig | Set-Content $configPath; + if([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)){ + # no proxy should be confgiured + return; + }else{ + $proxyConfig | Set-Content $configPath; + } } - elseif ($null -eq $powershellConfig.configuration) { + elseif ($null -eq $powershellConfig.configuration -and $false -eq [string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { $extensionNode = $powershellConfig.ImportNode($powershellConfigExtension.configuration, $true); $powershellConfig.AppendChild($extensionNode) | Out-Null; } - elseif ($null -eq $powershellConfig.configuration.'system.net') { + elseif ($null -eq $powershellConfig.configuration.'system.net' -and $false -eq [string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { $extensionNode = $powershellConfig.configuration.OwnerDocument.ImportNode($powershellConfigExtension.configuration.'system.net', $true); $powershellConfig.configuration.AppendChild($extensionNode) | Out-Null; } @@ -300,9 +329,11 @@ function Set-PowerShellProxyConfiguration { if ($null -ne $configuredDefaultProxy -and $configuredDefaultProxy.Count -gt 0) { $powershellConfig.configuration.GetElementsByTagName('system.net')[0].RemoveChild($configuredDefaultProxy[0]) | Out-Null; } - # add new proxy config - $extensionNode = $powershellConfig.configuration.GetElementsByTagName('system.net')[0].OwnerDocument.ImportNode($powershellConfigExtension.configuration.'system.net'.defaultProxy, $true); - $powershellConfig.configuration.GetElementsByTagName('system.net')[0].AppendChild($extensionNode) | Out-Null; + if($false -eq [string]::IsNullOrWhiteSpace($Settings.ProxyAddress)){ + # add new proxy config + $extensionNode = $powershellConfig.configuration.GetElementsByTagName('system.net')[0].OwnerDocument.ImportNode($powershellConfigExtension.configuration.'system.net'.defaultProxy, $true); + $powershellConfig.configuration.GetElementsByTagName('system.net')[0].AppendChild($extensionNode) | Out-Null; + } } if ($null -ne $powershellConfig) { $powershellConfig.Save("$configPath") | Out-Null; From 252e9f56656ed641296bb3083ee91214179e38bd Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 22:52:18 +0200 Subject: [PATCH 12/62] add working unset of proxy config --- src/Set-ProxyConfigurtion.ps1 | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index bfb380a..c45dceb 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -73,7 +73,7 @@ function Set-GitProxyConfiguration { $bypasskey = $_.Trim(); if ($bypasskey -match "(http\.)(http.*)(\.proxy)") { $bypassedUrl = $matches[2].Trim(); - $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object { $_ -like $bypassedUrl }); + $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object { "http://$_" -like $bypassedUrl }); if ($shouldBeRemoved) { Write-Warning "Remove '$bypassedUrl' from git bypass list"; . "git" "config" "--global" "--unset" "$bypasskey"; @@ -86,7 +86,7 @@ function Set-GitProxyConfiguration { $bypasskey = $_.Trim(); if ($bypasskey -match "(https\.)(https.*)(\.proxy)") { $bypassedUrl = $Matches[2].Trim(); - $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object { $_ -like $bypassedUrl }); + $shouldBeRemoved = $null -eq ($Settings.BypassList | Where-Object { "https://$_" -like $bypassedUrl }); if ($shouldBeRemoved) { Write-Warning "Remove '$bypassedUrl' from git bypass list"; . "git" "config" "--global" "--unset" "$bypasskey"; @@ -111,14 +111,24 @@ function Set-NpmProxyConfiguration { "We can't currently configure NPM for you."); return; } - # set base address - . "npm" "config" "set" "proxy" "$($Settings.ProxyAddress)"; - . "npm" "config" "set" "https-proxy" "$($Settings.ProxyAddress)"; + if([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)){ + # unset base address + . "npm" "config" "delete" "proxy"; + . "npm" "config" "delete" "https-proxy" + # TODO: only set the right format + . "npm" "config" "delete" "no-proxy"; # this is for npm version < 6.4.1 + . "npm" "config" "delete" "noproxy"; # this is for npm verison >= 6.4.1 + }else{ + # set base address + . "npm" "config" "set" "proxy" "$($Settings.ProxyAddress)" | Out-Null; + . "npm" "config" "set" "https-proxy" "$($Settings.ProxyAddress)" | Out-Null; + + $bypasstring = $(($Settings.BypassList -join ',').Trim()); + # TODO: only set the right format + . "npm" "config" "set" "no-proxy" "$bypasstring" | Out-Null; # this is for npm version < 6.4.1 + . "npm" "config" "set" "noproxy" $bypasstring | Out-Null; # this is for npm verison >= 6.4.1 + } - $bypasstring = $(($Settings.BypassList -join ',').Trim()); - # TODO: only set the right format - . "npm" "config" "set" "no-proxy" "$bypasstring"; # this is for npm version < 6.4.1 - . "npm" "config" "set" "noproxy" $bypasstring; # this is for npm verison >= 6.4.1 } function Set-AptProxyConfiguration { From 61c36803a6e2bb17b26809a8d03f2353f27337bd Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 22:52:31 +0200 Subject: [PATCH 13/62] add a sample for unsetting the proxy --- samples/basic.noproxy.config.json | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 samples/basic.noproxy.config.json diff --git a/samples/basic.noproxy.config.json b/samples/basic.noproxy.config.json new file mode 100644 index 0000000..c9816b0 --- /dev/null +++ b/samples/basic.noproxy.config.json @@ -0,0 +1,4 @@ +{ + "ProxyAddress": null, + "BypassList": [] +} \ No newline at end of file From 252b32f80e7b16f1087d595cbc06b92e8aa50c0b Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 22:56:44 +0200 Subject: [PATCH 14/62] fix unsetting git proxy config --- src/Set-ProxyConfigurtion.ps1 | 59 ++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index c45dceb..d202dda 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -42,30 +42,37 @@ function Set-GitProxyConfiguration { Write-Debug "Unable to find git on your system. Skip configuration"; return; } - # set base address - . "git" "config" "--global" "http.proxy" "$($Settings.ProxyAddress)"; - . "git" "config" "--global" "https.proxy" "$($Settings.ProxyAddress)"; + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { + # unset base address + . "git" "config" "--global" "--unset" "http.proxy"; + . "git" "config" "--global" "--unset" "https.proxy"; + } + else { + # set base address + . "git" "config" "--global" "http.proxy" "$($Settings.ProxyAddress)"; + . "git" "config" "--global" "https.proxy" "$($Settings.ProxyAddress)"; - # only git version 2.13 or higher supports hostname wildcards - $supportsWildcardHostnames = ((((git version) -split ' ')[2] -split '\.')[0] -ge 2) -and ((((git version) -split ' ')[2] -split '\.')[1] -ge 13); - # set all new entries - $Settings.BypassList | ForEach-Object { - if ($_ -contains '*' -and $supportsWildcardHostnames -eq $false) { - Write-Warning "Your git version is to old to support wild card hostnames. You must have version 2.13 or higher. We skip the hostname $_"; - } - else { - if ($_.StartsWith("https")) { - . "git" "config" "--global" "https.$_.proxy" '""'; - } - elseif ($_.StartsWith("http")) { - . "git" "config" "--global" "http.$_.proxy" '""'; + # only git version 2.13 or higher supports hostname wildcards + $supportsWildcardHostnames = ((((git version) -split ' ')[2] -split '\.')[0] -ge 2) -and ((((git version) -split ' ')[2] -split '\.')[1] -ge 13); + # set all new entries + $Settings.BypassList | ForEach-Object { + if ($_ -contains '*' -and $supportsWildcardHostnames -eq $false) { + Write-Warning "Your git version is to old to support wild card hostnames. You must have version 2.13 or higher. We skip the hostname $_"; } else { - . "git" "config" "--global" "http.http://$_.proxy" '""'; - . "git" "config" "--global" "https.https://$_.proxy" '""'; + if ($_.StartsWith("https")) { + . "git" "config" "--global" "https.$_.proxy" '""'; + } + elseif ($_.StartsWith("http")) { + . "git" "config" "--global" "http.$_.proxy" '""'; + } + else { + . "git" "config" "--global" "http.http://$_.proxy" '""'; + . "git" "config" "--global" "https.https://$_.proxy" '""'; + } } - } + } } # remove old entries: # http @@ -111,14 +118,15 @@ function Set-NpmProxyConfiguration { "We can't currently configure NPM for you."); return; } - if([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)){ + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { # unset base address . "npm" "config" "delete" "proxy"; . "npm" "config" "delete" "https-proxy" # TODO: only set the right format . "npm" "config" "delete" "no-proxy"; # this is for npm version < 6.4.1 . "npm" "config" "delete" "noproxy"; # this is for npm verison >= 6.4.1 - }else{ + } + else { # set base address . "npm" "config" "set" "proxy" "$($Settings.ProxyAddress)" | Out-Null; . "npm" "config" "set" "https-proxy" "$($Settings.ProxyAddress)" | Out-Null; @@ -222,7 +230,7 @@ function Set-DockerProxyConfiguration { $proxyConfig = ConvertFrom-Json $json; if ((Test-Path "~/.docker/config.json")) { $dockerConfig = (Get-Content "~/.docker/config.json" -Raw | ConvertFrom-Json); - if([string]::IsNullOrWhiteSpace($Settings.ProxyAddress) -and [bool]($dockerConfig.PSobject.Properties.name -match "proxies")){ + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress) -and [bool]($dockerConfig.PSobject.Properties.name -match "proxies")) { $dockerConfig.PSobject.Properties.Remove('proxies'); } elseif ($false -eq [bool]($dockerConfig.PSobject.Properties.name -match "proxies")) { @@ -318,10 +326,11 @@ function Set-PowerShellProxyConfiguration { } $powershellConfig = [xml](Get-Content "$configPath"); if ($null -eq $powershellConfig) { - if([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)){ + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { # no proxy should be confgiured return; - }else{ + } + else { $proxyConfig | Set-Content $configPath; } } @@ -339,7 +348,7 @@ function Set-PowerShellProxyConfiguration { if ($null -ne $configuredDefaultProxy -and $configuredDefaultProxy.Count -gt 0) { $powershellConfig.configuration.GetElementsByTagName('system.net')[0].RemoveChild($configuredDefaultProxy[0]) | Out-Null; } - if($false -eq [string]::IsNullOrWhiteSpace($Settings.ProxyAddress)){ + if ($false -eq [string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { # add new proxy config $extensionNode = $powershellConfig.configuration.GetElementsByTagName('system.net')[0].OwnerDocument.ImportNode($powershellConfigExtension.configuration.'system.net'.defaultProxy, $true); $powershellConfig.configuration.GetElementsByTagName('system.net')[0].AppendChild($extensionNode) | Out-Null; From b2eb9c79ab4de4d2f20cbfafe1e7ac694f017094 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sat, 19 Jun 2021 23:07:43 +0200 Subject: [PATCH 15/62] we can unset proxies now. So no need for developer saveties anymore :D --- src/Set-ProxyConfigurtion.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfigurtion.ps1 index d202dda..f365818 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfigurtion.ps1 @@ -23,7 +23,6 @@ function Set-ProxyConfiguration { Write-Warning "You don't have set proxy credentials. If your system is configured with proxy credentials we can't read them."; } } - # TODO: exclude this to make my machine working while im testing. Set-GitProxyConfiguration -Settings $proxySettings; Set-NpmProxyConfiguration -Settings $proxySettings; Set-AptProxyConfiguration -Settings $proxySettings -NoRoot:$NoRoot; From 35c619206c9e2f5b596e7bf6cf4214d4b2aa0e67 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sun, 20 Jun 2021 17:26:29 +0200 Subject: [PATCH 16/62] fix file names --- src/{Set-ProxyConfigurtion.ps1 => Set-ProxyConfiguration.ps1} | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename src/{Set-ProxyConfigurtion.ps1 => Set-ProxyConfiguration.ps1} (99%) diff --git a/src/Set-ProxyConfigurtion.ps1 b/src/Set-ProxyConfiguration.ps1 similarity index 99% rename from src/Set-ProxyConfigurtion.ps1 rename to src/Set-ProxyConfiguration.ps1 index f365818..cfefcd3 100644 --- a/src/Set-ProxyConfigurtion.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -6,13 +6,14 @@ function Set-ProxyConfiguration { [switch] $NoRoot ) - if ((Test-Path $ConfigPath) -eq $false) { + if ((Test-Path -Path $ConfigPath) -eq $false) { Write-Error "The config path doesn't exsists." -ErrorAction Stop; } [ProxySetting] $proxySettings = [ProxySetting] (Get-Content -Raw -Path $ConfigPath | ConvertFrom-Json); Write-Debug $proxySettings; if ($proxySettings.UseSystemProxyAddress -and [string]::IsNullOrWhiteSpace($proxySettings.ProxyAddress)) { if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { + $proxySettings.ProxyAddress = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer; } else { From 83ffe5b3b9cd5308ae7af06ea8f113b0f28ba885 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Sun, 20 Jun 2021 17:26:43 +0200 Subject: [PATCH 17/62] add some basic tests --- tests/Set-ProxyConfiguration.tests.ps1 | 93 ++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 tests/Set-ProxyConfiguration.tests.ps1 diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 new file mode 100644 index 0000000..bce0c94 --- /dev/null +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -0,0 +1,93 @@ +Describe "Set-ProxyConfiguration" { + BeforeAll { + $fileInfo = Get-ChildItem $PSScriptRoot; + $functionName = $fileInfo.Name.Split('.')[0]; + # load function to test + . "$PSScriptRoot/../src/$functionName.ps1"; + } + Describe "the main function" { + + Context "When Set-ProxyConfiguration is okay and" { + BeforeAll { + Mock -Verifiable Test-Path { + return $true; + }; + Mock -Verifiable Set-GitProxyConfiguration {}; + Mock -Verifiable Set-NpmProxyConfiguration {}; + Mock -Verifiable Set-AptProxyConfiguration {}; + Mock -Verifiable Set-DockerProxyConfiguration {}; + Mock -Verifiable Set-PowerShellProxyConfiguration {}; + Mock -Verifiable Set-EnvironmentProxyConfiguration {}; + } + It("It Should set the proxy") { + # Arrange + $ProxyAddress = 'http://proxy.codez.one:8080'; + Mock -Verifiable Get-Content { return '{ + "ProxyAddress": "'+ $ProxyAddress + '" + }' + } + $configPath = "something/that/not/exsists"; + # Act + Set-ProxyConfiguration -ConfigPath "$configPath"; + #Assert + Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; + Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; + Assert-MockCalled Set-GitProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; + Assert-MockCalled Set-NpmProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; + Assert-MockCalled Set-AptProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; + Assert-MockCalled Set-DockerProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; + Assert-MockCalled Set-PowerShellProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; + Assert-MockCalled Set-EnvironmentProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; + } + It("It Should set the BypassList") { + # Arrange + $BypassAddresses = 'git.codez.one'; + Mock -Verifiable Get-Content { return '{ + "ProxyAddress": "http://proxy.codez.one:8080", + "BypassList": [ + "'+ $BypassAddresses + '" + ] + }' + } + $configPath = "something/that/not/exsists"; + # Act + Set-ProxyConfiguration -ConfigPath "$configPath"; + #Assert + Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; + Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; + Assert-MockCalled Set-GitProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) }; + Assert-MockCalled Set-NpmProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses)}; + Assert-MockCalled Set-AptProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) -and $NoRoot -eq $false }; + Assert-MockCalled Set-DockerProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) }; + Assert-MockCalled Set-PowerShellProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) -and $NoRoot -eq $false }; + Assert-MockCalled Set-EnvironmentProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) -and $NoRoot -eq $false }; + } + It("It Should set the Proxy with the system settings on windows") { + # Arrange + $ProxyAddress = 'http://proxy.codez.one:8080'; + Mock -Verifiable Get-Content { return '{ + "UseSystemProxyAddress": true + }' + } + Mock -Verifiable Get-ItemProperty { + return [PSCustomObject]@{ + proxyServer = "$ProxyAddress"; + }; + } + $configPath = "something/that/not/exsists"; + # Act + Set-ProxyConfiguration -ConfigPath "$configPath"; + #Assert + Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; + Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; + Assert-MockCalled Get-ItemProperty -Times 1 -ParameterFilter { $Path -eq 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'}; + Assert-MockCalled Set-GitProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; + Assert-MockCalled Set-NpmProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress}; + Assert-MockCalled Set-AptProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; + Assert-MockCalled Set-DockerProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; + Assert-MockCalled Set-PowerShellProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; + Assert-MockCalled Set-EnvironmentProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; + } + } + } +} \ No newline at end of file From c3b175d23deba9688990f21ffcf2c14f98a4df27 Mon Sep 17 00:00:00 2001 From: paule96 Date: Mon, 16 Aug 2021 11:58:16 +0200 Subject: [PATCH 18/62] add dev container json --- devcontainer.json | 1 + 1 file changed, 1 insertion(+) create mode 120000 devcontainer.json diff --git a/devcontainer.json b/devcontainer.json new file mode 120000 index 0000000..d0e2418 --- /dev/null +++ b/devcontainer.json @@ -0,0 +1 @@ +CZ.PowerShell.NetworkTools.code-workspace \ No newline at end of file From 839bdc6bc452dbc4f45c9db79d8eacadf725396a Mon Sep 17 00:00:00 2001 From: paule96 Date: Mon, 16 Aug 2021 12:32:42 +0200 Subject: [PATCH 19/62] add dev container json --- devcontainer.json | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) mode change 120000 => 100644 devcontainer.json diff --git a/devcontainer.json b/devcontainer.json deleted file mode 120000 index d0e2418..0000000 --- a/devcontainer.json +++ /dev/null @@ -1 +0,0 @@ -CZ.PowerShell.NetworkTools.code-workspace \ No newline at end of file diff --git a/devcontainer.json b/devcontainer.json new file mode 100644 index 0000000..28d18da --- /dev/null +++ b/devcontainer.json @@ -0,0 +1,28 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": { + "files.trimTrailingWhitespace": true, + "cSpell.words": [ + "cmdlet", + "paule" + ] + }, + "extensions": { + "recommendations": [ + // for the powershell scripts + "ms-vscode.powershell", + // for the jupiter notebook integration for powershell + "ms-dotnettools.dotnet-interactive-vscode", + // for good language in the docs + "streetsidesoftware.code-spell-checker", + // for well formatted documentation + "docsmsft.docs-authoring-pack", + // for good language + "streetsidesoftware.code-spell-checker" + ] + } +} \ No newline at end of file From bb79e2da24bbb7f51e67758a1d148a2e76e24716 Mon Sep 17 00:00:00 2001 From: paule96 Date: Mon, 16 Aug 2021 12:36:17 +0200 Subject: [PATCH 20/62] Change devcontainer.json --- devcontainer.json | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/devcontainer.json b/devcontainer.json index 28d18da..e34ed2d 100644 --- a/devcontainer.json +++ b/devcontainer.json @@ -12,7 +12,6 @@ ] }, "extensions": { - "recommendations": [ // for the powershell scripts "ms-vscode.powershell", // for the jupiter notebook integration for powershell @@ -20,9 +19,6 @@ // for good language in the docs "streetsidesoftware.code-spell-checker", // for well formatted documentation - "docsmsft.docs-authoring-pack", - // for good language - "streetsidesoftware.code-spell-checker" - ] + "docsmsft.docs-authoring-pack" } } \ No newline at end of file From 827fda538d4697cbc3182b9c5e5fc620858f7e58 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Tue, 12 Oct 2021 22:43:01 +0200 Subject: [PATCH 21/62] improve linux environment support --- src/Set-ProxyConfiguration.ps1 | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index cfefcd3..e64c00d 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -13,7 +13,6 @@ function Set-ProxyConfiguration { Write-Debug $proxySettings; if ($proxySettings.UseSystemProxyAddress -and [string]::IsNullOrWhiteSpace($proxySettings.ProxyAddress)) { if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { - $proxySettings.ProxyAddress = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer; } else { @@ -413,14 +412,32 @@ function Set-EnvironmentProxyConfiguration { else { if ($NoRoot) { Write-Warning "Currently to set the environment this script needs root rights. Didn't change any environment varables."; + # TODO: add user proxy settings for this case. + } else { # Set environment for all users - "export http_proxy=`"$($Settings.ProxyAddress)`" - export no_proxy=`"$($Settings.BypassList -join ',')`" - export HTTP_PROXY=$($Settings.ProxyAddress) - export https_proxy=$($Settings.ProxyAddress) - export HTTPS_PROXY=$($Settings.ProxyAddress)" | Set-Content /etc/profile.d/proxy.sh; + $proxyshFilePath = "/etc/profile.d/proxy.sh"; + if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { + # Remove this content from the file, because a line with: + # `something=` + # is an error for some tools. So the lines must be empty + if(Test-Path -Path $proxyshFilePath){ + Remove-Item -Path "/etc/profile.d/proxy.sh" -Force; + Write-Verbose "$proxyshFilePath deleted. Proxy settings are resetted."; + } + else{ + Write-Verbose "$proxyshFilePath didn't exsist. Nothing changed."; + } + + } + else { + "export http_proxy=`"$($Settings.ProxyAddress)`" + export no_proxy=`"$($Settings.BypassList -join ',')`" + export HTTP_PROXY=$($Settings.ProxyAddress) + export https_proxy=$($Settings.ProxyAddress) + export HTTPS_PROXY=$($Settings.ProxyAddress)" | Set-Content -Path $proxyshFilePath; + } } } } From b966faaff58f488aabadfb53554e37fec8b9313b Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Tue, 12 Oct 2021 22:43:36 +0200 Subject: [PATCH 22/62] improve samples --- samples/basic.proxy.config.json | 2 +- samples/basic.systemproxy.json | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 samples/basic.systemproxy.json diff --git a/samples/basic.proxy.config.json b/samples/basic.proxy.config.json index 36d6971..bef6858 100644 --- a/samples/basic.proxy.config.json +++ b/samples/basic.proxy.config.json @@ -1,5 +1,5 @@ { - "ProxyAddress": "http://proxy.codez.one:8080", + "ProxyAddress": "http://proxy.codez.one:80", "BypassList": [ "git.codez.one" ] diff --git a/samples/basic.systemproxy.json b/samples/basic.systemproxy.json new file mode 100644 index 0000000..37ce968 --- /dev/null +++ b/samples/basic.systemproxy.json @@ -0,0 +1,3 @@ +{ + "UseSystemProxyAddress": true +} \ No newline at end of file From e5bb1626891a056e003f1bb59df093125648caba Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Tue, 12 Oct 2021 22:44:30 +0200 Subject: [PATCH 23/62] add tests for set-proxy function. - this brings test abilitiy for linux and windows --- tests/Set-ProxyConfiguration.tests.ps1 | 36 +++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index bce0c94..2f97acf 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -1,4 +1,6 @@ Describe "Set-ProxyConfiguration" { + $skipBecauseLinux = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $false; + $skipBecauseWindows = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $true; BeforeAll { $fileInfo = Get-ChildItem $PSScriptRoot; $functionName = $fileInfo.Name.Split('.')[0]; @@ -56,13 +58,13 @@ Describe "Set-ProxyConfiguration" { Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; Assert-MockCalled Set-GitProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) }; - Assert-MockCalled Set-NpmProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses)}; + Assert-MockCalled Set-NpmProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) }; Assert-MockCalled Set-AptProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) -and $NoRoot -eq $false }; Assert-MockCalled Set-DockerProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) }; Assert-MockCalled Set-PowerShellProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) -and $NoRoot -eq $false }; Assert-MockCalled Set-EnvironmentProxyConfiguration -Times 1 -ParameterFilter { $Settings.BypassList.Contains($BypassAddresses) -and $NoRoot -eq $false }; } - It("It Should set the Proxy with the system settings on windows") { + It("It Should set the Proxy with the system settings on windows") -Skip:($skipBecauseLinux) { # Arrange $ProxyAddress = 'http://proxy.codez.one:8080'; Mock -Verifiable Get-Content { return '{ @@ -80,14 +82,40 @@ Describe "Set-ProxyConfiguration" { #Assert Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; - Assert-MockCalled Get-ItemProperty -Times 1 -ParameterFilter { $Path -eq 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'}; + Assert-MockCalled Get-ItemProperty -Times 1 -ParameterFilter { $Path -eq 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' }; Assert-MockCalled Set-GitProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; - Assert-MockCalled Set-NpmProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress}; + Assert-MockCalled Set-NpmProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; Assert-MockCalled Set-AptProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; Assert-MockCalled Set-DockerProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress }; Assert-MockCalled Set-PowerShellProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; Assert-MockCalled Set-EnvironmentProxyConfiguration -Times 1 -ParameterFilter { $Settings.ProxyAddress -eq $ProxyAddress -and $NoRoot -eq $false }; } } + Context "When Set-ProxyConfiguration is not okay and" { + It("It Should write an error if the config file doesn't exsists.") { + Mock -Verifiable Test-Path { + return $false; + }; + $configPath = "something/that/not/exsists"; + # Act & assert + { Set-ProxyConfiguration -ConfigPath "$configPath" } | Should -Throw "The config path doesn't exsists."; + Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; + + } + It("It Should write an error if it wants to use system proxy on linux.") -Skip:($skipBecauseWindows) { + Mock -Verifiable Test-Path { + return $true; + }; + Mock -Verifiable Get-Content { return '{ + "UseSystemProxyAddress": true + }' + } + $configPath = "something/that/not/exsists"; + # Act & assert + { Set-ProxyConfiguration -ConfigPath "$configPath" } | Should -Throw "Currently we don't support linux, to read out the system proxy. Please configure it manualy"; + Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; + Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; + } + } } } \ No newline at end of file From 3934a19cacd441ebaceb6b05bac8b7b79f4f75bb Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Tue, 12 Oct 2021 22:44:51 +0200 Subject: [PATCH 24/62] add test pester extension to the workspace file --- CZ.PowerShell.NetworkTools.code-workspace | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CZ.PowerShell.NetworkTools.code-workspace b/CZ.PowerShell.NetworkTools.code-workspace index 28d18da..6fbec76 100644 --- a/CZ.PowerShell.NetworkTools.code-workspace +++ b/CZ.PowerShell.NetworkTools.code-workspace @@ -22,7 +22,9 @@ // for well formatted documentation "docsmsft.docs-authoring-pack", // for good language - "streetsidesoftware.code-spell-checker" + "streetsidesoftware.code-spell-checker", + // for pester tests + "pspester.pester-test" ] } } \ No newline at end of file From 9f5b7cef072d15206f4ee545a0eb891a8d0a4e28 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 00:13:22 +0200 Subject: [PATCH 25/62] improve comment in set proxy --- src/Set-ProxyConfiguration.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index e64c00d..f927d07 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -73,7 +73,7 @@ function Set-GitProxyConfiguration { } } - # remove old entries: + # remove old bypasses entries: # http . "git" "config" "--global" "--get-regexp" "http\.http" | ForEach-Object { $bypasskey = $_.Trim(); From 446e7ee160b37f74f9041631e643cdc29b93b289 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 00:13:47 +0200 Subject: [PATCH 26/62] add first basic tests for set git proxy --- tests/Set-ProxyConfiguration.tests.ps1 | 43 ++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 2f97acf..9e1735f 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -118,4 +118,47 @@ Describe "Set-ProxyConfiguration" { } } } + Describe "the git function"{ + Context "When Set-GitProxyConfiguration is okay and"{ + It("'git' is undefined, it shouldn't throw an error."){ + Mock -Verifiable Get-Command { + Write-Error "not found"; + } + # act + Set-GitProxyConfiguration -Settings $null; + #assert + Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "git"}; + } + It("if no proxy should be setted, the proxy should be unset."){ + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable "git" { + if($args[2] -eq "--get-regexp"){ + if($args[3] -eq "http\.http"){ + "http.http://codez.one.proxy "; + }else{ + "https.https://codez.one.proxy "; + } + } + return; + } + # act + Set-GitProxyConfiguration -Settings $null; + #assert + Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "git"}; + ## reset proxy entries + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--unset" -and $args[3] -eq "http.proxy"}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--unset" -and $args[3] -eq "https.proxy"}; + ## reset bypass + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--get-regexp" -and $args[3] -eq "http\.http"}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--get-regexp" -and $args[3] -eq "https\.https"}; + ## the removed bypassed is trimmed and in the right way combined + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--unset" -and $args[3] -eq "http.http://codez.one.proxy"}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--unset" -and $args[3] -eq "https.https://codez.one.proxy"}; + ## at the end there should be not more then 6 calls + Assert-MockCalled "git" -Times 6 -Exactly; + } + } + } } \ No newline at end of file From 9e44ce743fc190fc779b01656c729dccac82acf3 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 10:45:46 +0200 Subject: [PATCH 27/62] fix a git version deteciton issue --- src/Set-ProxyConfiguration.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index f927d07..002e240 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -55,7 +55,7 @@ function Set-GitProxyConfiguration { $supportsWildcardHostnames = ((((git version) -split ' ')[2] -split '\.')[0] -ge 2) -and ((((git version) -split ' ')[2] -split '\.')[1] -ge 13); # set all new entries $Settings.BypassList | ForEach-Object { - if ($_ -contains '*' -and $supportsWildcardHostnames -eq $false) { + if ($_.Contains('*') -and $supportsWildcardHostnames -eq $false) { Write-Warning "Your git version is to old to support wild card hostnames. You must have version 2.13 or higher. We skip the hostname $_"; } else { From 60dd9ec30b722b4d126b1605922f034099374905 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 10:46:04 +0200 Subject: [PATCH 28/62] add all missing tests for set-gitproxy --- tests/Set-ProxyConfiguration.tests.ps1 | 83 ++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 9e1735f..ed9590f 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -124,10 +124,14 @@ Describe "Set-ProxyConfiguration" { Mock -Verifiable Get-Command { Write-Error "not found"; } + Mock -Verifiable "git" { + return; + } # act Set-GitProxyConfiguration -Settings $null; #assert Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "git"}; + Assert-MockCalled "git" -Exactly -Times 0; } It("if no proxy should be setted, the proxy should be unset."){ Mock -Verifiable Get-Command { @@ -159,6 +163,85 @@ Describe "Set-ProxyConfiguration" { ## at the end there should be not more then 6 calls Assert-MockCalled "git" -Times 6 -Exactly; } + It("a proxy configuration is required all git commands are running"){ + # arrange + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable "git" { + if($args[2] -eq "--get-regexp"){ + if($args[3] -eq "http\.http"){ + "http.http://not.okay.proxy "; + }else{ + "https.https://not.okay.proxy "; + } + } + if($args[0] -eq "version"){ + return "git version 200.250.100" + } + return; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "http://codez.one", "https://codez.one"; + # act + Set-GitProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "git"}; + ## set proxy entries + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "http.proxy" -and $args[3] -eq $settings.ProxyAddress}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "https.proxy" -and $args[3] -eq $settings.ProxyAddress}; + ## set new bypass entries + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "http.http://codez.one.proxy"}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "https.https://codez.one.proxy"}; + ## reset old bypass + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--get-regexp" -and $args[3] -eq "http\.http"}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--get-regexp" -and $args[3] -eq "https\.https"}; + ## the removed bypassed is trimmed and in the right way combined + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--unset" -and $args[3] -eq "http.http://not.okay.proxy"}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "--unset" -and $args[3] -eq "https.https://not.okay.proxy"}; + ## git version is called + Assert-MockCalled "git" -Times 2 -Exactly -ParameterFilter {$args[0] -eq 'version'}; + ## at the end there should be not more then 6 calls + Assert-MockCalled "git" -Times 10 -Exactly; + } + It("bypass entry without protocoll is provided, it should set http and https"){ + # arrange + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable "git" { + return; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "codez.one"; + # act + Set-GitProxyConfiguration -Settings $settings; + ## set new bypass entries + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "http.http://codez.one.proxy"}; + Assert-MockCalled "git" -Times 1 -Exactly -ParameterFilter {$args[0] -eq 'config' -and $args[1] -eq "--global" -and $args[2] -eq "https.https://codez.one.proxy"}; + } + it("get version is to old for wildcard, it should warn the user."){ + # arrange + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable "git" { + if($args[0] -eq "version"){ + return "git version 2.0.100" + } + return; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one"; + # act + Set-GitProxyConfiguration -Settings $settings -WarningVariable warning; + # assert + $warning | Should -Be "Your git version is to old to support wild card hostnames. You must have version 2.13 or higher. We skip the hostname $($settings.BypassList[0])" + } + ## TODO: add tests if the bypass list isn't clean } } } \ No newline at end of file From 818e569b27503ba6d877b9e74fcc67047c72bc46 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 10:48:26 +0200 Subject: [PATCH 29/62] cleanup some test lines --- tests/Set-ProxyConfiguration.tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index ed9590f..23785d0 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -133,7 +133,7 @@ Describe "Set-ProxyConfiguration" { Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "git"}; Assert-MockCalled "git" -Exactly -Times 0; } - It("if no proxy should be setted, the proxy should be unset."){ + It("no proxy should be setted, the proxy should be unset."){ Mock -Verifiable Get-Command { return "not null"; } @@ -241,7 +241,7 @@ Describe "Set-ProxyConfiguration" { # assert $warning | Should -Be "Your git version is to old to support wild card hostnames. You must have version 2.13 or higher. We skip the hostname $($settings.BypassList[0])" } - ## TODO: add tests if the bypass list isn't clean } + ## TODO: add tests if the bypass list isn't clean } } \ No newline at end of file From 175e8b9a413f301b9189ee922a2b6b9dad7d58dd Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 11:22:05 +0200 Subject: [PATCH 30/62] add tests for full coverage for npm --- tests/Set-ProxyConfiguration.tests.ps1 | 71 ++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 23785d0..da6db7e 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -244,4 +244,75 @@ Describe "Set-ProxyConfiguration" { } ## TODO: add tests if the bypass list isn't clean } + Describe "the npm function"{ + Context "When Set-NpmProxyConfiguration is okay and"{ + It("'npm' is undefined, it shouldn't throw an error."){ + Mock -Verifiable Get-Command { + Write-Error "not found"; + } + Mock -Verifiable "npm" { + return; + } + # act + Set-NpmProxyConfiguration -Settings $null; + #assert + Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "npm"}; + Assert-MockCalled "npm" -Exactly -Times 0; + } + It("wsl is active and npm on the path, is the windows npm, it should write an warning."){ + Mock -Verifiable Get-Command { + return [pscustomobject]@{Path = "/mnt/c/Program Files/nodejs/npm"}; + } + Mock -Verifiable "npm" { + return; + } + # act + Set-NpmProxyConfiguration -Settings $null -WarningVariable warning; + #assert + Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "npm"}; + $warning | Should -Be ("In WSL2 you must override your environment variables to the linux version of NPM. " + ` + "We can't currently configure NPM for you."); + Assert-MockCalled "npm" -Exactly -Times 0; + } + It("no proxy setting is defined, it should reset all npm proxy settings."){ + Mock -Verifiable Get-Command { + return [pscustomobject]@{Path = "something"}; + } + Mock -Verifiable "npm" { + return; + } + # act + Set-NpmProxyConfiguration -Settings $null -WarningVariable warning; + #assert + Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "npm"}; + ## remove all proxy settings + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "delete" -and $args[2] -eq "proxy"}; + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "delete" -and $args[2] -eq "https-proxy"}; + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "delete" -and $args[2] -eq "no-proxy"}; + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "delete" -and $args[2] -eq "noproxy"}; + Assert-MockCalled "npm" -Exactly -Times 4; + } + It("and proxy settings are defined, it should set all npm proxy settings."){ + Mock -Verifiable Get-Command { + return [pscustomobject]@{Path = "something"}; + } + Mock -Verifiable "npm" { + return; + } + # act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + Set-NpmProxyConfiguration -Settings $settings -WarningVariable warning; + #assert + Assert-MockCalled Get-Command -Times 1 -ParameterFilter {$Name -eq "npm"}; + ## remove all proxy settings + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "set" -and $args[2] -eq "proxy" -and $args[3] -eq $settings.ProxyAddress}; + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "set" -and $args[2] -eq "https-proxy" -and $args[3] -eq $settings.ProxyAddress}; + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "set" -and $args[2] -eq "no-proxy" -and $args[3] -eq $(($settings.BypassList -join ',').Trim())}; + Assert-MockCalled "npm" -Times 1 -ParameterFilter {$args[0] -eq "config" -and $args[1] -eq "set" -and $args[2] -eq "noproxy" -and $args[3] -eq $(($settings.BypassList -join ',').Trim())}; + Assert-MockCalled "npm" -Exactly -Times 4; + } + } + } } \ No newline at end of file From 49270164da939c3278bb6f90f3db6107257a1ae8 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 15:36:45 +0200 Subject: [PATCH 31/62] fix regex bugs in apt get --- src/Set-ProxyConfiguration.ps1 | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index 002e240..9195e1f 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -139,6 +139,7 @@ function Set-NpmProxyConfiguration { } function Set-AptProxyConfiguration { + [CmdletBinding()] param ( [ProxySetting] $Settings, @@ -160,19 +161,25 @@ function Set-AptProxyConfiguration { } else { $isAProxyAlreadConfigured = $null -ne (. "apt-config" "dump" "Acquire::http::proxy"); + $regexOptions = [System.Text.RegularExpressions.RegexOptions]([System.Text.RegularExpressions.RegexOptions]::Multiline); + $regexSimplePattern = "Acquire::http::Proxy .*;"; + $regexComplexPattern = "(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy "".+"";)((.|\n)*}(.|\n)*})$"; + $regexSimple = New-Object System.Text.RegularExpressions.Regex $regexSimplePattern, $regexOptions; + $regexComplex = New-Object System.Text.RegularExpressions.Regex $regexComplexPattern, $regexOptions; if ($isAProxyAlreadConfigured) { $aptConfig = Get-Content "/etc/apt/apt.conf"; if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { # delete proxy config - $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', ""; - $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}`${5}"; + $aptConfig = $regexSimple.Replace($aptConfig, ""); + $aptConfig = $regexComplex.Replace($aptConfig, "`${1}`${5}"); } else { # add proxy config - $aptConfig = "$aptConfig" -replace 'Acquire::http::Proxy .*;', "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"; - $aptConfig = "$aptConfig" -replace '(^Acquire.*{(.|\n)*http.*{(.|\n)*)(proxy ".+";)((.|\n)*}(.|\n)*})$', "`${1}Proxy `"$($Settings.ProxyAddress)`";`${5}"; + $aptConfig = $regexSimple.Replace($aptConfig, "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";"); + $aptConfig = $regexComplex.Replace($aptConfig, "`${1}Proxy `"$($Settings.ProxyAddress)`";`${5}"); } # replace the file with new content + Write-Warning $aptConfig; $aptConfig | Set-Content "/etc/apt/apt.conf"; } else { @@ -182,9 +189,8 @@ function Set-AptProxyConfiguration { } else { # if no proxy is configured just append the line - "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Add-Content -Encoding ascii -NoNewline - >> "/etc/apt/apt.conf"; + "Acquire::http::Proxy ""$($Settings.ProxyAddress)"";" | Add-Content -Encoding ascii -NoNewline -Path "/etc/apt/apt.conf"; } - } } if ($null -ne $Settings.BypassList -and $Settings.BypassList.Count -ne 0) { @@ -197,7 +203,7 @@ function Set-AptProxyConfiguration { return; } else { - Write-Error "You must be root to change APT settings." -TargetObject $_ -RecommendedAction "Run powershell as root or specify the `NoRoot` switch."; + Write-Error "You must be root to change APT settings." -TargetObject $_ -RecommendedAction "Run powershell as root or specify the `NoRoot` switch." -ErrorAction Stop; return; } } From ba5dbf19a41888d132349e081276cd9d8e283bb8 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 15:37:00 +0200 Subject: [PATCH 32/62] add apt tests --- tests/Set-ProxyConfiguration.tests.ps1 | 262 +++++++++++++++++++++++++ 1 file changed, 262 insertions(+) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index da6db7e..e01620e 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -315,4 +315,266 @@ Describe "Set-ProxyConfiguration" { } } } + Describe "the apt function"{ + Context "When Set-AptProxyConfiguration is okay and" -Skip:($skipBecauseWindows) { + It("'apt' is undefined, it shouldn't throw an error"){ + # arrage + Mock -Verifiable Get-Command { + Write-Error "not found"; + } + #act + Set-AptProxyConfiguration -Settings $null; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + } + It("no config exsists and no proxy are required, do nothing."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable Set-Content { + return; + } + #act + Set-AptProxyConfiguration -Settings $null; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + Assert-MockCalled Set-Content -Times 0 -Exactly; + } + It("no config exsists and a proxy is required, write the config."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable Set-Content { + return; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + Set-AptProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Value -eq "Acquire::http::Proxy ""$($settings.ProxyAddress)"";"}; + } + It("no config exsists and a proxy with bypass is required, write a warning that bypass is not support by apt."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable Set-Content { + return; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + Set-AptProxyConfiguration -Settings $settings -WarningVariable warning; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Value -eq "Acquire::http::Proxy ""$($settings.ProxyAddress)"";"}; + $warning | Should -Be "apt-get don't support bypass list. To bypassing the proxy config for a given command starts the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; + } + It("config exsists but is empty and a proxy is required, write the config."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Add-Content { + return; + } + Mock -Verifiable "apt-config" { + return $null; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + Set-AptProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + Assert-MockCalled "apt-config" -Times 1 -Exactly -ParameterFilter {$Args[0] -eq "dump" -and $Args[1] -eq "Acquire::http::proxy"}; + Assert-MockCalled Add-Content -Times 1 -Exactly -ParameterFilter {$Value -eq "Acquire::http::Proxy ""$($settings.ProxyAddress)"";" -and $Encoding -eq [System.Text.Encoding]::ASCII}; + } + It("config exsists but is empty and a no proxy is required, do nothing."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Add-Content { + return; + } + Mock -Verifiable "apt-config" { + return $null; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = $null; + Set-AptProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + Assert-MockCalled "apt-config" -Times 1 -Exactly -ParameterFilter {$Args[0] -eq "dump" -and $Args[1] -eq "Acquire::http::proxy"}; + Assert-MockCalled Add-Content -Times 0 -Exactly; + } + It("config exsists but isn't empty and a no proxy is required, clean up the proxy settings."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Get-Content { + return "Acquire::http::Proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "Acquire {" + [System.Environment]::NewLine + + "http {" + [System.Environment]::NewLine + + "proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "}" + [System.Environment]::NewLine + + "}"; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable "apt-config" { + return "something"; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = $null; + Set-AptProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + Assert-MockCalled "apt-config" -Times 1 -Exactly -ParameterFilter {$Args[0] -eq "dump" -and $Args[1] -eq "Acquire::http::proxy"}; + Assert-MockCalled Get-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + $resultAptConf = [System.Environment]::NewLine + + "Acquire {" + [System.Environment]::NewLine + + "http {" + [System.Environment]::NewLine + + [System.Environment]::NewLine + + "}" + [System.Environment]::NewLine + + "}"; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Value -eq $resultAptConf}; + } + It("config exsists and isn't empty and a proxy is required, reset the proxy settings."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Get-Content { + return "Acquire::http::Proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "Acquire {" + [System.Environment]::NewLine + + "http {" + [System.Environment]::NewLine + + "proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "}" + [System.Environment]::NewLine + + "}"; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable "apt-config" { + return "something"; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + Set-AptProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + Assert-MockCalled "apt-config" -Times 1 -Exactly -ParameterFilter {$Args[0] -eq "dump" -and $Args[1] -eq "Acquire::http::proxy"}; + Assert-MockCalled Get-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + $resultAptConf = "Acquire::http::Proxy ""http://proxy.codez.one:8080"";" + [System.Environment]::NewLine + + "Acquire {" + [System.Environment]::NewLine + + "http {" + [System.Environment]::NewLine + + "proxy ""http://proxy.codez.one:8080"";" + [System.Environment]::NewLine + + "}" + [System.Environment]::NewLine + + "}"; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Value -eq $resultAptConf}; + } + It("user aren't root, but know it, do nothing."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + throw [System.UnauthorizedAccessException] "Your are not root"; + return $true; + } + Mock -Verifiable Get-Content { + return "Acquire::http::Proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "Acquire {" + [System.Environment]::NewLine + + "http {" + [System.Environment]::NewLine + + "proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "}" + [System.Environment]::NewLine + + "}"; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable "apt-config" { + return "something"; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + Set-AptProxyConfiguration -Settings $settings -NoRoot; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + } + It("user aren't root, but don't know it, show an error."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + throw [System.UnauthorizedAccessException] "Your are not root"; + return $true; + } + Mock -Verifiable Get-Content { + return "Acquire::http::Proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "Acquire {" + [System.Environment]::NewLine + + "http {" + [System.Environment]::NewLine + + "proxy ""http://old.proxy:80"";" + [System.Environment]::NewLine + + "}" + [System.Environment]::NewLine + + "}"; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable "apt-config" { + return "something"; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + + #act & assert + {Set-AptProxyConfiguration -Settings $settings} | Should -Throw "You must be root to change APT settings."; + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; + } + } + } } \ No newline at end of file From 3e20b87ba792415c733957dc25d87f2441fb7ef3 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 15:39:59 +0200 Subject: [PATCH 33/62] cmdlet binding is important!1!! --- src/Set-ProxyConfiguration.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index 9195e1f..f454709 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -212,6 +212,7 @@ function Set-AptProxyConfiguration { } function Set-DockerProxyConfiguration { + [CmdletBinding()] param ( [ProxySetting] $Settings @@ -263,6 +264,7 @@ function Set-DockerProxyConfiguration { } function Set-PowerShellProxyConfiguration { + [CmdletBinding()] param ( [ProxySetting] $Settings, From e14048a23182c7b47bd0ac081ff495a618932f28 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 20:20:17 +0200 Subject: [PATCH 34/62] make the docker settings more stable --- src/Set-ProxyConfiguration.ps1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index f454709..9015dc0 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -228,7 +228,7 @@ function Set-DockerProxyConfiguration { { "httpProxy": "' + $Settings.ProxyAddress + '", "httpsProxy": "' + $Settings.ProxyAddress + '", - "noProxy": "' + ($Settings.ProxyAddress -join ',') + '" + "noProxy": "' + ($Settings.BypassList -join ',') + '" } } }'; @@ -240,11 +240,11 @@ function Set-DockerProxyConfiguration { $dockerConfig.PSobject.Properties.Remove('proxies'); } elseif ($false -eq [bool]($dockerConfig.PSobject.Properties.name -match "proxies")) { - $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig -TypeName $json; + $dockerConfig | Add-Member -MemberType NoteProperty -Name "proxies" -Value $proxyConfig.proxies; } elseif ($false -eq [bool]($dockerConfig.proxies.PSobject.Properties.name -match "default")) { - $dockerConfig | Add-Member -NotePropertyMembers $proxyConfig.proxies -TypeName $json; + $dockerConfig.proxies | Add-Member -MemberType NoteProperty -Name "default" -Value $proxyConfig.proxies.default; } else { $dockerConfig.proxies.default | Add-Member -NotePropertyName "httpProxy" -NotePropertyValue $Settings.ProxyAddress -Force From a15b9872f14c41fddece7ae3cea8d69316d7cc55 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Wed, 13 Oct 2021 20:20:34 +0200 Subject: [PATCH 35/62] add all docker tests --- tests/Set-ProxyConfiguration.tests.ps1 | 199 +++++++++++++++++++++++++ 1 file changed, 199 insertions(+) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index e01620e..bfdf8b6 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -577,4 +577,203 @@ Describe "Set-ProxyConfiguration" { } } } + Describe "the docker function" { + Context "When Set-DockerProxyConfiguration is okay and" { + It("'docker' is undefined, it shouldn't throw an error"){ + # arrage + Mock -Verifiable Get-Command { + Write-Error "not found"; + } + #act + Set-DockerProxyConfiguration -Settings $null; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "docker"}; + } + It("no config exsists and no proxy are required, do nothing."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable Set-Content { + return; + } + #act + Set-DockerProxyConfiguration -Settings $null; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json"}; + Assert-MockCalled Set-Content -Times 0 -Exactly; + } + It("no config exsists and a proxy is required, write the config."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable New-Item{ + return; + } + #act + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + Set-DockerProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json"}; + Assert-MockCalled New-Item -Times 1 -Exactly -ParameterFilter {$ItemType -eq "Directory"}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json" -and ($Value | ConvertFrom-Json).proxies.default.httpProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.httpsProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.noProxy -eq ($settings.BypassList -join ',')}; + } + It("config exsists and no proxy is required, reset proxy settings."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable New-Item{ + return; + } + Mock -Verifiable Get-Content{ + return '{ + "someProp": "someValue", + "proxies": + { + "default": + { + "httpProxy": "http://old.proxy:80", + "httpsProxy": "http://old.proxy:80", + "noProxy": "old, older" + } + } + }' + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = $null; + #act + Set-DockerProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json"}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json" -and ($Value | ConvertFrom-Json).PsObject.Properties.name -notmatch "proxies" -and ($Value | ConvertFrom-Json).someProp -eq "someValue"}; + } + It("config exsists without proxy config and a proxy is required, set proxy settings."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable New-Item{ + return; + } + Mock -Verifiable Get-Content{ + return '{ + "someProp": "someValue" + }' + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-DockerProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json"}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json" -and ($Value | ConvertFrom-Json).proxies.default.httpProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.httpsProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.noProxy -eq ($settings.BypassList -join ',') -and ($Value | ConvertFrom-Json).someProp -eq "someValue"}; + } + It("config exsists with proxy config but without default config and a proxy is required, reset proxy settings."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable New-Item{ + return; + } + Mock -Verifiable Get-Content{ + return '{ + "someProp": "someValue", + "proxies": + { + "def": + { + "httpProxy": "http://old.proxy:80", + "httpsProxy": "http://old.proxy:80", + "noProxy": "old, older" + } + } + }' + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-DockerProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json"}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json" -and ($Value | ConvertFrom-Json).proxies.default.httpProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.httpsProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.noProxy -eq ($settings.BypassList -join ',') -and ($Value | ConvertFrom-Json).someProp -eq "someValue"}; + } + It("config exsists with proxy config and a proxy is required, reset proxy settings."){ + # arrage + Mock -Verifiable Get-Command { + return "not null"; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Set-Content { + return; + } + Mock -Verifiable New-Item{ + return; + } + Mock -Verifiable Get-Content{ + return '{ + "someProp": "someValue", + "proxies": + { + "default": + { + "httpProxy": "http://old.proxy:80", + "httpsProxy": "http://old.proxy:80", + "noProxy": "old, older" + } + } + }' + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-DockerProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly; + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json"}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "~/.docker/config.json" -and ($Value | ConvertFrom-Json).proxies.default.httpProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.httpsProxy -eq $settings.ProxyAddress -and ($Value | ConvertFrom-Json).proxies.default.noProxy -eq ($settings.BypassList -join ',') -and ($Value | ConvertFrom-Json).someProp -eq "someValue"}; + } + } + } } \ No newline at end of file From 758974e3509eeb37c91a5be90adb9b6f1a65d325 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 19:46:16 +0200 Subject: [PATCH 36/62] fix powershell bypasslist and make changes less often to the config --- src/Set-ProxyConfiguration.ps1 | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index 9015dc0..673dd30 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -275,6 +275,14 @@ function Set-PowerShellProxyConfiguration { Write-Verbose "You can't set a proxy for powershell 5 / 7 without admin / root rights. On Windows try to set IE Settings if this is possible."; return; } + if ($Settings.BypassList -ne $null -and $Settings.BypassList.Count -gt 0) { + $bypasslist = ' + '+ ( + (($Settings.BypassList | ForEach-Object { " " }) -join [System.Environment]::NewLine) + ) + ' + '; + } + $proxyConfig = ' @@ -283,11 +291,7 @@ function Set-PowerShellProxyConfiguration { proxyaddress="'+ $Settings.ProxyAddress + '" bypassonlocal="true" /> - - '+ ( - (($Settings.BypassList | ForEach-Object { " " }) -join [System.Environment]::NewLine) - ) + ' - + '+ $bypasslist + ' '; @@ -302,6 +306,11 @@ function Set-PowerShellProxyConfiguration { ) $configPath = "$powershellPath.config"; + if ((Test-Path $configPath) -eq $false -and [string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { + # do nothing, if the config isn't exsist and no proxy is required. + return + } + #create file if it isn't exsists if ((Test-Path $configPath) -eq $false) { # set acls for windows if ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) { @@ -427,14 +436,14 @@ function Set-EnvironmentProxyConfiguration { # Set environment for all users $proxyshFilePath = "/etc/profile.d/proxy.sh"; if ([string]::IsNullOrWhiteSpace($Settings.ProxyAddress)) { - # Remove this content from the file, because a line with: - # `something=` - # is an error for some tools. So the lines must be empty - if(Test-Path -Path $proxyshFilePath){ + # Remove this content from the file, because a line with: + # `something=` + # is an error for some tools. So the lines must be empty + if (Test-Path -Path $proxyshFilePath) { Remove-Item -Path "/etc/profile.d/proxy.sh" -Force; Write-Verbose "$proxyshFilePath deleted. Proxy settings are resetted."; } - else{ + else { Write-Verbose "$proxyshFilePath didn't exsist. Nothing changed."; } From 2a696c552d75a8afcd2a3c88be3b6076b83bce09 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 19:46:26 +0200 Subject: [PATCH 37/62] add all powershell tests --- tests/Set-ProxyConfiguration.tests.ps1 | 308 +++++++++++++++++++++++++ 1 file changed, 308 insertions(+) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index bfdf8b6..952a9c5 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -776,4 +776,312 @@ Describe "Set-ProxyConfiguration" { } } } + Describe "the powershell function" { + Context "When Set-PowerShellProxyConfiguration is okay and" -Skip:($skipBecauseWindows){ + It("user aren't root, but know it, do nothing."){ + # arrage + Mock -Verifiable Get-Command { + } + Mock -Verifiable Test-Path { + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + #act + Set-PowerShellProxyConfiguration -Settings $settings -NoRoot; + # assert + Assert-MockCalled Get-Command -Times 0 -Exactly; + Assert-MockCalled Test-Path -Times 0 -Exactly; + } + It("'pwsh' and 'powershell' isn't there, do nothing."){ + # arrage + Mock -Verifiable Get-Command { + Write-Error "not found"; + } + Mock -Verifiable Test-Path { + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 0 -Exactly; + } + It("no config exsists and no proxy are required, do nothing."){ + # arrage + Mock -Verifiable Get-Command { + return [pscustomobject]@{Path = "something"}; + } + Mock -Verifiable Test-Path { + return $false; + } + $settings = [ProxySetting](New-Object ProxySetting); + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 2 -Exactly -ParameterFilter {$Path -eq "something.config"}; + } + It("no config exsists and a proxy is required, write the config."){ + # arrage + Mock -Verifiable Get-Command { + return [pscustomobject]@{Path = "something"}; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable New-Item { + return; + } + Mock -Verifiable Get-Content { + return $null; + } + Mock -Verifiable Set-Content { + return ""; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 4 -Exactly -ParameterFilter {$Path -eq "something.config"}; + Assert-MockCalled New-Item -Times 2 -Exactly -ParameterFilter {$Path -eq "something.config" -and $ItemType -eq "File"}; + Assert-MockCalled Get-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "something.config"}; + Assert-MockCalled Set-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "something.config" -and ([xml]$Value).configuration["system.net"].defaultProxy.proxy.proxyaddress -eq $settings.ProxyAddress -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist -eq $null}; + + } + It("a proxy and a bypasslist is required, write both to the config."){ + # arrage + Mock -Verifiable Get-Command { + return [pscustomobject]@{Path = "something"}; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable New-Item { + return; + } + Mock -Verifiable Get-Content { + return $null; + } + Mock -Verifiable Set-Content { + return ""; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 4 -Exactly -ParameterFilter {$Path -eq "something.config"}; + Assert-MockCalled New-Item -Times 2 -Exactly -ParameterFilter {$Path -eq "something.config" -and $ItemType -eq "File"}; + Assert-MockCalled Get-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "something.config"}; + Assert-MockCalled Set-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "something.config" -and ([xml]$Value).configuration["system.net"].defaultProxy.proxy.proxyaddress -eq $settings.ProxyAddress -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[0].address -eq $settings.BypassList[0] -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[1].address -eq $settings.BypassList[1]}; + } + It("config is already exsists but is empty a proxy and a bypasslist is required, write both to the config"){ + # arrage + Mock -Verifiable Get-Command { + # use testdrive here, because the XML function save will use it. + return [pscustomobject]@{Path = "$TestDrive/something"}; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable New-Item { + return; + } + Mock -Verifiable Get-Content { + return ''; + } + Mock -Verifiable Set-Content { + return ""; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled New-Item -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and $ItemType -eq "File"}; + Assert-MockCalled Get-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled Set-Content -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and ([xml]$Value).configuration["system.net"].defaultProxy.proxy.proxyaddress -eq $settings.ProxyAddress -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[0].address -eq $settings.BypassList[0] -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[1].address -eq $settings.BypassList[1]}; + } + It("config is already used a proxy and a bypasslist is required, write both to the config, without destroying exsisting configuration."){ + # arrage + Mock -Verifiable Get-Command { + # use testdrive here, because the XML function save will use it. + return [pscustomobject]@{Path = "$TestDrive/something"}; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable New-Item { + return; + } + Mock -Verifiable Get-Content { + return ' + testvalue + '; + } + Mock -Verifiable Set-Content { + return ""; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled New-Item -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and $ItemType -eq "File"}; + Assert-MockCalled Get-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled Set-Content -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and ([xml]$Value).configuration["system.net"].defaultProxy.proxy.proxyaddress -eq $settings.ProxyAddress -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[0].address -eq $settings.BypassList[0] -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[1].address -eq $settings.BypassList[1]}; + ([xml](Get-Content TestDrive:/something.config)).configuration.someconfig | Should -Be "testvalue"; + } + It("config is already used a proxy and a bypasslist is required, write both to the config, without destroying exsisting configuration.system.net."){ + # arrage + Mock -Verifiable Get-Command { + # use testdrive here, because the XML function save will use it. + return [pscustomobject]@{Path = "$TestDrive/something"}; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable New-Item { + return; + } + Mock -Verifiable Get-Content { + return ' + + testvalue + + '; + } + Mock -Verifiable Set-Content { + return ""; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled New-Item -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and $ItemType -eq "File"}; + Assert-MockCalled Get-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled Set-Content -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and ([xml]$Value).configuration["system.net"].defaultProxy.proxy.proxyaddress -eq $settings.ProxyAddress -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[0].address -eq $settings.BypassList[0] -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[1].address -eq $settings.BypassList[1]}; + ([xml](Get-Content TestDrive:/something.config)).configuration["system.net"].someconfig | Should -Be "testvalue"; + } + It("config had alread proxy, but enother proxy and bypasslist is required, write both to the config, and remove the old one"){ + # arrage + Mock -Verifiable Get-Command { + # use testdrive here, because the XML function save will use it. + return [pscustomobject]@{Path = "$TestDrive/something"}; + } + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable New-Item { + return; + } + Mock -Verifiable Get-Content { + return ' + + + + + + + + + '; + } + Mock -Verifiable Set-Content { + return ""; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + $settings.BypassList = "*.codez.one", "codez.one"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled New-Item -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and $ItemType -eq "File"}; + Assert-MockCalled Get-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled Set-Content -Times 0 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and ([xml]$Value).configuration["system.net"].defaultProxy.proxy.proxyaddress -eq $settings.ProxyAddress -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[0].address -eq $settings.BypassList[0] -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist.add[1].address -eq $settings.BypassList[1]}; + } + } + Context "When Set-PowerShellProxyConfiguration is running in Windows and" -Skip:($skipBecauseLinux) { + It("no config exsists and a proxy is required, write the config."){ + # arrage + $defaultAcl = (New-Object System.Security.AccessControl.DirectorySecurity); + Mock -Verifiable Get-Command { + return [pscustomobject]@{Path = "$TestDrive/something"}; + } + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable New-Item { + return; + } + Mock -Verifiable Get-Item { + return ([pscustomobject]@{ + Directory = [pscustomobject]@{ + FullName = "$TestDrive" + } + }); + } + Mock -Verifiable Get-Content { + return $null; + } + Mock -Verifiable Set-Content { + return ""; + } + Mock -Verifiable Get-Acl { + return $defaultAcl; + } + Mock -Verifiable Set-Acl { + return; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + #act + Set-PowerShellProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "pwsh"}; + Assert-MockCalled Get-Command -Times 1 -Exactly -ParameterFilter {$Name -eq "powershell"}; + Assert-MockCalled Test-Path -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled New-Item -Times 2 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and $ItemType -eq "File"}; + Assert-MockCalled Get-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config"}; + Assert-MockCalled Set-Content -Times 2 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and ([xml]$Value).configuration["system.net"].defaultProxy.proxy.proxyaddress -eq $settings.ProxyAddress -and ([xml]$Value).configuration["system.net"].defaultProxy.bypasslist -eq $null}; + + ## make sure to set and reset folder acl + Assert-MockCalled Set-Acl -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive" -and $AclObject.Access.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq "S-1-5-32-544" -and $AclObject.Access.AccessControlType -eq "Allow"}; + Assert-MockCalled Set-Acl -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive" -and $AclObject -eq $defaultAcl}; + + ## make sure to set and reset file acl + Assert-MockCalled Set-Acl -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and $AclObject.Access.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq "S-1-5-32-544" -and $AclObject.Access.AccessControlType -eq "Allow"}; + Assert-MockCalled Set-Acl -Times 4 -Exactly -ParameterFilter {$Path -eq "$TestDrive/something.config" -and $AclObject -eq $defaultAcl}; + } + } + } } \ No newline at end of file From 749019669c93f52cd08b747016cb54d06b02ce16 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 20:19:25 +0200 Subject: [PATCH 38/62] write test for environment variables --- tests/Set-ProxyConfiguration.tests.ps1 | 58 ++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 952a9c5..5bb755c 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -1084,4 +1084,62 @@ Describe "Set-ProxyConfiguration" { } } } + Describe "the environment function" { + Context "When Set-EnvironmentProxyConfiguration is okay and" -Skip:($skipBecauseWindows){ + It("user aren't root, but know it, do nothing."){ + # arrage + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + #act + Set-EnvironmentProxyConfiguration -Settings $settings -NoRoot -WarningVariable warning; + # assert + $warning | Should -Be "Currently to set the environment this script needs root rights. Didn't change any environment varables."; + } + It("no config exsists and no proxy are required, do nothing."){ + # arrage + Mock -Verifiable Test-Path { + return $false; + } + Mock -Verifiable Remove-Item { + return $false; + } + $settings = [ProxySetting](New-Object ProxySetting); + #act + Set-EnvironmentProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/profile.d/proxy.sh"}; + Assert-MockCalled Remove-Item -Times 0 -Exactly -ParameterFilter {$Path -eq "/etc/profile.d/proxy.sh"}; + } + It("a proxy is required, write the config."){ + # arrage + Mock -Verifiable Set-Content { + return ; + } + $settings = [ProxySetting](New-Object ProxySetting); + $settings.ProxyAddress = "http://proxy.codez.one:8080"; + #act + Set-EnvironmentProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/profile.d/proxy.sh" -and ([string]$Value).Contains("export http_proxy=`"$($settings.ProxyAddress)`"") -and ([string]$Value).Contains("export https_proxy=`"$($settings.ProxyAddress)`"") -and ([string]$Value).Contains("export no_proxy=`"$($Settings.BypassList -join ',')`"") -and ([string]$Value).Contains("export HTTPS_PROXY=`"$($settings.ProxyAddress)`"") -and ([string]$Value).Contains("export HTTP_PROXY=`"$($settings.ProxyAddress)`"")}; + } + It("no proxy is required but config exsists, remove it."){ + # arrage + Mock -Verifiable Test-Path { + return $true; + } + Mock -Verifiable Remove-Item { + return; + } + $settings = [ProxySetting](New-Object ProxySetting); + #act + Set-EnvironmentProxyConfiguration -Settings $settings; + # assert + Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/profile.d/proxy.sh"}; + Assert-MockCalled Remove-Item -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/profile.d/proxy.sh"}; + } + } + Context "When Set-PowerShellProxyConfiguration is running in Windows and" -Skip:($skipBecauseLinux) { + # TODO: Can't test static dotnet calls. Needs a solution for this. + } + } } \ No newline at end of file From 58d1a492428df488a24a93c5d0a61f38ccc67b95 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 22:18:02 +0200 Subject: [PATCH 39/62] fix settings env variables linux --- src/Set-ProxyConfiguration.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index 673dd30..cded605 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -449,8 +449,8 @@ function Set-EnvironmentProxyConfiguration { } else { - "export http_proxy=`"$($Settings.ProxyAddress)`" - export no_proxy=`"$($Settings.BypassList -join ',')`" + "export http_proxy=$($Settings.ProxyAddress) + export no_proxy=$($Settings.BypassList -join ',') export HTTP_PROXY=$($Settings.ProxyAddress) export https_proxy=$($Settings.ProxyAddress) export HTTPS_PROXY=$($Settings.ProxyAddress)" | Set-Content -Path $proxyshFilePath; From 6b42bfb97e037a2fba935577cae8baf52111b627 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 22:21:25 +0200 Subject: [PATCH 40/62] fixing file finding for tests --- tests/Set-ProxyConfiguration.tests.ps1 | 10 +++++++--- tests/Test-ProxyConfiguration.tests.ps1 | 12 ++++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 5bb755c..df9a4cb 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -2,10 +2,13 @@ Describe "Set-ProxyConfiguration" { $skipBecauseLinux = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $false; $skipBecauseWindows = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $true; BeforeAll { - $fileInfo = Get-ChildItem $PSScriptRoot; + # load function to test + $fileInfo = Get-ChildItem $PSCommandPath; $functionName = $fileInfo.Name.Split('.')[0]; + $file = Get-ChildItem "$PSScriptRoot/../src/$functionName.ps1"; + $targetFileName = "$($file.FullName)"; # load function to test - . "$PSScriptRoot/../src/$functionName.ps1"; + . "$targetFileName"; } Describe "the main function" { @@ -1118,9 +1121,10 @@ Describe "Set-ProxyConfiguration" { $settings = [ProxySetting](New-Object ProxySetting); $settings.ProxyAddress = "http://proxy.codez.one:8080"; #act + Write-Warning "start"; Set-EnvironmentProxyConfiguration -Settings $settings; # assert - Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/profile.d/proxy.sh" -and ([string]$Value).Contains("export http_proxy=`"$($settings.ProxyAddress)`"") -and ([string]$Value).Contains("export https_proxy=`"$($settings.ProxyAddress)`"") -and ([string]$Value).Contains("export no_proxy=`"$($Settings.BypassList -join ',')`"") -and ([string]$Value).Contains("export HTTPS_PROXY=`"$($settings.ProxyAddress)`"") -and ([string]$Value).Contains("export HTTP_PROXY=`"$($settings.ProxyAddress)`"")}; + Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/profile.d/proxy.sh" -and ([string]$Value).Contains("export http_proxy=$($settings.ProxyAddress)") -and ([string]$Value).Contains("export https_proxy=$($settings.ProxyAddress)") -and ([string]$Value).Contains("export no_proxy=$($Settings.BypassList -join ',')") -and ([string]$Value).Contains("export HTTPS_PROXY=$($settings.ProxyAddress)") -and ([string]$Value).Contains("export HTTP_PROXY=$($settings.ProxyAddress)")}; } It("no proxy is required but config exsists, remove it."){ # arrage diff --git a/tests/Test-ProxyConfiguration.tests.ps1 b/tests/Test-ProxyConfiguration.tests.ps1 index e04a45d..0f67b00 100644 --- a/tests/Test-ProxyConfiguration.tests.ps1 +++ b/tests/Test-ProxyConfiguration.tests.ps1 @@ -1,9 +1,11 @@ Describe "Test-ProxyConfiguration" { BeforeAll { - $fileInfo = Get-ChildItem $PSScriptRoot; + $fileInfo = Get-ChildItem $PSCommandPath; $functionName = $fileInfo.Name.Split('.')[0]; + $file = Get-ChildItem "$PSScriptRoot/../src/$functionName.ps1"; + $targetFileName = "$($file.FullName)"; # load function to test - . "$PSScriptRoot/../src/$functionName.ps1"; + . "$targetFileName"; } Context "When Test-Connection is okay and" { BeforeEach { @@ -159,10 +161,12 @@ Describe "Test-ProxyConfiguration" { } Describe "ProxyTestResult" { BeforeAll { - $fileInfo = Get-ChildItem $PSScriptRoot; + $fileInfo = Get-ChildItem $PSCommandPath; $functionName = $fileInfo.Name.Split('.')[0]; + $file = Get-ChildItem "$PSScriptRoot/../src/$functionName.ps1"; + $targetFileName = "$($file.FullName)"; # load function to test - . "$PSScriptRoot/../src/$functionName.ps1"; + . "$targetFileName"; } Context 'everthing is perfect' { It 'It should print a good message, if the bypass list is used correct.' { From f0cdbb0fa629781b9a0edccc19584810cdabae8e Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 22:25:57 +0200 Subject: [PATCH 41/62] try to fix azure pipeline --- azure-pipelines.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 7bf5b15..b9b0d1b 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -47,12 +47,14 @@ steps: ArtifactName: 'drop' publishLocation: 'Container' - task: PublishTestResults@2 + condition: always() inputs: testResultsFormat: 'NUnit' testResultsFiles: 'testResults.xml' failTaskOnFailedTests: true testRunTitle: 'CZ.PowerShell.NetworkTools' - task: PublishCodeCoverageResults@1 + condition: always() inputs: codeCoverageTool: 'JaCoCo' summaryFileLocation: 'coverage.xml' From 45332334305ea6c3e4720926907b01698ad8aba2 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 22:38:52 +0200 Subject: [PATCH 42/62] try to make multi os build --- azure-pipelines.yml | 140 +++++++++++++++++++++++++++----------------- 1 file changed, 86 insertions(+), 54 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index b9b0d1b..37e6171 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -6,57 +6,89 @@ trigger: - main -pool: - vmImage: windows-latest - -steps: -- task: PowerShell@2 - displayName: "Run pester tests" - inputs: - targetType: 'inline' - script: | - Install-Module -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck Pester; - Import-Module Pester; - $configuration = [PesterConfiguration]::Default; - $configuration.CodeCoverage.Enabled = $true; - $configuration.CodeCoverage.Path = (Get-ChildItem src/*.ps1 | ForEach-Object{$_.FullName}); - $configuration.CodeCoverage.OutputFormat = "JaCoCo"; - $configuration.TestResult.Enabled = $true; - $configuration.Run.Exit = $true; - $configuration.Run.Path = (Get-ChildItem tests/*ps1 | ForEach-Object{$_.FullName}); - Invoke-Pester -Configuration $configuration; - showWarnings: true - pwsh: true -- task: PowerShell@2 - displayName: "Build the powershell package" - inputs: - filePath: 'build/build.ps1' - showWarnings: true - pwsh: true -- task: PowerShell@2 - displayName: "Debug files" - inputs: - targetType: 'inline' - script: | - ls -Recurse | select FullName; - showWarnings: true - pwsh: true -- task: PublishBuildArtifacts@1 - inputs: - PathtoPublish: 'src/bin/' - ArtifactName: 'drop' - publishLocation: 'Container' -- task: PublishTestResults@2 - condition: always() - inputs: - testResultsFormat: 'NUnit' - testResultsFiles: 'testResults.xml' - failTaskOnFailedTests: true - testRunTitle: 'CZ.PowerShell.NetworkTools' -- task: PublishCodeCoverageResults@1 - condition: always() - inputs: - codeCoverageTool: 'JaCoCo' - summaryFileLocation: 'coverage.xml' - pathToSources: 'src/' - failIfCoverageEmpty: true \ No newline at end of file +jobs: + - job: windows-test + pool: + vmImage: windows-latest + steps: + - task: PowerShell@2 + displayName: "Run pester tests" + inputs: + targetType: 'inline' + script: | + Install-Module -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck Pester; + Import-Module Pester; + $configuration = [PesterConfiguration]::Default; + $configuration.CodeCoverage.Enabled = $true; + $configuration.CodeCoverage.Path = (Get-ChildItem src/*.ps1 | ForEach-Object{$_.FullName}); + $configuration.CodeCoverage.OutputFormat = "JaCoCo"; + $configuration.TestResult.Enabled = $true; + $configuration.Run.Exit = $true; + $configuration.Run.Path = (Get-ChildItem tests/*ps1 | ForEach-Object{$_.FullName}); + Invoke-Pester -Configuration $configuration; + showWarnings: true + pwsh: true + - task: PublishTestResults@2 + condition: always() + inputs: + testResultsFormat: 'NUnit' + testResultsFiles: 'testResults.xml' + failTaskOnFailedTests: true + testRunTitle: 'CZ.PowerShell.NetworkTools' + - task: PublishCodeCoverageResults@1 + condition: always() + inputs: + codeCoverageTool: 'JaCoCo' + summaryFileLocation: 'coverage.xml' + pathToSources: 'src/' + failIfCoverageEmpty: true + - job: linux-test + pool: + vmImage: 'ubuntu-latest' + steps: + - task: PowerShell@2 + displayName: "Run pester tests" + inputs: + targetType: 'inline' + script: | + Install-Module -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck Pester; + Import-Module Pester; + $configuration = [PesterConfiguration]::Default; + $configuration.CodeCoverage.Enabled = $true; + $configuration.CodeCoverage.Path = (Get-ChildItem src/*.ps1 | ForEach-Object{$_.FullName}); + $configuration.CodeCoverage.OutputFormat = "JaCoCo"; + $configuration.TestResult.Enabled = $true; + $configuration.Run.Exit = $true; + $configuration.Run.Path = (Get-ChildItem tests/*ps1 | ForEach-Object{$_.FullName}); + Invoke-Pester -Configuration $configuration; + showWarnings: true + pwsh: true + - task: PublishTestResults@2 + condition: always() + inputs: + testResultsFormat: 'NUnit' + testResultsFiles: 'testResults.xml' + failTaskOnFailedTests: true + testRunTitle: 'CZ.PowerShell.NetworkTools' + - task: PublishCodeCoverageResults@1 + condition: always() + inputs: + codeCoverageTool: 'JaCoCo' + summaryFileLocation: 'coverage.xml' + pathToSources: 'src/' + failIfCoverageEmpty: true + - job: build-package + pool: + vmImage: windows-latest + steps: + - task: PowerShell@2 + displayName: "Build the powershell package" + inputs: + filePath: 'build/build.ps1' + showWarnings: true + pwsh: true + - task: PublishBuildArtifacts@1 + inputs: + PathtoPublish: 'src/bin/' + ArtifactName: 'drop' + publishLocation: 'Container' \ No newline at end of file From f93d0a341878184c475b8ce292c305e511979288 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 22:42:50 +0200 Subject: [PATCH 43/62] try to fix job names --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 37e6171..9c6e1e6 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -7,7 +7,7 @@ trigger: - main jobs: - - job: windows-test + - job: 'windows-test' pool: vmImage: windows-latest steps: @@ -42,7 +42,7 @@ jobs: summaryFileLocation: 'coverage.xml' pathToSources: 'src/' failIfCoverageEmpty: true - - job: linux-test + - job: 'linux-test' pool: vmImage: 'ubuntu-latest' steps: @@ -77,7 +77,7 @@ jobs: summaryFileLocation: 'coverage.xml' pathToSources: 'src/' failIfCoverageEmpty: true - - job: build-package + - job: 'build-package' pool: vmImage: windows-latest steps: From f02505b87856c8dd76d89b378074af1006e64500 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 22:45:14 +0200 Subject: [PATCH 44/62] try to fix job names again... --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9c6e1e6..85a419d 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -7,7 +7,7 @@ trigger: - main jobs: - - job: 'windows-test' + - job: 'windows_test' pool: vmImage: windows-latest steps: @@ -42,7 +42,7 @@ jobs: summaryFileLocation: 'coverage.xml' pathToSources: 'src/' failIfCoverageEmpty: true - - job: 'linux-test' + - job: 'linux_test' pool: vmImage: 'ubuntu-latest' steps: @@ -77,7 +77,7 @@ jobs: summaryFileLocation: 'coverage.xml' pathToSources: 'src/' failIfCoverageEmpty: true - - job: 'build-package' + - job: 'build_package' pool: vmImage: windows-latest steps: From d2b412b3e4b989cec6e31be49e2fc82ed50f398e Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 22:52:26 +0200 Subject: [PATCH 45/62] fix failed linux tests --- tests/Test-ProxyConfiguration.tests.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/Test-ProxyConfiguration.tests.ps1 b/tests/Test-ProxyConfiguration.tests.ps1 index 0f67b00..a883809 100644 --- a/tests/Test-ProxyConfiguration.tests.ps1 +++ b/tests/Test-ProxyConfiguration.tests.ps1 @@ -1,4 +1,6 @@ -Describe "Test-ProxyConfiguration" { +$skipBecauseLinux = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $false; +$skipBecauseWindows = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $true; +Describe "Test-ProxyConfiguration" -Skip:($skipBecauseLinux) { BeforeAll { $fileInfo = Get-ChildItem $PSCommandPath; $functionName = $fileInfo.Name.Split('.')[0]; @@ -159,7 +161,7 @@ Describe "Test-ProxyConfiguration" { } } -Describe "ProxyTestResult" { +Describe "ProxyTestResult" -Skip:($skipBecauseLinux) { BeforeAll { $fileInfo = Get-ChildItem $PSCommandPath; $functionName = $fileInfo.Name.Split('.')[0]; From 4fea58498f0e89a3a74a99ad28b4d3f43ffe94ea Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 23:04:09 +0200 Subject: [PATCH 46/62] try to get a better coverage report --- azure-pipelines.yml | 48 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 85a419d..fda0629 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -35,13 +35,12 @@ jobs: testResultsFiles: 'testResults.xml' failTaskOnFailedTests: true testRunTitle: 'CZ.PowerShell.NetworkTools' - - task: PublishCodeCoverageResults@1 + - task: PublishBuildArtifacts@1 condition: always() inputs: - codeCoverageTool: 'JaCoCo' - summaryFileLocation: 'coverage.xml' - pathToSources: 'src/' - failIfCoverageEmpty: true + PathtoPublish: 'coverage.xml' + ArtifactName: 'windows-coverage' + publishLocation: Container - job: 'linux_test' pool: vmImage: 'ubuntu-latest' @@ -70,16 +69,18 @@ jobs: testResultsFiles: 'testResults.xml' failTaskOnFailedTests: true testRunTitle: 'CZ.PowerShell.NetworkTools' - - task: PublishCodeCoverageResults@1 + - task: PublishBuildArtifacts@1 condition: always() inputs: - codeCoverageTool: 'JaCoCo' - summaryFileLocation: 'coverage.xml' - pathToSources: 'src/' - failIfCoverageEmpty: true + PathtoPublish: 'coverage.xml' + ArtifactName: 'linux-coverage' + publishLocation: Container - job: 'build_package' pool: vmImage: windows-latest + dependsOn: + - 'windows_test' + - 'linux_test' steps: - task: PowerShell@2 displayName: "Build the powershell package" @@ -91,4 +92,29 @@ jobs: inputs: PathtoPublish: 'src/bin/' ArtifactName: 'drop' - publishLocation: 'Container' \ No newline at end of file + publishLocation: 'Container' + - job: 'publish_coverage' + pool: + vmImage: windows-latest + dependsOn: + - 'windows_test' + - 'linux_test' + steps: + - task: DownloadBuildArtifacts@0 + displayName: 'Download Coverage Windows Artifacts' + inputs: + artifactName: windows-coverage + downloadPath: $(System.DefaultWorkingDirectory)/windows/ + - task: DownloadBuildArtifacts@0 + displayName: 'Download Coverage Linux Artifacts' + inputs: + artifactName: linux-coverage + downloadPath: $(System.DefaultWorkingDirectory)/linux/ + - task: PublishCodeCoverageResults@1 + condition: always() + inputs: + codeCoverageTool: 'JaCoCo' + summaryFileLocation: 'windows/coverage.xml' + additionalCodeCoverageFiles: 'linux/coverage.xml' + pathToSources: 'src/' + failIfCoverageEmpty: true \ No newline at end of file From aa8dbfbcdf64864a8c894f50e1f77e8c932c2ca1 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 23:08:07 +0200 Subject: [PATCH 47/62] try to fix the coverage again --- azure-pipelines.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index fda0629..22d17fb 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -104,17 +104,17 @@ jobs: displayName: 'Download Coverage Windows Artifacts' inputs: artifactName: windows-coverage - downloadPath: $(System.DefaultWorkingDirectory)/windows/ + downloadPath: $(System.DefaultWorkingDirectory)/ - task: DownloadBuildArtifacts@0 displayName: 'Download Coverage Linux Artifacts' inputs: artifactName: linux-coverage - downloadPath: $(System.DefaultWorkingDirectory)/linux/ + downloadPath: $(System.DefaultWorkingDirectory)/ - task: PublishCodeCoverageResults@1 condition: always() inputs: codeCoverageTool: 'JaCoCo' - summaryFileLocation: 'windows/coverage.xml' - additionalCodeCoverageFiles: 'linux/coverage.xml' + summaryFileLocation: 'windows-coverage/coverage.xml' + additionalCodeCoverageFiles: 'linux-coverage/coverage.xml' pathToSources: 'src/' failIfCoverageEmpty: true \ No newline at end of file From b7aa00afb751fcce5847a7a9760d5477f73ea23c Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 23:15:29 +0200 Subject: [PATCH 48/62] try to merge test results --- azure-pipelines.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 22d17fb..5ebbcab 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -35,6 +35,7 @@ jobs: testResultsFiles: 'testResults.xml' failTaskOnFailedTests: true testRunTitle: 'CZ.PowerShell.NetworkTools' + mergeTestResults: true - task: PublishBuildArtifacts@1 condition: always() inputs: @@ -69,6 +70,7 @@ jobs: testResultsFiles: 'testResults.xml' failTaskOnFailedTests: true testRunTitle: 'CZ.PowerShell.NetworkTools' + mergeTestResults: true - task: PublishBuildArtifacts@1 condition: always() inputs: @@ -114,7 +116,6 @@ jobs: condition: always() inputs: codeCoverageTool: 'JaCoCo' - summaryFileLocation: 'windows-coverage/coverage.xml' - additionalCodeCoverageFiles: 'linux-coverage/coverage.xml' + summaryFileLocation: '$(System.DefaultWorkingDirectory)/*-coverage/coverage.xml' pathToSources: 'src/' failIfCoverageEmpty: true \ No newline at end of file From 4165295fa4e981ea702a08324d1a312859e52b64 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Thu, 14 Oct 2021 23:25:36 +0200 Subject: [PATCH 49/62] try to fix test merge again --- azure-pipelines.yml | 54 ++++++++++++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 5ebbcab..009d63a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -28,20 +28,20 @@ jobs: Invoke-Pester -Configuration $configuration; showWarnings: true pwsh: true - - task: PublishTestResults@2 - condition: always() - inputs: - testResultsFormat: 'NUnit' - testResultsFiles: 'testResults.xml' - failTaskOnFailedTests: true - testRunTitle: 'CZ.PowerShell.NetworkTools' - mergeTestResults: true - task: PublishBuildArtifacts@1 + displayName: 'Publish Coverage' condition: always() inputs: PathtoPublish: 'coverage.xml' ArtifactName: 'windows-coverage' publishLocation: Container + - task: PublishBuildArtifacts@1 + displayName: 'Publish Tests' + condition: always() + inputs: + PathtoPublish: 'testResults.xml' + ArtifactName: 'windows-tests' + publishLocation: Container - job: 'linux_test' pool: vmImage: 'ubuntu-latest' @@ -63,20 +63,20 @@ jobs: Invoke-Pester -Configuration $configuration; showWarnings: true pwsh: true - - task: PublishTestResults@2 - condition: always() - inputs: - testResultsFormat: 'NUnit' - testResultsFiles: 'testResults.xml' - failTaskOnFailedTests: true - testRunTitle: 'CZ.PowerShell.NetworkTools' - mergeTestResults: true - task: PublishBuildArtifacts@1 + displayName: 'Publish Coverage' condition: always() inputs: PathtoPublish: 'coverage.xml' ArtifactName: 'linux-coverage' publishLocation: Container + - task: PublishBuildArtifacts@1 + displayName: 'Publish Tests' + condition: always() + inputs: + PathtoPublish: 'testResults.xml' + ArtifactName: 'linux-tests' + publishLocation: Container - job: 'build_package' pool: vmImage: windows-latest @@ -95,7 +95,7 @@ jobs: PathtoPublish: 'src/bin/' ArtifactName: 'drop' publishLocation: 'Container' - - job: 'publish_coverage' + - job: 'publish_coverage_and_tests' pool: vmImage: windows-latest dependsOn: @@ -112,10 +112,28 @@ jobs: inputs: artifactName: linux-coverage downloadPath: $(System.DefaultWorkingDirectory)/ + - task: DownloadBuildArtifacts@0 + displayName: 'Download Tests Windows Artifacts' + inputs: + artifactName: windows-tests + downloadPath: $(System.DefaultWorkingDirectory)/ + - task: DownloadBuildArtifacts@0 + displayName: 'Download Tests Linux Artifacts' + inputs: + artifactName: linux-tests + downloadPath: $(System.DefaultWorkingDirectory)/ - task: PublishCodeCoverageResults@1 condition: always() inputs: codeCoverageTool: 'JaCoCo' summaryFileLocation: '$(System.DefaultWorkingDirectory)/*-coverage/coverage.xml' pathToSources: 'src/' - failIfCoverageEmpty: true \ No newline at end of file + failIfCoverageEmpty: true + - task: PublishTestResults@2 + condition: always() + inputs: + testResultsFormat: 'NUnit' + testResultsFiles: '$(System.DefaultWorkingDirectory)/*-tests/testResults.xml' + failTaskOnFailedTests: true + testRunTitle: 'CZ.PowerShell.NetworkTools' + mergeTestResults: true \ No newline at end of file From 51e0bc2a0030e157a7cfd6abc6b9be54d2878b74 Mon Sep 17 00:00:00 2001 From: paule96 Date: Fri, 15 Oct 2021 20:01:54 +0200 Subject: [PATCH 50/62] fix messages Co-authored-by: DanielHabenicht --- src/Set-ProxyConfiguration.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index cded605..dd1ca06 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -194,7 +194,7 @@ function Set-AptProxyConfiguration { } } if ($null -ne $Settings.BypassList -and $Settings.BypassList.Count -ne 0) { - Write-Warning "apt-get don't support bypass list. To bypassing the proxy config for a given command starts the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; + Write-Warning "apt-get does not support bypass list. To bypass the proxy config for a given command start the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; } } catch [System.UnauthorizedAccessException] { From 69380f3e5bceea8ffe63ad58d03c2b476aefc3b7 Mon Sep 17 00:00:00 2001 From: paule96 Date: Fri, 15 Oct 2021 20:02:13 +0200 Subject: [PATCH 51/62] fix messags Co-authored-by: DanielHabenicht --- src/Set-ProxyConfiguration.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Set-ProxyConfiguration.ps1 b/src/Set-ProxyConfiguration.ps1 index dd1ca06..fa20eb4 100644 --- a/src/Set-ProxyConfiguration.ps1 +++ b/src/Set-ProxyConfiguration.ps1 @@ -199,7 +199,7 @@ function Set-AptProxyConfiguration { } catch [System.UnauthorizedAccessException] { if ($NoRoot) { - Write-Debug "Skip APT configuration because NORoot."; + Write-Debug "Skip APT configuration because NORoot Option is set."; return; } else { From 0a6e84869b3ba542c412871337c6522299c4ebfe Mon Sep 17 00:00:00 2001 From: paule96 Date: Fri, 15 Oct 2021 20:02:29 +0200 Subject: [PATCH 52/62] fix messages Co-authored-by: DanielHabenicht --- tests/Set-ProxyConfiguration.tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index df9a4cb..8049980 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -115,7 +115,7 @@ Describe "Set-ProxyConfiguration" { } $configPath = "something/that/not/exsists"; # Act & assert - { Set-ProxyConfiguration -ConfigPath "$configPath" } | Should -Throw "Currently we don't support linux, to read out the system proxy. Please configure it manualy"; + { Set-ProxyConfiguration -ConfigPath "$configPath" } | Should -Throw "Currently we don't support linux, to read out the system proxy. Please configure it manually"; Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; } From 03f8d4e16978709a3c10a640b7630518672d390a Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 20:10:28 +0200 Subject: [PATCH 53/62] fix tests --- tests/Set-ProxyConfiguration.tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 8049980..991314b 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -115,7 +115,7 @@ Describe "Set-ProxyConfiguration" { } $configPath = "something/that/not/exsists"; # Act & assert - { Set-ProxyConfiguration -ConfigPath "$configPath" } | Should -Throw "Currently we don't support linux, to read out the system proxy. Please configure it manually"; + { Set-ProxyConfiguration -ConfigPath "$configPath" } | Should -Throw "Currently we don't support linux, to read out the system proxy. Please configure it manualy"; Assert-MockCalled Test-Path -Times 1 -ParameterFilter { $Path -eq $configPath }; Assert-MockCalled Get-Content -Times 1 -ParameterFilter { $Path -eq $configPath -and $Raw -eq $true }; } @@ -388,7 +388,7 @@ Describe "Set-ProxyConfiguration" { Assert-MockCalled Get-Command -Times 1 -Exactly; Assert-MockCalled Test-Path -Times 1 -Exactly -ParameterFilter {$Path -eq "/etc/apt/apt.conf"}; Assert-MockCalled Set-Content -Times 1 -Exactly -ParameterFilter {$Value -eq "Acquire::http::Proxy ""$($settings.ProxyAddress)"";"}; - $warning | Should -Be "apt-get don't support bypass list. To bypassing the proxy config for a given command starts the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; + $warning | Should -Be "apt-get does not support bypass list. To bypass the proxy config for a given command start the command like: 'apt-get -o Acquire::http::proxy=false ....'. This will bypass the proxy for the runtime of the apt-get command."; } It("config exsists but is empty and a proxy is required, write the config."){ # arrage From 51c79c964ea5b89898be5dbbd3922b4b96d13c04 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 20:20:58 +0200 Subject: [PATCH 54/62] try to use matrix build in the pipeline --- azure-pipelines.yml | 59 ++++++++++++++------------------------------- 1 file changed, 18 insertions(+), 41 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 009d63a..72666f9 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -7,44 +7,17 @@ trigger: - main jobs: - - job: 'windows_test' + - job: 'tests' + strategy: + matrix: + linux: + imageName: 'ubuntu-latest' + mac: + imageName: 'macOS-latest' + windows: + imageName: 'windows-latest' pool: - vmImage: windows-latest - steps: - - task: PowerShell@2 - displayName: "Run pester tests" - inputs: - targetType: 'inline' - script: | - Install-Module -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck Pester; - Import-Module Pester; - $configuration = [PesterConfiguration]::Default; - $configuration.CodeCoverage.Enabled = $true; - $configuration.CodeCoverage.Path = (Get-ChildItem src/*.ps1 | ForEach-Object{$_.FullName}); - $configuration.CodeCoverage.OutputFormat = "JaCoCo"; - $configuration.TestResult.Enabled = $true; - $configuration.Run.Exit = $true; - $configuration.Run.Path = (Get-ChildItem tests/*ps1 | ForEach-Object{$_.FullName}); - Invoke-Pester -Configuration $configuration; - showWarnings: true - pwsh: true - - task: PublishBuildArtifacts@1 - displayName: 'Publish Coverage' - condition: always() - inputs: - PathtoPublish: 'coverage.xml' - ArtifactName: 'windows-coverage' - publishLocation: Container - - task: PublishBuildArtifacts@1 - displayName: 'Publish Tests' - condition: always() - inputs: - PathtoPublish: 'testResults.xml' - ArtifactName: 'windows-tests' - publishLocation: Container - - job: 'linux_test' - pool: - vmImage: 'ubuntu-latest' + vmImage: $(imageName) steps: - task: PowerShell@2 displayName: "Run pester tests" @@ -68,14 +41,14 @@ jobs: condition: always() inputs: PathtoPublish: 'coverage.xml' - ArtifactName: 'linux-coverage' + ArtifactName: '$(imageName)-coverage' publishLocation: Container - task: PublishBuildArtifacts@1 displayName: 'Publish Tests' condition: always() inputs: PathtoPublish: 'testResults.xml' - ArtifactName: 'linux-tests' + ArtifactName: '$(imageName)-tests' publishLocation: Container - job: 'build_package' pool: @@ -99,8 +72,7 @@ jobs: pool: vmImage: windows-latest dependsOn: - - 'windows_test' - - 'linux_test' + - 'tests' steps: - task: DownloadBuildArtifacts@0 displayName: 'Download Coverage Windows Artifacts' @@ -122,6 +94,11 @@ jobs: inputs: artifactName: linux-tests downloadPath: $(System.DefaultWorkingDirectory)/ + - task: DownloadBuildArtifacts@1 + displayName: 'Download All Tests Artifacts' + inputs: + artifactName: '*-tests' + downloadPath: $(System.DefaultWorkingDirectory)/ - task: PublishCodeCoverageResults@1 condition: always() inputs: From 943d3333e9e3345ec26898473c9e7bf8c47af4f3 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 20:22:01 +0200 Subject: [PATCH 55/62] fix dependencie of build package --- azure-pipelines.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 72666f9..a3e1b69 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -54,8 +54,7 @@ jobs: pool: vmImage: windows-latest dependsOn: - - 'windows_test' - - 'linux_test' + - 'tests' steps: - task: PowerShell@2 displayName: "Build the powershell package" From 8080f26735109d9cc6abf6428431235f8c7ef83f Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 20:24:13 +0200 Subject: [PATCH 56/62] =?UTF-8?q?our=20tests=20are=20not=20ready=20for=20m?= =?UTF-8?q?ac=20now=20=F0=9F=A4=B7=E2=80=8D=E2=99=80=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- azure-pipelines.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index a3e1b69..95a1d33 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -12,8 +12,8 @@ jobs: matrix: linux: imageName: 'ubuntu-latest' - mac: - imageName: 'macOS-latest' + # mac: + # imageName: 'macOS-latest' windows: imageName: 'windows-latest' pool: From 3c58c5b630a114f5af7117714d9deedc61018b9f Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 20:28:09 +0200 Subject: [PATCH 57/62] try to fix coverage download --- azure-pipelines.yml | 45 +++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 95a1d33..bc4699e 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -73,31 +73,36 @@ jobs: dependsOn: - 'tests' steps: - - task: DownloadBuildArtifacts@0 - displayName: 'Download Coverage Windows Artifacts' - inputs: - artifactName: windows-coverage - downloadPath: $(System.DefaultWorkingDirectory)/ - - task: DownloadBuildArtifacts@0 - displayName: 'Download Coverage Linux Artifacts' - inputs: - artifactName: linux-coverage - downloadPath: $(System.DefaultWorkingDirectory)/ - - task: DownloadBuildArtifacts@0 - displayName: 'Download Tests Windows Artifacts' - inputs: - artifactName: windows-tests - downloadPath: $(System.DefaultWorkingDirectory)/ - - task: DownloadBuildArtifacts@0 - displayName: 'Download Tests Linux Artifacts' - inputs: - artifactName: linux-tests - downloadPath: $(System.DefaultWorkingDirectory)/ + # - task: DownloadBuildArtifacts@0 + # displayName: 'Download Coverage Windows Artifacts' + # inputs: + # artifactName: windows-coverage + # downloadPath: $(System.DefaultWorkingDirectory)/ + # - task: DownloadBuildArtifacts@0 + # displayName: 'Download Coverage Linux Artifacts' + # inputs: + # artifactName: linux-coverage + # downloadPath: $(System.DefaultWorkingDirectory)/ + # - task: DownloadBuildArtifacts@0 + # displayName: 'Download Tests Windows Artifacts' + # inputs: + # artifactName: windows-tests + # downloadPath: $(System.DefaultWorkingDirectory)/ + # - task: DownloadBuildArtifacts@0 + # displayName: 'Download Tests Linux Artifacts' + # inputs: + # artifactName: linux-tests + # downloadPath: $(System.DefaultWorkingDirectory)/ - task: DownloadBuildArtifacts@1 displayName: 'Download All Tests Artifacts' inputs: artifactName: '*-tests' downloadPath: $(System.DefaultWorkingDirectory)/ + - task: DownloadBuildArtifacts@1 + displayName: 'Download All Coverage Artifacts' + inputs: + artifactName: '*-coverage' + downloadPath: $(System.DefaultWorkingDirectory)/ - task: PublishCodeCoverageResults@1 condition: always() inputs: From 467779fc611acdae70961042df8b7c12249637bf Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 20:35:10 +0200 Subject: [PATCH 58/62] try to fix test output --- azure-pipelines.yml | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index bc4699e..3c74a3e 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -30,7 +30,9 @@ jobs: $configuration.CodeCoverage.Enabled = $true; $configuration.CodeCoverage.Path = (Get-ChildItem src/*.ps1 | ForEach-Object{$_.FullName}); $configuration.CodeCoverage.OutputFormat = "JaCoCo"; + $configuration.CodeCoverage.OutputPath = '$(imageName)-coverage.xml' $configuration.TestResult.Enabled = $true; + $configuration.TestResult.OutputPath = '$(imageName)-testResults.xml' $configuration.Run.Exit = $true; $configuration.Run.Path = (Get-ChildItem tests/*ps1 | ForEach-Object{$_.FullName}); Invoke-Pester -Configuration $configuration; @@ -40,15 +42,15 @@ jobs: displayName: 'Publish Coverage' condition: always() inputs: - PathtoPublish: 'coverage.xml' - ArtifactName: '$(imageName)-coverage' + PathtoPublish: '$(imageName)-coverage.xml' + ArtifactName: 'coverage' publishLocation: Container - task: PublishBuildArtifacts@1 displayName: 'Publish Tests' condition: always() inputs: - PathtoPublish: 'testResults.xml' - ArtifactName: '$(imageName)-tests' + PathtoPublish: '$(imageName)-testResults.xml' + ArtifactName: 'tests' publishLocation: Container - job: 'build_package' pool: @@ -96,25 +98,25 @@ jobs: - task: DownloadBuildArtifacts@1 displayName: 'Download All Tests Artifacts' inputs: - artifactName: '*-tests' + artifactName: 'tests' downloadPath: $(System.DefaultWorkingDirectory)/ - task: DownloadBuildArtifacts@1 displayName: 'Download All Coverage Artifacts' inputs: - artifactName: '*-coverage' + artifactName: 'coverage' downloadPath: $(System.DefaultWorkingDirectory)/ - task: PublishCodeCoverageResults@1 condition: always() inputs: codeCoverageTool: 'JaCoCo' - summaryFileLocation: '$(System.DefaultWorkingDirectory)/*-coverage/coverage.xml' + summaryFileLocation: '$(System.DefaultWorkingDirectory)/coverage/*coverage.xml' pathToSources: 'src/' failIfCoverageEmpty: true - task: PublishTestResults@2 condition: always() inputs: testResultsFormat: 'NUnit' - testResultsFiles: '$(System.DefaultWorkingDirectory)/*-tests/testResults.xml' + testResultsFiles: '$(System.DefaultWorkingDirectory)/tests/*testResults.xml' failTaskOnFailedTests: true testRunTitle: 'CZ.PowerShell.NetworkTools' mergeTestResults: true \ No newline at end of file From be2fe040164de478dadfc66911c448efa7c89b00 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 20:57:06 +0200 Subject: [PATCH 59/62] try to fix macOS tests --- azure-pipelines.yml | 4 ++-- tests/Set-ProxyConfiguration.tests.ps1 | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 3c74a3e..40c94c0 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -12,8 +12,8 @@ jobs: matrix: linux: imageName: 'ubuntu-latest' - # mac: - # imageName: 'macOS-latest' + mac: + imageName: 'macOS-latest' windows: imageName: 'windows-latest' pool: diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 991314b..8e2f8e4 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -319,7 +319,7 @@ Describe "Set-ProxyConfiguration" { } } Describe "the apt function"{ - Context "When Set-AptProxyConfiguration is okay and" -Skip:($skipBecauseWindows) { + Context "When Set-AptProxyConfiguration is okay and" -Skip:($skipBecauseWindows -or (Get-Command apt -ErrorAction SilentlyContinue) -eq $null){ It("'apt' is undefined, it shouldn't throw an error"){ # arrage Mock -Verifiable Get-Command { From 2749cf0823e50a3a7b92c40d7f862a84c74579ea Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 21:04:17 +0200 Subject: [PATCH 60/62] fix tests again --- tests/Set-ProxyConfiguration.tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 8e2f8e4..7bc4b94 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -319,7 +319,7 @@ Describe "Set-ProxyConfiguration" { } } Describe "the apt function"{ - Context "When Set-AptProxyConfiguration is okay and" -Skip:($skipBecauseWindows -or (Get-Command apt -ErrorAction SilentlyContinue) -eq $null){ + Context "When Set-AptProxyConfiguration is okay and" -Skip:(($skipBecauseWindows) -or ($null -eq (Get-Command apt -ErrorAction SilentlyContinue))){ It("'apt' is undefined, it shouldn't throw an error"){ # arrage Mock -Verifiable Get-Command { From 772ffd7f9cccf451eb410ed9c93ff1fa0650e4d2 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 21:10:24 +0200 Subject: [PATCH 61/62] fix skiping apt tests --- tests/Set-ProxyConfiguration.tests.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 7bc4b94..8e74b51 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -1,6 +1,7 @@ Describe "Set-ProxyConfiguration" { $skipBecauseLinux = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $false; $skipBecauseWindows = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $true; + $noapt = ($null -eq (Get-Command apt -ErrorAction SilentlyContinue)); BeforeAll { # load function to test $fileInfo = Get-ChildItem $PSCommandPath; @@ -319,7 +320,7 @@ Describe "Set-ProxyConfiguration" { } } Describe "the apt function"{ - Context "When Set-AptProxyConfiguration is okay and" -Skip:(($skipBecauseWindows) -or ($null -eq (Get-Command apt -ErrorAction SilentlyContinue))){ + Context "When Set-AptProxyConfiguration is okay and" -Skip:(($skipBecauseWindows) -or ($noapt)){ It("'apt' is undefined, it shouldn't throw an error"){ # arrage Mock -Verifiable Get-Command { From 417b6775c550e9087e6a471249722cf05eacbea6 Mon Sep 17 00:00:00 2001 From: Paul Jeschke Date: Fri, 15 Oct 2021 21:15:17 +0200 Subject: [PATCH 62/62] try to finaly fix mac tests --- tests/Set-ProxyConfiguration.tests.ps1 | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/Set-ProxyConfiguration.tests.ps1 b/tests/Set-ProxyConfiguration.tests.ps1 index 8e74b51..0ec43c9 100644 --- a/tests/Set-ProxyConfiguration.tests.ps1 +++ b/tests/Set-ProxyConfiguration.tests.ps1 @@ -1,7 +1,9 @@ Describe "Set-ProxyConfiguration" { - $skipBecauseLinux = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $false; - $skipBecauseWindows = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $true; - $noapt = ($null -eq (Get-Command apt -ErrorAction SilentlyContinue)); + BeforeDiscovery { + $script:skipBecauseLinux = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $false; + $script:skipBecauseWindows = ($PSVersionTable.PSEdition -eq "Desktop" -or $IsWindows) -eq $true; + $script:noapt = ($null -eq (Get-Command apt -ErrorAction SilentlyContinue) -or $null -eq (Get-Command apt-config -ErrorAction SilentlyContinue)); + } BeforeAll { # load function to test $fileInfo = Get-ChildItem $PSCommandPath;