File size: 6,945 Bytes
2b1ff82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python3
"""
FinEE Release Script
====================

Automates the release process with proper checks:
1. Ensure on develop branch
2. Run all tests
3. Run benchmark
4. Merge to main
5. Create release tag
6. Build and upload to PyPI
7. Sync to Hugging Face

Usage:
    python scripts/release.py 1.0.4
    python scripts/release.py 1.0.4 --dry-run  # Preview only

Author: Ranjit Behera
"""

import argparse
import subprocess
import sys
import re
from pathlib import Path


def run(cmd: str, check: bool = True, capture: bool = False):
    """Run a shell command."""
    print(f"  $ {cmd}")
    result = subprocess.run(cmd, shell=True, capture_output=capture, text=True)
    if check and result.returncode != 0:
        print(f"  ❌ Command failed with exit code {result.returncode}")
        if capture:
            print(result.stderr)
        sys.exit(1)
    return result


def get_current_branch() -> str:
    """Get current git branch."""
    result = run("git branch --show-current", capture=True)
    return result.stdout.strip()


def check_clean_working_dir() -> bool:
    """Check if working directory is clean."""
    result = run("git status --porcelain", capture=True)
    return result.stdout.strip() == ""


def run_tests() -> bool:
    """Run all tests."""
    print("\nπŸ§ͺ Running tests...")
    result = subprocess.run("./venv/bin/pytest tests/ -v", shell=True)
    return result.returncode == 0


def run_benchmark() -> bool:
    """Run benchmark suite."""
    print("\nπŸ“Š Running benchmark...")
    result = subprocess.run("./venv/bin/python benchmark.py --all", shell=True)
    return result.returncode == 0


def update_version(new_version: str):
    """Update version in pyproject.toml."""
    pyproject = Path("pyproject.toml")
    content = pyproject.read_text()
    
    # Find and replace version
    pattern = r'version = "[^"]+"'
    new_content = re.sub(pattern, f'version = "{new_version}"', content)
    
    pyproject.write_text(new_content)
    print(f"  βœ… Updated pyproject.toml to version {new_version}")


def update_changelog(new_version: str):
    """Move [Unreleased] to new version section."""
    changelog = Path("CHANGELOG.md")
    content = changelog.read_text()
    
    from datetime import date
    today = date.today().isoformat()
    
    # Replace [Unreleased] with new version
    content = content.replace(
        "## [Unreleased]",
        f"## [Unreleased]\n### Added\n- (Next features go here)\n\n### Changed\n\n### Fixed\n\n---\n\n## [{new_version}] - {today}"
    )
    
    changelog.write_text(content)
    print(f"  βœ… Updated CHANGELOG.md for version {new_version}")


def main():
    parser = argparse.ArgumentParser(description="FinEE Release Script")
    parser.add_argument("version", help="New version (e.g., 1.0.4)")
    parser.add_argument("--dry-run", action="store_true", help="Preview only, no changes")
    parser.add_argument("--skip-tests", action="store_true", help="Skip test suite")
    parser.add_argument("--skip-benchmark", action="store_true", help="Skip benchmark")
    args = parser.parse_args()
    
    version = args.version
    if not re.match(r'^\d+\.\d+\.\d+$', version):
        print(f"❌ Invalid version format: {version}")
        print("   Expected: X.Y.Z (e.g., 1.0.4)")
        sys.exit(1)
    
    print("=" * 60)
    print(f"πŸš€ FinEE Release v{version}")
    print("=" * 60)
    
    if args.dry_run:
        print("⚠️  DRY RUN - No changes will be made\n")
    
    # Step 1: Check branch
    print("\nπŸ“ Step 1: Checking branch...")
    branch = get_current_branch()
    if branch != "develop":
        print(f"  ❌ Must be on 'develop' branch, currently on '{branch}'")
        print("  Run: git checkout develop")
        sys.exit(1)
    print(f"  βœ… On develop branch")
    
    # Step 2: Check clean working directory
    print("\nπŸ“ Step 2: Checking working directory...")
    if not check_clean_working_dir():
        print("  ❌ Working directory not clean")
        print("  Run: git status")
        sys.exit(1)
    print("  βœ… Working directory clean")
    
    # Step 3: Run tests
    if not args.skip_tests:
        print("\nπŸ“ Step 3: Running tests...")
        if not args.dry_run:
            if not run_tests():
                print("  ❌ Tests failed! Fix before releasing.")
                sys.exit(1)
            print("  βœ… All tests passed")
        else:
            print("  ⏭️  Skipped (dry run)")
    
    # Step 4: Run benchmark
    if not args.skip_benchmark:
        print("\nπŸ“ Step 4: Running benchmark...")
        if not args.dry_run:
            if not run_benchmark():
                print("  ⚠️  Benchmark had failures (continuing...)")
            print("  βœ… Benchmark complete")
        else:
            print("  ⏭️  Skipped (dry run)")
    
    # Step 5: Update version
    print("\nπŸ“ Step 5: Updating version...")
    if not args.dry_run:
        update_version(version)
        update_changelog(version)
        run(f'git add pyproject.toml CHANGELOG.md')
        run(f'git commit -m "chore: bump version to {version}"')
        run('git push origin develop')
    else:
        print(f"  ⏭️  Would update to version {version}")
    
    # Step 6: Merge to main
    print("\nπŸ“ Step 6: Merging to main...")
    if not args.dry_run:
        run('git checkout main')
        run('git pull origin main')
        run('git merge develop --no-edit')
        run('git push origin main')
    else:
        print("  ⏭️  Would merge develop β†’ main")
    
    # Step 7: Create tag
    print("\nπŸ“ Step 7: Creating release tag...")
    if not args.dry_run:
        run(f'git tag -a v{version} -m "Release v{version}"')
        run(f'git push origin v{version}')
    else:
        print(f"  ⏭️  Would create tag v{version}")
    
    # Step 8: Build and upload to PyPI
    print("\nπŸ“ Step 8: Building and uploading to PyPI...")
    if not args.dry_run:
        run('rm -rf dist/')
        run('./venv/bin/python -m build')
        run('./venv/bin/python -m twine upload dist/*')
    else:
        print("  ⏭️  Would build and upload to PyPI")
    
    # Step 9: Return to develop
    print("\nπŸ“ Step 9: Returning to develop branch...")
    if not args.dry_run:
        run('git checkout develop')
        run('git merge main')
        run('git push origin develop')
    else:
        print("  ⏭️  Would checkout develop")
    
    # Done
    print("\n" + "=" * 60)
    if args.dry_run:
        print("βœ… DRY RUN COMPLETE - No changes made")
        print(f"   Run without --dry-run to release v{version}")
    else:
        print(f"πŸŽ‰ RELEASE v{version} COMPLETE!")
        print("\nLinks:")
        print(f"  PyPI: https://pypi.org/project/finee/{version}/")
        print("  GitHub: https://github.com/Ranjitbehera0034/Finance-Entity-Extractor/releases")
    print("=" * 60)


if __name__ == "__main__":
    main()