Skip to content

Commit

Permalink
Merge pull request #122 from szymonos/feat/repo-modules
Browse files Browse the repository at this point in the history
feat: repository modules
  • Loading branch information
szymonos authored Oct 2, 2023
2 parents 1c915f0 + aa127f7 commit 9012358
Show file tree
Hide file tree
Showing 23 changed files with 1,029 additions and 177 deletions.
2 changes: 1 addition & 1 deletion .assets/config/omp_cfg/base.omp.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"tag_icon": ""
},
"style": "plain",
"template": "<#E8CC97>(</>{{ .HEAD }}<#E8CC97>) </>",
"template": "<#E8CC97>(</><b>{{ .HEAD }}</b><#E8CC97>)</> ",
"type": "git"
},
{
Expand Down
1 change: 0 additions & 1 deletion .assets/provision/fix_certifi_certs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ esac
# get list of installed certificates
cert_paths=($(ls $CERT_PATH/*.crt 2>/dev/null))
if [ -z "$cert_paths" ]; then
printf '\nThere are no certificate(s) to install.\n' >&2
exit 0
fi

Expand Down
7 changes: 7 additions & 0 deletions .assets/provision/install_miniconda.sh
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,10 @@ fi
# *Update conda.
conda update -n base -c defaults conda --yes
conda clean --yes --all

# *Fix certificates after update.
if $fix_certify; then
conda activate base
.assets/provision/fix_certifi_certs.sh
conda deactivate
fi
2 changes: 1 addition & 1 deletion .assets/provision/install_pwsh.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
: '
sudo .assets/provision/install_pwsh.sh $(id -un) >/dev/null
sudo .assets/provision/install_pwsh.sh >/dev/null
'
if [ $EUID -ne 0 ]; then
printf '\e[31;1mRun the script as root.\e[0m\n'
Expand Down
5 changes: 2 additions & 3 deletions .assets/provision/setup_gh_repos.sh
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#!/usr/bin/env bash
: '
.assets/provision/setup_gh_repos.sh --repos "szymonos/linux-setup-scripts szymonos/ps-modules" --user "szymo"
.assets/provision/setup_gh_repos.sh --repos "szymonos/linux-setup-scripts szymonos/ps-modules" --user "szymo" --ws_suffix "scripts"
.assets/provision/setup_gh_repos.sh --repos "szymonos/linux-setup-scripts szymonos/ps-modules"
.assets/provision/setup_gh_repos.sh --repos "szymonos/linux-setup-scripts szymonos/ps-modules" --ws_suffix "scripts"
'
# parse named parameters
repos=${repos}
user=${user}
ws_suffix=${ws_suffix:-devops}
while [ $# -gt 0 ]; do
if [[ $1 == *"--"* ]]; then
Expand Down
44 changes: 27 additions & 17 deletions .assets/scripts/linux_setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
# :set up the system using default values
.assets/scripts/linux_setup.sh
# :set up the system using specified values
scope="shell"
scope="k8s_base python shell"
scope="pwsh"
scope="k8s_base python pwsh"
scope="az distrobox docker k8s_base k8s_ext python rice shell"
# :set up the system using the specified scope
.assets/scripts/linux_setup.sh --scope "$scope"
Expand Down Expand Up @@ -41,20 +41,24 @@ pushd "$(cd "${SCRIPT_ROOT}/../../" && pwd)" >/dev/null
# *Calculate and show installation scopes
# convert scope string to array
array=($scope)
# determine scope for update if not provided
if [ -z "$array" ]; then
[ -f /usr/bin/kubectl ] && array+=(k8s_base) || true
[ -f /usr/bin/kustomize ] && array+=(k8s_ext) || true
[ -f /usr/bin/pwsh ] && array+=(shell) || true
[ -d "$HOME/miniconda3" ] && array+=(python) || true
fi
# determine additional scopes
[ -d "$HOME/.local/share/powershell/Modules/Az" ] && array+=(az) || true
[ -f /usr/bin/kubectl ] && array+=(k8s_base) || true
[ -f /usr/local/bin/k3d ] && array+=(k8s_ext) || true
[ -f /usr/bin/pwsh ] && array+=(pwsh) || true
[ -d "$HOME/miniconda3" ] && array+=(python) || true
[ -f /usr/bin/rg ] && array+=(shell) || true
# add corresponding scopes
grep -qw 'az' <<<${array[@]} && array+=(python) || true
grep -qw 'k8s_ext' <<<${array[@]} && array+=(docker) && array+=(k8s_base) || true
grep -qw 'pwsh' <<<${array[@]} && array+=(shell) || true
# add oh_my_posh scope if necessary
if [[ -n "$omp_theme" || -f /usr/bin/oh-my-posh ]]; then
array+=(oh_my_posh)
grep -qw 'shell' <<<${array[@]} || array+=(shell)
array+=(shell)
fi
# sort array
IFS=$'\n' scope_arr=($(sort <<<${array[*]})) && unset IFS
IFS=$'\n' scope_arr=($(sort --unique <<<${array[*]})) && unset IFS
# get distro name from os-release
. /etc/os-release
# display distro name and scopes to install
Expand Down Expand Up @@ -86,7 +90,6 @@ for sc in ${scope_arr[@]}; do
sudo .assets/provision/install_minikube.sh >/dev/null
sudo .assets/provision/install_k3d.sh >/dev/null
sudo .assets/provision/install_k9s.sh >/dev/null
sudo .assets/provision/install_yq.sh >/dev/null
;;
k8s_ext)
printf "\e[96minstalling kubernetes additional packages...\e[0m\n"
Expand All @@ -102,6 +105,14 @@ for sc in ${scope_arr[@]}; do
sudo .assets/provision/setup_omp.sh --theme $omp_theme --user $user
fi
;;
pwsh)
printf "\e[96minstalling pwsh...\e[0m\n"
sudo .assets/provision/install_pwsh.sh >/dev/null
printf "\e[96msetting up profile for all users...\e[0m\n"
sudo .assets/provision/setup_profile_allusers.ps1 -UserName $user
printf "\e[96msetting up profile for current user...\e[0m\n"
.assets/provision/setup_profile_user.ps1
;;
python)
printf "\e[96minstalling python packages...\e[0m\n"
.assets/provision/install_miniconda.sh --fix_certify true
Expand All @@ -117,23 +128,22 @@ for sc in ${scope_arr[@]}; do
;;
shell)
printf "\e[96minstalling shell packages...\e[0m\n"
sudo .assets/provision/install_pwsh.sh >/dev/null
sudo .assets/provision/install_eza.sh >/dev/null
sudo .assets/provision/install_bat.sh >/dev/null
sudo .assets/provision/install_ripgrep.sh >/dev/null
sudo .assets/provision/install_yq.sh >/dev/null
printf "\e[96msetting up profile for all users...\e[0m\n"
sudo .assets/provision/setup_profile_allusers.sh $user
sudo .assets/provision/setup_profile_allusers.ps1 -UserName $user
printf "\e[96msetting up profile for current user...\e[0m\n"
.assets/provision/setup_profile_user.sh
.assets/provision/setup_profile_user.ps1
;;
esac
done
# install powershell modules
if [ -f /usr/bin/pwsh ]; then
cloned=$(.assets/tools/gh_repo_clone.ps1 -OrgRepo 'szymonos/ps-modules')
if [ "$cloned" = "True" ]; then
cmd="Import-Module (Resolve-Path './modules/InstallUtils'); Invoke-GhRepoClone -OrgRepo 'szymonos/ps-modules'"
cloned=$(pwsh -nop -c $cmd)
if [ $cloned -gt 0 ]; then
printf "\e[96minstalling ps-modules...\e[0m\n"
# install do-common module for all users
printf "\e[3;32mAllUsers\e[23m : do-common\e[0m\n"
Expand Down
91 changes: 91 additions & 0 deletions .assets/scripts/modules_update.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#Requires -PSEdition Core
<#
.SYNOPSIS
Update repository modules from ps-modules.
.EXAMPLE
.assets/scripts/modules_update.ps1
#>
[CmdletBinding()]
param ()

begin {
$ErrorActionPreference = 'Stop'

# check if repository is up to date
Write-Host 'refreshing current repository...' -ForegroundColor Cyan
git fetch
$remote = "$(git remote)/$(git branch --show-current)"
if ((git rev-parse HEAD) -ne (git rev-parse $remote)) {
Write-Warning "Current branch is behind remote, performing hard reset.`n`t Run the script again!`n"
git reset --hard $remote
exit 0
}

# set location to workspace folder
Push-Location "$PSScriptRoot/../.."
# import InstallUtils for the Invoke-GhRepoClone function
Import-Module (Resolve-Path './modules/InstallUtils')

# specify update functions structure
$import = @{
'do-common' = @{
SetupUtils = @{
certs = @(
'ConvertTo-PEM'
'Get-Certificate'
)
common = @(
'ConvertFrom-Cfg'
'ConvertTo-Cfg'
'Invoke-ExampleScriptSave'
)
}
}
'psm-windows' = @{
InstallUtils = @{
common = @(
'Invoke-CommandRetry'
'Test-IsAdmin'
'Update-SessionEnvironmentPath'
)
}
}
}
}

process {
# *refresh ps-modules repository
Write-Host 'refreshing ps-modules repository...' -ForegroundColor Cyan
if ((Invoke-GhRepoClone -OrgRepo 'szymonos/ps-modules' -Path '..') -eq 0) {
Write-Error 'Cloning ps-modules repository failed.'
}

# *perform update
Write-Host 'perform modules update..' -ForegroundColor Cyan
foreach ($srcModule in $import.GetEnumerator()) {
Import-Module (Resolve-Path "../ps-modules/modules/$($srcModule.Key)")
Write-Host "`n$($srcModule.Key)" -ForegroundColor Green
foreach ($dstModule in $srcModule.Value.GetEnumerator()) {
Write-Host $dstModule.Key
foreach ($destFile in $dstModule.Value.GetEnumerator()) {
Write-Host " - $($destFile.Key).ps1"
$filePath = "./modules/$($dstModule.Key)/Functions/$($destFile.Key).ps1"
Set-Content -Value $null -Path $filePath
$builder = [System.Text.StringBuilder]::new()
foreach ($function in $destFile.Value) {
Write-Host "$function"
$def = " $((Get-Command $function -CommandType Function).Definition.Trim())"
$builder.AppendLine("function $function {") | Out-Null
$builder.AppendLine($def) | Out-Null
$builder.AppendLine("}`n") | Out-Null
}
Set-Content -Value $builder.ToString().Trim().Replace("`r`n", "`n") -Path $filePath -Encoding utf8
}
}
}
}

end {
Pop-Location
}
65 changes: 0 additions & 65 deletions .assets/tools/gh_repo_clone.ps1

This file was deleted.

71 changes: 71 additions & 0 deletions modules/InstallUtils/Functions/common.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
function Invoke-CommandRetry {
[CmdletBinding()]
param (
[Parameter(Mandatory, Position = 0, HelpMessage = 'The command to be invoked.')]
[scriptblock]$Command,

[Parameter(HelpMessage = 'The number of retries the command should be invoked.')]
[int]$MaxRetries = 10
)

Set-Variable -Name retryCount -Value 0
do {
try {
Invoke-Command -ScriptBlock $Command
$exit = $true
} catch [System.IO.IOException] {
if ($_.Exception.TargetSite.Name -eq 'MoveNext') {
if ($_.ErrorDetails) {
Write-Verbose $_.ErrorDetails.Message
} else {
Write-Verbose $_.Exception.Message
}
Write-Host "`nRetrying..."
} else {
Write-Verbose $_.Exception.GetType().FullName
Write-Error $_
}
} catch [System.AggregateException] {
if ($_.Exception.InnerException.GetType().Name -eq 'HttpRequestException') {
Write-Verbose $_.Exception.InnerException.Message
Write-Host "`nRetrying..."
} else {
Write-Verbose $_.Exception.InnerException.GetType().FullName
Write-Error $_
}
} catch {
Write-Verbose $_.Exception.GetType().FullName
Write-Error $_
}
$retryCount++
if ($retryCount -eq $MaxRetries) {
$exit = $true
}
} until ($exit)
}

function Test-IsAdmin {
$currentIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [System.Security.Principal.WindowsPrincipal]$currentIdentity
$admin = [System.Security.Principal.WindowsBuiltInRole]'Administrator'

return $principal.IsInRole($admin)
}

function Update-SessionEnvironmentPath {
# instantiate a HashSet to store unique paths
$auxHashSet = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)

# get Path env variable from all scopes and build unique set
foreach ($scope in @('Machine', 'User', 'Process')) {
[Environment]::GetEnvironmentVariable('Path', $scope).Split(';').Where({ $_ }).ForEach({
$auxHashSet.Add($_) | Out-Null
}
)
}

# build a path string from the HashSet
$pathStr = [string]::Join([System.IO.Path]::PathSeparator, $auxHashSet)
# set the Path environment variable in the current process scope
[System.Environment]::SetEnvironmentVariable('Path', $pathStr, 'Process')
}
Loading

0 comments on commit 9012358

Please sign in to comment.