├── LICENSE ├── README.md └── magit-gptcommit.el /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Intro 2 | 3 | Generate git commit messages on Magit using LLM providers, for example: OpenAI ChatGPT, Google Gemini, and more. 4 | 5 | ![melpa](https://melpa.org/packages/magit-gptcommit-badge.svg) 6 | 7 | https://github.com/douo/magit-gptcommit/assets/743074/8494b235-aa1a-4404-82e3-0a73da86e833 8 | 9 | # Dependencies 10 | 11 | - [magit](https://magit.vc/) 12 | - [llm](https://github.com/ahyatt/llm) 13 | - curl 14 | 15 | # Setup 16 | 17 | > [!NOTE] 18 | > If you are using [gptel](https://github.com/karthink/gptel) as a backend, please check out this branch(Not recommended!): [gptel](https://github.com/douo/magit-gptcommit/tree/gptel) 19 | 20 | 21 | `magit-gptcommit` depends on [llm](https://github.com/ahyatt/llm). Please read the 22 | [documentation](https://github.com/ahyatt/llm?tab=readme-ov-file#setting-up-providers) 23 | of `llm` for more details on how to set up providers. Debug logging for `llm` can be enabled by setting `llm-log` to `t`. 24 | 25 | For example, to set up the OpenAI provider, first create an [OpenAI API key](https://platform.openai.com/account/api-keys). Once obtained, configure the `llm` OpenAI provider with the API key (replace `"OPENAI-KEY"` with your key): 26 | 27 | ``` emacs-lisp 28 | (setq magit-gptcommit-llm-provider (make-llm-openai :key "OPENAI-KEY")) 29 | ``` 30 | 31 | **Recommended**: See [below](#using-auth-source-for-api-keys) how to use Emacs `auth-source` to protect API keys for `llm` providers. 32 | 33 | Activate `magit-gptcommit-mode` and open a Magit status buffer, the commit message will be automatically generated when changes are staged. You can run `magit-gptcommit-generate` when visiting a Magit status buffer to generate a commit message manually. 34 | 35 | Setup example using [use-package](https://github.com/jwiegley/use-package) and [straight](https://github.com/radian-software/straight.el): 36 | 37 | ``` emacs-lisp 38 | (use-package magit-gptcommit 39 | :straight t 40 | :demand t 41 | :after magit 42 | :bind (:map git-commit-mode-map 43 | ("C-c C-g" . magit-gptcommit-commit-accept)) 44 | :custom 45 | (magit-gptcommit-llm-provider (make-llm-openai :key "OPENAI-KEY")) 46 | 47 | :config 48 | ;; Enable magit-gptcommit-mode to watch staged changes and generate commit message automatically in magit status buffer 49 | ;; This mode is optional, you can also use `magit-gptcommit-generate' to generate commit message manually 50 | ;; `magit-gptcommit-generate' should only execute on magit status buffer currently 51 | ;; (magit-gptcommit-mode 1) 52 | 53 | ;; Add gptcommit transient commands to `magit-commit' 54 | ;; Eval (transient-remove-suffix 'magit-commit '(1 -1)) to remove gptcommit transient commands 55 | (magit-gptcommit-status-buffer-setup)) 56 | ``` 57 | 58 | # Usage 59 | 60 | | **Command** | Description | 61 | |----------------------------------|-----------------------------------------------------------------------------------------| 62 | | `magit-gptcommit-generate` | Generate gptcommit message and insert it into magit buffer. | 63 | | `magit-gptcommit-commit-create` | Execute \`magit-commit-create' and bring gptcommit message to editor. | 64 | | `magit-gptcommit-commit-quick` | Accept gptcommit message and make a commit with current staged. | 65 | | `magit-gptcommit-commit-accept` | Call on `COMMIT_EDITMSG` buffer, Accept gptcommit message after saving current message. | 66 | | `magit-gptcommit-abort` | Abort the query process of current Repository. | 67 | | `magit-gptcommit-remove-section` | Remove the gptcommit section from the current magit buffer. | 68 | 69 | | **Variable** | Description | 70 | |--------------------------------------------|----------------------------------------------------------------------------------------------| 71 | | `magit-gptcommit-prompt` | Prompt. | 72 | | `magit-gptcommit-max-token` | Default 4096, magit-gptcommit will truncate excessive characters based on 1 token = 4 chars | 73 | | `magit-gptcommit-determine-max-token` | Whether to use the llm provider max tokens, used only if `magit-gptcommit-max-token` is nil. | 74 | | `magit-gptcommit-cache-limit` | Cache size, default is 30 | 75 | | `magit-gptcommit--cache` | Cache of last generated commit message. | 76 | | `magit-gptcommit-llm-provider` | llm provider or a function that returns an llm provider. | 77 | | `magit-gptcommit-llm-provider-temperature` | llm provider temperature. (float) | 78 | | `magit-gptcommit-llm-provider-max-tokens` | llm provider max generated tokens. (integer) | 79 | 80 | # Using `auth-source` for API keys 81 | 82 | Setup an `llm` provider for Google Gemini using [use-package](https://github.com/jwiegley/use-package), [straight](https://github.com/radian-software/straight.el), and Emacs `auth-source`, given that there is an `auth-source` secret stored with the host "generativelanguage.googleapis.com" and the user "apikey". 83 | 84 | ``` emacs-lisp 85 | (use-package llm 86 | :straight t 87 | :init 88 | (require 'llm-gemini) 89 | :config 90 | (setopt llm-gemini-provider 91 | (make-llm-gemini :key (auth-info-password 92 | (car (auth-source-search 93 | :host "generativelanguage.googleapis.com" 94 | :user "apikey"))) 95 | :chat-model "gemini-1.5-flash-latest")) 96 | :custom 97 | (llm-warn-on-nonfree nil)) 98 | 99 | (use-package magit-gptcommit 100 | :straight t 101 | :demand t 102 | :after llm 103 | :custom 104 | (magit-gptcommit-llm-provider llm-gemini-provider) 105 | ...) 106 | ``` 107 | 108 | Content of the Auth Sources(`~/.authinfo`): 109 | ``` 110 | machine generativelanguage.googleapis.com login apikey password 111 | ``` 112 | > [!TIP] 113 | > Mastering Emacs has a great article on how to store secrets in Emacs using GnuPG and Auth Sources: [Keeping Secrets in Emacs](https://www.masteringemacs.org/article/keeping-secrets-in-emacs-gnupg-auth-sources) 114 | 115 | # Todo 116 | 117 | - [ ] Prompt optimization 118 | - There is still a lot of room for optimization. One problem is the context limitation, for example, GPT3.5 has a 4k context limit, so making a slightly larger edit will exceed the limit. Currently, the code roughly truncates the edit based on proportions to avoid this problem. 119 | - Alternatively, we could use a method similar to [gptcommit](https://github.com/zurawiki/gptcommit). This method summarizes the diff of each file and then merges all the summaries to generate the commit message. However, this approach requires n + 2 requests to generate a single message. 120 | - [ ] LRU Cache or Disk Cache 121 | - [X] NO Stream 122 | - [X] Other LLM Support 123 | 124 | # Credit 125 | 126 | - [llm](https://github.com/ahyatt/llm) Great project. 127 | - [gptcommit](https://github.com/zurawiki/gptcommit) Very helpful, Prompt modified from this project. 128 | - [magit-todos](https://github.com/alphapapa/magit-todos) This project has been of great help to me in learning magit development. 129 | - [GPT-Commit](https://github.com/ywkim/gpt-commit): Another Emacs pacakge for a similar purpose. 130 | -------------------------------------------------------------------------------- /magit-gptcommit.el: -------------------------------------------------------------------------------- 1 | ;;; magit-gptcommit.el --- Git commit with help of gpt -*- lexical-binding: t; -*- 2 | 3 | ;; Copyright (C) 2024 Tiou Lims 4 | 5 | ;; Author: Tiou Lims 6 | ;; URL: https://github.com/douo/magit-gptcommit 7 | ;; Version: 0.2.0 8 | ;; Package-Requires: ((emacs "29.1") (dash "2.13.0") (magit "2.90.1") (llm "0.16.1")) 9 | 10 | ;; SPDX-License-Identifier: GPL-3.0-or-later 11 | 12 | ;;; Commentary: 13 | 14 | ;; This package provides a way to commit with help of gpt. 15 | 16 | ;;; Code: 17 | 18 | ;;;; Requirements 19 | 20 | (require 'cl-lib) 21 | (require 'dash) 22 | (require 'eieio) 23 | (require 'magit) 24 | (require 'llm) 25 | 26 | ;; Debugging facilities 27 | (defcustom magit-gptcommit-debug nil 28 | "When non-nil, enable detailed debugging for magit-gptcommit. 29 | This will log detailed information about worker operations, callbacks, 30 | and state changes to help diagnose race conditions when staging 31 | changes quickly." 32 | :type 'boolean 33 | :group 'magit-gptcommit) 34 | 35 | (defvar magit-gptcommit--debug-buffer-name "*magit-gptcommit-debug*" 36 | "Name of the buffer where debug messages are logged.") 37 | 38 | (defun magit-gptcommit--debug (format-string &rest args) 39 | "Log a debug message if debugging is enabled. 40 | FORMAT-STRING and ARGS are passed to `format'." 41 | (when magit-gptcommit-debug 42 | (let ((buf (get-buffer-create magit-gptcommit--debug-buffer-name)) 43 | (msg (apply #'format format-string args))) 44 | (with-current-buffer buf 45 | (goto-char (point-max)) 46 | (let ((inhibit-read-only t) 47 | (inhibit-modification-hooks t) 48 | (buffer-undo-list t) 49 | (timestamp (format-time-string "%H:%M:%S.%3N"))) 50 | (insert (format "[%s] %s\n" timestamp msg))))))) 51 | 52 | (defun magit-gptcommit--safe-to-delete-p (start-pos end-pos &optional buffer) 53 | "Check if it's safe to delete region between START-POS and END-POS in BUFFER. 54 | If BUFFER is nil, use the current buffer." 55 | (let* ((buf (or buffer (current-buffer))) 56 | (buf-size (with-current-buffer buf (buffer-size))) 57 | ;; Use token size as a reasonable limit for commit message size 58 | ;; 4 chars per token is the approximation from the code 59 | (max-chars-per-token 4) 60 | (max-tokens (or magit-gptcommit-max-token 4096)) 61 | (max-commit-size (* max-chars-per-token max-tokens)) 62 | (region-size (- end-pos start-pos)) 63 | ;; Ensure we never delete more than 80% of the buffer 64 | (max-safe-deletion (min max-commit-size 65 | (/ (* buf-size 80) 100)))) 66 | 67 | ;; Basic sanity checks for marker positions 68 | (and (bufferp buf) 69 | (> start-pos 1) ;; Position 1 is suspicious 70 | (>= end-pos start-pos) 71 | (<= region-size max-safe-deletion) 72 | ;; We want to delete SOME content, but not too much 73 | (> region-size 0)))) 74 | 75 | (defun magit-gptcommit--safe-delete-region (start end &optional buffer) 76 | "Safely delete region between START and END if it passes safety checks. 77 | If BUFFER is nil, operate on current buffer. 78 | Returns t if deletion was performed, nil otherwise." 79 | (if (magit-gptcommit--safe-to-delete-p start end buffer) 80 | (progn 81 | (if buffer 82 | (with-current-buffer buffer 83 | (delete-region start end)) 84 | (delete-region start end)) 85 | t) 86 | ;; Deletion not performed due to safety concerns 87 | (magit-gptcommit--debug "⚠️ PREVENTED UNSAFE DELETION: start=%s end=%s size=%s, buffer-size=%s" 88 | start end (- end start) (buffer-size)) 89 | nil)) 90 | 91 | ;;;###autoload 92 | (define-minor-mode magit-gptcommit-mode 93 | "Magit gptcommit mode." 94 | :require 'magit-gptcommit 95 | :group 'magit-gptcommit 96 | :global t 97 | (if magit-gptcommit-mode 98 | (progn 99 | (magit-add-section-hook 'magit-status-sections-hook 100 | #'magit-gptcommit--status-insert-gptcommit 101 | nil 102 | 'append)) 103 | ;; Disable mode 104 | (remove-hook 'magit-status-sections-hook #'magit-gptcommit--status-insert-gptcommit))) 105 | 106 | (defvar magit-gptcommit--last-message nil 107 | "GPT generated commit message for current repository.") 108 | (defvar magit-gptcommit--active-section-list nil 109 | "List of active gptcommit sections for current repository.") 110 | (defvar magit-gptcommit--active-worker nil 111 | "Running gptcommit process for current repository. 112 | Stored as a cons cell (PROCESS . RESPONSE) where RESPONE is a SSO Message.") 113 | 114 | (cl-defstruct magit-gptcommit--worker 115 | "Structure respesenting current active llm request." 116 | key llm-request message sections 117 | (active t :read-only nil) 118 | (creation-time (float-time) :read-only t)) 119 | 120 | (defconst magit-gptcommit-prompt-one-line "You are an expert programmer writing a Git commit message. 121 | You have carefully reviewed every file diff included in this commit. 122 | 123 | First, choose the most appropriate label for the changes. 124 | Here are the labels you can choose from: 125 | - build: Changes that affect the build system or external dependencies (e.g., gulp, broccoli, npm) 126 | - chore: Routine tasks like updating dependencies, licenses, or repo settings 127 | - ci: Changes to CI configuration files or scripts (e.g., GitHub Actions, CircleCI) 128 | - docs: Documentation-only changes (e.g., fixing typos, adding examples) 129 | - feat: Introduces a new feature to the codebase 130 | - fix: Patches a bug in the codebase 131 | - perf: Improves performance without changing behavior 132 | - refactor: Code changes that neither fix bugs nor add features 133 | - style: Non-functional changes like formatting or whitespace 134 | - test: Adds or corrects tests 135 | 136 | Next, write a high-level summary of the commit. 137 | - Keep it to a single line, no more than 50 characters 138 | - Use the imperative tense (e.g., 'Add logging' not 'Added logging') 139 | - Ensure the message reflects a clear and cohesive change 140 | - Do not end the summary with a period 141 | - Do not use backticks (`) anywhere in the response 142 | 143 | THE FILE DIFFS: 144 | ``` 145 | %s 146 | ``` 147 | Now, write the commit message using this format: [label]: [summary]") 148 | 149 | (defcustom magit-gptcommit-prompt magit-gptcommit-prompt-one-line 150 | "The prompt that was used to generate the commit message." 151 | :type 'string 152 | :group 'magit-gptcommit) 153 | 154 | ;; (defun magit-gptcommit-load-prompt () 155 | ;; "Load prompt from file or download from url." 156 | ;; (let* ((directory (expand-file-name "assets/magit-gptcommit/" user-emacs-directory)) 157 | ;; (file-path (expand-file-name "prompt.txt" directory)) 158 | ;; (url "https://example.com/prompt.txt")) 159 | ;; (unless (file-exists-p directory) 160 | ;; (make-directory directory t)) 161 | ;; (if (file-exists-p file-path) 162 | ;; (with-temp-buffer 163 | ;; (insert-file-contents file-path) 164 | ;; (setq magit-gptcommit-prompt (buffer-string))) 165 | ;; ;; TODO download from url 166 | ;; (url-retrieve url (lambda (status) 167 | ;; (when (equal (car status) :ok) 168 | ;; (with-temp-buffer (url-retrieve-sentinel (current-buffer)) 169 | ;; (write-region (point-min) (point-max) file-path) 170 | ;; (setq magit-gptcommit-prompt (buffer-string))))))))) 171 | 172 | (defcustom magit-gptcommit-max-token 4096 173 | "Max token length." 174 | :type 'integer 175 | :group 'magit-gptcommit) 176 | 177 | (defcustom magit-gptcommit-determine-max-token nil 178 | "Whether to determine the max token for the llm provider. 179 | 180 | Max tokens set by the llm provider are used only if `magit-gptcommit-max-token' 181 | is nil." 182 | :type 'boolean 183 | :group 'magit-gptcommit) 184 | 185 | (defcustom magit-gptcommit-llm-provider nil 186 | "llm provider to use" 187 | :type '(choice 188 | (sexp :tag "llm provider") 189 | (function :tag "Function that returns an llm provider.")) 190 | :group 'magit-gptcommit) 191 | 192 | (defcustom magit-gptcommit-llm-provider-temperature nil 193 | "llm provider temperature." 194 | :type 'float 195 | :group 'magit-gptcommit) 196 | 197 | (defcustom magit-gptcommit-llm-provider-max-tokens nil 198 | "llm provider max tokens to generate." 199 | :type 'integer 200 | :group 'magit-gptcommit) 201 | 202 | (defcustom magit-gptcommit-process-commit-message-function #'magit-gptcommit--process-commit-message 203 | "Commit message function." 204 | :type 'function 205 | :group 'magit-gptcommit) 206 | 207 | (defcustom magit-gptcommit-commit-message-action 'replace 208 | "Commit message action." 209 | :type '(choice 210 | (const append) 211 | (const prepend) 212 | (const replace)) 213 | :group 'magit-gptcommit) 214 | 215 | ;;; Cache 216 | (defvar magit-gptcommit-cache-limit 4096 217 | "Max number of cache entries.") 218 | 219 | (defcustom magit-gptcommit-message-timeout 16 220 | "Number of seconds before messages expire from the message history. 221 | Set to nil to disable message expiration." 222 | :type '(choice (integer :tag "Seconds before expiration") 223 | (const :tag "Never expire" nil)) 224 | :group 'magit-gptcommit) 225 | 226 | (defcustom magit-gptcommit-request-cooldown 0.01 227 | "Time in seconds to wait after an LLM request completes before allowing another. 228 | This helps prevent `FTP access denied' errors by ensuring we don't 229 | make too many requests in quick succession." 230 | :type 'number 231 | :group 'magit-gptcommit) 232 | 233 | (defvar magit-gptcommit--request-in-progress nil 234 | "Non-nil when an LLM request is currently in progress. 235 | Used to serialize requests and prevent concurrent API calls.") 236 | 237 | (defvar magit-gptcommit--last-request-end-time 0 238 | "Timestamp of when the last LLM request completed.") 239 | 240 | (defvar magit-gptcommit--last-messages (make-hash-table :test 'equal :size 20) 241 | "Hash table to store recent messages from workers by key. 242 | Value is (CREATION-TIME . MESSAGE) where CREATION-TIME is used to find the newest.") 243 | 244 | (defvar magit-gptcommit--cache (make-hash-table :test 'equal :size magit-gptcommit-cache-limit) 245 | "Cache of generated commit messages as a hash table.") 246 | 247 | (cl-defun magit-gptcommit--cache-key (content &optional (repository (magit-repository-local-repository))) 248 | "Return cache key for CONTENT and REPOSITORY." 249 | ;; set repository to default if not initial 250 | (md5 (format "%s%s" repository content))) 251 | 252 | (defun magit-gptcommit--cache-set (key value) 253 | "Set cache VALUE for KEY." 254 | ;; If cache is full, remove half of the entries 255 | (when (>= (hash-table-count magit-gptcommit--cache) magit-gptcommit-cache-limit) 256 | (let* ((keys (hash-table-keys magit-gptcommit--cache)) 257 | (half-count (/ (length keys) 2))) 258 | (dolist (k (seq-take keys half-count)) 259 | (remhash k magit-gptcommit--cache)))) 260 | ;; Add the new value 261 | (puthash key value magit-gptcommit--cache)) 262 | 263 | (defun magit-gptcommit--cache-get (key &optional default) 264 | "Return cache value for KEY or DEFAULT if not found." 265 | (gethash key magit-gptcommit--cache default)) 266 | 267 | (defun magit-gptcommit--cache-p (key) 268 | "Non-nil when a value exists for KEY. 269 | 270 | Return a (KEY . VALUE) cons cell for compatibility with the old implementation." 271 | (let ((value (gethash key magit-gptcommit--cache 'not-found))) 272 | (unless (eq value 'not-found) 273 | (cons key value)))) 274 | 275 | (defun magit-gptcommit--find-newest-message () 276 | "Find the most recent message from all workers. 277 | Returns the message text or nil if no messages are available. 278 | Also removes expired messages from the hash table." 279 | (let ((newest-time 0) 280 | (newest-msg nil) 281 | (current-time (float-time)) 282 | (expired-keys '())) 283 | 284 | ;; Find the newest message and track expired messages 285 | (maphash 286 | (lambda (key value) 287 | (let ((time (car value)) 288 | (msg (cdr value))) 289 | ;; Check for expired messages if timeout is set 290 | (when (and magit-gptcommit-message-timeout 291 | (> (- current-time time) magit-gptcommit-message-timeout)) 292 | (push key expired-keys) 293 | (magit-gptcommit--debug "Message with key %s expired (age: %.1f seconds)" 294 | key (- current-time time))) 295 | 296 | ;; Track the newest message 297 | (when (> time newest-time) 298 | (setq newest-time time) 299 | (setq newest-msg msg)))) 300 | magit-gptcommit--last-messages) 301 | 302 | ;; Remove expired messages 303 | (dolist (key expired-keys) 304 | (remhash key magit-gptcommit--last-messages) 305 | (magit-gptcommit--debug "Removed expired message with key %s" key)) 306 | 307 | newest-msg)) 308 | 309 | 310 | ;;; utils 311 | (defun magit-gptcommit-status-buffer-setup () 312 | "Setup gptcommit transient command in `magit-status-mode' buffer." 313 | (interactive) 314 | (transient-append-suffix 'magit-commit '(1 -1) 315 | ["GPT Commit" 316 | :if magit-anything-staged-p 317 | ("G" "Generate" magit-gptcommit-generate) 318 | ("Q" "Quick Accept" magit-gptcommit-commit-quick) 319 | ("C" "Accept" magit-gptcommit-commit-create) 320 | ])) 321 | 322 | ;; credited: https://emacs.stackexchange.com/a/3339/30746 323 | (defmacro magit-gptcommit--add-hook-run-once (hook function &optional append local) 324 | "Like `add-hook', but remove the HOOK after FUNCTION is called. 325 | APPEND and LOCAL have the same meaning as in `add-hook'." 326 | (let ((sym (make-symbol "#once"))) 327 | `(progn 328 | (defun ,sym () 329 | (remove-hook ,hook ',sym ,local) 330 | (funcall ,function)) 331 | (add-hook ,hook ',sym ,append ,local)))) 332 | 333 | (defmacro magit-gptcommit--update-heading-status (status face) 334 | "Update gptcommit section heading with STATUS and FACE." 335 | `(progn 336 | (goto-char (+ 12 start)) 337 | (delete-region (point) (pos-eol)) 338 | (insert (propertize ,status 'font-lock-face ,face)))) 339 | 340 | (cl-defun magit-gptcommit--move-last-to-position (list position) 341 | "Move the last element of LIST to POSITION." 342 | (append (take position list) (last list) (butlast (-drop position list)))) 343 | 344 | (cl-defun magit-gptcommit--goto-target-position (&optional (condition '(tags tag branch))) ;; 345 | "Return end position of section after which to insert the commit message. 346 | Position is determined by CONDITION, which is defined in `magit-section-match'." 347 | (let ((children (oref magit-root-section children)) 348 | (pos 0)) 349 | ;; iterate over all children 350 | (cl-loop for child in children 351 | ;; find the first child that matches the condition 352 | if (or (null condition) 353 | (magit-section-match condition child)) 354 | return (goto-char (identity (oref child start))) 355 | do (cl-incf pos)) ;; index after target section 356 | (when (< pos (length children)) 357 | pos))) 358 | 359 | (cl-defun magit-gptcommit--goto-target-section (&optional (condition '(tags tag branch))) ;; 360 | "Return end position of section after which to insert the commit message. 361 | SECTION is determined by CONDITION, which is defined in `magit-section-match'." 362 | (let ((children (oref magit-root-section children)) 363 | (target)) 364 | ;; iterate over all children 365 | (setq target (cl-loop for child in children 366 | ;; find the first child that matches the condition 367 | if (or (null condition) 368 | (magit-section-match condition child)) 369 | return child)) 370 | (when target 371 | (goto-char (oref target start)) 372 | target))) 373 | 374 | 375 | (defun magit-gptcommit--retrieve-staged-diff () 376 | "Retrieve staged diff assuming current magit section is the staged section." 377 | (let* ((section (magit-current-section)) 378 | (max-token (if (and magit-gptcommit-determine-max-token (not magit-gptcommit-max-token)) 379 | (llm-chat-token-limit (magit-gptcommit--llm-provider)) 380 | magit-gptcommit-max-token)) 381 | ;; HACK: 1 token ~= 4 chars 382 | (max-char (- (* 4 max-token) (length magit-gptcommit-prompt))) 383 | (diffs (mapcar 384 | (lambda (child) 385 | (with-slots (start end) child 386 | (cons start 387 | (- (marker-position end) (marker-position start))))) 388 | (oref section children))) 389 | (total (with-slots (content end) section 390 | (- (marker-position end) (marker-position content))))) 391 | (if (> total max-char) 392 | (mapconcat 393 | (lambda (child) 394 | (buffer-substring-no-properties (car child) 395 | (+ (marker-position (car child)) 396 | (floor (* max-char (/ (float (cdr child)) total)))))) 397 | diffs "\n") 398 | (with-slots (content end) section 399 | (buffer-substring-no-properties content end))))) 400 | 401 | (cl-defun magit-gptcommit--running-p (&optional (repository (magit-repository-local-repository))) 402 | "Return non-nil if gptcommit is running for current REPOSITORY." 403 | (magit-repository-local-exists-p 'magit-gptcommit--active-worker repository)) 404 | 405 | 406 | (defun magit-gptcommit--status-insert-gptcommit () 407 | "Insert gptcommit section into status buffer." 408 | (magit-gptcommit--insert 'staged)) 409 | 410 | (defun magit-gptcommit--insert (condition &optional no-cache) 411 | "Insert gptcommit section above staged section. 412 | Staged section position is determined by CONDITION, 413 | which is defined in `magit-section-match'. 414 | NO-CACHE is non-nil if cache should be ignored." 415 | (magit-gptcommit--debug "Inserting gptcommit section with condition: %s, no-cache: %s" 416 | condition no-cache) 417 | (if (not magit-gptcommit-llm-provider) 418 | (progn 419 | (magit-gptcommit--debug "No LLM provider configured") 420 | (error "No llm provider, please configure `magit-gptcommit-llm-provider'.")) 421 | (save-excursion 422 | (when-let ((buf (current-buffer)) 423 | ;; generated if staged section exists 424 | ;; TODO: magit-anything-staged-p 425 | (pos (magit-gptcommit--goto-target-position condition)) 426 | (inhibit-read-only t) 427 | (magit-insert-section--parent magit-root-section)) 428 | 429 | (magit-repository-local-delete 'magit-gptcommit--last-message) 430 | (let* ((diff (magit-gptcommit--retrieve-staged-diff)) 431 | (key (magit-gptcommit--cache-key diff)) 432 | (worker (magit-repository-local-get 'magit-gptcommit--active-worker)) 433 | (oldkey (and worker (magit-gptcommit--worker-key worker)))) 434 | (if-let ((msg (and (not no-cache) (magit-gptcommit--cache-get key)))) 435 | ;; cache hit 436 | (progn 437 | ;; If a worker is running, abort it first when using cached message 438 | (when (magit-gptcommit--running-p) 439 | (magit-gptcommit--debug "Aborting any existing workers before using cached message") 440 | (magit-gptcommit-abort)) 441 | ;; Save message to last-messages table for consistency with streaming API 442 | (puthash key (cons (float-time) msg) magit-gptcommit--last-messages) 443 | ;; Insert the section with cached content 444 | (magit-insert-section (gptcommit nil nil) 445 | (magit-insert-heading 446 | (format 447 | (propertize "GPT commit: %s" 'font-lock-face 'magit-section-heading) 448 | (propertize "Cache" 'font-lock-face 'success))) 449 | ;; Use the helper function for consistent formatting 450 | (magit-gptcommit--insert-message (point) msg) 451 | (magit-repository-local-set 'magit-gptcommit--last-message msg))) 452 | ;; cache miss 453 | (magit-insert-section (gptcommit nil nil) 454 | (magit-insert-heading 455 | (format 456 | (propertize "GPT commit: %s" 'font-lock-face 'magit-section-heading) 457 | (propertize "Waiting" 'font-lock-face 'warning))) 458 | (if (and worker (equal key oldkey)) 459 | ;; if yes, then just insert the generated commit message 460 | (progn 461 | ;; First, remove any existing section to avoid duplicates 462 | (magit-gptcommit-remove-section) 463 | (setf (magit-gptcommit--worker-sections worker) 464 | (assq-delete-all buf (magit-gptcommit--worker-sections worker))) 465 | ;; Use the helper function for consistent formatting 466 | (magit-gptcommit--insert-message (point) 467 | (magit-gptcommit--worker-message 468 | (magit-repository-local-get 'magit-gptcommit--active-worker)))) 469 | (when worker 470 | (magit-gptcommit-abort)) 471 | (let ((start-position (point-marker)) 472 | (tracking-marker (point-marker))) 473 | (set-marker-insertion-type start-position nil) 474 | (set-marker-insertion-type tracking-marker t) 475 | (insert "\n") 476 | (magit-gptcommit--llm-chat-streaming 477 | key 478 | (list :prompt (format magit-gptcommit-prompt diff) 479 | :buffer buf 480 | :position start-position 481 | :tracking-marker tracking-marker) 482 | #'magit-gptcommit--stream-insert-response)))) 483 | ;; store section in repository-local active worker 484 | (let ((section (car (last (oref magit-root-section children)))) 485 | (worker (magit-repository-local-get 'magit-gptcommit--active-worker))) 486 | (setf (magit-gptcommit--worker-sections worker) 487 | (cons (cons buf section) 488 | (magit-gptcommit--worker-sections worker))))) 489 | ;; Add the buffer-local hook now that we know a section exists 490 | (add-hook 'kill-buffer-hook #'magit-gptcommit--buffer-kill-hook nil t)) 491 | ;; move section to correct position 492 | (oset magit-root-section children 493 | (magit-gptcommit--move-last-to-position 494 | (oref magit-root-section children) pos)))))) 495 | 496 | (defun magit-gptcommit--clear-message-history () 497 | "Clear the history of worker messages." 498 | (clrhash magit-gptcommit--last-messages) 499 | (magit-gptcommit--debug "Cleared message history")) 500 | 501 | (defun magit-gptcommit-generate () 502 | "Generate gptcommit message and insert it into the buffer." 503 | (interactive) 504 | (magit-gptcommit--debug "Starting new gptcommit generation in buffer %s" (current-buffer)) 505 | ;; Clear message history when explicitly generating a new message 506 | (magit-gptcommit--clear-message-history) 507 | (when (magit-gptcommit--running-p) 508 | (magit-gptcommit--debug "Aborting existing gptcommit worker before generating new one") 509 | (magit-gptcommit-abort)) 510 | (pcase (current-buffer) 511 | ((app (buffer-local-value 'major-mode) 'magit-status-mode) 512 | (magit-gptcommit--debug "Removing any existing GPT commit section") 513 | (magit-gptcommit-remove-section) 514 | (magit-gptcommit--debug "Inserting new GPT commit section with staged changes") 515 | (magit-gptcommit--insert 'staged t)) 516 | ((app (buffer-local-value 'major-mode) 'magit-diff-mode) 517 | (magit-gptcommit--debug "GPT commit in diff mode not implemented yet")) ; TODO 518 | ((pred (buffer-local-value 'with-editor-mode)) 519 | (magit-gptcommit--debug "GPT commit in with-editor mode not implemented yet")) ; TODO 520 | (_ (user-error "Not in a magit status buffer or with-editor buffer")))) 521 | 522 | (cl-defun magit-gptcommit-abort (&optional (repository (magit-repository-local-repository))) 523 | "Abort gptcommit process for current REPOSITORY." 524 | (interactive) 525 | (when-let ((worker (magit-repository-local-get 'magit-gptcommit--active-worker nil repository))) 526 | (magit-gptcommit--debug "Aborting worker with key: %s" 527 | (magit-gptcommit--worker-key worker)) 528 | ;; Mark worker as inactive first to prevent further callbacks from working 529 | (setf (magit-gptcommit--worker-active worker) nil) 530 | (magit-gptcommit--debug "Marked worker as inactive") 531 | 532 | (when (and worker 533 | (magit-gptcommit--worker-llm-request worker)) 534 | (magit-gptcommit--debug "Cancelling LLM request for worker") 535 | (condition-case err 536 | (llm-cancel-request (magit-gptcommit--worker-llm-request worker)) 537 | (error (magit-gptcommit--debug "Error cancelling LLM request: %S" err)))) 538 | 539 | ;; Always clean up the repository local variable 540 | (magit-gptcommit--debug "Removing worker from repository-local storage") 541 | (magit-repository-local-delete 'magit-gptcommit--active-worker repository) 542 | 543 | ;; Mark request as no longer in progress and update end time 544 | (setq magit-gptcommit--request-in-progress nil) 545 | (setq magit-gptcommit--last-request-end-time (float-time)) 546 | (magit-gptcommit--debug "Request marked as aborted and no longer in progress"))) 547 | 548 | (defun magit-gptcommit-remove-section () 549 | "Remove gptcommit SECTION from magit buffer if exist." 550 | (interactive) 551 | (when-let ((section (magit-gptcommit--goto-target-section 'gptcommit)) 552 | (inhibit-read-only t)) 553 | (magit-gptcommit--debug "Removing gptcommit section from buffer %s" (current-buffer)) 554 | (with-slots (start end) section 555 | (magit-gptcommit--debug "Deleting region from %s to %s" start end) 556 | (delete-region start end)) 557 | (magit-gptcommit--debug "Removing section from magit-root-section children") 558 | (delete section (oref magit-root-section children)))) 559 | 560 | (defun magit-gptcommit--process-commit-message (message orig-message) 561 | "Process commit message based on generated MESSAGE and current commit message ORIG-MESSAGE. 562 | 563 | Executed in the context of the commit message buffer." 564 | ;; Process the message but not the instructions at the end. 565 | (save-restriction 566 | (goto-char (point-min)) 567 | (narrow-to-region 568 | (point) 569 | (if (re-search-forward (concat "^" comment-start) nil t) 570 | (max 1 (- (point) 2)) 571 | (point-max))) 572 | (pcase magit-gptcommit-commit-message-action 573 | ('append (goto-char (point-max))) 574 | ('prepend (goto-char (point-min))) 575 | (_ (delete-region (point-min) (point)))) ; defaults to 'replace 576 | ;; Insert the new message. 577 | (insert (string-trim message) 578 | (or 579 | (and (eq magit-gptcommit-commit-message-action 'prepend) " ") 580 | "\n")))) 581 | 582 | ;;;; Commit Message 583 | (defun magit-gptcommit-commit-accept () 584 | "Accept gptcommit message, after saving current message." 585 | (interactive) 586 | (when-let ((message (magit-repository-local-get 'magit-gptcommit--last-message)) 587 | (buf (magit-commit-message-buffer))) 588 | (with-current-buffer buf 589 | (let (orig-message) 590 | ;; save the current non-empty and newly written comment, 591 | ;; because otherwise it would be irreversibly lost. 592 | (when-let ((message (git-commit-buffer-message))) 593 | (unless (ring-member log-edit-comment-ring message) 594 | (ring-insert log-edit-comment-ring message) 595 | (setq orig-message message))) 596 | (funcall magit-gptcommit-process-commit-message-function message orig-message) 597 | (save-buffer))))) 598 | 599 | (defun magit-gptcommit-commit-create () 600 | "Execute `magit-commit-create' and bring gptcommit message to editor." 601 | (interactive) 602 | (let ((hook #'magit-gptcommit-commit-accept)) 603 | (magit-gptcommit--add-hook-run-once 'git-commit-setup-hook hook) 604 | (magit-commit-create))) 605 | 606 | (defun magit-gptcommit-commit-quick () 607 | "Accept gptcommit message and make a commit with current staged." 608 | (interactive) 609 | (if-let ((message (magit-repository-local-get 'magit-gptcommit--last-message))) 610 | (magit-run-git "commit" "-m" message) 611 | (user-error "No last gptcommit message found"))) 612 | 613 | ;;;; response handling 614 | 615 | (defun magit-gptcommit--stream-insert-response (msg info) 616 | "Insert prompt response. 617 | 618 | MSG is the response. 619 | INFO is the request metadata." 620 | (magit-gptcommit--debug "Stream response received: %s..." (substring msg 0 (min 30 (length msg)))) 621 | (when-let* ((worker-buf (plist-get info :buffer)) 622 | (start-position (plist-get info :position)) 623 | (tracking-marker (plist-get info :tracking-marker)) 624 | (worker (magit-repository-local-get 'magit-gptcommit--active-worker))) 625 | 626 | ;; Always store the message in our last-messages table, regardless of worker status 627 | ;; This helps us keep track of all messages for cases when multiple workers are created/aborted 628 | (puthash (magit-gptcommit--worker-key worker) 629 | (cons (magit-gptcommit--worker-creation-time worker) msg) 630 | magit-gptcommit--last-messages) 631 | 632 | ;; Check if worker is still active 633 | (if (not (magit-gptcommit--worker-active worker)) 634 | (magit-gptcommit--debug "⚠️ Ignoring response for inactive worker with key: %s" 635 | (magit-gptcommit--worker-key worker)) 636 | 637 | ;; Worker is active, proceed with insertion 638 | (magit-gptcommit--debug "Processing response for worker with key: %s" 639 | (magit-gptcommit--worker-key worker)) 640 | (condition-case err 641 | (progn 642 | ;; Set worker message first to ensure it's available 643 | (magit-gptcommit--debug "Updating worker message") 644 | (setf (magit-gptcommit--worker-message worker) msg) 645 | 646 | ;; Process sections if they exist 647 | (when (magit-gptcommit--worker-sections worker) 648 | (magit-gptcommit--debug "Worker has %d section(s)" 649 | (length (magit-gptcommit--worker-sections worker))) 650 | (dolist (pair (magit-gptcommit--worker-sections worker)) 651 | (-let (((buf . section) pair)) 652 | (magit-gptcommit--debug "Processing section in buffer %s" buf) 653 | (when (and section 654 | buf 655 | (buffer-live-p buf)) 656 | (magit-gptcommit--debug "Buffer is live, updating content") 657 | (with-current-buffer buf 658 | (save-excursion 659 | (condition-case err2 660 | (let ((inhibit-read-only t) 661 | (magit-insert-section--parent magit-root-section)) 662 | (with-slots (start content end) section 663 | ;; Update heading status first 664 | (magit-gptcommit--debug "Updating section heading to 'Typing...'") 665 | (magit-gptcommit--update-heading-status "Typing..." 'success) 666 | 667 | ;; Use safe deletion to avoid buffer corruption 668 | (magit-gptcommit--debug "Attempting to replace content from %s to %s" 669 | start-position tracking-marker) 670 | (if (magit-gptcommit--safe-delete-region 671 | (marker-position start-position) 672 | (marker-position tracking-marker) 673 | buf) 674 | (progn 675 | ;; Deletion successful, insert new content 676 | ;; Use the helper function for consistent formatting 677 | (magit-gptcommit--insert-message start-position msg buf) 678 | (setq end tracking-marker)) 679 | ;; Deletion failed, log warning 680 | (magit-gptcommit--debug "⚠️ Skipped content update due to safety check")))) 681 | (error 682 | (magit-gptcommit--debug "Error inserting response: %S" err2) 683 | (message "Error inserting response: %S" err2)))))))))) 684 | (error 685 | (magit-gptcommit--debug "Stream response error: %S" err) 686 | (message "Stream response error: %S" err)))))) 687 | 688 | (cl-defun magit-gptcommit--stream-update-status (status &optional (error-msg)) 689 | "Update status of gptcommit section. 690 | 691 | STATUS is one of `success', `error'. 692 | ERROR-MSG is error message." 693 | (magit-gptcommit--debug "Updating section status to '%s'" status) 694 | (when-let* ((worker (magit-repository-local-get 'magit-gptcommit--active-worker)) 695 | (sections (and worker 696 | (magit-gptcommit--worker-sections worker)))) 697 | 698 | ;; Check if worker is still active before proceeding 699 | (if (not (magit-gptcommit--worker-active worker)) 700 | (magit-gptcommit--debug "⚠️ Ignoring status update for inactive worker with key: %s" 701 | (magit-gptcommit--worker-key worker)) 702 | 703 | ;; Worker is active, proceed with update 704 | (magit-gptcommit--debug "Found worker with key: %s" (magit-gptcommit--worker-key worker)) 705 | (magit-gptcommit--debug "Worker has %d section(s)" (length sections)) 706 | (dolist (pair sections) 707 | (-let (((buf . section) pair)) 708 | (when (and section 709 | buf 710 | (buffer-live-p buf)) 711 | (with-current-buffer buf 712 | (save-excursion 713 | (condition-case err 714 | (let ((inhibit-read-only t) 715 | (magit-insert-section--parent magit-root-section)) 716 | ;; Check if section markers are valid before proceeding 717 | (if (and (slot-boundp section 'start) 718 | (slot-boundp section 'content) 719 | (slot-boundp section 'end) 720 | (markerp (oref section start)) 721 | (markerp (oref section content)) 722 | (markerp (oref section end)) 723 | (> (marker-position (oref section start)) 1) 724 | (> (marker-position (oref section content)) 725 | (marker-position (oref section start)))) 726 | ;; Section markers are valid 727 | (with-slots (start content end) section 728 | (pcase status 729 | ('success 730 | (magit-gptcommit--debug "Setting status to 'Done'") 731 | (magit-gptcommit--update-heading-status "Done" 'success) 732 | ;; Use the newest message from our collection, if available 733 | (let* ((worker (magit-repository-local-get 'magit-gptcommit--active-worker)) 734 | (newest-message (magit-gptcommit--find-newest-message)) 735 | (last-message (or newest-message 736 | (and worker 737 | (magit-gptcommit--worker-message worker)))) 738 | (key (and worker 739 | (magit-gptcommit--worker-key worker)))) 740 | (when (and last-message key) 741 | (magit-gptcommit--debug "Using%s message for completion" 742 | (if newest-message " newest" "")) 743 | (magit-repository-local-set 'magit-gptcommit--last-message last-message) 744 | (magit-gptcommit--cache-set key last-message))) 745 | ;; update section properties 746 | (put-text-property content end 'magit-section section) 747 | ;; update keymap 748 | (put-text-property content end 'keymap (get-text-property start 'keymap))) 749 | ('error 750 | (magit-gptcommit--update-heading-status 751 | (format "Response Error: %s" error-msg) 'error)))) 752 | ;; Invalid section markers 753 | (magit-gptcommit--debug "⚠️ Invalid section markers in buffer %s" buf))) 754 | (error 755 | (magit-gptcommit--debug "Error updating section status: %S" err) 756 | (message "Error updating section status: %S" err))))))))))) 757 | 758 | ;;;; llm 759 | 760 | (defun magit-gptcommit--llm-provider () 761 | "Return llm provider stored in `magit-gptcommit-llm-provider'. 762 | 763 | If `magit-gptcommit-llm-provider' is a function, call it without arguments. 764 | Otherwise, return the stored value." 765 | (if (functionp magit-gptcommit-llm-provider) 766 | (funcall magit-gptcommit-llm-provider) 767 | magit-gptcommit-llm-provider)) 768 | 769 | (defun magit-gptcommit--llm-get-partial-callback (info callback) 770 | "Return parial callback for llm streaming responses. 771 | 772 | INFO is the request metadata. 773 | Calls CALLBACK with the prompt response and INFO to update the response." 774 | (lambda (response) 775 | (funcall callback response info))) 776 | 777 | (defun magit-gptcommit--llm-get-response-callback (info callback) 778 | "Return response callback for llm. 779 | 780 | INFO is the request metadata. 781 | Calls CALLBACK with the prompt response and INFO to update the response." 782 | (lambda (response) 783 | (condition-case err 784 | (let ((worker (magit-repository-local-get 'magit-gptcommit--active-worker))) 785 | ;; Only process the response if worker is still active 786 | (if (and worker (magit-gptcommit--worker-active worker)) 787 | (progn 788 | (funcall callback response info) 789 | (when (and (plist-get info :position) 790 | (plist-get info :tracking-marker)) 791 | (let ((start-position (marker-position (plist-get info :position))) 792 | (tracking-marker (marker-position (plist-get info :tracking-marker)))) 793 | (when (and start-position tracking-marker 794 | ;; Safety check for marker positions 795 | (> start-position 1) 796 | (> tracking-marker start-position)) 797 | (pulse-momentary-highlight-region start-position tracking-marker)))) 798 | (magit-gptcommit--stream-update-status 'success)) 799 | ;; Worker is inactive or gone, ignore response 800 | (magit-gptcommit--debug "⚠️ Ignoring response callback - worker inactive or gone"))) 801 | (error 802 | (magit-gptcommit--debug "Error in response callback: %S" err) 803 | (message "Error in response callback: %S" err))) 804 | (magit-gptcommit--llm-finalize))) 805 | 806 | (defun magit-gptcommit--llm-error-callback (err msg) 807 | "The error callback for llm." 808 | (magit-gptcommit--debug "LLM error callback triggered: %s" msg) 809 | (condition-case err2 810 | (magit-gptcommit--stream-update-status 'error msg) 811 | (error 812 | (magit-gptcommit--debug "Error in stream update status: %S" err2) 813 | (message "Error in llm error callback: %S" err2))) 814 | 815 | ;; Always ensure the request is properly finalized, even if errors occurred 816 | (condition-case err3 817 | (magit-gptcommit--llm-finalize) 818 | (error 819 | (magit-gptcommit--debug "Error in llm finalize: %S" err3) 820 | ;; Manually reset the request-in-progress flag as a last resort 821 | (setq magit-gptcommit--request-in-progress nil) 822 | (setq magit-gptcommit--last-request-end-time (float-time))))) 823 | 824 | (defun magit-gptcommit--insert-message (pos msg &optional buffer) 825 | "Insert MSG at position POS in BUFFER or current buffer. 826 | Ensures consistent message formatting across all insertion points." 827 | (with-current-buffer (or buffer (current-buffer)) 828 | (let ((inhibit-read-only t)) 829 | (save-excursion 830 | (goto-char pos) 831 | (insert msg "\n\n"))))) 832 | 833 | (defun magit-gptcommit--update-section-with-latest-message () 834 | "Update the current gptcommit section with the newest message available. 835 | This ensures that even if the current worker was aborted, the newest message 836 | from any worker is displayed in the section." 837 | (magit-gptcommit--debug "Attempting to update section with latest message") 838 | (condition-case err 839 | (when-let* ((newest-msg (magit-gptcommit--find-newest-message)) 840 | (section (magit-gptcommit--goto-target-section 'gptcommit))) 841 | (with-slots (start content end) section 842 | (when (and (markerp content) (markerp end) 843 | (> (marker-position content) 1) 844 | (> (marker-position end) (marker-position content))) 845 | ;; Check current content to avoid unnecessary buffer modifications 846 | (let* ((current-content (buffer-substring-no-properties 847 | (marker-position content) 848 | (marker-position end))) 849 | (current-msg (string-trim current-content)) 850 | (needs-update (not (string= current-msg newest-msg)))) 851 | 852 | (if needs-update 853 | (progn 854 | (magit-gptcommit--debug "Found valid section with different content, updating") 855 | (let ((inhibit-read-only t)) 856 | ;; Clear any existing content 857 | (delete-region content end) 858 | ;; Insert newest message using the helper function 859 | (magit-gptcommit--insert-message content newest-msg))) 860 | (magit-gptcommit--debug "Section already contains newest message, skipping update")))))) 861 | (error 862 | (magit-gptcommit--debug "Error updating section with latest message: %S" err)))) 863 | 864 | (defun magit-gptcommit--llm-finalize () 865 | "Finalize llm prompt response." 866 | (magit-gptcommit--debug "Finalizing LLM prompt response, cleaning up worker") 867 | ;; Try to update the section with the latest message before cleaning up 868 | (magit-gptcommit--update-section-with-latest-message) 869 | ;; Clean up the worker 870 | (magit-repository-local-delete 'magit-gptcommit--active-worker) 871 | 872 | ;; Mark request as no longer in progress and update end time 873 | (setq magit-gptcommit--request-in-progress nil) 874 | (setq magit-gptcommit--last-request-end-time (float-time)) 875 | (magit-gptcommit--debug "Request completed, marked as no longer in progress")) 876 | 877 | (defun magit-gptcommit--llm-chat-streaming (key info callback) 878 | "Retrieve response to prompt in INFO. 879 | 880 | KEY is a unique identifier for the request. 881 | 882 | INFO is a plist with the following keys: 883 | - :prompt (the prompt being sent) 884 | - :buffer (the magit buffer) 885 | - :position (marker at which to insert the response). 886 | - :tracking-marker (a marker that tracks the end of the inserted response text). 887 | 888 | Call CALLBACK with the response and INFO with partial and full responses." 889 | (magit-gptcommit--debug "Request for LLM chat streaming with key: %s" key) 890 | 891 | ;; Check if a request is already in progress or if we're in cooldown period 892 | (let* ((current-time (float-time)) 893 | (time-since-last-completion (- current-time magit-gptcommit--last-request-end-time)) 894 | (in-cooldown (< time-since-last-completion magit-gptcommit-request-cooldown))) 895 | 896 | (cond 897 | ;; If a request is already in progress, abort and show message 898 | (magit-gptcommit--request-in-progress 899 | (magit-gptcommit--debug "⚠️ Request blocked - another LLM request is in progress") 900 | (message "Another GPT commit request is already in progress. Please wait...") 901 | ;; Update section with a waiting message 902 | (when-let ((section (magit-gptcommit--goto-target-section 'gptcommit))) 903 | (with-slots (start) section 904 | (save-excursion 905 | (goto-char (+ 12 start)) 906 | (delete-region (point) (pos-eol)) 907 | (insert (propertize "Waiting for previous request" 'font-lock-face 'warning)))))) 908 | 909 | ;; If we're in cooldown period, wait until cooldown finishes 910 | (in-cooldown 911 | (let ((remaining (- magit-gptcommit-request-cooldown time-since-last-completion))) 912 | (magit-gptcommit--debug "Request in cooldown period (%.2f seconds remaining)" remaining) 913 | (when-let ((section (magit-gptcommit--goto-target-section 'gptcommit))) 914 | (with-slots (start) section 915 | (save-excursion 916 | (goto-char (+ 12 start)) 917 | (delete-region (point) (pos-eol)) 918 | (insert (propertize (format "Cooling down (%.1fs)" remaining) 919 | 'font-lock-face 'warning))))) 920 | (sit-for remaining) 921 | 922 | ;; After cooldown, proceed with request 923 | (magit-gptcommit--llm-chat-streaming-request key info callback))) 924 | 925 | ;; Otherwise, process the request 926 | (t (magit-gptcommit--llm-chat-streaming-request key info callback))))) 927 | 928 | (defun magit-gptcommit--llm-chat-streaming-request (key info callback) 929 | "Actual implementation of the LLM chat streaming request. 930 | See `magit-gptcommit--llm-chat-streaming' for parameter documentation." 931 | (magit-gptcommit--debug "Starting new LLM chat streaming request with key: %s" key) 932 | (let* ((prompt (plist-get info :prompt)) 933 | (buffer (plist-get info :buffer)) 934 | (llm-provider (magit-gptcommit--llm-provider)) 935 | (partial-callback 936 | (magit-gptcommit--llm-get-partial-callback info callback)) 937 | (response-callback 938 | (magit-gptcommit--llm-get-response-callback info callback)) 939 | (error-callback #'magit-gptcommit--llm-error-callback)) 940 | 941 | ;; Mark that a request is now in progress 942 | (setq magit-gptcommit--request-in-progress t) 943 | (magit-gptcommit--debug "Request marked as in progress") 944 | 945 | (magit-gptcommit--debug "Creating worker for buffer: %s" buffer) 946 | (magit-gptcommit--debug "Using prompt length: %d characters" (length prompt)) 947 | 948 | (magit-repository-local-set 949 | 'magit-gptcommit--active-worker 950 | (make-magit-gptcommit--worker 951 | :key key 952 | :llm-request (llm-chat-streaming 953 | llm-provider 954 | (llm-make-chat-prompt 955 | prompt 956 | :temperature magit-gptcommit-llm-provider-temperature 957 | :max-tokens magit-gptcommit-llm-provider-max-tokens) 958 | partial-callback 959 | response-callback 960 | error-callback))) 961 | (magit-gptcommit--debug "Worker created and stored in repository-local variable"))) 962 | 963 | ;; Add buffer-kill-hooks to abort gptcommit when magit buffers are killed 964 | (defun magit-gptcommit--buffer-kill-hook () 965 | "Abort gptcommit when a buffer is killed that might be part of the process." 966 | (when-let* ((worker (magit-repository-local-get 'magit-gptcommit--active-worker)) 967 | (sections (and worker (magit-gptcommit--worker-sections worker))) 968 | (current-buf (current-buffer))) 969 | ;; If this buffer is in the sections, abort the entire process 970 | (when (assq current-buf sections) 971 | (magit-gptcommit--debug "Magit buffer killed, aborting gptcommit process") 972 | (magit-gptcommit-abort)))) 973 | 974 | ;;;; Footer 975 | 976 | (provide 'magit-gptcommit) 977 | 978 | ;;; magit-gptcommit.el ends here 979 | --------------------------------------------------------------------------------