Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "feat: adding optional directory command for init, scan, and update" #157

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 13 additions & 20 deletions secureli/abstractions/pre_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,28 +189,29 @@ def secret_detection_hook_id(self, language: str) -> Optional[str]:

return None

def install(self, folder_path: Path, language: str) -> InstallResult:
def install(self, language: str) -> InstallResult:
"""
Identifies the template we hold for the specified language, writes it, installs it, and cleans up
:param language: The language to identify a template for
:raises LanguageNotSupportedError if a pre-commit template cannot be found for the specified language
:raises InstallFailedError if the template was found, but an error occurred installing it
"""
path_to_pre_commit_file = Path(folder_path / ".pre-commit-config.yaml")

path_to_pre_commit_file = Path(".pre-commit-config.yaml")

# Raises a LanguageNotSupportedError if language doesn't resolve to a yaml file
language_config = self._get_language_config(language)

with open(path_to_pre_commit_file, "w") as f:
f.write(language_config.config_data)

completed_process = subprocess.run(["pre-commit", "install"], cwd=folder_path)
completed_process = subprocess.run(["pre-commit", "install"])
if completed_process.returncode != 0:
raise InstallFailedError(
f"Installing the pre-commit script for {language} failed"
)

install_configs_result = self._install_pre_commit_configs(folder_path, language)
install_configs_result = self._install_pre_commit_configs(language)

return InstallResult(
successful=True,
Expand Down Expand Up @@ -326,15 +327,13 @@ def execute_hooks(

def autoupdate_hooks(
self,
folder_path: Path,
bleeding_edge: bool = False,
freeze: bool = False,
repos: Optional[list] = None,
) -> ExecuteResult:
"""
Updates the precommit hooks but executing precommit's autoupdate command. Additional info at
https://pre-commit.com/#pre-commit-autoupdate
:param folder path: specified full path directory (default to current directory)
:param bleeding edge: True if updating to the bleeding edge of the default branch instead of
the latest tagged version (which is the default behavior)
:param freeze: Set to True to store "frozen" hashes in rev instead of tag names.
Expand Down Expand Up @@ -368,9 +367,7 @@ def autoupdate_hooks(

subprocess_args.extend(repo_args)

completed_process = subprocess.run(
subprocess_args, cwd=folder_path, stdout=subprocess.PIPE
)
completed_process = subprocess.run(subprocess_args, stdout=subprocess.PIPE)
output = (
completed_process.stdout.decode("utf8") if completed_process.stdout else ""
)
Expand All @@ -379,16 +376,14 @@ def autoupdate_hooks(
else:
return ExecuteResult(successful=True, output=output)

def update(self, folder_path: Path) -> ExecuteResult:
def update(self) -> ExecuteResult:
"""
Installs the hooks defined in pre-commit-config.yml.
:return: ExecuteResult, indicating success or failure.
"""
subprocess_args = ["pre-commit", "install-hooks", "--color", "always"]

completed_process = subprocess.run(
subprocess_args, cwd=folder_path, stdout=subprocess.PIPE
)
completed_process = subprocess.run(subprocess_args, stdout=subprocess.PIPE)
output = (
completed_process.stdout.decode("utf8") if completed_process.stdout else ""
)
Expand All @@ -397,7 +392,7 @@ def update(self, folder_path: Path) -> ExecuteResult:
else:
return ExecuteResult(successful=True, output=output)

def remove_unused_hooks(self, folder_path: Path) -> ExecuteResult:
def remove_unused_hooks(self) -> ExecuteResult:
"""
Removes unused hook repos from the cache. Pre-commit determines which flags are "unused" by comparing
the repos to the pre-commit-config.yaml file. Any cached hook repos that are not in the config file
Expand All @@ -406,9 +401,7 @@ def remove_unused_hooks(self, folder_path: Path) -> ExecuteResult:
"""
subprocess_args = ["pre-commit", "gc", "--color", "always"]

completed_process = subprocess.run(
subprocess_args, cwd=folder_path, stdout=subprocess.PIPE
)
completed_process = subprocess.run(subprocess_args, stdout=subprocess.PIPE)
output = (
completed_process.stdout.decode("utf8") if completed_process.stdout else ""
)
Expand Down Expand Up @@ -826,7 +819,7 @@ def _load_language_config_file(self, language: str) -> LoadLanguageConfigsResult
return LoadLanguageConfigsResult(success=False, config_data=list())

def _install_pre_commit_configs(
self, folder_path: Path, language: str
self, language: str
) -> LanguagePreCommitConfigInstallResult:
"""
Install any config files for given language to support any pre-commit commands.
Expand All @@ -848,13 +841,13 @@ def _install_pre_commit_configs(
try:
for key in config:
config_name = f"{slugify(language)}.{key}.yaml"
path_to_config_file = folder_path / f".secureli/{config_name}"
path_to_config_file = Path(f".secureli/{config_name}")

with open(path_to_config_file, "w") as f:
f.write(yaml.dump(config[key]))

completed_process = subprocess.run(
["pre-commit", "install-language-config"], cwd=folder_path
["pre-commit", "install-language-config"]
)

if completed_process.returncode != 0:
Expand Down
32 changes: 10 additions & 22 deletions secureli/actions/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,7 @@ def verify_install(
:param always_yes: Assume "Yes" to all prompts
"""

config = (
SecureliConfig()
if reset
else self.action_deps.secureli_config.load(folder_path=folder_path)
)
config = SecureliConfig() if reset else self.action_deps.secureli_config.load()

if not config.overall_language or not config.version_installed:
return self._install_secureli(folder_path, always_yes)
Expand All @@ -102,9 +98,7 @@ def verify_install(

# Check for a new version and prompt for upgrade if available
if available_version != config.version_installed:
return self._upgrade_secureli(
folder_path, config, available_version, always_yes
)
return self._upgrade_secureli(config, available_version, always_yes)

# Validates the current .pre-commit-config.yaml against the generated config
config_validation_result = self.action_deps.pre_commit.validate_config(
Expand All @@ -114,7 +108,7 @@ def verify_install(
# If config mismatch between available version and current version prompt for upgrade
if not config_validation_result.successful:
self.action_deps.echo.print(config_validation_result.output)
return self._update_secureli(folder_path, always_yes)
return self._update_secureli(always_yes)

self.action_deps.echo.print(
f"SeCureLI is installed and up-to-date (language = {config.overall_language})"
Expand All @@ -125,11 +119,7 @@ def verify_install(
)

def _upgrade_secureli(
self,
folder_path: Path,
config: SecureliConfig,
available_version: str,
always_yes: bool,
self, config: SecureliConfig, available_version: str, always_yes: bool
) -> VerifyResult:
"""
Installs SeCureLI into the given folder path and returns the new configuration
Expand All @@ -154,12 +144,12 @@ def _upgrade_secureli(

try:
metadata = self.action_deps.language_support.apply_support(
folder_path, config.overall_language
config.overall_language
)

# Update config with new version installed and save it
config.version_installed = metadata.version
self.action_deps.secureli_config.save(folder_path, config)
self.action_deps.secureli_config.save(config)
self.action_deps.echo.print("SeCureLI has been upgraded successfully")
return VerifyResult(
outcome=VerifyOutcome.UPGRADE_SUCCEEDED,
Expand Down Expand Up @@ -215,9 +205,7 @@ def _install_secureli(self, folder_path: Path, always_yes: bool) -> VerifyResult
f"Overall Detected Language: {overall_language}"
)

metadata = self.action_deps.language_support.apply_support(
folder_path, overall_language
)
metadata = self.action_deps.language_support.apply_support(overall_language)

except (ValueError, LanguageNotSupportedError, InstallFailedError) as e:
self.action_deps.echo.error(
Expand All @@ -231,7 +219,7 @@ def _install_secureli(self, folder_path: Path, always_yes: bool) -> VerifyResult
overall_language=overall_language,
version_installed=metadata.version,
)
self.action_deps.secureli_config.save(folder_path, config)
self.action_deps.secureli_config.save(config)

if secret_test_id := metadata.security_hook_id:
self.action_deps.echo.print(
Expand All @@ -255,7 +243,7 @@ def _install_secureli(self, folder_path: Path, always_yes: bool) -> VerifyResult
analyze_result=analyze_result,
)

def _update_secureli(self, folder_path: Path, always_yes: bool):
def _update_secureli(self, always_yes: bool):
"""
Prompts the user to update to the latest secureli install.
:param always_yes: Assume "Yes" to all prompts
Expand All @@ -272,7 +260,7 @@ def _update_secureli(self, folder_path: Path, always_yes: bool):
self.action_deps.echo.print("\nUpdate declined.\n")
return VerifyResult(outcome=VerifyOutcome.UPDATE_CANCELED)

update_result = self.action_deps.updater.update(folder_path)
update_result = self.action_deps.updater.update()
details = update_result.output
self.action_deps.echo.print(details)

Expand Down
3 changes: 1 addition & 2 deletions secureli/actions/build.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from pathlib import Path
from secureli.abstractions.echo import EchoAbstraction, Color
from secureli.services.logging import LoggingService, LogAction

Expand All @@ -21,4 +20,4 @@ def print_build(self, color: Color):
"""
self.echo.print(self.build_data, color=color, bold=True)

self.logging.success(Path("."), LogAction.build)
self.logging.success(LogAction.build)
4 changes: 2 additions & 2 deletions secureli/actions/initializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ def initialize_repo(self, folder_path: Path, reset: bool, always_yes: bool):
"""
verify_result = self.verify_install(folder_path, reset, always_yes)
if verify_result.outcome in ScanAction.halting_outcomes:
self.logging.failure(folder_path, LogAction.init, verify_result.outcome)
self.logging.failure(LogAction.init, verify_result.outcome)
else:
self.logging.success(folder_path, LogAction.init)
self.logging.success(LogAction.init)
3 changes: 1 addition & 2 deletions secureli/actions/scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ def scan_repo(

if not scan_result.successful:
log_data = self.logging.failure(
folder_path,
LogAction.scan,
scan_result_failures_json_string,
failure_count,
Expand All @@ -95,7 +94,7 @@ def scan_repo(
post_log(log_data.json(exclude_none=True))
else:
self.echo.print("Scan executed successfully and detected no issues!")
log_data = self.logging.success(folder_path, LogAction.scan)
log_data = self.logging.success(LogAction.scan)

post_log(log_data.json(exclude_none=True))

Expand Down
15 changes: 7 additions & 8 deletions secureli/actions/update.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from typing import Optional

from pathlib import Path
from secureli.abstractions.echo import EchoAbstraction
from secureli.services.logging import LoggingService, LogAction
from secureli.services.updater import UpdaterService
Expand All @@ -20,7 +19,7 @@ def __init__(
self.logging = logging
self.updater = updater

def update_hooks(self, folder_path: Path, latest: Optional[bool] = False):
def update_hooks(self, latest: Optional[bool] = False):
"""
Installs the hooks defined in pre-commit-config.yml.
:param latest: Indicates whether you want to update to the latest versions
Expand All @@ -29,26 +28,26 @@ def update_hooks(self, folder_path: Path, latest: Optional[bool] = False):
"""
if latest:
self.echo.print("Updating hooks to the latest version...")
update_result = self.updater.update_hooks(folder_path)
update_result = self.updater.update_hooks()
details = (
update_result.output
or "Unknown output while updating hooks to latest version"
)
self.echo.print(details)
if not update_result.successful:
self.echo.print(details)
self.logging.failure(folder_path, LogAction.update, details)
self.logging.failure(LogAction.update, details)
else:
self.echo.print("Hooks successfully updated to latest version")
self.logging.success(folder_path, LogAction.update)
self.logging.success(LogAction.update)
else:
self.echo.print("Beginning update...")
install_result = self.updater.update(folder_path)
install_result = self.updater.update()
details = install_result.output or "Unknown output during hook installation"
self.echo.print(details)
if not install_result.successful:
self.echo.print(details)
self.logging.failure(folder_path, LogAction.update, details)
self.logging.failure(LogAction.update, details)
else:
self.echo.print("Update executed successfully.")
self.logging.success(folder_path, LogAction.update)
self.logging.success(LogAction.update)
26 changes: 4 additions & 22 deletions secureli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,11 @@ def init(
"-y",
help="Say 'yes' to every prompt automatically without input",
),
directory: Optional[str] = Option(
".",
"--directory",
"-d",
help="Run seCureLI on specified full path directory (default to current directory)",
),
):
"""
Detect languages and initialize pre-commit hooks and linters for the project
"""
container.initializer_action().initialize_repo(Path(directory), reset, yes)
container.initializer_action().initialize_repo(Path("."), reset, yes)


@app.command()
Expand All @@ -81,17 +75,11 @@ def scan(
"-t",
help="Limit the scan to a specific hook ID from your pre-commit config",
),
directory: Optional[str] = Option(
".",
"--directory",
"-d",
help="Run seCureLI on specified full path directory (default to current directory)",
),
):
"""
Performs an explicit check of the repository to detect security issues without remote logging.
"""
container.scan_action().scan_repo(Path(directory), mode, yes, specific_test)
container.scan_action().scan_repo(Path("."), mode, yes, specific_test)


@app.command(hidden=True)
Expand All @@ -109,18 +97,12 @@ def update(
"--latest",
"-l",
help="Update the installed pre-commit hooks to their latest versions",
),
directory: Optional[str] = Option(
".",
"--directory",
"-d",
help="Run seCureLI on specified full path directory (default to current directory)",
),
)
):
"""
Update linters, configuration, and all else needed to maintain a secure repository.
"""
container.update_action().update_hooks(Path(directory), latest)
container.update_action().update_hooks(latest)


if __name__ == "__main__":
Expand Down
Loading