-
Notifications
You must be signed in to change notification settings - Fork 1
/
profileTools.psm1
446 lines (389 loc) · 14.5 KB
/
profileTools.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
################# Profile By BarNuri #################
# author : ✡ BarNuri ✡
# git: https://github.com/barnuri/powershell-utils
# symbols - https://coolsymbol.com/
# PSReadLine - https://docs.microsoft.com/en-us/powershell/module/psreadline/set-psreadlinekeyhandler?view=powershell-7.2
$parentDir = $(Split-Path $profile)
$profileTools = Join-Path -Path $parentDir -ChildPath "profileTools.psm1"
function profileTools() {
echo $profileTools
}
function syncPowershellUtils() {
mkdir -p (Split-Path -Path $profile -Parent) -errorAction SilentlyContinue
$newProfileContent = $(Invoke-WebRequest https://raw.githubusercontent.com/barnuri/powershell-utils/master/profileTools.psm1?noCache=$((Get-Date).ToString())).Content
echo $newProfileContent > $profileTools
$installString = "### load profileTools.psm1"
$importModuleExists = Select-String -Quiet -Pattern $installString -Path $profile
if (-not $importModuleExists)
{
echo $installString >> $profile
echo "`$SaveVerbosePreference = `$global:VerbosePreference;" >> $profile
echo "`$global:VerbosePreference = 'SilentlyContinue';" >> $profile
echo "Import-Module $profileTools -Force -DisableNameChecking" >> $profile
echo "`$global:VerbosePreference = `$SaveVerbosePreference;" >> $profile
}
$SaveVerbosePreference = $global:VerbosePreference;
$global:VerbosePreference = 'SilentlyContinue';
Import-Module $profileTools -Force -DisableNameChecking
$global:VerbosePreference = $SaveVerbosePreference;
}
function reloadProfile() {
. $profile
$SaveVerbosePreference = $global:VerbosePreference;
$global:VerbosePreference = 'SilentlyContinue';
Import-Module $profileTools -Force -DisableNameChecking
$global:VerbosePreference = $SaveVerbosePreference;
}
function colorString($str, $color) {
$colorNum = 37
$color = "$color".ToLower()
if ($color -eq "black") {
$colorNum = 30
}
if ($color -eq "red") {
$colorNum = 31
}
if ($color -eq "green") {
$colorNum = 32
}
if ($color -eq "yellow") {
$colorNum = 33
}
if ($color -eq "blue") {
$colorNum = 34
}
if ($color -eq "magenta") {
$colorNum = 35
}
if ($color -eq "cyan") {
$colorNum = 36
}
if ($color -eq "white") {
$colorNum = 37
}
return "`e[$($colorNum)m$str`e[0m"
}
function gitStatus() {
if (!(Test-Path -Path ".git")) {
return
}
$status=$(git status --short --ahead-behind --branch -uno)
$lines=$status.Replace("`r","").Split("`n")
$firstLine, $statusLines = $lines
$statusLines += ""
$firstLine -match '## (.+)' | out-null
$isRemoteBranch = $Matches[1].Split("...").Count -gt 1
$branch=$Matches[1].Split("...")[0]
'' -match '' | out-null # reset regex result
$firstLine -match '\[(?:.*)?(?:behind (\d+))\]' | out-null
$behind=$($Matches[1] ?? 0)
'' -match '' | out-null # reset regex result
$firstLine -match '\[(?:ahead (\d+)).*\]' | out-null
$ahead=$($Matches[1] ?? 0)
'' -match '' | out-null # reset regex result
$output = ""
$output += colorString " [" Yellow
$output += colorString "$branch" Cyan
$statusLines = $statusLines | foreach { $_.Trim() }
$deleted=$($statusLines | where { $_.StartsWith("D ") }).Count
$modify=$($statusLines | where { $_.StartsWith("M ") -OR $_.StartsWith("T ") -OR $_.StartsWith("R ") -OR $_.StartsWith("C ") }).Count
$new=$($statusLines | where { $_.StartsWith("A ") }).Count
$new=$new+$($statusLines | where { $_.StartsWith("?? ") }).Count + $($statusLines | where { $_.StartsWith("? ") }).Count
$mergeConflicts=$($statusLines | where {
$_.StartsWith("UU ") -OR
$_.StartsWith("U ") -OR
$_.StartsWith("AA ") -OR
$_.StartsWith("DD ") -OR
$_.StartsWith("AU ") -OR
$_.StartsWith("UD ") -OR
$_.StartsWith("UA ") -OR
$_.StartsWith("DU ")
}).Count
if(!($isRemoteBranch)) {
$output += colorString " ☁ ↑" yellow
}
if ($isRemoteBranch -and $behind -eq 0 -and $ahead -eq 0 -and $new -eq 0 -and $modify -eq 0 -and $deleted -eq 0 -and $mergeConflicts -eq 0) {
$output += colorString " =" Cyan
} else {
$output += colorString " ↓$behind " Red
$output += colorString "↑$ahead " Cyan
if ($new -ne 0 -or $modify -ne 0 -or $deleted -ne 0) {
$output += colorString "+$new " Green
$output += colorString "±$modify " Cyan
$output += colorString "-$deleted" Red
}
if ($mergeConflicts -ne 0) {
$output += colorString " !$mergeConflicts" Magenta
}
}
$output += colorString "]" Yellow
return $output
}
function prompt {
$host.ui.RawUI.WindowTitle = "Current Folder: $pwd"
$CmdPromptUser = [Security.Principal.WindowsIdentity]::GetCurrent();
$IsAdmin = (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
Write-Host ($(if ($IsAdmin) { '[Admin]' } else { '' })) -BackgroundColor DarkBlue -ForegroundColor White -NoNewline
Write-Host " $($CmdPromptUser.Name.split("\")[1]) " -BackgroundColor DarkBlue -ForegroundColor White -NoNewline
Write-Host " $pwd" -NoNewline
if ($env:DISABLE_GIT -ne "true") {
Write-Host $(gitStatus) -NoNewline
}
return " > "
}
function gitDisableGitPrompt() {
$env:DISABLE_GIT = "true"
}
Import-Module PSReadLine
Set-PSReadLineOption -Colors @{ InlinePrediction = '#9CA3AF'}
Set-PSReadLineOption -EditMode Windows
Set-PSReadLineOption -PredictionSource HistoryAndPlugin
Set-PSReadlineOption -PredictionViewStyle InlineView
(Get-PSReadLineOption).ShowToolTips = $True
(Get-PSReadLineOption).HistoryNoDuplicates = $True
Set-PSReadlineKeyHandler -Key Ctrl+Spacebar -Function MenuComplete
Set-PSReadlineKeyHandler -Key Tab -Function AcceptNextSuggestionWord
Set-Alias ll dir
############# k8s
Set-Alias k kubectl
function kconf { kubectl config view --raw --flatten --minify }
function kall($appName='') { kubectl get deploy,svc,ingress,pod $appName }
function klog($search) { kubectl logs --tail=100000 -f -l $search }
function klogs($search) { klog $search }
############# ssh
function sshKeyFunc { cat $home\.ssh\id_rsa.pub }
Set-Alias sshkey sshKeyFunc
############# python
function p3venv() { python3 -m virtualenv venv }
function p2venv() { python2 -m virtualenv venv }
# pip install
function pipi() {
python -m pip install --upgrade pip;
pip install --upgrade -r REQUIREMENTS
}
# pip install package
function pipp() {
python -m pip install --upgrade pip;
pip install .
}
############# git
function gitRemoveMergedBranches { git branch --merged | ForEach-Object { $_.Trim() } | Where-Object {$_ -NotMatch "^\*"} | Where-Object {-not ( $_ -Like "*master" )} | ForEach-Object { git branch -d $_ } }
function getAllBranches() { git branch -a -l --format "%(refname:short)" | ForEach-Object { $_.Split("/")[-1] } | Where-Object { $_ -ne "HEAD" } }
function gitCleanLocalBranches() {
git fetch --all --prune ;
git branch -l --format "%(refname:short)" | ForEach-Object { git branch $_.Trim() -D }
}
function gitCleanIgnoreFiles() { git clean -dfx }
# Class BranchesNames : System.Management.Automation.IValidateSetValuesGenerator {
# [String[]] GetValidValues() {
# $BranchesNames = $(getAllBranches)
# return [String[]] $BranchesNames
# }
# }
function gitMergeTo(
#[ValidateSet([BranchesNames])]
$targetBranchName='integration') {
$currentBranch = $(git branch --show-current)
git checkout $targetBranchName;
git pull --no-edit;
git merge -X ignore-all-space --no-ff $currentBranch ;
git push ;
git checkout $currentBranch ;
}
Set-Alias gitmt gitMergeTo
function gitc(
#[ValidateSet([BranchesNames])]
$branchName='master') {
git checkout $branchName;
git pull --no-edit;
}
# git new branch
function gitnb($branchName) { git checkout -b $branchName; }
# git new branch from master
function gitnbm($branchName) {
git fetch origin master ;
git checkout origin/master ;
gitnb $branchName
}
# git merge
function gitm(
#[ValidateSet([BranchesNames])]
$branchName='master') {
git fetch origin $branchName;
git pull --no-edit;
git merge -X ignore-all-space --no-ff origin/$branchName
}
function gitMoveToHttps() {
$url=$(git remote get-url origin)
if ($url.startsWith("http")) {
return
}
$moveToHttp = $url.replace(":","/").replace("git@","https://")
git remote set-url origin $moveToHttp
}
function gitMoveToSSH() {
$url=$(git remote get-url origin)
if ($url.startsWith("git@")) {
return
}
$baseUrl, $path = $url.replace("https://","git@").replace("http://","git@").split("/")
$path = $path -join "/"
$moveToSsh = "$($baseUrl):$($path)"
git remote set-url origin $moveToSsh
}
function gitDiff(
#[ValidateSet([BranchesNames])]
$branchName='master') {
git fetch origin $branchName;
git diff origin/$branchName...$(git branch --show-current) --name-status
}
function gitCheckoutFile(
#[ValidateSet([BranchesNames])]
$branchName) {
git fetch origin $branchName;
git checkout origin/$branchName -- $args
}
function gitCheckoutFileFromMaster() {
git fetch origin master;
git checkout origin/master -- $args
}
function gitCleanCommitsIntoOne() {
$msg = "$args"
$currentBranchName = $(git name-rev --name-only HEAD)
if ($msg -eq "") {
$msg = "$currentBranchName"
}
git fetch origin master;
git reset $(git merge-base origin/master $(git branch --show-current));
git add -A;
git commit -m "$msg";
git push -f;
}
function gitCleanCommitsIntoOneWithoutCommit() {
$msg = "$args"
$currentBranchName = $(git name-rev --name-only HEAD)
if ($msg -eq "") {
$msg = "$currentBranchName"
}
git fetch origin master;
git reset $(git merge-base origin/master $(git branch --show-current));
}
# git commit & push
function gitCommitAndPush() {
$msg = "$args"
$currentBranchName = $(git name-rev --name-only HEAD)
$IsRemoteBranch=[bool]$(git config branch.$($currentBranchName).merge)
if ($msg -eq "") {
$msg = "$currentBranchName"
}
if(!$IsRemoteBranch) {
git push --set-upstream origin $currentBranchName;
}
git add .;
git commit -am $msg;
git pull --no-edit;
git push;
}
Set-Alias gitp gitCommitAndPush
function linkFromPushOutput($output) {
echo $output
if($output.Contains("Create a pull request") -and $output -match "remote:\s*(http.*)") {
Write-Output "`e[36m$($Matches[1])`e[0m"
}
'' -match '' | out-null # reset regex result
}
function gitOriginUrl() {
$repoUrl = $(git config --get remote.origin.url)
if($repoUrl.StartsWith("git@")) {
$repoUrl = $repoUrl.SubString(4)
}
$repoUrl = $repoUrl.Replace(":","/")
if($repoUrl.EndsWith(".git")) {
$repoUrl = $repoUrl.SubString(0, $repoUrl.Length - 4)
}
if(!$repoUrl.StartsWith("http")) {
$repoUrl = "https://$repoUrl"
}
$repoUrl = $repoUrl.Trim("/")
echo "$repoUrl"
}
function gitEmptyCommit($msg = "empty commit - trigger status checks") {
git commit --allow-empty -m "$msg";
git pull --no-edit;
git push;
}
function gitSpeedUp() {
$env:GIT_ASK_YESNO="false" ;
git fsck ;
git repack -ad ;
git gc --aggressive --prune=now --force ;
git status ;
}
# dotnet
function dotnetBuildOnlyErrors() {
dotnet build -clp:ErrorsOnly $args
}
Set-Alias dotnetBuild dotnetBuildOnlyErrors
function dotnetTestOnlyErrors() {
dotnet test -clp:ErrorsOnly $args
}
Set-Alias dotnetTest dotnetTestOnlyErrors
function dotnetRestoreOnlyErrors() {
dotnet restore $args 2>&1
}
Set-Alias dotnetRestore dotnetRestoreOnlyErrors
# general
function HistoryFile() { (Get-PSReadlineOption).HistorySavePath }
Set-Alias hfile HistoryFile
function filesByGlob($glob) {
Get-ChildItem -Filter $glob -Recurse -ErrorAction SilentlyContinue -Force | Select-Object -ExpandProperty FullName
}
function updatePowershell() {
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
}
function hardLink($src, $dest) {
try { del $dest 2>&1 | out-null } catch {}
New-Item -ItemType SymbolicLink -Path $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($dest) -Target $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($src)
}
function hostsFile() { echo "C:\Windows\System32\drivers\etc\hosts" }
function hostFile() { hostsFile }
function profile() { echo $profile }
function which($search) { $res=$(Get-Command $search -errorAction SilentlyContinue); if($res.Source) { echo $res.Source } else { echo $res } }
function screenClose() { (Add-Type '[DllImport(\"user32.dll\")]^public static extern int PostMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::PostMessage(-1,0x0112,0xF170,2) }
function watch($command, $secsToSleep = 5) {
while (1) {
clear ;
echo "$(Get-Date)" ;
. $command ;
sleep $secsToSleep ;
}
}
function wslIp($DOCKER_DISTRO = "Ubuntu-20.04") {
echo "$((wsl -d "$DOCKER_DISTRO" sh -c "hostname -I").Split(" ")[0] )"
}
function DockerService($DOCKER_DISTRO = "Ubuntu-20.04") {
$DOCKER_DIR = "/mnt/wsl/shared-docker"
$DOCKER_SOCK = "$DOCKER_DIR/docker.sock"
wsl -d "$DOCKER_DISTRO" sh -c "[ -S '$DOCKER_SOCK' ]"
if ($LASTEXITCODE) {
wsl -d "$DOCKER_DISTRO" sh -c "mkdir -pm o=,ug=rwx $DOCKER_DIR ; chgrp docker $DOCKER_DIR"
wsl -d "$DOCKER_DISTRO" sh -c "nohup sudo -b dockerd < /dev/null > $DOCKER_DIR/dockerd.log 2>&1"
}
}
function wslProxy($DOCKER_DISTRO = "Ubuntu-20.04") {
$env:WSL_HOST = (wsl -d "$DOCKER_DISTRO" sh -c "hostname -I").Split(" ")[0]
$env:DOCKER_HOST = "tcp://$($env:WSL_HOST):2375"
netsh interface portproxy add v4tov4 listenport=2375 connectport=2375 connectaddress=$env:WSL_HOST
}
function wslProxyPort($port, $DOCKER_DISTRO = "Ubuntu-20.04") {
$WSL_HOST = (wsl -d "$DOCKER_DISTRO" sh -c "hostname -I").Split(" ")[0]
netsh interface portproxy add v4tov4 listenport=$port connectport=$port connectaddress=$WSL_HOST
}
function wslProxyPortDelete($port) {
netsh interface portproxy delete v4tov4 listenport=$port
}
function minikubeProxy($DOCKER_DISTRO = "Ubuntu-20.04") {
$(wsl -d "$DOCKER_DISTRO" kubectl config view --raw --flatten --minify) > ~/.kube/config
}
Export-ModuleMember -Function * -Alias * -Variable * -Cmdlet *
################# END Profile By BarNuri #################