Files
Groupware/Project/_add_to_project.py

158 lines
5.4 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
C# 프로젝트 파일 자동 업데이트 도구
새로운 파일을 EETGW.csproj에 자동으로 등록합니다.
"""
import re
import os
import sys
from typing import List, Tuple, Optional
class ProjectFileUpdater:
def __init__(self, project_path: str = "EETGW.csproj"):
self.project_path = project_path
self.content = ""
self.load_project()
def load_project(self) -> bool:
"""프로젝트 파일 로드"""
try:
with open(self.project_path, 'r', encoding='utf-8') as f:
self.content = f.read()
return True
except Exception as e:
print(f"❌ 프로젝트 파일을 읽을 수 없습니다: {e}")
return False
def save_project(self) -> bool:
"""프로젝트 파일 저장"""
try:
with open(self.project_path, 'w', encoding='utf-8') as f:
f.write(self.content)
print("✅ 프로젝트 파일이 업데이트되었습니다.")
return True
except Exception as e:
print(f"❌ 프로젝트 파일 저장 실패: {e}")
return False
def is_file_registered(self, file_path: str) -> bool:
"""파일이 이미 등록되어 있는지 확인"""
# Windows 스타일 경로로 변환
windows_path = file_path.replace('/', '\\')
unix_path = file_path.replace('\\', '/')
patterns = [
f'Include="{windows_path}"',
f"Include='{windows_path}'",
f'Include="{unix_path}"',
f"Include='{unix_path}'"
]
return any(pattern in self.content for pattern in patterns)
def find_last_wwwroot_entry(self) -> Optional[Tuple[int, int]]:
"""마지막 wwwroot 관련 항목의 위치 찾기"""
pattern = r'<(?:Content|None) Include="Web\\wwwroot.*?</(?:Content|None)>'
matches = list(re.finditer(pattern, self.content, re.DOTALL))
if matches:
last_match = matches[-1]
return (last_match.start(), last_match.end())
return None
def add_file_to_project(self, file_path: str, file_type: str = "None") -> bool:
"""파일을 프로젝트에 추가"""
# Windows 스타일 경로로 변환
windows_path = file_path.replace('/', '\\')
# 이미 등록된 파일인지 확인
if self.is_file_registered(windows_path):
print(f"⚠️ 파일이 이미 등록되어 있습니다: {windows_path}")
return False
# 새로운 항목 생성
new_entry = f''' <{file_type} Include="{windows_path}">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</{file_type}>'''
# 마지막 wwwroot 항목 찾기
last_entry_pos = self.find_last_wwwroot_entry()
if last_entry_pos:
start_pos, end_pos = last_entry_pos
# 마지막 항목 다음에 새 항목 삽입
self.content = (
self.content[:end_pos] +
'\n' + new_entry +
self.content[end_pos:]
)
print(f"✅ 파일이 프로젝트에 추가되었습니다: {windows_path}")
return True
else:
print("❌ wwwroot 섹션을 찾을 수 없습니다.")
return False
def add_multiple_files(self, files: List[Tuple[str, str]]) -> int:
"""여러 파일을 한 번에 추가"""
added_count = 0
for file_path, file_type in files:
if self.add_file_to_project(file_path, file_type):
added_count += 1
return added_count
def add_react_component_files(component_name: str) -> bool:
"""React 컴포넌트 관련 파일들을 프로젝트에 추가"""
updater = ProjectFileUpdater()
files_to_add = [
(f"Web\\wwwroot\\react\\{component_name}.jsx", "None"),
(f"Web\\wwwroot\\react-{component_name.lower()}.html", "None")
]
added_count = updater.add_multiple_files(files_to_add)
if added_count > 0:
updater.save_project()
print(f"🎉 {component_name} 컴포넌트 관련 {added_count}개 파일이 등록되었습니다!")
return True
else:
print("추가된 파일이 없습니다.")
return False
def add_single_file(file_path: str, file_type: str = "None") -> bool:
"""단일 파일을 프로젝트에 추가"""
updater = ProjectFileUpdater()
if updater.add_file_to_project(file_path, file_type):
updater.save_project()
return True
return False
def main():
"""CLI 메인 함수"""
if len(sys.argv) < 2:
print("사용법:")
print(" python _add_to_project.py <파일경로> [파일타입]")
print(" python _add_to_project.py --react <컴포넌트명>")
print("")
print("예시:")
print(" python _add_to_project.py 'Web\\wwwroot\\react\\MyComponent.jsx'")
print(" python _add_to_project.py --react Dashboard")
sys.exit(1)
if sys.argv[1] == "--react" and len(sys.argv) >= 3:
component_name = sys.argv[2]
add_react_component_files(component_name)
else:
file_path = sys.argv[1]
file_type = sys.argv[2] if len(sys.argv) > 2 else "None"
add_single_file(file_path, file_type)
if __name__ == "__main__":
main()