ai-cr 2.0.0.dev2__py3-none-any.whl → 2.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gito/commands/fix.py CHANGED
@@ -1,157 +1,157 @@
1
- """
2
- Fix issues from code review report
3
- """
4
- import json
5
- import logging
6
- from pathlib import Path
7
- from typing import Optional
8
-
9
- import git
10
- import typer
11
- from microcore import ui
12
-
13
- from ..bootstrap import app
14
- from ..constants import JSON_REPORT_FILE_NAME
15
- from ..report_struct import Report, Issue
16
-
17
-
18
- @app.command(help="Fix an issue from the code review report")
19
- def fix(
20
- issue_number: int = typer.Argument(..., help="Issue number to fix"),
21
- report_path: Optional[str] = typer.Option(
22
- None,
23
- "--report",
24
- "-r",
25
- help="Path to the code review report (default: code-review-report.json)"
26
- ),
27
- dry_run: bool = typer.Option(
28
- False, "--dry-run", "-d", help="Only print changes without applying them"
29
- ),
30
- commit: bool = typer.Option(default=False, help="Commit changes after applying them"),
31
- push: bool = typer.Option(default=False, help="Push changes to the remote repository"),
32
- ) -> list[str]:
33
- """
34
- Applies the proposed change for the specified issue number from the code review report.
35
- """
36
- # Load the report
37
- report_path = report_path or JSON_REPORT_FILE_NAME
38
- try:
39
- report = Report.load(report_path)
40
- except (FileNotFoundError, json.JSONDecodeError) as e:
41
- logging.error(f"Failed to load report from {report_path}: {e}")
42
- raise typer.Exit(code=1)
43
-
44
- # Find the issue by number
45
- issue: Optional[Issue] = None
46
- for file_issues in report.issues.values():
47
- for i in file_issues:
48
- if i.id == issue_number:
49
- issue = i
50
- break
51
- if issue:
52
- break
53
-
54
- if not issue:
55
- logging.error(f"Issue #{issue_number} not found in the report")
56
- raise typer.Exit(code=1)
57
-
58
- if not issue.affected_lines:
59
- logging.error(f"Issue #{issue_number} has no affected lines specified")
60
- raise typer.Exit(code=1)
61
-
62
- if not any(affected_line.proposal for affected_line in issue.affected_lines):
63
- logging.error(f"Issue #{issue_number} has no proposal for fixing")
64
- raise typer.Exit(code=1)
65
-
66
- # Apply the fix
67
- logging.info(f"Fixing issue #{issue_number}: {ui.cyan(issue.title)}")
68
-
69
- for affected_line in issue.affected_lines:
70
- if not affected_line.proposal:
71
- continue
72
-
73
- file_path = Path(issue.file)
74
- if not file_path.exists():
75
- logging.error(f"File {file_path} not found")
76
- continue
77
-
78
- try:
79
- with open(file_path, "r", encoding="utf-8") as f:
80
- lines = f.readlines()
81
- except Exception as e:
82
- logging.error(f"Failed to read file {file_path}: {e}")
83
- continue
84
-
85
- # Check if line numbers are valid
86
- if affected_line.start_line < 1 or affected_line.end_line > len(lines):
87
- logging.error(
88
- f"Invalid line range: {affected_line.start_line}-{affected_line.end_line} "
89
- f"(file has {len(lines)} lines)"
90
- )
91
- continue
92
-
93
- # Get the affected line content for display
94
- affected_content = "".join(lines[affected_line.start_line - 1:affected_line.end_line])
95
- print(f"\nFile: {ui.blue(issue.file)}")
96
- print(f"Lines: {affected_line.start_line}-{affected_line.end_line}")
97
- print(f"Current content:\n{ui.red(affected_content)}")
98
- print(f"Proposed change:\n{ui.green(affected_line.proposal)}")
99
-
100
- if dry_run:
101
- print(f"{ui.yellow('Dry run')}: Changes not applied")
102
- continue
103
-
104
- # Apply the change
105
- proposal_lines = affected_line.proposal.splitlines(keepends=True)
106
- if not proposal_lines:
107
- proposal_lines = [""]
108
- elif not proposal_lines[-1].endswith(("\n", "\r")):
109
- # Ensure the last line has a newline if the original does
110
- if (
111
- affected_line.end_line < len(lines)
112
- and lines[affected_line.end_line - 1].endswith(("\n", "\r"))
113
- ):
114
- proposal_lines[-1] += "\n"
115
-
116
- lines[affected_line.start_line - 1:affected_line.end_line] = proposal_lines
117
-
118
- # Write changes back to the file
119
- try:
120
- with open(file_path, "w", encoding="utf-8") as f:
121
- f.writelines(lines)
122
- print(f"{ui.green('Success')}: Changes applied to {file_path}")
123
- except Exception as e:
124
- logging.error(f"Failed to write changes to {file_path}: {e}")
125
- raise typer.Exit(code=1)
126
-
127
- print(f"\n{ui.green('✓')} Issue #{issue_number} fixed successfully")
128
-
129
- changed_files = [file_path.as_posix()]
130
- if commit:
131
- commit_changes(
132
- changed_files,
133
- commit_message=f"[AI] Fix issue {issue_number}:{issue.title}",
134
- push=push
135
- )
136
- return changed_files
137
-
138
-
139
- def commit_changes(
140
- files: list[str],
141
- repo: git.Repo = None,
142
- commit_message: str = "fix by AI",
143
- push: bool = True
144
- ) -> None:
145
- if opened_repo := not repo:
146
- repo = git.Repo(".")
147
- for i in files:
148
- repo.index.add(i)
149
- repo.index.commit(commit_message)
150
- if push:
151
- origin = repo.remotes.origin
152
- origin.push()
153
- logging.info(f"Changes pushed to {origin.name}")
154
- else:
155
- logging.info("Changes committed but not pushed to remote")
156
- if opened_repo:
157
- repo.close()
1
+ """
2
+ Fix issues from code review report
3
+ """
4
+ import json
5
+ import logging
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import git
10
+ import typer
11
+ from microcore import ui
12
+
13
+ from ..bootstrap import app
14
+ from ..constants import JSON_REPORT_FILE_NAME
15
+ from ..report_struct import Report, Issue
16
+
17
+
18
+ @app.command(help="Fix an issue from the code review report")
19
+ def fix(
20
+ issue_number: int = typer.Argument(..., help="Issue number to fix"),
21
+ report_path: Optional[str] = typer.Option(
22
+ None,
23
+ "--report",
24
+ "-r",
25
+ help="Path to the code review report (default: code-review-report.json)"
26
+ ),
27
+ dry_run: bool = typer.Option(
28
+ False, "--dry-run", "-d", help="Only print changes without applying them"
29
+ ),
30
+ commit: bool = typer.Option(default=False, help="Commit changes after applying them"),
31
+ push: bool = typer.Option(default=False, help="Push changes to the remote repository"),
32
+ ) -> list[str]:
33
+ """
34
+ Applies the proposed change for the specified issue number from the code review report.
35
+ """
36
+ # Load the report
37
+ report_path = report_path or JSON_REPORT_FILE_NAME
38
+ try:
39
+ report = Report.load(report_path)
40
+ except (FileNotFoundError, json.JSONDecodeError) as e:
41
+ logging.error(f"Failed to load report from {report_path}: {e}")
42
+ raise typer.Exit(code=1)
43
+
44
+ # Find the issue by number
45
+ issue: Optional[Issue] = None
46
+ for file_issues in report.issues.values():
47
+ for i in file_issues:
48
+ if i.id == issue_number:
49
+ issue = i
50
+ break
51
+ if issue:
52
+ break
53
+
54
+ if not issue:
55
+ logging.error(f"Issue #{issue_number} not found in the report")
56
+ raise typer.Exit(code=1)
57
+
58
+ if not issue.affected_lines:
59
+ logging.error(f"Issue #{issue_number} has no affected lines specified")
60
+ raise typer.Exit(code=1)
61
+
62
+ if not any(affected_line.proposal for affected_line in issue.affected_lines):
63
+ logging.error(f"Issue #{issue_number} has no proposal for fixing")
64
+ raise typer.Exit(code=1)
65
+
66
+ # Apply the fix
67
+ logging.info(f"Fixing issue #{issue_number}: {ui.cyan(issue.title)}")
68
+
69
+ for affected_line in issue.affected_lines:
70
+ if not affected_line.proposal:
71
+ continue
72
+
73
+ file_path = Path(issue.file)
74
+ if not file_path.exists():
75
+ logging.error(f"File {file_path} not found")
76
+ continue
77
+
78
+ try:
79
+ with open(file_path, "r", encoding="utf-8") as f:
80
+ lines = f.readlines()
81
+ except Exception as e:
82
+ logging.error(f"Failed to read file {file_path}: {e}")
83
+ continue
84
+
85
+ # Check if line numbers are valid
86
+ if affected_line.start_line < 1 or affected_line.end_line > len(lines):
87
+ logging.error(
88
+ f"Invalid line range: {affected_line.start_line}-{affected_line.end_line} "
89
+ f"(file has {len(lines)} lines)"
90
+ )
91
+ continue
92
+
93
+ # Get the affected line content for display
94
+ affected_content = "".join(lines[affected_line.start_line - 1:affected_line.end_line])
95
+ print(f"\nFile: {ui.blue(issue.file)}")
96
+ print(f"Lines: {affected_line.start_line}-{affected_line.end_line}")
97
+ print(f"Current content:\n{ui.red(affected_content)}")
98
+ print(f"Proposed change:\n{ui.green(affected_line.proposal)}")
99
+
100
+ if dry_run:
101
+ print(f"{ui.yellow('Dry run')}: Changes not applied")
102
+ continue
103
+
104
+ # Apply the change
105
+ proposal_lines = affected_line.proposal.splitlines(keepends=True)
106
+ if not proposal_lines:
107
+ proposal_lines = [""]
108
+ elif not proposal_lines[-1].endswith(("\n", "\r")):
109
+ # Ensure the last line has a newline if the original does
110
+ if (
111
+ affected_line.end_line < len(lines)
112
+ and lines[affected_line.end_line - 1].endswith(("\n", "\r"))
113
+ ):
114
+ proposal_lines[-1] += "\n"
115
+
116
+ lines[affected_line.start_line - 1:affected_line.end_line] = proposal_lines
117
+
118
+ # Write changes back to the file
119
+ try:
120
+ with open(file_path, "w", encoding="utf-8") as f:
121
+ f.writelines(lines)
122
+ print(f"{ui.green('Success')}: Changes applied to {file_path}")
123
+ except Exception as e:
124
+ logging.error(f"Failed to write changes to {file_path}: {e}")
125
+ raise typer.Exit(code=1)
126
+
127
+ print(f"\n{ui.green('✓')} Issue #{issue_number} fixed successfully")
128
+
129
+ changed_files = [file_path.as_posix()]
130
+ if commit:
131
+ commit_changes(
132
+ changed_files,
133
+ commit_message=f"[AI] Fix issue {issue_number}:{issue.title}",
134
+ push=push
135
+ )
136
+ return changed_files
137
+
138
+
139
+ def commit_changes(
140
+ files: list[str],
141
+ repo: git.Repo = None,
142
+ commit_message: str = "fix by AI",
143
+ push: bool = True
144
+ ) -> None:
145
+ if opened_repo := not repo:
146
+ repo = git.Repo(".")
147
+ for i in files:
148
+ repo.index.add(i)
149
+ repo.index.commit(commit_message)
150
+ if push:
151
+ origin = repo.remotes.origin
152
+ origin.push()
153
+ logging.info(f"Changes pushed to {origin.name}")
154
+ else:
155
+ logging.info("Changes committed but not pushed to remote")
156
+ if opened_repo:
157
+ repo.close()
@@ -0,0 +1,63 @@
1
+ import logging
2
+ import os
3
+
4
+ import typer
5
+ from gito.bootstrap import app
6
+ from gito.constants import GITHUB_MD_REPORT_FILE_NAME
7
+ from gito.gh_api import post_gh_comment
8
+ from gito.project_config import ProjectConfig
9
+
10
+
11
+ @app.command(help="Leave a GitHub PR comment with the review.")
12
+ def github_comment(
13
+ token: str = typer.Option(
14
+ os.environ.get("GITHUB_TOKEN", ""), help="GitHub token (or set GITHUB_TOKEN env var)"
15
+ ),
16
+ ):
17
+ """
18
+ Leaves a comment with the review on the current GitHub pull request.
19
+ """
20
+ file = GITHUB_MD_REPORT_FILE_NAME
21
+ if not os.path.exists(file):
22
+ logging.error(f"Review file not found: {file}, comment will not be posted.")
23
+ raise typer.Exit(4)
24
+
25
+ with open(file, "r", encoding="utf-8") as f:
26
+ body = f.read()
27
+
28
+ if not token:
29
+ print("GitHub token is required (--token or GITHUB_TOKEN env var).")
30
+ raise typer.Exit(1)
31
+
32
+ github_env = ProjectConfig.load().prompt_vars["github_env"]
33
+ repo = github_env.get("github_repo", "")
34
+ pr_env_val = github_env.get("github_pr_number", "")
35
+ logging.info(f"github_pr_number = {pr_env_val}")
36
+
37
+ pr = None
38
+ # e.g. could be "refs/pull/123/merge" or a direct number
39
+ if "/" in pr_env_val and "pull" in pr_env_val:
40
+ # refs/pull/123/merge
41
+ try:
42
+ pr_num_candidate = pr_env_val.strip("/").split("/")
43
+ idx = pr_num_candidate.index("pull")
44
+ pr = int(pr_num_candidate[idx + 1])
45
+ except Exception:
46
+ pass
47
+ else:
48
+ try:
49
+ pr = int(pr_env_val)
50
+ except ValueError:
51
+ pass
52
+ if not pr:
53
+ if pr_str := os.getenv("PR_NUMBER_FROM_WORKFLOW_DISPATCH"):
54
+ try:
55
+ pr = int(pr_str)
56
+ except ValueError:
57
+ pass
58
+ if not pr:
59
+ logging.error("Could not resolve PR number from environment variables.")
60
+ raise typer.Exit(3)
61
+
62
+ if not post_gh_comment(repo, pr, token, body):
63
+ raise typer.Exit(5)