Skip to content

Commit 126a7ef

Browse files
authored
Merge pull request #259 from crytic/cleanup
Clean up codebase
2 parents 2c1d0a7 + 6070e3e commit 126a7ef

File tree

11 files changed

+74
-92
lines changed

11 files changed

+74
-92
lines changed

solc_select/constants.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
11
import os
22
from pathlib import Path
33

4-
# DIRs path
5-
if "VIRTUAL_ENV" in os.environ:
6-
HOME_DIR = Path(os.environ["VIRTUAL_ENV"])
7-
else:
8-
HOME_DIR = Path.home()
9-
SOLC_SELECT_DIR = HOME_DIR.joinpath(".solc-select")
10-
ARTIFACTS_DIR = SOLC_SELECT_DIR.joinpath("artifacts")
4+
# Directory paths
5+
HOME_DIR = Path(os.environ.get("VIRTUAL_ENV", Path.home()))
6+
SOLC_SELECT_DIR = HOME_DIR / ".solc-select"
7+
ARTIFACTS_DIR = SOLC_SELECT_DIR / "artifacts"
118

12-
# CLI Commands
9+
# CLI commands
1310
INSTALL_COMMAND = "install"
1411
USE_COMMAND = "use"
1512
VERSIONS_COMMAND = "versions"

solc_select/infrastructure/filesystem.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -30,20 +30,19 @@ def get_current_version(self) -> SolcVersion | None:
3030
return None
3131

3232
global_version_file = self.config_dir / "global-version"
33-
if global_version_file.exists():
34-
try:
35-
with open(global_version_file, encoding="utf-8") as f:
36-
return SolcVersion.parse(f.read().strip())
37-
except (OSError, ValueError):
38-
return None
33+
if not global_version_file.exists():
34+
return None
3935

40-
return None
36+
try:
37+
version_text = global_version_file.read_text(encoding="utf-8").strip()
38+
return SolcVersion.parse(version_text)
39+
except (OSError, ValueError):
40+
return None
4141

4242
def set_global_version(self, version: SolcVersion) -> None:
4343
"""Set the global version."""
4444
global_version_file = self.config_dir / "global-version"
45-
with open(global_version_file, "w", encoding="utf-8") as f:
46-
f.write(str(version))
45+
global_version_file.write_text(str(version), encoding="utf-8")
4746

4847
def get_version_source(self) -> str:
4948
"""Get the source of the current version setting."""
@@ -77,17 +76,17 @@ def get_installed_versions(self) -> list[SolcVersion]:
7776

7877
installed = []
7978
for item in self.artifacts_dir.iterdir():
80-
if item.is_dir() and item.name.startswith("solc-"):
81-
version_str = item.name.replace("solc-", "")
82-
try:
83-
version = SolcVersion.parse(version_str)
84-
if self.is_installed(version):
85-
installed.append(version)
86-
except ValueError:
87-
continue
88-
89-
installed.sort()
90-
return installed
79+
if not (item.is_dir() and item.name.startswith("solc-")):
80+
continue
81+
version_str = item.name.removeprefix("solc-")
82+
try:
83+
version = SolcVersion.parse(version_str)
84+
if self.is_installed(version):
85+
installed.append(version)
86+
except ValueError:
87+
pass
88+
89+
return sorted(installed)
9190

9291
def is_installed(self, version: SolcVersion) -> bool:
9392
"""Check if a version is installed."""

solc_select/models/artifacts.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,9 @@ def __post_init__(self) -> None:
3333
raise ValueError("Download URL cannot be empty")
3434
if not self.checksum_sha256:
3535
raise ValueError("SHA256 checksum cannot be empty")
36-
# Normalize by removing 0x prefix
37-
if self.checksum_sha256.startswith("0x"):
38-
object.__setattr__(self, "checksum_sha256", self.checksum_sha256[2:])
39-
if self.checksum_keccak256 and self.checksum_keccak256.startswith("0x"):
40-
object.__setattr__(self, "checksum_keccak256", self.checksum_keccak256[2:])
36+
self.checksum_sha256 = self.checksum_sha256.removeprefix("0x")
37+
if self.checksum_keccak256:
38+
self.checksum_keccak256 = self.checksum_keccak256.removeprefix("0x")
4139

4240
@property
4341
def is_zip_archive(self) -> bool:

solc_select/models/platforms.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,22 @@ def __post_init__(self) -> None:
2525

2626
def get_capability(self) -> PlatformCapability:
2727
"""Get the capability declaration for this platform."""
28-
key = f"{self.os_type}-{self.architecture}"
29-
return CAPABILITY_REGISTRY.get(key, self._create_default_capability())
28+
identifier = self.to_identifier()
29+
return CAPABILITY_REGISTRY.get(str(identifier), self._create_default_capability())
3030

3131
def _create_default_capability(self) -> PlatformCapability:
3232
"""Create default capability (native-only, no emulation)."""
33-
platform_id = PlatformIdentifier(self.os_type, self.architecture)
33+
platform_id = self.to_identifier()
3434
return PlatformCapability(
3535
host_platform=platform_id,
3636
native_support=platform_id,
3737
emulation_capabilities=[],
3838
)
3939

40+
def to_identifier(self) -> PlatformIdentifier:
41+
"""Convert to a PlatformIdentifier."""
42+
return PlatformIdentifier(self.os_type, self.architecture)
43+
4044
@classmethod
4145
def current(cls) -> "Platform":
4246
"""Get the current system platform."""

solc_select/platform_capabilities.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ class PlatformIdentifier:
1212
os_type: str # 'linux', 'darwin', 'windows'
1313
architecture: str # 'amd64', 'arm64'
1414

15+
def __str__(self) -> str:
16+
return f"{self.os_type}-{self.architecture}"
17+
1518

1619
@dataclass(frozen=True)
1720
class EmulationCapability:

solc_select/repositories.py

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,10 @@ def __init__(
2626
has_latest_release: bool = False,
2727
):
2828
self.session = session
29-
self._base_url = base_url
30-
self._list_url = list_url
29+
self.base_url = base_url
30+
self.list_url = list_url
3131
self._has_latest_release = has_latest_release
3232

33-
@property
34-
def base_url(self) -> str:
35-
return self._base_url
36-
37-
@property
38-
def list_url(self) -> str:
39-
return self._list_url
40-
4133
@lru_cache(maxsize=5) # noqa: B019
4234
def _fetch_list_json(self) -> dict[str, Any]:
4335
response = self.session.get(self.list_url)
@@ -77,14 +69,10 @@ def get_checksums(self, version: SolcVersion) -> tuple[str, str | None]:
7769
if not matches or not matches[0]["sha256"]:
7870
raise ValueError(f"Unable to retrieve checksum for {version}")
7971

80-
sha256_hash = matches[0]["sha256"]
72+
sha256_hash = matches[0]["sha256"].removeprefix("0x")
8173
keccak256_hash = matches[0].get("keccak256")
82-
83-
# Normalize checksums by removing 0x prefix if present
84-
if sha256_hash and sha256_hash.startswith("0x"):
85-
sha256_hash = sha256_hash[2:]
86-
if keccak256_hash and keccak256_hash.startswith("0x"):
87-
keccak256_hash = keccak256_hash[2:]
74+
if keccak256_hash:
75+
keccak256_hash = keccak256_hash.removeprefix("0x")
8876

8977
return sha256_hash, keccak256_hash
9078

solc_select/services/artifact_manager.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,23 @@ def verify_checksum(self, artifact: SolcArtifact, file_handle: BufferedRandom) -
9595
if artifact.checksum_keccak256 and artifact.checksum_keccak256 != local_keccak256:
9696
raise ChecksumMismatchError(artifact.checksum_keccak256, local_keccak256, "Keccak256")
9797

98+
def _download_artifact(self, artifact: SolcArtifact) -> None:
99+
"""Download artifact and verify checksums."""
100+
response = self.session.get(artifact.download_url, stream=True)
101+
response.raise_for_status()
102+
103+
with open(artifact.file_path, "w+b", opener=partial(os.open, mode=0o664)) as f:
104+
try:
105+
for chunk in response.iter_content(chunk_size=8192):
106+
if chunk:
107+
f.write(chunk)
108+
except KeyboardInterrupt:
109+
if artifact.file_path.exists():
110+
artifact.file_path.unlink(missing_ok=True)
111+
raise
112+
113+
self.verify_checksum(artifact, f)
114+
98115
def download_and_install(self, version: SolcVersion, silent: bool = False) -> bool:
99116
"""Download and install a Solidity compiler version."""
100117
if self.filesystem.is_installed(version):
@@ -115,21 +132,7 @@ def download_and_install(self, version: SolcVersion, silent: bool = False) -> bo
115132
self.filesystem.ensure_artifact_directory(version)
116133

117134
try:
118-
response = self.session.get(artifact.download_url, stream=True)
119-
response.raise_for_status()
120-
121-
with open(artifact.file_path, "w+b", opener=partial(os.open, mode=0o664)) as f:
122-
try:
123-
for chunk in response.iter_content(chunk_size=8192):
124-
if chunk:
125-
f.write(chunk)
126-
except KeyboardInterrupt:
127-
# Clean up partially downloaded file on interrupt
128-
if artifact.file_path.exists():
129-
artifact.file_path.unlink(missing_ok=True)
130-
raise
131-
132-
self.verify_checksum(artifact, f)
135+
self._download_artifact(artifact)
133136

134137
if artifact.is_zip_archive:
135138
self._extract_zip_archive(artifact)

solc_select/services/platform_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def warn_about_arm64_compatibility(self, force: bool = False) -> None:
3434
if self.platform.architecture != "arm64":
3535
return
3636

37-
warning_file = SOLC_SELECT_DIR.joinpath(".arm64_warning_shown")
37+
warning_file = SOLC_SELECT_DIR / ".arm64_warning_shown"
3838
if not force and warning_file.exists():
3939
return
4040

solc_select/services/repository_matcher.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def find_repository_for_version(
7777
if not exact or str(version) in repo.available_versions:
7878
return repo, target_platform
7979

80-
platform_list = ", ".join(str(p) for p in runnable_platforms)
80+
platform_list = ", ".join(map(str, runnable_platforms))
8181
raise VersionNotFoundError(
8282
str(version),
8383
available_versions=[],
@@ -124,15 +124,13 @@ def _create_repository(
124124
repository_id = manifest.repository_id
125125

126126
if repository_id == "soliditylang":
127-
platform_obj = Platform(os_type=platform.os_type, architecture=platform.architecture)
127+
platform_obj = Platform(platform.os_type, platform.architecture)
128128
return SoliditylangRepository(platform_obj, self.session)
129129

130-
factories = {
131-
"crytic": CryticRepository,
132-
"alloy": AlloyRepository,
133-
}
134-
factory = factories.get(repository_id)
135-
if factory is not None:
136-
return factory(self.session)
130+
if repository_id == "crytic":
131+
return CryticRepository(self.session)
132+
133+
if repository_id == "alloy":
134+
return AlloyRepository(self.session)
137135

138136
raise ValueError(f"Unknown repository: {repository_id}")

solc_select/services/solc_service.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def __init__(self, platform: Platform | None = None):
4848
)
4949
self.platform_service = PlatformService(platform)
5050

51-
def get_current_version(self) -> tuple[SolcVersion | None, str]:
51+
def get_current_version(self) -> tuple[SolcVersion, str]:
5252
"""Get the current version and its source."""
5353
version = self.filesystem.get_current_version()
5454
source = self.filesystem.get_version_source()
@@ -57,8 +57,7 @@ def get_current_version(self) -> tuple[SolcVersion | None, str]:
5757
raise NoVersionSetError()
5858

5959
if not self.filesystem.is_installed(version):
60-
installed_versions = self.filesystem.get_installed_versions()
61-
installed_strs = [str(v) for v in installed_versions]
60+
installed_strs = [str(v) for v in self.filesystem.get_installed_versions()]
6261
raise VersionNotInstalledError(str(version), installed_strs, source)
6362

6463
return version, source
@@ -153,9 +152,6 @@ def execute_solc(self, args: list[str]) -> None:
153152
print(f"Error: {e}", file=sys.stderr)
154153
sys.exit(1)
155154

156-
if version is None:
157-
sys.exit(1)
158-
159155
binary_path = self.filesystem.get_binary_path(version)
160156
artifact = self.artifact_manager.create_local_artifact_metadata(version)
161157

0 commit comments

Comments
 (0)