ai-cr 2.0.2__tar.gz → 3.0.0__tar.gz

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.
Files changed (38) hide show
  1. {ai_cr-2.0.2 → ai_cr-3.0.0}/PKG-INFO +4 -4
  2. {ai_cr-2.0.2 → ai_cr-3.0.0}/README.md +1 -1
  3. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/bootstrap.py +34 -13
  4. ai_cr-3.0.0/gito/cli.py +210 -0
  5. ai_cr-3.0.0/gito/cli_base.py +90 -0
  6. ai_cr-3.0.0/gito/commands/deploy.py +101 -0
  7. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/commands/fix.py +1 -1
  8. ai_cr-3.0.0/gito/commands/gh_post_review_comment.py +111 -0
  9. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/commands/gh_react_to_comment.py +3 -5
  10. ai_cr-3.0.0/gito/commands/linear_comment.py +53 -0
  11. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/commands/repl.py +2 -1
  12. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/config.toml +31 -12
  13. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/constants.py +1 -0
  14. ai_cr-3.0.0/gito/context.py +19 -0
  15. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/core.py +158 -31
  16. ai_cr-3.0.0/gito/env.py +3 -0
  17. ai_cr-3.0.0/gito/gh_api.py +85 -0
  18. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/issue_trackers.py +3 -2
  19. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/pipeline.py +8 -7
  20. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/pipeline_steps/jira.py +6 -1
  21. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/project_config.py +11 -0
  22. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/report_struct.py +4 -2
  23. ai_cr-3.0.0/gito/tpl/github_workflows/components/env-vars.j2 +10 -0
  24. ai_cr-3.0.0/gito/tpl/github_workflows/components/installs.j2 +23 -0
  25. ai_cr-3.0.0/gito/tpl/github_workflows/gito-code-review.yml.j2 +33 -0
  26. ai_cr-3.0.0/gito/tpl/github_workflows/gito-react-to-comments.yml.j2 +70 -0
  27. ai_cr-3.0.0/gito/tpl/release_notes.j2 +24 -0
  28. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/utils.py +19 -3
  29. {ai_cr-2.0.2 → ai_cr-3.0.0}/pyproject.toml +3 -3
  30. ai_cr-2.0.2/gito/cli.py +0 -217
  31. ai_cr-2.0.2/gito/commands/gh_post_review_comment.py +0 -63
  32. ai_cr-2.0.2/gito/gh_api.py +0 -35
  33. {ai_cr-2.0.2 → ai_cr-3.0.0}/LICENSE +0 -0
  34. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/__init__.py +0 -0
  35. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/__main__.py +0 -0
  36. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/commands/__init__.py +0 -0
  37. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/pipeline_steps/__init__.py +0 -0
  38. {ai_cr-2.0.2 → ai_cr-3.0.0}/gito/pipeline_steps/linear.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: ai-cr
3
- Version: 2.0.2
3
+ Version: 3.0.0
4
4
  Summary: AI code review tool that works with any language model provider. It detects issues in GitHub pull requests or local changes—instantly, reliably, and without vendor lock-in.
5
5
  License: MIT
6
6
  Keywords: static code analysis,code review,code quality,ai,coding,assistant,llm,github,automation,devops,developer tools,github actions,workflows,git
@@ -16,8 +16,8 @@ Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Topic :: Software Development
18
18
  Requires-Dist: GitPython (>=3.1.44,<4.0.0)
19
- Requires-Dist: ai-microcore (==4.0.0)
20
- Requires-Dist: anthropic (>=0.52.2,<0.53.0)
19
+ Requires-Dist: ai-microcore (==4.2.1)
20
+ Requires-Dist: anthropic (>=0.57.1,<0.58.0)
21
21
  Requires-Dist: ghapi (>=1.0.6,<1.1.0)
22
22
  Requires-Dist: google-generativeai (>=0.8.5,<0.9.0)
23
23
  Requires-Dist: jira (>=3.8.0,<4.0.0)
@@ -87,7 +87,7 @@ jobs:
87
87
  uses: actions/setup-python@v5
88
88
  with: { python-version: "3.13" }
89
89
  - name: Install AI Code Review tool
90
- run: pip install gito.bot~=2.0
90
+ run: pip install gito.bot~=3.0
91
91
  - name: Run AI code analysis
92
92
  env:
93
93
  LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
@@ -58,7 +58,7 @@ jobs:
58
58
  uses: actions/setup-python@v5
59
59
  with: { python-version: "3.13" }
60
60
  - name: Install AI Code Review tool
61
- run: pip install gito.bot~=2.0
61
+ run: pip install gito.bot~=3.0
62
62
  - name: Run AI code analysis
63
63
  env:
64
64
  LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
@@ -1,15 +1,18 @@
1
- import logging
2
1
  import os
2
+ import sys
3
+ import io
4
+ import logging
3
5
  from datetime import datetime
6
+ from pathlib import Path
4
7
 
5
8
  import microcore as mc
6
- import typer
7
9
 
8
10
  from .utils import is_running_in_github_action
9
- from .constants import HOME_ENV_PATH, EXECUTABLE
11
+ from .constants import HOME_ENV_PATH, EXECUTABLE, PROJECT_GITO_FOLDER
12
+ from .env import Env
10
13
 
11
14
 
12
- def setup_logging():
15
+ def setup_logging(log_level: int = logging.INFO):
13
16
  class CustomFormatter(logging.Formatter):
14
17
  def format(self, record):
15
18
  dt = datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S")
@@ -24,19 +27,41 @@ def setup_logging():
24
27
 
25
28
  handler = logging.StreamHandler()
26
29
  handler.setFormatter(CustomFormatter())
27
- logging.basicConfig(level=logging.INFO, handlers=[handler])
30
+ logging.basicConfig(level=log_level, handlers=[handler])
28
31
 
29
32
 
30
- def bootstrap():
33
+ def bootstrap(verbosity: int = 1):
31
34
  """Bootstrap the application with the environment configuration."""
32
- setup_logging()
33
- logging.info("Bootstrapping...")
35
+ log_levels_by_verbosity = {
36
+ 0: logging.CRITICAL,
37
+ 1: logging.INFO,
38
+ 2: logging.DEBUG,
39
+ 3: logging.DEBUG,
40
+ }
41
+ Env.verbosity = verbosity
42
+ Env.logging_level = log_levels_by_verbosity.get(verbosity, logging.INFO)
43
+ setup_logging(Env.logging_level)
44
+ logging.info("Bootstrapping... "+mc.ui.gray(f"[verbosity={verbosity}]"))
45
+
46
+ # cp1251 is used on Windows when redirecting output
47
+ if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
48
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
49
+
34
50
  try:
35
51
  mc.configure(
36
52
  DOT_ENV_FILE=HOME_ENV_PATH,
37
- USE_LOGGING=True,
53
+ USE_LOGGING=verbosity >= 1,
38
54
  EMBEDDING_DB_TYPE=mc.EmbeddingDbType.NONE,
55
+ PROMPT_TEMPLATES_PATH=[
56
+ PROJECT_GITO_FOLDER,
57
+ Path(__file__).parent / "tpl"
58
+ ],
39
59
  )
60
+ if verbosity > 1:
61
+ mc.logging.LoggingConfig.STRIP_REQUEST_LINES = None
62
+ else:
63
+ mc.logging.LoggingConfig.STRIP_REQUEST_LINES = [300, 15]
64
+
40
65
  except mc.LLMConfigError as e:
41
66
  msg = str(e)
42
67
  if is_running_in_github_action():
@@ -60,7 +85,3 @@ def bootstrap():
60
85
  except Exception as e:
61
86
  logging.error(f"Unexpected configuration error: {e}")
62
87
  raise SystemExit(3)
63
- mc.logging.LoggingConfig.STRIP_REQUEST_LINES = [300, 15]
64
-
65
-
66
- app = typer.Typer(pretty_exceptions_show_locals=False)
@@ -0,0 +1,210 @@
1
+ import os
2
+ import asyncio
3
+ import logging
4
+ import sys
5
+ import textwrap
6
+
7
+ import microcore as mc
8
+ import typer
9
+ from git import Repo
10
+
11
+ from .core import review, get_diff, filter_diff, answer
12
+ from .cli_base import (
13
+ app,
14
+ args_to_target,
15
+ arg_refs,
16
+ arg_what,
17
+ arg_filters,
18
+ arg_out,
19
+ arg_against,
20
+ get_repo_context,
21
+ )
22
+ from .report_struct import Report
23
+ from .constants import HOME_ENV_PATH, GITHUB_MD_REPORT_FILE_NAME
24
+ from .bootstrap import bootstrap
25
+ from .utils import no_subcommand, extract_gh_owner_repo, remove_html_comments
26
+ from .gh_api import resolve_gh_token
27
+
28
+ # Import fix command to register it
29
+ from .commands import fix, gh_react_to_comment, repl, deploy # noqa
30
+ from .commands.gh_post_review_comment import post_github_cr_comment
31
+ from .commands.linear_comment import linear_comment
32
+
33
+ app_no_subcommand = typer.Typer(pretty_exceptions_show_locals=False)
34
+
35
+
36
+ def main():
37
+ if sys.platform == "win32":
38
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
39
+ # Help subcommand alias: if 'help' appears as first non-option arg, replace it with '--help'
40
+ if len(sys.argv) > 1 and sys.argv[1] == "help":
41
+ sys.argv = [sys.argv[0]] + sys.argv[2:] + ["--help"]
42
+
43
+ if no_subcommand(app):
44
+ bootstrap()
45
+ app_no_subcommand()
46
+ else:
47
+ app()
48
+
49
+
50
+ @app.callback(invoke_without_command=True)
51
+ def cli(
52
+ ctx: typer.Context,
53
+ verbose: bool = typer.Option(default=None),
54
+ verbosity: int = typer.Option(
55
+ None,
56
+ '--verbosity', '-v',
57
+ help="Set verbosity level (0-3, default 1)"
58
+ ),
59
+ ):
60
+ if verbose is not None and verbosity is not None:
61
+ raise typer.BadParameter(
62
+ "Please specify either --verbose or --verbosity, not both."
63
+ )
64
+ if verbose is not None:
65
+ verbosity = 2 if verbose else 0
66
+ if verbosity is None:
67
+ verbosity = 1
68
+
69
+ if ctx.invoked_subcommand != "setup":
70
+ bootstrap(verbosity)
71
+
72
+
73
+ @app_no_subcommand.command(name="review", help="Perform code review")
74
+ @app.command(name="review", help="Perform code review")
75
+ @app.command(name="run", hidden=True)
76
+ def cmd_review(
77
+ refs: str = arg_refs(),
78
+ what: str = arg_what(),
79
+ against: str = arg_against(),
80
+ filters: str = arg_filters(),
81
+ merge_base: bool = typer.Option(default=True, help="Use merge base for comparison"),
82
+ url: str = typer.Option("", "--url", help="Git repository URL"),
83
+ post_comment: bool = typer.Option(default=False, help="Post review comment to GitHub"),
84
+ pr: int = typer.Option(
85
+ default=None,
86
+ help=textwrap.dedent("""\n
87
+ GitHub Pull Request number to post the comment to
88
+ (for local usage together with --post-comment,
89
+ in the github actions PR is resolved from the environment)
90
+ """)
91
+ ),
92
+ out: str = arg_out()
93
+ ):
94
+ _what, _against = args_to_target(refs, what, against)
95
+ with get_repo_context(url, _what) as (repo, out_folder):
96
+ asyncio.run(review(
97
+ repo=repo,
98
+ what=_what,
99
+ against=_against,
100
+ filters=filters,
101
+ use_merge_base=merge_base,
102
+ out_folder=out or out_folder,
103
+ ))
104
+ if post_comment:
105
+ try:
106
+ owner, repo_name = extract_gh_owner_repo(repo)
107
+ except ValueError as e:
108
+ logging.error(
109
+ "Error posting comment:\n"
110
+ "Could not extract GitHub owner and repository name from the local repository."
111
+ )
112
+ raise typer.Exit(code=1) from e
113
+ post_github_cr_comment(
114
+ md_report_file=os.path.join(out or out_folder, GITHUB_MD_REPORT_FILE_NAME),
115
+ pr=pr,
116
+ gh_repo=f"{owner}/{repo_name}",
117
+ token=resolve_gh_token()
118
+ )
119
+
120
+
121
+ @app.command(name="ask", help="Answer questions about codebase changes")
122
+ @app.command(name="answer", hidden=True)
123
+ @app.command(name="talk", hidden=True)
124
+ def cmd_answer(
125
+ question: str = typer.Argument(help="Question to ask about the codebase changes"),
126
+ refs: str = arg_refs(),
127
+ what: str = arg_what(),
128
+ against: str = arg_against(),
129
+ filters: str = arg_filters(),
130
+ merge_base: bool = typer.Option(default=True, help="Use merge base for comparison"),
131
+ use_pipeline: bool = typer.Option(default=True),
132
+ post_to: str = typer.Option(
133
+ help="Post answer to ... Supported values: linear",
134
+ default=None,
135
+ show_default=False
136
+ ),
137
+ ):
138
+ _what, _against = args_to_target(refs, what, against)
139
+ if str(question).startswith("tpl:"):
140
+ prompt_file = str(question)[4:]
141
+ question = ""
142
+ else:
143
+ prompt_file = None
144
+ out = answer(
145
+ question=question,
146
+ what=_what,
147
+ against=_against,
148
+ filters=filters,
149
+ use_merge_base=merge_base,
150
+ prompt_file=prompt_file,
151
+ use_pipeline=use_pipeline,
152
+ )
153
+ if post_to == 'linear':
154
+ logging.info("Posting answer to Linear...")
155
+ linear_comment(remove_html_comments(out))
156
+ return out
157
+
158
+
159
+ @app.command(help="Configure LLM for local usage interactively")
160
+ def setup():
161
+ mc.interactive_setup(HOME_ENV_PATH)
162
+
163
+
164
+ @app.command(name="render")
165
+ @app.command(name="report", hidden=True)
166
+ def render(
167
+ format: str = typer.Argument(default=Report.Format.CLI),
168
+ source: str = typer.Option(
169
+ "",
170
+ "--src",
171
+ "--source",
172
+ help="Source file (json) to load the report from"
173
+ )
174
+ ):
175
+ Report.load(file_name=source).to_cli(report_format=format)
176
+
177
+
178
+ @app.command(help="List files in the diff. Might be useful to check what will be reviewed.")
179
+ def files(
180
+ refs: str = arg_refs(),
181
+ what: str = arg_what(),
182
+ against: str = arg_against(),
183
+ filters: str = arg_filters(),
184
+ merge_base: bool = typer.Option(default=True, help="Use merge base for comparison"),
185
+ diff: bool = typer.Option(default=False, help="Show diff content")
186
+ ):
187
+ _what, _against = args_to_target(refs, what, against)
188
+ repo = Repo(".")
189
+ try:
190
+ patch_set = get_diff(repo=repo, what=_what, against=_against, use_merge_base=merge_base)
191
+ patch_set = filter_diff(patch_set, filters)
192
+ print(
193
+ f"Changed files: "
194
+ f"{mc.ui.green(_what or 'INDEX')} vs "
195
+ f"{mc.ui.yellow(_against or repo.remotes.origin.refs.HEAD.reference.name)}"
196
+ f"{' filtered by ' + mc.ui.cyan(filters) if filters else ''}"
197
+ )
198
+
199
+ for patch in patch_set:
200
+ if patch.is_added_file:
201
+ color = mc.ui.green
202
+ elif patch.is_removed_file:
203
+ color = mc.ui.red
204
+ else:
205
+ color = mc.ui.blue
206
+ print(f"- {color(patch.path)}")
207
+ if diff:
208
+ print(mc.ui.gray(textwrap.indent(str(patch), " ")))
209
+ finally:
210
+ repo.close()
@@ -0,0 +1,90 @@
1
+ import contextlib
2
+ import logging
3
+ import tempfile
4
+
5
+ import microcore as mc
6
+ import typer
7
+ from git import Repo
8
+ from gito.utils import parse_refs_pair
9
+
10
+
11
+ def args_to_target(refs, what, against) -> tuple[str | None, str | None]:
12
+ _what, _against = parse_refs_pair(refs)
13
+ if _what:
14
+ if what:
15
+ raise typer.BadParameter(
16
+ "You cannot specify both 'refs' <WHAT>..<AGAINST> and '--what'. Use one of them."
17
+ )
18
+ else:
19
+ _what = what
20
+ if _against:
21
+ if against:
22
+ raise typer.BadParameter(
23
+ "You cannot specify both 'refs' <WHAT>..<AGAINST> and '--against'. Use one of them."
24
+ )
25
+ else:
26
+ _against = against
27
+ return _what, _against
28
+
29
+
30
+ def arg_refs() -> typer.Argument:
31
+ return typer.Argument(
32
+ default=None,
33
+ help="Git refs to review, [what]..[against] e.g. 'HEAD..HEAD~1'"
34
+ )
35
+
36
+
37
+ def arg_what() -> typer.Option:
38
+ return typer.Option(None, "--what", "-w", help="Git ref to review")
39
+
40
+
41
+ def arg_filters() -> typer.Option:
42
+ return typer.Option(
43
+ "", "--filter", "-f", "--filters",
44
+ help="""
45
+ filter reviewed files by glob / fnmatch pattern(s),
46
+ e.g. 'src/**/*.py', may be comma-separated
47
+ """,
48
+ )
49
+
50
+
51
+ def arg_out() -> typer.Option:
52
+ return typer.Option(
53
+ None,
54
+ "--out", "-o", "--output",
55
+ help="Output folder for the code review report"
56
+ )
57
+
58
+
59
+ def arg_against() -> typer.Option:
60
+ return typer.Option(
61
+ None,
62
+ "--against", "-vs", "--vs",
63
+ help="Git ref to compare against"
64
+ )
65
+
66
+
67
+ app = typer.Typer(pretty_exceptions_show_locals=False)
68
+
69
+
70
+ @contextlib.contextmanager
71
+ def get_repo_context(url: str, branch: str):
72
+ """Context manager for handling both local and remote repositories."""
73
+ if url:
74
+ with tempfile.TemporaryDirectory() as temp_dir:
75
+ logging.info(
76
+ f"get_repo_context: "
77
+ f"Cloning [{mc.ui.green(url)}] to {mc.utils.file_link(temp_dir)} ..."
78
+ )
79
+ repo = Repo.clone_from(url, branch=branch, to_path=temp_dir)
80
+ try:
81
+ yield repo, temp_dir
82
+ finally:
83
+ repo.close()
84
+ else:
85
+ logging.info("get_repo_context: Using local repo...")
86
+ repo = Repo(".")
87
+ try:
88
+ yield repo, "."
89
+ finally:
90
+ repo.close()
@@ -0,0 +1,101 @@
1
+ from pathlib import Path
2
+
3
+ import microcore as mc
4
+ from microcore import ApiType, ui, utils
5
+ from git import Repo
6
+
7
+ from ..utils import version, extract_gh_owner_repo
8
+ from ..cli_base import app
9
+
10
+
11
+ @app.command(name="deploy", help="Deploy Gito workflows to GitHub Actions")
12
+ @app.command(name="init", hidden=True)
13
+ def deploy(api_type: ApiType = None, commit: bool = None, rewrite: bool = False):
14
+ repo = Repo(".")
15
+ workflow_files = dict(
16
+ code_review=Path(".github/workflows/gito-code-review.yml"),
17
+ react_to_comments=Path(".github/workflows/gito-react-to-comments.yml")
18
+ )
19
+ for file in workflow_files.values():
20
+ if file.exists():
21
+ message = f"Gito workflow already exists at {utils.file_link(file)}."
22
+ if rewrite:
23
+ ui.warning(message)
24
+ else:
25
+ message += "\nUse --rewrite to overwrite it."
26
+ ui.error(message)
27
+ return False
28
+
29
+ api_types = [ApiType.ANTHROPIC, ApiType.OPEN_AI, ApiType.GOOGLE_AI_STUDIO]
30
+ default_models = {
31
+ ApiType.ANTHROPIC: "claude-sonnet-4-20250514",
32
+ ApiType.OPEN_AI: "gpt-4.1",
33
+ ApiType.GOOGLE_AI_STUDIO: "gemini-2.5-pro",
34
+ }
35
+ secret_names = {
36
+ ApiType.ANTHROPIC: "ANTHROPIC_API_KEY",
37
+ ApiType.OPEN_AI: "OPENAI_API_KEY",
38
+ ApiType.GOOGLE_AI_STUDIO: "GOOGLE_AI_API_KEY",
39
+ }
40
+ if not api_type:
41
+ api_type = mc.ui.ask_choose(
42
+ "Choose your LLM API type",
43
+ api_types,
44
+ )
45
+ elif api_type not in api_types:
46
+ mc.ui.error(f"Unsupported API type: {api_type}")
47
+ return False
48
+ major, minor, *_ = version().split(".")
49
+ template_vars = dict(
50
+ model=default_models[api_type],
51
+ api_type=api_type,
52
+ secret_name=secret_names[api_type],
53
+ major=major,
54
+ minor=minor,
55
+ ApiType=ApiType,
56
+ remove_indent=True,
57
+ )
58
+ gito_code_review_yml = mc.tpl(
59
+ "github_workflows/gito-code-review.yml.j2",
60
+ **template_vars
61
+ )
62
+ gito_react_to_comments_yml = mc.tpl(
63
+ "github_workflows/gito-react-to-comments.yml.j2",
64
+ **template_vars
65
+ )
66
+
67
+ workflow_files["code_review"].parent.mkdir(parents=True, exist_ok=True)
68
+ workflow_files["code_review"].write_text(gito_code_review_yml)
69
+ workflow_files["react_to_comments"].write_text(gito_react_to_comments_yml)
70
+ print(
71
+ mc.ui.green("Gito workflows have been created.\n")
72
+ + f" - {mc.utils.file_link(workflow_files['code_review'])}\n"
73
+ + f" - {mc.utils.file_link(workflow_files['react_to_comments'])}\n"
74
+ )
75
+ owner, repo_name = extract_gh_owner_repo(repo)
76
+ if commit is True or commit is None and mc.ui.ask_yn(
77
+ "Do you want to commit and push created GitHub workflows to a new branch?"
78
+ ):
79
+ repo.git.add([str(file) for file in workflow_files.values()])
80
+ branch_name = "gito_deploy"
81
+ if not repo.active_branch.name.startswith(branch_name):
82
+ repo.git.checkout("-b", branch_name)
83
+ repo.git.commit("-m", "Deploy Gito workflows")
84
+ repo.git.push("origin", branch_name)
85
+ print(f"Changes pushed to {branch_name} branch.")
86
+ print(
87
+ f"Please create a PR from {branch_name} to your main branch and merge it:\n"
88
+ f"https://github.com/{owner}/{repo_name}/compare/gito_deploy?expand=1"
89
+ )
90
+ else:
91
+ print(
92
+ "Now you can commit and push created GitHub workflows to your main repository branch.\n"
93
+ )
94
+
95
+ print(
96
+ "(!IMPORTANT):\n"
97
+ f"Add {mc.ui.cyan(secret_names[api_type])} with actual API_KEY "
98
+ "to your repository secrets here:\n"
99
+ f"https://github.com/{owner}/{repo_name}/settings/secrets/actions"
100
+ )
101
+ return True
@@ -10,7 +10,7 @@ import git
10
10
  import typer
11
11
  from microcore import ui
12
12
 
13
- from ..bootstrap import app
13
+ from ..cli_base import app
14
14
  from ..constants import JSON_REPORT_FILE_NAME
15
15
  from ..report_struct import Report, Issue
16
16
 
@@ -0,0 +1,111 @@
1
+ import logging
2
+ import os
3
+ from time import sleep
4
+
5
+ import typer
6
+ from ghapi.core import GhApi
7
+
8
+ from ..cli_base import app
9
+ from ..constants import GITHUB_MD_REPORT_FILE_NAME, HTML_CR_COMMENT_MARKER
10
+ from ..gh_api import (
11
+ post_gh_comment,
12
+ resolve_gh_token,
13
+ hide_gh_comment,
14
+ )
15
+ from ..project_config import ProjectConfig
16
+
17
+
18
+ @app.command(name="github-comment", help="Leave a GitHub PR comment with the review.")
19
+ def post_github_cr_comment(
20
+ md_report_file: str = typer.Option(default=None),
21
+ pr: int = typer.Option(default=None),
22
+ gh_repo: str = typer.Option(default=None, help="owner/repo"),
23
+ token: str = typer.Option(
24
+ "", help="GitHub token (or set GITHUB_TOKEN env var)"
25
+ ),
26
+ ):
27
+ """
28
+ Leaves a comment with the review on the current GitHub pull request.
29
+ """
30
+ file = md_report_file or GITHUB_MD_REPORT_FILE_NAME
31
+ if not os.path.exists(file):
32
+ logging.error(f"Review file not found: {file}, comment will not be posted.")
33
+ raise typer.Exit(4)
34
+
35
+ with open(file, "r", encoding="utf-8") as f:
36
+ body = f.read()
37
+
38
+ token = resolve_gh_token(token)
39
+ if not token:
40
+ print("GitHub token is required (--token or GITHUB_TOKEN env var).")
41
+ raise typer.Exit(1)
42
+ config = ProjectConfig.load()
43
+ gh_env = config.prompt_vars["github_env"]
44
+ gh_repo = gh_repo or gh_env.get("github_repo", "")
45
+ pr_env_val = gh_env.get("github_pr_number", "")
46
+ logging.info(f"github_pr_number = {pr_env_val}")
47
+
48
+ if not pr:
49
+ # e.g. could be "refs/pull/123/merge" or a direct number
50
+ if "/" in pr_env_val and "pull" in pr_env_val:
51
+ # refs/pull/123/merge
52
+ try:
53
+ pr_num_candidate = pr_env_val.strip("/").split("/")
54
+ idx = pr_num_candidate.index("pull")
55
+ pr = int(pr_num_candidate[idx + 1])
56
+ except Exception:
57
+ pass
58
+ else:
59
+ try:
60
+ pr = int(pr_env_val)
61
+ except ValueError:
62
+ pass
63
+ if not pr:
64
+ if pr_str := os.getenv("PR_NUMBER_FROM_WORKFLOW_DISPATCH"):
65
+ try:
66
+ pr = int(pr_str)
67
+ except ValueError:
68
+ pass
69
+ if not pr:
70
+ logging.error("Could not resolve PR number from environment variables.")
71
+ raise typer.Exit(3)
72
+
73
+ if not post_gh_comment(gh_repo, pr, token, body):
74
+ raise typer.Exit(5)
75
+
76
+ if config.collapse_previous_code_review_comments:
77
+ sleep(1)
78
+ collapse_gh_outdated_cr_comments(gh_repo, pr, token)
79
+
80
+
81
+ def collapse_gh_outdated_cr_comments(
82
+ gh_repository: str,
83
+ pr_or_issue_number: int,
84
+ token: str = None
85
+ ):
86
+ """
87
+ Collapse outdated code review comments in a GitHub pull request or issue.
88
+ """
89
+ logging.info(f"Collapsing outdated comments in {gh_repository} #{pr_or_issue_number}...")
90
+
91
+ token = resolve_gh_token(token)
92
+ owner, repo = gh_repository.split('/')
93
+ api = GhApi(owner, repo, token=token)
94
+
95
+ comments = api.issues.list_comments(pr_or_issue_number)
96
+ review_marker = HTML_CR_COMMENT_MARKER
97
+ collapsed_title = "🗑️ Outdated Code Review by Gito"
98
+ collapsed_marker = f"<summary>{collapsed_title}</summary>"
99
+ outdated_comments = [
100
+ c for c in comments
101
+ if c.body and review_marker in c.body and collapsed_marker not in c.body
102
+ ][:-1]
103
+ if not outdated_comments:
104
+ logging.info("No outdated comments found")
105
+ return
106
+ for comment in outdated_comments:
107
+ logging.info(f"Collapsing comment {comment.id}...")
108
+ new_body = f"<details>\n<summary>{collapsed_title}</summary>\n\n{comment.body}\n</details>"
109
+ api.issues.update_comment(comment.id, new_body)
110
+ hide_gh_comment(comment.node_id, token)
111
+ logging.info("All outdated comments collapsed successfully.")
@@ -16,10 +16,10 @@ from microcore import ui
16
16
  from ghapi.all import GhApi
17
17
  import git
18
18
 
19
- from ..bootstrap import app
19
+ from ..cli_base import app
20
20
  from ..constants import JSON_REPORT_FILE_NAME, HTML_TEXT_ICON
21
21
  from ..core import answer
22
- from ..gh_api import post_gh_comment
22
+ from ..gh_api import post_gh_comment, resolve_gh_token
23
23
  from ..project_config import ProjectConfig
24
24
  from ..utils import extract_gh_owner_repo
25
25
  from .fix import fix
@@ -51,9 +51,7 @@ def react_to_comment(
51
51
  repo = git.Repo(".") # Current directory
52
52
  owner, repo_name = extract_gh_owner_repo(repo)
53
53
  logging.info(f"Using repository: {ui.yellow}{owner}/{repo_name}{ui.reset}")
54
- gh_token = (
55
- gh_token or os.getenv("GITHUB_TOKEN", None) or os.getenv("GH_TOKEN", None)
56
- )
54
+ gh_token = resolve_gh_token(gh_token)
57
55
  api = GhApi(owner=owner, repo=repo_name, token=gh_token)
58
56
  comment = api.issues.get_comment(comment_id=comment_id)
59
57
  logging.info(