# 8. 개발자 가이드 (Developer Guide) > **문서 버전**: 1.0 > **최종 업데이트**: 2025-11-15 --- ## 8.1 개발 환경 설정 ### 8.1.1 개발 도구 설치 #### Visual Studio Code PowerShell 개발을 위한 권장 IDE입니다. **설치**: - [VS Code 다운로드](https://code.visualstudio.com/) **필수 확장**: - PowerShell Extension (`ms-vscode.powershell`) - GitLens (`eamodio.gitlens`) **선택 확장**: - Code Spell Checker - Better Comments --- #### PowerShell Extension 설정 `.vscode/settings.json`: ```json { "powershell.codeFormatting.preset": "OTBS", "powershell.scriptAnalysis.enable": true, "powershell.integratedConsole.showOnStartup": false, "files.encoding": "utf8", "files.eol": "\n" } ``` --- ### 8.1.2 로컬 개발 환경 구축 #### Repository Clone ```bash git clone git@github.com:planitaicojp/poster-ai-create-psd.git cd poster-ai-create-psd ``` #### 개발용 설정 파일 작성 `Create-PSD-config-dev.ps1`: ```powershell # 개발 환경 설정 $global:TemplateRootPath = "E:\dev\psd_template" # 개발용 템플릿 $global:MachineRootPath = "E:\dev\machine" # 테스트용 머신 데이터 $global:WorkingRootPath = "E:\dev\working" # 개발 작업 디렉토리 $global:DebugMode = $true # 디버그 모드 활성화 $global:LogLevel = "DEBUG" # 상세 로그 ``` #### 테스트 데이터 준비 최소한의 테스트 데이터로 개발 환경 구성: ``` E:\dev\ ├── psd_template\ │ └── vertical\ │ └── renewalOpen\ │ └── machine_1\ │ └── ... ├── machine\ │ └── 1\ │ ├── main.png │ └── machine-text\ │ └── gtwcs.png └── working\ ``` --- ### 8.1.3 디버그 모드 사용법 #### 디버그 모드 활성화 ```powershell # Create-PSD-config.ps1에서 $global:DebugMode = $true ``` #### 디버그 출력 예시 ``` [DEBUG] Loading configuration from: Create-PSD-config.ps1 [DEBUG] Template root path: E:\dev\psd_template [DEBUG] Loading Aspose.PSD DLL: E:\dev\aspose-packages\Aspose.PSD.dll [DEBUG] DLL loaded successfully [DEBUG] Applying license: E:\dev\Aspose.PSD.NET.lic [DEBUG] License applied: True [DEBUG] Searching for template: orientation=vertical, logotype=renewalOpen, count=1 [DEBUG] Template found: E:\dev\psd_template\vertical\renewalOpen\... [DEBUG] Loading PSD document... [DEBUG] PSD loaded: 3840x2160, 72 layers ``` #### VS Code에서 디버깅 `launch.json`: ```json { "version": "0.2.0", "configurations": [ { "name": "PowerShell: Launch Create-PSD", "type": "PowerShell", "request": "launch", "script": "${workspaceFolder}/Create-PSD.ps1", "args": ["-machineIds", "1", "-orientation", "vertical"] } ] } ``` --- ## 8.2 코드 구조 ### 8.2.1 코드 구조 및 모듈화 #### 모듈 분리 원칙 | 파일 | 역할 | 의존성 | |------|------|--------| | `Create-PSD.ps1` | 오케스트레이션 | 모든 모듈 | | `PSD-Functions.ps1` | 비즈니스 로직 | Aspose.PSD, Utilities | | `PSD-Utilities.ps1` | 유틸리티 | 없음 (독립) | | `Load-AsposePSD.ps1` | 라이브러리 로더 | Aspose.PSD DLL | | `Create-PSD-config.ps1` | 설정 | 없음 | #### 함수 명명 규칙 PowerShell Verb-Noun 규칙: ```powershell # 좋은 예 Get-TemplateMetadata Set-WorkingDirectory Find-MachineNameLayer Copy-MachineImages # 나쁜 예 TemplateMetadata SetDir FindLayer ``` --- ### 8.2.2 에러 처리 전략 #### 일관된 에러 처리 패턴 ```powershell function Process-Template { param($templatePath) try { # 파라미터 검증 if (-not (Test-Path $templatePath)) { throw "Template not found: $templatePath" } # 메인 로직 $psd = [Aspose.PSD.Image]::Load($templatePath) # 성공 로그 Write-Log "Template loaded successfully" -Level "INFO" return $psd } catch { # 에러 로그 Write-Log "Failed to load template: $_" -Level "ERROR" # JSON 모드에서는 예외 재발생 if ($global:JsonMode) { throw } return $null } finally { # 정리 작업 (있는 경우) } } ``` #### 에러 타입 분류 | 타입 | 설명 | 처리 방법 | |------|------|----------| | `ValidationError` | 파라미터 검증 실패 | 즉시 중단, 에러 메시지 | | `TemplateNotFoundError` | 템플릿 없음 | 중단, 사용 가능한 템플릿 안내 | | `DataError` | 데이터 파일 오류 | 해당 항목 건너뛰기 또는 중단 | | `AsposePsdError` | Aspose.PSD 오류 | 로그 및 중단 | --- ### 8.2.3 코드 스타일 가이드 #### 들여쓰기 및 포맷 ```powershell # 4 스페이스 들여쓰기 function Get-Example { param($value) if ($value -gt 10) { Write-Host "Greater than 10" } else { Write-Host "Less or equal" } } ``` #### 주석 작성 ```powershell <# .SYNOPSIS 템플릿 메타데이터를 로드합니다. .DESCRIPTION 템플릿 PSD 파일과 동일한 이름의 JSON 메타데이터 파일을 로드합니다. 파일이 없으면 기본값으로 자동 생성합니다. .PARAMETER TemplatePath 템플릿 PSD 파일의 전체 경로 .PARAMETER WorkingDirectory 작업 디렉토리 경로 .EXAMPLE Get-TemplateMetadata -TemplatePath "template.psd" -WorkingDirectory "/data/working" .OUTPUTS Hashtable: {ImageFilename, JsonPath, AutoCreated} #> function Get-TemplateMetadata { param( [Parameter(Mandatory=$true)] [string]$TemplatePath, [Parameter(Mandatory=$true)] [string]$WorkingDirectory ) # 구현... } ``` #### 변수 명명 ```powershell # 명확하고 설명적인 이름 사용 $machineImagePath # Good $mip # Bad # Boolean은 Is/Has/Should 접두사 $isValid # Good $valid # Acceptable ``` --- ## 8.3 기능 확장 가이드 ### 8.3.1 새로운 기능 추가 절차 #### 1. 요구사항 정의 - 기능 목적 명확화 - 입력/출력 정의 - Edge cases 식별 #### 2. 함수 설계 ```powershell <# .SYNOPSIS 새로운 기능에 대한 간단한 설명 #> function New-Feature { param( [Parameter(Mandatory=$true)] [string]$RequiredParam, [Parameter(Mandatory=$false)] [string]$OptionalParam = "default" ) try { # 파라미터 검증 # 메인 로직 # 결과 반환 } catch { Write-Log "Error in New-Feature: $_" -Level "ERROR" throw } } ``` #### 3. 테스트 작성 (선택) ```powershell # Tests/New-Feature.Tests.ps1 Describe "New-Feature" { It "Should process valid input" { $result = New-Feature -RequiredParam "test" $result | Should -Not -BeNullOrEmpty } It "Should handle invalid input" { { New-Feature -RequiredParam "" } | Should -Throw } } ``` #### 4. 통합 - `PSD-Functions.ps1`에 추가 - `Create-PSD.ps1`에서 호출 - 문서 업데이트 --- ### 8.3.2 함수 작성 가이드라인 #### 단일 책임 원칙 ```powershell # Good: 하나의 책임만 수행 function Get-ImageDimensions { param($imagePath) $image = [System.Drawing.Image]::FromFile($imagePath) return @{Width = $image.Width; Height = $image.Height} } # Bad: 여러 책임 function ProcessImage { # 이미지 로드 + 크기 확인 + 스케일 + 저장 + 로그 } ``` #### 명확한 반환값 ```powershell # Good: 명확한 타입 반환 function Get-Result { return @{ Success = $true Data = $result } } # Bad: 불명확한 반환 function Get-Result { if ($success) { return $data } else { return $false } # 타입 불일치 } ``` --- ### 8.3.3 문서 업데이트 새로운 기능 추가 시 업데이트 필요 문서: - [ ] README.md (기능 개요) - [ ] doc_6_core_features.md (기능 상세) - [ ] doc_7_api_reference.md (API 레퍼런스) - [ ] doc_8_developer_guide.md (개발 가이드, 필요시) --- ## 8.4 Git 워크플로우 ### 8.4.1 브랜치 전략 ``` main (프로덕션) └─ develop (개발) ├─ feature/new-feature-name ├─ bugfix/issue-123 └─ hotfix/critical-bug ``` #### 브랜치 명명 규칙 ```bash # 새 기능 git checkout -b feature/machine-name-layer-replacement # 버그 수정 git checkout -b bugfix/template-selection-error # 핫픽스 git checkout -b hotfix/license-validation-crash ``` --- ### 8.4.2 커밋 메시지 규칙 #### 형식 ``` :