Compare commits

...

10 Commits

Author SHA1 Message Date
PapaTramp e1ba24eb74 init-cursor: ASCII-подсказка после dot-source (без em dash). 2026-06-19 23:43:33 +10:00
PapaTramp 7388ef1462 README: краткая шпаргалка; install.sh как install.ps1 (SSH/HTTPS авто). 2026-06-19 23:41:57 +10:00
PapaTramp 2e3b303029 init-cursor: подсказка после dot-source. 2026-06-19 23:37:35 +10:00
PapaTramp 584ddde1d1 Set-GitRemotes: имя repo из remote URL, не из имени папки. 2026-06-19 23:34:45 +10:00
PapaTramp 25f4d5972e install.ps1: backup старого CursorRules, fix вызова init-cursor. 2026-06-19 23:33:53 +10:00
PapaTramp 12dd597360 install: SSH clone first; убрать irm для приватного repo. 2026-06-19 23:32:31 +10:00
PapaTramp e1078dc6ed Setup-GitSsh: писать ssh config без UTF-8 BOM. 2026-06-18 11:34:18 +10:00
PapaTramp 4caedb3074 Remotes: kalinamall, home, github по SSH (.ru); origin убран.
Set-GitRemotes переименует origin по хосту; SSH config для .ru через LAN IP.
2026-06-18 11:34:03 +10:00
PapaTramp 7f8e7c0cb2 init-cursor: авто-bootstrap git на новом ПК, install.ps1 с Gitea.
Один вызов init-cursor настраивает SSH при необходимости и копирует rules в проект.
2026-06-18 11:23:30 +10:00
PapaTramp bdf405e2c1 Добавить bootstrap для новых ПК и Linux-скрипты.
SSH-ключи и Gitea API до clone Rules; init-cursor копирует из локального $HOME/CursorRules.
2026-06-18 10:01:11 +10:00
18 changed files with 1675 additions and 30 deletions
+100 -10
View File
@@ -1,24 +1,114 @@
# Rules # Rules
Правила и скрипты для настройки нового компьютера: Cursor rules, git remotes, home Gitea. Скрипты для Cursor rules, SSH и git remotes (`kalinamall`, `home`, `github`).
## Первичная настройка ## Быстро: что запускать
| Ситуация | Windows | Mac / Linux |
|----------|---------|-------------|
| **Новый комп** (ничего не настроено) | Скопировать `install.ps1` с рабочего ПК → запустить в каталоге проекта | То же с `install.sh` |
| **Комп уже настраивали** (`~/CursorRules` есть) | `init-cursor` в каталоге проекта | `init-cursor` |
| **Только обновить rules** | `init-cursor -Update` | `init-cursor --update` |
Скрипты **сами** проверяют SSH, clone, ключи и remotes. Вручную выбирать SSH/HTTPS не нужно.
---
## Новый компьютер
Нужен только **git**. Repo приватный — `curl`/`irm` по raw-URL **не работают**.
### 1. Скопировать один файл с рабочей машины
```powershell ```powershell
git clone https://git.kalinamall.ru/PapaTramp/Rules $HOME\CursorRules # Windows — с другого ПК (пример)
scp user@work-pc:CursorRules/install.ps1 $env:TEMP\
``` ```
Добавьте `init-cursor` в профиль PowerShell (один раз): ```bash
# Mac — с другого ПК
```powershell scp user@work-pc:CursorRules/install.sh /tmp/
. $HOME\CursorRules\init-cursor.ps1
``` ```
## В каждом проекте USB, общая папка — тоже подходит.
### 2. Запустить в каталоге **вашего проекта**
```powershell ```powershell
cd C:\path\to\repo # Windows
cd C:\path\to\your-repo
& $env:TEMP\install.ps1
```
```bash
# Mac
cd ~/projects/your-repo
bash /tmp/install.sh
```
Скрипт сам:
1. Клонирует Rules в `~/CursorRules` (SSH → если не вышло, HTTPS с логином)
2. Настраивает SSH-ключи и Gitea API (если ещё нет)
3. Копирует rules в текущий проект, настраивает remotes
4. Добавляет `init-cursor` в профиль shell
---
## Уже настроенный компьютер
```powershell
cd C:\path\to\your-repo
init-cursor init-cursor
``` ```
Скрипт копирует `.cursorignore` и `.cursor/rules/*.mdc`, при необходимости дополняет `.gitignore`, настраивает remotes (`home`, `github`, `kalinamall`) и создаёт репозиторий на home Gitea через API. ```bash
cd ~/projects/your-repo
init-cursor
```
Если команда не найдена — один раз:
```powershell
. $HOME\CursorRules\init-cursor.ps1 # Windows
```
```bash
source ~/CursorRules/init-cursor.sh # Mac
```
---
## Обновить rules / скрипты
```powershell
init-cursor -Update # Windows
```
```bash
init-cursor --update # Mac
```
Обновит `$HOME/CursorRules` с Gitea и перекопирует rules в проект.
---
## Git remotes (в каждом проекте)
| Remote | Куда |
|--------|------|
| `kalinamall` | git.kalinamall.ru |
| `home` | git.papatramp.ru |
| `github` | github.com/PTah |
Push: `git push kalinamall`
---
## Конфиги (`local/`)
| Файл | Назначение |
|------|------------|
| `git-ssh-hosts.conf` | SSH-хосты и ключи |
| `git-user.conf` | git user.name / email |
| `kalinamall-gitea.conf` | API kalinamall |
| `papatramp-gitea.conf` | API home Gitea |
+28
View File
@@ -0,0 +1,28 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Обёртка над Invoke-MachineBootstrap.ps1 (совместимость).
#>
[CmdletBinding()]
param(
[string]$RulesDest = '',
[switch]$SkipClone,
[switch]$SkipProfile,
[switch]$WhatIf
)
$root = $PSScriptRoot
if (-not $RulesDest) {
$RulesDest = Join-Path $HOME 'CursorRules'
}
& (Join-Path $root 'scripts\Invoke-MachineBootstrap.ps1') @{
Root = $root
RulesDest = $RulesDest
SkipClone = $SkipClone.IsPresent
SkipProfile = $SkipProfile.IsPresent
WhatIf = $WhatIf.IsPresent
}
Write-Host ''
Write-Host '[+] Bootstrap complete. In a project run: init-cursor' -ForegroundColor Green
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Обёртка над invoke-machine-bootstrap.sh (совместимость).
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RULES_DEST="${RULES_DEST:-$HOME/CursorRules}"
SKIP_CLONE="${SKIP_CLONE:-0}"
SKIP_PROFILE="${SKIP_PROFILE:-0}"
ROOT="$ROOT" RULES_DEST="$RULES_DEST" SKIP_CLONE="$SKIP_CLONE" SKIP_PROFILE="$SKIP_PROFILE" \
bash "$ROOT/scripts/invoke-machine-bootstrap.sh"
printf '\n[+] Bootstrap complete. In a project run: init-cursor\n'
+92 -12
View File
@@ -1,32 +1,93 @@
#Requires -Version 5.1 #Requires -Version 5.1
<# <#
.SYNOPSIS .SYNOPSIS
Копирует Cursor rules в текущий каталог и настраивает git remotes. Инициализация Cursor в текущем проекте; на новом ПК сначала настраивает git/SSH.
.DESCRIPTION .DESCRIPTION
1. .cursorignore из $HOME\CursorRules Один вызов init-cursor:
2. .cursor/rules/*.mdc - если машина не настроена: SSH, Gitea keys, clone Rules в $HOME\CursorRules
3. В git-репо: Set-GitRemotes.ps1 + Ensure-GiteaHomeRepo.ps1 (home Gitea) - затем копирует rules в текущий репозиторий и настраивает remotes
Первый запуск (приватный repo — через git clone, см. README):
git clone --depth 1 ssh://git@git.kalinamall.ru:2222/PapaTramp/Rules.git $HOME\CursorRules
& $HOME\CursorRules\install.ps1
.EXAMPLE .EXAMPLE
cd C:\Users\papat\Projects\MyRepo cd C:\Users\papat\Projects\MyRepo
init-cursor init-cursor
init-cursor -Update
#> #>
function init-cursor { function Get-CursorRulesDest {
return (Join-Path $HOME 'CursorRules')
}
function Get-CursorBootstrapRoot {
param([string]$RulesDest)
$scriptRoot = $PSScriptRoot
if (Test-Path (Join-Path $scriptRoot 'scripts\Invoke-MachineBootstrap.ps1')) {
return $scriptRoot
}
if (Test-Path (Join-Path $RulesDest 'local\git-ssh-hosts.conf')) {
return $RulesDest
}
if (Test-Path (Join-Path $scriptRoot 'local\git-ssh-hosts.conf')) {
return $scriptRoot
}
return $null
}
function Initialize-CursorRulesEnvironment {
[CmdletBinding()]
param(
[switch]$Update
)
$rulesDest = Get-CursorRulesDest
$bootstrapRoot = Get-CursorBootstrapRoot -RulesDest $rulesDest
if (-not $bootstrapRoot) {
Write-Host 'Error: CursorRules not found. Run install.ps1 from Gitea first:' -ForegroundColor Red
Write-Host ' git clone --depth 1 ssh://git@git.kalinamall.ru:2222/PapaTramp/Rules.git $HOME\CursorRules' -ForegroundColor Yellow
Write-Host ' & $HOME\CursorRules\install.ps1' -ForegroundColor Yellow
return $false
}
$bootstrapScript = Join-Path $bootstrapRoot 'scripts\Invoke-MachineBootstrap.ps1'
if (-not (Test-Path -LiteralPath $bootstrapScript)) {
Write-Host "Error: bootstrap script not found: $bootstrapScript" -ForegroundColor Red
return $false
}
$repoReady = Test-Path (Join-Path $rulesDest '.git')
$skipClone = $repoReady
& $bootstrapScript -Root $bootstrapRoot -RulesDest $rulesDest -SkipClone:$skipClone
if ($Update -and $repoReady) {
Write-Host '[*] Updating CursorRules from remote...' -ForegroundColor Cyan
git -C $rulesDest pull --ff-only
if ($LASTEXITCODE -ne 0) {
Write-Host '[!] git pull failed in CursorRules' -ForegroundColor Yellow
}
else {
Write-Host '[+] CursorRules updated' -ForegroundColor Green
}
}
return $true
}
function Install-CursorInCurrentProject {
[CmdletBinding()] [CmdletBinding()]
param( param(
[switch]$SkipGitRemotes [switch]$SkipGitRemotes
) )
$source = Join-Path $HOME 'CursorRules' $source = Get-CursorRulesDest
$rulesSrc = Join-Path $source '.cursor\rules' $rulesSrc = Join-Path $source '.cursor\rules'
$scripts = Join-Path $source 'scripts' $scripts = Join-Path $source 'scripts'
if (-not (Test-Path $source)) {
Write-Host "Error: $source not found" -ForegroundColor Red
return
}
$cursorIgnore = Join-Path $source '.cursorignore' $cursorIgnore = Join-Path $source '.cursorignore'
if (Test-Path $cursorIgnore) { if (Test-Path $cursorIgnore) {
Copy-Item $cursorIgnore . -Force Copy-Item $cursorIgnore . -Force
@@ -68,7 +129,7 @@ function init-cursor {
git rev-parse --is-inside-work-tree 2>$null | Out-Null git rev-parse --is-inside-work-tree 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -ne 0) {
Write-Host '[!] Not a git repo remotes skipped' -ForegroundColor Yellow Write-Host '[!] Not a git repo - remotes skipped' -ForegroundColor Yellow
return return
} }
@@ -90,3 +151,22 @@ function init-cursor {
} }
} }
} }
function init-cursor {
[CmdletBinding()]
param(
[switch]$SkipGitRemotes,
[switch]$Update
)
if (-not (Initialize-CursorRulesEnvironment -Update:$Update)) {
return
}
Install-CursorInCurrentProject -SkipGitRemotes:$SkipGitRemotes
Write-Host '[+] init-cursor complete' -ForegroundColor Green
}
if ($MyInvocation.InvocationName -eq '.') {
Write-Host '[+] init-cursor loaded - run: init-cursor' -ForegroundColor DarkCyan
}
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env bash
# Инициализация Cursor в текущем проекте; на новом хосте сначала настраивает git/SSH.
get_cursor_rules_dest() {
printf '%s' "$HOME/CursorRules"
}
get_cursor_bootstrap_root() {
local rules_dest script_dir
rules_dest="$(get_cursor_rules_dest)"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "$script_dir/scripts/invoke-machine-bootstrap.sh" ]]; then
printf '%s' "$script_dir"
return 0
fi
if [[ -f "$rules_dest/local/git-ssh-hosts.conf" ]]; then
printf '%s' "$rules_dest"
return 0
fi
if [[ -f "$script_dir/local/git-ssh-hosts.conf" ]]; then
printf '%s' "$script_dir"
return 0
fi
return 1
}
initialize_cursor_rules_environment() {
local update=0
[[ "${1:-}" == '--update' ]] && update=1
local rules_dest bootstrap_root
rules_dest="$(get_cursor_rules_dest)"
bootstrap_root="$(get_cursor_bootstrap_root)" || {
echo 'Error: CursorRules not found. Run install.sh from Gitea first:' >&2
echo ' curl -fsSL https://git.kalinamall.ru/PapaTramp/Rules/raw/branch/main/install.sh | bash' >&2
return 1
}
local skip_clone=0
[[ -d "$rules_dest/.git" ]] && skip_clone=1
ROOT="$bootstrap_root" RULES_DEST="$rules_dest" SKIP_CLONE="$skip_clone" \
bash "$bootstrap_root/scripts/invoke-machine-bootstrap.sh"
if [[ "$update" -eq 1 && -d "$rules_dest/.git" ]]; then
echo '[*] Updating CursorRules from remote...'
if git -C "$rules_dest" pull --ff-only; then
echo '[+] CursorRules updated'
else
echo '[!] git pull failed in CursorRules' >&2
fi
fi
}
install_cursor_in_current_project() {
local skip_git_remotes=0
while [[ $# -gt 0 ]]; do
case "$1" in
--skip-git-remotes) skip_git_remotes=1; shift ;;
*) shift ;;
esac
done
local source rules_src scripts
source="$(get_cursor_rules_dest)"
rules_src="$source/.cursor/rules"
scripts="$source/scripts"
if [[ -f "$source/.cursorignore" ]]; then
cp -f "$source/.cursorignore" .
echo '[+] .cursorignore copied'
fi
if [[ -d "$rules_src" ]]; then
mkdir -p ./.cursor/rules
cp -f "$rules_src"/*.mdc ./.cursor/rules/
echo '[+] .cursor/rules (*.mdc) copied'
fi
if [[ -d .git ]]; then
local gitignore='.gitignore' line
for line in '.cursor/' '.cursorignore'; do
if [[ ! -f "$gitignore" ]]; then
printf '%s\n' "$line" > "$gitignore"
echo "[+] .gitignore created ($line)"
elif ! grep -Fxq "$line" "$gitignore" 2>/dev/null; then
printf '%s\n' "$line" >> "$gitignore"
echo "[+] .gitignore updated ($line)"
fi
done
fi
if [[ "$skip_git_remotes" -eq 1 ]]; then
echo '[!] Git remotes skipped'
return 0
fi
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo '[!] Not a git repo - remotes skipped'
return 0
fi
if [[ -f "$scripts/Set-GitRemotes.sh" ]]; then
echo '[*] Configuring git remotes...'
bash "$scripts/Set-GitRemotes.sh" || true
fi
if [[ -f "$scripts/Ensure-GiteaHomeRepo.ps1" ]]; then
local repo_name
repo_name="$(basename "$(git rev-parse --show-toplevel)")"
echo "[*] Ensuring home Gitea repo: $repo_name"
if command -v pwsh >/dev/null 2>&1; then
pwsh -NoProfile -File "$scripts/Ensure-GiteaHomeRepo.ps1" -RepoName "$repo_name" || true
fi
fi
}
init-cursor() {
local update=0
local skip_git_remotes=0
while [[ $# -gt 0 ]]; do
case "$1" in
-Update|--update) update=1; shift ;;
-SkipGitRemotes|--skip-git-remotes) skip_git_remotes=1; shift ;;
*) shift ;;
esac
done
if [[ "$update" -eq 1 ]]; then
initialize_cursor_rules_environment --update || return 1
else
initialize_cursor_rules_environment || return 1
fi
if [[ "$skip_git_remotes" -eq 1 ]]; then
install_cursor_in_current_project --skip-git-remotes
else
install_cursor_in_current_project
fi
echo '[+] init-cursor complete'
}
+65
View File
@@ -0,0 +1,65 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Точка входа на новом ПК: clone Rules, bootstrap, init-cursor в текущем проекте.
.DESCRIPTION
SSH / HTTPS / ключи / remotes — автоматически. Запускать из каталога проекта.
На голом ПК: скопируйте этот файл с рабочей машины (scp/USB), затем:
& .\install.ps1
.EXAMPLE
cd C:\path\to\your-repo
& $env:TEMP\install.ps1
#>
[CmdletBinding()]
param(
[switch]$SkipGitRemotes,
[switch]$Update
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$rulesDest = Join-Path $HOME 'CursorRules'
$httpsUrl = 'https://git.kalinamall.ru/PapaTramp/Rules.git'
$sshUrl = 'ssh://git@git.kalinamall.ru:2222/PapaTramp/Rules.git'
function Ensure-RulesClone {
if (Test-Path (Join-Path $rulesDest '.git')) {
Write-Host '[*] Updating CursorRules...' -ForegroundColor Cyan
git -C $rulesDest pull --ff-only
return
}
if (Test-Path -LiteralPath $rulesDest) {
$backup = "${rulesDest}.bak-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Write-Host "[!] Replacing non-git folder: $rulesDest -> $backup" -ForegroundColor Yellow
Move-Item -LiteralPath $rulesDest -Destination $backup
}
Write-Host '[*] Cloning Rules via SSH...' -ForegroundColor Cyan
git clone --depth 1 $sshUrl $rulesDest 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Host '[!] SSH clone failed - trying HTTPS (enter Gitea login once)...' -ForegroundColor Yellow
git clone --depth 1 $httpsUrl $rulesDest
if ($LASTEXITCODE -ne 0) {
throw 'git clone failed'
}
}
Write-Host "[+] Cloned to $rulesDest" -ForegroundColor Green
}
Ensure-RulesClone
. (Join-Path $rulesDest 'init-cursor.ps1')
if ($Update) {
init-cursor -Update -SkipGitRemotes:$SkipGitRemotes
}
elseif ($SkipGitRemotes) {
init-cursor -SkipGitRemotes
}
else {
init-cursor
}
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Первая загрузка Rules и init-cursor. SSH/HTTPS и bootstrap — автоматически.
set -euo pipefail
RULES_DEST="${RULES_DEST:-$HOME/CursorRules}"
HTTPS_URL="${HTTPS_URL:-https://git.kalinamall.ru/PapaTramp/Rules.git}"
SSH_URL="${SSH_URL:-ssh://git@git.kalinamall.ru:2222/PapaTramp/Rules.git}"
SKIP_GIT_REMOTES=0
UPDATE=0
while [[ $# -gt 0 ]]; do
case "$1" in
--skip-git-remotes) SKIP_GIT_REMOTES=1; shift ;;
--update|-Update) UPDATE=1; shift ;;
*) shift ;;
esac
done
log_step() { printf '[*] %s\n' "$1"; }
log_ok() { printf '[+] %s\n' "$1"; }
log_warn() { printf '[!] %s\n' "$1"; }
ensure_rules_clone() {
if [[ -d "$RULES_DEST/.git" ]]; then
log_step 'Updating CursorRules...'
git -C "$RULES_DEST" pull --ff-only
return 0
fi
if [[ -e "$RULES_DEST" ]]; then
local backup="${RULES_DEST}.bak-$(date +%Y%m%d-%H%M%S)"
log_warn "Replacing non-git folder: $RULES_DEST -> $backup"
mv "$RULES_DEST" "$backup"
fi
log_step 'Cloning Rules via SSH...'
if git clone --depth 1 "$SSH_URL" "$RULES_DEST" 2>/dev/null; then
log_ok "Cloned to $RULES_DEST"
return 0
fi
log_warn 'SSH clone failed - trying HTTPS (enter Gitea login once)...'
git clone --depth 1 "$HTTPS_URL" "$RULES_DEST"
log_ok "Cloned to $RULES_DEST"
}
ensure_rules_clone
# shellcheck source=/dev/null
source "$RULES_DEST/init-cursor.sh"
if [[ "$UPDATE" -eq 1 ]]; then
if [[ "$SKIP_GIT_REMOTES" -eq 1 ]]; then
init-cursor --update --skip-git-remotes
else
init-cursor --update
fi
elif [[ "$SKIP_GIT_REMOTES" -eq 1 ]]; then
init-cursor --skip-git-remotes
else
init-cursor
fi
+52
View File
@@ -0,0 +1,52 @@
# Профили SSH-ключей и хосты Git. GiteaConfig — файл в local/ для регистрации pubkey через API.
[profile:kalinamall-git]
KeyName=id_ed25519_git_kalinamall
KeyComment=papatramp@kalinamall
GiteaConfig=kalinamall-gitea.conf
[host:git.kalinamall.ru]
HostName=192.168.160.129
Port=2222
User=git
Profile=kalinamall-git
[host:git.kalinamall.lan]
HostName=192.168.160.129
Port=2222
User=git
Profile=kalinamall-git
[profile:papatramp-git]
KeyName=id_ed25519_git_papatramp
KeyComment=papatramp@papatramp.ru
GiteaConfig=papatramp-gitea.conf
[host:git.papatramp.ru]
HostName=192.168.128.48
Port=2222
User=git
Profile=papatramp-git
[host:git.papatramp.lan]
HostName=192.168.128.48
Port=2222
User=git
Profile=papatramp-git
[host:git.papatramp-haproxy]
HostName=192.168.128.65
Port=2222
User=git
Profile=papatramp-git
[profile:github]
KeyName=id_ed25519_github
KeyComment=papatramp@gmail.com
GiteaConfig=
[host:github.com]
HostName=github.com
Port=22
User=git
Profile=github
+2
View File
@@ -0,0 +1,2 @@
UserName=PTah
UserEmail=papatramp@gmail.com
+9
View File
@@ -0,0 +1,9 @@
Type=gitea
GiteaHost=git.kalinamall.ru
GiteaPort=2222
GiteaWebUrl=https://git.kalinamall.ru
GiteaApiUrl=http://192.168.160.129:3000
GiteaApiUser=papatramp
GiteaApiPassword=R3tt3tnatur
KeyName=id_ed25519_git_kalinamall
KeyComment=papatramp@kalinamall
+210
View File
@@ -0,0 +1,210 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Настройка git на машине: user, SSH, Gitea keys, clone/update Rules.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][string]$Root,
[string]$RulesDest = '',
[string]$CloneUrl = 'ssh://git@git.kalinamall.ru:2222/PapaTramp/Rules.git',
[string]$HttpsCloneUrl = 'https://git.kalinamall.ru/PapaTramp/Rules.git',
[switch]$SkipClone,
[switch]$SkipProfile,
[switch]$SkipGitSetup,
[switch]$WhatIf
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Write-Step([string]$Message) { Write-Host "[*] $Message" -ForegroundColor Cyan }
function Write-Ok([string]$Message) { Write-Host "[+] $Message" -ForegroundColor Green }
function Write-Warn([string]$Message) { Write-Host "[!] $Message" -ForegroundColor Yellow }
function Read-KeyValueFile {
param([string]$Path)
$data = @{}
if (-not (Test-Path -LiteralPath $Path)) { return $data }
Get-Content -LiteralPath $Path | ForEach-Object {
if ($_ -match '^([^#=]+)=(.*)$') {
$data[$Matches[1].Trim()] = $Matches[2].Trim()
}
}
return $data
}
function Test-MachineGitReady {
param([string]$ConfigDir)
$hostsConfig = Join-Path $ConfigDir 'git-ssh-hosts.conf'
if (-not (Test-Path -LiteralPath $hostsConfig)) { return $false }
$sshConfig = Join-Path $HOME '.ssh\config'
if (-not (Test-Path -LiteralPath $sshConfig)) { return $false }
$profiles = @{}
$currentProfile = $null
Get-Content -LiteralPath $hostsConfig | ForEach-Object {
$line = $_.Trim()
if ($line -match '^\[profile:(.+)\]$') {
$currentProfile = $Matches[1]
$profiles[$currentProfile] = @{}
return
}
if ($line -match '^\[host:') { $currentProfile = $null; return }
if ($line -match '^([^=]+)=(.*)$' -and $currentProfile) {
$profiles[$currentProfile][$Matches[1].Trim()] = $Matches[2].Trim()
}
}
$sshText = Get-Content -LiteralPath $sshConfig -Raw
foreach ($profile in $profiles.Values) {
$keyName = $profile.KeyName
if (-not $keyName) { continue }
$keyPath = Join-Path $HOME ".ssh\$keyName"
if (-not (Test-Path -LiteralPath $keyPath)) { return $false }
}
if ($sshText -notmatch '(?m)^Host\s+git\.kalinamall\.ru\s*$') { return $false }
return $true
}
function Ensure-RulesRepository {
param(
[string]$Destination,
[string]$SshUrl,
[string]$HttpsUrl
)
if (Test-Path -LiteralPath $Destination) {
if (Test-Path (Join-Path $Destination '.git')) {
if ($WhatIf) {
Write-Step "WhatIf: git pull $Destination"
return
}
Write-Step "Updating $Destination"
git -C $Destination pull --ff-only
Write-Ok 'CursorRules updated'
return
}
$backup = "${Destination}.bak-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Write-Warn "Replacing non-git folder: $Destination -> $backup"
if (-not $WhatIf) {
Move-Item -LiteralPath $Destination -Destination $backup
}
}
if ($WhatIf) {
Write-Step "WhatIf: clone -> $Destination"
return
}
Write-Step "Cloning Rules via SSH: $SshUrl"
git clone --depth 1 $SshUrl $Destination 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Ok "Cloned to $Destination"
return
}
Write-Warn 'SSH clone failed - trying HTTPS (enter Gitea login once)'
git clone --depth 1 $HttpsUrl $Destination
if ($LASTEXITCODE -ne 0) {
throw "Failed to clone Rules repository"
}
Write-Ok "Cloned via HTTPS to $Destination"
}
function Ensure-InitCursorProfile {
param([string]$RulesDest)
$profileHook = ". `"$RulesDest\init-cursor.ps1`""
$profilePath = $PROFILE.CurrentUserAllHosts
if (-not $profilePath) { $profilePath = $PROFILE.CurrentUserCurrentHost }
if ($WhatIf) {
Write-Step "WhatIf: profile hook -> $profilePath"
return
}
$profileDir = Split-Path -Parent $profilePath
if (-not (Test-Path -LiteralPath $profileDir)) {
New-Item -ItemType Directory -Path $profileDir -Force | Out-Null
}
$profileText = if (Test-Path -LiteralPath $profilePath) {
Get-Content -LiteralPath $profilePath -Raw
} else {
''
}
if ($profileText -notmatch [regex]::Escape($profileHook)) {
if ($profileText -and -not $profileText.EndsWith("`n")) { $profileText += "`n" }
$profileText += $profileHook + "`n"
Set-Content -LiteralPath $profilePath -Value $profileText.TrimEnd() -Encoding UTF8
Write-Ok "Profile updated: $profilePath"
}
}
if (-not $RulesDest) {
$RulesDest = Join-Path $HOME 'CursorRules'
}
$configDir = Join-Path $Root 'local'
if (-not (Test-Path -LiteralPath $configDir)) {
throw "Bootstrap config not found: $configDir"
}
$gitReady = Test-MachineGitReady -ConfigDir $configDir
$repoReady = Test-Path (Join-Path $RulesDest '.git')
if (-not $gitReady -and -not $SkipGitSetup) {
Write-Step 'Machine bootstrap: git + SSH'
$userCfgPath = Join-Path $configDir 'git-user.conf'
if (Test-Path -LiteralPath $userCfgPath) {
$userCfg = Read-KeyValueFile -Path $userCfgPath
if ($userCfg.UserName -and -not $WhatIf) {
git config --global user.name $userCfg.UserName | Out-Null
Write-Ok "git user.name = $($userCfg.UserName)"
}
if ($userCfg.UserEmail -and -not $WhatIf) {
git config --global user.email $userCfg.UserEmail | Out-Null
Write-Ok "git user.email = $($userCfg.UserEmail)"
}
}
$setupArgs = @{ ConfigDir = $configDir; WhatIf = $WhatIf.IsPresent }
& (Join-Path $Root 'scripts\Setup-GitSsh.ps1') @setupArgs
$registerArgs = @{ ConfigDir = $configDir; WhatIf = $WhatIf.IsPresent }
& (Join-Path $Root 'scripts\Register-GiteaSshKeys.ps1') @registerArgs
if (-not $WhatIf) {
Write-Step 'Testing git@git.kalinamall.ru'
ssh -T -o BatchMode=yes -o ConnectTimeout=10 git@git.kalinamall.ru 2>&1 | ForEach-Object { Write-Host $_ }
}
}
elseif ($gitReady) {
Write-Ok 'Git SSH already configured'
}
if (-not $SkipClone -and -not $repoReady) {
Ensure-RulesRepository -Destination $RulesDest -SshUrl $CloneUrl -HttpsUrl $HttpsCloneUrl
}
elseif ($repoReady -and -not $SkipClone -and -not $WhatIf) {
Write-Ok "CursorRules repo OK: $RulesDest"
}
if (-not $SkipProfile) {
Ensure-InitCursorProfile -RulesDest $RulesDest
}
Write-Ok 'Machine bootstrap complete'
# Export test function for init-cursor dot-source
function Test-CursorMachineGitReady {
param([string]$ConfigDir = (Join-Path $HOME 'CursorRules\local'))
return Test-MachineGitReady -ConfigDir $ConfigDir
}
+136
View File
@@ -0,0 +1,136 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Регистрирует публичные SSH-ключи в Gitea через API (kalinamall, papatramp).
#>
[CmdletBinding()]
param(
[string]$ConfigDir = "$HOME\CursorRules\local",
[string]$HostsConfig = '',
[switch]$WhatIf
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Write-Step([string]$Message) { Write-Host "[*] $Message" -ForegroundColor Cyan }
function Write-Ok([string]$Message) { Write-Host "[+] $Message" -ForegroundColor Green }
function Write-Warn([string]$Message) { Write-Host "[!] $Message" -ForegroundColor Yellow }
function Read-KeyValueFile {
param([string]$Path)
$data = @{}
Get-Content -LiteralPath $Path | ForEach-Object {
if ($_ -match '^([^#=]+)=(.*)$') {
$data[$Matches[1].Trim()] = $Matches[2].Trim()
}
}
return $data
}
function Read-GitSshHostsConfig {
param([string]$Path)
$profiles = @{}
$currentProfile = $null
Get-Content -LiteralPath $Path | ForEach-Object {
$line = $_.Trim()
if (-not $line -or $line.StartsWith('#')) { return }
if ($line -match '^\[profile:(.+)\]$') {
$currentProfile = $Matches[1]
$profiles[$currentProfile] = @{}
return
}
if ($line -match '^\[host:') { $currentProfile = $null; return }
if ($line -match '^([^=]+)=(.*)$' -and $currentProfile) {
$profiles[$currentProfile][$Matches[1].Trim()] = $Matches[2].Trim()
}
}
return $profiles
}
function Get-GiteaAuthHeader {
param([hashtable]$Cfg)
$pair = '{0}:{1}' -f $Cfg.GiteaApiUser, $Cfg.GiteaApiPassword
$auth = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair))
return @{ Authorization = $auth; 'Content-Type' = 'application/json' }
}
function Register-GiteaKey {
param(
[hashtable]$Cfg,
[string]$PublicKeyPath,
[string]$Title
)
if (-not $Cfg.GiteaApiPassword) {
Write-Warn "$Title : GiteaApiPassword empty - add key manually in Gitea UI"
Write-Host (Get-Content -LiteralPath $PublicKeyPath -Raw).Trim()
return
}
$base = $Cfg.GiteaApiUrl.TrimEnd('/')
$headers = Get-GiteaAuthHeader -Cfg $Cfg
$pub = (Get-Content -LiteralPath $PublicKeyPath -Raw).Trim()
$existing = Invoke-RestMethod -Method Get -Uri "$base/api/v1/user/keys" -Headers $headers -TimeoutSec 15
foreach ($item in @($existing)) {
if ($item.key.Trim() -eq $pub) {
Write-Ok "$Title : key already registered ($($item.title))"
return
}
}
$body = (@{ title = $Title; key = $pub } | ConvertTo-Json)
if ($WhatIf) {
Write-Step "WhatIf: POST $base/api/v1/user/keys ($Title)"
return
}
$created = Invoke-RestMethod -Method Post -Uri "$base/api/v1/user/keys" -Headers $headers -Body $body -TimeoutSec 30
Write-Ok "$Title : registered ($($created.title))"
}
if (-not $HostsConfig) {
$HostsConfig = Join-Path $ConfigDir 'git-ssh-hosts.conf'
}
if (-not (Test-Path -LiteralPath $HostsConfig)) {
throw "Config not found: $HostsConfig"
}
$profiles = Read-GitSshHostsConfig -Path $HostsConfig
$sshDir = Join-Path $HOME '.ssh'
$machine = $env:COMPUTERNAME
if (-not $machine) { $machine = [Environment]::MachineName }
$registered = @{}
foreach ($profileName in $profiles.Keys) {
$profile = $profiles[$profileName]
$giteaConfigName = $profile.GiteaConfig
if (-not $giteaConfigName) { continue }
$keyName = $profile.KeyName
if ($registered.ContainsKey($keyName)) { continue }
$registered[$keyName] = $true
$giteaPath = Join-Path $ConfigDir $giteaConfigName
if (-not (Test-Path -LiteralPath $giteaPath)) {
Write-Warn "Gitea config not found: $giteaPath"
continue
}
$cfg = Read-KeyValueFile -Path $giteaPath
$pubPath = Join-Path $sshDir "$keyName.pub"
if (-not (Test-Path -LiteralPath $pubPath)) {
Write-Warn "Public key not found: $pubPath (run Setup-GitSsh first)"
continue
}
$title = "$machine-$keyName"
Write-Step "Registering $keyName on $($cfg.GiteaHost)"
Register-GiteaKey -Cfg $cfg -PublicKeyPath $pubPath -Title $title
}
Write-Ok 'Gitea SSH key registration done'
+43 -8
View File
@@ -1,7 +1,7 @@
#Requires -Version 5.1 #Requires -Version 5.1
<# <#
.SYNOPSIS .SYNOPSIS
Стандартные git remote: home, kalinamall, github. Стандартные git remote: home (papatramp), kalinamall, github (PTah).
.EXAMPLE .EXAMPLE
cd C:\Users\papat\Projects\MyRepo cd C:\Users\papat\Projects\MyRepo
@@ -29,19 +29,46 @@ function Test-GitRepo {
} }
} }
function Get-RepoNameFromRemoteUrl {
param([string]$Url)
if ($Url -match '/([^/]+?)(?:\.git)?/?$') {
return $Matches[1]
}
return $null
}
function Get-RepoName { function Get-RepoName {
param([string]$Name) param([string]$Name)
if ($Name) { return $Name } if ($Name) { return $Name }
foreach ($remote in @('kalinamall', 'home', 'github', 'origin')) {
$url = git remote get-url $remote 2>$null
if ($url) {
$fromUrl = Get-RepoNameFromRemoteUrl -Url $url.Trim()
if ($fromUrl) { return $fromUrl }
}
}
return (Split-Path -Leaf (git rev-parse --show-toplevel)) return (Split-Path -Leaf (git rev-parse --show-toplevel))
} }
function Get-OriginRemoteTarget {
$url = (git remote get-url origin 2>$null)
if (-not $url) { return $null }
$lower = $url.ToLower()
if ($lower -match 'kalinamall') { return 'kalinamall' }
if ($lower -match 'papatramp') { return 'home' }
if ($lower -match 'github\.com') { return 'github' }
return $null
}
function Set-Remote { function Set-Remote {
param( param(
[string]$Name, [string]$Name,
[string]$Url [string]$Url
) )
$existing = git remote 2>$null $existing = @(git remote 2>$null)
$has = $existing -contains $Name $has = $existing -contains $Name
if ($WhatIf) { if ($WhatIf) {
@@ -60,9 +87,19 @@ function Set-Remote {
return return
} }
if ($existing -contains 'origin') {
$originTarget = Get-OriginRemoteTarget
if ($originTarget -eq $Name) {
git remote rename origin $Name
git remote set-url $Name $Url
Write-Ok "remote origin renamed to $Name -> $Url"
return
}
}
$legacy = @{ $legacy = @{
home = @('gitea', 'papatramp', 'origin-home') home = @('gitea', 'papatramp', 'origin-home')
github = @('origin') github = @()
kalinamall = @('gitea-kalinamall', 'kalina') kalinamall = @('gitea-kalinamall', 'kalina')
} }
foreach ($old in $legacy[$Name]) { foreach ($old in $legacy[$Name]) {
@@ -81,16 +118,14 @@ function Set-Remote {
Test-GitRepo Test-GitRepo
$repoName = Get-RepoName -Name $Repo $repoName = Get-RepoName -Name $Repo
$homeUrl = "ssh://git@git.papatramp.lan:2222/${Owner}/${repoName}.git" $homeUrl = "ssh://git@git.papatramp.ru:2222/${Owner}/${repoName}.git"
$kalinamallUrl = "ssh://git@git.kalinamall.lan:2222/${Owner}/${repoName}.git" $kalinamallUrl = "ssh://git@git.kalinamall.ru:2222/${Owner}/${repoName}.git"
$githubUrl = "git@github.com:${GithubOrg}/${repoName}.git" $githubUrl = "git@github.com:${GithubOrg}/${repoName}.git"
Write-Step "Repo: $repoName" Write-Step "Repo: $repoName"
Set-Remote -Name 'home' -Url $homeUrl Set-Remote -Name 'home' -Url $homeUrl
Set-Remote -Name 'kalinamall' -Url $kalinamallUrl
Set-Remote -Name 'github' -Url $githubUrl Set-Remote -Name 'github' -Url $githubUrl
if (-not $SkipKalinamall) {
Set-Remote -Name 'kalinamall' -Url $kalinamallUrl
}
Write-Host '' Write-Host ''
Write-Host 'Remotes:' -ForegroundColor Magenta Write-Host 'Remotes:' -ForegroundColor Magenta
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env bash
# Стандартные git remote: home (papatramp), kalinamall, github (PTah).
set -euo pipefail
OWNER="${OWNER:-PapaTramp}"
GITHUB_ORG="${GITHUB_ORG:-PTah}"
REPO="${REPO:-}"
WHAT_IF="${WHAT_IF:-0}"
log_step() { printf '[*] %s\n' "$1"; }
log_ok() { printf '[+] %s\n' "$1"; }
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo 'Run inside a git repository or set REPO.' >&2
exit 1
fi
repo_name_from_url() {
local url="$1"
if [[ "$url" =~ /([^/]+)(\.git)?/?$ ]]; then
echo "${BASH_REMATCH[1]}"
fi
}
repo_name="${REPO:-}"
if [[ -z "$repo_name" ]]; then
for remote in kalinamall home github origin; do
if url="$(git remote get-url "$remote" 2>/dev/null)"; then
repo_name="$(repo_name_from_url "$url")"
[[ -n "$repo_name" ]] && break
fi
done
fi
repo_name="${repo_name:-$(basename "$(git rev-parse --show-toplevel)")}"
home_url="ssh://git@git.papatramp.ru:2222/${OWNER}/${repo_name}.git"
kalinamall_url="ssh://git@git.kalinamall.ru:2222/${OWNER}/${repo_name}.git"
github_url="git@github.com:${GITHUB_ORG}/${repo_name}.git"
origin_remote_target() {
local url
url="$(git remote get-url origin 2>/dev/null | tr '[:upper:]' '[:lower:]' || true)"
[[ -z "$url" ]] && return 0
if [[ "$url" == *kalinamall* ]]; then echo kalinamall; return 0; fi
if [[ "$url" == *papatramp* ]]; then echo home; return 0; fi
if [[ "$url" == *github.com* ]]; then echo github; return 0; fi
}
set_remote() {
local name="$1"
local url="$2"
local existing current old origin_target
if [[ "$WHAT_IF" == '1' ]]; then
log_step "WhatIf: remote $name -> $url"
return 0
fi
if git remote | grep -Fxq "$name"; then
current="$(git remote get-url "$name" | tr -d '\r\n')"
if [[ "$current" == "$url" ]]; then
log_ok "remote $name OK"
return 0
fi
git remote set-url "$name" "$url"
log_ok "remote $name updated -> $url"
return 0
fi
if git remote | grep -Fxq origin; then
origin_target="$(origin_remote_target || true)"
if [[ "$origin_target" == "$name" ]]; then
git remote rename origin "$name"
git remote set-url "$name" "$url"
log_ok "remote origin renamed to $name -> $url"
return 0
fi
fi
case "$name" in
home) legacy=(gitea papatramp origin-home) ;;
github) legacy=() ;;
kalinamall) legacy=(gitea-kalinamall kalina) ;;
*) legacy=() ;;
esac
for old in "${legacy[@]}"; do
if git remote | grep -Fxq "$old"; then
git remote rename "$old" "$name"
git remote set-url "$name" "$url"
log_ok "remote $old renamed to $name -> $url"
return 0
fi
done
git remote add "$name" "$url"
log_ok "remote $name added -> $url"
}
log_step "Repo: $repo_name"
set_remote home "$home_url"
set_remote kalinamall "$kalinamall_url"
set_remote github "$github_url"
printf '\n'
git remote -v
+192
View File
@@ -0,0 +1,192 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Генерирует SSH-ключи и ~/.ssh/config для Git-хостов из local/git-ssh-hosts.conf.
#>
[CmdletBinding()]
param(
[string]$ConfigDir = "$HOME\CursorRules\local",
[string]$HostsConfig = '',
[switch]$WhatIf
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Write-Step([string]$Message) { Write-Host "[*] $Message" -ForegroundColor Cyan }
function Write-Ok([string]$Message) { Write-Host "[+] $Message" -ForegroundColor Green }
function Write-Warn([string]$Message) { Write-Host "[!] $Message" -ForegroundColor Yellow }
function Read-KeyValueFile {
param([string]$Path)
$data = @{}
if (-not (Test-Path -LiteralPath $Path)) { return $data }
Get-Content -LiteralPath $Path | ForEach-Object {
if ($_ -match '^([^#=]+)=(.*)$') {
$data[$Matches[1].Trim()] = $Matches[2].Trim()
}
}
return $data
}
function Read-GitSshHostsConfig {
param([string]$Path)
$profiles = @{}
$hosts = @{}
$currentProfile = $null
$currentHost = $null
Get-Content -LiteralPath $Path | ForEach-Object {
$line = $_.Trim()
if (-not $line -or $line.StartsWith('#')) { return }
if ($line -match '^\[profile:(.+)\]$') {
$currentProfile = $Matches[1]
$currentHost = $null
$profiles[$currentProfile] = @{}
return
}
if ($line -match '^\[host:(.+)\]$') {
$currentHost = $Matches[1]
$currentProfile = $null
$hosts[$currentHost] = @{ Name = $currentHost }
return
}
if ($line -match '^([^=]+)=(.*)$') {
$key = $Matches[1].Trim()
$value = $Matches[2].Trim()
if ($currentHost) { $hosts[$currentHost][$key] = $value }
elseif ($currentProfile) { $profiles[$currentProfile][$key] = $value }
}
}
return @{ Profiles = $profiles; Hosts = $hosts }
}
function Get-SshConfigBlock {
param(
[string]$HostAlias,
[hashtable]$HostEntry,
[string]$IdentityFile
)
@(
"# BEGIN Setup-SshAccess:$HostAlias"
"Host $HostAlias"
" HostName $($HostEntry.HostName)"
" User $($HostEntry.User)"
" Port $($HostEntry.Port)"
" IdentityFile $IdentityFile"
" IdentitiesOnly yes"
" AddKeysToAgent yes"
" StrictHostKeyChecking accept-new"
"# END Setup-SshAccess:$HostAlias"
) -join "`n"
}
function Update-SshConfigText {
param(
[string]$ExistingText,
[string]$HostAlias,
[string]$Block
)
$begin = "# BEGIN Setup-SshAccess:$HostAlias"
$end = "# END Setup-SshAccess:$HostAlias"
$existing = $ExistingText
$pattern = "(?ms)^$([regex]::Escape($begin)).*?$([regex]::Escape($end))\r?\n?"
if ($existing -match $pattern) {
return ($existing -replace $pattern, ($Block + "`n"))
}
if ($existing -and -not $existing.EndsWith("`n")) {
$existing += "`n"
}
return $existing + $Block + "`n"
}
if (-not $HostsConfig) {
$HostsConfig = Join-Path $ConfigDir 'git-ssh-hosts.conf'
}
if (-not (Test-Path -LiteralPath $HostsConfig)) {
throw "Config not found: $HostsConfig"
}
$parsed = Read-GitSshHostsConfig -Path $HostsConfig
$sshDir = Join-Path $HOME '.ssh'
$sshConfigPath = Join-Path $sshDir 'config'
if (-not $WhatIf) {
New-Item -ItemType Directory -Path $sshDir -Force | Out-Null
}
$configText = if (Test-Path -LiteralPath $sshConfigPath) {
Get-Content -LiteralPath $sshConfigPath -Raw
} else {
''
}
$profileKeys = @{}
foreach ($profileName in $parsed.Profiles.Keys) {
$profile = $parsed.Profiles[$profileName]
$keyName = $profile.KeyName
if (-not $keyName -or $profileKeys.ContainsKey($keyName)) { continue }
$keyPath = Join-Path $sshDir $keyName
$comment = if ($profile.KeyComment) { $profile.KeyComment } else { $keyName }
if (-not (Test-Path -LiteralPath $keyPath)) {
Write-Step "Generating $keyName"
if ($WhatIf) {
Write-Warn "WhatIf: ssh-keygen -t ed25519 -f $keyPath"
}
else {
& ssh-keygen -t ed25519 -f $keyPath -N '""' -C $comment -q
Write-Ok "key $keyName created"
}
}
else {
Write-Ok "key $keyName exists"
}
$profileKeys[$keyName] = $profile
}
foreach ($hostAlias in ($parsed.Hosts.Keys | Sort-Object)) {
$hostEntry = $parsed.Hosts[$hostAlias]
$profileName = $hostEntry.Profile
if (-not $profileName -or -not $parsed.Profiles.ContainsKey($profileName)) {
throw "Host ${hostAlias}: unknown profile $profileName"
}
$profile = $parsed.Profiles[$profileName]
$identity = "~/.ssh/$($profile.KeyName)"
$block = Get-SshConfigBlock -HostAlias $hostAlias -HostEntry $hostEntry -IdentityFile $identity
if ($WhatIf) {
Write-Step "WhatIf: ssh config block for $hostAlias"
continue
}
$configText = Update-SshConfigText -ExistingText $configText -HostAlias $hostAlias -Block $block
Write-Ok "ssh config: $hostAlias"
}
if (-not $WhatIf) {
$utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText($sshConfigPath, $configText.TrimEnd() + "`n", $utf8NoBom)
Get-Service ssh-agent -ErrorAction SilentlyContinue | Where-Object { $_.Status -ne 'Running' } |
ForEach-Object { Start-Service ssh-agent -ErrorAction SilentlyContinue | Out-Null }
foreach ($keyName in $profileKeys.Keys) {
$keyPath = Join-Path $sshDir $keyName
if (Test-Path -LiteralPath $keyPath) {
try { ssh-add $keyPath 2>$null | Out-Null } catch { }
}
}
}
Write-Ok 'SSH setup complete'
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env bash
# Настройка git на машине: user, SSH, Gitea keys, clone/update Rules.
set -euo pipefail
ROOT="${ROOT:?ROOT is required}"
RULES_DEST="${RULES_DEST:-$HOME/CursorRules}"
CLONE_URL="${CLONE_URL:-ssh://git@git.kalinamall.ru:2222/PapaTramp/Rules.git}"
HTTPS_CLONE_URL="${HTTPS_CLONE_URL:-https://git.kalinamall.ru/PapaTramp/Rules.git}"
SKIP_CLONE="${SKIP_CLONE:-0}"
SKIP_PROFILE="${SKIP_PROFILE:-0}"
SKIP_GIT_SETUP="${SKIP_GIT_SETUP:-0}"
WHAT_IF="${WHAT_IF:-0}"
log_step() { printf '[*] %s\n' "$1"; }
log_ok() { printf '[+] %s\n' "$1"; }
log_warn() { printf '[!] %s\n' "$1"; }
CONFIG_DIR="$ROOT/local"
[[ -d "$CONFIG_DIR" ]] || { echo "Bootstrap config not found: $CONFIG_DIR" >&2; exit 1; }
test_machine_git_ready() {
local hosts_config="$CONFIG_DIR/git-ssh-hosts.conf"
local ssh_config="$HOME/.ssh/config"
[[ -f "$hosts_config" && -f "$ssh_config" ]] || return 1
grep -q '^Host git.kalinamall.ru$' "$ssh_config" || return 1
local line current_profile='' key_name
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%%#*}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue
if [[ "$line" =~ ^\[profile:(.+)\]$ ]]; then
current_profile="${BASH_REMATCH[1]}"
continue
fi
if [[ "$line" =~ ^\[host: ]]; then
current_profile=''
continue
fi
if [[ "$line" == KeyName=* && -n "$current_profile" ]]; then
key_name="${line#KeyName=}"
[[ -f "$HOME/.ssh/$key_name" ]] || return 1
fi
done < "$hosts_config"
return 0
}
ensure_rules_repository() {
if [[ -d "$RULES_DEST/.git" ]]; then
return 0
fi
if [[ -e "$RULES_DEST" ]]; then
local backup="${RULES_DEST}.bak-$(date +%Y%m%d-%H%M%S)"
log_warn "Replacing non-git folder: $RULES_DEST -> $backup"
if [[ "$WHAT_IF" != '1' ]]; then
mv "$RULES_DEST" "$backup"
fi
fi
log_step "Cloning Rules via SSH: $CLONE_URL"
if [[ "$WHAT_IF" == '1' ]]; then
log_step "WhatIf: clone -> $RULES_DEST"
return 0
fi
if git clone --depth 1 "$CLONE_URL" "$RULES_DEST" 2>/dev/null; then
log_ok "Cloned to $RULES_DEST"
return 0
fi
log_warn 'SSH clone failed - trying HTTPS (enter Gitea login once)'
git clone --depth 1 "$HTTPS_CLONE_URL" "$RULES_DEST"
log_ok "Cloned via HTTPS to $RULES_DEST"
}
ensure_init_cursor_profile() {
local hook="source \"$RULES_DEST/init-cursor.sh\""
local profile
for profile in "$HOME/.bashrc" "$HOME/.zshrc"; do
[[ -f "$profile" ]] || continue
if [[ "$WHAT_IF" == '1' ]]; then
log_step "WhatIf: profile hook -> $profile"
continue
fi
if ! grep -Fq "$hook" "$profile" 2>/dev/null; then
printf '\n%s\n' "$hook" >> "$profile"
log_ok "Profile updated: $profile"
fi
done
}
git_ready=0
repo_ready=0
test_machine_git_ready && git_ready=1
[[ -d "$RULES_DEST/.git" ]] && repo_ready=1
if [[ "$git_ready" -eq 0 && "$SKIP_GIT_SETUP" != '1' ]]; then
log_step 'Machine bootstrap: git + SSH'
if [[ -f "$CONFIG_DIR/git-user.conf" ]]; then
while IFS= read -r kv; do
key="${kv%%=*}"
value="${kv#*=}"
case "$key" in
UserName) git config --global user.name "$value"; log_ok "git user.name = $value" ;;
UserEmail) git config --global user.email "$value"; log_ok "git user.email = $value" ;;
esac
done < <(grep -v '^#' "$CONFIG_DIR/git-user.conf" | grep '=' || true)
fi
export CONFIG_DIR WHAT_IF
bash "$ROOT/scripts/setup-git-ssh.sh"
bash "$ROOT/scripts/register-gitea-ssh-keys.sh"
log_step 'Testing git@git.kalinamall.ru'
ssh -T -o BatchMode=yes -o ConnectTimeout=10 git@git.kalinamall.ru || true
elif [[ "$git_ready" -eq 1 ]]; then
log_ok 'Git SSH already configured'
fi
if [[ "$SKIP_CLONE" != '1' && "$repo_ready" -eq 0 ]]; then
ensure_rules_repository
elif [[ "$repo_ready" -eq 1 ]]; then
log_ok "CursorRules repo OK: $RULES_DEST"
fi
if [[ "$SKIP_PROFILE" != '1' ]]; then
ensure_init_cursor_profile
fi
log_ok 'Machine bootstrap complete'
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env bash
# Регистрирует публичные SSH-ключи в Gitea через API.
set -euo pipefail
CONFIG_DIR="${CONFIG_DIR:-$HOME/CursorRules/local}"
HOSTS_CONFIG="${HOSTS_CONFIG:-$CONFIG_DIR/git-ssh-hosts.conf}"
WHAT_IF="${WHAT_IF:-0}"
log_step() { printf '[*] %s\n' "$1"; }
log_ok() { printf '[+] %s\n' "$1"; }
log_warn() { printf '[!] %s\n' "$1"; }
if [[ ! -f "$HOSTS_CONFIG" ]]; then
echo "Config not found: $HOSTS_CONFIG" >&2
exit 1
fi
read_kv_file() {
local file="$1"
local line key value
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*# ]] && continue
[[ "$line" != *=* ]] && continue
key="${line%%=*}"
value="${line#*=}"
key="${key%"${key##*[![:space:]]}"}"
value="${value#"${value%%[![:space:]]*}"}"
printf '%s=%s\n' "$key" "$value"
done < "$file"
}
declare -A PROFILE_KEYNAME PROFILE_GITEA
current_section=''
current_name=''
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%%#*}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue
if [[ "$line" =~ ^\[profile:(.+)\]$ ]]; then
current_section='profile'
current_name="${BASH_REMATCH[1]}"
continue
fi
if [[ "$line" =~ ^\[host: ]]; then
current_section=''
continue
fi
[[ "$line" != *=* || "$current_section" != 'profile' ]] && continue
key="${line%%=*}"
value="${line#*=}"
key="${key%"${key##*[![:space:]]}"}"
value="${value#"${value%%[![:space:]]*}"}"
case "$key" in
KeyName) PROFILE_KEYNAME["$current_name"]="$value" ;;
GiteaConfig) PROFILE_GITEA["$current_name"]="$value" ;;
esac
done < "$HOSTS_CONFIG"
SSH_DIR="$HOME/.ssh"
MACHINE="$(hostname -s 2>/dev/null || hostname)"
declare -A REGISTERED
register_gitea_key() {
local cfg_file="$1"
local pub_path="$2"
local title="$3"
declare -A CFG=()
local kv key value
while IFS= read -r kv; do
key="${kv%%=*}"
value="${kv#*=}"
CFG["$key"]="$value"
done < <(read_kv_file "$cfg_file")
if [[ -z "${CFG[GiteaApiPassword]:-}" ]]; then
log_warn "$title : GiteaApiPassword empty — add key manually in Gitea UI"
cat "$pub_path"
return 0
fi
local base="${CFG[GiteaApiUrl]%/}"
local auth user pass pub body response
user="${CFG[GiteaApiUser]}"
pass="${CFG[GiteaApiPassword]}"
auth="$(printf '%s:%s' "$user" "$pass" | base64 -w0 2>/dev/null || printf '%s:%s' "$user" "$pass" | base64)"
pub="$(tr -d '\r\n' < "$pub_path")"
response="$(curl -fsS -H "Authorization: Basic $auth" "$base/api/v1/user/keys" 2>/dev/null || true)"
if [[ -n "$response" ]] && printf '%s' "$response" | grep -Fq "$pub"; then
log_ok "$title : key already registered"
return 0
fi
body="$(printf '{"title":"%s","key":"%s"}' "$title" "$pub")"
if [[ "$WHAT_IF" == '1' ]]; then
log_step "WhatIf: POST $base/api/v1/user/keys ($title)"
return 0
fi
curl -fsS -X POST -H "Authorization: Basic $auth" -H 'Content-Type: application/json' \
-d "$body" "$base/api/v1/user/keys" >/dev/null
log_ok "$title : registered"
}
for profile in "${!PROFILE_GITEA[@]}"; do
gitea_config="${PROFILE_GITEA[$profile]}"
[[ -z "$gitea_config" ]] && continue
key_name="${PROFILE_KEYNAME[$profile]}"
[[ -z "$key_name" || -n "${REGISTERED[$key_name]:-}" ]] && continue
REGISTERED["$key_name"]=1
gitea_path="$CONFIG_DIR/$gitea_config"
pub_path="$SSH_DIR/$key_name.pub"
if [[ ! -f "$gitea_path" ]]; then
log_warn "Gitea config not found: $gitea_path"
continue
fi
if [[ ! -f "$pub_path" ]]; then
log_warn "Public key not found: $pub_path (run setup-git-ssh.sh first)"
continue
fi
title="$MACHINE-$key_name"
log_step "Registering $key_name"
register_gitea_key "$gitea_path" "$pub_path" "$title"
done
log_ok 'Gitea SSH key registration done'
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env bash
# Генерирует SSH-ключи и ~/.ssh/config для Git-хостов из local/git-ssh-hosts.conf.
set -euo pipefail
CONFIG_DIR="${CONFIG_DIR:-$HOME/CursorRules/local}"
HOSTS_CONFIG="${HOSTS_CONFIG:-$CONFIG_DIR/git-ssh-hosts.conf}"
WHAT_IF="${WHAT_IF:-0}"
log_step() { printf '[*] %s\n' "$1"; }
log_ok() { printf '[+] %s\n' "$1"; }
log_warn() { printf '[!] %s\n' "$1"; }
if [[ ! -f "$HOSTS_CONFIG" ]]; then
echo "Config not found: $HOSTS_CONFIG" >&2
exit 1
fi
SSH_DIR="$HOME/.ssh"
SSH_CONFIG="$SSH_DIR/config"
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"
declare -A PROFILE_KEYNAME PROFILE_COMMENT PROFILE_GITEA
declare -A HOST_HOSTNAME HOST_PORT HOST_USER HOST_PROFILE
current_section=''
current_name=''
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%%#*}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue
if [[ "$line" =~ ^\[profile:(.+)\]$ ]]; then
current_section='profile'
current_name="${BASH_REMATCH[1]}"
continue
fi
if [[ "$line" =~ ^\[host:(.+)\]$ ]]; then
current_section='host'
current_name="${BASH_REMATCH[1]}"
HOST_HOSTNAME["$current_name"]=''
continue
fi
if [[ "$line" != *=* ]]; then
continue
fi
key="${line%%=*}"
value="${line#*=}"
key="${key%"${key##*[![:space:]]}"}"
value="${value#"${value%%[![:space:]]*}"}"
if [[ "$current_section" == 'profile' ]]; then
case "$key" in
KeyName) PROFILE_KEYNAME["$current_name"]="$value" ;;
KeyComment) PROFILE_COMMENT["$current_name"]="$value" ;;
GiteaConfig) PROFILE_GITEA["$current_name"]="$value" ;;
esac
elif [[ "$current_section" == 'host' ]]; then
case "$key" in
HostName) HOST_HOSTNAME["$current_name"]="$value" ;;
Port) HOST_PORT["$current_name"]="$value" ;;
User) HOST_USER["$current_name"]="$value" ;;
Profile) HOST_PROFILE["$current_name"]="$value" ;;
esac
fi
done < "$HOSTS_CONFIG"
declare -A SEEN_KEYS
for profile in "${!PROFILE_KEYNAME[@]}"; do
key_name="${PROFILE_KEYNAME[$profile]}"
[[ -z "$key_name" || -n "${SEEN_KEYS[$key_name]:-}" ]] && continue
SEEN_KEYS["$key_name"]=1
key_path="$SSH_DIR/$key_name"
comment="${PROFILE_COMMENT[$profile]:-$key_name}"
if [[ ! -f "$key_path" ]]; then
log_step "Generating $key_name"
if [[ "$WHAT_IF" == '1' ]]; then
log_warn "WhatIf: ssh-keygen -t ed25519 -f $key_path"
else
ssh-keygen -t ed25519 -f "$key_path" -N '' -C "$comment" -q
chmod 600 "$key_path"
log_ok "key $key_name created"
fi
else
log_ok "key $key_name exists"
fi
done
update_ssh_block() {
local host_alias="$1"
local block="$2"
local begin="# BEGIN Setup-SshAccess:$host_alias"
local end="# END Setup-SshAccess:$host_alias"
local tmp
tmp="$(mktemp)"
if [[ -f "$SSH_CONFIG" ]]; then
awk -v begin="$begin" -v end="$end" -v block="$block" '
$0 == begin { skip=1; next }
$0 == end { skip=0; next }
skip { next }
{ print }
END {
if (block != "") {
print block
}
}
' block="$block" "$SSH_CONFIG" > "$tmp"
else
printf '%s\n' "$block" > "$tmp"
fi
if [[ "$WHAT_IF" != '1' ]]; then
mv "$tmp" "$SSH_CONFIG"
chmod 600 "$SSH_CONFIG"
else
rm -f "$tmp"
fi
}
for host_alias in $(printf '%s\n' "${!HOST_HOSTNAME[@]}" | sort); do
profile="${HOST_PROFILE[$host_alias]:-}"
key_name="${PROFILE_KEYNAME[$profile]:-}"
if [[ -z "$profile" || -z "$key_name" ]]; then
echo "Host $host_alias: unknown profile" >&2
exit 1
fi
block="# BEGIN Setup-SshAccess:$host_alias
Host $host_alias
HostName ${HOST_HOSTNAME[$host_alias]}
User ${HOST_USER[$host_alias]}
Port ${HOST_PORT[$host_alias]}
IdentityFile ~/.ssh/$key_name
IdentitiesOnly yes
AddKeysToAgent yes
StrictHostKeyChecking accept-new
# END Setup-SshAccess:$host_alias"
if [[ "$WHAT_IF" == '1' ]]; then
log_step "WhatIf: ssh config block for $host_alias"
else
update_ssh_block "$host_alias" "$block"
log_ok "ssh config: $host_alias"
fi
done
if [[ "$WHAT_IF" != '1' ]]; then
eval "$(ssh-agent -s)" >/dev/null
for key_name in "${!SEEN_KEYS[@]}"; do
[[ -f "$SSH_DIR/$key_name" ]] && ssh-add "$SSH_DIR/$key_name" >/dev/null 2>&1 || true
done
fi
log_ok 'SSH setup complete'