From 0718bf28c711f8f7f6e87f06060a3970e4c7d459 Mon Sep 17 00:00:00 2001 From: lksz Date: Thu, 1 Oct 2020 00:28:57 -0400 Subject: [PATCH 01/30] Minor midifications --- Reload-MyScripts.ps1 | 2 +- Setup-Profile.ps1 | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Reload-MyScripts.ps1 b/Reload-MyScripts.ps1 index fd0aca3..a9eac00 100644 --- a/Reload-MyScripts.ps1 +++ b/Reload-MyScripts.ps1 @@ -1,7 +1,7 @@ [CmdletBinding(SupportsShouldProcess)]param() $local:myAliases = [ordered]@{} -$myAliases.sudo = 'Invoke-Sudo' +#$myAliases.sudo = 'Invoke-Sudo' $myAliases.vi = 'Edit-TextFile' $myAliases.vim = 'Edit-TextFile' $myAliases.nvim = 'Edit-TextFile' diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index 0173767..b5a3cfb 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -414,6 +414,8 @@ if ( -not $MyPSScriptRoot -or (Test-Path function:Test-IsAdmin, function:Convert . ProfileCode_common } +$SetupFromWeb = [bool]$(@( $SetupFromWeb, $sfw, $LoadCode ) | Where-Object { $_ }) + if ( -not $SetupFromWeb ) { _setup @PSBoundParameters Get-Item function:_setup | Remove-Item From a782d09b2c728e393856e650dc7034f4206ca157 Mon Sep 17 00:00:00 2001 From: Gal Szkolnik Date: Thu, 1 Oct 2020 18:16:54 -0400 Subject: [PATCH 02/30] fixed scoping issue --- Setup-Profile.ps1 | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index b5a3cfb..fcfb59f 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -380,10 +380,10 @@ param([string]$EnvPath) # Establish Module Path $global:MyPSModulePath = Split-PathEnv $env:PSModulePath | -Where-Object { $_ -match "^$($(Resolve-Path ~) -replace '\\',"\\")" } | -Where-Object { Test-Path $_ } | -Get-Item | Sort-Object -Property LastWriteTime -Descending | -Select-Object -ExpandProperty FullName -First 1 + Where-Object { $_ -match "^$($(Resolve-Path ~) -replace '\\',"\\")" } | + Where-Object { Test-Path $_ } | + Get-Item | Sort-Object -Property LastWriteTime -Descending | + Select-Object -ExpandProperty FullName -First 1 if ( -not $MyPSModulePath ) { $MyPSModulePath = $(Join-Path $(Join-Path $(Resolve-Path ~) 'powershell') 'Modules') @@ -409,10 +409,12 @@ $p = @($p[0], $MyPSScriptRoot) + $($p | Select-Object -Skip 1) $env:PATH = $p -join $PathEnvDelimiter } +$local:importExpression = "" if ( -not $MyPSScriptRoot -or (Test-Path function:Test-IsAdmin, function:ConvertTo-Base64, function:Invoke-ExpressionEx, function:Get-PowerShellPath, function:Export-FunctionSource | Where-Object { -not $_ } | Measure-Object | Select-Object -ExpandProperty Count) ) { Write-Verbose "Calling ProfileCode inline..." - . ProfileCode_common + $importExpression = "ProfileCode_common" } +. Invoke-Expression $importExpression $SetupFromWeb = [bool]$(@( $SetupFromWeb, $sfw, $LoadCode ) | Where-Object { $_ }) From 2d2a7bba5d2f9d2c47c9508f4756584bd50d32a4 Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 12:45:04 -0400 Subject: [PATCH 03/30] System specific update Reload-Scripts now loads Platform/OS specific scripts depending on current state. This required the SystemName class sranger is an example of running ranger as sudo, but only in Linux. Moved Get-MyAliases into Reload-MyScripts, and changed Reload-MyScripts to load Aliases dynamically via the Aliases directory. --- Edit-MyScript.ps1 | 33 ++++++++++++++-- Get-MyAliases.ps1 | 26 ------------- Reload-MyScripts.ps1 | 71 +++++++++++++++++++++++++++------- profile.d/MyConfig.class.ps1 | 18 +++++++++ profile.d/Style.ps1 | 2 + profile.d/SystemName.class.ps1 | 37 ++++++++++++++++++ profile.d/UnixCompleters.ps1 | 4 ++ sys.Linux/sranger.ps1 | 2 + 8 files changed, 150 insertions(+), 43 deletions(-) delete mode 100644 Get-MyAliases.ps1 create mode 100644 profile.d/MyConfig.class.ps1 create mode 100644 profile.d/Style.ps1 create mode 100644 profile.d/SystemName.class.ps1 create mode 100644 profile.d/UnixCompleters.ps1 create mode 100644 sys.Linux/sranger.ps1 diff --git a/Edit-MyScript.ps1 b/Edit-MyScript.ps1 index 1cc37a9..ddfbdbe 100644 --- a/Edit-MyScript.ps1 +++ b/Edit-MyScript.ps1 @@ -9,6 +9,16 @@ [FunctionName]::_GetValidValues($wordToComplete,$true) })] [string[]]$ImportFunction, + [ArgumentCompleter({ param ( + $commandName, + $parameterName, + $wordToComplete, + $commandAst, + $fakeBoundParameters + ) + [SystemName]::_GetValidValues($wordToComplete,$false,$true) + })] + [string]$System, [switch]$ForceImport, [Parameter(Position = 0, ValueFromRemainingArguments = $true)] [ArgumentCompleter({ param ( @@ -18,16 +28,24 @@ $commandAst, $fakeBoundParameters ) - [MyScript]::_GetValidValues($wordToComplete,$true) + $local:possibleValues = [MyScript]::_GetValidValues($wordToComplete,$true) + if( $fakeBoundParameters.ContainsKey("System") ) { + $possibleValues = $possibleValues | Where-Object { $_ -match "^sys\.$($fakeBoundParameters.System)" } | ForEach-Object { $_ -replace "^sys\.$($fakeBoundParameters.System).",'' } + } + $possibleValues })] [string[]]$ScriptName ) +$local:EditRootPath=$MyPSScriptRoot +if( $System ) { + $EditRootPath = Join-Path $EditRootPath "sys.$System" +} $local:ScriptPaths = @() foreach( $local:p in $ImportFunction ) { $local:f = Get-Command $p -Type Function if( $f ) { - $local:sp = Join-Path $MyPSScriptRoot "$p`.ps1" + $local:sp = Join-Path $EditRootPath "$p`.ps1" if( $ForceImport -or -not (Test-Path $sp) ) { Export-FunctionSource $p -NoHeader > $sp } elseif ( -not $ForceImport ) { @@ -37,12 +55,19 @@ foreach( $local:p in $ImportFunction ) { } } foreach( $local:p in $ScriptName ) { - $local:sp = Join-Path $MyPSScriptRoot "$p`.ps1" + $local:sp = Join-Path $EditRootPath "$p`.ps1" $ScriptPaths += $sp } if( -not $ScriptPaths ) { - $ScriptPaths += $MyPSScriptRoot + $ScriptPaths += $EditRootPath +} + +foreach( $local:p in $ScriptPaths ) { + $local:parentPath = Split-Path -Parent $p; + if( -not (Test-Path $p) -and -not (Test-Path $parentPath) ) { + New-Item -Directory $parentPath + } } Edit-TextFile $ScriptPaths diff --git a/Get-MyAliases.ps1 b/Get-MyAliases.ps1 deleted file mode 100644 index ddcbcef..0000000 --- a/Get-MyAliases.ps1 +++ /dev/null @@ -1,26 +0,0 @@ -[CmdletBinding(SupportsShouldProcess)]param() - -$local:allAliases = @() - -$MyAliasScope = 0 -$local:_scope = 0 -$local:_done = $false -do { - try { - $local:newAliases += Get-Alias -Scope $_scope | - Where-Object { - ($_.Definition -match "^$MyPSScriptRoot") -or ($_.Description -match '#MyAlias') - } - if( $newAliases ) { - $allAliases += $newAliases - $MyAliasScope = $_scope; - Write-Verbose "`$MyAliasScope is now set to $MyAliasScope" - } - } catch { - Write-Verbose "catch: $($_.Exception.Message)" - $_done = $_.Exception.Message -match 'The scope .* exceeds' - } - $_scope += 1 -} until ( $_done ) - -$allAliases diff --git a/Reload-MyScripts.ps1 b/Reload-MyScripts.ps1 index fd0aca3..0f2e337 100644 --- a/Reload-MyScripts.ps1 +++ b/Reload-MyScripts.ps1 @@ -1,21 +1,55 @@ [CmdletBinding(SupportsShouldProcess)]param() +function Get-MyAliases { +[CmdletBinding(SupportsShouldProcess)]param([switch]$ScriptsOnly) + + $local:allAliases = @() + + $MyAliasScope = 0 + $local:_scope = 0 + $local:_done = $false + do { + try { + $local:newAliases += Get-Alias -Scope $_scope | + Where-Object { + ($_.Definition -match "^$MyPSScriptRoot") -or (-not $ScriptsOnly -and ($_.Description -match '#MyAlias')) + } + if( $newAliases ) { + $allAliases += $newAliases + $MyAliasScope = $_scope; + Write-Verbose "`$MyAliasScope is now set to $MyAliasScope" + } + } catch { + Write-Verbose "catch: $($_.Exception.Message)" + $_done = $_.Exception.Message -match 'The scope .* exceeds' + } + $_scope += 1 + } until ( $_done ) + + $allAliases +} + $local:myAliases = [ordered]@{} -$myAliases.sudo = 'Invoke-Sudo' -$myAliases.vi = 'Edit-TextFile' -$myAliases.vim = 'Edit-TextFile' -$myAliases.nvim = 'Edit-TextFile' -$myAliases.nvim = 'Edit-TextFile' -$myAliases.l = 'ls.ps1' -$myAliases.ll = 'ls.ps1' +if( Test-Path $(Join-Path $MyPSScriptRoot Aliases) ) { + Get-ChildItem Join-Path (Join-Path $MyPSScriptRoot Aliases) | ForEach-Object { + $myAliases[$_.BaseName] = Get-Content $_ + } +} +# $myAliases.sudo = 'Invoke-Sudo' +# $myAliases.vi = 'Edit-TextFile' +# $myAliases.vim = 'Edit-TextFile' +# $myAliases.nvim = 'Edit-TextFile' +# $myAliases.nvim = 'Edit-TextFile' +# $myAliases.l = 'ls.ps1' +# $myAliases.ll = 'ls.ps1' ####################################################################### $local:IsVerbose = [bool]($PSBoundParameters['Verbose']) -$local:MyAliasScope = 1 +$script:MyAliasScope = 0 -$local:oldAliases = . Get-MyAliases +$local:oldAliases = Get-MyAliases $oldAliases = Get-Alias -Scope $MyAliasScope | Where-Object Name -in $($oldAliases.Name + $myAliases.Keys) @@ -29,8 +63,21 @@ if( Get-Command Remove-Alias -ErrorAction SilentlyContinue ) { $oldAliases | ForEach-Object { Remove-Item "Alias:$($_.Name)" } } -Get-ChildItem (Join-Path $MyPSScriptRoot '*.ps1') | - ForEach-Object { +if( $(. Get-ScopeDepth) -gt 0 ) { Write-Host -ForegroundColor Red "Try sourcing Reload-MyScripts instead of just running it" } +Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object { ". '$($_.FullName)';" } | Invoke-Expression + +$local:CommandsToAlias = ( + @( $MyPSScriptRoot ) + $( + [SystemName]::_GetValidValues("",$true,$true) | ForEach-Object { + Join-Path $MyPSScriptRoot $_ + } + )) | ForEach-Object { + if( Test-Path $_ ) { + Get-ChildItem (Join-Path $_ '*.ps1') | Where-Object Name -notmatch '\.inc\.ps1$' + } + } + +$CommandsToAlias | ForEach-Object { Set-Alias $($_.BaseName) $_.FullName -Scope $MyAliasScope } @@ -38,5 +85,3 @@ foreach( $local:alias in $myAliases.Keys ) { Set-Alias -Name $alias -Value $myAliases[$alias] -Description '#MyAlias' -Scope $MyAliasScope } -if( $(. Get-ScopeDepth) -gt 0 ) { Write-Host -ForegroundColor Red "Try sourcing Reload-MyScripts instead of just running it" } -Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object { ". '$($_.FullName)';" } | Invoke-Expression diff --git a/profile.d/MyConfig.class.ps1 b/profile.d/MyConfig.class.ps1 new file mode 100644 index 0000000..19f3d52 --- /dev/null +++ b/profile.d/MyConfig.class.ps1 @@ -0,0 +1,18 @@ +class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { + static [hashtable]$configDirectory = [ordered]@{ + 'vi' = '~/.virc' + 'vim' = '~/.vimrc','~/.vim/vimrc' + 'neovim' = '~/.config/nvim/init.vim','~/.config/nvim/vim-plug/plugins.vim','#vim','#vi' + } + static [string[]] GetConfigPaths([string[]]$ConfigNames) { + return $null + } + static [string[]] _GetValidValues([string]$wordToComplete,[bool]$Strict) { + $local:possibleValues = [MyConfig]::configDirectory.Keys + return $(Get-PossibleArguments -WordToComplete $wordToComplete -FullValueSet $possibleValues -Strict:$Strict ); + } + + [String[]] GetValidValues() { + return [MyConfig]::_GetValidValues('',$true) + } +} diff --git a/profile.d/Style.ps1 b/profile.d/Style.ps1 new file mode 100644 index 0000000..7b7f354 --- /dev/null +++ b/profile.d/Style.ps1 @@ -0,0 +1,2 @@ +Get-Command Set-PSReadLineKeyHandler | ForEach-Object { Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete } +Get-Command Set-Theme -ErrorAction SilentlyContinue | ForEach-Object { Set-Theme Paradox } diff --git a/profile.d/SystemName.class.ps1 b/profile.d/SystemName.class.ps1 new file mode 100644 index 0000000..022340f --- /dev/null +++ b/profile.d/SystemName.class.ps1 @@ -0,0 +1,37 @@ +class SystemName { #: System.Management.Automation.IValidateSetValuesGenerator { + static [string[]] _GetValidValues([string]$wordToComplete,[bool]$CurrentOnly,[bool]$Strict) { + $MyPSScriptRoot = "$global:MyPSScriptRoot"; + $local:possibleValues = [ordered]@{} + $possibleValues.out = @() + $possibleValues.Current = @( + $($global:PSVersionTable.OS -split ' '|Select-Object -First 1).Replace('Microsoft','Windows'), + $global:PSVersionTable.Platform, + $global:PSVersionTable.PSEdition + ); + $possibleValues.out = $possibleValues.Current + + if( -not $CurrentOnly ) { + $possibleValues.Platform = @( 'Windows','Linux','Unix' ); + $possibleValues.Edition = @( 'Desktop', 'Core' ); + $possibleValues.Exist = Get-ChildItem (Join-Path $MyPSScriptRoot "sys.*") | ForEach-Object { $_.Name -replace 'sys\.','' }; + $possibleValues.out += $possibleValues.Platform + $possibleValues.Edition + $possibleValues.Exist + } + $possibleValues.out = $possibleValues.out | + Select-Object -Unique | + Sort-Object { + $local:sortName = "zz_$_"; + if( $_ -in $possibleValues.Exist -and $_ -in $possibleValues.Current ) { $sortName[0] = "a" } + elseif( $_ -in $possibleValues.Exist ) { $sortName[0] = "b" } + elseif( $_ -in $possibleValues.Current ) { $sortName[0] = "c" } + if( $_ -in $possibleValues.Platform ) { $sortName[1] = "a" } + if( $_ -in $possibleValues.Edition ) { $sortName[1] = "b" } + $sortName; + } + return $(Get-PossibleArguments -WordToComplete $wordToComplete -FullValueSet $possibleValues.out -Strict:$Strict ); + } + + [String[]] GetValidValues() { + return [SystemName]::_GetValidValues('',$false,$true) + } +} + diff --git a/profile.d/UnixCompleters.ps1 b/profile.d/UnixCompleters.ps1 new file mode 100644 index 0000000..aeb3a6d --- /dev/null +++ b/profile.d/UnixCompleters.ps1 @@ -0,0 +1,4 @@ +Get-Command Import-UnixCompleters -ErrorAction SilentlyContinue | ForEach-Object { + Import-UnixCompleters + Set-UnixCompleter -ShellType Zsh +} diff --git a/sys.Linux/sranger.ps1 b/sys.Linux/sranger.ps1 new file mode 100644 index 0000000..fa3e734 --- /dev/null +++ b/sys.Linux/sranger.ps1 @@ -0,0 +1,2 @@ + +Invoke-ExpressionEx -sudo "`$env:TERM='tmux-256color'; `$env:EDITOR='$env:EDITOR'; ranger" From eec4eb2cbedf3dc122d59e5496074fab69637376 Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 13:04:17 -0400 Subject: [PATCH 04/30] Updating README.md with current instructinos --- README.md | 52 ++++++++++++++++++---------------------------------- 1 file changed, 18 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index a6b3396..2569fb0 100644 --- a/README.md +++ b/README.md @@ -6,41 +6,25 @@ The development of these is documented in my blog: https://blog.lksz.me They are provided 'as is' for your review and for your reuse. -There is a [blog post](https://blog.lksz.me/keeping-track-of-everything/#-mypsscriptroot) about how to clone this repo and use it as your own. - -The scripts all [assume](https://blog.lksz.me/functions-or-scripts/#myprofilecode) the code below is part of one of your $PROFILE files. -The code establishes the following variables: -* `$PathEnvDelimiter` - Linux/Unix it's `:`, while in Windows it's `;` -* `$MyPSModulePath` - Location to place personal Modules -* `$MyPSScriptRoot` - Location of personal Scripts. - -The code also makes sure `$MyPSScriptRoot` is in the `$env:PATH` environment vairable, and finally it calls [`Reload-MyAliases`](https://blog.lksz.me/a-case-of-sensitivity/#myaliases) if it exists. - +This envrionment can be installed using one the following options: +### The Short, yet safer way +```PowerShell +iwr https://lksz.me/pwsz | iex ``` -$global:PathEnvDelimiter = $(if( $PSVersionTable.Platform -match 'unix' ) {':'} else {';'}) -function Split-PathEnv { -param([string]$EnvPath) - $EnvPath -split $PathEnvDelimiter -} -$global:MyPSModulePath = Split-PathEnv $env:PSModulePath | Where-Object { $_ -match "^$(Resolve-Path ~)" } +This sets up the `$PROFILE` file, and initilizes the default dir, but nothing else is done. +Cloning the repo, is something you'll need to deal with on your own, or you can call the next line. -if( -not $MyPSModulePath ) { - $MyPSModulePath = Resolve-Path ~/powershell/Modules - if( -not (Test-Path $MyPSModulePath) ) { - New-Item -ItemType Directory -Path $MyPSModulePath -Force | Out-Null - } - $env:PSModulePath = "$MyPSModulePath$PathEnvDelimiter$env:PSModulePath" -} - -$local:p = Split-PathEnv $env:PATH -$global:MyPSScriptRoot = Join-Path (Split-Path -Parent $MyPSModulePath) Scripts -if( -not (Test-Path $MyPSScriptRoot) ) { - New-Item -ItemType Directory -Path $MyPSScriptRoot -Force | Out-Null -} - -$p = @($p[0], $MyPSScriptRoot) + $($p | Select-Object -Skip 1) -$env:PATH = $p -join $PathEnvDelimiter - -Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $_.Name } +### The [prefered] Short, but with control option +```PowerShell +$sfw=1; iwr https://lksz.me/pwsz | iex; _setup [-sudo] [-Force] [-GitClone] [-GitURL ] [-WhatIf] [-Confirm] [] ``` + +This will setup the `$PROFILE` file properly, and when the `-GitClone` switch is used, the git repo is cloned into `$MyPSScriptRoot`. + +### The 'I don't trust one liners, what's going on ?!?' option +Follow the instructions in the initial [blog post](https://blog.lksz.me/keeping-track-of-everything/#-mypsscriptroot) which contains the steps for cloning and using the env as your own. + +In the above one-liners, `https://lksz.me/pwsz` actually points to the [Setup-Profile.ps1] file, which means, that after you have the `Scripts` directory setup, you can all `Setup-Profile` to setup the `$PROFILE` file. + + From ef920fbb7dbfb024c5e96251a943275b58cf29af Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 14:01:29 -0400 Subject: [PATCH 05/30] Fixed /home/szmedia/.local/share/powershell/Scripts assignment --- Setup-Profile.ps1 | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index fcfb59f..06d3865 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -397,24 +397,19 @@ Write-Verbose $(Get-Item $MyPSModulePath | Select-Object -ExpandProperty FullNam # Establish local/personal Script Root and make sure it's in $env:Path $local:p = Split-PathEnv $env:PATH -$MyPSScriptRoot = Join-Path (Split-Path -Parent $MyPSModulePath) Scripts -Write-Verbose "MyPSScriptRoot = $MyPSScriptRoot" -if ( -not (Test-Path $MyPSScriptRoot) ) { - New-Item -ItemType Directory -Path $MyPSScriptRoot -Force | Out-Null - New-Item -ItemType Directory -Path $MyPSScriptRoot/profile.d -Force | Out-Null +$local:My_PSScriptRoot = Join-Path (Split-Path -Parent $MyPSModulePath) Scripts +Write-Verbose "MyPSScriptRoot = $My_PSScriptRoot" +if ( -not (Test-Path $My_PSScriptRoot) ) { + New-Item -ItemType Directory -Path $My_PSScriptRoot -Force | Out-Null + New-Item -ItemType Directory -Path $My_PSScriptRoot/profile.d -Force | Out-Null } -$global:MyPSScriptRoot = $MyPSScriptRoot +$global:MyPSScriptRoot = $My_PSScriptRoot $p = @($p[0], $MyPSScriptRoot) + $($p | Select-Object -Skip 1) $env:PATH = $p -join $PathEnvDelimiter } -$local:importExpression = "" -if ( -not $MyPSScriptRoot -or (Test-Path function:Test-IsAdmin, function:ConvertTo-Base64, function:Invoke-ExpressionEx, function:Get-PowerShellPath, function:Export-FunctionSource | Where-Object { -not $_ } | Measure-Object | Select-Object -ExpandProperty Count) ) { - Write-Verbose "Calling ProfileCode inline..." - $importExpression = "ProfileCode_common" -} -. Invoke-Expression $importExpression +. ProfileCode_common $SetupFromWeb = [bool]$(@( $SetupFromWeb, $sfw, $LoadCode ) | Where-Object { $_ }) From 5a119da010c506c45c0dc0cbb68410571cdd7dba Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 14:11:46 -0400 Subject: [PATCH 06/30] Better instructions --- README.md | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 2569fb0..47dd6b2 100644 --- a/README.md +++ b/README.md @@ -12,19 +12,15 @@ This envrionment can be installed using one the following options: iwr https://lksz.me/pwsz | iex ``` -This sets up the `$PROFILE` file, and initilizes the default dir, but nothing else is done. -Cloning the repo, is something you'll need to deal with on your own, or you can call the next line. +This sets up the `$PROFILE` file, and initilizes the default dir `$MyPSScriptRoot` with a git clone of this repo. +The `https://lksz.me/pwsz` actually points to the [`Setup-Profile.ps1`](Setup-Profile.ps1) script, which means, that after you have the `Scripts` directory setup, you can call `Setup-Profile` to update the `$PROFILE` after the `Setup-Profile.ps1` has been modified (or updated via `git pull`). -### The [prefered] Short, but with control option +### The Short, but with control option ```PowerShell -$sfw=1; iwr https://lksz.me/pwsz | iex; _setup [-sudo] [-Force] [-GitClone] [-GitURL ] [-WhatIf] [-Confirm] [] +$sfw=1; iwr https://lksz.me/pwsz | iex; _setup [-sudo] [-Force] [-NoGitClone] [-GitURL ] [-WhatIf] [-Confirm] [] ``` -This will setup the `$PROFILE` file properly, and when the `-GitClone` switch is used, the git repo is cloned into `$MyPSScriptRoot`. +The key here is `$sfw=1`, which can be substitued with the more verbose `$SetupFromWeb=1`, this let's the [`Setup-Profile`](Setup-Profile.ps1) script know to just load it's content, but allow you to manually call it's internal function via `_setup` ### The 'I don't trust one liners, what's going on ?!?' option -Follow the instructions in the initial [blog post](https://blog.lksz.me/keeping-track-of-everything/#-mypsscriptroot) which contains the steps for cloning and using the env as your own. - -In the above one-liners, `https://lksz.me/pwsz` actually points to the [Setup-Profile.ps1] file, which means, that after you have the `Scripts` directory setup, you can all `Setup-Profile` to setup the `$PROFILE` file. - - +You can always clone the git repo first, and only then run the [`Setup-Profile.ps1`](Setup-Profile.ps1) script. \ No newline at end of file From c25de685c150378f6079f4ec887417f324c7111d Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 14:13:33 -0400 Subject: [PATCH 07/30] Replaced -GitClone with -NoGitClone --- Setup-Profile.ps1 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index 06d3865..8c9c4c4 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -3,7 +3,7 @@ [switch]$RemoveOnly, [switch]$ShowSkipped, [switch]$Force, - [switch]$GitClone, + [switch]$NoGitClone, [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [Parameter(DontShow)] [string]$MyPSScriptRoot = $MyPSScriptRoot @@ -15,7 +15,7 @@ function _Setup { [switch]$RemoveOnly, [switch]$ShowSkipped, [switch]$Force, - [switch]$GitClone, + [switch]$NoGitClone, [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [Parameter(DontShow)] [string]$MyPSScriptRoot = $MyPSScriptRoot) @@ -40,9 +40,9 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . ## _Setup Logic starts here ####################################################################### - if ( $GitClone -and -not (Test-Path $(Join-Path $MyPSScriptRoot '.git')) ) { + if ( -not $NoGitClone -and -not (Test-Path $(Join-Path $MyPSScriptRoot '.git')) ) { if ( -not [bool]$(Get-Command git -ErrorAction SilentlyContinue) ) { - throw "No git command found, you may either omit the -GitClone switch or install git and try again." + throw "No git command found, you may either omit run with the -NoGitClone switch or install git and try again." } if ( $PSCmdlet.ShouldProcess("Pull git repo from $GitURL into $MyPSScriptRoot ?") ) { Push-Location $MyPSScriptRoot @@ -59,7 +59,7 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $GitOutput = "$(& git checkout --force)" Write-Verbose $GitOutput Pop-Location - Write-Verbose "-GitClone step done." + Write-Verbose "Git clone done." } } From e14f00d98d5750a2c154946dfb2876dec3ef02b9 Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 14:16:23 -0400 Subject: [PATCH 08/30] Streamline setting of /home/szmedia/.local/share/powershell/Scripts during _setup --- Setup-Profile.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index 8c9c4c4..7a24ab8 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -40,6 +40,8 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . ## _Setup Logic starts here ####################################################################### + . ProfileCode_common + if ( -not $NoGitClone -and -not (Test-Path $(Join-Path $MyPSScriptRoot '.git')) ) { if ( -not [bool]$(Get-Command git -ErrorAction SilentlyContinue) ) { throw "No git command found, you may either omit run with the -NoGitClone switch or install git and try again." @@ -409,8 +411,6 @@ $p = @($p[0], $MyPSScriptRoot) + $($p | Select-Object -Skip 1) $env:PATH = $p -join $PathEnvDelimiter } -. ProfileCode_common - $SetupFromWeb = [bool]$(@( $SetupFromWeb, $sfw, $LoadCode ) | Where-Object { $_ }) if ( -not $SetupFromWeb ) { From fe97c2880a5b76df443cd2eb4dde1c64020d0a88 Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 14:23:54 -0400 Subject: [PATCH 09/30] Fixed cross linked device failing move of .git dir --- Setup-Profile.ps1 | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index 7a24ab8..46363f1 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -55,7 +55,15 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $local:GitOutput = "$(& git clone $GitURL $tmpGitDir.FullName --no-checkout)" Write-Verbose $GitOutput Write-Verbose "Moving git repo from temp location to $MyPSScriptRoot . . ." - Move-Item (Join-Path $tmpGitDir.FullName .git) ./.git + try { + Move-Item (Join-Path $tmpGitDir.FullName .git) ./.git -ErrorAction Stop + } catch { + if( $_.Exception.Message -eq "Invalid cross-device link" ) { + Copy-Item -Recurse (Join-Path $tmpGitDir.FullName .git) ./.git + } else { + throw $_ + } + } Remove-Item $tmpGitDir.FullName Write-Verbose "Checking out repo..." $GitOutput = "$(& git checkout --force)" From ccaaadf37146e1ff2f0330a72787f9294a9c292a Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 15:42:40 -0400 Subject: [PATCH 10/30] Setup fixed setup of MyPSScriptRoot (again) --- Reload-MyScripts.ps1 | 5 ++++- Setup-Profile.ps1 | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Reload-MyScripts.ps1 b/Reload-MyScripts.ps1 index a68e497..2762b22 100644 --- a/Reload-MyScripts.ps1 +++ b/Reload-MyScripts.ps1 @@ -55,7 +55,10 @@ if( Get-Command Remove-Alias -ErrorAction SilentlyContinue ) { } if( $(. Get-ScopeDepth) -gt 0 ) { Write-Host -ForegroundColor Red "Try sourcing Reload-MyScripts instead of just running it" } -Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object { ". '$($_.FullName)';" } | Invoke-Expression +Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object { + Write-Verbose "Loading $($_.FullName -replace '\.ps1$','' -replace "^$([regex]::Escape($MyPSScriptRoot)).",'')..."; + ". '$($_.FullName)';" + } | Invoke-Expression $local:CommandsToAlias = ( @( $MyPSScriptRoot ) + $( diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index 46363f1..ae273b3 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -6,7 +6,7 @@ [switch]$NoGitClone, [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [Parameter(DontShow)] - [string]$MyPSScriptRoot = $MyPSScriptRoot + [string]$My_PSScriptRoot = $MyPSScriptRoot ) function _Setup { @@ -18,7 +18,7 @@ function _Setup { [switch]$NoGitClone, [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [Parameter(DontShow)] - [string]$MyPSScriptRoot = $MyPSScriptRoot) + [string]$My_PSScriptRoot = $MyPSScriptRoot) ####################################################################### @@ -41,6 +41,7 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . ####################################################################### . ProfileCode_common + if( -not $MyPSScriptRoot ) { throw '$MyPSScriptRoot does NOT exist!' } if ( -not $NoGitClone -and -not (Test-Path $(Join-Path $MyPSScriptRoot '.git')) ) { if ( -not [bool]$(Get-Command git -ErrorAction SilentlyContinue) ) { From 90e17230521ad584f24679084ac8f20a67c8ca93 Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 15:49:24 -0400 Subject: [PATCH 11/30] Change Move-Item to Copy-Item --- Setup-Profile.ps1 | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index ae273b3..36f388f 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -56,15 +56,7 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $local:GitOutput = "$(& git clone $GitURL $tmpGitDir.FullName --no-checkout)" Write-Verbose $GitOutput Write-Verbose "Moving git repo from temp location to $MyPSScriptRoot . . ." - try { - Move-Item (Join-Path $tmpGitDir.FullName .git) ./.git -ErrorAction Stop - } catch { - if( $_.Exception.Message -eq "Invalid cross-device link" ) { - Copy-Item -Recurse (Join-Path $tmpGitDir.FullName .git) ./.git - } else { - throw $_ - } - } + Copy-Item -Recurse (Join-Path $tmpGitDir.FullName .git) ./.git Remove-Item $tmpGitDir.FullName Write-Verbose "Checking out repo..." $GitOutput = "$(& git checkout --force)" @@ -177,7 +169,7 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . Invoke-ExpressionEx -sudo:$shouldSudo chmod 'a+r' $tmpOutput.FullName } try { - $local:errMsg = $(Invoke-ExpressionEx -sudo:$shouldSudo "Move-Item $($tmpOutput.FullName) $p -Force:`$$Force -ErrorAction Stop | Out-Null" 2>&1) + $local:errMsg = $(Invoke-ExpressionEx -sudo:$shouldSudo "Copy-Item $($tmpOutput.FullName) $p -Force:`$$Force -ErrorAction Stop | Out-Null; Remove-Item $($tmpOutput.FullName) -Force:`$$Force -ErrorAction Stop" 2>&1) if ( $errMsg ) { Write-Error "$errMsg" $status = $status -replace 'Need ', 'Failed ' From e86c7350be83b375352538ba29e73635096c46a4 Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 15:54:23 -0400 Subject: [PATCH 12/30] Create $PROFILE's parent dir if it doesn't exists --- Setup-Profile.ps1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index 36f388f..8ad5c92 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -169,7 +169,11 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . Invoke-ExpressionEx -sudo:$shouldSudo chmod 'a+r' $tmpOutput.FullName } try { - $local:errMsg = $(Invoke-ExpressionEx -sudo:$shouldSudo "Copy-Item $($tmpOutput.FullName) $p -Force:`$$Force -ErrorAction Stop | Out-Null; Remove-Item $($tmpOutput.FullName) -Force:`$$Force -ErrorAction Stop" 2>&1) + $local:errMsg = $(Invoke-ExpressionEx -sudo:$shouldSudo @" + if( -not (Test-Path $(Split-Path -Parent $p)) ) { New-Item -Type Directory $(Split-Path -Parent $p) -Force }; + Copy-Item $($tmpOutput.FullName) $p -Force:`$$Force -ErrorAction Stop | Out-Null; + Remove-Item $($tmpOutput.FullName) -Force:`$$Force -ErrorAction Stop +"@ 2>&1) if ( $errMsg ) { Write-Error "$errMsg" $status = $status -replace 'Need ', 'Failed ' From 38aa7720de4e094af8a95a7cb616f5cacb112338 Mon Sep 17 00:00:00 2001 From: lksz Date: Fri, 2 Oct 2020 16:17:32 -0400 Subject: [PATCH 13/30] Added default env.ps1 --- profile.d/env.local.ps1.template | 3 +++ profile.d/env.ps1 | 1 + 2 files changed, 4 insertions(+) create mode 100644 profile.d/env.local.ps1.template create mode 100644 profile.d/env.ps1 diff --git a/profile.d/env.local.ps1.template b/profile.d/env.local.ps1.template new file mode 100644 index 0000000..80023cb --- /dev/null +++ b/profile.d/env.local.ps1.template @@ -0,0 +1,3 @@ +# $env:DOMAIN_NAME='example.com' +# +# $env:EDITOR='/usr/bin/nvim' diff --git a/profile.d/env.ps1 b/profile.d/env.ps1 new file mode 100644 index 0000000..cdf84f8 --- /dev/null +++ b/profile.d/env.ps1 @@ -0,0 +1 @@ +$env:SZ_SKIP_DEFAULT_SHELL = 1 From 968b6c2bbb7ea540e5b92d2cbb2f46a6ed4ab921 Mon Sep 17 00:00:00 2001 From: lksz Date: Sat, 3 Oct 2020 16:17:11 -0400 Subject: [PATCH 14/30] Adding common commands + Minor modifications Reload-MyScripts modified to check for past aliases that might block it from working. Aliases dir created with some basic aliases Invoke-Sudo to make sudo command line calling simpler. --- Aliases/edit | 1 + Aliases/nvim | 1 + Aliases/vi | 1 + Aliases/vim | 1 + ConvertFrom-Base64.ps1 | 2 ++ Edit-MyScript.ps1 | 3 ++- Invoke-Sudo.ps1 | 6 ++++++ Reload-MyScripts.ps1 | 13 ++++++++++--- dps.ps1 | 12 ++++++++++++ sys.Linux/ls.ps1 | 4 ++++ sys.Linux/sranger.ps1 | 3 +-- 11 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 Aliases/edit create mode 100644 Aliases/nvim create mode 100644 Aliases/vi create mode 100644 Aliases/vim create mode 100644 ConvertFrom-Base64.ps1 create mode 100644 Invoke-Sudo.ps1 create mode 100644 dps.ps1 create mode 100644 sys.Linux/ls.ps1 diff --git a/Aliases/edit b/Aliases/edit new file mode 100644 index 0000000..e099b51 --- /dev/null +++ b/Aliases/edit @@ -0,0 +1 @@ +Edit-TextFile diff --git a/Aliases/nvim b/Aliases/nvim new file mode 100644 index 0000000..e099b51 --- /dev/null +++ b/Aliases/nvim @@ -0,0 +1 @@ +Edit-TextFile diff --git a/Aliases/vi b/Aliases/vi new file mode 100644 index 0000000..e099b51 --- /dev/null +++ b/Aliases/vi @@ -0,0 +1 @@ +Edit-TextFile diff --git a/Aliases/vim b/Aliases/vim new file mode 100644 index 0000000..e099b51 --- /dev/null +++ b/Aliases/vim @@ -0,0 +1 @@ +Edit-TextFile diff --git a/ConvertFrom-Base64.ps1 b/ConvertFrom-Base64.ps1 new file mode 100644 index 0000000..4dbbdeb --- /dev/null +++ b/ConvertFrom-Base64.ps1 @@ -0,0 +1,2 @@ +param([string]$Base64String) + return [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Base64String)) diff --git a/Edit-MyScript.ps1 b/Edit-MyScript.ps1 index ddfbdbe..a3e57ba 100644 --- a/Edit-MyScript.ps1 +++ b/Edit-MyScript.ps1 @@ -66,7 +66,8 @@ if( -not $ScriptPaths ) { foreach( $local:p in $ScriptPaths ) { $local:parentPath = Split-Path -Parent $p; if( -not (Test-Path $p) -and -not (Test-Path $parentPath) ) { - New-Item -Directory $parentPath + Write-Verbose "Creating missing path $parentPath..." + New-Item -Type Directory $parentPath } } diff --git a/Invoke-Sudo.ps1 b/Invoke-Sudo.ps1 new file mode 100644 index 0000000..c8816d3 --- /dev/null +++ b/Invoke-Sudo.ps1 @@ -0,0 +1,6 @@ +[CmdletBinding(SupportsShouldProcess)]param( + [Parameter(Mandatory = $true,Position = 0, ValueFromRemainingArguments = $true)] + $expr +) + +. Invoke-ExpressionEx -sudo $expr diff --git a/Reload-MyScripts.ps1 b/Reload-MyScripts.ps1 index 2762b22..a2017bf 100644 --- a/Reload-MyScripts.ps1 +++ b/Reload-MyScripts.ps1 @@ -1,5 +1,6 @@ [CmdletBinding(SupportsShouldProcess)]param() +try { Get-Alias Get-MyAliases -ErrorAction Stop | ForEach-Object { Remove-Item "Alias:$($_.Name)" } } catch {} function Get-MyAliases { [CmdletBinding(SupportsShouldProcess)]param([switch]$ScriptsOnly) @@ -29,9 +30,13 @@ function Get-MyAliases { $allAliases } +function getScriptName{param([string]$FullPath) + $FullPath -replace '\.ps1$','' -replace "^$([regex]::Escape($MyPSScriptRoot)).",'' +} + $local:myAliases = [ordered]@{} if( Test-Path $(Join-Path $MyPSScriptRoot Aliases) ) { - Get-ChildItem Join-Path (Join-Path $MyPSScriptRoot Aliases) | ForEach-Object { + Get-ChildItem $(Join-Path $MyPSScriptRoot Aliases) | ForEach-Object { $myAliases[$_.BaseName] = Get-Content $_ } } @@ -56,14 +61,14 @@ if( Get-Command Remove-Alias -ErrorAction SilentlyContinue ) { if( $(. Get-ScopeDepth) -gt 0 ) { Write-Host -ForegroundColor Red "Try sourcing Reload-MyScripts instead of just running it" } Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object { - Write-Verbose "Loading $($_.FullName -replace '\.ps1$','' -replace "^$([regex]::Escape($MyPSScriptRoot)).",'')..."; + Write-Verbose "Loading $(getScriptName $_.FullName)..."; ". '$($_.FullName)';" } | Invoke-Expression $local:CommandsToAlias = ( @( $MyPSScriptRoot ) + $( [SystemName]::_GetValidValues("",$true,$true) | ForEach-Object { - Join-Path $MyPSScriptRoot $_ + Join-Path $MyPSScriptRoot "sys.$_" } )) | ForEach-Object { if( Test-Path $_ ) { @@ -72,10 +77,12 @@ $local:CommandsToAlias = ( } $CommandsToAlias | ForEach-Object { + Write-Verbose "Creating alias for $(getScriptName $_.FullName) Script..." Set-Alias $($_.BaseName) $_.FullName -Scope $MyAliasScope } foreach( $local:alias in $myAliases.Keys ) { + Write-Verbose "Adding $($alias) alias..." Set-Alias -Name $alias -Value $myAliases[$alias] -Description '#MyAlias' -Scope $MyAliasScope } diff --git a/dps.ps1 b/dps.ps1 new file mode 100644 index 0000000..85aa8c6 --- /dev/null +++ b/dps.ps1 @@ -0,0 +1,12 @@ +#[CmdletBinding(SupportsShouldProcess)]param( +[CmdletBinding()]param([string[]]$OrderBy,[switch]$PassThru) + +$local:result = $(docker ps --format='{{ .Image }}\t{{ .Names }}\t{{ .Status }}\t{{ .Ports }}' | ForEach-Object { $local:l = $_ -split '\t'; [PSCustomObject](@{Image=$l[0];Names=$l[1];Status=$l[2];Ports=$l[3] -replace ', '," +"}) } ) | Sort-Object Names + +if( $OrderBy ) { + $result = $result | Sort-Object $OrderBy +} + +if( $PassThru ) { return $result } +$result | Format-Table -Wrap -Property Image,Names,Status,Ports diff --git a/sys.Linux/ls.ps1 b/sys.Linux/ls.ps1 new file mode 100644 index 0000000..42cc8eb --- /dev/null +++ b/sys.Linux/ls.ps1 @@ -0,0 +1,4 @@ +$local:params = $args -join ' ' +if( -not $params ) { $params = '-la' } +/usr/bin/env ls $params + diff --git a/sys.Linux/sranger.ps1 b/sys.Linux/sranger.ps1 index fa3e734..d8146d3 100644 --- a/sys.Linux/sranger.ps1 +++ b/sys.Linux/sranger.ps1 @@ -1,2 +1 @@ - -Invoke-ExpressionEx -sudo "`$env:TERM='tmux-256color'; `$env:EDITOR='$env:EDITOR'; ranger" +Invoke-ExpressionEx -sudo "`$env:TERM='tmux-256color'; `$env:EDITOR='$env:EDITOR'; ranger $args" From f4abdf1a2d0c95f0295d50cf4e6262123d0a78c9 Mon Sep 17 00:00:00 2001 From: Gal Szkolnik Date: Sat, 3 Oct 2020 16:23:08 -0400 Subject: [PATCH 15/30] Fixed minor cross-platfrom bug in Reload-MyScripts --- Reload-MyScripts.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Reload-MyScripts.ps1 b/Reload-MyScripts.ps1 index a2017bf..c421da8 100644 --- a/Reload-MyScripts.ps1 +++ b/Reload-MyScripts.ps1 @@ -37,7 +37,7 @@ function getScriptName{param([string]$FullPath) $local:myAliases = [ordered]@{} if( Test-Path $(Join-Path $MyPSScriptRoot Aliases) ) { Get-ChildItem $(Join-Path $MyPSScriptRoot Aliases) | ForEach-Object { - $myAliases[$_.BaseName] = Get-Content $_ + $myAliases[$_.BaseName] = Get-Content $_.FullName } } From 306e03874d7fc02b7e7e151b818667e81c4a6b5c Mon Sep 17 00:00:00 2001 From: lksz Date: Sat, 3 Oct 2020 16:32:55 -0400 Subject: [PATCH 16/30] Setup-Profile will update git scripts from git repo --- Setup-Profile.ps1 | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/Setup-Profile.ps1 b/Setup-Profile.ps1 index 8ad5c92..b4276dc 100644 --- a/Setup-Profile.ps1 +++ b/Setup-Profile.ps1 @@ -3,7 +3,7 @@ [switch]$RemoveOnly, [switch]$ShowSkipped, [switch]$Force, - [switch]$NoGitClone, + [switch]$NoGitAction, [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [Parameter(DontShow)] [string]$My_PSScriptRoot = $MyPSScriptRoot @@ -15,7 +15,7 @@ function _Setup { [switch]$RemoveOnly, [switch]$ShowSkipped, [switch]$Force, - [switch]$NoGitClone, + [switch]$NoGitAction, [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [Parameter(DontShow)] [string]$My_PSScriptRoot = $MyPSScriptRoot) @@ -43,12 +43,14 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . . ProfileCode_common if( -not $MyPSScriptRoot ) { throw '$MyPSScriptRoot does NOT exist!' } - if ( -not $NoGitClone -and -not (Test-Path $(Join-Path $MyPSScriptRoot '.git')) ) { + if ( -not $NoGitAction ) { if ( -not [bool]$(Get-Command git -ErrorAction SilentlyContinue) ) { - throw "No git command found, you may either omit run with the -NoGitClone switch or install git and try again." + throw "No git command found, you may either omit run with the -NoGitAction switch or install git and try again." } - if ( $PSCmdlet.ShouldProcess("Pull git repo from $GitURL into $MyPSScriptRoot ?") ) { - Push-Location $MyPSScriptRoot + Push-Location $MyPSScriptRoot + if( Test-Path $(Join-Path $MyPSScriptRoot '.git') ) { + git pull + } elseif ( $PSCmdlet.ShouldProcess("Pull git repo from $GitURL into $MyPSScriptRoot ?") ) { $local:tmpGitDir = New-TemporaryFile Remove-Item $tmpGitDir New-Item -Type Directory $tmpGitDir.FullName | Out-Null @@ -61,9 +63,9 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . Write-Verbose "Checking out repo..." $GitOutput = "$(& git checkout --force)" Write-Verbose $GitOutput - Pop-Location - Write-Verbose "Git clone done." } + Pop-Location + Write-Verbose "Git operation done." } $local:ProfileSignature = [PSCustomObject]([ordered]@{ @@ -421,5 +423,6 @@ $SetupFromWeb = [bool]$(@( $SetupFromWeb, $sfw, $LoadCode ) | Where-Object { $_ if ( -not $SetupFromWeb ) { _setup @PSBoundParameters Get-Item function:_setup | Remove-Item + Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $_.Name } } Remove-Variable SetupFromWeb -ErrorAction SilentlyContinue From 310103c2f73be35d3847cec345dc024e0efe05bd Mon Sep 17 00:00:00 2001 From: lksz Date: Sat, 31 Oct 2020 17:10:32 -0400 Subject: [PATCH 17/30] A lot of new stuff Docker and Docker-Compose commands and aliases: - dco: docker-compose - dcc: docker-compose config - dcedit/vidc/Edit-DockerCompose: edit docker-compose.yml and satellite files - dcdown.ps1 - dl/dll/dcl/dcll: view docker/docker-compose logs l : follow ll : just list - dx/dcx: docker / docker-compose exec - dcdown: docker-compose down - dcup: docker-compose up - dcr: docker-compose run - dcre: docker-compose restart - dcreup: docker-compose up with force recreate - di: docker inspect A bunch of other aliases and tools: - l/ll - shortcuts for ls -la - Edit-MyConfig with MyConfig.class: Edit various configuration files - Update-ArchOSz: my common update params for Arch all ready to run - Update-UbuntuOSz: my common update params for Ubuntu all ready to run - sz-df - a ps stylized df - sz-du - what's the size of a dir - sys.Linux/ls - a Linux specific ls (with all required configuration) Works in progress (not completely tested yet): - Stop-ProcessTree - Update-OSz.ps1 - src/smartsudo.inc.ps1 --- Aliases/dcedit.ps1 | 1 + Aliases/dco.ps1 | 1 + Aliases/l.ps1 | 1 + Aliases/ll.ps1 | 1 + Aliases/vidc.ps1 | 1 + Edit-DockerCompose.ps1 | 14 ++++++++++ Edit-MyConfig.ps1 | 21 ++++++++++++++ Stop-ProcessTree.ps1 | 13 +++++++++ Update-ArchOSz.ps1 | 13 +++++++++ Update-OSz.ps1 | 10 +++++++ Update-UbuntuOSz.ps1 | 14 ++++++++++ dcc.ps1 | 1 + dcdown.ps1 | 1 + dcl.ps1 | 1 + dcll.ps1 | 1 + dcr.ps1 | 1 + dcre.ps1 | 1 + dcreup.ps1 | 11 ++++++++ dcup.ps1 | 10 +++++++ dcx.ps1 | 1 + di.ps1 | 1 + dl.ps1 | 1 + dll.ps1 | 1 + dx.ps1 | 1 + profile.d/MyConfig.class.ps1 | 53 ++++++++++++++++++++++++++++++++---- src/smartsudo.inc.ps1 | 18 ++++++++++++ sys.Linux/ls.ps1 | 5 ++-- sz-df.ps1 | 35 ++++++++++++++++++++++++ sz-du.ps1 | 1 + 29 files changed, 226 insertions(+), 8 deletions(-) create mode 100644 Aliases/dcedit.ps1 create mode 100644 Aliases/dco.ps1 create mode 100644 Aliases/l.ps1 create mode 100644 Aliases/ll.ps1 create mode 100644 Aliases/vidc.ps1 create mode 100644 Edit-DockerCompose.ps1 create mode 100644 Edit-MyConfig.ps1 create mode 100644 Stop-ProcessTree.ps1 create mode 100644 Update-ArchOSz.ps1 create mode 100644 Update-OSz.ps1 create mode 100644 Update-UbuntuOSz.ps1 create mode 100644 dcc.ps1 create mode 100644 dcdown.ps1 create mode 100644 dcl.ps1 create mode 100644 dcll.ps1 create mode 100644 dcr.ps1 create mode 100644 dcre.ps1 create mode 100644 dcreup.ps1 create mode 100644 dcup.ps1 create mode 100644 dcx.ps1 create mode 100644 di.ps1 create mode 100644 dl.ps1 create mode 100644 dll.ps1 create mode 100644 dx.ps1 create mode 100644 src/smartsudo.inc.ps1 create mode 100644 sz-df.ps1 create mode 100644 sz-du.ps1 diff --git a/Aliases/dcedit.ps1 b/Aliases/dcedit.ps1 new file mode 100644 index 0000000..a5533c7 --- /dev/null +++ b/Aliases/dcedit.ps1 @@ -0,0 +1 @@ +Edit-DockerCompose diff --git a/Aliases/dco.ps1 b/Aliases/dco.ps1 new file mode 100644 index 0000000..e41f756 --- /dev/null +++ b/Aliases/dco.ps1 @@ -0,0 +1 @@ +docker-compose diff --git a/Aliases/l.ps1 b/Aliases/l.ps1 new file mode 100644 index 0000000..9e2740c --- /dev/null +++ b/Aliases/l.ps1 @@ -0,0 +1 @@ +ls diff --git a/Aliases/ll.ps1 b/Aliases/ll.ps1 new file mode 100644 index 0000000..9e2740c --- /dev/null +++ b/Aliases/ll.ps1 @@ -0,0 +1 @@ +ls diff --git a/Aliases/vidc.ps1 b/Aliases/vidc.ps1 new file mode 100644 index 0000000..a5533c7 --- /dev/null +++ b/Aliases/vidc.ps1 @@ -0,0 +1 @@ +Edit-DockerCompose diff --git a/Edit-DockerCompose.ps1 b/Edit-DockerCompose.ps1 new file mode 100644 index 0000000..9557e54 --- /dev/null +++ b/Edit-DockerCompose.ps1 @@ -0,0 +1,14 @@ +[CmdletBinding(SupportsShouldProcess)]param([string[]]$ProjectPath=@($PWD)) + +$local:editCandidates = @('docker-compose.yml','.base.docker-compose.yml') +$local:editFiles = @() +foreach( $local:fileName in $EditCandidates ) { + foreach( $local:path in $ProjectPath ) { + $local:testPath = Join-Path $path $fileName + if( Test-Path $testPath ) { $editFiles += $testPath } + } +} + +Edit-TextFile $editFiles + +docker-compose config -q diff --git a/Edit-MyConfig.ps1 b/Edit-MyConfig.ps1 new file mode 100644 index 0000000..882f5cf --- /dev/null +++ b/Edit-MyConfig.ps1 @@ -0,0 +1,21 @@ +[CmdletBinding(SupportsShouldProcess)]param( + [Parameter(Position = 0, ValueFromRemainingArguments)] + [ArgumentCompleter({ param ( + $commandName, + $parameterName, + $wordToComplete, + $commandAst, + $fakeBoundParameters + ) + [MyConfig]::_GetValidValues($wordToComplete,$true) | Sort-Object + })] + [string[]]$ConfigName, + [switch]$Force +) +if( -not $ConfigName ) { + ([MyConfig]::_GetValidValues('',$true)) | Sort-Object + return +} +$local:ScriptPaths = [MyConfig]::GetConfigPaths($ConfigName,$Force) + +Edit-TextFile $ScriptPaths diff --git a/Stop-ProcessTree.ps1 b/Stop-ProcessTree.ps1 new file mode 100644 index 0000000..9e838e0 --- /dev/null +++ b/Stop-ProcessTree.ps1 @@ -0,0 +1,13 @@ +[cmdletbinding()]param([string]$ProcessName) + $local:new_KillPIDs = @() + (Get-Process -name $processName | Select-Object -ExpandProperty ID) + $local:KillPIDs = @() + Do { + $KillPIDs += $new_KillPIDs | Where-Object { $_ -notin $KillPIDs } + Write-Verbose "Again" + Write-Verbose $new_KillPIDs -join ", " + $new_KillPIDs = $new_KillPIDs | ForEach-Object { Get-CimInstance -ClassName Win32_Process -Filter "ParentProcessId = $_" } | Select-Object -ExpandProperty ProcessId + } Until ( -not $new_KillPIDs ) + + Write-Verbose "Done" + + start-process powershell -ArgumentList "-command","Stop-Process -Force -Id @($($KillPIDs -join '', ''))" -WindowStyle Minimized diff --git a/Update-ArchOSz.ps1 b/Update-ArchOSz.ps1 new file mode 100644 index 0000000..2c8e0b2 --- /dev/null +++ b/Update-ArchOSz.ps1 @@ -0,0 +1,13 @@ +param( + [ValidateSet('List','Update','Auto','All')] + [string]$Mode = 'List' +) + +$script:yayCli = "cat /run/check.yay.updates/list" +switch( $Mode ){ + 'Update' { $yayCli = "yay -Syu --needed --ignore docker,linux,linux-api-headers,linux-firmware,linux-headers,zfs-linux" } + 'Auto' { $yayCli = "yay -Syu --needed --noconfirm --ignore docker || yay -Syu --needed --ignore docker,linux,linux-api-headers,linux-firmware,linux-headers,zfs-linux --noconfirm" } + 'All' { $yayCli = "yay -Syu --needed" } +} + +& sh "-c" "$yayCli" -replace '#args',"$args" diff --git a/Update-OSz.ps1 b/Update-OSz.ps1 new file mode 100644 index 0000000..a82dfcc --- /dev/null +++ b/Update-OSz.ps1 @@ -0,0 +1,10 @@ +param( + [ValidateSet('List','Update','Auto','All')] + [string]$Mode = 'List' +) + +$local:detectedDisistro = cat /etc/os-release | Select-String -Pattern "^ID=" | ForEach-Object { $_ -split '=' | Select-Object -Skip 1 } +switch ($detectedDisistro) { + 'arch' { Update-ArchOSz -Mode:$Mode $args } + 'ubuntu' { Update-UbuntuOSz -Mode:$Mode $args } +} diff --git a/Update-UbuntuOSz.ps1 b/Update-UbuntuOSz.ps1 new file mode 100644 index 0000000..71bc9bf --- /dev/null +++ b/Update-UbuntuOSz.ps1 @@ -0,0 +1,14 @@ +param( + [ValidateSet('List','Update','Auto','All')] + [string]$Mode = 'List' +) + +$script:aptCli = "echo 'not defined'" +switch( $Mode ){ + 'List' { } + 'Auto' { $aptCli = "sudo apt-get update && sudo apt-get upgrade --auto-remove --assume-yes" } + default { $aptCli = "sudo apt-get update && sudo apt-get upgrade --auto-remove " } +} + +& sh "-c" "$aptCli" -replace '#args',"$args" + diff --git a/dcc.ps1 b/dcc.ps1 new file mode 100644 index 0000000..f8a1e1c --- /dev/null +++ b/dcc.ps1 @@ -0,0 +1 @@ +docker-compose config | less diff --git a/dcdown.ps1 b/dcdown.ps1 new file mode 100644 index 0000000..a7cd9c5 --- /dev/null +++ b/dcdown.ps1 @@ -0,0 +1 @@ +docker-compose down --timeout=3 --volumes --remove-orphans "$args" diff --git a/dcl.ps1 b/dcl.ps1 new file mode 100644 index 0000000..d41ca60 --- /dev/null +++ b/dcl.ps1 @@ -0,0 +1 @@ +docker-compose logs --tail=40 --follow "$args" diff --git a/dcll.ps1 b/dcll.ps1 new file mode 100644 index 0000000..a5ffc0d --- /dev/null +++ b/dcll.ps1 @@ -0,0 +1 @@ +docker-compose logs "$args" diff --git a/dcr.ps1 b/dcr.ps1 new file mode 100644 index 0000000..6406f9e --- /dev/null +++ b/dcr.ps1 @@ -0,0 +1 @@ +docker-compose run --rm "$args" diff --git a/dcre.ps1 b/dcre.ps1 new file mode 100644 index 0000000..f0fc796 --- /dev/null +++ b/dcre.ps1 @@ -0,0 +1 @@ +docker-compose restart "$args" diff --git a/dcreup.ps1 b/dcreup.ps1 new file mode 100644 index 0000000..052c0d5 --- /dev/null +++ b/dcreup.ps1 @@ -0,0 +1,11 @@ +#[CmdletBinding(SupportsShouldProcess)]param() + +$local:dcParams = [string]::Empty +if( $args ) { + $dcParams = $args | ForEach-Object { + if( $_ -match "(?:^'[^']+'$)|(?:^`"[^`"]+`"$)|(?:^[^\s]+$)" ) { $_ } + else { "'$($_.Replace( "'", "''" ))'" } + } +} +docker-compose up -d --force-recreate --remove-orphans $dcParams && docker-compose logs --follow --tail 10 $dcParams + diff --git a/dcup.ps1 b/dcup.ps1 new file mode 100644 index 0000000..5ab64b0 --- /dev/null +++ b/dcup.ps1 @@ -0,0 +1,10 @@ +#[CmdletBinding(SupportsShouldProcess)]param() + +$local:dcParams = [string]::Empty +if( $args ) { + $dcParams = $args | ForEach-Object { + if( $_ -match "(?:^'[^']+'$)|(?:^`"[^`"]+`"$)|(?:^[^\s]+$)" ) { $_ } + else { "'$($_.Replace( "'", "''" ))'" } + } +} +docker-compose up -d --remove-orphans $dcParams && docker-compose logs --follow --tail 10 $dcParams diff --git a/dcx.ps1 b/dcx.ps1 new file mode 100644 index 0000000..130dda9 --- /dev/null +++ b/dcx.ps1 @@ -0,0 +1 @@ +docker-compose exec "$args" diff --git a/di.ps1 b/di.ps1 new file mode 100644 index 0000000..97c8027 --- /dev/null +++ b/di.ps1 @@ -0,0 +1 @@ +docker inspect "$args" diff --git a/dl.ps1 b/dl.ps1 new file mode 100644 index 0000000..6d4edec --- /dev/null +++ b/dl.ps1 @@ -0,0 +1 @@ +docker logs --tail=40 --follow "$args" diff --git a/dll.ps1 b/dll.ps1 new file mode 100644 index 0000000..cadf8c1 --- /dev/null +++ b/dll.ps1 @@ -0,0 +1 @@ +docker logs "$args" diff --git a/dx.ps1 b/dx.ps1 new file mode 100644 index 0000000..d69452c --- /dev/null +++ b/dx.ps1 @@ -0,0 +1 @@ +docker exec "$args" diff --git a/profile.d/MyConfig.class.ps1 b/profile.d/MyConfig.class.ps1 index 19f3d52..eb4a92f 100644 --- a/profile.d/MyConfig.class.ps1 +++ b/profile.d/MyConfig.class.ps1 @@ -1,13 +1,54 @@ class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { - static [hashtable]$configDirectory = [ordered]@{ - 'vi' = '~/.virc' - 'vim' = '~/.vimrc','~/.vim/vimrc' - 'neovim' = '~/.config/nvim/init.vim','~/.config/nvim/vim-plug/plugins.vim','#vim','#vi' + static [hashtable]$configDirectory = @{}; + static ReloadConfigPaths() { + [MyConfig]::ConfigDirectory = [ordered]@{ + 'vi' = '~/.virc' + 'vim' = '~/.vimrc','~/.vim/vimrc' + 'neovim' = '~/.config/nvim/init.vim','~/.config/nvim/vim-plug/plugins.vim','#vim','#vi' + 'zshrc' = '~/.zshrc' + 'sz-zshrc' = '~/.sz.zshrc.sh', '#zshrc' + 'sz-local-rc' = '~/.sz.local.sh' + 'sz-aliases-sh' = '~/.sz.aliases.sh' + 'sz-shrc' = '~/.sz.shrc.sh' + 'sz-rc-all' = '#sz-aliases-sh', '#sz-local-rc', '#sz-shrc', '#sz-zshrc', '#zshrc' + 'tmux' = '~/.tmux.conf', '~/.byobu/.tmux.conf' + } } - static [string[]] GetConfigPaths([string[]]$ConfigNames) { - return $null + static [string[]] GetConfigPaths([string[]]$ConfigNames,[switch]$Force) { + [MyConfig]::ReloadConfigPaths() + $local:result = [string[]]@() + $local:flat = $false + while(-not $flat) { + $flat = $true + $ConfigNames += $ConfigNames | ForEach-Object { + [MyConfig]::configDirectory[$_] + } | Where-Object { $_ -match '^#[\w-\.]+$' } | ForEach-Object { + $_.Substring(1) + } | Where-Object { $_ -notin $ConfigNames } | ForEach-Object { + $flat = false; $_; + } + } + + $local:flatConfigList = $ConfigNames | ForEach-Object { + [MyConfig]::configDirectory[$_] + } | Where-Object { $_ -notmatch '^#[\w-\.]+$' } + + $local:exists = $false; + $local:first = $null + foreach( $local:configPath in $flatConfigList ) { + if( -not $first ) { $first = $configPath } + if( $Force -or (Test-Path $configPath) ) { + $result += Resolve-Path $configPath + $exists = $true + } + } + if( -not $exists -and -not $Force ) { + $result += $first + } + return $result } static [string[]] _GetValidValues([string]$wordToComplete,[bool]$Strict) { + [MyConfig]::ReloadConfigPaths() $local:possibleValues = [MyConfig]::configDirectory.Keys return $(Get-PossibleArguments -WordToComplete $wordToComplete -FullValueSet $possibleValues -Strict:$Strict ); } diff --git a/src/smartsudo.inc.ps1 b/src/smartsudo.inc.ps1 new file mode 100644 index 0000000..0dee229 --- /dev/null +++ b/src/smartsudo.inc.ps1 @@ -0,0 +1,18 @@ +function smartsudo() { +[CmdletBinding(SupportsShouldProcess)]param( + [switch]$sudo, + [switch]$Force, + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]]$expr +) + + if( $sudo -and -not $(Test-IsAdmin) ) { + Write-Verbose "Perofrming the following command line via SUDO:`n$($expr -join ' ')" + $local:base64command = ConvertTo-Base64 "$expr" + /usr/bin/env sudo pwsh -EncodedCommand $base64command + return + } + + Write-Verbose "Perofrming the following expression in-line:`n$($expr -join ' ')" + Invoke-Expression "$expr" +} diff --git a/sys.Linux/ls.ps1 b/sys.Linux/ls.ps1 index 42cc8eb..89ef76e 100644 --- a/sys.Linux/ls.ps1 +++ b/sys.Linux/ls.ps1 @@ -1,4 +1,5 @@ $local:params = $args -join ' ' -if( -not $params ) { $params = '-la' } -/usr/bin/env ls $params +if( -not $params ) { $params = '-lah' } + +/usr/bin/env ls --color=auto $params diff --git a/sz-df.ps1 b/sz-df.ps1 new file mode 100644 index 0000000..c1adf10 --- /dev/null +++ b/sz-df.ps1 @@ -0,0 +1,35 @@ +param([ValidateSet('KB','GB','TB')]$SizeUnitName = 'GB') +$local:zpool_cmd = $null +$local:excludeType = '' + +$script:SizeUnit = Invoke-Expression "1$SizeUnitName" +$script:SizeRound = 2 +$SizeUnit /= 1KB + +function NewDataRow{param($Size,$Used,$Available,$Percent,$Source,$FSType,$Target) + [PSCustomObject]@{ + "Size$SizeUnitName" = [Math]::Round($Size /$SizeUnit, $SizeRound) + "Used$SizeUnitName" = [Math]::Round($Used /$SizeUnit, $SizeRound) + "Available$SizeUnitName" = [Math]::Round($Available/$SizeUnit, $SizeRound) + 'Used%' = [int]($Percent -replace '%$','') + Source = $Source + FSType = $FSType + Target = $Target + } +} + +$local:df = @() +& df '--output=size,used,avail,pcent,source,fstype,target' | + Select-Object -Skip 1 | ForEach-Object { + $local:df = $_.Split(' ', [StringSplitOptions]::RemoveEmptyEntries) + NewDataRow $df[0] $df[1] $df[2] $df[3] $df[4] $df[5] $df[6] + } | Where-Object { + -not ($_.FSType -eq 'zfs' -and $_.Source -match '/') + } | Sort-Object -Property Target + +#$zpool_cmd = get-command zpool | Where-Object CommandType -eq 'Application' | Select-Object -ExpandProperty Source +#if( $zpool_cmd ) { +# $excludeType = '--exclude-type=zfs' +#} + + diff --git a/sz-du.ps1 b/sz-du.ps1 new file mode 100644 index 0000000..134e3bf --- /dev/null +++ b/sz-du.ps1 @@ -0,0 +1 @@ +sudo /bin/du --human-readable --max-depth=1 --one-file-system $args | sort --human-numeric-sort --reverse From b1980e5820b2f09ac1723579d0d7108180d5ade9 Mon Sep 17 00:00:00 2001 From: lksz Date: Sun, 1 Nov 2020 00:55:38 -0400 Subject: [PATCH 18/30] Ansible support + sz-update alias --- Aliases/sz-update.ps1 | 1 + Invoke-ViaAnsible.ps1 | 19 +++++++++++++++++++ Pull-ViaAnsible.ps1 | 3 +++ Update-ViaAnsible.ps1 | 3 +++ 4 files changed, 26 insertions(+) create mode 100644 Aliases/sz-update.ps1 create mode 100644 Invoke-ViaAnsible.ps1 create mode 100644 Pull-ViaAnsible.ps1 create mode 100644 Update-ViaAnsible.ps1 diff --git a/Aliases/sz-update.ps1 b/Aliases/sz-update.ps1 new file mode 100644 index 0000000..c680027 --- /dev/null +++ b/Aliases/sz-update.ps1 @@ -0,0 +1 @@ +Update-OSz diff --git a/Invoke-ViaAnsible.ps1 b/Invoke-ViaAnsible.ps1 new file mode 100644 index 0000000..3f1425d --- /dev/null +++ b/Invoke-ViaAnsible.ps1 @@ -0,0 +1,19 @@ +[CmdletBinding()]param([string[]]$Command, [switch]$NotPowerShell, [string[]]$Remotes) + +$script:ansible_cli=@('ansible') +if( (Test-Path './ansible.cfg') -or (Test-Path '/opt/ansible/hosts') -and (Test-Path '/opt/ansible/ssh_key_for_ansible') ) { + $ansible_cli += '-i', '/opt/ansible/hosts', '--private-key=/opt/ansible/ssh_key_for_ansible' +} +if( $Command ) { + $ansible_cli += '-a' + if( $NotPowerShell ) { + $ansible_cli += $(($Command -join '; ').Replace("'","\`$(printf '\x27')").Replace('"',"\`$(printf '\x22')")) + } else { + $ansible_cli += "pwsh -encodedcommand $(ConvertTo-Base64 $($Command -join '; '))" + } +} +$ansible_cli += $Remotes + +$local:expr = $('& "'+$($ansible_cli -join '" "')+'"') +Write-Verbose $expr +Invoke-Expression $expr diff --git a/Pull-ViaAnsible.ps1 b/Pull-ViaAnsible.ps1 new file mode 100644 index 0000000..8b53770 --- /dev/null +++ b/Pull-ViaAnsible.ps1 @@ -0,0 +1,3 @@ +[CmdletBinding()]param([string[]]$Remotes = 'All') + +Invoke-ViaAnsible -Command "git pull" -Remotes:$($Remotes.ToLower()) diff --git a/Update-ViaAnsible.ps1 b/Update-ViaAnsible.ps1 new file mode 100644 index 0000000..7433136 --- /dev/null +++ b/Update-ViaAnsible.ps1 @@ -0,0 +1,3 @@ +[CmdletBinding()]param([string[]]$Remotes = 'All') + +Invoke-ViaAnsible -Command "Update-OSz -Mode Auto" -Remotes:$($Remotes.ToLower()) From 4de25b4a56ddcaaf66d8588dfeb81dd5534c84d6 Mon Sep 17 00:00:00 2001 From: lksz Date: Sun, 1 Nov 2020 01:26:20 -0400 Subject: [PATCH 19/30] Added -OneLine which outputs a PS table --- Invoke-ViaAnsible.ps1 | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Invoke-ViaAnsible.ps1 b/Invoke-ViaAnsible.ps1 index 3f1425d..3e5c8ce 100644 --- a/Invoke-ViaAnsible.ps1 +++ b/Invoke-ViaAnsible.ps1 @@ -1,4 +1,10 @@ -[CmdletBinding()]param([string[]]$Command, [switch]$NotPowerShell, [string[]]$Remotes) +[CmdletBinding()]param( + [string[]]$Command, + [string[]]$Remotes = 'all', + [string[]]$MoreArgs, + [switch]$NotPowerShell, + [switch]$OneLine +) $script:ansible_cli=@('ansible') if( (Test-Path './ansible.cfg') -or (Test-Path '/opt/ansible/hosts') -and (Test-Path '/opt/ansible/ssh_key_for_ansible') ) { @@ -12,8 +18,29 @@ if( $Command ) { $ansible_cli += "pwsh -encodedcommand $(ConvertTo-Base64 $($Command -join '; '))" } } +if( $OneLine ) { + $ansible_cli += '--one-line' +} $ansible_cli += $Remotes +$ansible_cli += $MoreArgs $local:expr = $('& "'+$($ansible_cli -join '" "')+'"') Write-Verbose $expr -Invoke-Expression $expr +$local:SaveConsoleColor = [Console]::ForegroundColor +Invoke-Expression $expr | ForEach-Object { + if( -not $OneLine ) { return $_ }; + $local:res = $_.Split('|'); + $res = [PSCustomObject]([ordered]@{ + Machine = $res[0].Trim(); + Status = $res[1].Trim(); + RC = "$($res[2])".Trim(); + Output = "$($res[3])".Trim(); + }) + if( $res.Status -match '^\w+!:' ) { + [Console]::ForegroundColor = [ConsoleColor]::Red + } else { + [Console]::ForegroundColor = [ConsoleColor]::Yellow + } + $res +} +[Console]::ForegroundColor = $SaveConsoleColor From 2302343a153b68a318aa5feff7dd7cfc71806bc7 Mon Sep 17 00:00:00 2001 From: lksz Date: Sun, 1 Nov 2020 01:15:34 -0500 Subject: [PATCH 20/30] Get-PlexInfo and txm sz-rsync, not expected to work yet. --- sys.Linux/Get-PlexInfo.ps1 | 12 ++++++++++++ sys.Linux/sz-rsync.ps1 | 6 ++++++ sys.Linux/txm.ps1 | 1 + 3 files changed, 19 insertions(+) create mode 100644 sys.Linux/Get-PlexInfo.ps1 create mode 100644 sys.Linux/sz-rsync.ps1 create mode 100644 sys.Linux/txm.ps1 diff --git a/sys.Linux/Get-PlexInfo.ps1 b/sys.Linux/Get-PlexInfo.ps1 new file mode 100644 index 0000000..1a3b7a1 --- /dev/null +++ b/sys.Linux/Get-PlexInfo.ps1 @@ -0,0 +1,12 @@ +$local:PlexInfo = $(try{([xml](Get-Content /run/plex.stream.counter/sessions -Raw -ErrorAction Stop)).MediaContainer}catch{}) + +$PlexInfo.ChildNodes | ForEach-Object { [PSCustomObject]@{ + Object = $_ + Type = $_.type + Library = $_.librarySectionTitle + Title = $(@($_.grandparentTitle,$_.parentIndex,$_.parentTitle,$_.index,$_.title) | Where-Object {$_}) -join ' | ' + User = $_.User.title + Offset = [TimeSpan]::FromMilliseconds($_.viewOffset).ToString() -split '\.' | select-object -first 1 + Duration = [TimeSpan]::FromMilliseconds($_.duration).ToString() -split '\.' | select-object -first 1 +# UpdateTime = [TimeSpan]::FromMilliseconds($_.).ToString() +} } diff --git a/sys.Linux/sz-rsync.ps1 b/sys.Linux/sz-rsync.ps1 new file mode 100644 index 0000000..6b5cd89 --- /dev/null +++ b/sys.Linux/sz-rsync.ps1 @@ -0,0 +1,6 @@ +#setopt dotglob +$szSrc="'$($args -join "','")'" +$szSrcCount=$(Invoke-ExpressionEx -sudo "& find $szSrc -type f | wc -l ) +Invoke-ExpressionEx -sudo "& rsync --archive --acls --xattrs --human-readable -v $szSrc /szmedia/media/ | pv -lepts $szSrcCount" +#unsetopt dotglob + diff --git a/sys.Linux/txm.ps1 b/sys.Linux/txm.ps1 new file mode 100644 index 0000000..e0f0b55 --- /dev/null +++ b/sys.Linux/txm.ps1 @@ -0,0 +1 @@ +tmux set-option mouse $args From 59a2949268e4f2fa909295fab9748bf582cccb7c Mon Sep 17 00:00:00 2001 From: lksz Date: Sun, 1 Nov 2020 01:19:26 -0500 Subject: [PATCH 21/30] Moved Ansible invocation to sys.Linux --- Invoke-ViaAnsible.ps1 => sys.Linux/Invoke-ViaAnsible.ps1 | 0 Pull-ViaAnsible.ps1 => sys.Linux/Pull-ViaAnsible.ps1 | 0 Update-ViaAnsible.ps1 => sys.Linux/Update-ViaAnsible.ps1 | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Invoke-ViaAnsible.ps1 => sys.Linux/Invoke-ViaAnsible.ps1 (100%) rename Pull-ViaAnsible.ps1 => sys.Linux/Pull-ViaAnsible.ps1 (100%) rename Update-ViaAnsible.ps1 => sys.Linux/Update-ViaAnsible.ps1 (100%) diff --git a/Invoke-ViaAnsible.ps1 b/sys.Linux/Invoke-ViaAnsible.ps1 similarity index 100% rename from Invoke-ViaAnsible.ps1 rename to sys.Linux/Invoke-ViaAnsible.ps1 diff --git a/Pull-ViaAnsible.ps1 b/sys.Linux/Pull-ViaAnsible.ps1 similarity index 100% rename from Pull-ViaAnsible.ps1 rename to sys.Linux/Pull-ViaAnsible.ps1 diff --git a/Update-ViaAnsible.ps1 b/sys.Linux/Update-ViaAnsible.ps1 similarity index 100% rename from Update-ViaAnsible.ps1 rename to sys.Linux/Update-ViaAnsible.ps1 From ac9c5ed35204a23531e99b522a39f12a211de6df Mon Sep 17 00:00:00 2001 From: lksz Date: Wed, 4 Nov 2020 10:58:04 -0500 Subject: [PATCH 22/30] Various additions dps is now an Alias to Get-DockerProcess Get-DockerProcess has been cleaned up and search features added to it. Added FromPowerShellCookbook, which loads a piece of code from the module, but does not load the entire module. MyConfig now includes ansible and tmux configs, also added -sudo switch Get-PlexInfo added, with ability to read directly from Server Invoke-ViaAnsible modified - cleaned up output Added -Force to Edit-DockerCompose dcc modified to read from raw log (which allows filtering by source, and has timestamps) --- Aliases/dps.ps1 | 1 + Edit-DockerCompose.ps1 | 6 +++--- Edit-MyConfig.ps1 | 5 +++-- Get-DockerProcess.ps1 | 24 ++++++++++++++++++++++++ dcc.ps1 | 4 +++- dps.ps1 | 12 ------------ profile.d/FromPowerShellCookbook.ps1 | 21 +++++++++++++++++++++ profile.d/MyConfig.class.ps1 | 1 + sys.Linux/Get-PlexInfo.ps1 | 23 +++++++++++++++++++++-- sys.Linux/Invoke-ViaAnsible.ps1 | 3 +++ 10 files changed, 80 insertions(+), 20 deletions(-) create mode 100644 Aliases/dps.ps1 create mode 100644 Get-DockerProcess.ps1 delete mode 100644 dps.ps1 create mode 100644 profile.d/FromPowerShellCookbook.ps1 diff --git a/Aliases/dps.ps1 b/Aliases/dps.ps1 new file mode 100644 index 0000000..640b880 --- /dev/null +++ b/Aliases/dps.ps1 @@ -0,0 +1 @@ +Get-DockerProcess diff --git a/Edit-DockerCompose.ps1 b/Edit-DockerCompose.ps1 index 9557e54..9d491f4 100644 --- a/Edit-DockerCompose.ps1 +++ b/Edit-DockerCompose.ps1 @@ -1,14 +1,14 @@ -[CmdletBinding(SupportsShouldProcess)]param([string[]]$ProjectPath=@($PWD)) +[CmdletBinding(SupportsShouldProcess)]param([string[]]$ProjectPath=@($PWD),[switch]$Force) $local:editCandidates = @('docker-compose.yml','.base.docker-compose.yml') $local:editFiles = @() foreach( $local:fileName in $EditCandidates ) { foreach( $local:path in $ProjectPath ) { $local:testPath = Join-Path $path $fileName - if( Test-Path $testPath ) { $editFiles += $testPath } + if( $Force -or $(Test-Path $testPath) ) { $editFiles += $testPath } } } Edit-TextFile $editFiles -docker-compose config -q +$editFiles | Select-Object -First 1 | ForEach-Object { docker-compose --file $(Resolve-Path $_) config -q } diff --git a/Edit-MyConfig.ps1 b/Edit-MyConfig.ps1 index 882f5cf..92a098c 100644 --- a/Edit-MyConfig.ps1 +++ b/Edit-MyConfig.ps1 @@ -10,7 +10,8 @@ [MyConfig]::_GetValidValues($wordToComplete,$true) | Sort-Object })] [string[]]$ConfigName, - [switch]$Force + [switch]$Force, + [switch]$sudo ) if( -not $ConfigName ) { ([MyConfig]::_GetValidValues('',$true)) | Sort-Object @@ -18,4 +19,4 @@ if( -not $ConfigName ) { } $local:ScriptPaths = [MyConfig]::GetConfigPaths($ConfigName,$Force) -Edit-TextFile $ScriptPaths +Edit-TextFile -sudo:$sudo $ScriptPaths diff --git a/Get-DockerProcess.ps1 b/Get-DockerProcess.ps1 new file mode 100644 index 0000000..b6f1aa3 --- /dev/null +++ b/Get-DockerProcess.ps1 @@ -0,0 +1,24 @@ +#[CmdletBinding(SupportsShouldProcess)]param( +[CmdletBinding()]param([string[]]$MatchName,[string[]]$OrderBy,[switch]$PassThru,[string[]]$MatchAny) + +$local:result = $(docker ps --format='{{ .Image }}\t{{ .Names }}\t{{ .Status }}\t{{ .Ports }}' | + ForEach-Object { + $local:l = $_ -split '\t'; + [PSCustomObject]([ordered]@{Image=$l[0];Name=$l[1];Status=$l[2];Ports=$l[3] -replace ', ',"`n"}) + } ) | Sort-Object Name + +if( $MatchName ) { + $result = $result | Where-Object Name -match $($MatchName -join '|') +} + +if( $MatchAny ) { + $result = $result | Where-Object { $_ | Out-String | Where-Object { $_ -match $($MatchAny -join '|') } } +} + +if( $OrderBy ) { + $result = $result | Sort-Object $OrderBy +} + +if( $PassThru ) { return $result } +$result | Format-Table -Wrap + diff --git a/dcc.ps1 b/dcc.ps1 index f8a1e1c..6154b3a 100644 --- a/dcc.ps1 +++ b/dcc.ps1 @@ -1 +1,3 @@ -docker-compose config | less +[CmdletBinding(SupportsShouldProcess)]param([string[]]$ProjectPath=@($PWD)) + +$ProjectPath | ForEach-Object { docker-compose --file $(Resolve-Path $(Join-Path $_ docker-compose.yml)) config | less } diff --git a/dps.ps1 b/dps.ps1 deleted file mode 100644 index 85aa8c6..0000000 --- a/dps.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -#[CmdletBinding(SupportsShouldProcess)]param( -[CmdletBinding()]param([string[]]$OrderBy,[switch]$PassThru) - -$local:result = $(docker ps --format='{{ .Image }}\t{{ .Names }}\t{{ .Status }}\t{{ .Ports }}' | ForEach-Object { $local:l = $_ -split '\t'; [PSCustomObject](@{Image=$l[0];Names=$l[1];Status=$l[2];Ports=$l[3] -replace ', '," -"}) } ) | Sort-Object Names - -if( $OrderBy ) { - $result = $result | Sort-Object $OrderBy -} - -if( $PassThru ) { return $result } -$result | Format-Table -Wrap -Property Image,Names,Status,Ports diff --git a/profile.d/FromPowerShellCookbook.ps1 b/profile.d/FromPowerShellCookbook.ps1 new file mode 100644 index 0000000..a9e7f42 --- /dev/null +++ b/profile.d/FromPowerShellCookbook.ps1 @@ -0,0 +1,21 @@ +# PowerShell Cookbook has a lot of code there, I'm only interested in +# the Add-ObjectCollector which adds an overloaded Out-Default version, +# which stores a history of output objects. +# One major problem with loading this from the module, is that when the +# module is removed the shell BREAKS. +# +# The code below, makes sure the module is removed, and then imports +# only the Add-ObjectCollector code from it. +# All I really want is the Out-Default function created by +# Add-ObjectCollector, and so, I'll also remove the function once done. + +if( Get-Module PowerShellCookbook ) { + Remove-Module PowerShellCookbook + + Import-Module PowerShellCookbook -Cmdlet Add-ObjectCollector +} +# +. Get-Command Add-ObjectCollector SilentlyContinue | ForEach-Object { + Add-ObjectCollector + Get-Item function:/Add-ObjectCollector | Remove-Item +} diff --git a/profile.d/MyConfig.class.ps1 b/profile.d/MyConfig.class.ps1 index eb4a92f..fed67a7 100644 --- a/profile.d/MyConfig.class.ps1 +++ b/profile.d/MyConfig.class.ps1 @@ -12,6 +12,7 @@ class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { 'sz-shrc' = '~/.sz.shrc.sh' 'sz-rc-all' = '#sz-aliases-sh', '#sz-local-rc', '#sz-shrc', '#sz-zshrc', '#zshrc' 'tmux' = '~/.tmux.conf', '~/.byobu/.tmux.conf' + 'ansible' = '/etc/ansible/ansible.cfg', '/opt/ansible/ansible.cfg' } } static [string[]] GetConfigPaths([string[]]$ConfigNames,[switch]$Force) { diff --git a/sys.Linux/Get-PlexInfo.ps1 b/sys.Linux/Get-PlexInfo.ps1 index 1a3b7a1..f679500 100644 --- a/sys.Linux/Get-PlexInfo.ps1 +++ b/sys.Linux/Get-PlexInfo.ps1 @@ -1,6 +1,21 @@ -$local:PlexInfo = $(try{([xml](Get-Content /run/plex.stream.counter/sessions -Raw -ErrorAction Stop)).MediaContainer}catch{}) +param([switch]$FetchFromServer,[string]$PlexHost='localhost',[switch]$PassThruOnly) -$PlexInfo.ChildNodes | ForEach-Object { [PSCustomObject]@{ +$local:content = $(try{(Get-Content /run/plex.stream.counter/sessions -Raw -ErrorAction Stop)}catch{}) + +if( $FetchFromServer ) { + $local:creds = New-Object System.Management.Automation.PsCredential($env:PLEX_USERNAME,$(ConvertTo-SecureString -AsPlainText $env:PLEX_PASSWORD -Force)) + $local:webResp = Invoke-WebRequest -Headers @{ "Content-Length" = "0"; "X-Plex-Client-Identifier" = "my-app" } -Credential $creds -Method Post -Uri "https://my.plexapp.com/users/sign_in.xml" + $local:plexHeaders = @{ "X-Plex-Token" = ([xml]$webResp.Content).user.authenticationToken } + $webResp = Invoke-WebRequest -Headers $plexHeaders "http://${PlexHost}:32400" + $local:plexVersion = ([xml]$webResp.Content).MediaContainer.version + Write-Host -ForegroundColor Cyan "Plex Version: $plexVersion" + $webResp = Invoke-WebRequest -Headers $plexHeaders "http://${PlexHost}:32400/status/sessions" + $content = $webResp.Content +} + +$local:PlexInfo = $(try{([xml]$content).MediaContainer}catch{}) + +$local:result = $PlexInfo.ChildNodes | ForEach-Object { [PSCustomObject]@{ Object = $_ Type = $_.type Library = $_.librarySectionTitle @@ -8,5 +23,9 @@ $PlexInfo.ChildNodes | ForEach-Object { [PSCustomObject]@{ User = $_.User.title Offset = [TimeSpan]::FromMilliseconds($_.viewOffset).ToString() -split '\.' | select-object -first 1 Duration = [TimeSpan]::FromMilliseconds($_.duration).ToString() -split '\.' | select-object -first 1 + Player = "$($_.Player.Platform)|$($_.Player.State)" # UpdateTime = [TimeSpan]::FromMilliseconds($_.).ToString() } } + +if( $PassThruOnly ) { return $result } +$result | Format-Table diff --git a/sys.Linux/Invoke-ViaAnsible.ps1 b/sys.Linux/Invoke-ViaAnsible.ps1 index 3e5c8ce..242ecdc 100644 --- a/sys.Linux/Invoke-ViaAnsible.ps1 +++ b/sys.Linux/Invoke-ViaAnsible.ps1 @@ -11,6 +11,8 @@ if( (Test-Path './ansible.cfg') -or (Test-Path '/opt/ansible/hosts') -and (Test- $ansible_cli += '-i', '/opt/ansible/hosts', '--private-key=/opt/ansible/ssh_key_for_ansible' } if( $Command ) { + $ansible_cli += '-a' + $ansible_cli += 'ANSIBLE_PYTHON_INTERPRETER=auto_silent ' $ansible_cli += '-a' if( $NotPowerShell ) { $ansible_cli += $(($Command -join '; ').Replace("'","\`$(printf '\x27')").Replace('"',"\`$(printf '\x22')")) @@ -27,6 +29,7 @@ $ansible_cli += $MoreArgs $local:expr = $('& "'+$($ansible_cli -join '" "')+'"') Write-Verbose $expr $local:SaveConsoleColor = [Console]::ForegroundColor +$env:ANSIBLE_DEPRECATION_WARNINGS='false' Invoke-Expression $expr | ForEach-Object { if( -not $OneLine ) { return $_ }; $local:res = $_.Split('|'); From d85aec0480328c4de032e34fad7b67151ead30ed Mon Sep 17 00:00:00 2001 From: Gal Szkolnik Date: Wed, 4 Nov 2020 11:45:53 -0500 Subject: [PATCH 23/30] Fixed a bug in FromPowerShellCookbook --- Aliases/nvim | 1 - profile.d/FromPowerShellCookbook.ps1 | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) delete mode 100644 Aliases/nvim diff --git a/Aliases/nvim b/Aliases/nvim deleted file mode 100644 index e099b51..0000000 --- a/Aliases/nvim +++ /dev/null @@ -1 +0,0 @@ -Edit-TextFile diff --git a/profile.d/FromPowerShellCookbook.ps1 b/profile.d/FromPowerShellCookbook.ps1 index a9e7f42..75018ca 100644 --- a/profile.d/FromPowerShellCookbook.ps1 +++ b/profile.d/FromPowerShellCookbook.ps1 @@ -15,7 +15,7 @@ if( Get-Module PowerShellCookbook ) { Import-Module PowerShellCookbook -Cmdlet Add-ObjectCollector } # -. Get-Command Add-ObjectCollector SilentlyContinue | ForEach-Object { +. Get-Command Add-ObjectCollector -ErrorAction SilentlyContinue | ForEach-Object { Add-ObjectCollector Get-Item function:/Add-ObjectCollector | Remove-Item } From 524bce25ded92d53eb26cda69d16abdf9595e6bb Mon Sep 17 00:00:00 2001 From: lksz Date: Wed, 4 Nov 2020 23:31:34 -0500 Subject: [PATCH 24/30] MyConfig modifications Moved configuration into src/config.files.json, it will also load src/config.files.local.json (which will not be included in the git repo) Added Git-Path to resolve paths simply, even when Path does not exist. --- Edit-MyConfig.ps1 | 2 ++ Get-Path.ps1 | 8 ++++++++ profile.d/MyConfig.class.ps1 | 38 +++++++++++++++++------------------- src/config.files.json | 37 +++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 20 deletions(-) create mode 100644 Get-Path.ps1 create mode 100644 src/config.files.json diff --git a/Edit-MyConfig.ps1 b/Edit-MyConfig.ps1 index 92a098c..1204eef 100644 --- a/Edit-MyConfig.ps1 +++ b/Edit-MyConfig.ps1 @@ -20,3 +20,5 @@ if( -not $ConfigName ) { $local:ScriptPaths = [MyConfig]::GetConfigPaths($ConfigName,$Force) Edit-TextFile -sudo:$sudo $ScriptPaths + +$null = [MyConfig]::_GetValidValues('', $true) diff --git a/Get-Path.ps1 b/Get-Path.ps1 new file mode 100644 index 0000000..7dccf1f --- /dev/null +++ b/Get-Path.ps1 @@ -0,0 +1,8 @@ +[CmdletBinding()]param([string]$Path) + +try { + get-item $Path -Force -ErrorAction Stop | + Select-Object -ExpandProperty FullName +} catch { + $_.targetObject +} diff --git a/profile.d/MyConfig.class.ps1 b/profile.d/MyConfig.class.ps1 index fed67a7..28d7b2e 100644 --- a/profile.d/MyConfig.class.ps1 +++ b/profile.d/MyConfig.class.ps1 @@ -1,28 +1,27 @@ class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { - static [hashtable]$configDirectory = @{}; - static ReloadConfigPaths() { - [MyConfig]::ConfigDirectory = [ordered]@{ - 'vi' = '~/.virc' - 'vim' = '~/.vimrc','~/.vim/vimrc' - 'neovim' = '~/.config/nvim/init.vim','~/.config/nvim/vim-plug/plugins.vim','#vim','#vi' - 'zshrc' = '~/.zshrc' - 'sz-zshrc' = '~/.sz.zshrc.sh', '#zshrc' - 'sz-local-rc' = '~/.sz.local.sh' - 'sz-aliases-sh' = '~/.sz.aliases.sh' - 'sz-shrc' = '~/.sz.shrc.sh' - 'sz-rc-all' = '#sz-aliases-sh', '#sz-local-rc', '#sz-shrc', '#sz-zshrc', '#zshrc' - 'tmux' = '~/.tmux.conf', '~/.byobu/.tmux.conf' - 'ansible' = '/etc/ansible/ansible.cfg', '/opt/ansible/ansible.cfg' + hidden static [string[]]$_MyConfigDictionaryPath = @( + $(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.json'), + $(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.local.json') + ) + static [hashtable]GetConfigDictionary() { + $local:result = @{} + $result['myconfig'] = [MyConfig]::_MyConfigDictionaryPath; + foreach( $local:jsonSource in [MyConfig]::_MyConfigDictionaryPath ) { + if( -not ( Test-Path $jsonSource ) ) { continue } + foreach( $local:prop in $(Get-Content $jsonSource | ConvertFrom-Json).PSObject.Properties ) { + $result[$prop.Name] = $prop.Value + } } + return $result; } static [string[]] GetConfigPaths([string[]]$ConfigNames,[switch]$Force) { - [MyConfig]::ReloadConfigPaths() + $local:configDirectory = [MyConfig]::GetConfigDictionary() $local:result = [string[]]@() $local:flat = $false while(-not $flat) { $flat = $true $ConfigNames += $ConfigNames | ForEach-Object { - [MyConfig]::configDirectory[$_] + $configDirectory[$_] } | Where-Object { $_ -match '^#[\w-\.]+$' } | ForEach-Object { $_.Substring(1) } | Where-Object { $_ -notin $ConfigNames } | ForEach-Object { @@ -31,7 +30,7 @@ class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { } $local:flatConfigList = $ConfigNames | ForEach-Object { - [MyConfig]::configDirectory[$_] + $configDirectory[$_] } | Where-Object { $_ -notmatch '^#[\w-\.]+$' } $local:exists = $false; @@ -39,7 +38,7 @@ class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { foreach( $local:configPath in $flatConfigList ) { if( -not $first ) { $first = $configPath } if( $Force -or (Test-Path $configPath) ) { - $result += Resolve-Path $configPath + $result += Get-Path $configPath $exists = $true } } @@ -49,8 +48,7 @@ class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { return $result } static [string[]] _GetValidValues([string]$wordToComplete,[bool]$Strict) { - [MyConfig]::ReloadConfigPaths() - $local:possibleValues = [MyConfig]::configDirectory.Keys + $local:possibleValues = [MyConfig]::GetConfigDictionary().Keys return $(Get-PossibleArguments -WordToComplete $wordToComplete -FullValueSet $possibleValues -Strict:$Strict ); } diff --git a/src/config.files.json b/src/config.files.json new file mode 100644 index 0000000..7cdc1ac --- /dev/null +++ b/src/config.files.json @@ -0,0 +1,37 @@ +{ + "neovim": [ + "~/.config/nvim/init.vim", + "~/.config/nvim/vim-plug/plugins.vim", + "#vim", + "#vi" + ], + "sz-shrc": "~/.sz.shrc.sh", + "sz-rc-all": [ + "#sz-aliases-sh", + "#sz-local-rc", + "#sz-shrc", + "#sz-zshrc", + "#zshrc" + ], + "vi": "~/.virc", + "sz-local-rc": "~/.sz.local.sh", + "zshrc": "~/.zshrc", + "ansible": [ + "/etc/ansible/ansible.cfg", + "/opt/ansible/ansible.cfg", + "/opt/ansible/hosts" + ], + "sz-aliases-sh": "~/.sz.aliases.sh", + "vim": [ + "~/.vimrc", + "~/.vim/vimrc" + ], + "sz-zshrc": [ + "~/.sz.zshrc.sh", + "#zshrc" + ], + "tmux": [ + "~/.tmux.conf", + "~/.byobu/.tmux.conf" + ] +} From f00e9090a52d0956211b6f85b5e2b5a0a069bccd Mon Sep 17 00:00:00 2001 From: lksz Date: Wed, 4 Nov 2020 23:42:17 -0500 Subject: [PATCH 25/30] Added ssh configuration to MyConfig Added files to config.files.json file --- src/config.files.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/config.files.json b/src/config.files.json index 7cdc1ac..a11b946 100644 --- a/src/config.files.json +++ b/src/config.files.json @@ -33,5 +33,10 @@ "tmux": [ "~/.tmux.conf", "~/.byobu/.tmux.conf" - ] + ], + "ssh-pub": "~/.ssh/id_*.pub", + "ssh-id": ["~/.ssh/id_ed25519","~/.ssh/id_rsa"], + "ssh-auth": "~/.ssh/authorized_keys", + "ssh-conf": "/etc/ssh/sshd_config", + "ssh" : [ "#ssh-auth", "#ssh-conf", "#ssh-pub", "#ssh-id" ] } From baa3ccd04d8e1b71f664c828e65269a22f50dad3 Mon Sep 17 00:00:00 2001 From: Gal Szkolnik Date: Thu, 5 Nov 2020 00:00:18 -0500 Subject: [PATCH 26/30] Updated MyConfig code to include modules This is a prep for MyModules, a way to notify users that a module installation is recommended for the features of the scripting environment --- profile.d/MyConfig.class.ps1 | 15 +++++++++------ src/modules.json | 7 +++++++ 2 files changed, 16 insertions(+), 6 deletions(-) create mode 100644 src/modules.json diff --git a/profile.d/MyConfig.class.ps1 b/profile.d/MyConfig.class.ps1 index 28d7b2e..4e7c457 100644 --- a/profile.d/MyConfig.class.ps1 +++ b/profile.d/MyConfig.class.ps1 @@ -1,12 +1,15 @@ class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator { - hidden static [string[]]$_MyConfigDictionaryPath = @( - $(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.json'), - $(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.local.json') - ) + hidden static [hashtable]$_HardCodedConfigDict = @{ + 'myconfig' = @($(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.json'), + $(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.local.json')) + 'mymodules' = @($(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'modules.json'), + $(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'modules.local.json')) + } + static [hashtable]GetConfigDictionary() { $local:result = @{} - $result['myconfig'] = [MyConfig]::_MyConfigDictionaryPath; - foreach( $local:jsonSource in [MyConfig]::_MyConfigDictionaryPath ) { + [MyConfig]::_HardCodedConfigDict.Keys | ForEach-Object { $result[$_] = [MyConfig]::_HardCodedConfigDict[$_] } + foreach( $local:jsonSource in $result.myconfig ) { if( -not ( Test-Path $jsonSource ) ) { continue } foreach( $local:prop in $(Get-Content $jsonSource | ConvertFrom-Json).PSObject.Properties ) { $result[$prop.Name] = $prop.Value diff --git a/src/modules.json b/src/modules.json new file mode 100644 index 0000000..2bd93a2 --- /dev/null +++ b/src/modules.json @@ -0,0 +1,7 @@ +{ + "Modules": [ + "Microsoft.PowerShell.UnixCompleters", + "oh-my-posh", + "posh-git" + ] +} From 0d5522b8c707d73e04c30fc559f75e4fe28abbd3 Mon Sep 17 00:00:00 2001 From: lksz Date: Thu, 5 Nov 2020 00:08:59 -0500 Subject: [PATCH 27/30] test-modules startup script draft --- profile.d/test-modules.ps1 | 1 + src/modules.json | 1 + 2 files changed, 2 insertions(+) create mode 100644 profile.d/test-modules.ps1 diff --git a/profile.d/test-modules.ps1 b/profile.d/test-modules.ps1 new file mode 100644 index 0000000..d3adfc5 --- /dev/null +++ b/profile.d/test-modules.ps1 @@ -0,0 +1 @@ +$(Get-Content $MyPSScriptRoot/src/modules.json | ConvertFrom-Json).Modules | Where-Object { try{-not (Get-Module -ListAvailable $_aaa -ErrorAction stop) }catch{} } | ForEach-Object { Write-Warning "Missing module: $_" } diff --git a/src/modules.json b/src/modules.json index 2bd93a2..d375d21 100644 --- a/src/modules.json +++ b/src/modules.json @@ -1,6 +1,7 @@ { "Modules": [ "Microsoft.PowerShell.UnixCompleters", + "PowerShellCookbook", "oh-my-posh", "posh-git" ] From 7dd40b7b82d1c73d99e6e4849413aa98d43b2602 Mon Sep 17 00:00:00 2001 From: Gal Date: Thu, 5 Nov 2020 00:29:04 -0500 Subject: [PATCH 28/30] Test-MyModules finalized, ready for work Future imporvement will allow prompting for installation or a command to automate following recommendations. --- profile.d/Test-MyModules.ps1 | 18 ++++++++++++++++++ profile.d/test-modules.ps1 | 1 - 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 profile.d/Test-MyModules.ps1 delete mode 100644 profile.d/test-modules.ps1 diff --git a/profile.d/Test-MyModules.ps1 b/profile.d/Test-MyModules.ps1 new file mode 100644 index 0000000..c8d7e9b --- /dev/null +++ b/profile.d/Test-MyModules.ps1 @@ -0,0 +1,18 @@ +if( -not $global:MyModulesWarning ) { + $global:MyModulesWarning = @() +} +[MyConfig]::GetConfigPaths('mymodules',$false) | + ForEach-Object { + $( Get-Content $_ | ConvertFrom-Json ).Modules + } | Where-Object { + $local:m = $_ + if( $( try { + -not (Get-Module -ListAvailable $m -ErrorAction stop) + } catch { $true } + )) { + $m -notin $global:MyModulesWarning + } + } | ForEach-Object { + $global:MyModulesWarning += $_ + Write-Warning "Missing module: $_" + } diff --git a/profile.d/test-modules.ps1 b/profile.d/test-modules.ps1 deleted file mode 100644 index d3adfc5..0000000 --- a/profile.d/test-modules.ps1 +++ /dev/null @@ -1 +0,0 @@ -$(Get-Content $MyPSScriptRoot/src/modules.json | ConvertFrom-Json).Modules | Where-Object { try{-not (Get-Module -ListAvailable $_aaa -ErrorAction stop) }catch{} } | ForEach-Object { Write-Warning "Missing module: $_" } From 8566ea68630163a2740dd50ede635dd2d0a59b23 Mon Sep 17 00:00:00 2001 From: Gal Szkolnik Date: Mon, 9 Nov 2020 13:06:17 -0500 Subject: [PATCH 29/30] Better cross platform support Edit-MyScript will pause if edit is running in background (conext returning less than a second after launching editor) Test-MyModules which loads at stratup now has specific platform lists --- Edit-MyScript.ps1 | 6 ++++++ profile.d/Test-MyModules.ps1 | 12 +++++++++--- src/modules.json | 12 +++++++++--- Update-ArchOSz.ps1 => sys.Linux/Update-ArchOSz.ps1 | 0 Update-OSz.ps1 => sys.Linux/Update-OSz.ps1 | 0 .../Update-UbuntuOSz.ps1 | 0 6 files changed, 24 insertions(+), 6 deletions(-) rename Update-ArchOSz.ps1 => sys.Linux/Update-ArchOSz.ps1 (100%) rename Update-OSz.ps1 => sys.Linux/Update-OSz.ps1 (100%) rename Update-UbuntuOSz.ps1 => sys.Linux/Update-UbuntuOSz.ps1 (100%) diff --git a/Edit-MyScript.ps1 b/Edit-MyScript.ps1 index a3e57ba..50cf3b0 100644 --- a/Edit-MyScript.ps1 +++ b/Edit-MyScript.ps1 @@ -71,7 +71,13 @@ foreach( $local:p in $ScriptPaths ) { } } +$local:sw = [System.Diagnostics.Stopwatch]::StartNew(); Edit-TextFile $ScriptPaths +$sw.Stop(); + +if( $sw.Elapsed.TotalSeconds -lt 1 ) { + $null = Read-Host "Waiting before refreshing. Press when you're done editing ( don't forget to save ;) )..." +} Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $_.Definition } diff --git a/profile.d/Test-MyModules.ps1 b/profile.d/Test-MyModules.ps1 index c8d7e9b..7ac05fc 100644 --- a/profile.d/Test-MyModules.ps1 +++ b/profile.d/Test-MyModules.ps1 @@ -1,9 +1,15 @@ -if( -not $global:MyModulesWarning ) { +param([switch]$Force) + +$local:currentSys = [SystemName]::_GetValidValues('',$true,$true); + +if( -not $global:MyModulesWarning -or $Force ) { $global:MyModulesWarning = @() } [MyConfig]::GetConfigPaths('mymodules',$false) | ForEach-Object { - $( Get-Content $_ | ConvertFrom-Json ).Modules + $local:modules = $( Get-Content $_ | ConvertFrom-Json ); + $modules.Always; + $currentSys | ForEach-Object { $modules."$_" } | Where-Object { $_} } | Where-Object { $local:m = $_ if( $( try { @@ -15,4 +21,4 @@ if( -not $global:MyModulesWarning ) { } | ForEach-Object { $global:MyModulesWarning += $_ Write-Warning "Missing module: $_" - } + } \ No newline at end of file diff --git a/src/modules.json b/src/modules.json index d375d21..4c33ec3 100644 --- a/src/modules.json +++ b/src/modules.json @@ -1,8 +1,14 @@ { - "Modules": [ - "Microsoft.PowerShell.UnixCompleters", + "Always": [ "PowerShellCookbook", "oh-my-posh", - "posh-git" + "posh-git", + "z" + ], + "Desktop": [ + ], + "Unix": [ + "Microsoft.PowerShell.UnixCompleters" ] + } diff --git a/Update-ArchOSz.ps1 b/sys.Linux/Update-ArchOSz.ps1 similarity index 100% rename from Update-ArchOSz.ps1 rename to sys.Linux/Update-ArchOSz.ps1 diff --git a/Update-OSz.ps1 b/sys.Linux/Update-OSz.ps1 similarity index 100% rename from Update-OSz.ps1 rename to sys.Linux/Update-OSz.ps1 diff --git a/Update-UbuntuOSz.ps1 b/sys.Linux/Update-UbuntuOSz.ps1 similarity index 100% rename from Update-UbuntuOSz.ps1 rename to sys.Linux/Update-UbuntuOSz.ps1 From 38dab59d62ea1a97517575ca28f470983d465726 Mon Sep 17 00:00:00 2001 From: Gal Szkolnik Date: Mon, 9 Nov 2020 13:16:09 -0500 Subject: [PATCH 30/30] Make sure Z is loaded if it exists --- profile.d/load-z.ps1 | 1 + 1 file changed, 1 insertion(+) create mode 100644 profile.d/load-z.ps1 diff --git a/profile.d/load-z.ps1 b/profile.d/load-z.ps1 new file mode 100644 index 0000000..45cd02b --- /dev/null +++ b/profile.d/load-z.ps1 @@ -0,0 +1 @@ +Get-Module -ListAvailable z | Import-Module \ No newline at end of file