Repository navigation
Expand file tree
/
Copy pathpublish_assistant.py
More file actions
410 lines (333 loc) Β· 13.7 KB
/
Copy pathpublish_assistant.py
File metadata and controls
410 lines (333 loc) Β· 13.7 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/env python3
"""
π AgentCoach PyPI Publishing Assistant
A Streamlit app to help publish agentcoach to PyPI with guided steps and checks.
Usage:
streamlit run publish_assistant.py
"""
import json
import subprocess
import sys
from pathlib import Path
from typing import Optional, Tuple
try:
import streamlit as st
import toml
except ImportError:
print("β Missing dependencies. Install with:")
print(" pip install streamlit toml")
sys.exit(1)
def run_command(cmd: list[str], capture: bool = True) -> Tuple[bool, str]:
"""Run a shell command and return success status and output."""
try:
if capture:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False
)
return result.returncode == 0, result.stdout + result.stderr
else:
result = subprocess.run(cmd, check=False)
return result.returncode == 0, ""
except Exception as e:
return False, str(e)
def check_git_status() -> Tuple[bool, str]:
"""Check if git working directory is clean."""
success, output = run_command(["git", "status", "--porcelain"])
if not success:
return False, "Git not available or not a git repository"
is_clean = len(output.strip()) == 0
return is_clean, "Clean" if is_clean else "Uncommitted changes"
def check_tests() -> Tuple[bool, str]:
"""Run pytest and check if tests pass."""
success, output = run_command(["pytest", "-q"])
return success, output if success else "Tests failed"
def get_current_version() -> str:
"""Get current version from pyproject.toml."""
try:
with open("pyproject.toml") as f:
data = toml.load(f)
return data["project"]["version"]
except Exception as e:
return f"Error: {e}"
def calculate_new_version(current: str, bump_type: str) -> str:
"""Calculate new version based on bump type."""
try:
parts = current.split(".")
major, minor, patch = int(parts[0]), int(parts[1]), int(parts[2])
if bump_type == "major":
return f"{major + 1}.0.0"
elif bump_type == "minor":
return f"{major}.{minor + 1}.0"
else: # patch
return f"{major}.{minor}.{patch + 1}"
except Exception:
return "Error calculating version"
def update_version_in_file(new_version: str) -> bool:
"""Update version in pyproject.toml."""
try:
with open("pyproject.toml") as f:
content = f.read()
# Replace version line
import re
content = re.sub(
r'version = "[^"]+"',
f'version = "{new_version}"',
content
)
with open("pyproject.toml", "w") as f:
f.write(content)
return True
except Exception as e:
st.error(f"Failed to update version: {e}")
return False
def main():
st.set_page_config(
page_title="AgentCoach PyPI Publisher",
page_icon="π",
layout="wide"
)
st.title("π AgentCoach PyPI Publishing Assistant")
st.markdown("*Guided workflow for publishing to PyPI*")
# Sidebar with quick links
with st.sidebar:
st.header("π Resources")
st.markdown("""
- [PyPI](https://pypi.org)
- [TestPyPI](https://test.pypi.org)
- [Publishing Guide](PUBLISHING.md)
- [Changelog](CHANGELOG.md)
""")
st.header("βοΈ Settings")
use_testpypi = st.checkbox("Test on TestPyPI first", value=True)
auto_tag = st.checkbox("Auto-create git tag", value=True)
# Main workflow
tabs = st.tabs([
"1οΈβ£ Pre-flight",
"2οΈβ£ Version",
"3οΈβ£ Build",
"4οΈβ£ Test",
"5οΈβ£ Publish"
])
# Tab 1: Pre-flight Checks
with tabs[0]:
st.header("Pre-flight Checks")
st.markdown("Verify everything is ready for publishing")
if st.button("π Run All Checks", type="primary"):
with st.spinner("Running checks..."):
checks = {}
# Check 1: Files exist
checks["pyproject.toml"] = Path("pyproject.toml").exists()
checks["README.md"] = Path("README.md").exists()
checks["LICENSE"] = Path("LICENSE").exists()
checks["CHANGELOG.md"] = Path("CHANGELOG.md").exists()
# Check 2: Git status
git_clean, git_msg = check_git_status()
checks["Git clean"] = git_clean
# Check 3: Tests
if st.session_state.get("run_tests", True):
tests_pass, test_output = check_tests()
checks["Tests pass"] = tests_pass
if not tests_pass:
st.code(test_output, language="text")
# Display results
for check, passed in checks.items():
if passed:
st.success(f"β
{check}")
else:
st.error(f"β {check}")
all_passed = all(checks.values())
if all_passed:
st.balloons()
st.success("π All checks passed! Ready to proceed.")
else:
st.warning("β οΈ Some checks failed. Fix issues before publishing.")
st.checkbox("Skip tests (not recommended)", key="skip_tests")
# Tab 2: Version Management
with tabs[1]:
st.header("Version Management")
current_version = get_current_version()
st.info(f"π Current version: **{current_version}**")
col1, col2 = st.columns(2)
with col1:
bump_type = st.selectbox(
"Bump type",
["patch", "minor", "major"],
help="patch: 0.1.0β0.1.1, minor: 0.1.0β0.2.0, major: 0.1.0β1.0.0"
)
with col2:
new_version = calculate_new_version(current_version, bump_type)
st.metric("New version", new_version)
st.markdown("---")
# Manual version override
manual_version = st.text_input(
"Or enter version manually",
placeholder="e.g., 0.2.0"
)
if manual_version:
new_version = manual_version
if st.button("π Update Version", type="primary"):
if update_version_in_file(new_version):
st.success(f"β
Version updated to {new_version}")
st.info("π‘ Don't forget to update CHANGELOG.md!")
else:
st.error("β Failed to update version")
# Changelog reminder
st.markdown("### π Changelog")
st.markdown("Add an entry to CHANGELOG.md:")
st.code(f"""
## [{new_version}] - {Path('CHANGELOG.md').stat().st_mtime if Path('CHANGELOG.md').exists() else 'YYYY-MM-DD'}
### Added
- New feature
### Fixed
- Bug fix
### Changed
- Improvement
""", language="markdown")
# Tab 3: Build
with tabs[2]:
st.header("Build Package")
st.markdown("""
This will create distribution files in the `dist/` directory:
- Source distribution (`.tar.gz`)
- Wheel (`.whl`)
""")
if st.button("π¨ Build Package", type="primary"):
with st.spinner("Building..."):
# Clean previous builds
st.info("Cleaning previous builds...")
run_command(["rm", "-rf", "dist/", "build/", "*.egg-info"])
# Build
st.info("Building package...")
success, output = run_command(["python", "-m", "build"])
if success:
st.success("β
Build successful!")
st.code(output, language="text")
# Show built files
dist_files = list(Path("dist").glob("*"))
if dist_files:
st.markdown("**Built files:**")
for f in dist_files:
st.text(f" π¦ {f.name}")
# Check package
st.info("Checking package...")
check_success, check_output = run_command(
["twine", "check", "dist/*"]
)
if check_success:
st.success("β
Package check passed")
else:
st.error("β Package check failed")
st.code(check_output, language="text")
else:
st.error("β Build failed")
st.code(output, language="text")
# Tab 4: Test on TestPyPI
with tabs[3]:
st.header("Test on TestPyPI")
if not use_testpypi:
st.warning("β οΈ TestPyPI testing is disabled. Enable in sidebar.")
else:
st.markdown("""
Upload to TestPyPI to verify everything works before publishing to production PyPI.
**You'll need:**
- TestPyPI account: https://test.pypi.org
- API token from TestPyPI
""")
testpypi_token = st.text_input(
"TestPyPI API Token",
type="password",
help="Get from https://test.pypi.org/manage/account/token/"
)
if st.button("π€ Upload to TestPyPI", type="primary", disabled=not testpypi_token):
with st.spinner("Uploading to TestPyPI..."):
# Set environment variables for twine
import os
os.environ["TWINE_USERNAME"] = "__token__"
os.environ["TWINE_PASSWORD"] = testpypi_token
success, output = run_command([
"twine", "upload",
"--repository", "testpypi",
"dist/*"
])
if success:
st.success("β
Uploaded to TestPyPI!")
st.markdown(f"""
**Test installation:**
```bash
pip install --index-url https://test.pypi.org/simple/ \\
--extra-index-url https://pypi.org/simple/ \\
agentcoach
```
**View on TestPyPI:**
https://test.pypi.org/project/agentcoach/
""")
else:
st.error("β Upload failed")
st.code(output, language="text")
# Tab 5: Publish to PyPI
with tabs[4]:
st.header("π Publish to PyPI")
st.warning("""
β οΈ **Warning:** This will publish to production PyPI.
Make sure you've tested on TestPyPI first!
""")
st.markdown("""
**You'll need:**
- PyPI account: https://pypi.org
- API token from PyPI
""")
pypi_token = st.text_input(
"PyPI API Token",
type="password",
help="Get from https://pypi.org/manage/account/token/"
)
confirm = st.checkbox("I confirm I want to publish to PyPI")
if st.button(
"π Publish to PyPI",
type="primary",
disabled=not (pypi_token and confirm)
):
with st.spinner("Publishing to PyPI..."):
# Set environment variables for twine
import os
os.environ["TWINE_USERNAME"] = "__token__"
os.environ["TWINE_PASSWORD"] = pypi_token
success, output = run_command(["twine", "upload", "dist/*"])
if success:
st.success("π Published to PyPI!")
st.balloons()
version = get_current_version()
st.markdown(f"""
**Installation:**
```bash
pip install agentcoach
```
**View on PyPI:**
https://pypi.org/project/agentcoach/{version}/
""")
# Git tag
if auto_tag:
st.info("Creating git tag...")
tag_name = f"v{version}"
run_command(["git", "tag", "-a", tag_name, "-m", f"Release {version}"])
st.success(f"β
Created tag: {tag_name}")
st.info("π‘ Don't forget to push tags: `git push origin --tags`")
else:
st.error("β Publish failed")
st.code(output, language="text")
# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; color: gray;'>
π See <a href='PUBLISHING.md'>PUBLISHING.md</a> for detailed instructions
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
# Check if we're in the right directory
if not Path("pyproject.toml").exists():
st.error("β pyproject.toml not found. Run this from the project root directory.")
st.stop()
main()