Powershell은 은근히 멋지다
Source: Dev.to
PowerShell는 더 인기 있는 셸에 비해 종종 간과되지만, 로컬 개발 워크플로우를 간소화할 수 있는 강력한 기능을 제공합니다. 아래는 PowerShell을 사용해 Go 프로젝트용 파일 감시자를 만드는 단계별 가이드이며, 기본 설정부터 백그라운드 작업을 이용한 장기 실행 프로세스 처리까지 다룹니다.
PowerShell란?
PowerShell은 .NET 런타임 위에 구축된 명령줄 셸이자 스크립팅 언어입니다. 일반적인 Unix 셸(예: Bash)이 순수 텍스트를 파이프라인으로 전달하는 것과 달리, PowerShell 파이프라인은 객체를 전달하므로 셸 안에서 보다 풍부한 데이터 조작이 가능합니다.
감시자 디렉터리 설정
# Create a directory for the watcher
mkdir watcher
PowerShell은 항목을 만들기 위해 New-Item cmdlet을 제공하지만, 편의를 위해 mkdir과 같은 일반적인 별칭도 사용할 수 있습니다.
# Navigate into the directory
cd watcher
# Create a placeholder Go source file
ni main.go
# Create the PowerShell script that will perform the watching
ni watcher.ps1
실행 정책 조정
PowerShell의 실행 정책은 스크립트 실행 여부를 결정합니다. 진행하기 전에 RemoteSigned(또는 더 낮은 제한 수준)로 설정되어 있는지 확인하세요.
# View the current policy
Get-ExecutionPolicy
# If needed, set it to RemoteSigned
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
샘플 Go 프로그램
“Hello World”를 출력하는 간단한 Go 프로그램을 만듭니다. watcher 폴더 안에 main.go로 저장합니다.
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
기본 감시자 스크립트 (동기식)
다음 PowerShell 스크립트는 현재 디렉터리(및 하위 디렉터리)의 모든 .go 파일을 감시합니다. 변경이 감지되면 Go 프로그램을 다시 실행합니다.
# watcher.ps1
# Path to the Go file (can be overridden later)
$path = "main.go"
Write-Host 'GoWatcher *Press CTRL+C to quit*'
$dirname = "."
$files = Get-ChildItem $dirname -Filter "*.go" -Recurse
# Initial run
go run $path
# Compute an initial signature (hash) of all Go files
$signature = $files | Get-FileHash -ErrorAction SilentlyContinue |
Sort-Object Path | Out-String
while ($true) {
$current_signature = $files | Get-FileHash -ErrorAction SilentlyContinue |
Sort-Object Path | Out-String
if ($signature -ne $current_signature) {
Write-Host 'File change detected: Restarting...'
go run $path
$signature = $current_signature
}
Start-Sleep -Milliseconds 300
}
스크립트를 실행합니다:
.\watcher.ps1
파일 경로 매개변수 추가
스크립트를 더 유연하게 만들어 Go 파일 경로를 명령줄 인수로 받을 수 있게 합니다.
# watcher.ps1 (updated)
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
$path
)
Write-Host 'GoWatcher *Press CTRL+C to quit*'
$dirname = "."
$files = Get-ChildItem $dirname -Filter "*.go" -Recurse
go run $path
$signature = $files | Get-FileHash -ErrorAction SilentlyContinue |
Sort-Object Path | Out-String
while ($true) {
$current_signature = $files | Get-FileHash -ErrorAction SilentlyContinue |
Sort-Object Path | Out-String
if ($signature -ne $current_signature) {
Write-Host 'File change detected: Restarting...'
go run $path
$signature = $current_signature
}
Start-Sleep -Milliseconds 300
}
경로 인수와 함께 실행합니다:
.\watcher.ps1 -path 'main.go'
백그라운드 작업으로 장기 실행 프로세스 처리
Go 애플리케이션이 웹 서버나 다른 차단 작업을 실행할 경우, 감시자 스크립트가 멈춰버립니다. PowerShell 작업을 사용하면 이러한 프로세스를 비동기적으로 실행할 수 있습니다.
유용한 작업 Cmdlet
# Start a background job
Start-Job -Name GoServer -ScriptBlock { ... }
# Stop a job
Stop-Job -Name GoServer
# Remove a job
Remove-Job -Name GoServer
# Retrieve job output
Receive-Job -Name GoServer
# List jobs
Get-Job -Name GoServer
작업 관리가 포함된 고급 감시자
아래 스크립트는 Go 서버를 백그라운드 작업으로 실행하고, 파일 변경 시 재시작하며, 감시자가 종료될 때 정리 작업을 수행합니다.
# watcher.ps1 (advanced version)
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
$path
)
Write-Host 'GoWatcher *Press CTRL+C to quit*'
$dirname = "."
$jobname = "GoServer"
$binary = "GoApp"
function Start-ServerJob {
# Remove any existing job with the same name
Get-Job -Name $jobname -ErrorAction SilentlyContinue | Remove-Job -Force
# Start a new job that builds and runs the Go binary
$job = Start-Job -Name $jobname -ScriptBlock {
param($path, $dirname, $binary)
Set-Location $dirname
# Build the binary (adjust as needed for your project)
go build -o "bin/$binary.exe" $path
# Execute the binary
& "./bin/$binary.exe"
} -ArgumentList $path, $dirname, $binary
return $job
}
# Gather all Go source files
$files = Get-ChildItem $dirname -Filter "*.go" -Recurse
# Initial launch
$job = Start-ServerJob
# Initial signature
$signature = $files | Get-FileHash -ErrorAction SilentlyContinue |
Sort-Object Path | Out-String
try {
while ($true) {
$current_signature = $files | Get-FileHash -ErrorAction SilentlyContinue |
Sort-Object Path | Out-String
if ($signature -ne $current_signature) {
Write-Host 'File change detected: Restarting...'
# Restart the server job
$job = Start-ServerJob
$signature = $current_signature
}
Start-Sleep -Milliseconds 300
}
}
finally {
# Clean up the background job
Get-Job -Name $jobname -ErrorAction SilentlyContinue | Remove-Job -Force
# Ensure the binary process is terminated
if (Get-Process -Name $binary -ErrorAction SilentlyContinue) {
Stop-Process -Name $binary -Force
}
}
고급 감시자를 같은 방식으로 실행합니다:
.\watcher.ps1 -path 'main.go'
이 스크립트는 이제:
- Builds the Go program into an executable.
- Runs the executable as a background job.
- Detects changes to any
.gofile. - Restarts the background job when changes occur.
- Cleans up resources on termination.
결론
PowerShell의 객체 지향 파이프라인, 내장 별칭, 그리고 강력한 작업 시스템은 파일 감시와 프로세스 관리 같은 개발 작업을 자동화하기에 탁월한 선택입니다. 이러한 기능을 활용하면 외부 유틸리티에 의존하지 않고도 가볍고 크로스‑플랫폼 도구를 만들 수 있습니다.