From 165c20920f50c5ce8a42284756f1d789f1870032 Mon Sep 17 00:00:00 2001 From: erclu <30255227+erclu@users.noreply.github.com> Date: Tue, 31 Mar 2020 19:11:12 +0200 Subject: [PATCH 01/50] perf: change how repositories are found --- .../Invoke-GitGarbageCollectorInAllRepositories.ps1 | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 b/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 index 269b029..7aaedcd 100644 --- a/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 +++ b/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 @@ -9,8 +9,15 @@ param ( Write-Output "Searching for repositories in $RootFolder..." -$repos = Get-ChildItem -Directory -Force -Recurse $RootFolder -Include ".git" | - Where-Object FullName -NotMatch "node_modules" +$repos = Get-ChildItem -Verbose -Directory -Force -Recurse $RootFolder | + Where-Object FullName -NotMatch "node_modules" | + Where-Object FullName -NotMatch "vendor" | + Where-Object FullName -NotMatch "Library" | + Where-Object FullName -Match ".git$" | + ForEach-Object { + Write-Verbose "scanning $($_.FullName)" + $_ + } Write-Output "Found $($repos.Length) repos." From f9a07f645adac60c13abba5da3060d11795b25c4 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Mon, 22 Jun 2020 20:43:48 +0200 Subject: [PATCH 02/50] feat: bunch of stuff --- PSDockerUtils/PSDockerUtils.psm1 | 94 +++++++++++++++ PSUtils/PSUtils.psm1 | 150 ++++++++++++++++++++++++ Scripts/Get-DirtyRepositories.ps1 | 7 +- Scripts/Test-GradleWrapperIntegrity.ps1 | 19 +++ Scripts/Write-RepoContributions.ps1 | 42 +++++++ 5 files changed, 311 insertions(+), 1 deletion(-) create mode 100644 PSDockerUtils/PSDockerUtils.psm1 create mode 100644 PSUtils/PSUtils.psm1 create mode 100644 Scripts/Test-GradleWrapperIntegrity.ps1 create mode 100644 Scripts/Write-RepoContributions.ps1 diff --git a/PSDockerUtils/PSDockerUtils.psm1 b/PSDockerUtils/PSDockerUtils.psm1 new file mode 100644 index 0000000..178b1ca --- /dev/null +++ b/PSDockerUtils/PSDockerUtils.psm1 @@ -0,0 +1,94 @@ +function Switch-DockerHost { + [CmdletBinding()] + param ( + [Parameter(Position = 0)] + [ValidateSet('local', 'erclu-server')] + [string] + $dockerHost, + [switch] + $persist + ) + + switch ($dockerHost) { + local { + Write-Verbose "switching to local docker host" + $targetDockerMachine = "default" + + # & "C:\Program Files\Git\bin\bash.exe" --login -i "C:\Program Files\Docker Toolbox\start.sh" + } + + erclu-server { + Write-Verbose "switching DOCKER_HOST to erclu-server via ssh" + $targetDockerMachine = "erclu-server" + + # $env:DOCKER_HOST = "ssh://erclu@192.168.1.81" + } + Default { + $hereString = @" +CURRENT DOCKER ENVIRONMENT VARIABLES: + +DOCKER_HOST=$($env:DOCKER_HOST) + +DOCKER_CERT_PATH=$($env:DOCKER_CERT_PATH) +DOCKER_TLS_VERIFY=$($env:DOCKER_TLS_VERIFY) - this should never change +DOCKER_MACHINE_NAME=$($env:DOCKER_MACHINE_NAME) +MACHINE_STORAGE_PATH=$($env:MACHINE_STORAGE_PATH) - this should never change +COMPOSE_CONVERT_WINDOWS_PATHS=$($env:COMPOSE_CONVERT_WINDOWS_PATHS) - this should never change +"@ + + Write-Output $hereString + + return 0 + } + } + + docker-machine env $targetDockerMachine --shell powershell | Invoke-Expression + + docker-machine start $targetDockerMachine + + if ($persist) { + [environment]::setEnvironmentVariable('DOCKER_TLS_VERIFY', $env:DOCKER_TLS_VERIFY, 'User') + [environment]::setEnvironmentVariable('DOCKER_HOST', $env:DOCKER_HOST, 'User') + [environment]::setEnvironmentVariable('DOCKER_CERT_PATH', $env:DOCKER_CERT_PATH, 'User') + [environment]::setEnvironmentVariable('DOCKER_MACHINE_NAME', $env:DOCKER_MACHINE_NAME, 'User') + [environment]::setEnvironmentVariable('COMPOSE_CONVERT_WINDOWS_PATHS', $env:COMPOSE_CONVERT_WINDOWS_PATHS, 'User') + + if (Get-Process "code" -ErrorAction SilentlyContinue) { + Write-Warning "you probably need to restart vscode" + Write-Warning "!!! remember that vscode explorer does NOT work on remote host" + } + } +} + +function Start-DockerToolbox { + [CmdletBinding()] + param ( + [Parameter()] + [Switch] + $RegenerateCerts + ) + docker-machine start default + + if ($RegenerateCerts) { + Start-Sleep -Seconds 1 + + "y" | docker-machine regenerate-certs + } +} + +function Stop-DockerToolbox { + docker-machine stop default +} + + +function ForwardDockerMachine { + [CmdletBinding()] + param ( + # Parameter help description + [Parameter(Mandatory)] + [string] + $port + ) + + docker-machine ssh default -N -L "$($port):localhost:$($port)" +} diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 new file mode 100644 index 0000000..b18cd98 --- /dev/null +++ b/PSUtils/PSUtils.psm1 @@ -0,0 +1,150 @@ +######################################################################################################################## +####################################### Scoop utils +######################################################################################################################## + +function Get-ScoopSize { + $cache = Get-ChildItem -Recurse $env:SCOOP/cache | + Measure-Object -Sum Length | + Select-Object -ExpandProperty Sum + + $persisted = Get-ChildItem -Recurse $env:SCOOP/persist | + Measure-Object -Sum Length | + Select-Object -ExpandProperty Sum + + $installed = Get-ChildItem -Recurse $env:SCOOP/apps | + Measure-Object -Sum Length | + Select-Object -ExpandProperty Sum + + + [PSCustomObject]@{ + "cache size (MB)" = [math]::Round($cache / 1MB, 2) + "persisted data size (MB)" = [math]::Round($persisted / 1MB, 2) + "installed apps size (GB)" = [math]::Round($installed / 1GB, 2) + } +} + +function Update-ScoopAndCleanAfter { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param () + + scoop update + scoop status + + if ($PSCmdlet.ShouldProcess("Update apps")) { + scoop update * + } + + Write-Output "Running scoop cleanup..." + scoop cleanup * + + Write-Output "Clearing cache..." + scoop cache show + scoop cache rm * +} + +######################################################################################################################## +####################################### JSCPD +######################################################################################################################## + +function Invoke-CopyPasteDetectorDefaultConfig { + [CmdletBinding()] + param ( + # path + [Parameter(Mandatory = $true)] + [System.IO.DirectoryInfo] + $Folder + ) + + jscpd --config "$($env:PROJECTS_FOLDER)/_CONFIGS/.jscpd.json" $Folder +} + +######################################################################################################################## +####################################### File utils +######################################################################################################################## + +function Test-ContainsBOM { + [CmdletBinding()] + [OutputType([bool])] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [System.IO.FileInfo] + $file + ) + + process { + $contents = New-Object byte[] 3 + $stream = [System.IO.File]::OpenRead($file.FullName) + $stream.Read($contents, 0, 3) | Out-Null + $stream.Close() + + return $contents[0] -eq 0xEF -and $contents[1] -eq 0xBB -and $contents[2] -eq 0xBF + } +} + +function Test-HasCrlfEndings { + [CmdletBinding()] + [OutputType([bool])] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [System.IO.FileInfo] + $file + ) + + process { + (Get-Content -Raw -LiteralPath $file.FullName) -match "`r`n" + } +} + +function Test-BomHereRecursive { + + Get-ChildItem -File -Recurse | + Where-Object FullName -NotMatch ".zip" | + Where-Object FullName -NotMatch ".git" | + Where-Object FullName -NotMatch ".mypy_cache" | + Where-Object FullName -NotMatch "node_modules" | + Where-Object FullName -NotMatch "vendor" | + Where-Object { -not (Test-ContainsBOM $_) } | + Select-Object FullName +} +function Find-Duplicates { + [CmdletBinding()] + param ( + [Parameter()] + [String[]] + $Paths = "." + ) + python D:/Projects/_LIBRARIES-WHEELS-ETC/find_duplicates.py $Paths +} + +function New-TemporaryDirectory { + $parent = [System.IO.Path]::GetTempPath() + [string] $name = [System.Guid]::NewGuid() + New-Item -ItemType Directory -Path (Join-Path $parent $name) +} + +function New-FastTemporaryDirectory { + [string] $name = [System.Guid]::NewGuid() + New-Item -ItemType Directory -Path ("C:/TEMP-$name") +} + +######################################################################################################################## +####################################### Hardlinks utils +######################################################################################################################## + +function New-HardLink { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + Param( + [parameter(position = 0)] [String] $Name, + [parameter(position = 1)] [Object] $Value + ) + + if ($PSCmdlet.ShouldProcess("Create new HardLink")) { + New-Item -ItemType HardLink -Name $Name -Value $Value + } +} + +function Find-HardLinks { + Get-ChildItem . -Recurse -Force | + Where-Object { $_.LinkType } | + Select-Object FullName, LinkType, Target +} diff --git a/Scripts/Get-DirtyRepositories.ps1 b/Scripts/Get-DirtyRepositories.ps1 index 4701a5a..b9d5ec2 100644 --- a/Scripts/Get-DirtyRepositories.ps1 +++ b/Scripts/Get-DirtyRepositories.ps1 @@ -74,13 +74,18 @@ $repos | $unpushedCommits = Test-HasUnpushedCommits $gitDir $forgottenStashes = Test-HasForgottenStashes $gitDir + # TODO might wanna refactor this + $ignoredFilesAndFolders = ( git --git-dir $gitDir --work-tree $workTree status -s --ignored ) | Measure-Object | Select-Object -ExpandProperty Count + [pscustomobject]@{ PSTypename = "GitRepo" Repo = $workTree - AllGood = -not ($dirtyIndex -or $unpushedCommits -or $forgottenStashes) + AllGood = -not ($dirtyIndex -or $unpushedCommits -or $forgottenStashes ) ChangesToCommit = $dirtyIndex CommitsToPush = $unpushedCommits StashesToClear = $forgottenStashes + # AllGood does not count these + Ignored = $ignoredFilesAndFolders } } @forEachArguments diff --git a/Scripts/Test-GradleWrapperIntegrity.ps1 b/Scripts/Test-GradleWrapperIntegrity.ps1 new file mode 100644 index 0000000..5455b75 --- /dev/null +++ b/Scripts/Test-GradleWrapperIntegrity.ps1 @@ -0,0 +1,19 @@ +[CmdletBinding()] +param ( + [Parameter(Mandatory)] + [String] + $Version +) + +$wrapperPath = "gradle/wrapper/gradle-wrapper.jar" + +if (-not (Test-Path $wrapperPath )) { + throw "No wrapper found" +} + +$expected = Invoke-RestMethod -Uri "https://services.gradle.org/distributions/gradle-$Version-wrapper.jar.sha256" +$actual = (Get-FileHash $wrapperPath -Algorithm SHA256).Hash.ToLower() +Write-Verbose "expected hash: $expected" +Write-Verbose "actual hash: $actual" + +@{$true = 'OK: Checksum match'; $false = "ERROR: Checksum mismatch!`nExpected: $expected`nActual: $actual" }[$actual -eq $expected] diff --git a/Scripts/Write-RepoContributions.ps1 b/Scripts/Write-RepoContributions.ps1 new file mode 100644 index 0000000..46fc852 --- /dev/null +++ b/Scripts/Write-RepoContributions.ps1 @@ -0,0 +1,42 @@ + +[CmdletBinding()] +param ( + [System.IO.DirectoryInfo] + $TargetRepo = ".", + # comma-separated string with folder/file names + [System.IO.DirectoryInfo[]] + $Include, + [System.IO.DirectoryInfo[]] + $Exclude, + [Switch] + $Quiet +) +$repoName = Split-Path -Leaf $TargetRepo +Write-Output "------------------------------------------------" +Write-Output "- $repoName" +Write-Output "------------------------------------------------" +Write-Output "" + +$cmdArgs = @( + if ($Quiet) { + "--silent-progress" + } + "-C" # Detect inter-file line moves and copies + "-M" # Detect intra-file line moves and copies + "--ignore-whitespace" + "--cost"; "cocomo,hours" + "--branch"; "master" + if ($Include) { + "--incl" + (( $Include | Resolve-Path -Relative ) -join "," -replace "\\", "/" ) + } + if ($Exclude) { + "--excl" + (( $Exclude | Resolve-Path -Relative ) -join "," -replace "\\", "/" ) + } + $TargetRepo +) +Write-Verbose "git-fame $cmdArgs" +git-fame @cmdArgs + +Write-Output "" From 750c65c0f7c9fc63d85719cc8f0450f8add8a20e Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Sun, 6 Sep 2020 17:28:48 +0200 Subject: [PATCH 03/50] feat: another bunch of stuff --- .../PSRestoreMyStuff/PSRestoreMyStuff.psm1 | 2 +- PSUtils/PSUtils.psm1 | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/BackupAndRestoreStuff/PSRestoreMyStuff/PSRestoreMyStuff.psm1 b/BackupAndRestoreStuff/PSRestoreMyStuff/PSRestoreMyStuff.psm1 index 814a4ab..1eea18f 100644 --- a/BackupAndRestoreStuff/PSRestoreMyStuff/PSRestoreMyStuff.psm1 +++ b/BackupAndRestoreStuff/PSRestoreMyStuff/PSRestoreMyStuff.psm1 @@ -10,7 +10,7 @@ function Install-ScoopWithPackages { Invoke-WebRequest -UseBasicParsing 'https://raw.githubusercontent.com/scoopinstaller/install/master/install.ps1' -OutFile install.ps1 # FIXME not cross platform - ./install.ps1 -ScoopDir 'C:/Tools/scoop' -NoProxy -RunAsAdmin + ./install.ps1 -ScoopDir 'C:/Tools/scoop' -ScoopGlobalDir 'C:/Tools/scoop-global-apps' -NoProxy -RunAsAdmin Remove-Item ./install.ps1 diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index b18cd98..8e3353a 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -27,8 +27,15 @@ function Update-ScoopAndCleanAfter { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param () + $telegram = "telegram" + scoop update - scoop status + $out = scoop status + $out + if ($out -match $telegram) { + Write-Output "stopping telegram..." + Get-Process $telegram | Stop-Process + } if ($PSCmdlet.ShouldProcess("Update apps")) { scoop update * @@ -40,6 +47,11 @@ function Update-ScoopAndCleanAfter { Write-Output "Clearing cache..." scoop cache show scoop cache rm * + + if ($out -match $telegram) { + Write-Output "starting telegram..." + & $telegram + } } ######################################################################################################################## @@ -113,7 +125,7 @@ function Find-Duplicates { [String[]] $Paths = "." ) - python D:/Projects/_LIBRARIES-WHEELS-ETC/find_duplicates.py $Paths + python 'D:/Projects/__libraries-wheels-etc/find_duplicates.py' $Paths } function New-TemporaryDirectory { From b8c1199cb98d44eac1325709d6cfc4fa3b88e0b0 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Wed, 23 Sep 2020 10:49:07 +0200 Subject: [PATCH 04/50] refactor: move utilities from scripts to a module --- PSUtils/PSUtils.psm1 | 62 ++++++++++++++++++++++++++++++++++++++ Scripts/Add-ModuleShim.ps1 | 11 ------- Scripts/Send-WOL.ps1 | 29 ------------------ 3 files changed, 62 insertions(+), 40 deletions(-) delete mode 100644 Scripts/Add-ModuleShim.ps1 delete mode 100644 Scripts/Send-WOL.ps1 diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 8e3353a..4386a1c 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -160,3 +160,65 @@ function Find-HardLinks { Where-Object { $_.LinkType } | Select-Object FullName, LinkType, Target } + +######################################################################################################################## +####################################### Send Magic Packet +######################################################################################################################## + +<# + .SYNOPSIS + Send a WOL packet to a broadcast address + .PARAMETER mac + The MAC address of the device that need to wake up + .PARAMETER ip + The IP address where the WOL packet will be sent to + .EXAMPLE + Send-WOL -mac 00:11:32:21:2D:11 -ip 192.168.8.255 +#> +function Send-MagicPacket { + [CmdletBinding()] + param( + [Parameter(Mandatory = $True, Position = 1)] + [string]$mac, + [string]$ip = "255.255.255.255", + [int]$port = 9 + ) + $broadcast = [Net.IPAddress]::Parse($ip) + + $mac = (($mac.replace(":", "")).replace("-", "")).replace(".", "") + $target = 0, 2, 4, 6, 8, 10 | ForEach-Object { [convert]::ToByte($mac.substring($_, 2), 16) } + $packet = (, [byte]255 * 6) + ($target * 16) + + $UDPclient = New-Object System.Net.Sockets.UdpClient + $UDPclient.Connect($broadcast, $port) + [void]$UDPclient.Send($packet, 102) +} + +######################################################################################################################## +####################################### Misc +######################################################################################################################## + +function Invoke-SshCopyId { + Param( + [parameter(Mandatory, Position = 1)] + [String] + $Destination + ) + + Get-Content "~/.ssh/id_rsa.pub" | ssh $Destination "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys" +} + + +function Add-ModuleShim { + [CmdletBinding()] + param ( + [System.IO.DirectoryInfo] + $ModuleFolder + ) + + $ModuleName = $ModuleFolder.Name + + $ShimPath = Join-Path "$HOME/Documents/PowerShell/Modules/" $ModuleName + + New-Item -ItemType Junction -Path $ShimPath -Value $ModuleFolder -Confirm +} \ No newline at end of file diff --git a/Scripts/Add-ModuleShim.ps1 b/Scripts/Add-ModuleShim.ps1 deleted file mode 100644 index 21b24d2..0000000 --- a/Scripts/Add-ModuleShim.ps1 +++ /dev/null @@ -1,11 +0,0 @@ -[CmdletBinding()] -param ( - [System.IO.DirectoryInfo] - $ModuleFolder -) - -$ModuleName = $ModuleFolder.Name - -$ShimPath = Join-Path "$HOME/Documents/PowerShell/Modules/" $ModuleName - -New-Item -ItemType Junction -Path $ShimPath -Value $ModuleFolder -Confirm diff --git a/Scripts/Send-WOL.ps1 b/Scripts/Send-WOL.ps1 deleted file mode 100644 index 144fd9f..0000000 --- a/Scripts/Send-WOL.ps1 +++ /dev/null @@ -1,29 +0,0 @@ -# function Send-WOL { -<# - .SYNOPSIS - Send a WOL packet to a broadcast address - .PARAMETER mac - The MAC address of the device that need to wake up - .PARAMETER ip - The IP address where the WOL packet will be sent to - .EXAMPLE - Send-WOL -mac 00:11:32:21:2D:11 -ip 192.168.8.255 -#> - -[CmdletBinding()] -param( - [Parameter(Mandatory = $True, Position = 1)] - [string]$mac, - [string]$ip = "255.255.255.255", - [int]$port = 9 -) -$broadcast = [Net.IPAddress]::Parse($ip) - -$mac = (($mac.replace(":", "")).replace("-", "")).replace(".", "") -$target = 0, 2, 4, 6, 8, 10 | ForEach-Object { [convert]::ToByte($mac.substring($_, 2), 16) } -$packet = (, [byte]255 * 6) + ($target * 16) - -$UDPclient = New-Object System.Net.Sockets.UdpClient -$UDPclient.Connect($broadcast, $port) -[void]$UDPclient.Send($packet, 102) -# } From 478e32d0e1b6a4212455ceb3b72aea7b699d04e5 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Wed, 23 Sep 2020 10:49:49 +0200 Subject: [PATCH 05/50] feat: add function to find old versions of installed vscode extensions --- PSUtils/PSUtils.psm1 | 50 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 4386a1c..59a722d 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -221,4 +221,52 @@ function Add-ModuleShim { $ShimPath = Join-Path "$HOME/Documents/PowerShell/Modules/" $ModuleName New-Item -ItemType Junction -Path $ShimPath -Value $ModuleFolder -Confirm -} \ No newline at end of file +} + +function Get-OldVsCodeExtensions { + [CmdletBinding()] + param ( + # [switch] + # $Aggro + ) + + $VSCODE_EXTENSIONS_DIR = "C:/Tools/scoop/apps/vscode-portable/current/data/extensions" + + $SEMVER_REGEX = "(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?" + $SPLITTER_REGEX = "^(?.*?)-(?$SEMVER_REGEX)$" + + # if (-not $Aggro) { + $DATETIME_CUTOFF = (Get-Date).AddDays(-7) + # } + # else { + # $DATETIME_CUTOFF = Get-Date + # } + + Get-ChildItem -Directory -Path $VSCODE_EXTENSIONS_DIR | + Sort-Object -Descending CreationTime | + Where-Object LastWriteTime -GT $DATETIME_CUTOFF | + ForEach-Object { + $name = $_.Name + + if (-not ($name -match $SPLITTER_REGEX)) { + Write-Error "this name is not correctly matched: $name" + } + + [pscustomobject]@{ + Name = $Matches.name + Version = $Matches.version + Directory = $_ + } + } | + Group-Object Name | + Where-Object Count -GT 1 | + ForEach-Object { + $newest, $old = $_.Group + + $old.Directory + } | + # Flatten array of arrays + ForEach-Object { + $_ + } +} From bbbd1dccb6db0cf36f9f9e41a15b316a55e58ef4 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Feb 2021 13:16:20 +0100 Subject: [PATCH 06/50] feat: add contig wrapper module --- Contig-Wrapper/Contig-Wrapper.psm1 | 82 ++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Contig-Wrapper/Contig-Wrapper.psm1 diff --git a/Contig-Wrapper/Contig-Wrapper.psm1 b/Contig-Wrapper/Contig-Wrapper.psm1 new file mode 100644 index 0000000..c11649a --- /dev/null +++ b/Contig-Wrapper/Contig-Wrapper.psm1 @@ -0,0 +1,82 @@ + +if (-not (Get-Command -ErrorAction SilentlyContinue Contig.exe) ) { + throw "CONTIG IS NOT AVAILABLE ON PATH" +} + +###### TODO is it needed? +# Requires -RunAsAdministrator + +function Invoke-Contig { + # Contig64.exe -nobanner $args + Contig.exe -nobanner $args +} + +Set-Alias contig Invoke-Contig + +function Test-FileFragmentation { + [CmdletBinding()] + param ( + # File to analyze + [Parameter(Mandatory)] + [System.IO.FileInfo] + $file + ) + + begin { + } + + process { + Invoke-Contig -a $file + } + + end { + } +} + +function Invoke-FileDefragmentation { + [CmdletBinding()] + param ( + # File to defragment + [Parameter(Mandatory)] + [System.IO.FileInfo] + $file + ) + + begin { + } + + process { + $start = Get-Date; + + Invoke-Contig $file + + $elapsed = (Get-Date) - $start; + + Write-Verbose "defrag of $file completed in $elapsed" + } + + end { + } +} + +Set-Alias defrag Invoke-FileDefragmentation + +# TODO implement +function Read-ContigOutput { + [CmdletBinding()] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [String] + $rawOutput + ) + + begin { + } + + process { + Write-Verbose $rawOutput + } + + end { + } +} From 436605a0322af6409008d6daa3e2a59277337806 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Feb 2021 13:20:40 +0100 Subject: [PATCH 07/50] refactor: remove deprecated module --- .../PSBackupMyStuff/PSBackupMyStuff.psm1 | 2 +- PSDockerUtils/PSDockerUtils.psm1 | 94 ------------------- 2 files changed, 1 insertion(+), 95 deletions(-) delete mode 100644 PSDockerUtils/PSDockerUtils.psm1 diff --git a/BackupAndRestoreStuff/PSBackupMyStuff/PSBackupMyStuff.psm1 b/BackupAndRestoreStuff/PSBackupMyStuff/PSBackupMyStuff.psm1 index 85ce598..218c4b0 100644 --- a/BackupAndRestoreStuff/PSBackupMyStuff/PSBackupMyStuff.psm1 +++ b/BackupAndRestoreStuff/PSBackupMyStuff/PSBackupMyStuff.psm1 @@ -42,7 +42,7 @@ function Export-ScoopPackages { # "npm install" takes multiple arguments separated by space function Export-NpmGlobalPackages { # FIXME not cross platform - $rawList = npm.cmd list --global --depth=0 --parseable + $rawList = npm list --global --depth=0 --parseable $baseFolder, $packages = $rawList $basePath = Join-Path $baseFolder "node_modules\" diff --git a/PSDockerUtils/PSDockerUtils.psm1 b/PSDockerUtils/PSDockerUtils.psm1 deleted file mode 100644 index 178b1ca..0000000 --- a/PSDockerUtils/PSDockerUtils.psm1 +++ /dev/null @@ -1,94 +0,0 @@ -function Switch-DockerHost { - [CmdletBinding()] - param ( - [Parameter(Position = 0)] - [ValidateSet('local', 'erclu-server')] - [string] - $dockerHost, - [switch] - $persist - ) - - switch ($dockerHost) { - local { - Write-Verbose "switching to local docker host" - $targetDockerMachine = "default" - - # & "C:\Program Files\Git\bin\bash.exe" --login -i "C:\Program Files\Docker Toolbox\start.sh" - } - - erclu-server { - Write-Verbose "switching DOCKER_HOST to erclu-server via ssh" - $targetDockerMachine = "erclu-server" - - # $env:DOCKER_HOST = "ssh://erclu@192.168.1.81" - } - Default { - $hereString = @" -CURRENT DOCKER ENVIRONMENT VARIABLES: - -DOCKER_HOST=$($env:DOCKER_HOST) - -DOCKER_CERT_PATH=$($env:DOCKER_CERT_PATH) -DOCKER_TLS_VERIFY=$($env:DOCKER_TLS_VERIFY) - this should never change -DOCKER_MACHINE_NAME=$($env:DOCKER_MACHINE_NAME) -MACHINE_STORAGE_PATH=$($env:MACHINE_STORAGE_PATH) - this should never change -COMPOSE_CONVERT_WINDOWS_PATHS=$($env:COMPOSE_CONVERT_WINDOWS_PATHS) - this should never change -"@ - - Write-Output $hereString - - return 0 - } - } - - docker-machine env $targetDockerMachine --shell powershell | Invoke-Expression - - docker-machine start $targetDockerMachine - - if ($persist) { - [environment]::setEnvironmentVariable('DOCKER_TLS_VERIFY', $env:DOCKER_TLS_VERIFY, 'User') - [environment]::setEnvironmentVariable('DOCKER_HOST', $env:DOCKER_HOST, 'User') - [environment]::setEnvironmentVariable('DOCKER_CERT_PATH', $env:DOCKER_CERT_PATH, 'User') - [environment]::setEnvironmentVariable('DOCKER_MACHINE_NAME', $env:DOCKER_MACHINE_NAME, 'User') - [environment]::setEnvironmentVariable('COMPOSE_CONVERT_WINDOWS_PATHS', $env:COMPOSE_CONVERT_WINDOWS_PATHS, 'User') - - if (Get-Process "code" -ErrorAction SilentlyContinue) { - Write-Warning "you probably need to restart vscode" - Write-Warning "!!! remember that vscode explorer does NOT work on remote host" - } - } -} - -function Start-DockerToolbox { - [CmdletBinding()] - param ( - [Parameter()] - [Switch] - $RegenerateCerts - ) - docker-machine start default - - if ($RegenerateCerts) { - Start-Sleep -Seconds 1 - - "y" | docker-machine regenerate-certs - } -} - -function Stop-DockerToolbox { - docker-machine stop default -} - - -function ForwardDockerMachine { - [CmdletBinding()] - param ( - # Parameter help description - [Parameter(Mandatory)] - [string] - $port - ) - - docker-machine ssh default -N -L "$($port):localhost:$($port)" -} From 3534ba0c82c7c532ebe31177fc9413c61fdb380a Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Feb 2021 13:22:21 +0100 Subject: [PATCH 08/50] feat: remove datetime cutoff in get-oldvscodeextensions --- PSUtils/PSUtils.psm1 | 83 ++++++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 50 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 59a722d..adaf4ce 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -30,7 +30,7 @@ function Update-ScoopAndCleanAfter { $telegram = "telegram" scoop update - $out = scoop status + $out = scoop status 6>&1 $out if ($out -match $telegram) { Write-Output "stopping telegram..." @@ -161,39 +161,6 @@ function Find-HardLinks { Select-Object FullName, LinkType, Target } -######################################################################################################################## -####################################### Send Magic Packet -######################################################################################################################## - -<# - .SYNOPSIS - Send a WOL packet to a broadcast address - .PARAMETER mac - The MAC address of the device that need to wake up - .PARAMETER ip - The IP address where the WOL packet will be sent to - .EXAMPLE - Send-WOL -mac 00:11:32:21:2D:11 -ip 192.168.8.255 -#> -function Send-MagicPacket { - [CmdletBinding()] - param( - [Parameter(Mandatory = $True, Position = 1)] - [string]$mac, - [string]$ip = "255.255.255.255", - [int]$port = 9 - ) - $broadcast = [Net.IPAddress]::Parse($ip) - - $mac = (($mac.replace(":", "")).replace("-", "")).replace(".", "") - $target = 0, 2, 4, 6, 8, 10 | ForEach-Object { [convert]::ToByte($mac.substring($_, 2), 16) } - $packet = (, [byte]255 * 6) + ($target * 16) - - $UDPclient = New-Object System.Net.Sockets.UdpClient - $UDPclient.Connect($broadcast, $port) - [void]$UDPclient.Send($packet, 102) -} - ######################################################################################################################## ####################################### Misc ######################################################################################################################## @@ -236,30 +203,46 @@ function Get-OldVsCodeExtensions { $SPLITTER_REGEX = "^(?.*?)-(?$SEMVER_REGEX)$" # if (-not $Aggro) { - $DATETIME_CUTOFF = (Get-Date).AddDays(-7) + # $DATETIME_CUTOFF = (Get-Date).AddDays(-7) # } # else { - # $DATETIME_CUTOFF = Get-Date + # $DATETIME_CUTOFF = Get-Date # } - Get-ChildItem -Directory -Path $VSCODE_EXTENSIONS_DIR | - Sort-Object -Descending CreationTime | - Where-Object LastWriteTime -GT $DATETIME_CUTOFF | - ForEach-Object { - $name = $_.Name - - if (-not ($name -match $SPLITTER_REGEX)) { - Write-Error "this name is not correctly matched: $name" + $parsedExtensionFolders = @( + Get-ChildItem -Directory -Path $VSCODE_EXTENSIONS_DIR | + Sort-Object -Descending CreationTime | + ForEach-Object { + $name = $_.Name + + if (-not ($name -match $SPLITTER_REGEX)) { + Write-Error "this name is not correctly matched: $name" + } + + [pscustomobject]@{ + Name = $Matches.name + Version = $Matches.version + Directory = $_ + } } + ) - [pscustomobject]@{ - Name = $Matches.name - Version = $Matches.version - Directory = $_ - } - } | + # $VSCODE_INSTALLED_EXTENSIONS = @(code --list-extensions) | + # ForEach-Object { + # [PSCustomObject]@{ + # Name = $_ + # } + # } + # $uniqueExtensionFoldersFound = @($parsedExtensionFolders | Sort-Object Name -Unique) + + # Compare-Object -PassThru $VSCODE_INSTALLED_EXTENSIONS $uniqueExtensionFoldersFound -Property Name | + # Where-Object SideIndicator -match "=>" | + # Select-Object Name, Version, Directory + + $parsedExtensionFolders | Group-Object Name | Where-Object Count -GT 1 | + # Where-Object LastWriteTime -GT $DATETIME_CUTOFF | ForEach-Object { $newest, $old = $_.Group From bfb6ca9988a496b26c716a55bcd0288bb9c0988e Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Feb 2021 13:23:00 +0100 Subject: [PATCH 09/50] feat: add single-purpose script to move docker desktop data wsl distro --- Scripts/Move-DockerDesktopDataDistro.ps1 | 39 ++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Scripts/Move-DockerDesktopDataDistro.ps1 diff --git a/Scripts/Move-DockerDesktopDataDistro.ps1 b/Scripts/Move-DockerDesktopDataDistro.ps1 new file mode 100644 index 0000000..53a510e --- /dev/null +++ b/Scripts/Move-DockerDesktopDataDistro.ps1 @@ -0,0 +1,39 @@ +[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] +param ( + # Path of tar file + [Parameter()] + [string] + $TarFileName = "W:\docker-desktop-data.tar", + # Path where the new distro is imported + [string] + [string] + $WslDistroDestination = "W:\docker-desktop-data\" +) + +Write-Output "shutting down WSL" +wsl --shutdown + +Write-Output "---" +wsl -l -v +Write-Output "---" + +if ($PSCmdlet.ShouldProcess($TarFileName, "export wsl distro")) { + wsl --export docker-desktop-data $TarFileName +} +else { + throw "cannot continue" +} + +if ($PSCmdlet.ShouldProcess("docker-desktop-data", "unregister wsl distro")) { + wsl --unregister docker-desktop-data +} +else { + throw "cannot continue" +} + +if ($PSCmdlet.ShouldProcess($WslDistroDestination, "import wsl distro")) { + wsl --import docker-desktop-data $WslDistroDestination $TarFileName --version 2 +} +else { + throw "cannot continue" +} From c598e145f23b852a45a380766c519c6777dc47df Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Feb 2021 13:25:43 +0100 Subject: [PATCH 10/50] feat: improve tracking dirty repositories --- Scripts/Get-DirtyRepositories.ps1 | 50 ++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 14 deletions(-) diff --git a/Scripts/Get-DirtyRepositories.ps1 b/Scripts/Get-DirtyRepositories.ps1 index b9d5ec2..5918037 100644 --- a/Scripts/Get-DirtyRepositories.ps1 +++ b/Scripts/Get-DirtyRepositories.ps1 @@ -24,10 +24,21 @@ function Test-HasDirtyIndex { param ( [Parameter(Mandatory)] [System.IO.DirectoryInfo] - $gitDir + $path ) - return $null -ne (git --git-dir $gitDir --work-tree $workTree status -s) + return $null -ne (git -C $path status -s) +} + +function Test-HasRemote { + [CmdletBinding()] + param ( + [Parameter(Mandatory)] + [System.IO.DirectoryInfo] + $path + ) + + return $null -ne (git -C $path remote -v) } function Test-HasUnpushedCommits { @@ -35,10 +46,10 @@ function Test-HasUnpushedCommits { param ( [Parameter(Mandatory)] [System.IO.DirectoryInfo] - $gitDir + $path ) - return $null -ne (git --git-dir $gitDir --work-tree $workTree log --branches --not --remotes --oneline) + return $null -ne (git -C $path log --branches --not --remotes --oneline) } function Test-HasForgottenStashes { @@ -46,11 +57,23 @@ function Test-HasForgottenStashes { param ( [Parameter(Mandatory)] [System.IO.DirectoryInfo] - $gitDir + $path + ) + + return $null -ne (git -C $path stash list) +} + +function Test-HasIgnoredFilesAndFolder { + [CmdletBinding()] + param ( + [Parameter(Mandatory)] + [System.IO.DirectoryInfo] + $path ) - return $null -ne (git --git-dir $gitDir stash list) + return ( git -C $path status -s --ignored ) | Measure-Object | Select-Object -ExpandProperty Count } + Write-Output "Searching for repositories in $RootFolder ..." $repos = Get-ChildItem -Verbose -Directory -Force -Recurse $RootFolder | @@ -67,21 +90,20 @@ Write-Output "found $($repos.Length) repos; checking status..." $repos | ForEach-Object { - $gitDir = $_ $workTree = Split-Path -Path $_ -Parent - $dirtyIndex = Test-HasDirtyIndex $gitDir - $unpushedCommits = Test-HasUnpushedCommits $gitDir - $forgottenStashes = Test-HasForgottenStashes $gitDir - - # TODO might wanna refactor this - $ignoredFilesAndFolders = ( git --git-dir $gitDir --work-tree $workTree status -s --ignored ) | Measure-Object | Select-Object -ExpandProperty Count + $dirtyIndex = Test-HasDirtyIndex $workTree + $hasRemote = Test-HasRemote $workTree + $unpushedCommits = Test-HasUnpushedCommits $workTree + $forgottenStashes = Test-HasForgottenStashes $workTree + $ignoredFilesAndFolders = Test-HasIgnoredFilesAndFolder $workTree [pscustomobject]@{ PSTypename = "GitRepo" Repo = $workTree - AllGood = -not ($dirtyIndex -or $unpushedCommits -or $forgottenStashes ) + AllGood = -not ($dirtyIndex -or $hasRemote -or $unpushedCommits -or $forgottenStashes ) ChangesToCommit = $dirtyIndex + HasRemote = $hasRemote CommitsToPush = $unpushedCommits StashesToClear = $forgottenStashes # AllGood does not count these From e7a540747aaf0fcad0c8d7bcafd9cf1dc4c8220a Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Feb 2021 17:29:31 +0100 Subject: [PATCH 11/50] feat: add wol and watch scripts --- Scripts/Wake.ps1 | 79 ++++++++++++++++++++++++ Scripts/Watch-Command.ps1 | 123 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 Scripts/Wake.ps1 create mode 100644 Scripts/Watch-Command.ps1 diff --git a/Scripts/Wake.ps1 b/Scripts/Wake.ps1 new file mode 100644 index 0000000..dab82f9 --- /dev/null +++ b/Scripts/Wake.ps1 @@ -0,0 +1,79 @@ +####################################################### +## +## Wake.ps1, v1.0, 2013 +## +## Adapted by Ammaar Limbada +## Original Author: Matthijs ten Seldam, Microsoft (see: http://blogs.technet.com/matthts) +## +####################################################### + +<# +.SYNOPSIS +Starts a list of physical machines by using Wake On LAN. + +.DESCRIPTION +Wake sends a Wake On LAN magic packet to a given machine's MAC address. + +.PARAMETER MacAddress +MacAddress of target machine to wake. + +.EXAMPLE +Wake A0DEF169BE02 + +.INPUTS +None + +.OUTPUTS +None + +.NOTES +Make sure the MAC addresses supplied don't contain "-" or ".". +#> + + +param( [Parameter(Mandatory = $true, HelpMessage = "MAC address of target machine to wake up")] + [string] $MacAddress ) + + +Set-StrictMode -Version Latest + +function Send-Packet([string]$MacAddress) { + <# + .SYNOPSIS + Sends a number of magic packets using UDP broadcast. + + .DESCRIPTION + Send-Packet sends a specified number of magic packets to a MAC address in order to wake up the machine. + + .PARAMETER MacAddress + The MAC address of the machine to wake up. + #> + + try { + $Broadcast = ([System.Net.IPAddress]::Broadcast) + + ## Create UDP client instance + $UdpClient = New-Object Net.Sockets.UdpClient + + ## Create IP endpoints for each port + $IPEndPoint = New-Object Net.IPEndPoint $Broadcast, 9 + + ## Construct physical address instance for the MAC address of the machine (string to byte array) + $MAC = [Net.NetworkInformation.PhysicalAddress]::Parse($MacAddress.ToUpper()) + + ## Construct the Magic Packet frame + $Packet = [Byte[]](, 0xFF * 6) + ($MAC.GetAddressBytes() * 16) + + ## Broadcast UDP packets to the IP endpoint of the machine + $UdpClient.Send($Packet, $Packet.Length, $IPEndPoint) | Out-Null + $UdpClient.Close() + } + catch { + $UdpClient.Dispose() + $Error | Write-Error; + } +} + +## Send magic packet to wake machine +Write-Output "Sending magic packet to $MacAddress" +Send-Packet $MacAddress diff --git a/Scripts/Watch-Command.ps1 b/Scripts/Watch-Command.ps1 new file mode 100644 index 0000000..6ca55bf --- /dev/null +++ b/Scripts/Watch-Command.ps1 @@ -0,0 +1,123 @@ +############################################################################## +## +## Watch-Command +## +## From Windows PowerShell Cookbook (O'Reilly) +## by Lee Holmes (http://www.leeholmes.com/guide) +## +## as found on https://www.powershellcookbook.com/recipe/PrtD/program-monitor-a-command-for-changes +## +############################################################################## + +<# + +.SYNOPSIS + +Watches the result of a command invocation, alerting you when the output +either matches a specified string, lacks a specified string, or has simply +changed. + +.EXAMPLE + +PS > Watch-Command { Get-Process -Name Notepad | Measure } -UntilChanged +Monitors Notepad processes until you start or stop one. + +.EXAMPLE + +PS > Watch-Command { Get-Process -Name Notepad | Measure } -Until "Count : 1" +Monitors Notepad processes until there is exactly one open. + +.EXAMPLE + +PS > Watch-Command { + Get-Process -Name Notepad | Measure } -While 'Count : \d\s*\n' +Monitors Notepad processes while there are between 0 and 9 open +(once number after the colon). + +#> + + +[CmdletBinding(DefaultParameterSetName = "Forever")] +param( + ## The script block to invoke while monitoring + [Parameter(Mandatory = $true, Position = 0)] + [ScriptBlock] $ScriptBlock, + + ## The delay, in seconds, between monitoring attempts + [Parameter()] + [Double] $DelaySeconds = 1, + + ## Specifies that the alert sound should not be played + [Parameter()] + [Switch] $Quiet, + + ## Monitoring continues only while the output of the + ## command remains the same. + [Parameter(ParameterSetName = "UntilChanged", Mandatory = $false)] + [Switch] $UntilChanged, + + ## The regular expression to search for. Monitoring continues + ## until this expression is found. + [Parameter(ParameterSetName = "Until", Mandatory = $false)] + [String] $Until, + + ## The regular expression to search for. Monitoring continues + ## until this expression is not found. + [Parameter(ParameterSetName = "While", Mandatory = $false)] + [String] $While +) + +Set-StrictMode -Version 3 + +$initialOutput = "" + +## Start a continuous loop +while ($true) { + ## Run the provided script block + $r = & $ScriptBlock + + ## Clear the screen and display the results + Clear-Host + $ScriptBlock.ToString().Trim() + "" + $textOutput = $r | Out-String + $textOutput + + ## Remember the initial output, if we haven't + ## stored it yet + if (-not $initialOutput) { + $initialOutput = $textOutput + } + + ## If we are just looking for any change, + ## see if the text has changed. + if ($UntilChanged) { + if ($initialOutput -ne $textOutput) { + break + } + } + + ## If we need to ensure some text is found, + ## break if we didn't find it. + if ($While) { + if ($textOutput -notmatch $While) { + break + } + } + + ## If we need to wait for some text to be found, + ## break if we find it. + if ($Until) { + if ($textOutput -match $Until) { + break + } + } + + ## Delay + Start-Sleep -Seconds $DelaySeconds +} + +## Notify the user +if (-not $Quiet) { + [Console]::Beep(1000, 1000) +} From c7f48b6758ba2f734ff0d507e6a6e67739856777 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Feb 2021 17:34:31 +0100 Subject: [PATCH 12/50] feat: move stuff from profile to psutils and fix get dirty repos --- PSUtils/PSUtils.psm1 | 44 ++++++++++++++++++++++++++----- Scripts/Get-DirtyRepositories.ps1 | 10 +++---- 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index adaf4ce..cb06030 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -23,6 +23,26 @@ function Get-ScoopSize { } } +function Update-EverythingHaphazardly { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param () + + if (-not $PSCmdlet.ShouldProcess("Update apps")) { + return + } + + pipx upgrade-all + + Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) + + npm update -g npm@7 + npm update -g + + Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) + + Update-ScoopAndCleanAfter +} + function Update-ScoopAndCleanAfter { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param () @@ -118,6 +138,13 @@ function Test-BomHereRecursive { Where-Object { -not (Test-ContainsBOM $_) } | Select-Object FullName } + +function Get-BranchAndSha { + param () + + "$(git branch --show-current)-$(git rev-parse --short HEAD)" +} + function Find-Duplicates { [CmdletBinding()] param ( @@ -129,16 +156,19 @@ function Find-Duplicates { } function New-TemporaryDirectory { - $parent = [System.IO.Path]::GetTempPath() - [string] $name = [System.Guid]::NewGuid() - New-Item -ItemType Directory -Path (Join-Path $parent $name) -} + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')] + param() -function New-FastTemporaryDirectory { - [string] $name = [System.Guid]::NewGuid() - New-Item -ItemType Directory -Path ("C:/TEMP-$name") + if ($PSCmdlet.ShouldProcess("Create new temporary directory")) { + New-Item -ItemType Directory -Path (Join-Path ([System.IO.Path]::GetTempPath()) ([System.Guid]::NewGuid())) + } } +# function New-FastTemporaryDirectory { +# [string] $name = [System.Guid]::NewGuid() +# New-Item -ItemType Directory -Path ("C:/TEMP-$name") +# } + ######################################################################################################################## ####################################### Hardlinks utils ######################################################################################################################## diff --git a/Scripts/Get-DirtyRepositories.ps1 b/Scripts/Get-DirtyRepositories.ps1 index 5918037..36a56ec 100644 --- a/Scripts/Get-DirtyRepositories.ps1 +++ b/Scripts/Get-DirtyRepositories.ps1 @@ -30,7 +30,7 @@ function Test-HasDirtyIndex { return $null -ne (git -C $path status -s) } -function Test-HasRemote { +function Test-HasNoRemote { [CmdletBinding()] param ( [Parameter(Mandatory)] @@ -38,7 +38,7 @@ function Test-HasRemote { $path ) - return $null -ne (git -C $path remote -v) + return $null -eq (git -C $path remote -v) } function Test-HasUnpushedCommits { @@ -93,7 +93,7 @@ $repos | $workTree = Split-Path -Path $_ -Parent $dirtyIndex = Test-HasDirtyIndex $workTree - $hasRemote = Test-HasRemote $workTree + $hasNoRemote = Test-HasNoRemote $workTree $unpushedCommits = Test-HasUnpushedCommits $workTree $forgottenStashes = Test-HasForgottenStashes $workTree $ignoredFilesAndFolders = Test-HasIgnoredFilesAndFolder $workTree @@ -101,9 +101,9 @@ $repos | [pscustomobject]@{ PSTypename = "GitRepo" Repo = $workTree - AllGood = -not ($dirtyIndex -or $hasRemote -or $unpushedCommits -or $forgottenStashes ) + AllGood = -not ($dirtyIndex -or $hasNoRemote -or $unpushedCommits -or $forgottenStashes ) ChangesToCommit = $dirtyIndex - HasRemote = $hasRemote + HasNoRemote = $hasNoRemote CommitsToPush = $unpushedCommits StashesToClear = $forgottenStashes # AllGood does not count these From e63e0f5255a61cc63ca8227bc198185ac2be10e1 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 11 Feb 2021 19:25:24 +0100 Subject: [PATCH 13/50] refactor: add stub for new function and fix error when updating npm packages --- PSUtils/PSUtils.psm1 | 8 ++++++-- Scripts/Find-Duplicates.ps1 | 16 ++++++++++++++++ Scripts/Get-DirtyRepositories.ps1 | 19 +++++-------------- 3 files changed, 27 insertions(+), 16 deletions(-) create mode 100644 Scripts/Find-Duplicates.ps1 diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index cb06030..e36833c 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -30,15 +30,19 @@ function Update-EverythingHaphazardly { if (-not $PSCmdlet.ShouldProcess("Update apps")) { return } + Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) + Write-Output "Updating pipx packages" pipx upgrade-all Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) + Write-Output "Updating npm@7, then typescript commitizen jscpd (HARDCODED)" - npm update -g npm@7 - npm update -g + npm install -g npm@7 + npm install -g typescript commitizen jscpd Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) + Write-Output "Updating scoop packages" Update-ScoopAndCleanAfter } diff --git a/Scripts/Find-Duplicates.ps1 b/Scripts/Find-Duplicates.ps1 new file mode 100644 index 0000000..30d0548 --- /dev/null +++ b/Scripts/Find-Duplicates.ps1 @@ -0,0 +1,16 @@ +[CmdletBinding()] +param ( + [Parameter()] + [System.IO.DirectoryInfo[]] + $Paths = (Get-Location) +) + +# TODO implement me +throw "NOT IMPLEMENTED" + +$files = Get-ChildItem -LiteralPath $Paths + +$files | ForEach-Object { + $size = $_.Length + +} diff --git a/Scripts/Get-DirtyRepositories.ps1 b/Scripts/Get-DirtyRepositories.ps1 index 36a56ec..4c908c0 100644 --- a/Scripts/Get-DirtyRepositories.ps1 +++ b/Scripts/Get-DirtyRepositories.ps1 @@ -10,15 +10,6 @@ param ( # TODO export type data? # Update-TypeData ... -$forEachArguments = @{ - OutVariable = if ($SaveToVariable) { - "OutVariable" - } - else { - $null - } -} - function Test-HasDirtyIndex { [CmdletBinding()] param ( @@ -109,9 +100,9 @@ $repos | # AllGood does not count these Ignored = $ignoredFilesAndFolders } - } @forEachArguments + } -if ($SaveToVariable) { - Write-Verbose "setting variable $SaveToVariable in parent scope" - Set-Variable -Scope 1 -Name $SaveToVariable -Value $OutVariable -} +# if ($SaveToVariable) { +# Write-Verbose "setting variable $SaveToVariable in parent scope" +# Set-Variable -Scope 1 -Name $SaveToVariable -Value $OutVariable +# } From c83af8ea17a6eb93099051d4b602d1199306afcc Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 12 Feb 2021 13:23:06 +0100 Subject: [PATCH 14/50] feat: add windows proxy utility functions --- ProxyUtils/ProxyUtils.psm1 | 95 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 ProxyUtils/ProxyUtils.psm1 diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 new file mode 100644 index 0000000..13d4d75 --- /dev/null +++ b/ProxyUtils/ProxyUtils.psm1 @@ -0,0 +1,95 @@ +$PROXY_REGISTRY_PATH = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' + +function Get-NetProxy { + [CmdletBinding()] + param ( + [switch] + $Raw + ) + + $rawObject = Get-ItemProperty -Path $PROXY_REGISTRY_PATH + + if ($Raw) { + $rawObject + } + else { + $arguments = @{ + Property = @(@{ + Name = 'IsEnabled' + Expression = { $_.ProxyEnable -eq 1 } + } + @{ + Name = 'Server Address' + Expression = { $_.ProxyServer } + } + @{ + Name = 'Exclusions' + Expression = { + $_.ProxyOverride -split ";" + } + } + ) + } + + + $rawObject | Select-Object @arguments + # $rawObject | Select-Object ProxyEnable, ProxyServer, @{Name = 'Exclusions'; Expression = { $_.ProxyOverride -split ";" } } + } +} + +function Set-NetProxy { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] + [Alias('proxy')] + [OutputType([string])] + Param + ( + # server address + # [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)] + [Parameter(Position = 0)] + [String] + $server, + # port number + # [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)] + [Parameter(Position = 1)] + [String] + $port, + # exclusions + [Parameter(Position = 2)] + [String[]] + $exclusions + ) + + process { + #Test if the TCP Port on the server is open before applying the settings + If (-not (Test-NetConnection -ComputerName $server -Port $port).TcpTestSucceeded) { + Write-Error -Message "The proxy address is not valid: $($server):$($port)" + } + Else { + if ($server -and $port) { + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "$($server):$($port)" + } + if ($exclusions) { + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value ($exclusions -join ";") + } + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 1 + } + + Get-NetProxy + } +} + +function Remove-NetProxy { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] + [Alias('Unset-NetProxy')] + param ( + [switch] + $RemoveProxyServerAddress + ) + + if ($RemoveProxyServerAddress) { + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "" + } + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 + + Get-NetProxy +} From 11445052d0b954c8eaed2a46a4f683cf1981be08 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Sun, 14 Feb 2021 15:49:18 +0100 Subject: [PATCH 15/50] refactor: some small things --- BitwardenWrapper/BitwardenWrapper.psm1 | 7 ++++++- PSUtils/PSUtils.psm1 | 5 ++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/BitwardenWrapper/BitwardenWrapper.psm1 b/BitwardenWrapper/BitwardenWrapper.psm1 index 50ae3c9..fc6d73b 100644 --- a/BitwardenWrapper/BitwardenWrapper.psm1 +++ b/BitwardenWrapper/BitwardenWrapper.psm1 @@ -62,7 +62,12 @@ function Test-ContainsSensitiveWords { $SensitiveWords ) - return $null -ne ($SensitiveWords | Where-Object { $InputString -match $_ } | Select-Object -First 1) + process { + Write-Output "matching each of $SensitiveWords against $InputString" + + return $null -ne ($SensitiveWords | Where-Object { $InputString -match $SensitiveWords } | Select-Object -First 1) + } + } # Unlock-BitwardenDatabase diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index e36833c..fa874b2 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -36,10 +36,9 @@ function Update-EverythingHaphazardly { pipx upgrade-all Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) - Write-Output "Updating npm@7, then typescript commitizen jscpd (HARDCODED)" + Write-Output "Updating npm global packages" - npm install -g npm@7 - npm install -g typescript commitizen jscpd + npm update -g Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) Write-Output "Updating scoop packages" From 0b324acdf4e79692777f68e46ce3df44f6e84cae Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 16 Feb 2021 13:25:09 +0100 Subject: [PATCH 16/50] feat: add winhttp proxy functions to module --- ProxyUtils/ProxyUtils.psm1 | 45 ++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 13d4d75..72e6df8 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -1,19 +1,17 @@ $PROXY_REGISTRY_PATH = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -function Get-NetProxy { +function Get-Proxy { [CmdletBinding()] param ( [switch] $Raw ) - $rawObject = Get-ItemProperty -Path $PROXY_REGISTRY_PATH - - if ($Raw) { - $rawObject + $arguments = if ($Raw) { + @{ Property = "*" } } else { - $arguments = @{ + @{ Property = @(@{ Name = 'IsEnabled' Expression = { $_.ProxyEnable -eq 1 } @@ -30,26 +28,22 @@ function Get-NetProxy { } ) } - - - $rawObject | Select-Object @arguments - # $rawObject | Select-Object ProxyEnable, ProxyServer, @{Name = 'Exclusions'; Expression = { $_.ProxyOverride -split ";" } } } + + Get-ItemProperty -Path $PROXY_REGISTRY_PATH | Select-Object @arguments } -function Set-NetProxy { +function Enable-Proxy { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] [Alias('proxy')] [OutputType([string])] Param ( # server address - # [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)] [Parameter(Position = 0)] [String] $server, # port number - # [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)] [Parameter(Position = 1)] [String] $port, @@ -61,10 +55,10 @@ function Set-NetProxy { process { #Test if the TCP Port on the server is open before applying the settings - If (-not (Test-NetConnection -ComputerName $server -Port $port).TcpTestSucceeded) { + if (-not (Test-NetConnection -ComputerName $server -Port $port).TcpTestSucceeded) { Write-Error -Message "The proxy address is not valid: $($server):$($port)" } - Else { + else { if ($server -and $port) { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "$($server):$($port)" } @@ -74,13 +68,12 @@ function Set-NetProxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 1 } - Get-NetProxy + Get-Proxy } } -function Remove-NetProxy { +function Disable-Proxy { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] - [Alias('Unset-NetProxy')] param ( [switch] $RemoveProxyServerAddress @@ -91,5 +84,19 @@ function Remove-NetProxy { } Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 - Get-NetProxy + Get-Proxy +} + +function Import-WinHttpProxyFromIeProxy { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] + param () + + sudo netsh winhttp import proxy source=ie +} + +function Reset-WinHttpProxy { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] + param () + + sudo netsh winhttp reset proxy } From feda14a5dcc6c7bc508d0defcaff38b5415f1d84 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Wed, 17 Feb 2021 13:17:39 +0100 Subject: [PATCH 17/50] feat: add new git gc util and refactor proxy utils --- PSUtils/PSUtils.psm1 | 16 ++++++++++ ProxyUtils/ProxyUtils.psm1 | 32 ++++++++++++------- ...e-GitGarbageCollectorInAllRepositories.ps1 | 10 +++--- 3 files changed, 41 insertions(+), 17 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index fa874b2..c8a2bb2 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -286,3 +286,19 @@ function Get-OldVsCodeExtensions { $_ } } + +function Invoke-GitGcWithReflogExpire { + [CmdletBinding()] + [Alias("git-gc-turbo-aggro")] + param ( + # Work tree of the repository where git gc should be invoked + [Parameter(Position = 0)] + [System.IO.DirectoryInfo] + $Path = (Get-Location) + ) + + process { + git -C $Path reflog expire --expire-unreachable=now --all + git -C $Path gc --aggressive --prune=now + } +} diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 72e6df8..4af8547 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -42,30 +42,36 @@ function Enable-Proxy { # server address [Parameter(Position = 0)] [String] - $server, + $ProxyHost, # port number [Parameter(Position = 1)] [String] - $port, - # exclusions + $ProxyPort, + # Exclusions [Parameter(Position = 2)] [String[]] - $exclusions + $Exclusions ) process { + $ProxyServer = "$($ProxyHost):$($ProxyPort)" + #Test if the TCP Port on the server is open before applying the settings - if (-not (Test-NetConnection -ComputerName $server -Port $port).TcpTestSucceeded) { - Write-Error -Message "The proxy address is not valid: $($server):$($port)" + if (-not (Test-NetConnection -ComputerName $ProxyHost -Port $ProxyPort).TcpTestSucceeded) { + Write-Error -Message "The proxy address is not valid: $ProxyServer" } else { - if ($server -and $port) { - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "$($server):$($port)" + if ($ProxyHost -and $ProxyHost) { + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value $ProxyServer } - if ($exclusions) { - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value ($exclusions -join ";") + if ($Exclusions) { + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value ($Exclusions -join ";") } - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 1 + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 1 + + (ipconfig /flushdns && ipconfig /registerdns) | + Out-String | + Write-Verbose } Get-Proxy @@ -84,6 +90,10 @@ function Disable-Proxy { } Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 + ipconfig /flushdns && ipconfig /registerdns | + Out-String | + Write-Verbose + Get-Proxy } diff --git a/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 b/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 index 7aaedcd..dabead8 100644 --- a/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 +++ b/Scripts/Invoke-GitGarbageCollectorInAllRepositories.ps1 @@ -23,16 +23,14 @@ Write-Output "Found $($repos.Length) repos." $repos | ForEach-Object { - $gitDir = $_ $workTree = Split-Path -Path $_ -Parent Write-Output "running aggressive garbage collection in $workTree" - if ($Quiet) { - git --git-dir $gitDir gc --aggressive | Out-Null - } - else { - git --git-dir $gitDir gc --aggressive + $output = git -C $workTree gc --aggressive + + if (-not $Quiet) { + Write-Output $output } if ($LASTEXITCODE) { From 82df5121aa376208d5eb51ea37adf02e6bddedee Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 18 Feb 2021 17:52:15 +0100 Subject: [PATCH 18/50] fix: count ignored files correctly and refactor stuff --- ProxyUtils/ProxyUtils.psm1 | 16 ++++++++++++++-- Scripts/Get-DirtyRepositories.ps1 | 27 +++++++++++++++------------ 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 4af8547..ccce21d 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -50,7 +50,9 @@ function Enable-Proxy { # Exclusions [Parameter(Position = 2)] [String[]] - $Exclusions + $Exclusions, + [Switch] + $ImportWinHttpProxy ) process { @@ -72,6 +74,10 @@ function Enable-Proxy { (ipconfig /flushdns && ipconfig /registerdns) | Out-String | Write-Verbose + + if ($ImportWinHttpProxy) { + Import-WinHttpProxyFromIeProxy + } } Get-Proxy @@ -82,7 +88,9 @@ function Disable-Proxy { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] param ( [switch] - $RemoveProxyServerAddress + $RemoveProxyServerAddress, + [switch] + $ResetWinHttpProxy ) if ($RemoveProxyServerAddress) { @@ -94,6 +102,10 @@ function Disable-Proxy { Out-String | Write-Verbose + if ($ResetWinHttpProxy) { + Reset-WinHttpProxy + } + Get-Proxy } diff --git a/Scripts/Get-DirtyRepositories.ps1 b/Scripts/Get-DirtyRepositories.ps1 index 4c908c0..57570ee 100644 --- a/Scripts/Get-DirtyRepositories.ps1 +++ b/Scripts/Get-DirtyRepositories.ps1 @@ -10,7 +10,7 @@ param ( # TODO export type data? # Update-TypeData ... -function Test-HasDirtyIndex { +function Test-HasUncommittedChanges { [CmdletBinding()] param ( [Parameter(Mandatory)] @@ -29,7 +29,7 @@ function Test-HasNoRemote { $path ) - return $null -eq (git -C $path remote -v) + return $null -eq (git -C $path remote) } function Test-HasUnpushedCommits { @@ -62,7 +62,10 @@ function Test-HasIgnoredFilesAndFolder { $path ) - return ( git -C $path status -s --ignored ) | Measure-Object | Select-Object -ExpandProperty Count + return ( git -C $path status -s --ignored ) | + Select-String -Pattern "^!!" | + Measure-Object | + Select-Object -ExpandProperty Count } Write-Output "Searching for repositories in $RootFolder ..." @@ -83,22 +86,22 @@ $repos | ForEach-Object { $workTree = Split-Path -Path $_ -Parent - $dirtyIndex = Test-HasDirtyIndex $workTree + $uncommittedChanges = Test-HasUncommittedChanges $workTree $hasNoRemote = Test-HasNoRemote $workTree $unpushedCommits = Test-HasUnpushedCommits $workTree $forgottenStashes = Test-HasForgottenStashes $workTree $ignoredFilesAndFolders = Test-HasIgnoredFilesAndFolder $workTree [pscustomobject]@{ - PSTypename = "GitRepo" - Repo = $workTree - AllGood = -not ($dirtyIndex -or $hasNoRemote -or $unpushedCommits -or $forgottenStashes ) - ChangesToCommit = $dirtyIndex - HasNoRemote = $hasNoRemote - CommitsToPush = $unpushedCommits - StashesToClear = $forgottenStashes + PSTypename = "GitRepo" + Repo = $workTree + AllGood = -not ($uncommittedChanges -or $hasNoRemote -or $unpushedCommits -or $forgottenStashes ) + UncommittedChanges = $uncommittedChanges + HasNoRemote = $hasNoRemote + CommitsToPush = $unpushedCommits + StashesToClear = $forgottenStashes # AllGood does not count these - Ignored = $ignoredFilesAndFolders + Ignored = $ignoredFilesAndFolders } } From 9b6f4fbdd21912d401ec982557c544f7df8e0770 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 19 Feb 2021 13:38:40 +0100 Subject: [PATCH 19/50] fix: wrong property name when setting proxy exclusions --- ProxyUtils/ProxyUtils.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index ccce21d..65a992e 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -67,7 +67,7 @@ function Enable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value $ProxyServer } if ($Exclusions) { - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value ($Exclusions -join ";") + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value ($Exclusions -join ";") } Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 1 From a6d62fa855a6aa1b4e5806c34f263933c52d0acd Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Mon, 22 Feb 2021 09:51:05 +0100 Subject: [PATCH 20/50] refactor: do not flush dns by default --- PSUtils/PSUtils.psm1 | 2 +- ProxyUtils/ProxyUtils.psm1 | 47 +++++++++++++++++++------------------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index c8a2bb2..92c559a 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -294,7 +294,7 @@ function Invoke-GitGcWithReflogExpire { # Work tree of the repository where git gc should be invoked [Parameter(Position = 0)] [System.IO.DirectoryInfo] - $Path = (Get-Location) + $Path = "." ) process { diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 65a992e..62e51ec 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -3,7 +3,7 @@ $PROXY_REGISTRY_PATH = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet function Get-Proxy { [CmdletBinding()] param ( - [switch] + [Switch] $Raw ) @@ -22,9 +22,7 @@ function Get-Proxy { } @{ Name = 'Exclusions' - Expression = { - $_.ProxyOverride -split ";" - } + Expression = { $_.ProxyOverride -split ";" } } ) } @@ -35,16 +33,14 @@ function Get-Proxy { function Enable-Proxy { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] - [Alias('proxy')] - [OutputType([string])] Param ( # server address - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] [String] $ProxyHost, # port number - [Parameter(Position = 1)] + [Parameter(Position = 1, Mandatory)] [String] $ProxyPort, # Exclusions @@ -52,7 +48,9 @@ function Enable-Proxy { [String[]] $Exclusions, [Switch] - $ImportWinHttpProxy + $ImportWinHttpProxy, + [switch] + $FlushDns ) process { @@ -63,17 +61,15 @@ function Enable-Proxy { Write-Error -Message "The proxy address is not valid: $ProxyServer" } else { - if ($ProxyHost -and $ProxyHost) { - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value $ProxyServer - } - if ($Exclusions) { - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value ($Exclusions -join ";") - } Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 1 + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value $ProxyServer + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value ($Exclusions -join ";") - (ipconfig /flushdns && ipconfig /registerdns) | - Out-String | - Write-Verbose + if ($FlushDns) { + (ipconfig /flushdns && ipconfig /registerdns) | + Out-String | + Write-Verbose + } if ($ImportWinHttpProxy) { Import-WinHttpProxyFromIeProxy @@ -90,17 +86,22 @@ function Disable-Proxy { [switch] $RemoveProxyServerAddress, [switch] - $ResetWinHttpProxy + $ResetWinHttpProxy, + [switch] + $FlushDns ) + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 + if ($RemoveProxyServerAddress) { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "" } - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 - ipconfig /flushdns && ipconfig /registerdns | - Out-String | - Write-Verbose + if ($FlushDns) { + ipconfig /flushdns && ipconfig /registerdns | + Out-String | + Write-Verbose + } if ($ResetWinHttpProxy) { Reset-WinHttpProxy From 2c7e902c90fd6ceffb216bed9679652041e9d661 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Mar 2021 10:34:44 +0100 Subject: [PATCH 21/50] feat: show winhttp proxy settings in get-proxy --- ProxyUtils/ProxyUtils.psm1 | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 62e51ec..5d3d759 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -4,7 +4,9 @@ function Get-Proxy { [CmdletBinding()] param ( [Switch] - $Raw + $Raw, + [Switch] + $ShowWinHttpProxy ) $arguments = if ($Raw) { @@ -29,6 +31,10 @@ function Get-Proxy { } Get-ItemProperty -Path $PROXY_REGISTRY_PATH | Select-Object @arguments + + if ($ShowWinHttpProxy) { + netsh winhttp show proxy + } } function Enable-Proxy { From c8b6debf338ecf664b0e0a7307d50ad4ff1858f7 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 2 Mar 2021 11:34:18 +0100 Subject: [PATCH 22/50] feat: remove exclusions when resetting proxy --- ProxyUtils/ProxyUtils.psm1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 5d3d759..0215b87 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -90,7 +90,7 @@ function Disable-Proxy { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] param ( [switch] - $RemoveProxyServerAddress, + $RemoveProxySettings, [switch] $ResetWinHttpProxy, [switch] @@ -99,8 +99,9 @@ function Disable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 - if ($RemoveProxyServerAddress) { + if ($RemoveProxySettings) { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "" + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyOverride -Value "" } if ($FlushDns) { From 97bea98973397ddf571a714099a7517c24ab6402 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Wed, 10 Mar 2021 18:11:59 +0100 Subject: [PATCH 23/50] feat: improve bitwardenwrapper and set proxy env vars on windows --- BitwardenWrapper/BitwardenWrapper.psd1 | 5 ++-- BitwardenWrapper/BitwardenWrapper.psm1 | 35 ++++++++++++++++---------- PSUtils/PSUtils.psm1 | 8 +++--- ProxyUtils/ProxyUtils.psm1 | 8 ++++++ 4 files changed, 37 insertions(+), 19 deletions(-) diff --git a/BitwardenWrapper/BitwardenWrapper.psd1 b/BitwardenWrapper/BitwardenWrapper.psd1 index 527a997..24fe3e0 100644 --- a/BitwardenWrapper/BitwardenWrapper.psd1 +++ b/BitwardenWrapper/BitwardenWrapper.psd1 @@ -82,7 +82,9 @@ # VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. - AliasesToExport = @() + AliasesToExport = @( + "bw-unlock" + ) # DSC resources to export from this module # DscResourcesToExport = @() @@ -124,4 +126,3 @@ # DefaultCommandPrefix = '' } - diff --git a/BitwardenWrapper/BitwardenWrapper.psm1 b/BitwardenWrapper/BitwardenWrapper.psm1 index fc6d73b..e8eac39 100644 --- a/BitwardenWrapper/BitwardenWrapper.psm1 +++ b/BitwardenWrapper/BitwardenWrapper.psm1 @@ -1,31 +1,40 @@ +# $CONFIG = [PSCustomObject]@{} +$BITWARDEN_WRAPPER_MESSAGES = [PSCustomObject]@{ + ALREADY_UNLOCKED = 'Bitwarden database was already unlocked' + WRONG_MASTER_PASSWORD = 'Invalid master password.' + EMPTY_MASTER_PASSWORD = 'Master password is required.' + NOT_LOGGED_IN = 'No user logged in.' +} function Unlock-BitwardenDatabase { [CmdletBinding()] - param () - - $WRONG_MASTER_PASSWORD = 'Invalid master password.' - $EMPTY_MASTER_PASSWORD = 'Master password is required.' + [Alias("bw-unlock")] + param ( + [Switch] + $RemovePSReadline + ) - if ($env:BW_SESSION) { - Write-Output "Bitwarden database was already unlocked" + $status = bw status | ConvertFrom-Json | Select-Object -ExpandProperty status + if ($status -eq "unlocked") { + Write-Warning $BITWARDEN_WRAPPER_MESSAGES.ALREADY_UNLOCKED return } - $SESSION = bw unlock --raw + $bwUnlockOutput = bw unlock --raw - if (Get-Module PSReadLine) { - Write-Verbose "Removing PSReadline module" - Remove-Module PSReadLine + if (-not $LASTEXITCODE -eq 0) { + return } - if ($SESSION -match $WRONG_MASTER_PASSWORD -or $SESSION -match $EMPTY_MASTER_PASSWORD) { - Throw "Unlock failed" + if ($RemovePSReadline -and (Get-Module PSReadLine)) { + Write-Output "Removing PSReadline module from current session..." + Remove-Module PSReadLine } Write-Output "Bitwarden database unlocked" # remember current session Write-Verbose "Saving session key to environment variable" - $env:BW_SESSION = $SESSION + $env:BW_SESSION = $bwUnlockOutput } Get-ChildItem -Recurse -File -LiteralPath "$PSScriptRoot/Classes" | ForEach-Object { diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 92c559a..3f46971 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -30,6 +30,7 @@ function Update-EverythingHaphazardly { if (-not $PSCmdlet.ShouldProcess("Update apps")) { return } + Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) Write-Output "Updating pipx packages" @@ -216,11 +217,10 @@ function Add-ModuleShim { $ModuleFolder ) - $ModuleName = $ModuleFolder.Name - - $ShimPath = Join-Path "$HOME/Documents/PowerShell/Modules/" $ModuleName + $ModuleFullPath = $ModuleFolder.FullName + $ShimPath = Join-Path "$HOME/Documents/PowerShell/Modules/" $ModuleFolder.Name - New-Item -ItemType Junction -Path $ShimPath -Value $ModuleFolder -Confirm + New-Item -ItemType Junction -Path $ShimPath -Value $ModuleFullPath -Confirm } function Get-OldVsCodeExtensions { diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 0215b87..fa8df95 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -71,6 +71,11 @@ function Enable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value $ProxyServer Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value ($Exclusions -join ";") + $ProxyUrl = "http://$ProxyServer" + + [Environment]::SetEnvironmentVariable("all_proxy", $ProxyUrl, "User") + [Environment]::SetEnvironmentVariable("no_proxy", ($Exclusions -join ","), "User") + if ($FlushDns) { (ipconfig /flushdns && ipconfig /registerdns) | Out-String | @@ -99,6 +104,9 @@ function Disable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 + [Environment]::SetEnvironmentVariable("all_proxy", $null, "User") + [Environment]::SetEnvironmentVariable("no_proxy", $null, "User") + if ($RemoveProxySettings) { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "" Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyOverride -Value "" From 6b1f02792b1060d66d63d4452f34be83cbca314b Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 11 Mar 2021 10:41:10 +0100 Subject: [PATCH 24/50] fix: print environment variable values and some small stuff --- PSScriptAnalyzerSettings.psd1 | 1 + PSUtils/PSUtils.psm1 | 4 +++- ProxyUtils/ProxyUtils.psm1 | 13 ++++++++++--- Scripts/Get-DirtyRepositories.ps1 | 5 ----- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/PSScriptAnalyzerSettings.psd1 b/PSScriptAnalyzerSettings.psd1 index 2d7aa8a..a13ef92 100644 --- a/PSScriptAnalyzerSettings.psd1 +++ b/PSScriptAnalyzerSettings.psd1 @@ -1,3 +1,4 @@ @{ Severity = @('Error', 'Warning') + ExcludeRules = @('PSAvoidUsingPositionalParameters') } diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 3f46971..6ed67b8 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -289,7 +289,7 @@ function Get-OldVsCodeExtensions { function Invoke-GitGcWithReflogExpire { [CmdletBinding()] - [Alias("git-gc-turbo-aggro")] + [Alias('git-gc-expire-unreachable')] param ( # Work tree of the repository where git gc should be invoked [Parameter(Position = 0)] @@ -302,3 +302,5 @@ function Invoke-GitGcWithReflogExpire { git -C $Path gc --aggressive --prune=now } } + +Export-Alias 'git-gc-expire-unreachable' diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index fa8df95..0ad93e2 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -32,6 +32,9 @@ function Get-Proxy { Get-ItemProperty -Path $PROXY_REGISTRY_PATH | Select-Object @arguments + Write-Output "all_proxy: $($env:all_proxy)" + Write-Output "no_proxy: $($env:no_proxy)" + if ($ShowWinHttpProxy) { netsh winhttp show proxy } @@ -126,15 +129,19 @@ function Disable-Proxy { } function Import-WinHttpProxyFromIeProxy { - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] + # [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] + [CmdletBinding()] param () sudo netsh winhttp import proxy source=ie } function Reset-WinHttpProxy { - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] + [CmdletBinding()] param () - sudo netsh winhttp reset proxy + if ($PSCmdlet.ShouldProcess("Reset WinHTTP proxy settings?")) { + sudo netsh winhttp reset proxy + } } diff --git a/Scripts/Get-DirtyRepositories.ps1 b/Scripts/Get-DirtyRepositories.ps1 index 57570ee..a069e7c 100644 --- a/Scripts/Get-DirtyRepositories.ps1 +++ b/Scripts/Get-DirtyRepositories.ps1 @@ -104,8 +104,3 @@ $repos | Ignored = $ignoredFilesAndFolders } } - -# if ($SaveToVariable) { -# Write-Verbose "setting variable $SaveToVariable in parent scope" -# Set-Variable -Scope 1 -Name $SaveToVariable -Value $OutVariable -# } From 7a7cc313e1f9b63f2141771ec7d17cd931459990 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 12 Mar 2021 12:16:06 +0100 Subject: [PATCH 25/50] fix: remove useless export-alias --- PSUtils/PSUtils.psm1 | 2 -- 1 file changed, 2 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 6ed67b8..8849264 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -302,5 +302,3 @@ function Invoke-GitGcWithReflogExpire { git -C $Path gc --aggressive --prune=now } } - -Export-Alias 'git-gc-expire-unreachable' From aa2ad4f076537f4746bc4b452d3a7ac80f9abc9a Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 18 Mar 2021 12:51:17 +0100 Subject: [PATCH 26/50] style: apply new default formatting --- ProxyUtils/ProxyUtils.psm1 | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 0ad93e2..69a6844 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -10,7 +10,7 @@ function Get-Proxy { ) $arguments = if ($Raw) { - @{ Property = "*" } + @{ Property = '*' } } else { @{ @@ -24,7 +24,7 @@ function Get-Proxy { } @{ Name = 'Exclusions' - Expression = { $_.ProxyOverride -split ";" } + Expression = { $_.ProxyOverride -split ';' } } ) } @@ -41,7 +41,7 @@ function Get-Proxy { } function Enable-Proxy { - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] Param ( # server address @@ -72,12 +72,12 @@ function Enable-Proxy { else { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 1 Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value $ProxyServer - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value ($Exclusions -join ";") + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value ($Exclusions -join ';') $ProxyUrl = "http://$ProxyServer" - [Environment]::SetEnvironmentVariable("all_proxy", $ProxyUrl, "User") - [Environment]::SetEnvironmentVariable("no_proxy", ($Exclusions -join ","), "User") + [Environment]::SetEnvironmentVariable('all_proxy', $ProxyUrl, 'User') + [Environment]::SetEnvironmentVariable('no_proxy', ($Exclusions -join ','), 'User') if ($FlushDns) { (ipconfig /flushdns && ipconfig /registerdns) | @@ -95,7 +95,7 @@ function Enable-Proxy { } function Disable-Proxy { - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param ( [switch] $RemoveProxySettings, @@ -105,14 +105,14 @@ function Disable-Proxy { $FlushDns ) - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyEnable -Value 0 + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 0 - [Environment]::SetEnvironmentVariable("all_proxy", $null, "User") - [Environment]::SetEnvironmentVariable("no_proxy", $null, "User") + [Environment]::SetEnvironmentVariable('all_proxy', $null, 'User') + [Environment]::SetEnvironmentVariable('no_proxy', $null, 'User') if ($RemoveProxySettings) { - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyServer -Value "" - Set-ItemProperty -Path $PROXY_REGISTRY_PATH -name ProxyOverride -Value "" + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value '' + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value '' } if ($FlushDns) { @@ -137,11 +137,11 @@ function Import-WinHttpProxyFromIeProxy { } function Reset-WinHttpProxy { - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] [CmdletBinding()] param () - if ($PSCmdlet.ShouldProcess("Reset WinHTTP proxy settings?")) { + if ($PSCmdlet.ShouldProcess('Reset WinHTTP proxy settings?')) { sudo netsh winhttp reset proxy } } From e4b142a9e762b55cd8cfacfce1cee36ca410ade0 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 18 Mar 2021 12:52:51 +0100 Subject: [PATCH 27/50] fix: remove env vars from current session too --- ProxyUtils/ProxyUtils.psm1 | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 69a6844..17d3661 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -77,6 +77,8 @@ function Enable-Proxy { $ProxyUrl = "http://$ProxyServer" [Environment]::SetEnvironmentVariable('all_proxy', $ProxyUrl, 'User') + [Environment]::SetEnvironmentVariable('http_proxy', $ProxyUrl, 'User') + [Environment]::SetEnvironmentVariable('https_proxy', $ProxyUrl, 'User') [Environment]::SetEnvironmentVariable('no_proxy', ($Exclusions -join ','), 'User') if ($FlushDns) { @@ -108,7 +110,13 @@ function Disable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 0 [Environment]::SetEnvironmentVariable('all_proxy', $null, 'User') + [Environment]::SetEnvironmentVariable('http_proxy', $null, 'User') + [Environment]::SetEnvironmentVariable('https_proxy', $null, 'User') [Environment]::SetEnvironmentVariable('no_proxy', $null, 'User') + Remove-Item Env:\all_proxy + Remove-Item Env:\http_proxy + Remove-Item Env:\https_proxy + Remove-Item Env:\no_proxy if ($RemoveProxySettings) { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value '' From 5d0a3f084cdd6da5fe848b883237865e12b6e41f Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 19 Mar 2021 01:02:29 +0100 Subject: [PATCH 28/50] feat: start implementing update-vscodeportable --- PSUtils/PSUtils.psm1 | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 8849264..25375a5 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -302,3 +302,35 @@ function Invoke-GitGcWithReflogExpire { git -C $Path gc --aggressive --prune=now } } + +function Update-VsCodePortable { + [CmdletBinding()] + param ( + # Parameter help description + [Parameter()] + [System.IO.DirectoryInfo] + $Destination = (Get-Item "C:/Tools/vscode/portable") + ) + + # New-Item -Verbose -ItemType Junction -Path "$PSScriptRoot/portable/data" -Value "$PSScriptRoot/data" + + $allProducts = Invoke-WebRequest "https://code.visualstudio.com/sha?build=stable" | + Select-Object -ExpandProperty Content | + ConvertFrom-Json | + Select-Object -ExpandProperty "products" + + $winPortableProduct = $allProducts | Where-Object { $_.platform.os -match "win32-x64-archive" } + + $installedVersionHash = (code -v)[1] + + if ($winPortableProduct.version -match $installedVersionHash) { + Write-Output "VSCode is up to date. Current version is $($winPortableProduct.name)" + return + } + + # TODO finish implementing + # TODO check hash + throw "NOT IMPLEMENTED" + + Invoke-WebRequest $winPortableProduct.url +} From a6dfbba55e64f05b9346e8d1e75a6d520a9fd109 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 23 Mar 2021 18:00:02 +0100 Subject: [PATCH 29/50] feat: implement update-vscode --- PSUtils/PSUtils.psm1 | 102 ++++++++++++++++++++++--------------- ProxyUtils/ProxyUtils.psm1 | 26 +++++++--- 2 files changed, 80 insertions(+), 48 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 25375a5..bb347df 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -17,9 +17,9 @@ function Get-ScoopSize { [PSCustomObject]@{ - "cache size (MB)" = [math]::Round($cache / 1MB, 2) - "persisted data size (MB)" = [math]::Round($persisted / 1MB, 2) - "installed apps size (GB)" = [math]::Round($installed / 1GB, 2) + 'cache size (MB)' = [math]::Round($cache / 1MB, 2) + 'persisted data size (MB)' = [math]::Round($persisted / 1MB, 2) + 'installed apps size (GB)' = [math]::Round($installed / 1GB, 2) } } @@ -27,22 +27,22 @@ function Update-EverythingHaphazardly { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param () - if (-not $PSCmdlet.ShouldProcess("Update apps")) { + if (-not $PSCmdlet.ShouldProcess('Update apps')) { return } - Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) - Write-Output "Updating pipx packages" + Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) + Write-Output 'Updating pipx packages' pipx upgrade-all - Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) - Write-Output "Updating npm global packages" + Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) + Write-Output 'Updating npm global packages' npm update -g - Write-Output ("-" * $Host.UI.RawUI.WindowSize.Width) - Write-Output "Updating scoop packages" + Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) + Write-Output 'Updating scoop packages' Update-ScoopAndCleanAfter } @@ -51,29 +51,29 @@ function Update-ScoopAndCleanAfter { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param () - $telegram = "telegram" + $telegram = 'telegram' scoop update $out = scoop status 6>&1 $out if ($out -match $telegram) { - Write-Output "stopping telegram..." + Write-Output 'stopping telegram...' Get-Process $telegram | Stop-Process } - if ($PSCmdlet.ShouldProcess("Update apps")) { + if ($PSCmdlet.ShouldProcess('Update apps')) { scoop update * } - Write-Output "Running scoop cleanup..." + Write-Output 'Running scoop cleanup...' scoop cleanup * - Write-Output "Clearing cache..." + Write-Output 'Clearing cache...' scoop cache show scoop cache rm * if ($out -match $telegram) { - Write-Output "starting telegram..." + Write-Output 'starting telegram...' & $telegram } } @@ -134,11 +134,11 @@ function Test-HasCrlfEndings { function Test-BomHereRecursive { Get-ChildItem -File -Recurse | - Where-Object FullName -NotMatch ".zip" | - Where-Object FullName -NotMatch ".git" | - Where-Object FullName -NotMatch ".mypy_cache" | - Where-Object FullName -NotMatch "node_modules" | - Where-Object FullName -NotMatch "vendor" | + Where-Object FullName -NotMatch '.zip' | + Where-Object FullName -NotMatch '.git' | + Where-Object FullName -NotMatch '.mypy_cache' | + Where-Object FullName -NotMatch 'node_modules' | + Where-Object FullName -NotMatch 'vendor' | Where-Object { -not (Test-ContainsBOM $_) } | Select-Object FullName } @@ -154,7 +154,7 @@ function Find-Duplicates { param ( [Parameter()] [String[]] - $Paths = "." + $Paths = '.' ) python 'D:/Projects/__libraries-wheels-etc/find_duplicates.py' $Paths } @@ -163,7 +163,7 @@ function New-TemporaryDirectory { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')] param() - if ($PSCmdlet.ShouldProcess("Create new temporary directory")) { + if ($PSCmdlet.ShouldProcess('Create new temporary directory')) { New-Item -ItemType Directory -Path (Join-Path ([System.IO.Path]::GetTempPath()) ([System.Guid]::NewGuid())) } } @@ -184,7 +184,7 @@ function New-HardLink { [parameter(position = 1)] [Object] $Value ) - if ($PSCmdlet.ShouldProcess("Create new HardLink")) { + if ($PSCmdlet.ShouldProcess('Create new HardLink')) { New-Item -ItemType HardLink -Name $Name -Value $Value } } @@ -206,7 +206,7 @@ function Invoke-SshCopyId { $Destination ) - Get-Content "~/.ssh/id_rsa.pub" | ssh $Destination "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys" + Get-Content '~/.ssh/id_rsa.pub' | ssh $Destination 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys' } @@ -230,9 +230,9 @@ function Get-OldVsCodeExtensions { # $Aggro ) - $VSCODE_EXTENSIONS_DIR = "C:/Tools/scoop/apps/vscode-portable/current/data/extensions" + $VSCODE_EXTENSIONS_DIR = 'C:/Tools/scoop/apps/vscode-portable/current/data/extensions' - $SEMVER_REGEX = "(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?" + $SEMVER_REGEX = '(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?' $SPLITTER_REGEX = "^(?.*?)-(?$SEMVER_REGEX)$" # if (-not $Aggro) { @@ -294,7 +294,7 @@ function Invoke-GitGcWithReflogExpire { # Work tree of the repository where git gc should be invoked [Parameter(Position = 0)] [System.IO.DirectoryInfo] - $Path = "." + $Path = '.' ) process { @@ -304,33 +304,55 @@ function Invoke-GitGcWithReflogExpire { } function Update-VsCodePortable { - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( - # Parameter help description - [Parameter()] + [Parameter(Mandatory, Position = 0)] + [System.IO.DirectoryInfo] + $Destination, + [Parameter(Mandatory)] [System.IO.DirectoryInfo] - $Destination = (Get-Item "C:/Tools/vscode/portable") + $DataFolder, + [Switch] + $Force ) - # New-Item -Verbose -ItemType Junction -Path "$PSScriptRoot/portable/data" -Value "$PSScriptRoot/data" + if (-not $PSCmdlet.ShouldProcess('UPDATE VSCODE??? THIS FUNCTION IS BAD')) { + return + } - $allProducts = Invoke-WebRequest "https://code.visualstudio.com/sha?build=stable" | + $allProducts = Invoke-WebRequest 'https://code.visualstudio.com/sha?build=stable' | Select-Object -ExpandProperty Content | ConvertFrom-Json | - Select-Object -ExpandProperty "products" + Select-Object -ExpandProperty 'products' - $winPortableProduct = $allProducts | Where-Object { $_.platform.os -match "win32-x64-archive" } + $winPortableProduct = $allProducts | Where-Object { $_.platform.os -match 'win32-x64-archive' } + $readableInstalledVersion = (code -v)[0] $installedVersionHash = (code -v)[1] - if ($winPortableProduct.version -match $installedVersionHash) { + if (-not $Force -and $winPortableProduct.version -match $installedVersionHash) { Write-Output "VSCode is up to date. Current version is $($winPortableProduct.name)" return } - # TODO finish implementing + if (Test-Path $Destination) { + $backupFolder = "$($Destination.Name)-$readableInstalledVersion" + + if (Test-Path (Join-Path $Destination $backupFolder)) { + throw 'Backup folder already exists' + } + + Write-Output "Backing up current content of $Destination to $backupFolder" + Rename-Item $Destination -NewName $backupFolder + } + + # TODO cache downloaded archive + $archive = New-TemporaryFile + Invoke-WebRequest $winPortableProduct.url -OutFile $archive + # TODO check hash - throw "NOT IMPLEMENTED" - Invoke-WebRequest $winPortableProduct.url + Expand-Archive -Path $archive -DestinationPath $Destination + + New-Item -ItemType Junction -Path (Join-Path $Destination 'data') -Target (Resolve-Path $DataFolder) } diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 17d3661..96ebe87 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -68,6 +68,8 @@ function Enable-Proxy { #Test if the TCP Port on the server is open before applying the settings if (-not (Test-NetConnection -ComputerName $ProxyHost -Port $ProxyPort).TcpTestSucceeded) { Write-Error -Message "The proxy address is not valid: $ProxyServer" + Write-Output 'Press any key to continue...' + $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } else { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 1 @@ -76,10 +78,14 @@ function Enable-Proxy { $ProxyUrl = "http://$ProxyServer" - [Environment]::SetEnvironmentVariable('all_proxy', $ProxyUrl, 'User') - [Environment]::SetEnvironmentVariable('http_proxy', $ProxyUrl, 'User') - [Environment]::SetEnvironmentVariable('https_proxy', $ProxyUrl, 'User') - [Environment]::SetEnvironmentVariable('no_proxy', ($Exclusions -join ','), 'User') + $env:all_proxy = $ProxyUrl + $env:http_proxy = $ProxyUrl + $env:https_proxy = $ProxyUrl + $env:no_proxy = $Exclusions -join ',' + [Environment]::SetEnvironmentVariable('all_proxy', $env:all_proxy, 'User') + [Environment]::SetEnvironmentVariable('http_proxy', $env:http_proxy, 'User') + [Environment]::SetEnvironmentVariable('https_proxy', $env:https_proxy, 'User') + [Environment]::SetEnvironmentVariable('no_proxy', $env:no_proxy , 'User') if ($FlushDns) { (ipconfig /flushdns && ipconfig /registerdns) | @@ -113,10 +119,14 @@ function Disable-Proxy { [Environment]::SetEnvironmentVariable('http_proxy', $null, 'User') [Environment]::SetEnvironmentVariable('https_proxy', $null, 'User') [Environment]::SetEnvironmentVariable('no_proxy', $null, 'User') - Remove-Item Env:\all_proxy - Remove-Item Env:\http_proxy - Remove-Item Env:\https_proxy - Remove-Item Env:\no_proxy + + # Remove from current shell if present + @( + 'Env:\all_proxy' + 'Env:\http_proxy' + 'Env:\https_proxy' + 'Env:\no_proxy' + ) | Where-Object { Test-Path $_ } | Remove-Item if ($RemoveProxySettings) { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value '' From 5c18293b1d26861694c4b27e3253c3a15124d779 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 16 Apr 2021 14:43:41 +0200 Subject: [PATCH 30/50] feat: add edit-hostsfile utility function --- PSUtils/PSUtils.psm1 | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index bb347df..409f26e 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -356,3 +356,10 @@ function Update-VsCodePortable { New-Item -ItemType Junction -Path (Join-Path $Destination 'data') -Target (Resolve-Path $DataFolder) } + +function Edit-HostsFile { + [CmdletBinding()] + param () + + sudo notepad c:\windows\system32\drivers\etc\hosts +} From 1779b66b6580f21a4f97b562466a9d27ebe068c4 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 23 Apr 2021 19:04:43 +0200 Subject: [PATCH 31/50] fix: output of contig should now be wrapped correctly --- Contig-Wrapper/Contig-Wrapper.psm1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Contig-Wrapper/Contig-Wrapper.psm1 b/Contig-Wrapper/Contig-Wrapper.psm1 index c11649a..2f6f518 100644 --- a/Contig-Wrapper/Contig-Wrapper.psm1 +++ b/Contig-Wrapper/Contig-Wrapper.psm1 @@ -3,12 +3,8 @@ if (-not (Get-Command -ErrorAction SilentlyContinue Contig.exe) ) { throw "CONTIG IS NOT AVAILABLE ON PATH" } -###### TODO is it needed? -# Requires -RunAsAdministrator - function Invoke-Contig { - # Contig64.exe -nobanner $args - Contig.exe -nobanner $args + Contig.exe -nobanner $args | Write-Output } Set-Alias contig Invoke-Contig @@ -46,13 +42,17 @@ function Invoke-FileDefragmentation { } process { + if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) { + throw "retry as administrator" + } + $start = Get-Date; Invoke-Contig $file $elapsed = (Get-Date) - $start; - Write-Verbose "defrag of $file completed in $elapsed" + Write-Output "$file defragmented in $elapsed" } end { From 59059e425082b3b4818569907cfefd8bd9ae44ac Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 29 Apr 2021 11:22:07 +0200 Subject: [PATCH 32/50] feat: add includeWsl parameter in proxyutils --- ProxyUtils/ProxyUtils.psm1 | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 96ebe87..dfa415b 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -58,8 +58,10 @@ function Enable-Proxy { $Exclusions, [Switch] $ImportWinHttpProxy, - [switch] - $FlushDns + [Switch] + $FlushDns, + [Switch] + $IncludeWsl ) process { @@ -87,10 +89,12 @@ function Enable-Proxy { [Environment]::SetEnvironmentVariable('https_proxy', $env:https_proxy, 'User') [Environment]::SetEnvironmentVariable('no_proxy', $env:no_proxy , 'User') + if ($IncludeWsl) { + wsl -d ubuntu -- bash -i -c 'enable-proxy' + } + if ($FlushDns) { - (ipconfig /flushdns && ipconfig /registerdns) | - Out-String | - Write-Verbose + (ipconfig /flushdns && ipconfig /registerdns) | Write-Output } if ($ImportWinHttpProxy) { @@ -110,7 +114,9 @@ function Disable-Proxy { [switch] $ResetWinHttpProxy, [switch] - $FlushDns + $FlushDns, + [Switch] + $IncludeWsl ) Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 0 @@ -133,6 +139,10 @@ function Disable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value '' } + if ($IncludeWsl) { + wsl -d ubuntu -- bash -i -c 'disable-proxy' + } + if ($FlushDns) { ipconfig /flushdns && ipconfig /registerdns | Out-String | From 8f32c5ca6fba2323c6e28fe09b6d1ad01cde7be1 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 29 Apr 2021 11:25:17 +0200 Subject: [PATCH 33/50] feat: add create-shortcuts to proxy utils --- ProxyUtils/ProxyUtils.psm1 | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index dfa415b..5c98c00 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -173,3 +173,34 @@ function Reset-WinHttpProxy { sudo netsh winhttp reset proxy } } + +# TODO test me +# TODO reduce duplication +function New-ProxyShortcuts { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param ( + [Parameter(Position = 0)] + [System.IO.DirectoryInfo] + $Destination = '.', + [Switch] + $EnableShortcut, + [Switch] + $DisableShortcut + ) + if (-not($PSCmdlet.ShouldProcess('Create shortcuts?'))) { + return + } + + $WshShell = New-Object -ComObject WScript.Shell + + if ($EnableShortcut) { + $Shortcut = $WshShell.CreateShortcut("$Destination\enable-proxy.lnk") + $Shortcut.TargetPath = 'pwsh.exe -NoLogo -Command "Enable-Proxy -ImportWinHttpProxy -IncludeWsl"' + $Shortcut.Save() + } + if ($DisableShortcut) { + $Shortcut = $WshShell.CreateShortcut("$Destination\disable-proxy.lnk") + $Shortcut.TargetPath = 'pwsh.exe -NoLogo -Command "Disable-Proxy -FlushDns -ResetWinHttpProxy -IncludeWsl"' + $Shortcut.Save() + } +} From 698ef58d278d236817c162e38052330af78170d6 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 7 May 2021 10:19:25 +0200 Subject: [PATCH 34/50] refactor: change order of switches in enable and disable proxy functions --- ProxyUtils/ProxyUtils.psm1 | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 5c98c00..0aaf4dd 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -67,11 +67,10 @@ function Enable-Proxy { process { $ProxyServer = "$($ProxyHost):$($ProxyPort)" - #Test if the TCP Port on the server is open before applying the settings - if (-not (Test-NetConnection -ComputerName $ProxyHost -Port $ProxyPort).TcpTestSucceeded) { + $connection = Test-NetConnection -ComputerName $ProxyHost -Port $ProxyPort + + if (-not $connection.TcpTestSucceeded) { Write-Error -Message "The proxy address is not valid: $ProxyServer" - Write-Output 'Press any key to continue...' - $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } else { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 1 @@ -89,20 +88,24 @@ function Enable-Proxy { [Environment]::SetEnvironmentVariable('https_proxy', $env:https_proxy, 'User') [Environment]::SetEnvironmentVariable('no_proxy', $env:no_proxy , 'User') - if ($IncludeWsl) { - wsl -d ubuntu -- bash -i -c 'enable-proxy' + if ($ImportWinHttpProxy) { + Import-WinHttpProxyFromIeProxy } if ($FlushDns) { (ipconfig /flushdns && ipconfig /registerdns) | Write-Output } - if ($ImportWinHttpProxy) { - Import-WinHttpProxyFromIeProxy + if ($IncludeWsl) { + wsl -d ubuntu -- bash -i -c 'enable-proxy' } } Get-Proxy + + [System.Console]::Beep() + Write-Output 'Press any key to continue...' + $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } } @@ -139,8 +142,8 @@ function Disable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value '' } - if ($IncludeWsl) { - wsl -d ubuntu -- bash -i -c 'disable-proxy' + if ($ResetWinHttpProxy) { + Reset-WinHttpProxy } if ($FlushDns) { @@ -149,11 +152,15 @@ function Disable-Proxy { Write-Verbose } - if ($ResetWinHttpProxy) { - Reset-WinHttpProxy + if ($IncludeWsl) { + wsl -d ubuntu -- bash -i -c 'disable-proxy' } Get-Proxy + + [System.Console]::Beep() + Write-Output 'Press any key to continue...' + $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } function Import-WinHttpProxyFromIeProxy { From 9b50bebafd1a1a861e08d90055c39fdff8abe204 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 14 May 2021 18:16:58 +0200 Subject: [PATCH 35/50] fix: remove registerdns because it requires sudo --- ProxyUtils/ProxyUtils.psm1 | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 0aaf4dd..217e167 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -93,7 +93,7 @@ function Enable-Proxy { } if ($FlushDns) { - (ipconfig /flushdns && ipconfig /registerdns) | Write-Output + ipconfig /flushdns | Write-Output } if ($IncludeWsl) { @@ -147,9 +147,7 @@ function Disable-Proxy { } if ($FlushDns) { - ipconfig /flushdns && ipconfig /registerdns | - Out-String | - Write-Verbose + ipconfig /flushdns | Write-Output } if ($IncludeWsl) { From 8961d5970662860d93e20d5e7b1a4aa7c412c21a Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Tue, 18 May 2021 10:20:44 +0200 Subject: [PATCH 36/50] feat: add specificy wsl proxy cmdlet --- ProxyUtils/ProxyUtils.psm1 | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 217e167..dab77ee 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -97,7 +97,7 @@ function Enable-Proxy { } if ($IncludeWsl) { - wsl -d ubuntu -- bash -i -c 'enable-proxy' + Enable-WslProxy } } @@ -151,7 +151,7 @@ function Disable-Proxy { } if ($IncludeWsl) { - wsl -d ubuntu -- bash -i -c 'disable-proxy' + Disable-WslProxy } Get-Proxy @@ -161,8 +161,21 @@ function Disable-Proxy { $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } +function Enable-WslProxy { + [CmdletBinding()] + param () + + wsl -d ubuntu -- bash -i -c 'enable-proxy' +} + +function Disable-WslProxy { + [CmdletBinding()] + param () + + wsl -d ubuntu -- bash -i -c 'disable-proxy' +} + function Import-WinHttpProxyFromIeProxy { - # [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] [CmdletBinding()] param () From 02e6b218507bb0e0317f02aecc1a191a160d7ed9 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Wed, 2 Jun 2021 14:20:59 +0200 Subject: [PATCH 37/50] fix: use correct vscode extensions directory --- PSUtils/PSUtils.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 409f26e..4a72bfe 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -230,7 +230,7 @@ function Get-OldVsCodeExtensions { # $Aggro ) - $VSCODE_EXTENSIONS_DIR = 'C:/Tools/scoop/apps/vscode-portable/current/data/extensions' + $VSCODE_EXTENSIONS_DIR = 'C:/Tools/vscode/data/extensions' $SEMVER_REGEX = '(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?' $SPLITTER_REGEX = "^(?.*?)-(?$SEMVER_REGEX)$" From 30c81c2b259f7c1d329607aeb1083ff13e129b48 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Sat, 3 Jul 2021 17:34:22 +0200 Subject: [PATCH 38/50] feat: print outdated npm packages before updating --- PSUtils/PSUtils.psm1 | 1 + 1 file changed, 1 insertion(+) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 4a72bfe..6d00d49 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -39,6 +39,7 @@ function Update-EverythingHaphazardly { Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) Write-Output 'Updating npm global packages' + npm outdated -g npm update -g Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) From 31a3e47c1c8f627df9c3936079235f9102b1c0d3 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Sun, 11 Jul 2021 17:16:35 +0200 Subject: [PATCH 39/50] feat: improved update-vscodeportable --- PSUtils/PSUtils.psm1 | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 6d00d49..0686ee5 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -317,7 +317,7 @@ function Update-VsCodePortable { $Force ) - if (-not $PSCmdlet.ShouldProcess('UPDATE VSCODE??? THIS FUNCTION IS BAD')) { + if (-not $PSCmdlet.ShouldProcess('UPDATE VSCODE PORTABLE?')) { return } @@ -336,6 +336,9 @@ function Update-VsCodePortable { return } + Write-Output "Shutting down wsl just to be sure" + wsl --shutdown + if (Test-Path $Destination) { $backupFolder = "$($Destination.Name)-$readableInstalledVersion" @@ -343,8 +346,8 @@ function Update-VsCodePortable { throw 'Backup folder already exists' } - Write-Output "Backing up current content of $Destination to $backupFolder" - Rename-Item $Destination -NewName $backupFolder + Write-Output "Backing up current content of $Destination $backupFolder" + Rename-Item $Destination -NewName $backupFolder -ErrorAction Stop } # TODO cache downloaded archive From 1b387108f588d4e47adea21104df484fc7c03de5 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 15 Jul 2021 10:04:51 +0200 Subject: [PATCH 40/50] feat: improve proxyutils and fix get-oldvscodeextensions --- PSUtils/PSUtils.psm1 | 8 +++----- ProxyUtils/ProxyUtils.psm1 | 30 +++++++++++++++++++----------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 0686ee5..188f709 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -227,12 +227,10 @@ function Add-ModuleShim { function Get-OldVsCodeExtensions { [CmdletBinding()] param ( - # [switch] - # $Aggro + [System.IO.DirectoryInfo] + $VscodeExtensionsDirectory = (Get-Item 'C:/Tools/vscode/data/extensions') ) - $VSCODE_EXTENSIONS_DIR = 'C:/Tools/vscode/data/extensions' - $SEMVER_REGEX = '(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?' $SPLITTER_REGEX = "^(?.*?)-(?$SEMVER_REGEX)$" @@ -244,7 +242,7 @@ function Get-OldVsCodeExtensions { # } $parsedExtensionFolders = @( - Get-ChildItem -Directory -Path $VSCODE_EXTENSIONS_DIR | + Get-ChildItem -Directory -Path $VscodeExtensionsDirectory | Sort-Object -Descending CreationTime | ForEach-Object { $name = $_.Name diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index dab77ee..5bcd087 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -61,15 +61,17 @@ function Enable-Proxy { [Switch] $FlushDns, [Switch] - $IncludeWsl + $IncludeWsl, + [Switch] + $TestProxyAvailability, + [Switch] + $Beep ) process { $ProxyServer = "$($ProxyHost):$($ProxyPort)" - $connection = Test-NetConnection -ComputerName $ProxyHost -Port $ProxyPort - - if (-not $connection.TcpTestSucceeded) { + if ($TestProxyAvailability -and -not (Test-NetConnection -ComputerName $ProxyHost -Port $ProxyPort).TcpTestSucceeded) { Write-Error -Message "The proxy address is not valid: $ProxyServer" } else { @@ -103,9 +105,11 @@ function Enable-Proxy { Get-Proxy - [System.Console]::Beep() - Write-Output 'Press any key to continue...' - $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') + if ($Beep) { + [System.Console]::Beep() + } + # Write-Output 'Press any key to continue...' + # $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } } @@ -119,7 +123,9 @@ function Disable-Proxy { [switch] $FlushDns, [Switch] - $IncludeWsl + $IncludeWsl, + [Switch] + $Beep ) Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 0 @@ -156,9 +162,11 @@ function Disable-Proxy { Get-Proxy - [System.Console]::Beep() - Write-Output 'Press any key to continue...' - $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') + if ($Beep) { + [System.Console]::Beep() + } + # Write-Output 'Press any key to continue...' + # $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } function Enable-WslProxy { From a8a54ca6643241253182988593874d8e2cf4820b Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 12 Aug 2021 10:25:52 +0200 Subject: [PATCH 41/50] feat: use the coolest stream ever to write information --- Scripts/Get-DirtyRepositories.ps1 | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Scripts/Get-DirtyRepositories.ps1 b/Scripts/Get-DirtyRepositories.ps1 index a069e7c..59b3755 100644 --- a/Scripts/Get-DirtyRepositories.ps1 +++ b/Scripts/Get-DirtyRepositories.ps1 @@ -6,7 +6,6 @@ param ( [string] $SaveToVariable ) - # TODO export type data? # Update-TypeData ... @@ -63,24 +62,24 @@ function Test-HasIgnoredFilesAndFolder { ) return ( git -C $path status -s --ignored ) | - Select-String -Pattern "^!!" | + Select-String -Pattern '^!!' | Measure-Object | Select-Object -ExpandProperty Count } -Write-Output "Searching for repositories in $RootFolder ..." +Write-Information -InformationAction Continue "Searching for repositories in $RootFolder ..." $repos = Get-ChildItem -Verbose -Directory -Force -Recurse $RootFolder | - Where-Object FullName -NotMatch "node_modules" | - Where-Object FullName -NotMatch "vendor" | - Where-Object FullName -NotMatch "Library" | - Where-Object FullName -Match ".git$" | + Where-Object FullName -NotMatch 'node_modules' | + Where-Object FullName -NotMatch 'vendor' | + Where-Object FullName -NotMatch 'Library' | + Where-Object FullName -Match '.git$' | ForEach-Object { Write-Verbose "scanning $($_.FullName)" $_ } -Write-Output "found $($repos.Length) repos; checking status..." +Write-Information -InformationAction Continue "found $($repos.Length) repos; checking status..." $repos | ForEach-Object { @@ -93,7 +92,7 @@ $repos | $ignoredFilesAndFolders = Test-HasIgnoredFilesAndFolder $workTree [pscustomobject]@{ - PSTypename = "GitRepo" + PSTypename = 'GitRepo' Repo = $workTree AllGood = -not ($uncommittedChanges -or $hasNoRemote -or $unpushedCommits -or $forgottenStashes ) UncommittedChanges = $uncommittedChanges From 8301366dccf8ffae1d89e6f9c86628ccabfb681e Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Thu, 12 Aug 2021 10:58:21 +0200 Subject: [PATCH 42/50] feat: improve messaging for update-* functions --- PSUtils/PSUtils.psm1 | 69 ++++++++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 19 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 188f709..1a8169f 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -31,34 +31,42 @@ function Update-EverythingHaphazardly { return } - Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) - Write-Output 'Updating pipx packages' - - pipx upgrade-all + if (Get-Command -ErrorAction SilentlyContinue pipx) { + Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) + Write-Output '- Updating pipx packages' - Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) - Write-Output 'Updating npm global packages' + pipx upgrade-all + } - npm outdated -g - npm update -g + if (Get-Command -ErrorAction SilentlyContinue npm) { + Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) + Write-Output '- Outdated npm global packages' + npm outdated -g - Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) - Write-Output 'Updating scoop packages' + Write-Output '- Updating npm global packages' + npm update -g + } Update-ScoopAndCleanAfter + + Update-GitRepositoriesSafely } function Update-ScoopAndCleanAfter { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param () + Write-Output ('-' * $Host.UI.RawUI.WindowSize.Width) + Write-Output '- Updating scoop packages' + $telegram = 'telegram' - scoop update - $out = scoop status 6>&1 - $out - if ($out -match $telegram) { - Write-Output 'stopping telegram...' + scoop update 6>&1 | Write-Verbose + + $status_output = scoop status 6>&1 + $status_output + if ($status_output -match $telegram) { + Write-Output '- Stopping telegram...' Get-Process $telegram | Stop-Process } @@ -66,19 +74,42 @@ function Update-ScoopAndCleanAfter { scoop update * } - Write-Output 'Running scoop cleanup...' + Write-Output '- Running scoop cleanup...' scoop cleanup * - Write-Output 'Clearing cache...' + Write-Output '- Clearing cache...' scoop cache show scoop cache rm * if ($out -match $telegram) { - Write-Output 'starting telegram...' + Write-Output '- Starting telegram...' & $telegram } } +function Update-GitRepositoriesSafely { + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')] + [CmdletBinding()] + param ( + [Parameter(Mandatory, Position = 0)] + [System.IO.DirectoryInfo[]] + $Repositories + ) + + Write-Error 'NOT IMPLEMENTED' + return + + if (-not $PSCmdlet.ShouldProcess('Update apps')) { + Write-Output 'Really?? Running git fetch is less risky than ' + } + foreach ($repo in $Repositories) { + + git -C $repo fetch --all + # TODO can i use status -s here?? + git -C $repo status + } + +} ######################################################################################################################## ####################################### JSCPD ######################################################################################################################## @@ -334,7 +365,7 @@ function Update-VsCodePortable { return } - Write-Output "Shutting down wsl just to be sure" + Write-Output 'Shutting down wsl just to be sure' wsl --shutdown if (Test-Path $Destination) { From 86e89685349f7b78fa24cb178cccc36099bc68a0 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Sun, 18 Jul 2021 18:03:29 +0200 Subject: [PATCH 43/50] fix: ensure docker is not running when updating vscode --- PSUtils/PSUtils.psm1 | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 1a8169f..2542bc8 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -365,6 +365,10 @@ function Update-VsCodePortable { return } + if (Get-Process -Name com.docker.backend -ErrorAction SilentlyContinue) { + throw "STOP DOCKER BEFORE UPDATING VSCODE" + } + Write-Output 'Shutting down wsl just to be sure' wsl --shutdown From c72a581ef5857721559382d179fde50644833064 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Mon, 13 Sep 2021 10:51:57 +0200 Subject: [PATCH 44/50] feat: implement update-gitrepositoriessafely --- PSUtils/PSUtils.psm1 | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 2542bc8..f24b262 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -93,20 +93,29 @@ function Update-GitRepositoriesSafely { param ( [Parameter(Mandatory, Position = 0)] [System.IO.DirectoryInfo[]] - $Repositories + $RootRepositoriesFolder ) - Write-Error 'NOT IMPLEMENTED' - return - if (-not $PSCmdlet.ShouldProcess('Update apps')) { - Write-Output 'Really?? Running git fetch is less risky than ' - } - foreach ($repo in $Repositories) { + Write-Output 'Really?? Running git fetch is reaaaaaaally low risk' + + }Write-Information -InformationAction Continue "Searching for repositories in $RootRepositoriesFolder ..." + + $repos = Get-ChildItem -Verbose -Directory -Force -Recurse $RootRepositoriesFolder | + Where-Object FullName -NotMatch 'node_modules' | + Where-Object FullName -NotMatch 'vendor' | + Where-Object FullName -NotMatch 'Library' | + Where-Object FullName -Match '.git$' | + ForEach-Object { + Write-Verbose "scanning $($_.FullName)" + $_ + } + + foreach ($gitFolder in $repos) { + $repo = Split-Path -Path $gitFolder -Parent git -C $repo fetch --all - # TODO can i use status -s here?? - git -C $repo status + git -C $repo status --short --branch | Select-String "##" } } From 19a2ccd6250316cb13c4d67150e2a6e21456a0c8 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Mon, 13 Sep 2021 10:52:16 +0200 Subject: [PATCH 45/50] feat: unset automatic proxy when enabling my proxy --- ProxyUtils/ProxyUtils.psm1 | 1 + 1 file changed, 1 insertion(+) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 5bcd087..31c4297 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -78,6 +78,7 @@ function Enable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 1 Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyServer -Value $ProxyServer Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyOverride -Value ($Exclusions -join ';') + Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name AutoConfigURL -Value '' $ProxyUrl = "http://$ProxyServer" From 80fd9020363bbf09b1175f024401bd45740a9e0b Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Mon, 20 Dec 2021 12:11:32 +0100 Subject: [PATCH 46/50] refactor: improve output of get-proxy --- ProxyUtils/ProxyUtils.psm1 | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 31c4297..41b70aa 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -32,8 +32,12 @@ function Get-Proxy { Get-ItemProperty -Path $PROXY_REGISTRY_PATH | Select-Object @arguments - Write-Output "all_proxy: $($env:all_proxy)" - Write-Output "no_proxy: $($env:no_proxy)" + [PSCustomObject]@{ + all_proxy = $env:all_proxy + http_proxy = $env:http_proxy + https_proxy = $env:https_proxy + no_proxy = $env:no_proxy + } | Format-List if ($ShowWinHttpProxy) { netsh winhttp show proxy From 8058076dcb3c393dd2c5f771c1ebebc64633ae36 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Wed, 29 Dec 2021 14:26:45 +0100 Subject: [PATCH 47/50] feat: add wait parameter and accept igt proxy automatically --- ProxyUtils/ProxyUtils.psm1 | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 41b70aa..770b606 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -69,7 +69,9 @@ function Enable-Proxy { [Switch] $TestProxyAvailability, [Switch] - $Beep + $Beep, + [Switch] + $Wait ) process { @@ -113,8 +115,11 @@ function Enable-Proxy { if ($Beep) { [System.Console]::Beep() } - # Write-Output 'Press any key to continue...' - # $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') + + if ($Wait) { + Write-Output 'Press any key to continue...' + $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') + } } } @@ -130,7 +135,9 @@ function Disable-Proxy { [Switch] $IncludeWsl, [Switch] - $Beep + $Beep, + [Switch] + $Wait ) Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 0 @@ -170,15 +177,18 @@ function Disable-Proxy { if ($Beep) { [System.Console]::Beep() } - # Write-Output 'Press any key to continue...' - # $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') + + if ($Wait) { + Write-Output 'Press any key to continue...' + $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') + } } function Enable-WslProxy { [CmdletBinding()] param () - wsl -d ubuntu -- bash -i -c 'enable-proxy' + wsl -d ubuntu -- bash -i -c 'enable-proxy && accept-igt-proxy' } function Disable-WslProxy { From 749dc71c355f4386766bfd2e5824878ad25ee817 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Fri, 18 Feb 2022 20:42:24 +0100 Subject: [PATCH 48/50] refactor: wrap contig output --- Contig-Wrapper/Contig-Wrapper.psm1 | 6 +++++- PSUtils/PSUtils.psm1 | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Contig-Wrapper/Contig-Wrapper.psm1 b/Contig-Wrapper/Contig-Wrapper.psm1 index 2f6f518..e4c5c91 100644 --- a/Contig-Wrapper/Contig-Wrapper.psm1 +++ b/Contig-Wrapper/Contig-Wrapper.psm1 @@ -4,7 +4,11 @@ if (-not (Get-Command -ErrorAction SilentlyContinue Contig.exe) ) { } function Invoke-Contig { - Contig.exe -nobanner $args | Write-Output + Write-Output ("+" * 80) + Contig.exe -nobanner $args + Write-Output ("-" * 80) + # Contig.exe -nobanner $args | Write-Output + # Contig64.exe -nobanner $args | Write-Output } Set-Alias contig Invoke-Contig diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index f24b262..05e5c9b 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -91,9 +91,9 @@ function Update-GitRepositoriesSafely { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')] [CmdletBinding()] param ( - [Parameter(Mandatory, Position = 0)] + [Parameter(Position = 0)] [System.IO.DirectoryInfo[]] - $RootRepositoriesFolder + $RootRepositoriesFolder = (Get-Item $env:PROJECTS_FOLDER) ) if (-not $PSCmdlet.ShouldProcess('Update apps')) { From 807683c7ffc9dbe817a6897d5dcf6d6369ed2833 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Mon, 21 Nov 2022 10:36:52 +0100 Subject: [PATCH 49/50] do not set "all_proxy" env var --- ProxyUtils/ProxyUtils.psm1 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ProxyUtils/ProxyUtils.psm1 b/ProxyUtils/ProxyUtils.psm1 index 770b606..0a559f8 100644 --- a/ProxyUtils/ProxyUtils.psm1 +++ b/ProxyUtils/ProxyUtils.psm1 @@ -33,7 +33,7 @@ function Get-Proxy { Get-ItemProperty -Path $PROXY_REGISTRY_PATH | Select-Object @arguments [PSCustomObject]@{ - all_proxy = $env:all_proxy + # all_proxy = $env:all_proxy http_proxy = $env:http_proxy https_proxy = $env:https_proxy no_proxy = $env:no_proxy @@ -88,11 +88,11 @@ function Enable-Proxy { $ProxyUrl = "http://$ProxyServer" - $env:all_proxy = $ProxyUrl + # $env:all_proxy = $ProxyUrl $env:http_proxy = $ProxyUrl $env:https_proxy = $ProxyUrl $env:no_proxy = $Exclusions -join ',' - [Environment]::SetEnvironmentVariable('all_proxy', $env:all_proxy, 'User') + # [Environment]::SetEnvironmentVariable('all_proxy', $env:all_proxy, 'User') [Environment]::SetEnvironmentVariable('http_proxy', $env:http_proxy, 'User') [Environment]::SetEnvironmentVariable('https_proxy', $env:https_proxy, 'User') [Environment]::SetEnvironmentVariable('no_proxy', $env:no_proxy , 'User') @@ -142,14 +142,14 @@ function Disable-Proxy { Set-ItemProperty -Path $PROXY_REGISTRY_PATH -Name ProxyEnable -Value 0 - [Environment]::SetEnvironmentVariable('all_proxy', $null, 'User') + # [Environment]::SetEnvironmentVariable('all_proxy', $null, 'User') [Environment]::SetEnvironmentVariable('http_proxy', $null, 'User') [Environment]::SetEnvironmentVariable('https_proxy', $null, 'User') [Environment]::SetEnvironmentVariable('no_proxy', $null, 'User') # Remove from current shell if present @( - 'Env:\all_proxy' + # 'Env:\all_proxy' 'Env:\http_proxy' 'Env:\https_proxy' 'Env:\no_proxy' From 3c5add4458ed4522efd621f9b8648655ec8f8cc5 Mon Sep 17 00:00:00 2001 From: Luca Ercole <30255227+erclu@users.noreply.github.com> Date: Mon, 9 Jan 2023 09:37:27 +0100 Subject: [PATCH 50/50] fix format in update-gitrepositoriessafely --- PSUtils/PSUtils.psm1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/PSUtils/PSUtils.psm1 b/PSUtils/PSUtils.psm1 index 05e5c9b..e42c860 100644 --- a/PSUtils/PSUtils.psm1 +++ b/PSUtils/PSUtils.psm1 @@ -49,7 +49,7 @@ function Update-EverythingHaphazardly { Update-ScoopAndCleanAfter - Update-GitRepositoriesSafely + Update-GitRepositoriesSafely | Format-Table } function Update-ScoopAndCleanAfter { @@ -99,7 +99,8 @@ function Update-GitRepositoriesSafely { if (-not $PSCmdlet.ShouldProcess('Update apps')) { Write-Output 'Really?? Running git fetch is reaaaaaaally low risk' - }Write-Information -InformationAction Continue "Searching for repositories in $RootRepositoriesFolder ..." + } + Write-Information -InformationAction Continue "Searching for repositories in $RootRepositoriesFolder ..." $repos = Get-ChildItem -Verbose -Directory -Force -Recurse $RootRepositoriesFolder | Where-Object FullName -NotMatch 'node_modules' | @@ -115,9 +116,8 @@ function Update-GitRepositoriesSafely { $repo = Split-Path -Path $gitFolder -Parent git -C $repo fetch --all - git -C $repo status --short --branch | Select-String "##" + git -C $repo status --short --branch | Select-String '##' } - } ######################################################################################################################## ####################################### JSCPD