github-haystack 1.0.0__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.
- github_haystack-1.0.0.dist-info/METADATA +45 -0
- github_haystack-1.0.0.dist-info/RECORD +26 -0
- github_haystack-1.0.0.dist-info/WHEEL +4 -0
- github_haystack-1.0.0.dist-info/licenses/LICENSE.txt +73 -0
- haystack_integrations/components/connectors/github/__init__.py +19 -0
- haystack_integrations/components/connectors/github/file_editor.py +303 -0
- haystack_integrations/components/connectors/github/issue_commenter.py +161 -0
- haystack_integrations/components/connectors/github/issue_viewer.py +216 -0
- haystack_integrations/components/connectors/github/pr_creator.py +277 -0
- haystack_integrations/components/connectors/github/repo_forker.py +306 -0
- haystack_integrations/components/connectors/github/repo_viewer.py +272 -0
- haystack_integrations/prompts/github/__init__.py +22 -0
- haystack_integrations/prompts/github/context_prompt.py +176 -0
- haystack_integrations/prompts/github/file_editor_prompt.py +122 -0
- haystack_integrations/prompts/github/issue_commenter_prompt.py +21 -0
- haystack_integrations/prompts/github/issue_viewer_prompt.py +25 -0
- haystack_integrations/prompts/github/pr_creator_prompt.py +83 -0
- haystack_integrations/prompts/github/repo_viewer_prompt.py +81 -0
- haystack_integrations/prompts/github/system_prompt.py +63 -0
- haystack_integrations/tools/github/__init__.py +16 -0
- haystack_integrations/tools/github/file_editor_tool.py +128 -0
- haystack_integrations/tools/github/issue_commenter_tool.py +123 -0
- haystack_integrations/tools/github/issue_viewer_tool.py +123 -0
- haystack_integrations/tools/github/pr_creator_tool.py +117 -0
- haystack_integrations/tools/github/repo_viewer_tool.py +138 -0
- haystack_integrations/tools/github/utils.py +73 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: github-haystack
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Haystack components for interacting with GitHub repositories
|
|
5
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/github
|
|
6
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/github/README.md
|
|
7
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
8
|
+
Author-email: deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
20
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Requires-Dist: haystack-ai>=2.12.0
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# github-haystack
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/github-haystack)
|
|
28
|
+
[](https://pypi.org/project/github-haystack)
|
|
29
|
+
|
|
30
|
+
-----
|
|
31
|
+
|
|
32
|
+
## Table of Contents
|
|
33
|
+
|
|
34
|
+
- [Installation](#installation)
|
|
35
|
+
- [License](#license)
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```console
|
|
40
|
+
pip install github-haystack
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
`github-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
haystack_integrations/components/connectors/github/__init__.py,sha256=aRIkCcJ_ogsyt67cwjZQu8rqP7yIQu8jRzK6TAYRGx4,557
|
|
2
|
+
haystack_integrations/components/connectors/github/file_editor.py,sha256=DbW57Ztm9kv8mCYSJGhUY7xp9wXOvRdhomOosNbBFnQ,11738
|
|
3
|
+
haystack_integrations/components/connectors/github/issue_commenter.py,sha256=S8VhaPaIQJ29TJNMsnfPns4lNBNAnC0QUxuktKTrnfE,5618
|
|
4
|
+
haystack_integrations/components/connectors/github/issue_viewer.py,sha256=Xionw1Y8jGxMCo2AXDUjqWk_yaJTW0d9xhvSr8bOGcM,7368
|
|
5
|
+
haystack_integrations/components/connectors/github/pr_creator.py,sha256=KEWgXVQlLjaSJiwqn-5vIxOCG1PHH8OKEJtNphI3o_g,11428
|
|
6
|
+
haystack_integrations/components/connectors/github/repo_forker.py,sha256=HHDXrRzIOcDCBVxnxpe1ygR-CzIScGIMwXojrToeJ_I,11555
|
|
7
|
+
haystack_integrations/components/connectors/github/repo_viewer.py,sha256=tECbnxaBxqX3zAZQ2MzCrqvKfY-Ml9MGMhgtLKrsmKw,9199
|
|
8
|
+
haystack_integrations/prompts/github/__init__.py,sha256=jjkSZGJ76S0EX-ZTv4qrhpxGrwVpBb_TCyqMJFhl2ec,759
|
|
9
|
+
haystack_integrations/prompts/github/context_prompt.py,sha256=RSzISqtaBHaC7v6rcyyxt2vxmbBVp5OHsWR6Z2wp5pk,8783
|
|
10
|
+
haystack_integrations/prompts/github/file_editor_prompt.py,sha256=_ro-I3MbVIpYpVFJbSpj4TuzbKLX7wTGn55Q95q8jFE,3301
|
|
11
|
+
haystack_integrations/prompts/github/issue_commenter_prompt.py,sha256=MavmvrnNCJNYzT5zwv61pY_BkehbJqSPSsGzILIItb4,701
|
|
12
|
+
haystack_integrations/prompts/github/issue_viewer_prompt.py,sha256=AvkDmRvpcQX9wGnouPI3kH7nZ_JuehpmBnUvbNTzh6A,966
|
|
13
|
+
haystack_integrations/prompts/github/pr_creator_prompt.py,sha256=tNC9BdzIowZ42o8bmnrJ46aonIzMfVHRrZopwryiABI,3944
|
|
14
|
+
haystack_integrations/prompts/github/repo_viewer_prompt.py,sha256=JkU2ODn06Vs_YQozF1H0vYym7jzczSdN1kAOXSD5IkA,3257
|
|
15
|
+
haystack_integrations/prompts/github/system_prompt.py,sha256=xiOEAbENJiLHL8M1qrgSdUxrfguAphI_6B0kqelxDok,4209
|
|
16
|
+
haystack_integrations/tools/github/__init__.py,sha256=FyNJ5F0IO2Xied-wP6utoMB13lPLK1Y0fAu7YlKhWu0,532
|
|
17
|
+
haystack_integrations/tools/github/file_editor_tool.py,sha256=RUhNvFD4ofug3tcuhwmEKM-LPvg2FAzMjVgVi2RCMLo,5279
|
|
18
|
+
haystack_integrations/tools/github/issue_commenter_tool.py,sha256=ZxDUbEzEe9oLAF-jKCRRx-xgzAXgiYqfPaUdXEpbJTg,5226
|
|
19
|
+
haystack_integrations/tools/github/issue_viewer_tool.py,sha256=cfpQLoSj3KvZc0gv78OCYGC4kxTwOEhASTdAkcdp2ls,5166
|
|
20
|
+
haystack_integrations/tools/github/pr_creator_tool.py,sha256=WGn6ovtmiiFINrwlP00l_Jt6PUrF7A_N9ATPJHOLQEE,4925
|
|
21
|
+
haystack_integrations/tools/github/repo_viewer_tool.py,sha256=jcXv0zXEQnAstWq5A4H_5hp50DUfGobRKI5COlnTupE,5984
|
|
22
|
+
haystack_integrations/tools/github/utils.py,sha256=xNAOtPo7Txq8Q4KhYARopP-4DOiU_m53hd4tHZKaStE,2936
|
|
23
|
+
github_haystack-1.0.0.dist-info/METADATA,sha256=se7kf9JKuvakNRJP6RK58xPJRMvVV9mNPJ0QvC-v7AA,1709
|
|
24
|
+
github_haystack-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
25
|
+
github_haystack-1.0.0.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
|
|
26
|
+
github_haystack-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright [yyyy] [name of copyright owner]
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
from .file_editor import Command, GitHubFileEditor
|
|
5
|
+
from .issue_commenter import GitHubIssueCommenter
|
|
6
|
+
from .issue_viewer import GitHubIssueViewer
|
|
7
|
+
from .pr_creator import GitHubPRCreator
|
|
8
|
+
from .repo_forker import GitHubRepoForker
|
|
9
|
+
from .repo_viewer import GitHubRepoViewer
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"Command",
|
|
13
|
+
"GitHubFileEditor",
|
|
14
|
+
"GitHubIssueCommenter",
|
|
15
|
+
"GitHubIssueViewer",
|
|
16
|
+
"GitHubPRCreator",
|
|
17
|
+
"GitHubRepoForker",
|
|
18
|
+
"GitHubRepoViewer",
|
|
19
|
+
]
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
from base64 import b64decode, b64encode
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Any, Dict, Optional, Union
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
from haystack import component, default_from_dict, default_to_dict, logging
|
|
10
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Command(str, Enum):
|
|
16
|
+
"""
|
|
17
|
+
Available commands for file operations in GitHub.
|
|
18
|
+
|
|
19
|
+
Attributes:
|
|
20
|
+
EDIT: Edit an existing file by replacing content
|
|
21
|
+
UNDO: Revert the last commit if made by the same user
|
|
22
|
+
CREATE: Create a new file
|
|
23
|
+
DELETE: Delete an existing file
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
EDIT = "edit"
|
|
27
|
+
UNDO = "undo"
|
|
28
|
+
CREATE = "create"
|
|
29
|
+
DELETE = "delete"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@component
|
|
33
|
+
class GitHubFileEditor:
|
|
34
|
+
"""
|
|
35
|
+
A Haystack component for editing files in GitHub repositories.
|
|
36
|
+
|
|
37
|
+
Supports editing, undoing changes, deleting files, and creating new files
|
|
38
|
+
through the GitHub API.
|
|
39
|
+
|
|
40
|
+
### Usage example
|
|
41
|
+
```python
|
|
42
|
+
from haystack_integrations.components.connectors.github import Command, GitHubFileEditor
|
|
43
|
+
from haystack.utils import Secret
|
|
44
|
+
|
|
45
|
+
# Initialize with default repo and branch
|
|
46
|
+
editor = GitHubFileEditor(
|
|
47
|
+
github_token=Secret.from_env_var("GITHUB_TOKEN"),
|
|
48
|
+
repo="owner/repo",
|
|
49
|
+
branch="main"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Edit a file using default repo and branch
|
|
53
|
+
result = editor.run(
|
|
54
|
+
command=Command.EDIT,
|
|
55
|
+
payload={
|
|
56
|
+
"path": "path/to/file.py",
|
|
57
|
+
"original": "def old_function():",
|
|
58
|
+
"replacement": "def new_function():",
|
|
59
|
+
"message": "Renamed function for clarity"
|
|
60
|
+
}
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# Edit a file in a different repo/branch
|
|
64
|
+
result = editor.run(
|
|
65
|
+
command=Command.EDIT,
|
|
66
|
+
repo="other-owner/other-repo", # Override default repo
|
|
67
|
+
branch="feature", # Override default branch
|
|
68
|
+
payload={
|
|
69
|
+
"path": "path/to/file.py",
|
|
70
|
+
"original": "def old_function():",
|
|
71
|
+
"replacement": "def new_function():",
|
|
72
|
+
"message": "Renamed function for clarity"
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
```
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
*,
|
|
81
|
+
github_token: Secret = Secret.from_env_var("GITHUB_TOKEN"),
|
|
82
|
+
repo: Optional[str] = None,
|
|
83
|
+
branch: str = "main",
|
|
84
|
+
raise_on_failure: bool = True,
|
|
85
|
+
):
|
|
86
|
+
"""
|
|
87
|
+
Initialize the component.
|
|
88
|
+
|
|
89
|
+
:param github_token: GitHub personal access token for API authentication
|
|
90
|
+
:param repo: Default repository in owner/repo format
|
|
91
|
+
:param branch: Default branch to work with
|
|
92
|
+
:param raise_on_failure: If True, raises exceptions on API errors
|
|
93
|
+
|
|
94
|
+
:raises TypeError: If github_token is not a Secret
|
|
95
|
+
"""
|
|
96
|
+
if not isinstance(github_token, Secret):
|
|
97
|
+
error_message = "github_token must be a Secret"
|
|
98
|
+
raise TypeError(error_message)
|
|
99
|
+
|
|
100
|
+
self.github_token = github_token
|
|
101
|
+
self.default_repo = repo
|
|
102
|
+
self.default_branch = branch
|
|
103
|
+
self.raise_on_failure = raise_on_failure
|
|
104
|
+
|
|
105
|
+
self.base_headers = {
|
|
106
|
+
"Accept": "application/vnd.github.v3+json",
|
|
107
|
+
"User-Agent": "Haystack/GitHubFileEditor",
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
def _get_request_headers(self) -> dict:
|
|
111
|
+
"""
|
|
112
|
+
Get headers with resolved token for the request.
|
|
113
|
+
|
|
114
|
+
:return: Dictionary of headers including authorization if token is present
|
|
115
|
+
"""
|
|
116
|
+
headers = self.base_headers.copy()
|
|
117
|
+
if self.github_token is not None:
|
|
118
|
+
headers["Authorization"] = f"Bearer {self.github_token.resolve_value()}"
|
|
119
|
+
return headers
|
|
120
|
+
|
|
121
|
+
def _get_file_content(self, owner: str, repo: str, path: str, branch: str) -> tuple[str, str]:
|
|
122
|
+
"""Get file content and SHA from GitHub."""
|
|
123
|
+
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
|
|
124
|
+
response = requests.get(url, headers=self._get_request_headers(), params={"ref": branch}, timeout=10)
|
|
125
|
+
response.raise_for_status()
|
|
126
|
+
data = response.json()
|
|
127
|
+
content = b64decode(data["content"]).decode("utf-8")
|
|
128
|
+
return content, data["sha"]
|
|
129
|
+
|
|
130
|
+
def _update_file(self, owner: str, repo: str, path: str, content: str, message: str, sha: str, branch: str) -> bool:
|
|
131
|
+
"""Update file content on GitHub."""
|
|
132
|
+
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
|
|
133
|
+
payload = {
|
|
134
|
+
"message": message,
|
|
135
|
+
"content": b64encode(content.encode("utf-8")).decode("utf-8"),
|
|
136
|
+
"sha": sha,
|
|
137
|
+
"branch": branch,
|
|
138
|
+
}
|
|
139
|
+
response = requests.put(url, headers=self._get_request_headers(), json=payload, timeout=10)
|
|
140
|
+
response.raise_for_status()
|
|
141
|
+
return True
|
|
142
|
+
|
|
143
|
+
def _check_last_commit(self, owner: str, repo: str, branch: str) -> bool:
|
|
144
|
+
"""Check if last commit was made by the current token user."""
|
|
145
|
+
url = f"https://api.github.com/repos/{owner}/{repo}/commits"
|
|
146
|
+
params: Dict[str, Union[str, int]] = {"per_page": 1, "sha": branch}
|
|
147
|
+
response = requests.get(url, headers=self._get_request_headers(), params=params, timeout=10)
|
|
148
|
+
response.raise_for_status()
|
|
149
|
+
last_commit = response.json()[0]
|
|
150
|
+
commit_author = last_commit["author"]["login"]
|
|
151
|
+
|
|
152
|
+
# Get current user
|
|
153
|
+
user_response = requests.get("https://api.github.com/user", headers=self._get_request_headers(), timeout=10)
|
|
154
|
+
user_response.raise_for_status()
|
|
155
|
+
current_user = user_response.json()["login"]
|
|
156
|
+
|
|
157
|
+
return commit_author == current_user
|
|
158
|
+
|
|
159
|
+
def _edit_file(self, owner: str, repo: str, payload: Dict[str, str], branch: str) -> str:
|
|
160
|
+
"""Handle file editing."""
|
|
161
|
+
try:
|
|
162
|
+
content, sha = self._get_file_content(owner, repo, payload["path"], branch)
|
|
163
|
+
|
|
164
|
+
# Check if original string is unique
|
|
165
|
+
occurrences = content.count(payload["original"])
|
|
166
|
+
if occurrences == 0:
|
|
167
|
+
return "Error: Original string not found in file"
|
|
168
|
+
if occurrences > 1:
|
|
169
|
+
return "Error: Original string appears multiple times. Please provide more context"
|
|
170
|
+
|
|
171
|
+
# Perform the replacement
|
|
172
|
+
new_content = content.replace(payload["original"], payload["replacement"])
|
|
173
|
+
success = self._update_file(owner, repo, payload["path"], new_content, payload["message"], sha, branch)
|
|
174
|
+
return "Edit successful" if success else "Edit failed"
|
|
175
|
+
|
|
176
|
+
except requests.RequestException as e:
|
|
177
|
+
if self.raise_on_failure:
|
|
178
|
+
raise
|
|
179
|
+
return f"Error: {e!s}"
|
|
180
|
+
|
|
181
|
+
def _undo_changes(self, owner: str, repo: str, payload: Dict[str, Any], branch: str) -> str:
|
|
182
|
+
"""Handle undoing changes."""
|
|
183
|
+
try:
|
|
184
|
+
if not self._check_last_commit(owner, repo, branch):
|
|
185
|
+
return "Error: Last commit was not made by the current user"
|
|
186
|
+
|
|
187
|
+
# Reset to previous commit
|
|
188
|
+
url = f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{branch}"
|
|
189
|
+
commits_url = f"https://api.github.com/repos/{owner}/{repo}/commits"
|
|
190
|
+
|
|
191
|
+
# Get the previous commit SHA
|
|
192
|
+
params: Dict[str, Union[str, int]] = {"per_page": 2, "sha": branch}
|
|
193
|
+
commits = requests.get(commits_url, headers=self._get_request_headers(), params=params, timeout=10).json()
|
|
194
|
+
previous_sha = commits[1]["sha"]
|
|
195
|
+
|
|
196
|
+
# Update branch reference to previous commit
|
|
197
|
+
payload = {"sha": previous_sha, "force": True}
|
|
198
|
+
response = requests.patch(url, headers=self._get_request_headers(), json=payload, timeout=10)
|
|
199
|
+
response.raise_for_status()
|
|
200
|
+
|
|
201
|
+
return "Successfully undid last change"
|
|
202
|
+
|
|
203
|
+
except requests.RequestException as e:
|
|
204
|
+
if self.raise_on_failure:
|
|
205
|
+
raise
|
|
206
|
+
return f"Error: {e!s}"
|
|
207
|
+
|
|
208
|
+
def _create_file(self, owner: str, repo: str, payload: Dict[str, str], branch: str) -> str:
|
|
209
|
+
"""Handle file creation."""
|
|
210
|
+
try:
|
|
211
|
+
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{payload['path']}"
|
|
212
|
+
content = b64encode(payload["content"].encode("utf-8")).decode("utf-8")
|
|
213
|
+
|
|
214
|
+
data = {"message": payload["message"], "content": content, "branch": branch}
|
|
215
|
+
|
|
216
|
+
response = requests.put(url, headers=self._get_request_headers(), json=data, timeout=10)
|
|
217
|
+
response.raise_for_status()
|
|
218
|
+
return "File created successfully"
|
|
219
|
+
|
|
220
|
+
except requests.RequestException as e:
|
|
221
|
+
if self.raise_on_failure:
|
|
222
|
+
raise
|
|
223
|
+
return f"Error: {e!s}"
|
|
224
|
+
|
|
225
|
+
def _delete_file(self, owner: str, repo: str, payload: Dict[str, str], branch: str) -> str:
|
|
226
|
+
"""Handle file deletion."""
|
|
227
|
+
try:
|
|
228
|
+
content, sha = self._get_file_content(owner, repo, payload["path"], branch)
|
|
229
|
+
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{payload['path']}"
|
|
230
|
+
|
|
231
|
+
data = {"message": payload["message"], "sha": sha, "branch": branch}
|
|
232
|
+
|
|
233
|
+
response = requests.delete(url, headers=self._get_request_headers(), json=data, timeout=10)
|
|
234
|
+
response.raise_for_status()
|
|
235
|
+
return "File deleted successfully"
|
|
236
|
+
|
|
237
|
+
except requests.RequestException as e:
|
|
238
|
+
if self.raise_on_failure:
|
|
239
|
+
raise
|
|
240
|
+
return f"Error: {e!s}"
|
|
241
|
+
|
|
242
|
+
@component.output_types(result=str)
|
|
243
|
+
def run(
|
|
244
|
+
self,
|
|
245
|
+
command: Union[Command, str],
|
|
246
|
+
payload: Dict[str, Any],
|
|
247
|
+
repo: Optional[str] = None,
|
|
248
|
+
branch: Optional[str] = None,
|
|
249
|
+
) -> Dict[str, str]:
|
|
250
|
+
"""
|
|
251
|
+
Process GitHub file operations.
|
|
252
|
+
|
|
253
|
+
:param command: Operation to perform ("edit", "undo", "create", "delete")
|
|
254
|
+
:param payload: Dictionary containing command-specific parameters
|
|
255
|
+
:param repo: Repository in owner/repo format (overrides default if provided)
|
|
256
|
+
:param branch: Branch to perform operations on (overrides default if provided)
|
|
257
|
+
:return: Dictionary containing operation result
|
|
258
|
+
|
|
259
|
+
:raises ValueError: If command is not a valid Command enum value
|
|
260
|
+
"""
|
|
261
|
+
if repo is None:
|
|
262
|
+
if self.default_repo is None:
|
|
263
|
+
return {
|
|
264
|
+
"result": "Error: No repository specified. Either provide it in initialization or in run() method"
|
|
265
|
+
}
|
|
266
|
+
repo = self.default_repo
|
|
267
|
+
|
|
268
|
+
working_branch = branch if branch is not None else self.default_branch
|
|
269
|
+
owner, repo_name = repo.split("/")
|
|
270
|
+
|
|
271
|
+
# Convert string command to Command enum if needed
|
|
272
|
+
if isinstance(command, str):
|
|
273
|
+
command = Command(command.lower())
|
|
274
|
+
|
|
275
|
+
command_handlers = {
|
|
276
|
+
Command.EDIT: self._edit_file,
|
|
277
|
+
Command.UNDO: self._undo_changes,
|
|
278
|
+
Command.CREATE: self._create_file,
|
|
279
|
+
Command.DELETE: self._delete_file,
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if command not in command_handlers:
|
|
283
|
+
return {"result": f"Error: Unknown command '{command}'"}
|
|
284
|
+
|
|
285
|
+
result = command_handlers[command](owner, repo_name, payload, working_branch)
|
|
286
|
+
return {"result": result}
|
|
287
|
+
|
|
288
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
289
|
+
"""Serialize the component to a dictionary."""
|
|
290
|
+
return default_to_dict(
|
|
291
|
+
self,
|
|
292
|
+
github_token=self.github_token.to_dict() if self.github_token else None,
|
|
293
|
+
repo=self.default_repo,
|
|
294
|
+
branch=self.default_branch,
|
|
295
|
+
raise_on_failure=self.raise_on_failure,
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
@classmethod
|
|
299
|
+
def from_dict(cls, data: Dict[str, Any]) -> "GitHubFileEditor":
|
|
300
|
+
"""Deserialize the component from a dictionary."""
|
|
301
|
+
init_params = data["init_parameters"]
|
|
302
|
+
deserialize_secrets_inplace(init_params, keys=["github_token"])
|
|
303
|
+
return default_from_dict(cls, data)
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any, Dict
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
from haystack import component, default_from_dict, default_to_dict, logging
|
|
9
|
+
from haystack.utils import deserialize_secrets_inplace
|
|
10
|
+
from haystack.utils.auth import Secret
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@component
|
|
16
|
+
class GitHubIssueCommenter:
|
|
17
|
+
"""
|
|
18
|
+
Posts comments to GitHub issues.
|
|
19
|
+
|
|
20
|
+
The component takes a GitHub issue URL and comment text, then posts the comment
|
|
21
|
+
to the specified issue using the GitHub API.
|
|
22
|
+
|
|
23
|
+
### Usage example
|
|
24
|
+
```python
|
|
25
|
+
from haystack_integrations.components.connectors.github import GitHubIssueCommenter
|
|
26
|
+
from haystack.utils import Secret
|
|
27
|
+
|
|
28
|
+
commenter = GitHubIssueCommenter(github_token=Secret.from_env_var("GITHUB_TOKEN"))
|
|
29
|
+
result = commenter.run(
|
|
30
|
+
url="https://github.com/owner/repo/issues/123",
|
|
31
|
+
comment="Thanks for reporting this issue! We'll look into it."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
print(result["success"])
|
|
35
|
+
```
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
*,
|
|
41
|
+
github_token: Secret = Secret.from_env_var("GITHUB_TOKEN"),
|
|
42
|
+
raise_on_failure: bool = True,
|
|
43
|
+
retry_attempts: int = 2,
|
|
44
|
+
):
|
|
45
|
+
"""
|
|
46
|
+
Initialize the component.
|
|
47
|
+
|
|
48
|
+
:param github_token: GitHub personal access token for API authentication as a Secret
|
|
49
|
+
:param raise_on_failure: If True, raises exceptions on API errors
|
|
50
|
+
:param retry_attempts: Number of retry attempts for failed requests
|
|
51
|
+
"""
|
|
52
|
+
self.github_token = github_token
|
|
53
|
+
self.raise_on_failure = raise_on_failure
|
|
54
|
+
self.retry_attempts = retry_attempts
|
|
55
|
+
|
|
56
|
+
# Set base headers during initialization
|
|
57
|
+
self.base_headers = {
|
|
58
|
+
"Accept": "application/vnd.github.v3+json",
|
|
59
|
+
"User-Agent": "Haystack/GitHubIssueCommenter",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
def _get_request_headers(self) -> dict:
|
|
63
|
+
"""
|
|
64
|
+
Get headers with resolved token for the request.
|
|
65
|
+
|
|
66
|
+
:return: Dictionary of headers including authorization if token is present
|
|
67
|
+
"""
|
|
68
|
+
headers = self.base_headers.copy()
|
|
69
|
+
if self.github_token is not None:
|
|
70
|
+
headers["Authorization"] = f"Bearer {self.github_token.resolve_value()}"
|
|
71
|
+
return headers
|
|
72
|
+
|
|
73
|
+
def _parse_github_url(self, url: str) -> tuple[str, str, int]:
|
|
74
|
+
"""
|
|
75
|
+
Parse GitHub URL into owner, repo and issue number.
|
|
76
|
+
|
|
77
|
+
:param url: GitHub issue URL
|
|
78
|
+
:return: Tuple of (owner, repo, issue_number)
|
|
79
|
+
:raises ValueError: If URL format is invalid
|
|
80
|
+
"""
|
|
81
|
+
pattern = r"https?://github\.com/([^/]+)/([^/]+)/issues/(\d+)"
|
|
82
|
+
match = re.match(pattern, url)
|
|
83
|
+
if not match:
|
|
84
|
+
msg = f"Invalid GitHub issue URL format: {url}"
|
|
85
|
+
raise ValueError(msg)
|
|
86
|
+
|
|
87
|
+
owner, repo, issue_number = match.groups()
|
|
88
|
+
return owner, repo, int(issue_number)
|
|
89
|
+
|
|
90
|
+
def _post_comment(self, owner: str, repo: str, issue_number: int, comment: str) -> bool:
|
|
91
|
+
"""
|
|
92
|
+
Post a comment to a GitHub issue.
|
|
93
|
+
|
|
94
|
+
:param owner: Repository owner
|
|
95
|
+
:param repo: Repository name
|
|
96
|
+
:param issue_number: Issue number
|
|
97
|
+
:param comment: Comment text to post
|
|
98
|
+
:return: True if comment was posted successfully
|
|
99
|
+
:raises requests.exceptions.RequestException: If the API request fails
|
|
100
|
+
"""
|
|
101
|
+
url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/comments"
|
|
102
|
+
data = {"body": comment}
|
|
103
|
+
|
|
104
|
+
for attempt in range(self.retry_attempts):
|
|
105
|
+
try:
|
|
106
|
+
response = requests.post(url, headers=self._get_request_headers(), json=data, timeout=10)
|
|
107
|
+
response.raise_for_status()
|
|
108
|
+
return True
|
|
109
|
+
except requests.exceptions.RequestException as e:
|
|
110
|
+
if attempt == self.retry_attempts - 1:
|
|
111
|
+
raise
|
|
112
|
+
logger.warning(f"Attempt {attempt + 1} failed: {e!s}. Retrying...")
|
|
113
|
+
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
117
|
+
"""
|
|
118
|
+
Serialize the component to a dictionary.
|
|
119
|
+
|
|
120
|
+
:returns: Dictionary with serialized data.
|
|
121
|
+
"""
|
|
122
|
+
return default_to_dict(
|
|
123
|
+
self,
|
|
124
|
+
github_token=self.github_token.to_dict() if self.github_token else None,
|
|
125
|
+
raise_on_failure=self.raise_on_failure,
|
|
126
|
+
retry_attempts=self.retry_attempts,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def from_dict(cls, data: Dict[str, Any]) -> "GitHubIssueCommenter":
|
|
131
|
+
"""
|
|
132
|
+
Deserialize the component from a dictionary.
|
|
133
|
+
|
|
134
|
+
:param data: Dictionary to deserialize from.
|
|
135
|
+
:returns: Deserialized component.
|
|
136
|
+
"""
|
|
137
|
+
init_params = data["init_parameters"]
|
|
138
|
+
deserialize_secrets_inplace(init_params, keys=["github_token"])
|
|
139
|
+
return default_from_dict(cls, data)
|
|
140
|
+
|
|
141
|
+
@component.output_types(success=bool)
|
|
142
|
+
def run(self, url: str, comment: str) -> dict:
|
|
143
|
+
"""
|
|
144
|
+
Post a comment to a GitHub issue.
|
|
145
|
+
|
|
146
|
+
:param url: GitHub issue URL
|
|
147
|
+
:param comment: Comment text to post
|
|
148
|
+
:return: Dictionary containing success status
|
|
149
|
+
"""
|
|
150
|
+
try:
|
|
151
|
+
owner, repo, issue_number = self._parse_github_url(url)
|
|
152
|
+
success = self._post_comment(owner, repo, issue_number, comment)
|
|
153
|
+
return {"success": success}
|
|
154
|
+
|
|
155
|
+
except (requests.exceptions.RequestException, ValueError) as e:
|
|
156
|
+
if self.raise_on_failure:
|
|
157
|
+
raise
|
|
158
|
+
|
|
159
|
+
error_message = f"Error posting comment to GitHub issue {url}: {e!s}"
|
|
160
|
+
logger.warning(error_message)
|
|
161
|
+
return {"success": False}
|