Skip to content

Commit d857eeb

Browse files
committed
chore: run black
1 parent 0aabef6 commit d857eeb

10 files changed

+127
-111
lines changed

setup.py

+5-12
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,17 @@
44
name="vyper-sphinx-docs",
55
version="0.1.0",
66
packages=find_packages(),
7-
install_requires=[
8-
"sphinx>=4.0.0",
9-
"sphinx-rtd-theme>=1.0.0"
10-
],
7+
install_requires=["sphinx>=4.0.0", "sphinx-rtd-theme>=1.0.0"],
118
extras_require={
129
"dev": [
1310
"pytest>=7.0.0",
1411
"pytest-cov>=4.0.0",
1512
"black>=22.0.0",
1613
"isort>=5.0.0",
17-
"requests>=2.0.0" # For testing server
18-
]
19-
},
20-
entry_points={
21-
"console_scripts": [
22-
"vyper-docs=vyper_sphinx_docs.cli:main"
14+
"requests>=2.0.0", # For testing server
2315
]
2416
},
17+
entry_points={"console_scripts": ["vyper-docs=vyper_sphinx_docs.cli:main"]},
2518
author="Vyper Developer",
2619
description="Sphinx documentation generator for Vyper smart contracts",
2720
long_description=open("README.md").read(),
@@ -32,5 +25,5 @@
3225
"License :: OSI Approved :: MIT License",
3326
"Operating System :: OS Independent",
3427
],
35-
python_requires=">=3.7"
36-
)
28+
python_requires=">=3.7",
29+
)

sphinx_autodoc_vyper/cli.py

+21-11
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,19 @@
1111

1212
def main():
1313
"""Main entry point for the CLI."""
14-
parser = argparse.ArgumentParser(description='Generate Sphinx documentation for Vyper contracts')
15-
parser.add_argument('contracts_dir', help='Directory containing Vyper contracts')
16-
parser.add_argument('--output', '-o', default='.', help='Output directory for documentation')
17-
parser.add_argument('--serve', '-s', action='store_true', help='Serve documentation after building')
18-
parser.add_argument('--port', '-p', type=int, default=8000, help='Port for the documentation server')
14+
parser = argparse.ArgumentParser(
15+
description="Generate Sphinx documentation for Vyper contracts"
16+
)
17+
parser.add_argument("contracts_dir", help="Directory containing Vyper contracts")
18+
parser.add_argument(
19+
"--output", "-o", default=".", help="Output directory for documentation"
20+
)
21+
parser.add_argument(
22+
"--serve", "-s", action="store_true", help="Serve documentation after building"
23+
)
24+
parser.add_argument(
25+
"--port", "-p", type=int, default=8000, help="Port for the documentation server"
26+
)
1927
args = parser.parse_args()
2028

2129
# Parse contracts
@@ -27,12 +35,14 @@ def main():
2735
generator.generate(contracts)
2836

2937
# Build HTML documentation
30-
docs_dir = Path(args.output) / 'docs'
31-
build_dir = docs_dir / '_build'
32-
subprocess.run(['sphinx-build', '-b', 'html', str(docs_dir), str(build_dir)], check=True)
33-
34-
print(f'Documentation built successfully in {build_dir}/html')
35-
38+
docs_dir = Path(args.output) / "docs"
39+
build_dir = docs_dir / "_build"
40+
subprocess.run(
41+
["sphinx-build", "-b", "html", str(docs_dir), str(build_dir)], check=True
42+
)
43+
44+
print(f"Documentation built successfully in {build_dir}/html")
45+
3646
# Serve documentation if requested
3747
if args.serve:
3848
serve_docs(args.port)

sphinx_autodoc_vyper/generator.py

+24-18
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class SphinxGenerator:
1010

1111
def __init__(self, output_dir: str):
1212
self.output_dir = output_dir
13-
self.docs_dir = os.path.join(output_dir, 'docs')
13+
self.docs_dir = os.path.join(output_dir, "docs")
1414
os.makedirs(self.docs_dir, exist_ok=True)
1515

1616
def generate(self, contracts: List[Contract]):
@@ -21,7 +21,7 @@ def generate(self, contracts: List[Contract]):
2121

2222
def _generate_conf_py(self):
2323
"""Generate Sphinx configuration file."""
24-
conf_content = '''# Configuration file for Sphinx documentation
24+
conf_content = """# Configuration file for Sphinx documentation
2525
2626
project = 'Vyper Smart Contracts'
2727
copyright = '2023'
@@ -38,45 +38,51 @@ def _generate_conf_py(self):
3838
3939
html_theme = 'sphinx_rtd_theme'
4040
html_static_path = ['_static']
41-
'''
42-
with open(os.path.join(self.docs_dir, 'conf.py'), 'w', encoding='utf-8') as f:
41+
"""
42+
with open(os.path.join(self.docs_dir, "conf.py"), "w", encoding="utf-8") as f:
4343
f.write(conf_content)
4444

4545
def _generate_index_rst(self, contracts: List[Contract]):
4646
"""Generate index.rst file."""
47-
content = '''Vyper Smart Contracts Documentation
47+
content = """Vyper Smart Contracts Documentation
4848
================================
4949
5050
.. toctree::
5151
:maxdepth: 2
5252
:caption: Contents:
5353
54-
'''
54+
"""
5555
for contract in contracts:
56-
content += f' {contract.name}\n'
56+
content += f" {contract.name}\n"
5757

58-
with open(os.path.join(self.docs_dir, 'index.rst'), 'w', encoding='utf-8') as f:
58+
with open(os.path.join(self.docs_dir, "index.rst"), "w", encoding="utf-8") as f:
5959
f.write(content)
6060

6161
def _generate_contract_docs(self, contracts: List[Contract]):
6262
"""Generate documentation for each contract."""
6363
for contract in contracts:
64-
content = f'''{contract.name}
64+
content = f"""{contract.name}
6565
{'=' * len(contract.name)}
6666
67-
'''
67+
"""
6868
if contract.docstring:
69-
content += f'{contract.docstring}\n\n'
69+
content += f"{contract.docstring}\n\n"
7070

7171
if contract.functions:
72-
content += 'Functions\n---------\n\n'
72+
content += "Functions\n---------\n\n"
7373
for func in contract.functions:
74-
params = ', '.join(f'{p.name}: {p.type}' for p in func.params)
75-
return_type = f' -> {func.return_type}' if func.return_type else ''
76-
content += f'.. py:function:: {func.name}({params}){return_type}\n\n'
77-
74+
params = ", ".join(f"{p.name}: {p.type}" for p in func.params)
75+
return_type = f" -> {func.return_type}" if func.return_type else ""
76+
content += (
77+
f".. py:function:: {func.name}({params}){return_type}\n\n"
78+
)
79+
7880
if func.docstring:
79-
content += f' {func.docstring}\n\n'
81+
content += f" {func.docstring}\n\n"
8082

81-
with open(os.path.join(self.docs_dir, f'{contract.name}.rst'), 'w', encoding='utf-8') as f:
83+
with open(
84+
os.path.join(self.docs_dir, f"{contract.name}.rst"),
85+
"w",
86+
encoding="utf-8",
87+
) as f:
8288
f.write(content)

sphinx_autodoc_vyper/parser.py

+33-17
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@
99
@dataclass
1010
class Parameter:
1111
"""Function parameter representation."""
12+
1213
name: str
1314
type: str
1415

1516

1617
@dataclass
1718
class Function:
1819
"""Vyper function representation."""
20+
1921
name: str
2022
params: List[Parameter]
2123
return_type: Optional[str]
@@ -25,6 +27,7 @@ class Function:
2527
@dataclass
2628
class Contract:
2729
"""Vyper contract representation."""
30+
2831
name: str
2932
path: str
3033
docstring: Optional[str]
@@ -42,27 +45,29 @@ def parse_contracts(self) -> List[Contract]:
4245
contracts = []
4346
for root, _, files in os.walk(self.contracts_dir):
4447
for file in files:
45-
if file.endswith('.vy'):
48+
if file.endswith(".vy"):
4649
file_path = os.path.join(root, file)
4750
contract = self._parse_contract(file_path)
4851
contracts.append(contract)
4952
return contracts
5053

5154
def _parse_contract(self, file_path: str) -> Contract:
5255
"""Parse a single Vyper contract file."""
53-
with open(file_path, 'r', encoding='utf-8') as f:
56+
with open(file_path, "r", encoding="utf-8") as f:
5457
content = f.read()
5558

56-
name = os.path.basename(file_path).replace('.vy', '')
59+
name = os.path.basename(file_path).replace(".vy", "")
5760
rel_path = os.path.relpath(file_path, self.contracts_dir)
58-
61+
5962
# Extract contract docstring
6063
docstring = self._extract_contract_docstring(content)
61-
64+
6265
# Extract functions
6366
functions = self._extract_functions(content)
64-
65-
return Contract(name=name, path=rel_path, docstring=docstring, functions=functions)
67+
68+
return Contract(
69+
name=name, path=rel_path, docstring=docstring, functions=functions
70+
)
6671

6772
def _extract_contract_docstring(self, content: str) -> Optional[str]:
6873
"""Extract the contract's main docstring."""
@@ -72,27 +77,38 @@ def _extract_contract_docstring(self, content: str) -> Optional[str]:
7277
def _extract_functions(self, content: str) -> List[Function]:
7378
"""Extract all functions from the contract."""
7479
functions = []
75-
function_pattern = r'@external\s+def\s+([^(]+)\(([^)]*)\)(\s*->\s*[^:]+)?:\s*("""[\s\S]*?""")?'
76-
80+
function_pattern = (
81+
r'@external\s+def\s+([^(]+)\(([^)]*)\)(\s*->\s*[^:]+)?:\s*("""[\s\S]*?""")?'
82+
)
83+
7784
for match in re.finditer(function_pattern, content):
7885
name = match.group(1).strip()
7986
params_str = match.group(2).strip()
80-
return_type = match.group(3).replace('->', '').strip() if match.group(3) else None
87+
return_type = (
88+
match.group(3).replace("->", "").strip() if match.group(3) else None
89+
)
8190
docstring = match.group(4)[3:-3].strip() if match.group(4) else None
82-
91+
8392
params = self._parse_params(params_str)
84-
functions.append(Function(name=name, params=params, return_type=return_type, docstring=docstring))
85-
93+
functions.append(
94+
Function(
95+
name=name,
96+
params=params,
97+
return_type=return_type,
98+
docstring=docstring,
99+
)
100+
)
101+
86102
return functions
87103

88104
def _parse_params(self, params_str: str) -> List[Parameter]:
89105
"""Parse function parameters."""
90106
if not params_str:
91107
return []
92-
108+
93109
params = []
94-
for param in params_str.split(','):
95-
if ':' in param:
96-
name, type_str = param.split(':')
110+
for param in params_str.split(","):
111+
if ":" in param:
112+
name, type_str = param.split(":")
97113
params.append(Parameter(name=name.strip(), type=type_str.strip()))
98114
return params

sphinx_autodoc_vyper/server.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,17 @@
99

1010
def serve_docs(port: int = 8000):
1111
"""Serve the documentation on a local development server."""
12-
build_dir = Path('docs/_build/html')
13-
12+
build_dir = Path("docs/_build/html")
13+
1414
if not build_dir.exists():
1515
raise FileNotFoundError(
1616
"Documentation not found. Run 'vyper-docs' first to generate the documentation."
1717
)
18-
18+
1919
os.chdir(build_dir)
20-
20+
2121
handler = http.server.SimpleHTTPRequestHandler
22-
22+
2323
with socketserver.TCPServer(("", port), handler) as httpd:
2424
url = f"http://localhost:{port}"
2525
print(f"Serving documentation at {url}")

tests/conftest.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,17 @@ def contracts_dir(tmp_path, sample_contract):
4747
"""Create a temporary directory with sample contracts."""
4848
contracts = tmp_path / "contracts"
4949
contracts.mkdir()
50-
50+
5151
# Create main contract
5252
contract_file = contracts / "token.vy"
5353
contract_file.write_text(sample_contract)
54-
54+
5555
# Create nested contract
5656
nested_dir = contracts / "nested"
5757
nested_dir.mkdir()
5858
nested_contract = nested_dir / "nested_token.vy"
5959
nested_contract.write_text(sample_contract)
60-
60+
6161
return contracts
6262

6363

tests/test_cli.py

+9-15
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,17 @@
88
def test_cli_basic(contracts_dir, output_dir, monkeypatch, capsys):
99
"""Test basic CLI functionality."""
1010
# Mock sys.argv
11-
monkeypatch.setattr('sys.argv', [
12-
'vyper-docs',
13-
str(contracts_dir),
14-
'--output',
15-
str(output_dir)
16-
])
17-
11+
monkeypatch.setattr(
12+
"sys.argv", ["vyper-docs", str(contracts_dir), "--output", str(output_dir)]
13+
)
14+
1815
# Run CLI
1916
main()
20-
17+
2118
# Check output
2219
captured = capsys.readouterr()
2320
assert "Documentation built successfully" in captured.out
24-
21+
2522
# Check generated files
2623
docs_dir = output_dir / "docs"
2724
build_dir = docs_dir / "_build"
@@ -33,13 +30,10 @@ def test_cli_basic(contracts_dir, output_dir, monkeypatch, capsys):
3330
def test_cli_invalid_contracts_dir(tmp_path, monkeypatch, capsys):
3431
"""Test CLI with invalid contracts directory."""
3532
invalid_dir = tmp_path / "nonexistent"
36-
33+
3734
# Mock sys.argv
38-
monkeypatch.setattr('sys.argv', [
39-
'vyper-docs',
40-
str(invalid_dir)
41-
])
42-
35+
monkeypatch.setattr("sys.argv", ["vyper-docs", str(invalid_dir)])
36+
4337
# Run CLI and check for error
4438
with pytest.raises(FileNotFoundError):
4539
main()

0 commit comments

Comments
 (0)