Skip to content

Commit d3e9217

Browse files
Merge pull request #3 from eapache-opslevel/tidra-repository_wide_code_simplification_initiative-199db0b2
Repository-Wide Code Simplification Initiative
2 parents 2dd052d + d9811d0 commit d3e9217

5 files changed

Lines changed: 280 additions & 154 deletions

File tree

add-static-analysis-workflow.py

Lines changed: 105 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
- Documents which repositories were updated vs. skipped in tracking logs
1414
"""
1515

16-
import os
1716
import sys
1817
import subprocess
1918
import yaml
@@ -221,65 +220,99 @@ def write_workflow_file(self, content: str) -> bool:
221220
logger.error(f"Error writing workflow file: {e}")
222221
return False
223222

224-
def add_workflow(self) -> dict:
225-
"""Add or update the static analysis workflow.
223+
def _create_result_dict(self, success=False, action=None, reason=None, default_branch=None) -> dict:
224+
"""Create a standardized result dictionary.
226225
226+
Args:
227+
success: Whether the operation was successful
228+
action: Action taken (created/updated/skipped)
229+
reason: Reason for the action or failure
230+
default_branch: Default branch name
231+
227232
Returns:
228233
Dictionary with result information
229234
"""
230-
result = {
235+
return {
231236
"repository": str(self.repo_path),
232237
"timestamp": datetime.now().isoformat(),
233-
"success": False,
234-
"action": None,
235-
"reason": None,
236-
"default_branch": None
238+
"success": success,
239+
"action": action,
240+
"reason": reason,
241+
"default_branch": default_branch
237242
}
243+
244+
def _prepare_workflow_content(self, result: dict) -> Optional[str]:
245+
"""Prepare and validate workflow content.
238246
239-
# Detect default branch
247+
Args:
248+
result: Result dictionary to update on failure
249+
250+
Returns:
251+
Workflow content if successful, None otherwise
252+
"""
240253
default_branch = self.detect_default_branch()
241254
if not default_branch:
242255
result["reason"] = "Could not detect default branch"
243256
logger.error(result["reason"])
244-
return result
257+
return None
245258

246259
result["default_branch"] = default_branch
247-
248-
# Generate workflow content
249260
workflow_content = self.generate_workflow_content(default_branch)
250261

251-
# Validate YAML
252262
if not self.validate_yaml(workflow_content):
253263
result["reason"] = "Generated workflow has invalid YAML syntax"
254264
logger.error(result["reason"])
255-
return result
265+
return None
266+
267+
return workflow_content
268+
269+
def _write_workflow_if_needed(self, workflow_content: str, result: dict) -> bool:
270+
"""Write workflow file if update is needed.
256271
257-
# Check if update is needed
272+
Args:
273+
workflow_content: Content to write
274+
result: Result dictionary to update
275+
276+
Returns:
277+
True if successful, False otherwise
278+
"""
258279
should_update, reason = self.should_update_workflow(workflow_content)
259280
result["reason"] = reason
260281

261282
if not should_update:
262283
result["success"] = True
263284
result["action"] = "skipped"
264285
logger.info(f"Skipping: {reason}")
265-
return result
286+
return True
266287

267-
# Create directory if needed
268288
if not self.create_workflows_directory():
269289
result["reason"] = "Failed to create workflows directory"
270290
logger.error(result["reason"])
271-
return result
291+
return False
272292

273-
# Write workflow file
274293
if not self.write_workflow_file(workflow_content):
275294
result["reason"] = "Failed to write workflow file"
276295
logger.error(result["reason"])
277-
return result
296+
return False
278297

279298
result["success"] = True
280299
result["action"] = "updated" if self.workflow_file.exists() else "created"
281300
logger.info(f"Successfully {result['action']} workflow file")
301+
return True
302+
303+
def add_workflow(self) -> dict:
304+
"""Add or update the static analysis workflow.
305+
306+
Returns:
307+
Dictionary with result information
308+
"""
309+
result = self._create_result_dict()
310+
311+
workflow_content = self._prepare_workflow_content(result)
312+
if not workflow_content:
313+
return result
282314

315+
self._write_workflow_if_needed(workflow_content, result)
283316
return result
284317

285318
def save_tracking_log(self, result: dict, log_file: Optional[str] = None):
@@ -314,10 +347,13 @@ def save_tracking_log(self, result: dict, log_file: Optional[str] = None):
314347
logger.error(f"Error saving tracking log: {e}")
315348

316349

317-
def main():
318-
"""Main entry point."""
319-
import argparse
350+
def _create_argument_parser():
351+
"""Create and configure argument parser.
320352
353+
Returns:
354+
Configured ArgumentParser instance
355+
"""
356+
import argparse
321357
parser = argparse.ArgumentParser(
322358
description="Add standardized static analysis workflow to repositories"
323359
)
@@ -336,35 +372,43 @@ def main():
336372
action="store_true",
337373
help="Show what would be done without making changes"
338374
)
375+
return parser
376+
377+
378+
def _run_dry_run(manager):
379+
"""Execute dry run mode.
339380
340-
args = parser.parse_args()
341-
342-
# Initialize manager
343-
manager = StaticAnalysisWorkflowManager(args.repo_path)
381+
Args:
382+
manager: StaticAnalysisWorkflowManager instance
383+
384+
Returns:
385+
Exit code (0 for success)
386+
"""
387+
logger.info("DRY RUN MODE - No changes will be made")
388+
default_branch = manager.detect_default_branch()
344389

345-
if args.dry_run:
346-
logger.info("DRY RUN MODE - No changes will be made")
347-
default_branch = manager.detect_default_branch()
348-
if default_branch:
349-
workflow_content = manager.generate_workflow_content(default_branch)
350-
print("\nGenerated workflow content:")
351-
print("-" * 80)
352-
print(workflow_content)
353-
print("-" * 80)
354-
should_update, reason = manager.should_update_workflow(workflow_content)
355-
print(f"\nAction needed: {'Yes' if should_update else 'No'}")
356-
print(f"Reason: {reason}")
357-
else:
358-
print("ERROR: Could not detect default branch")
390+
if not default_branch:
391+
print("ERROR: Could not detect default branch")
359392
return 0
360393

361-
# Add workflow
362-
result = manager.add_workflow()
394+
workflow_content = manager.generate_workflow_content(default_branch)
395+
print("\nGenerated workflow content:")
396+
print("-" * 80)
397+
print(workflow_content)
398+
print("-" * 80)
363399

364-
# Save tracking log
365-
manager.save_tracking_log(result, args.log_file)
400+
should_update, reason = manager.should_update_workflow(workflow_content)
401+
print(f"\nAction needed: {'Yes' if should_update else 'No'}")
402+
print(f"Reason: {reason}")
403+
return 0
404+
405+
406+
def _print_summary(result):
407+
"""Print operation summary.
366408
367-
# Print summary
409+
Args:
410+
result: Result dictionary from add_workflow
411+
"""
368412
print("\n" + "=" * 80)
369413
print("SUMMARY")
370414
print("=" * 80)
@@ -374,6 +418,21 @@ def main():
374418
print(f"Success: {result['success']}")
375419
print(f"Reason: {result['reason']}")
376420
print("=" * 80)
421+
422+
423+
def main():
424+
"""Main entry point."""
425+
parser = _create_argument_parser()
426+
args = parser.parse_args()
427+
428+
manager = StaticAnalysisWorkflowManager(args.repo_path)
429+
430+
if args.dry_run:
431+
return _run_dry_run(manager)
432+
433+
result = manager.add_workflow()
434+
manager.save_tracking_log(result, args.log_file)
435+
_print_summary(result)
377436

378437
return 0 if result['success'] else 1
379438

0 commit comments

Comments
 (0)