Skip to content

Commit f29992c

Browse files
working locally
1 parent fa989c8 commit f29992c

File tree

7 files changed

+513
-48
lines changed

7 files changed

+513
-48
lines changed

analyze_branch_data_with_date.py

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
#!/usr/bin/env python3
2+
3+
import json
4+
import os
5+
import sys
6+
import argparse
7+
from datetime import datetime
8+
9+
def load_branch_data(file_path):
10+
"""
11+
Load branch data from JSON file.
12+
13+
Args:
14+
file_path (str): Path to the JSON file containing branch data
15+
16+
Returns:
17+
dict: Branch data
18+
"""
19+
try:
20+
with open(file_path, 'r') as f:
21+
data = json.load(f)
22+
return data
23+
except FileNotFoundError:
24+
print(f"Error: File {file_path} not found.")
25+
sys.exit(1)
26+
except json.JSONDecodeError:
27+
print(f"Error: File {file_path} is not valid JSON.")
28+
sys.exit(1)
29+
30+
def analyze_branch_data(data):
31+
"""
32+
Analyze branch data and generate statistics.
33+
34+
Args:
35+
data (dict): Branch data
36+
37+
Returns:
38+
dict: Analysis results
39+
"""
40+
# Verify data structure
41+
required_keys = ['main', 'release', 'common', 'mainOnly', 'releaseOnly']
42+
for key in required_keys:
43+
if key not in data:
44+
print(f"Error: Missing required key '{key}' in branch data.")
45+
sys.exit(1)
46+
47+
# Calculate statistics
48+
stats = {
49+
'total_branches': len(set(data['main'] + data['release'])),
50+
'main_count': len(data['main']),
51+
'release_count': len(data['release']),
52+
'common_count': len(data['common']),
53+
'main_only_count': len(data['mainOnly']),
54+
'release_only_count': len(data['releaseOnly']),
55+
'repository': data.get('repository', 'Unknown'),
56+
'timestamp': data.get('timestamp', datetime.now().isoformat()),
57+
'analysis_time': datetime.now().isoformat(),
58+
'analysis_date': data.get('analysisDate', 'latest')
59+
}
60+
61+
# Calculate percentages
62+
if stats['total_branches'] > 0:
63+
stats['common_percentage'] = round(stats['common_count'] / stats['total_branches'] * 100, 1)
64+
stats['main_only_percentage'] = round(stats['main_only_count'] / stats['total_branches'] * 100, 1)
65+
stats['release_only_percentage'] = round(stats['release_only_count'] / stats['total_branches'] * 100, 1)
66+
else:
67+
stats['common_percentage'] = 0
68+
stats['main_only_percentage'] = 0
69+
stats['release_only_percentage'] = 0
70+
71+
# Combine with original data
72+
result = {**data, 'stats': stats}
73+
return result
74+
75+
def save_analysis_results(data, output_file):
76+
"""
77+
Save analysis results to a JSON file.
78+
79+
Args:
80+
data (dict): Analysis results
81+
output_file (str): Path to the output JSON file
82+
"""
83+
with open(output_file, 'w') as f:
84+
json.dump(data, f, indent=2)
85+
print(f"Analysis results saved to {output_file}")
86+
87+
def print_analysis_summary(data):
88+
"""
89+
Print a summary of the analysis results.
90+
91+
Args:
92+
data (dict): Analysis results
93+
"""
94+
stats = data['stats']
95+
96+
print("\n" + "="*50)
97+
print(f"BRANCH ANALYSIS SUMMARY FOR {stats['repository']}")
98+
if stats.get('analysis_date') and stats['analysis_date'] != 'latest':
99+
print(f"Analysis Date: {stats['analysis_date']}")
100+
print("="*50)
101+
print(f"Total unique branches: {stats['total_branches']}")
102+
print(f"Branches in main: {stats['main_count']}")
103+
print(f"Branches in release: {stats['release_count']}")
104+
print(f"Common branches: {stats['common_count']} ({stats['common_percentage']}%)")
105+
print(f"Branches only in main: {stats['main_only_count']} ({stats['main_only_percentage']}%)")
106+
print(f"Branches only in release: {stats['release_only_count']} ({stats['release_only_percentage']}%)")
107+
print("="*50)
108+
109+
# Print branch lists
110+
print("\nBranches in main:")
111+
for branch in data['main']:
112+
print(f" - {branch}")
113+
114+
print("\nBranches in release:")
115+
for branch in data['release']:
116+
print(f" - {branch}")
117+
118+
print("\nCommon branches:")
119+
for branch in data['common']:
120+
print(f" - {branch}")
121+
122+
print("\nBranches only in main:")
123+
for branch in data['mainOnly']:
124+
print(f" - {branch}")
125+
126+
print("\nBranches only in release:")
127+
for branch in data['releaseOnly']:
128+
print(f" - {branch}")
129+
130+
def main():
131+
# Parse command line arguments
132+
parser = argparse.ArgumentParser(description='Analyze branch data with date filtering')
133+
parser.add_argument('input_file', nargs='?', default='branch_data.json', help='Input JSON file path')
134+
parser.add_argument('output_file', nargs='?', help='Output JSON file path')
135+
args = parser.parse_args()
136+
137+
# Default input and output files
138+
input_file = args.input_file
139+
140+
# Determine output filename if not provided
141+
if args.output_file:
142+
output_file = args.output_file
143+
else:
144+
# If input file has date in name, use same pattern for output
145+
if '_' in input_file and input_file.startswith('branch_data_'):
146+
date_part = input_file.split('branch_data_')[1]
147+
output_file = f"analyzed_branch_data_{date_part}"
148+
else:
149+
output_file = "analyzed_branch_data.json"
150+
151+
print(f"Loading branch data from {input_file}...")
152+
data = load_branch_data(input_file)
153+
154+
print("Analyzing branch data...")
155+
analyzed_data = analyze_branch_data(data)
156+
157+
# Save analysis results
158+
save_analysis_results(analyzed_data, output_file)
159+
160+
# Print summary
161+
print_analysis_summary(analyzed_data)
162+
163+
print(f"\nAnalysis complete. Results saved to {output_file}")
164+
165+
if __name__ == "__main__":
166+
main()

analyzed_branch_data.json

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,24 @@
1919
"name": "feature/sites-40",
2020
"merged_at": "2025-04-08T18:55:00+00:00",
2121
"pr_number": 1,
22-
"pr_title": "hello",
23-
"pr_url": "https://github.com/correasebastian/layers/pull/1",
24-
"author": "correasebastian"
22+
"pr_title": "hello"
2523
}
2624
],
2725
"releaseDetails": [
2826
{
2927
"name": "feature/sites-42",
3028
"merged_at": "2025-04-09T01:10:20+00:00",
3129
"pr_number": 3,
32-
"pr_title": "add sites-42",
33-
"pr_url": "https://github.com/correasebastian/layers/pull/3",
34-
"author": "correasebastian"
30+
"pr_title": "add sites-42"
3531
},
3632
{
3733
"name": "feature/sites-41",
3834
"merged_at": "2025-04-08T18:58:45+00:00",
3935
"pr_number": 2,
40-
"pr_title": "using grid areas",
41-
"pr_url": "https://github.com/correasebastian/layers/pull/2",
42-
"author": "correasebastian"
36+
"pr_title": "using grid areas"
4337
}
4438
],
45-
"timestamp": "2025-04-08T20:27:33.243559",
39+
"timestamp": "2025-04-08T20:48:59.461936",
4640
"repository": "correasebastian/layers",
4741
"analysisDate": "latest",
4842
"stats": {
@@ -53,8 +47,8 @@
5347
"main_only_count": 1,
5448
"release_only_count": 2,
5549
"repository": "correasebastian/layers",
56-
"timestamp": "2025-04-08T20:27:33.243559",
57-
"analysis_time": "2025-04-08T20:27:57.149519",
50+
"timestamp": "2025-04-08T20:48:59.461936",
51+
"analysis_time": "2025-04-08T20:49:32.478997",
5852
"analysis_date": "latest",
5953
"common_percentage": 0.0,
6054
"main_only_percentage": 33.3,

branch_data.json

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,24 @@
1919
"name": "feature/sites-40",
2020
"merged_at": "2025-04-08T18:55:00+00:00",
2121
"pr_number": 1,
22-
"pr_title": "hello",
23-
"pr_url": "https://github.com/correasebastian/layers/pull/1",
24-
"author": "correasebastian"
22+
"pr_title": "hello"
2523
}
2624
],
2725
"releaseDetails": [
2826
{
2927
"name": "feature/sites-42",
3028
"merged_at": "2025-04-09T01:10:20+00:00",
3129
"pr_number": 3,
32-
"pr_title": "add sites-42",
33-
"pr_url": "https://github.com/correasebastian/layers/pull/3",
34-
"author": "correasebastian"
30+
"pr_title": "add sites-42"
3531
},
3632
{
3733
"name": "feature/sites-41",
3834
"merged_at": "2025-04-08T18:58:45+00:00",
3935
"pr_number": 2,
40-
"pr_title": "using grid areas",
41-
"pr_url": "https://github.com/correasebastian/layers/pull/2",
42-
"author": "correasebastian"
36+
"pr_title": "using grid areas"
4337
}
4438
],
45-
"timestamp": "2025-04-08T20:27:33.243559",
39+
"timestamp": "2025-04-08T20:48:59.461936",
4640
"repository": "correasebastian/layers",
4741
"analysisDate": "latest"
4842
}

configure_with_date.sh

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/bin/bash
2+
3+
# Configuration script for GitHub Branch Analyzer with date filtering
4+
# This script sets up the environment variables needed for the analyzer
5+
6+
# Check if .env file exists and source it if it does
7+
if [ -f .env ]; then
8+
source .env
9+
fi
10+
11+
# Function to prompt for input with a default value
12+
prompt_with_default() {
13+
local prompt=$1
14+
local default=$2
15+
local input
16+
17+
echo -n "$prompt [$default]: "
18+
read input
19+
echo "${input:-$default}"
20+
}
21+
22+
# Prompt for GitHub token if not set
23+
if [ -z "$GITHUB_TOKEN" ]; then
24+
echo "GitHub Personal Access Token is required to access private repositories."
25+
echo "You can create one at: https://github.com/settings/tokens"
26+
echo "Ensure it has 'repo' permissions to access private repositories."
27+
read -p "Enter your GitHub Personal Access Token: " GITHUB_TOKEN
28+
fi
29+
30+
# Prompt for repository name if not set
31+
if [ -z "$GITHUB_REPO" ]; then
32+
GITHUB_REPO=$(prompt_with_default "Enter repository name (format: owner/repo)" "")
33+
fi
34+
35+
# Prompt for branch names
36+
MAIN_BRANCH=$(prompt_with_default "Enter main branch name" "main")
37+
RELEASE_BRANCH=$(prompt_with_default "Enter release branch name" "release")
38+
39+
# Prompt for analysis date (optional)
40+
DEFAULT_DATE=$(date +%Y-%m-%d) # Today's date in YYYY-MM-DD format
41+
ANALYSIS_DATE=$(prompt_with_default "Enter analysis date (YYYY-MM-DD format, leave empty for latest)" "$DEFAULT_DATE")
42+
43+
# Save to .env file
44+
cat > .env << EOF
45+
GITHUB_TOKEN=$GITHUB_TOKEN
46+
GITHUB_REPO=$GITHUB_REPO
47+
MAIN_BRANCH=$MAIN_BRANCH
48+
RELEASE_BRANCH=$RELEASE_BRANCH
49+
ANALYSIS_DATE=$ANALYSIS_DATE
50+
EOF
51+
52+
echo "Configuration saved to .env file"
53+
echo "To run the analyzer, use: ./run_with_date.sh"
54+
55+
# Make the .env file readable only by the owner
56+
chmod 600 .env
57+
58+
# Export variables for immediate use
59+
export GITHUB_TOKEN
60+
export GITHUB_REPO
61+
export MAIN_BRANCH
62+
export RELEASE_BRANCH
63+
export ANALYSIS_DATE

0 commit comments

Comments
 (0)