-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_workflow.sh
More file actions
1725 lines (1444 loc) · 55.9 KB
/
Copy pathgithub_workflow.sh
File metadata and controls
1725 lines (1444 loc) · 55.9 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
set -e
REPO="mohameden19961/codeguard"
DIR="/tmp/opencode/codeguard"
cd "$DIR"
echo "=== CREATING ISSUES ==="
# Create issues
ISSUE_1=$(gh issue create --repo "$REPO" --title "Add plugin system for custom checks" \
--label "enhancement" \
--body "## Feature Request
We need a plugin system that allows users to write custom checks without modifying the core codebase.
### Acceptance Criteria
- [ ] Plugin discovery from a directory
- [ ] Plugin loading and registration
- [ ] Documentation for creating plugins
- [ ] Example plugin included" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_1: Add plugin system"
ISSUE_2=$(gh issue create --repo "$REPO" --title "Fix config parsing with empty YAML values" \
--label "bug" \
--body "## Bug Report
When the config file contains empty values, the parser crashes with a TypeError.
### Steps to Reproduce
1. Create .codeguard.yml with an empty section
2. Run codeguard analyze
3. See crash" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_2: Fix config parsing"
ISSUE_3=$(gh issue create --repo "$REPO" --title "Add HTML dashboard with charts and trends" \
--label "enhancement" \
--body "## Feature Request
Enhance the HTML report to include charts showing violation trends, severity distribution, and file-level metrics.
### Design
- Use Chart.js for interactive charts
- Add trend graphs over time
- Show severity distribution pie chart
- File-level heat map" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_3: HTML dashboard"
ISSUE_4=$(gh issue create --repo "$REPO" --title "Improve performance for large codebases" \
--label "enhancement" \
--label "performance" \
--body "## Performance Improvement
Analysis of large codebases (>10K files) is too slow. Need to optimize.
### Optimizations
- [ ] Incremental file scanning
- [ ] Better caching strategy
- [ ] Multi-processing support
- [ ] Memory-efficient result collection" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_4: Performance improvements"
ISSUE_5=$(gh issue create --repo "$REPO" --title "Add SARIF output format support" \
--label "enhancement" \
--body "## Feature Request
Support SARIF (Static Analysis Results Interchange Format) output for integration with GitHub Code Scanning.
### Details
- Implement SARIF 2.1.0 format
- Include all violation details
- Map severity levels correctly" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_5: SARIF format"
ISSUE_6=$(gh issue create --repo "$REPO" --title "Memory leak in cache module" \
--label "bug" \
--label "priority-high" \
--body "## Bug Report
The cache module doesn't properly clean up old entries, causing memory usage to grow unbounded.
### Impact
- Memory grows with each analysis run
- Can cause OOM for large projects
- Cache directory fills up" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_6: Memory leak"
ISSUE_7=$(gh issue create --repo "$REPO" --title "Add pre-commit hook support" \
--label "enhancement" \
--body "## Feature Request
Add official pre-commit hook support so users can run CodeGuard as part of their pre-commit workflow.
### Tasks
- [ ] Create pre-commit hook script
- [ ] Add pre-commit config example
- [ ] Document integration steps" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_7: Pre-commit hooks"
ISSUE_8=$(gh issue create --repo "$REPO" --title "Refactor core engine for testability" \
--label "refactor" \
--body "## Refactoring
The core AnalysisEngine class is difficult to test due to tight coupling with file system and checks.
### Plan
- [ ] Extract file reading to a separate service
- [ ] Use dependency injection for checks
- [ ] Add interfaces for all major components
- [ ] Increase test coverage to 90%" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_8: Core refactoring"
ISSUE_9=$(gh issue create --repo "$REPO" --title "Add JSON Schema validation for config" \
--label "enhancement" \
--body "## Feature Request
Validate the configuration file against a JSON Schema to provide better error messages.
### Schema
- Define JSON Schema for all config options
- Validate on load
- Provide helpful error messages for invalid config" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_9: JSON Schema validation"
ISSUE_10=$(gh issue create --repo "$REPO" --title "Create GitHub Action for CodeGuard" \
--label "enhancement" \
--label "documentation" \
--body "## Feature Request
Create a GitHub Action that makes it easy to run CodeGuard in CI pipelines.
### Deliverables
- GitHub Action Dockerfile
- Action metadata file
- Documentation page
- Example workflow" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_10: GitHub Action"
ISSUE_11=$(gh issue create --repo "$REPO" --title "Fix UnicodeDecodeError on binary files" \
--label "bug" \
--body "## Bug Report
CodeGuard crashes with UnicodeDecodeError when encountering binary files in the analysis path.
### Fix
- Skip binary files during collection
- Add binary file detection
- Graceful error handling" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_11: Binary file fix"
ISSUE_12=$(gh issue create --repo "$REPO" --title "Add auto-fix capability for style issues" \
--label "enhancement" \
--body "## Feature Request
Allow CodeGuard to automatically fix certain issues (trailing whitespace, line endings, etc.).
### Auto-fixable issues
- [ ] Trailing whitespace removal
- [ ] Line ending normalization
- [ ] Blank line normalization
- [ ] Import ordering" | grep -oE '[0-9]+$')
echo "Issue #$ISSUE_12: Auto-fix support"
echo ""
echo "=== ISSUES CREATED ==="
echo "Issue #$ISSUE_1: Plugin system"
echo "Issue #$ISSUE_2: Config parsing fix"
echo "Issue #$ISSUE_3: HTML dashboard"
echo "Issue #$ISSUE_4: Performance"
echo "Issue #$ISSUE_5: SARIF format"
echo "Issue #$ISSUE_6: Memory leak"
echo "Issue #$ISSUE_7: Pre-commit hooks"
echo "Issue #$ISSUE_8: Core refactoring"
echo "Issue #$ISSUE_9: JSON Schema"
echo "Issue #$ISSUE_10: GitHub Action"
echo "Issue #$ISSUE_11: Binary file fix"
echo "Issue #$ISSUE_12: Auto-fix support"
echo ""
echo "=== CREATING BRANCHES AND PUSHING CODE ==="
create_branch_and_push() {
local branch=$1
local issue=$2
local commit_count=$3
git checkout main
git pull origin main
git checkout -b "$branch"
echo "Created branch: $branch"
}
# Branch 1: plugin-system (Issue 1)
git checkout main
git checkout -b feature/plugin-system
mkdir -p src/codeguard/plugins
cat > src/codeguard/plugins/__init__.py << 'PYEOF'
"""Plugin system for custom CodeGuard checks."""
import importlib
import os
from typing import List, Type
from codeguard.checks.base import BaseCheck, CheckRegistry
class PluginManager:
def __init__(self, plugin_dir: str = None):
self.plugin_dir = plugin_dir or os.path.expanduser("~/.codeguard/plugins")
def discover_plugins(self) -> List[Type[BaseCheck]]:
if not os.path.exists(self.plugin_dir):
return []
checks = []
for fname in os.listdir(self.plugin_dir):
if fname.endswith(".py") and not fname.startswith("_"):
mod_name = fname[:-3]
spec = importlib.util.spec_from_file_location(mod_name, os.path.join(self.plugin_dir, fname))
if spec and spec.loader:
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
for attr in dir(mod):
obj = getattr(mod, attr)
if isinstance(obj, type) and issubclass(obj, BaseCheck) and obj is not BaseCheck:
CheckRegistry.register(obj)
checks.append(obj)
return checks
PYEOF
echo "Added plugin system implementation"
git add -A && git commit -m "Add plugin system with directory discovery
Implement plugin discovery from ~/.codeguard/plugins directory.
Supports loading custom check classes dynamically.
Refs: #$ISSUE_1"
cat > src/codeguard/plugins/example_plugin.py << 'PYEOF'
"""Example plugin demonstrating the CodeGuard plugin system."""
from typing import List
from codeguard.checks.base import BaseCheck
from codeguard.core.engine import Violation
from codeguard.config import Config
class TodoCheck(BaseCheck):
name = "todo_check"
description = "Warns about TODO/FIXME comments"
def check(self, file_path: str, content: str, lines: List[str]) -> List[Violation]:
violations = []
for i, line in enumerate(lines, 1):
if "TODO" in line:
violations.append(Violation(
check_name=self.name, severity="low",
message=f"Line {i} contains TODO comment",
file_path=file_path, line_number=i,
suggestion="Address TODO before committing",
))
if "FIXME" in line:
violations.append(Violation(
check_name=self.name, severity="medium",
message=f"Line {i} contains FIXME comment",
file_path=file_path, line_number=i,
suggestion="Fix the issue before committing",
))
return violations
PYEOF
echo "Added example plugin"
git add -A && git commit -m "Add example plugin for TODO/FIXME detection
Demonstrates how to create a custom check using the plugin API.
Refs: #$ISSUE_1"
cat > docs/plugin_development.md << 'PYEOF'
# Plugin Development Guide
## Overview
CodeGuard supports plugins - custom checks that extend its analysis capabilities.
## Creating a Plugin
1. Create a Python file in `~/.codeguard/plugins/`
2. Define a class that inherits from `BaseCheck`
3. Set the `name` and `description` attributes
4. Implement the `check` method
5. The plugin is automatically discovered
## Example
```python
from codeguard.checks.base import BaseCheck
from codeguard.core.engine import Violation
class MyCustomCheck(BaseCheck):
name = "my_custom_check"
description = "My custom check"
def check(self, file_path, content, lines):
violations = []
# Your analysis logic here
return violations
```
## Testing Plugins
```python
def test_my_plugin():
check = MyCustomCheck(config=Config.default())
violations = check.check("test.py", "code", ["code"])
assert len(violations) == 0
```
PYEOF
git add -A && git commit -m "Add plugin development documentation
Comprehensive guide for creating and testing custom CodeGuard plugins.
Refs: #$ISSUE_1"
git push origin feature/plugin-system
echo "Pushed feature/plugin-system"
# Branch 2: fix-config-parsing (Issue 2)
git checkout main
git checkout -b fix/config-parsing
cat > tests/test_config_edge.py << 'PYEOF'
"""Edge case tests for config parsing."""
import pytest
import yaml
import tempfile
from codeguard.config import load_config
class TestConfigEdgeCases:
def test_empty_file(self, tmp_path):
f = tmp_path / ".codeguard.yml"
f.write_text("")
config = load_config(str(f))
assert config is not None
def test_empty_sections(self, tmp_path):
f = tmp_path / ".codeguard.yml"
f.write_text("complexity:\nstyle:\n")
config = load_config(str(f))
assert config is not None
assert config.complexity.max_cyclomatic == 10
def test_partial_config(self, tmp_path):
f = tmp_path / ".codeguard.yml"
f.write_text("verbose: true\n")
config = load_config(str(f))
assert config.verbose is True
def test_invalid_yaml(self, tmp_path):
f = tmp_path / ".codeguard.yml"
f.write_text(": invalid yaml :")
config = load_config(str(f))
assert config is not None
def test_nonexistent_file(self):
config = load_config("/nonexistent/path/.codeguard.yml")
assert config is not None
assert config.verbose is False
PYEOF
git add -A && git commit -m "Add edge case tests for config parsing
Tests for empty files, empty sections, partial configs, and invalid YAML.
Refs: #$ISSUE_2"
# Fix config.py
cat > /tmp/config_fix.py << 'PYEOF'
def load_config(path=None):
if path is None:
for candidate in [".codeguard.yml", ".codeguard.yaml",
"~/.codeguard.yml", "~/.codeguard/config.yml"]:
expanded = os.path.expanduser(candidate)
if os.path.exists(expanded):
path = expanded
break
if path and os.path.exists(path):
try:
with open(path) as f:
data = yaml.safe_load(f)
if data is None:
return Config.default()
if not isinstance(data, dict):
return Config.default()
return Config.from_dict(data)
except (yaml.YAMLError, IOError):
pass
return Config.default()
PYEOF
echo "Config parsing fix prepared"
# Actually modify the real config.py
cd "$DIR"
python3 -c "
import re
with open('src/codeguard/config.py') as f:
content = f.read()
old = ''' if path and os.path.exists(path):
with open(path) as f:
data = yaml.safe_load(f)
if data is None:
return Config.default()
return Config.from_dict(data)'''
new = ''' if path and os.path.exists(path):
try:
with open(path) as f:
data = yaml.safe_load(f)
except (yaml.YAMLError, IOError):
return Config.default()
if data is None:
return Config.default()
if not isinstance(data, dict):
return Config.default()
return Config.from_dict(data)'''
content = content.replace(old, new)
with open('src/codeguard/config.py', 'w') as f:
f.write(content)
print('Config.py updated')
"
git add -A && git commit -m "Fix config parser for empty YAML and edge cases
Handle empty files, empty sections, invalid YAML gracefully.
Added try/except for parse errors and type checking.
Fixes: #$ISSUE_2"
git push origin fix/config-parsing
echo "Pushed fix/config-parsing"
# Branch 3: html-dashboard (Issue 3)
git checkout main
git checkout -b feature/html-dashboard
cat > src/codeguard/output/dashboard.py << 'PYEOF'
"""Interactive HTML dashboard with charts."""
from typing import Optional
from codeguard.config import Config
from codeguard.core.engine import AnalysisResults
class DashboardWriter:
def __init__(self, output_path: Optional[str] = None, config: Optional[Config] = None):
self.output_path = output_path
self.config = config or Config.default()
def write(self, results: AnalysisResults):
sev_counts = results.count_by_severity()
check_counts = results.count_by_check()
sev_json = str(sev_counts).replace("'", '"')
check_json = str(check_counts).replace("'", '"')
html = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CodeGuard Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {{ font-family: sans-serif; margin: 2em; background: #f5f5f5; }}
.card {{ background: white; border-radius: 8px; padding: 1.5em; margin: 1em 0; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
.grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1em; }}
.stat {{ text-align: center; }}
.stat-value {{ font-size: 2em; font-weight: bold; color: #333; }}
.stat-label {{ color: #666; font-size: 0.9em; }}
.chart-container {{ position: relative; height: 300px; }}
</style>
</head>
<body>
<h1>CodeGuard Analysis Dashboard</h1>
<div class="grid">
<div class="card stat">
<div class="stat-value">{results.files_analyzed}</div>
<div class="stat-label">Files Analyzed</div>
</div>
<div class="card stat">
<div class="stat-value">{len(results.violations)}</div>
<div class="stat-label">Total Violations</div>
</div>
<div class="card stat">
<div class="stat-value">{results.total_lines}</div>
<div class="stat-label">Lines of Code</div>
</div>
<div class="card stat">
<div class="stat-value">{results.duration:.2f}s</div>
<div class="stat-label">Duration</div>
</div>
</div>
<div class="grid">
<div class="card"><h3>Severity Distribution</h3><div class="chart-container"><canvas id="severityChart"></canvas></div></div>
<div class="card"><h3>Check Distribution</h3><div class="chart-container"><canvas id="checkChart"></canvas></div></div>
</div>
<div class="card"><h3>Recent Violations</h3><table><tr><th>Severity</th><th>Check</th><th>Message</th><th>File</th></tr>
{"".join(f"<tr><td>{v.severity}</td><td>{v.check_name}</td><td>{v.message}</td><td>{v.file_path}:{v.line_number}</td></tr>" for v in results.violations[:20])}
</table></div>
<script>
new Chart(document.getElementById('severityChart'), {{
type: 'pie',
data: {{
labels: {list(sev_counts.keys())!r},
datasets: [{{ data: {list(sev_counts.values())!r},
backgroundColor: ['#4caf50', '#ff9800', '#f44336', '#d32f2f'] }}]
}}
}});
new Chart(document.getElementById('checkChart'), {{
type: 'bar',
data: {{
labels: {list(check_counts.keys())!r},
datasets: [{{ data: {list(check_counts.values())!r},
backgroundColor: '#2196f3' }}]
}},
options: {{ scales: {{ y: {{ beginAtZero: true }} }} }}
}});
</script>
</body>
</html>'''
if self.output_path:
with open(self.output_path, "w") as f:
f.write(html)
else:
print(html)
PYEOF
git add -A && git commit -m "Add interactive HTML dashboard with Chart.js
Includes severity pie chart, check distribution bar chart,
statistics cards, and violations table.
Refs: #$ISSUE_3"
# Add dashboard writer to CLI and output init
python3 -c "
with open('src/codeguard/output/__init__.py') as f:
content = f.read()
if 'DashboardWriter' not in content:
content += 'from codeguard.output.dashboard import DashboardWriter\n'
with open('src/codeguard/output/__init__.py', 'w') as f:
f.write(content)
"
git add -A && git commit -m "Register DashboardWriter in output module
Make dashboard available as an output format option.
Refs: #$ISSUE_3"
git push origin feature/html-dashboard
echo "Pushed feature/html-dashboard"
# Branch 4: performance (Issue 4)
git checkout main
git checkout -b feature/performance
cat > src/codeguard/core/scanner.py << 'PYEOF'
"""Incremental file scanner for large codebases."""
import os
import hashlib
import json
from typing import List, Optional
from codeguard.config import Config
class IncrementalScanner:
def __init__(self, config: Config):
self.config = config
self.state_file = os.path.join(config.cache_dir, "scanner_state.json")
def get_changed_files(self, paths: List[str]) -> List[str]:
state = self._load_state()
files = self._collect_files(paths)
changed = []
for f in files:
current_hash = self._file_hash(f)
if f not in state or state[f] != current_hash:
changed.append(f)
state[f] = current_hash
self._save_state(state)
return changed
def _collect_files(self, paths: List[str]) -> List[str]:
from codeguard.core.collector import FileCollector
collector = FileCollector(self.config)
return collector.collect(paths)
def _file_hash(self, path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
def _load_state(self) -> dict:
if os.path.exists(self.state_file):
with open(self.state_file) as f:
return json.load(f)
return {}
def _save_state(self, state: dict):
os.makedirs(os.path.dirname(self.state_file), exist_ok=True)
with open(self.state_file, "w") as f:
json.dump(state, f)
PYEOF
git add -A && git commit -m "Add incremental file scanner for large codebases
Only analyzes changed files by tracking file hashes between runs.
Reduces analysis time for repeated runs.
Refs: #$ISSUE_4"
python3 -c "
with open('src/codeguard/core/engine.py') as f:
content = f.read()
content = content.replace(
'from codeguard.utils.timer import Timer',
'from codeguard.utils.timer import Timer\nfrom codeguard.core.scanner import IncrementalScanner'
)
content = content.replace(
' files = self.collector.collect(paths)',
' if self.config.use_cache:\n scanner = IncrementalScanner(self.config)\n files = scanner.get_changed_files(paths)\n else:\n files = self.collector.collect(paths)'
)
with open('src/codeguard/core/engine.py', 'w') as f:
f.write(content)
print('Engine updated with incremental scanner')
"
git add -A && git commit -m "Integrate incremental scanner into analysis engine
Skip unchanged files when cache is enabled.
Refs: #$ISSUE_4"
cat > tests/test_scanner.py << 'PYEOF'
"""Tests for incremental scanner."""
import pytest
from codeguard.core.scanner import IncrementalScanner
from codeguard.config import Config
class TestIncrementalScanner:
@pytest.fixture
def scanner(self, tmp_path):
config = Config.default()
config.cache_dir = str(tmp_path / ".cache")
return IncrementalScanner(config=config)
def test_first_run(self, scanner, tmp_path):
f = tmp_path / "test.py"
f.write_text("x = 1\n")
changed = scanner.get_changed_files([str(tmp_path)])
assert len(changed) > 0
def test_no_changes(self, scanner, tmp_path):
f = tmp_path / "test.py"
f.write_text("x = 1\n")
scanner.get_changed_files([str(tmp_path)])
changed = scanner.get_changed_files([str(tmp_path)])
assert len(changed) == 0
def test_file_modified(self, scanner, tmp_path):
f = tmp_path / "test.py"
f.write_text("x = 1\n")
scanner.get_changed_files([str(tmp_path)])
f.write_text("x = 2\n")
changed = scanner.get_changed_files([str(tmp_path)])
assert len(changed) > 0
PYEOF
git add -A && git commit -m "Add tests for incremental scanner
Test first run, unchanged files, and modified file detection.
Refs: #$ISSUE_4"
git push origin feature/performance
echo "Pushed feature/performance"
# Branch 5: sarif-format (Issue 5)
git checkout main
git checkout -b feature/sarif-format
cat > src/codeguard/output/sarif_writer.py << 'PYEOF'
"""SARIF 2.1.0 output writer for GitHub Code Scanning integration."""
import json
from typing import Optional
from codeguard.config import Config
from codeguard.core.engine import AnalysisResults
class SARIFWriter:
def __init__(self, output_path: Optional[str] = None, config: Optional[Config] = None):
self.output_path = output_path
self.config = config or Config.default()
def write(self, results: AnalysisResults):
rules = {}
results_list = []
for v in results.violations:
rule_id = v.check_name
if rule_id not in rules:
rules[rule_id] = {
"id": rule_id,
"name": rule_id,
"shortDescription": {"text": v.message},
"helpUri": f"https://codeguard.dev/docs/checks/{rule_id}",
"properties": {"severity": v.severity},
}
results_list.append({
"ruleId": rule_id,
"level": "error" if v.severity == "critical" else "warning",
"message": {"text": v.message},
"locations": [{
"physicalLocation": {
"artifactLocation": {"uri": v.file_path},
"region": {"startLine": v.line_number, "startColumn": max(v.column, 1)},
}
}],
"properties": {"suggestion": v.suggestion or ""},
})
sarif = {
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
"version": "2.1.0",
"runs": [{
"tool": {
"driver": {
"name": "CodeGuard",
"version": "0.1.0",
"informationUri": "https://github.com/mohameden19961/codeguard",
"rules": list(rules.values()),
}
},
"results": results_list,
}],
}
output = json.dumps(sarif, indent=2)
if self.output_path:
with open(self.output_path, "w") as f:
f.write(output)
else:
print(output)
PYEOF
git add -A && git commit -m "Add SARIF 2.1.0 output writer
Enables GitHub Code Scanning integration and SARIF-compatible tool ingestion.
Refs: #$ISSUE_5"
python3 -c "
with open('src/codeguard/output/__init__.py') as f:
content = f.read()
if 'SARIFWriter' not in content:
content += 'from codeguard.output.sarif_writer import SARIFWriter\n'
with open('src/codeguard/output/__init__.py', 'w') as f:
f.write(content)
"
git add -A && git commit -m "Register SARIFWriter in output module
Refs: #$ISSUE_5"
cat > tests/test_sarif_writer.py << 'PYEOF'
"""Tests for SARIF output writer."""
import json
from codeguard.output.sarif_writer import SARIFWriter
from codeguard.core.engine import AnalysisResults, Violation
class TestSARIFWriter:
def test_write(self, tmp_path):
output = tmp_path / "results.sarif"
writer = SARIFWriter(output_path=str(output))
results = AnalysisResults(
files_analyzed=1, total_lines=5, duration=0.1,
violations=[Violation(check_name="test", severity="high",
message="test msg", file_path="a.py", line_number=3)],
)
writer.write(results)
assert output.exists()
data = json.loads(output.read_text())
assert data["version"] == "2.1.0"
assert len(data["runs"][0]["results"]) == 1
assert data["runs"][0]["results"][0]["ruleId"] == "test"
PYEOF
git add -A && git commit -m "Add tests for SARIF output format
Validate SARIF structure, version, and content.
Refs: #$ISSUE_5"
git push origin feature/sarif-format
echo "Pushed feature/sarif-format"
# Branch 6: fix-memory-leak (Issue 6)
git checkout main
git checkout -b fix/memory-leak
python3 -c "
with open('src/codeguard/utils/cache.py') as f:
content = f.read()
# Add LRU eviction
new_content = content.replace(
'class AnalysisCache:',
'''import time
from collections import OrderedDict
class AnalysisCache:'''
)
# Add max_size and eviction
new_content = new_content.replace(
' def __init__(self, cache_dir: str = \".codeguard_cache\"):',
' def __init__(self, cache_dir: str = \".codeguard_cache\", max_size: int = 1000):'
)
new_content = new_content.replace(
' self.cache_dir = cache_dir',
''' self.cache_dir = cache_dir
self.max_size = max_size
self._memory_cache = OrderedDict()
self._access_times = {}'''
)
new_content = new_content.replace(
' def set(self, key: str, file_hash: int, violations: list):',
''' def _evict_if_needed(self):
if len(self._memory_cache) >= self.max_size:
oldest = next(iter(self._memory_cache))
del self._memory_cache[oldest]
if oldest in self._access_times:
del self._access_times[oldest]
def set(self, key: str, file_hash: int, violations: list):'''
)
new_content = new_content.replace(
' cache_key = self._hash_key(key)\n os.makedirs(self.cache_dir, exist_ok=True)\n cache_path = os.path.join(self.cache_dir, cache_key)\n try:\n with open(cache_path, \"w\") as f:\n json.dump({\"hash\": file_hash, \"violations\": violations}, f)\n except IOError as e:\n raise CacheError(f\"Failed to write cache: {e}\")',
''' cache_key = self._hash_key(key)
self._evict_if_needed()
self._memory_cache[cache_key] = {\"hash\": file_hash, \"violations\": violations}
self._access_times[cache_key] = time.time()
os.makedirs(self.cache_dir, exist_ok=True)
cache_path = os.path.join(self.cache_dir, cache_key)
try:
with open(cache_path, \"w\") as f:
json.dump({\"hash\": file_hash, \"violations\": violations}, f)
except IOError as e:
raise CacheError(f\"Failed to write cache: {e}\")'''
)
new_content = new_content.replace(
' def clear(self):',
''' def clear_memory(self):
self._memory_cache.clear()
self._access_times.clear()
def get_stats(self) -> dict:
return {
\"memory_entries\": len(self._memory_cache),
\"max_size\": self.max_size,
\"disk_entries\": len(os.listdir(self.cache_dir)) if os.path.exists(self.cache_dir) else 0,
}
def clear(self):'''
)
with open('src/codeguard/utils/cache.py', 'w') as f:
f.write(new_content)
print('Cache.py updated with LRU eviction')
"
git add -A && git commit -m "Fix memory leak in cache module with LRU eviction
Added bounded memory cache with LRU eviction policy.
Prevents unbounded memory growth during analysis.
Fixes: #$ISSUE_6"
cat > tests/test_cache_lru.py << 'PYEOF'
"""Tests for cache LRU eviction."""
import pytest
from codeguard.utils.cache import AnalysisCache
class TestCacheLRU:
def test_memory_limit(self, tmp_path):
cache = AnalysisCache(cache_dir=str(tmp_path / ".cache"), max_size=2)
cache.set("key1", 1, ["v1"])
cache.set("key2", 2, ["v2"])
cache.set("key3", 3, ["v3"])
assert cache.get("key1") is None
assert cache.get("key2") is not None
def test_stats(self, tmp_path):
cache = AnalysisCache(cache_dir=str(tmp_path / ".cache"))
stats = cache.get_stats()
assert "memory_entries" in stats
assert "max_size" in stats
PYEOF
git add -A && git commit -m "Add tests for cache LRU eviction behavior
Verify memory limit enforcement and stats reporting.
Refs: #$ISSUE_6"
git push origin fix/memory-leak
echo "Pushed fix/memory-leak"
# Branch 7: pre-commit-hooks (Issue 7)
git checkout main
git checkout -b feature/pre-commit-hooks
cat > .pre-commit-hooks.yaml << 'PYEOF'
- id: codeguard
name: CodeGuard
description: Run CodeGuard on Python files
entry: codeguard
language: python
types: [python]
args: ["check", "--severity", "medium"]
minimum_pre_commit_version: "2.9.0"
PYEOF
git add -A && git commit -m "Add pre-commit hook configuration
Standard pre-commit hook definition for CodeGuard analysis.
Refs: #$ISSUE_7"
cat > scripts/pre-commit.sh << 'PYEOF'
#!/bin/bash
# Pre-commit hook for CodeGuard
# Install: ln -s ../../scripts/pre-commit.sh .git/hooks/pre-commit
echo "Running CodeGuard pre-commit check..."
# Get staged Python files
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$')
if [ -z "$FILES" ]; then
exit 0
fi
# Run CodeGuard on staged files
python -m codeguard check $FILES --severity medium
STATUS=$?
if [ $STATUS -ne 0 ]; then
echo "CodeGuard found violations. Please fix them before committing."
echo "To bypass: git commit --no-verify"
exit 1
fi
echo "CodeGuard check passed!"
exit 0
PYEOF
chmod +x scripts/pre-commit.sh
git add -A && git commit -m "Add pre-commit hook script for Git
Shell script that runs CodeGuard on staged Python files before commit.
Refs: #$ISSUE_7"
cat > docs/pre-commit-integration.md << 'PYEOF'
# Pre-commit Integration
## Using with pre-commit
Add to your `.pre-commit-config.yaml`:
```yaml
repos:
- repo: https://github.com/mohameden19961/codeguard
rev: v0.1.0
hooks:
- id: codeguard
```
## Manual Hook Installation
```bash
ln -s ../../scripts/pre-commit.sh .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
```
PYEOF
git add -A && git commit -m "Add pre-commit integration documentation
Guide for using CodeGuard with pre-commit framework and manual hooks.
Refs: #$ISSUE_7"
git push origin feature/pre-commit-hooks
echo "Pushed feature/pre-commit-hooks"
# Branch 8: refactor-core (Issue 8)
git checkout main
git checkout -b refactor/core-module
python3 -c "
# Extract interfaces
with open('src/codeguard/core/engine.py') as f:
content = f.read()
# Add IFileReader interface
content = content.replace(
'class AnalysisEngine:',
'''from abc import ABC, abstractmethod
class IFileReader(ABC):
\"\"\"Interface for file reading operations.\"\"\"
@abstractmethod
def read_file(self, path: str) -> str:
pass
class ICheckRunner(ABC):
\"\"\"Interface for running checks.\"\"\"
@abstractmethod
def run_checks(self, file_path: str, content: str, lines: list) -> list:
pass
class FileReader(IFileReader):
def read_file(self, path: str) -> str: