Skip to content

Commit

Permalink
Merge branch 'feature/ver-diff' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
Sunwood-ai-labs committed May 14, 2024
2 parents eacde96 + 83feb0b commit 1d01017
Show file tree
Hide file tree
Showing 11 changed files with 306 additions and 8 deletions.
4 changes: 3 additions & 1 deletion .SourceSageignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ modules\__pycache__
sourcesage.egg-info
.pytest_cache
dist
build
build
.SourceSageAssets
docs
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,5 @@ SourceSageAssets

.pypirc
temp/
.SourceSageAssets
.Gaiah.md
49 changes: 49 additions & 0 deletions example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@


## 1. `generate_diff_report.py`

### 概要
このスクリプトは、Gitリポジトリ内の最新のリリースと前回のリリースの間の差分を取得し、それをマークダウン形式のレポートに変換します。

### 主な機能
- **`run_command`関数**: 指定されたコマンドを実行し、その出力をキャプチャして表示します。
- **`get_git_diff`関数**: 最新のGitタグを取得し、それと前のタグの間の差分を生成します。
- **`generate_markdown_report`関数**: 差分情報を整理し、マークダウン形式のレポートを生成します。
- **`main`関数**: 全体のプロセスを管理し、実行します。

---

## 2. `get_diff.py`

### 概要
このスクリプトは、現在のGitリポジトリのステージングエリアにある変更を取得し、その差分を表示します。

### 主な機能
- **リポジトリの初期化**: 指定されたパスのGitリポジトリを初期化します。
- **差分の取得**: ステージングエリアにある変更を取得し、それを表示します。

---

## 3. `get_issues.py`

### 概要
このスクリプトは、指定されたGitHubリポジトリから開いているIssueを取得し、そのデータをJSONファイルとして保存します。

### 主な機能
- **GitHub APIの使用**: GitHub APIを利用して、指定されたリポジトリから開いているIssueを取得します。
- **データの保存**: 取得したIssueデータをJSON形式で保存します。

---

## 4. `make_issue_res.py`

### 概要
このスクリプトは、取得したIssueデータを元に、指定されたテンプレートを使用してマークダウンファイルを生成します。

### 主な機能
- **テンプレートの読み込み**: 指定されたテンプレートファイルを読み込みます。
- **マークダウンファイルの生成**: 各Issueに対してテンプレートを適用し、マークダウンファイルを生成します。

---

以上が`example`フォルダ内の各ファイルの日本語解説です。それぞれのスクリプトは、SourceSageプロジェクトの様々な自動化タスクをサポートするために設計されています。
76 changes: 76 additions & 0 deletions example/generate_diff_report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import subprocess
import os
from loguru import logger

def run_command(command):
"""
指定されたコマンドを実行し、出力をキャプチャして表示します。
"""
logger.info(f">>>>>> 実行コマンド: {' '.join(command)}")
result = subprocess.run(command, capture_output=True, text=True, encoding='utf-8')
if result.returncode != 0:
raise Exception(f"コマンドが失敗しました: {result.stderr}")
return result.stdout.strip() # 出力の前後の空白を削除

def get_git_diff():
"""
現在のリリースと前のリリースの間の git diff を取得します。
"""
logger.info("最新の git タグを取得しています...")
run_command(["git", "fetch", "--tags"])

logger.info("最新と前のタグを取得しています...")
tags_output = run_command(["git", "tag", "--sort=-creatordate"])
tags = tags_output.split()

if len(tags) < 2:
raise Exception("比較するタグが十分にありません。")

latest_tag, previous_tag = tags[:2]
logger.success(f"最新タグ: {latest_tag}, 前のタグ: {previous_tag}")

logger.info("git diff を生成しています...")
diff = run_command(["git", "diff", previous_tag, latest_tag])

return diff, latest_tag, previous_tag

def generate_markdown_report(diff, latest_tag, previous_tag):
"""
git diff からマークダウンレポートを生成します。
"""
logger.info("マークダウンレポートを生成しています...")
report_content = f"# Git Diff レポート\n\n"
report_content += f"## バージョン比較\n\n"
report_content += f"**{previous_tag}** と **{latest_tag}** の比較\n\n"
report_content += "## 差分の詳細\n\n"

# ファイル名ごとに差分を整理
file_diffs = {}
current_file = None
for line in diff.split("\n"):
if line.startswith("diff --git"):
current_file = line.split(" ")[-1][2:] # ファイル名を抽出
file_diffs[current_file] = []
elif current_file:
file_diffs[current_file].append(line)

# ファイル名ごとに見出しとコードブロックを生成
for file, lines in file_diffs.items():
report_content += f"### {file}\n\n"
report_content += "```diff\n"
report_content += "\n".join(lines)
report_content += "\n```\n\n"

with open(".SourceSageAssets/git_diff_report.md", "w", encoding='utf8') as file:
file.write(report_content)

logger.success("マークダウンレポートが正常に生成されました!")

def main():
logger.info("git diff レポートの生成を開始します...")
diff, latest_tag, previous_tag = get_git_diff()
generate_markdown_report(diff, latest_tag, previous_tag)
logger.success("プロセスが完了しました。")

if __name__ == "__main__":
main()
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
name='sourcesage',

# パッケージのバージョン
version='4.2.1',
version='4.3.0',

# パッケージに含めるモジュールを自動的に探す
packages=find_packages(),
Expand Down Expand Up @@ -55,5 +55,6 @@
'GitPython',
'requests',
'art',
'termcolor',
],
)
31 changes: 26 additions & 5 deletions sourcesage/cli.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import argparse
from .core import SourceSage
from .modules.ReleaseDiffReportGenerator import GitDiffGenerator, MarkdownReportGenerator
import os
from loguru import logger
import sys
# logger.add(sink=sys.stderr, format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level:<8} | {name}:{line} | {message}")
from art import *

# ログ出力のフォーマットを指定
logger.configure(
handlers=[
{
"sink": sys.stderr,
"format": "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level:<6}</level> | <cyan>{name:<45}:{line:<5}</cyan> | <level>{message}</level>",
"format": "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level:<8}</level> | <cyan>{name:<45}:{line:<5}</cyan> | <level>{message}</level>",
"colorize": True,
}
]
Expand All @@ -21,8 +21,8 @@ def main():
parser.add_argument('--config', help='Path to the configuration file', default='sourcesage.yml')
parser.add_argument('--output', help='Output directory for generated files', default='./')
parser.add_argument('--repo', help='Path to the repository', default='./')
parser.add_argument('--owner', help='Owner of the repository', default='Sunwood-ai-labs') # デフォルト値を設定
parser.add_argument('--repository', help='Name of the repository', default='SourceSage') # デフォルト値を設定
parser.add_argument('--owner', help='Owner of the repository', default='Sunwood-ai-labs')
parser.add_argument('--repository', help='Name of the repository', default='SourceSage')

package_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
default_ignore_file = os.path.join(package_root, 'sourcesage', 'config', '.SourceSageignore')
Expand All @@ -39,10 +39,31 @@ def main():
parser.add_argument('--ignore-file', help='Path to the ignore file', default=ignore_file)
parser.add_argument('--language-map', help='Path to the language map file', default=default_language_map)

# レポート生成用の引数を追加
parser.add_argument('--repo-path', type=str, default="", help='Path to the git repository')
parser.add_argument('--git-fetch-tags', type=str, nargs='+', default=["git", "fetch", "--tags"], help='Command to fetch git tags')
parser.add_argument('--git-tag-sort', type=str, nargs='+', default=["git", "tag", "--sort=-creatordate"], help='Command to sort git tags')
parser.add_argument('--git-diff-command', type=str, nargs='+', default=["git", "diff"], help='Command to generate git diff')
parser.add_argument('--report-title', type=str, default="Git Diff レポート", help='Title of the Markdown report')
parser.add_argument('--report-sections', type=str, nargs='+', default=["version_comparison", "diff_details"], help='Sections to include in the report')
parser.add_argument('--output-path', type=str, default=".SourceSageAssets/git_diff_report.md", help='Path to save the Markdown report')

args = parser.parse_args()

# SourceSageの実行
sourcesage = SourceSage(args.config, args.output, args.repo, args.owner, args.repository, args.ignore_file, args.language_map)
sourcesage.run()

# レポートの生成
logger.info("git diff レポートの生成を開始します...")
git_diff_generator = GitDiffGenerator(args.repo_path, args.git_fetch_tags, args.git_tag_sort, args.git_diff_command)
diff, latest_tag, previous_tag = git_diff_generator.get_git_diff()

markdown_report_generator = MarkdownReportGenerator(diff, latest_tag, previous_tag, args.report_title, args.report_sections, args.output_path)
markdown_report_generator.generate_markdown_report()

logger.success("プロセスが完了しました。")
tprint("!! successfully !!", font="rnd-medium")

if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion sourcesage/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self, output_dir, owner, repository):
self.set_output_dir(output_dir)

def set_output_dir(self, output_dir):
self.SOURCE_SAGE_ASSETS_DIR = os.path.join(output_dir, "SourceSageAssets")
self.SOURCE_SAGE_ASSETS_DIR = os.path.join(output_dir, ".SourceSageAssets")
self.ISSUE_LOG_DIR = os.path.join(self.SOURCE_SAGE_ASSETS_DIR, "ISSUE_LOG")
self.ISSUES_RESOLVE_DIR = os.path.join(self.SOURCE_SAGE_ASSETS_DIR, "ISSUE_WISE/ISSUES_RESOLVE")
self.STAGE_INFO_DIR = os.path.join(self.SOURCE_SAGE_ASSETS_DIR, "COMMIT_CRAFT/STAGE_INFO")
Expand Down
147 changes: 147 additions & 0 deletions sourcesage/modules/ReleaseDiffReportGenerator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# sourcesage\modules\ReleaseDiffReportGenerator.py
import subprocess
import os
from loguru import logger
import argparse
from art import *

class GitDiffGenerator:
def __init__(self, repo_path, git_fetch_tags, git_tag_sort, git_diff_command):
self.repo_path = repo_path
self.git_fetch_tags = git_fetch_tags
self.git_tag_sort = git_tag_sort
self.git_diff_command = git_diff_command
tprint("GitDiffGenerator")

def run_command(self, command):
"""
指定されたコマンドを実行し、出力をキャプチャして表示します。
"""
logger.info(f">>>>>> 実行コマンド: {' '.join(command)}")
result = subprocess.run(command, capture_output=True, text=True, encoding='utf-8')
if result.returncode != 0:
raise Exception(f"コマンドが失敗しました: {result.stderr}")
return result.stdout.strip()

def get_git_diff(self):
"""
現在のリリースと前のリリースの間の git diff を取得します。
"""
logger.info("最新の git タグを取得しています...")
self.run_command(self.git_fetch_tags)

logger.info("最新と前のタグを取得しています...")
tags_output = self.run_command(self.git_tag_sort)
tags = tags_output.split()

if len(tags) < 2:
raise Exception("比較するタグが十分にありません。")

latest_tag, previous_tag = tags[:2]
logger.success(f"最新タグ: {latest_tag}, 前のタグ: {previous_tag}")

logger.info("git diff を生成しています...")
diff_command = self.git_diff_command + [previous_tag, latest_tag]
diff = self.run_command(diff_command)

return diff, latest_tag, previous_tag

class MarkdownReportGenerator:
def __init__(self, diff, latest_tag, previous_tag, report_title, report_sections, output_path):
self.diff = diff
self.latest_tag = latest_tag
self.previous_tag = previous_tag
self.report_title = report_title
self.report_sections = report_sections
self.output_path = output_path
tprint("MarkdownReportGenerator")

def generate_markdown_report(self):
"""
git diff からマークダウンレポートを生成します。
"""
logger.info("マークダウンレポートを生成しています...")
report_content = f"# {self.report_title}\n\n"

for section in self.report_sections:
if section == "version_comparison":
report_content += self._generate_version_comparison_section()
elif section == "diff_details":
report_content += self._generate_diff_details_section()

with open(self.output_path, "w", encoding='utf8') as file:
file.write(report_content)

logger.success("マークダウンレポートが正常に生成されました!")

def _generate_version_comparison_section(self):
"""
バージョン比較セクションを生成します。
"""
section_content = f"## バージョン比較\n\n"
section_content += f"**{self.previous_tag}** と **{self.latest_tag}** の比較\n\n"
return section_content

def _generate_diff_details_section(self):
"""
差分の詳細セクションを生成します。
"""
section_content = "## 差分の詳細\n\n"
file_diffs = self._organize_diff_by_file()
section_content += self._generate_file_sections(file_diffs)
return section_content

def _organize_diff_by_file(self):
"""
ファイル名ごとに差分を整理します。
"""
file_diffs = {}
current_file = None
for line in self.diff.split("\n"):
if line.startswith("diff --git"):
current_file = line.split(" ")[-1][2:]
file_diffs[current_file] = []
elif current_file:
file_diffs[current_file].append(line)
return file_diffs

def _generate_file_sections(self, file_diffs):
"""
ファイル名ごとに見出しとコードブロックを生成します。
"""
file_sections = ""
for file, lines in file_diffs.items():
file_sections += f"### {file}\n\n"
file_sections += "```diff\n"
file_sections += "\n".join(lines)
file_sections += "\n```\n\n"
return file_sections

def parse_arguments():
"""
コマンドライン引数をパースします。
"""
parser = argparse.ArgumentParser(description='Generate a git diff report in Markdown format.')
parser.add_argument('--repo-path', type=str, default="", help='Path to the git repository')
parser.add_argument('--git-fetch-tags', type=str, nargs='+', default=["git", "fetch", "--tags"], help='Command to fetch git tags')
parser.add_argument('--git-tag-sort', type=str, nargs='+', default=["git", "tag", "--sort=-creatordate"], help='Command to sort git tags')
parser.add_argument('--git-diff-command', type=str, nargs='+', default=["git", "diff"], help='Command to generate git diff')
parser.add_argument('--report-title', type=str, default="Git Diff レポート", help='Title of the Markdown report')
parser.add_argument('--report-sections', type=str, nargs='+', default=["version_comparison", "diff_details"], help='Sections to include in the report')
parser.add_argument('--output-path', type=str, default=".SourceSageAssets/git_diff_report.md", help='Path to save the Markdown report')
return parser.parse_args()

def main():
logger.info("git diff レポートの生成を開始します...")

args = parse_arguments()
git_diff_generator = GitDiffGenerator(args.repo_path, args.git_fetch_tags, args.git_tag_sort, args.git_diff_command)
diff, latest_tag, previous_tag = git_diff_generator.get_git_diff()

markdown_report_generator = MarkdownReportGenerator(diff, latest_tag, previous_tag, args.report_title, args.report_sections, args.output_path)
markdown_report_generator.generate_markdown_report()

logger.success("プロセスが完了しました。")

if __name__ == "__main__":
main()

0 comments on commit 1d01017

Please sign in to comment.