diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 85b674e..47cde8a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -140,11 +140,55 @@ jobs: tag_name: ${{ steps.version.outputs.version }} name: '${{ steps.version.outputs.version }}' body: | - A new version of git-auto-commit is available "${{ steps.version.outputs.version }}"! A command-line utility that analyzes changes and automatically generates the name of the commit it. + ## Git auto-commit - automatic commit generation tool + + > A new version of git-auto-commit is available `${{ steps.version.outputs.version }}`! A command-line utility that analyzes changes and automatically generates the name of the commit it. + + Git Auto-Commit is an extension for the Git version control system designed to automatically generate meaningful and context—sensitive commit messages based on changes made to the codebase. The tool simplifies developers' workflows by allowing them to focus on the content of edits rather than on the formulation of descriptions for commits. + + The development is conducted as an open source project and is distributed under the MIT license (or other compatible licensing, depending on the implementation). Git Auto-Commit can be integrated into CI/CD pipelines, hook scripts, or used manually via the command line. + + Main features: + + - Analysis of changes in the work tree and automatic generation of commit messages in natural language. + - Integration with Git via the `git auto` sub-command or configuration of user aliases. + - Support for templates and configurations for configuring the message structure in accordance with project standards (Conventional Commits, Semantic Commit Messages, etc.). + - Scalability: works both in small projects and in large monorepositories. + + ### Install + + #### If you're on windows + + Go to the root of the project and run the command. + + ```bash + iex ((New-Object Net.WebClient).DownloadString('https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-windows-auto-commit.ps1?raw=true')) + ``` + + #### If you're on linux + + Go to the root of the project and run the command. + + ```bash + curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-linux-auto-commit.sh?raw=true | bash + ``` + + ### Setting up + + #### Launch + + Everything is ready now, after making changes to the code, just run: + + ```bash + git add . + git auto + git push + ``` ${{ steps.changelog.outputs.changelog_issues_by_label }} ### Pull Requests + ${{ steps.changelog.outputs.changelog_pr }} [©thefuture-industries](https://github.com/thefuture-industries) diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100644 index 0000000..fa42ab4 --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,17 @@ +#!/bin/sh +set -e + +REPO_ROOT=$(git rev-parse --show-toplevel) + +echo "Running pre-push hook..." + +cd "$REPO_ROOT" +make fmt +make lint +make check +make buildrelease + +git add . +git commit -m "build 'binary file' for release/push bin/auto-commit" + +echo "[+] Success pre-push!" diff --git a/LGPL-2.1 b/LGPL-2.1 new file mode 100644 index 0000000..d38b1b9 --- /dev/null +++ b/LGPL-2.1 @@ -0,0 +1,511 @@ + + While most of this project is under the GPL (see COPYING), the xdiff/ + library and some libc code from compat/ are licensed under the + GNU LGPL, version 2.1 or (at your option) any later version and some + other files are under other licenses. Check the individual files to + be sure. + +---------------------------------------- + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/Makefile b/Makefile index 1a0e2c1..ddb8e04 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,11 @@ build: @echo "Running build..." @go build -o bin/auto-commit . +buildrelease: + @echo "Running release build..." + @go build -ldflags="-s -w" -trimpath -o bin/auto-commit . + @upx.exe --best --lzma bin/auto-commit + test: @go test -v ./... diff --git a/README.md b/README.md index 35fbd0f..8d04036 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,16 @@ curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scr Everything is ready now, after making changes to the code, just run: +- 1 Option + ```bash git add . git auto git push ``` + +- 2 Option + +```bash +git auto -w OR git auto --watch - Comit observer, you don't have to think and write more `git auto` -w (--watch) will figure it out when to make a comit and commit it yourself! +``` diff --git a/auto-function.go b/auto-function.go index 37631d4..112b97f 100644 --- a/auto-function.go +++ b/auto-function.go @@ -1,12 +1,20 @@ package main import ( - "fmt" "git-auto-commit/types" "regexp" "strings" ) +var ( + functionRegexGo = regexp.MustCompile(`func\s+(\w+)\s*\(([^)]*)\)`) + functionRegexPython = regexp.MustCompile(`def\s+(\w+)\s*\(([^)]*)\)`) + functionRegexTSJS = regexp.MustCompile(`function\s+(\w+)\s*\(([^)]*)\)(:\s*(\w+))?`) + functionRegexTSJSConst = regexp.MustCompile(`(const|let|var)\s+(\w+)\s*=\s*(?:function)?\s*\(([^)]*)\)\s*=>?`) + functionRegexCJava = regexp.MustCompile(`(\w+)\s+(\w+)\s*\(([^)]*)\)`) + functionRegexCSharp = regexp.MustCompile(`(public|private|protected|internal)?\s*(static)?\s*(\w+)\s+(\w+)\s*\(([^)]*)\)`) +) + func ParseToStructureFunction(line, lang string) *types.FunctionSignature { switch lang { case "go": @@ -25,6 +33,7 @@ func ParseToStructureFunction(line, lang string) *types.FunctionSignature { } func FormattedFunction(diff, lang string) string { + var addedFuncs, deletedFuncs, renamedFuncs, changedParams, changedTypes []string var oldFunc, newFunc *types.FunctionSignature lines := strings.Split(diff, "\n") @@ -41,14 +50,14 @@ func FormattedFunction(diff, lang string) string { newFunc = nil if oldFunc != nil { - return fmt.Sprintf("deleted function %s", oldFunc.Name) + deletedFuncs = append(deletedFuncs, oldFunc.Name) } } } else if strings.HasPrefix(line, "+") { newFunc = ParseToStructureFunction(line[1:], lang) if oldFunc == nil && newFunc != nil { - return fmt.Sprintf("added function %s", newFunc.Name) + addedFuncs = append(addedFuncs, newFunc.Name) } } else { oldFunc, newFunc = nil, nil @@ -57,17 +66,17 @@ func FormattedFunction(diff, lang string) string { if oldFunc != nil && newFunc != nil { if oldFunc.Name != newFunc.Name { - return fmt.Sprintf("renamed function %s -> %s", oldFunc.Name, newFunc.Name) + renamedFuncs = append(renamedFuncs, oldFunc.Name+" -> "+newFunc.Name) } if len(oldFunc.Params) == len(newFunc.Params) { for i := range oldFunc.Params { if oldFunc.Params[i].Name != newFunc.Params[i].Name && oldFunc.Params[i].Type == newFunc.Params[i].Type { - return fmt.Sprintf("changed parameter in %s function", oldFunc.Name) + changedParams = append(changedParams, oldFunc.Name+" function") } if oldFunc.Params[i].Name == newFunc.Params[i].Name && oldFunc.Params[i].Type != newFunc.Params[i].Type { - return fmt.Sprintf("changed type '%s %s' -> '%s %s'", oldFunc.Params[i].Name, oldFunc.Params[i].Type, newFunc.Params[i].Name, newFunc.Params[i].Type) + changedTypes = append(changedTypes, oldFunc.Params[i].Name+" in "+oldFunc.Name+" function") } } } @@ -76,12 +85,46 @@ func FormattedFunction(diff, lang string) string { } } - return "" + var results []string + if len(addedFuncs) == 1 { + results = append(results, "added function "+addedFuncs[0]) + } else if len(addedFuncs) > 1 { + results = append(results, "added functions: "+strings.Join(addedFuncs, ", ")) + } + + if len(deletedFuncs) == 1 { + results = append(results, "deleted function "+deletedFuncs[0]) + } else if len(deletedFuncs) > 1 { + results = append(results, "deleted functions: "+strings.Join(deletedFuncs, ", ")) + } + + if len(renamedFuncs) == 1 { + results = append(results, "renamed function "+renamedFuncs[0]) + } else if len(renamedFuncs) > 1 { + results = append(results, "renamed functions: "+strings.Join(renamedFuncs, ", ")) + } + + if len(changedParams) == 1 { + results = append(results, "changed parameter in "+changedParams[0]) + } else if len(changedParams) > 1 { + results = append(results, "changed parameters in functions: "+strings.Join(changedParams, ", ")) + } + + if len(changedTypes) == 1 { + results = append(results, "changed parameter type "+changedTypes[0]) + } else if len(changedTypes) > 1 { + results = append(results, "changed parameter types: "+strings.Join(changedTypes, ", ")) + } + + if len(results) == 0 { + return "" + } + + return strings.Join(results, " | ") } func parseGoFunction(line string) *types.FunctionSignature { - functionRegex := regexp.MustCompile(`func\s+(\w+)\s*\(([^)]*)\)`) - m := functionRegex.FindStringSubmatch(line) + m := functionRegexGo.FindStringSubmatch(line) if m == nil { return nil } @@ -106,8 +149,7 @@ func parseGoFunction(line string) *types.FunctionSignature { } func parsePythonFunction(line string) *types.FunctionSignature { - functionRegex := regexp.MustCompile(`def\s+(\w+)\s*\(([^)]*)\)`) - m := functionRegex.FindStringSubmatch(line) + m := functionRegexPython.FindStringSubmatch(line) if m == nil { return nil } @@ -133,39 +175,59 @@ func parsePythonFunction(line string) *types.FunctionSignature { } func parseTSJSFunction(line string) *types.FunctionSignature { - functionRegex := regexp.MustCompile(`function\s+(\w+)\s*\(([^)]*)\)(:\s*(\w+))?`) - m := functionRegex.FindStringSubmatch(line) - if m == nil { - return nil - } + m := functionRegexTSJS.FindStringSubmatch(line) + if m != nil { + name := m[1] + returnType := "" + if len(m) > 4 { + returnType = m[4] + } - name := m[1] - returnType := "" - if len(m) > 4 { - returnType = m[4] - } + params := []types.FunctionParameters{} + for _, p := range strings.Split(m[2], ",") { + p = strings.TrimSpace(p) + if p == "" { + continue + } - params := []types.FunctionParameters{} - for _, p := range strings.Split(m[2], ",") { - p = strings.TrimSpace(p) - if p == "" { - continue + parts := strings.Split(p, ":") + if len(parts) == 2 { + params = append(params, types.FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) + } else { + params = append(params, types.FunctionParameters{Name: p, Type: ""}) + } } - parts := strings.Split(p, ":") - if len(parts) == 2 { - params = append(params, types.FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) - } else { - params = append(params, types.FunctionParameters{Name: p, Type: ""}) + return &types.FunctionSignature{Name: name, Params: params, ReturnType: returnType} + } + + m = functionRegexTSJSConst.FindStringSubmatch(line) + if m != nil { + name := m[2] + + params := []types.FunctionParameters{} + for _, p := range strings.Split(m[3], ",") { + p = strings.TrimSpace(p) + if p == "" { + continue + } + + parts := strings.Split(p, ":") + if len(parts) == 2 { + params = append(params, types.FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) + } else { + params = append(params, types.FunctionParameters{Name: p, Type: ""}) + } } + + return &types.FunctionSignature{Name: name, Params: params, ReturnType: ""} } - return &types.FunctionSignature{Name: name, Params: params, ReturnType: returnType} + return nil } func parseCJavaFunction(line string) *types.FunctionSignature { - functionRegex := regexp.MustCompile(`(\w+)\s+(\w+)\s*\(([^)]*)\)`) - m := functionRegex.FindStringSubmatch(line) + m := functionRegexCJava.FindStringSubmatch(line) if m == nil { return nil } @@ -192,9 +254,7 @@ func parseCJavaFunction(line string) *types.FunctionSignature { } func parseCSharpFunction(line string) *types.FunctionSignature { - functionRegex := regexp.MustCompile(`(public|private|protected|internal)?\s*(static)?\s*(\w+)\s+(\w+)\s*\(([^)]*)\)`) - - m := functionRegex.FindStringSubmatch(line) + m := functionRegexCSharp.FindStringSubmatch(line) if m == nil { return nil } diff --git a/auto-import.go b/auto-import.go new file mode 100644 index 0000000..5870b18 --- /dev/null +++ b/auto-import.go @@ -0,0 +1,92 @@ +package main + +import ( + "regexp" + "strings" +) + +func FormattedImport(diff, lang, filename string) string { + var importRegex *regexp.Regexp + + var imports []string + + lines := strings.Split(diff, "\n") + + switch lang { + case "python": + importRegex = regexp.MustCompile(`^import\s+(\w+)`) + case "go": + inImportBlock := false + for _, line := range lines { + if strings.HasPrefix(line, "+") && len(line) > 1 { + trimmed := strings.TrimSpace(line[1:]) + + if strings.HasPrefix(trimmed, "import (") { + inImportBlock = true + continue + } + + if inImportBlock { + if strings.HasPrefix(trimmed, ")") { + inImportBlock = false + continue + } + + if strings.HasPrefix(trimmed, "\"") && strings.HasSuffix(trimmed, "\"") { + importName := strings.Trim(trimmed, "\"") + imports = append(imports, importName) + } + } else if strings.HasPrefix(trimmed, "import ") { + if m := regexp.MustCompile(`^import\s+\"([^\"]+)\"`).FindStringSubmatch(trimmed); m != nil { + imports = append(imports, m[1]) + } + } + } + } + + if len(imports) == 1 { + return "included '" + imports[0] + "' in " + filename + } else if len(imports) > 1 { + quoted := make([]string, len(imports)) + for i, imp := range imports { + quoted[i] = "'" + imp + "'" + } + + return "included " + strings.Join(quoted, ", ") + " in " + filename + } + + return "" + case "javascript", "typescript": + importRegex = regexp.MustCompile(`^import\s+.*from\s+['\"]([^'\"]+)['\"]`) + case "java": + importRegex = regexp.MustCompile(`^import\s+([\w\.]+);`) + case "c", "cpp": + importRegex = regexp.MustCompile(`^#include\s+[<\"]([^>\"]+)[>\"]`) + case "csharp": + importRegex = regexp.MustCompile(`^using\s+([\w\.]+);`) + default: + return "" + } + + for _, line := range lines { + if strings.HasPrefix(line, "+") { + l := line[1:] + if m := importRegex.FindStringSubmatch(strings.TrimSpace(l)); m != nil { + imports = append(imports, m[1]) + } + } + } + + if len(imports) == 1 { + return "included '" + imports[0] + "' in " + filename + } else if len(imports) > 1 { + quoted := make([]string, len(imports)) + for i, imp := range imports { + quoted[i] = "'" + imp + "'" + } + + return "included " + strings.Join(quoted, ", ") + " in " + filename + } + + return "" +} diff --git a/auto-logic.go b/auto-logic.go index 99fdf1f..c321232 100644 --- a/auto-logic.go +++ b/auto-logic.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "git-auto-commit/types" "regexp" "strings" @@ -68,46 +67,133 @@ func extractSwitchBlocks(lines []string, lang string, isNew bool) []types.Switch return blocks } -func FormattedLogic(line, lang string) string { +func extractIfBlocks(lines []string, lang string, isNew bool) []string { + var blocks []string + var ifRegex *regexp.Regexp + + switch lang { + case "python": + ifRegex = regexp.MustCompile(`if\s+([^:]+):`) + case "go": + ifRegex = regexp.MustCompile(`^\s*if\b`) + case "c", "cpp", "java", "csharp", "typescript", "javascript": + ifRegex = regexp.MustCompile(`if\s*\(([^)]+)\)`) + default: + ifRegex = regexp.MustCompile(`if`) + } + + for _, line := range lines { + if (isNew && strings.HasPrefix(line, "+")) || (!isNew && strings.HasPrefix(line, "-")) { + l := line[1:] + if m := ifRegex.FindStringSubmatch(l); m != nil { + expr := "if" + if len(m) > 1 { + expr = strings.TrimSpace(m[1]) + } + + blocks = append(blocks, expr) + } + } + } + + return blocks +} + +func _(expr string) string { // describeCondition + expr = strings.TrimSpace(expr) + + replacements := []struct { + pattern *regexp.Regexp + replace string + }{ + {regexp.MustCompile(`(\w+)\s*==\s*"?(\w+)"?`), "if $1 is equal to $2"}, + {regexp.MustCompile(`(\w+)\s*!=\s*"?(\w+)"?`), "if $1 is not equal to $2"}, + {regexp.MustCompile(`(\w+)\s*<\s*(\d+)`), "if $1 is less than $2"}, + {regexp.MustCompile(`(\w+)\s*>\s*(\d+)`), "if $1 is greater than $2"}, + } + + for _, r := range replacements { + if r.pattern.MatchString(expr) { + return r.pattern.ReplaceAllString(expr, r.replace) + } + } + + expr = strings.ReplaceAll(expr, "&&", " and ") + expr = strings.ReplaceAll(expr, "||", " or ") + + return "added condition logic: " + expr +} + +func FormattedLogic(line, lang, filename string) string { lines := strings.Split(line, "\n") + var builder strings.Builder + oldSwitches := extractSwitchBlocks(lines, lang, false) newSwitches := extractSwitchBlocks(lines, lang, true) + oldIfs := extractIfBlocks(lines, lang, false) + newIfs := extractIfBlocks(lines, lang, true) + + if len(newIfs) > 0 && len(oldIfs) == 0 { + builder.Reset() + builder.WriteString("added logic to the ") + builder.WriteString("'") + builder.WriteString(filename) + builder.WriteString("'") + builder.WriteString(" file") + return builder.String() + } + if len(oldSwitches) > 0 && len(newSwitches) == 0 { - var parts []string - for _, sw := range oldSwitches { - cases := "" + builder.WriteString("deleted switch: ") + for i, sw := range oldSwitches { + if i > 0 { + builder.WriteString("; ") + } + builder.WriteString(sw.Expr) if len(sw.Cases) > 0 { - cases = fmt.Sprintf(" (cases: %s)", strings.ReplaceAll(strings.Join(sw.Cases, ", "), "\"", "'")) + builder.WriteString(" (cases: ") + builder.WriteString(strings.ReplaceAll(strings.Join(sw.Cases, ", "), "\"", "'")) + builder.WriteString(")") } - - parts = append(parts, fmt.Sprintf("%s%s", sw.Expr, cases)) } - return fmt.Sprintf("deleted switch: %s", strings.Join(parts, "; ")) + return builder.String() } if len(newSwitches) > 0 && len(oldSwitches) == 0 { - var parts []string - for _, sw := range newSwitches { - cases := "" + builder.WriteString("added switch: ") + for i, sw := range newSwitches { + if i > 0 { + builder.WriteString("; ") + } + builder.WriteString(sw.Expr) if len(sw.Cases) > 0 { - cases = fmt.Sprintf(" (cases: %s)", strings.ReplaceAll(strings.Join(sw.Cases, ", "), "\"", "'")) + builder.WriteString(" (cases: ") + builder.WriteString(strings.ReplaceAll(strings.Join(sw.Cases, ", "), "\"", "'")) + builder.WriteString(")") } - - parts = append(parts, fmt.Sprintf("%s%s", sw.Expr, cases)) } - return fmt.Sprintf("added switch: %s", strings.Join(parts, "; ")) + return builder.String() } if len(oldSwitches) > 0 && len(newSwitches) > 0 { osw := oldSwitches[0] nsw := newSwitches[0] if osw.Expr != nsw.Expr || strings.Join(osw.Cases, ",") != strings.Join(nsw.Cases, ",") { - return fmt.Sprintf("changed logic switch '%s (cases: %s)' -> '%s (cases: %s)'", osw.Expr, strings.Join(osw.Cases, ", "), nsw.Expr, strings.ReplaceAll(strings.Join(nsw.Cases, ", "), "\"", "'")) + builder.WriteString("changed logic switch '") + builder.WriteString(osw.Expr) + builder.WriteString(" (cases: ") + builder.WriteString(strings.Join(osw.Cases, ", ")) + builder.WriteString(")' -> '") + builder.WriteString(nsw.Expr) + builder.WriteString(" (cases: ") + builder.WriteString(strings.ReplaceAll(strings.Join(nsw.Cases, ", "), "\"", "'")) + builder.WriteString(")'") + return builder.String() } } diff --git a/auto-class.go b/auto-oop.go similarity index 65% rename from auto-class.go rename to auto-oop.go index c9433f1..8435cd8 100644 --- a/auto-class.go +++ b/auto-oop.go @@ -1,12 +1,20 @@ package main import ( - "fmt" "git-auto-commit/types" "regexp" "strings" ) +var ( + classRegexTSJS = regexp.MustCompile(`class\s+(\w+)(?:\s+extends\s+(\w+))?`) + classRegexPython = regexp.MustCompile(`class\\s+(\\w+)(?:\\s*:\\s*(\\w+))?`) + classRegexCpp = regexp.MustCompile(`class\\s+(\\w+)(?:\\s*:\\s*(public|protected|private)\\s+(\\w+))?`) + classRegexCSharp = regexp.MustCompile(`(?:public\\s+)?class\\s+(\\w+)(?:\\s*:\\s*(\\w+))?`) + classRegexGo = regexp.MustCompile(`type\\s+(\\w+)\\s+struct\\s*{`) + classRegexJava = regexp.MustCompile(`(?:public\\s+)?class\\s+(\\w+)(?:\\s+extends\\s+(\\w+))?`) +) + func ParseToStructureClass(line, lang string) *types.ClassSignature { switch lang { case "typescript", "javascript": @@ -27,8 +35,7 @@ func ParseToStructureClass(line, lang string) *types.ClassSignature { } func parseTSJSClass(line string) *types.ClassSignature { - classRegex := regexp.MustCompile(`class\s+(\w+)(?:\s+extends\s+(\w+))?`) - m := classRegex.FindStringSubmatch(line) + m := classRegexTSJS.FindStringSubmatch(line) name := m[1] parent := "" @@ -41,8 +48,7 @@ func parseTSJSClass(line string) *types.ClassSignature { } func parsePythonClass(line string) *types.ClassSignature { - classRegex := regexp.MustCompile(`class\\s+(\\w+)(?:\\((\\w+)\\))?:`) - m := classRegex.FindStringSubmatch(line) + m := classRegexPython.FindStringSubmatch(line) if m == nil { return nil } @@ -73,8 +79,7 @@ func parsePythonClass(line string) *types.ClassSignature { } func parseCppClass(line string) *types.ClassSignature { - classRegex := regexp.MustCompile(`class\\s+(\\w+)(?:\\s*:\\s*(public|protected|private)\\s+(\\w+))?`) - m := classRegex.FindStringSubmatch(line) + m := classRegexCpp.FindStringSubmatch(line) if m == nil { return nil } @@ -90,8 +95,7 @@ func parseCppClass(line string) *types.ClassSignature { } func parseCSharpClass(line string) *types.ClassSignature { - classRegex := regexp.MustCompile(`(?:public\\s+)?class\\s+(\\w+)(?:\\s*:\\s*(\\w+))?`) - m := classRegex.FindStringSubmatch(line) + m := classRegexCSharp.FindStringSubmatch(line) if m == nil { return nil } @@ -107,8 +111,7 @@ func parseCSharpClass(line string) *types.ClassSignature { } func parseGoStruct(line string) *types.ClassSignature { - structRegex := regexp.MustCompile(`type\\s+(\\w+)\\s+struct\\s*{`) - m := structRegex.FindStringSubmatch(line) + m := classRegexGo.FindStringSubmatch(line) if m == nil { return nil } @@ -118,8 +121,7 @@ func parseGoStruct(line string) *types.ClassSignature { } func parseJavaClass(line string) *types.ClassSignature { - classRegex := regexp.MustCompile(`(?:public\\s+)?class\\s+(\\w+)(?:\\s+extends\\s+(\\w+))?`) - m := classRegex.FindStringSubmatch(line) + m := classRegexJava.FindStringSubmatch(line) if m == nil { return nil } @@ -150,8 +152,11 @@ func parseAccessModifiers(line, regex string) map[string]string { func FormattedClass(diff, lang string) string { var oldClass, newClass *types.ClassSignature + var builder strings.Builder var oldLines, newLines []string + var results []string + lines := strings.Split(diff, "\n") for _, line := range lines { if strings.HasPrefix(line, "-") { @@ -164,25 +169,60 @@ func FormattedClass(diff, lang string) string { oldClass = ParseToStructureClass(strings.Join(oldLines, "\n"), lang) newClass = ParseToStructureClass(strings.Join(newLines, "\n"), lang) + if oldClass == nil && newClass != nil { + builder.Reset() + builder.WriteString("added new class module ") + builder.WriteString(newClass.Name) + results = append(results, builder.String()) + } + if oldClass != nil && newClass == nil { - return fmt.Sprintf("deleted class %s", oldClass.Name) + builder.Reset() + builder.WriteString("deleted class ") + builder.WriteString(oldClass.Name) + results = append(results, builder.String()) } if oldClass != nil && newClass != nil { if oldClass.Name != newClass.Name { - return fmt.Sprintf("renamed class %s -> %s", oldClass.Name, newClass.Name) + builder.Reset() + builder.WriteString("renamed class ") + builder.WriteString(oldClass.Name) + builder.WriteString(" -> ") + builder.WriteString(newClass.Name) + results = append(results, builder.String()) } if oldClass.Parent != newClass.Parent { - return fmt.Sprintf("the heir was changed to %s", oldClass.Name) + builder.Reset() + builder.WriteString("the heir was changed to ") + builder.WriteString(newClass.Parent) + results = append(results, builder.String()) } for m, oldMod := range oldClass.Methods { if newMod, ok := newClass.Methods[m]; ok && oldMod != newMod { - return fmt.Sprintf("the access modifier of the %s method has been changed", m) + builder.Reset() + builder.WriteString("the access modifier of the ") + builder.WriteString(m) + builder.WriteString(" method has been changed") + results = append(results, builder.String()) } } } - return "" + if len(results) == 0 { + return "" + } + + builder.Reset() + for i, result := range results { + if i > 0 { + builder.WriteString(", ") + } + + builder.WriteString(result) + } + + return builder.String() } diff --git a/auto-remote.go b/auto-remote.go index b65d923..cdde711 100644 --- a/auto-remote.go +++ b/auto-remote.go @@ -1,8 +1,14 @@ package main -import "fmt" +import ( + "strconv" + "strings" +) func FormattedByRemote(token string) (string, error) { + var builder strings.Builder + builder.Reset() + branch, err := GetCurrentBranch() if err != nil { return "", err @@ -23,16 +29,27 @@ func FormattedByRemote(token string) (string, error) { return "", err } - commitMsg := fmt.Sprintf("%s (%d)", issueName, issueNumber) + builder.WriteString(issueName) + builder.WriteString(" (") + builder.WriteString(strconv.Itoa(int(issueNumber))) + builder.WriteString(")") - return commitMsg, nil + return builder.String(), nil } func FormattedByBranch() (string, error) { + var builder strings.Builder + builder.Reset() + branch, err := GetCurrentBranch() if err != nil { return "", err } - return fmt.Sprintf("changed the '%s' branch", branch), err + builder.WriteString("changed the ") + builder.WriteString("'") + builder.WriteString(branch) + builder.WriteString("'") + builder.WriteString(" branch") + return builder.String(), err } diff --git a/auto-structure.go b/auto-structure.go index 269ad27..d1826d8 100644 --- a/auto-structure.go +++ b/auto-structure.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "git-auto-commit/types" "regexp" "strings" @@ -90,6 +89,7 @@ func parseEnum(line, lang string) *types.EnumSignature { func FormattedStruct(diff, lang string) string { var oldStruct, newStruct *types.StructureSignature + var addedStruct, deletedStruct, renamedStruct []string var oldLines, newLines []string lines := strings.Split(diff, "\n") @@ -105,15 +105,48 @@ func FormattedStruct(diff, lang string) string { newStruct = parseStruct(strings.Join(newLines, "\n"), lang) if oldStruct != nil && newStruct == nil { - return fmt.Sprintf("deleted struct %s", oldStruct.Name) + deletedStruct = append(deletedStruct, oldStruct.Name) } if oldStruct == nil && newStruct != nil { - return fmt.Sprintf("added struct %s", newStruct.Name) + addedStruct = append(addedStruct, newStruct.Name) } if oldStruct != nil && newStruct != nil && oldStruct.Name != newStruct.Name { - return fmt.Sprintf("renamed struct %s -> %s", oldStruct.Name, newStruct.Name) + renamedStruct = append(renamedStruct, oldStruct.Name+" -> "+newStruct.Name) + } + + if len(addedStruct) == 1 { + return "added structure " + addedStruct[0] + } else if len(addedStruct) > 1 { + quoted := make([]string, len(addedStruct)) + for i, structName := range addedStruct { + quoted[i] = "'" + structName + "'" + } + + return "added structs: " + strings.Join(quoted, ", ") + } + + if len(deletedStruct) == 1 { + return "deleted structure " + deletedStruct[0] + } else if len(deletedStruct) > 1 { + quoted := make([]string, len(deletedStruct)) + for i, structName := range deletedStruct { + quoted[i] = "'" + structName + "'" + } + + return "deleted structs: " + strings.Join(quoted, ", ") + } + + if len(renamedStruct) == 1 { + return "renamed structure " + renamedStruct[0] + } else if len(renamedStruct) > 1 { + quoted := make([]string, len(renamedStruct)) + for i, structName := range renamedStruct { + quoted[i] = "'" + structName + "'" + } + + return "renamed structs: " + strings.Join(quoted, ", ") } return "" @@ -121,6 +154,7 @@ func FormattedStruct(diff, lang string) string { func FormattedType(diff, lang string) string { var oldType, newType *types.TypeSignature + var addedType, deletedType, renamedType []string var oldLines, newLines []string lines := strings.Split(diff, "\n") @@ -136,15 +170,48 @@ func FormattedType(diff, lang string) string { newType = parseType(strings.Join(newLines, "\n"), lang) if oldType != nil && newType == nil { - return fmt.Sprintf("deleted type %s", oldType.Name) + deletedType = append(deletedType, oldType.Name) } if oldType == nil && newType != nil { - return fmt.Sprintf("added type %s", newType.Name) + addedType = append(addedType, newType.Name) } if oldType != nil && newType != nil && oldType.Name != newType.Name { - return fmt.Sprintf("renamed type %s -> %s", oldType.Name, newType.Name) + renamedType = append(renamedType, oldType.Name+" -> "+newType.Name) + } + + if len(addedType) == 1 { + return "added type " + addedType[0] + } else if len(addedType) > 1 { + quoted := make([]string, len(addedType)) + for i, typeName := range addedType { + quoted[i] = "'" + typeName + "'" + } + + return "added types: " + strings.Join(quoted, ", ") + } + + if len(deletedType) == 1 { + return "deleted type " + deletedType[0] + } else if len(deletedType) > 1 { + quoted := make([]string, len(deletedType)) + for i, typeName := range deletedType { + quoted[i] = "'" + typeName + "'" + } + + return "deleted types: " + strings.Join(quoted, ", ") + } + + if len(renamedType) == 1 { + return "renamed type " + renamedType[0] + } else if len(renamedType) > 1 { + quoted := make([]string, len(renamedType)) + for i, typeName := range renamedType { + quoted[i] = "'" + typeName + "'" + } + + return "renamed types: " + strings.Join(quoted, ", ") } return "" @@ -152,6 +219,7 @@ func FormattedType(diff, lang string) string { func FormattedInterface(diff, lang string) string { var oldInterface, newInterface *types.InterfaceSignature + var addedInterface, deletedInterface, renamedInterface []string var oldLines, newLines []string lines := strings.Split(diff, "\n") @@ -167,15 +235,48 @@ func FormattedInterface(diff, lang string) string { newInterface = parseInterface(strings.Join(newLines, "\n"), lang) if oldInterface != nil && newInterface == nil { - return fmt.Sprintf("deleted interface %s", oldInterface.Name) + deletedInterface = append(deletedInterface, oldInterface.Name) } if oldInterface == nil && newInterface != nil { - return fmt.Sprintf("added interface %s", newInterface.Name) + addedInterface = append(addedInterface, newInterface.Name) } if oldInterface != nil && newInterface != nil && oldInterface.Name != newInterface.Name { - return fmt.Sprintf("renamed interface %s -> %s", oldInterface.Name, newInterface.Name) + renamedInterface = append(renamedInterface, oldInterface.Name+" -> "+newInterface.Name) + } + + if len(addedInterface) == 1 { + return "added interface " + addedInterface[0] + } else if len(addedInterface) > 1 { + quoted := make([]string, len(addedInterface)) + for i, interfaceName := range addedInterface { + quoted[i] = "'" + interfaceName + "'" + } + + return "added interfaces: " + strings.Join(quoted, ", ") + } + + if len(deletedInterface) == 1 { + return "deleted interface " + deletedInterface[0] + } else if len(deletedInterface) > 1 { + quoted := make([]string, len(deletedInterface)) + for i, interfaceName := range deletedInterface { + quoted[i] = "'" + interfaceName + "'" + } + + return "deleted interfaces: " + strings.Join(quoted, ", ") + } + + if len(renamedInterface) == 1 { + return "renamed interface " + renamedInterface[0] + } else if len(renamedInterface) > 1 { + quoted := make([]string, len(renamedInterface)) + for i, interfaceName := range renamedInterface { + quoted[i] = "'" + interfaceName + "'" + } + + return "renamed interfaces: " + strings.Join(quoted, ", ") } return "" @@ -183,6 +284,7 @@ func FormattedInterface(diff, lang string) string { func FormattedEnum(diff, lang string) string { var oldEnum, newEnum *types.EnumSignature + var addedEnum, deletedEnum, renamedEnum []string var oldLines, newLines []string lines := strings.Split(diff, "\n") @@ -198,15 +300,48 @@ func FormattedEnum(diff, lang string) string { newEnum = parseEnum(strings.Join(newLines, "\n"), lang) if oldEnum != nil && newEnum == nil { - return fmt.Sprintf("deleted enum %s", oldEnum.Name) + deletedEnum = append(deletedEnum, oldEnum.Name) } if oldEnum == nil && newEnum != nil { - return fmt.Sprintf("added enum %s", newEnum.Name) + addedEnum = append(addedEnum, newEnum.Name) } if oldEnum != nil && newEnum != nil && oldEnum.Name != newEnum.Name { - return fmt.Sprintf("renamed enum %s -> %s", oldEnum.Name, newEnum.Name) + renamedEnum = append(renamedEnum, oldEnum.Name+" -> "+newEnum.Name) + } + + if len(addedEnum) == 1 { + return "added enum " + addedEnum[0] + } else if len(addedEnum) > 1 { + quoted := make([]string, len(addedEnum)) + for i, enumName := range addedEnum { + quoted[i] = "'" + enumName + "'" + } + + return "added enums: " + strings.Join(quoted, ", ") + } + + if len(deletedEnum) == 1 { + return "deleted enum " + deletedEnum[0] + } else if len(deletedEnum) > 1 { + quoted := make([]string, len(deletedEnum)) + for i, enumName := range deletedEnum { + quoted[i] = "'" + enumName + "'" + } + + return "deleted enums: " + strings.Join(quoted, ", ") + } + + if len(renamedEnum) == 1 { + return "renamed enum " + renamedEnum[0] + } else if len(renamedEnum) > 1 { + quoted := make([]string, len(renamedEnum)) + for i, enumName := range renamedEnum { + quoted[i] = "'" + enumName + "'" + } + + return "renamed enums: " + strings.Join(quoted, ", ") } return "" diff --git a/auto-variables.go b/auto-variables.go index 87b67f5..5f26fef 100644 --- a/auto-variables.go +++ b/auto-variables.go @@ -1,25 +1,31 @@ package main import ( - "fmt" "git-auto-commit/types" "regexp" "strings" ) +var ( + varRegexPython = regexp.MustCompile(`^\s*(\w+)\s*=\s*(.+)`) + varRegexTSJS = regexp.MustCompile(`^\s*(let|const|var)\s+(\w+)(\s*:\s*(\w+))?\s*=\s*(.+);?`) + varRegexGoFull = regexp.MustCompile(`^\s*var\s+(\w+)\s+(\w+)\s*=\s*(.+)`) + varRegexGoShort = regexp.MustCompile(`^\s*(\w+)\s*:=\s*(.+)`) + varRegexGoNoValue = regexp.MustCompile(`^\s*var\s+(\w+)\s+(\w+)`) + defaultVarRegex = regexp.MustCompile(`^\s*(\w+)\s+(\w+)\s*=\s*([^;]+);`) +) + func ParseToStructureVariable(line, lang string) *types.VariableSignature { switch lang { case "python": - reg := regexp.MustCompile(`^\s*(\w+)\s*=\s*(.+)`) - m := reg.FindStringSubmatch(line) + m := varRegexPython.FindStringSubmatch(line) if m == nil { return nil } return &types.VariableSignature{Type: "", Name: m[1], Value: strings.TrimSpace(m[2])} case "typescript", "javascript": - reg := regexp.MustCompile(`^\s*(let|const|var)\s+(\w+)(\s*:\s*(\w+))?\s*=\s*(.+);?`) - m := reg.FindStringSubmatch(line) + m := varRegexTSJS.FindStringSubmatch(line) if m == nil { return nil } @@ -32,19 +38,27 @@ func ParseToStructureVariable(line, lang string) *types.VariableSignature { return &types.VariableSignature{Type: typ, Name: m[2], Value: strings.TrimSpace(m[5])} case "go": - reg := regexp.MustCompile(`^\s*([\w\s,]+):=\s*(.+)`) - m := reg.FindStringSubmatch(line) + m := varRegexGoFull.FindStringSubmatch(line) + if m != nil { + // names := strings.Split(m[1], ",") + // value := strings.TrimSpace(m[2]) + // return &types.VariableSignature{Type: "", Name: strings.TrimSpace(names[0]), Value: value} + return &types.VariableSignature{Type: m[2], Name: m[1], Value: strings.TrimSpace(m[3])} + } + + m = varRegexGoShort.FindStringSubmatch(line) if m != nil { - names := strings.Split(m[1], ",") - value := strings.TrimSpace(m[2]) - return &types.VariableSignature{Type: "", Name: strings.TrimSpace(names[0]), Value: value} + return &types.VariableSignature{Type: "", Name: m[1], Value: strings.TrimSpace(m[2])} + } + + m = varRegexGoNoValue.FindStringSubmatch(line) + if m != nil { + return &types.VariableSignature{Type: m[2], Name: m[1], Value: ""} } return nil default: - reg := regexp.MustCompile(`^\s*(\w+)\s+(\w+)\s*=\s*([^;]+);`) - - m := reg.FindStringSubmatch(line) + m := defaultVarRegex.FindStringSubmatch(line) if m == nil { return nil } @@ -54,6 +68,7 @@ func ParseToStructureVariable(line, lang string) *types.VariableSignature { } func FormattedVariables(diff, lang string) string { + var addedVars, renamedVars, changedTypes, changedValues []string var oldVar, newVar *types.VariableSignature lines := strings.Split(diff, "\n") @@ -66,20 +81,52 @@ func FormattedVariables(diff, lang string) string { if oldVar != nil && newVar != nil { if oldVar.Name == newVar.Name && oldVar.Type != newVar.Type { - return fmt.Sprintf("changed type of variable %s -> %s", oldVar.Type, newVar.Type) + changedTypes = append(changedTypes, oldVar.Name+" ("+oldVar.Type+" -> "+newVar.Type+")") } if oldVar.Type == newVar.Type && oldVar.Value == newVar.Value && oldVar.Name != newVar.Name { - return fmt.Sprintf("renamed variable %s -> %s", oldVar.Name, newVar.Name) + renamedVars = append(renamedVars, oldVar.Name+" -> "+newVar.Name) } if oldVar.Name == newVar.Name && oldVar.Type == newVar.Type && oldVar.Value != newVar.Value { - return fmt.Sprintf("changed value in variable %s", oldVar.Name) + changedValues = append(changedValues, oldVar.Name) } - oldVar, oldVar = nil, nil + oldVar, newVar = nil, nil + } else if newVar != nil && oldVar == nil { + addedVars = append(addedVars, newVar.Name) + newVar = nil } } - return "" + var results []string + if len(addedVars) == 1 { + results = append(results, "added variable "+addedVars[0]) + } else if len(addedVars) > 1 { + results = append(results, "added variables: "+strings.Join(addedVars, ", ")) + } + + if len(renamedVars) == 1 { + results = append(results, "renamed variable "+renamedVars[0]) + } else if len(renamedVars) > 1 { + results = append(results, "renamed variables: "+strings.Join(renamedVars, ", ")) + } + + if len(changedTypes) == 1 { + results = append(results, "changed type of variable "+changedTypes[0]) + } else if len(changedTypes) > 1 { + results = append(results, "changed types of variables: "+strings.Join(changedTypes, ", ")) + } + + if len(changedValues) == 1 { + results = append(results, "changed value in variable "+changedValues[0]) + } else if len(changedValues) > 1 { + results = append(results, "changed values in variables: "+strings.Join(changedValues, ", ")) + } + + if len(results) == 0 { + return "" + } + + return strings.Join(results, " | ") } diff --git a/bin/auto-commit b/bin/auto-commit index 6d6cddc..f59e4ea 100644 Binary files a/bin/auto-commit and b/bin/auto-commit differ diff --git a/define.go b/define.go index 9140ad1..cc247b6 100644 --- a/define.go +++ b/define.go @@ -1,11 +1,9 @@ package main +import "time" + const ( - MAX_BUFFER uint32 = 100000 - MAX_FUNC_COUNT uint8 = 128 - MAX_FUNC_NAME uint8 = 255 - MAX_LINE_LENGTH uint16 = 1024 - MAX_STRING_LENGTH uint16 = 1024 - COMMIT_LENGTH uint8 = 255 - MAX_COMMIT_LENGTH uint16 = 300 + MAX_LINE_LENGTH uint16 = 1024 + MAX_COMMIT_LENGTH uint16 = 300 + COMMIT_TIME time.Duration = 27 * time.Second ) diff --git a/detected.go b/detected.go index f21a77a..67158b8 100644 --- a/detected.go +++ b/detected.go @@ -15,8 +15,12 @@ func DetectLanguage(filename string) string { return "python" case ".js": return "javascript" + case ".jsx": + return "javascript" case ".ts": return "typescript" + case ".tsx": + return "typescript" case ".cpp": return "cpp" case ".c", ".h": diff --git a/diff.go b/diff.go index 48bad69..ba71fba 100644 --- a/diff.go +++ b/diff.go @@ -3,25 +3,42 @@ package main import ( "bufio" "bytes" - "fmt" "os/exec" + "strings" + "sync" ) +var diffBufferPool = sync.Pool{ + New: func() interface{} { + return new(bytes.Buffer) + }, +} + func GetDiff(file string) (string, error) { + var builder strings.Builder + builder.Reset() + root, err := GetGitRoot() if err != nil { return "", err } - cmd := exec.Command("git", "diff", "--cached", "--", fmt.Sprintf("%s/%s", root, file)) - var out bytes.Buffer + builder.WriteString(root) + builder.WriteString("/") + builder.WriteString(file) + + cmd := exec.Command("git", "diff", "--cached", "--", builder.String()) + + buf := diffBufferPool.Get().(*bytes.Buffer) + buf.Reset() + defer diffBufferPool.Put(buf) - cmd.Stdout = &out + cmd.Stdout = buf if err := cmd.Run(); err != nil { return "", err } - return out.String(), nil + return buf.String(), nil } func GetStagedFiles() ([]string, error) { diff --git a/go.mod b/go.mod index 12e1b8b..5024f47 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,11 @@ module git-auto-commit go 1.23.0 + +require ( + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + golang.org/x/sys v0.13.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..516f010 --- /dev/null +++ b/go.sum @@ -0,0 +1,16 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/issues.go b/issues.go index d4a8b16..af8e347 100644 --- a/issues.go +++ b/issues.go @@ -1,7 +1,7 @@ package main import ( - "encoding/json" + "bytes" "fmt" "git-auto-commit/types" "io" @@ -9,8 +9,15 @@ import ( "os/exec" "regexp" "strings" + "sync" ) +var bufferPool = sync.Pool{ + New: func() interface{} { + return new(bytes.Buffer) + }, +} + func ExtractIssueNumber(branch string) string { re := regexp.MustCompile(`(\\d+)`) match := re.FindStringSubmatch(branch) @@ -40,8 +47,17 @@ func GetOwnerRepository() (string, string, error) { } func GetIssueData(owner, repo, issue, token string) (string, uint32, error) { - url := fmt.Sprintf("https://api.github.com/repos/%s/%s/issues/%s", owner, repo, issue) - req, _ := http.NewRequest("GET", url, nil) + var builder strings.Builder + builder.Reset() + + builder.WriteString("https://api.github.com/repos/") + builder.WriteString(owner) + builder.WriteString("/") + builder.WriteString(repo) + builder.WriteString("/issues/") + builder.WriteString(issue) + + req, _ := http.NewRequest("GET", builder.String(), nil) if token != "" { req.Header.Set("Authorization", "token "+token) } @@ -52,9 +68,17 @@ func GetIssueData(owner, repo, issue, token string) (string, uint32, error) { } defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) + buf := bufferPool.Get().(*bytes.Buffer) + buf.Reset() + defer bufferPool.Put(buf) + + _, err = io.Copy(buf, resp.Body) + if err != nil { + return "", 0, err + } + var githubIssue types.GithubIssue - if err := json.Unmarshal(body, &githubIssue); err != nil { + if err := json.Unmarshal(buf.Bytes(), &githubIssue); err != nil { return "", 0, err } diff --git a/json.go b/json.go new file mode 100644 index 0000000..b406a6a --- /dev/null +++ b/json.go @@ -0,0 +1,5 @@ +package main + +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigCompatibleWithStandardLibrary diff --git a/logger.go b/logger.go index dfeca72..73a9efe 100644 --- a/logger.go +++ b/logger.go @@ -1,15 +1,32 @@ package main -import "fmt" +import ( + "fmt" + "strings" +) func InfoLogger(msg string) { - fmt.Printf("[git auto-commit] %s\n", msg) + var builder strings.Builder + builder.Reset() + builder.WriteString("[git auto-commit] ") + builder.WriteString(msg) + fmt.Println(builder.String()) } func GitLogger(msg string) { - fmt.Printf("\033[0;34m[git auto-commit] %s\033[0m\n", msg) + var builder strings.Builder + builder.Reset() + builder.WriteString("\033[0;34m[git auto-commit] ") + builder.WriteString(msg) + builder.WriteString("\033[0m\n") + fmt.Print(builder.String()) } func ErrorLogger(err error) { - fmt.Printf("\033[0;31m[git auto-commit] %s\033[0m\n", err.Error()) + var builder strings.Builder + builder.Reset() + builder.WriteString("\033[0;31m[git auto-commit] ") + builder.WriteString(err.Error()) + builder.WriteString("\033[0m\n") + fmt.Print(builder.String()) } diff --git a/main.go b/main.go index 1d9fd0d..827e6ce 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,29 @@ package main -import "fmt" +import ( + "fmt" + "os" +) func main() { + if len(os.Args) > 1 && (os.Args[1] == "-w" || os.Args[1] == "--watch") { + path, err := GetGitRoot() + if err != nil { + ErrorLogger(err) + return + } + + if len(os.Args) > 2 { + path = fmt.Sprintf("%s/%s", path, os.Args[2]) + } + + WatchCommit(path) + } else { + AutoCommit() + } +} + +func AutoCommit() { files, err := GetStagedFiles() if err != nil { ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error())) diff --git a/parser.go b/parser.go index c7738d0..5b48648 100644 --- a/parser.go +++ b/parser.go @@ -1,51 +1,107 @@ package main -import "fmt" +import ( + "fmt" + "path/filepath" + "strings" + "sync" +) func appendMsg(commitMsg, addition string) string { + var builder strings.Builder + builder.Reset() + if len(commitMsg) == 0 { return addition } - return fmt.Sprintf("%s | %s", commitMsg, addition) + builder.WriteString(commitMsg) + builder.WriteString(" | ") + builder.WriteString(addition) + return builder.String() } func Parser(files []string) (string, error) { - var commitMsg string = "" + var ( + payloadMsg string + mu sync.Mutex + wg sync.WaitGroup + errChan = make(chan error, len(files)) + ) + + workers := 3 + jobs := make(chan string, len(files)) + + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + + for file := range jobs { + mu.Lock() + if uint16(len(strings.Fields(payloadMsg))) > MAX_COMMIT_LENGTH { + mu.Unlock() + continue + } + mu.Unlock() + + diff, err := GetDiff(file) + if err != nil { + errChan <- fmt.Errorf("error getting diff for %s: %w", file, err) + continue + } + + lang := DetectLanguage(file) + if lang == "" { + mu.Lock() + payloadMsg = appendMsg(payloadMsg, fmt.Sprintf("the '%s' file has been changed", filepath.Base(file))) + mu.Unlock() + continue // README.md, etc. + } + + var fileChanges []string + for _, formatted := range []string{ + FormattedVariables(diff, lang), + FormattedFunction(diff, lang), + FormattedClass(diff, lang), + FormattedLogic(diff, lang, filepath.Base(file)), + FormattedImport(diff, lang, filepath.Base(file)), + FormattedStruct(diff, lang), + FormattedType(diff, lang), + FormattedInterface(diff, lang), + FormattedEnum(diff, lang), + } { + if formatted != "" { + fileChanges = append(fileChanges, formatted) + } // else -> continue + } + + if len(fileChanges) > 0 { + mu.Lock() + for _, change := range fileChanges { + payloadMsg = appendMsg(payloadMsg, change) + } + mu.Unlock() + } + } + }() + } for _, file := range files { - if uint16(len(commitMsg)) > MAX_COMMIT_LENGTH { - break - } + jobs <- file + } + close(jobs) - diff, err := GetDiff(file) + wg.Wait() + close(errChan) + + for err := range errChan { if err != nil { return "", err } - - lang := DetectLanguage(file) - if lang == "" { - commitMsg = appendMsg(commitMsg, fmt.Sprintf("the '%s' file has been changed", file)) - continue // README.md, etc. - } - - for _, formatted := range []string{ - FormattedVariables(diff, lang), - FormattedFunction(diff, lang), - FormattedClass(diff, lang), - FormattedLogic(diff, lang), - FormattedStruct(diff, lang), - FormattedType(diff, lang), - FormattedInterface(diff, lang), - FormattedEnum(diff, lang), - } { - if formatted != "" { - commitMsg = appendMsg(commitMsg, formatted) - } // else -> continue - } } - if len(commitMsg) == 0 { + if len(payloadMsg) == 0 { formattedByRemote, err := FormattedByRemote("") if err != nil { return "", err @@ -57,11 +113,11 @@ func Parser(files []string) (string, error) { } if formattedByRemote != "" { - commitMsg = appendMsg(commitMsg, formattedByRemote) + payloadMsg = appendMsg(payloadMsg, formattedByRemote) } else { - commitMsg = appendMsg(commitMsg, formattedByBranch) + payloadMsg = appendMsg(payloadMsg, formattedByBranch) } } - return commitMsg, nil + return payloadMsg, nil } diff --git a/scripts/install-linux-auto-commit.sh b/scripts/install-linux-auto-commit.sh index c28034d..df0debf 100644 --- a/scripts/install-linux-auto-commit.sh +++ b/scripts/install-linux-auto-commit.sh @@ -5,6 +5,19 @@ set -e HOME="$(git rev-parse --show-toplevel)" cd "$HOME" +echo "" +cat <<'EOF' + _ _ _ _ _ + __ _(_) |_ __ _ _ _| |_ ___ ___ ___ _ __ ___ _ __ ___ (_) |_ + / _` | | __| / _` | | | | __/ _ \ _____ / __/ _ \| '_ ` _ \| '_ ` _ \| | __| + | (_| | | |_ | (_| | |_| | || (_) |_____| (_| (_) | | | | | | | | | | | | |_ + \__, |_|\__| \__,_|\__,_|\__\___/ \___\___/|_| |_| |_|_| |_| |_|_|\__| + |___/ +EOF +echo "" + +echo -e "\e[33mGit Auto-Commit is an extension for the Git version control system designed to automatically generate meaningful and context-sensitive commit messages based on changes made to the codebase. The tool simplifies developers' workflows by allowing them to focus on the content of edits rather than on the formulation of descriptions for commits.\e[0m" + BINARY_NAME="auto-commit" HOOKS_DIR=".git/hooks" HOOK_PATH="$HOOKS_DIR/$BINARY_NAME" @@ -16,14 +29,24 @@ if [ ! -d .git ]; then exit 1 fi -echo "Installing $URL..." -if curl -fsSL "$URL" -o "$HOOK_PATH"; then +read -p "Should I install git auto-commit in the project? (Y/N) " answer + +if [[ "$answer" == "Y" || "$answer" == "y" ]]; then + echo -e "\e[32mInstall $URL...\e[0m" + curl -L "$URL" -o "$HOOK_PATH" chmod +x "$HOOK_PATH" - echo "File saved as $HOOK_PATH" + echo -e "\e[33mFile saved as $HOOK_PATH\e[0m" + + git config --local alias.auto '!./.git/hooks/auto-commit' + + echo -e "\e[32mSuccessful installation and settings alias for auto-commit.\e[0m" + echo "" + echo -e "\e[33mMore detailed: https://github.com/thefuture-industries/git-auto-commit\e[0m" + echo -e "\e[33mNow you can run: git auto\e[0m" +elif [[ "$answer" == "N" || "$answer" == "n" ]]; then + echo -e "\e[33mSkipping installation.\e[0m" + exit 0 else - echo "Error: Failed to download the hook script." + echo -e "\e[31mInvalid input. Please enter Y or N.\e[0m" exit 1 fi - -git config --local alias.auto "!$HOOK_PATH" -echo "[+] Git alias 'git auto' is configured. Now you can run: git auto" diff --git a/scripts/install-windows-auto-commit.ps1 b/scripts/install-windows-auto-commit.ps1 index d8e3145..8b6ab46 100644 --- a/scripts/install-windows-auto-commit.ps1 +++ b/scripts/install-windows-auto-commit.ps1 @@ -1,6 +1,19 @@ # auto-commit.psm1 $ErrorActionPreference = "Stop" +Write-Host @" + + _ _ _ _ _ + __ _(_) |_ __ _ _ _| |_ ___ ___ ___ _ __ ___ _ __ ___ (_) |_ + / _` | | __| / _` | | | | __/ _ \ _____ / __/ _ \| '_ ` _ \| '_ ` _ \| | __| + | (_| | | |_ | (_| | |_| | || (_) |_____| (_| (_) | | | | | | | | | | | | |_ + \__, |_|\__| \__,_|\__,_|\__\___/ \___\___/|_| |_| |_|_| |_| |_|_|\__| + |___/ + +"@ + +Write-Host "Git Auto-Commit is an extension for the Git version control system designed to automatically generate meaningful and context-sensitive commit messages based on changes made to the codebase. The tool simplifies developers workflows by allowing them to focus on the content of edits rather than on the formulation of descriptions for commits" -ForegroundColor Yellow + $gitRoot = & git rev-parse --show-toplevel Set-Location $gitRoot @@ -16,13 +29,29 @@ if (-not (Test-Path ".git/hooks")) { $hookPath = Join-Path -Path ".git/hooks" -ChildPath $HookName try { - Write-Host "Install $Url..." - Invoke-WebRequest -Uri $Url -OutFile $hookPath -UseBasicParsing - Write-Host "File saved as $hookPath" + $answer = Read-Host "Should I install git auto-commit in the project? (Y/N)" + + if ($answer -eq "Y" -or $answer -eq "y") { + # Install auto-commit + Write-Host "Install $Url..." -ForegroundColor Green + Invoke-WebRequest -Uri $Url -OutFile $hookPath -UseBasicParsing + Write-Host "File saved as $hookPath" -ForegroundColor Yellow + + git config --local alias.auto '!./.git/hooks/auto-commit' + + Write-Host "Successful installation and settings alias for auto-commit." -ForegroundColor Green + + Write-Host "" + Write-Host "More detailed: https://github.com/thefuture-industries/git-auto-commit" + Write-Host "Now you can run: git auto" + } elseif ($answer -eq "N" -or $answer -eq "n") { + Write-Host "Skipping installation." -ForegroundColor Yellow + exit + } else { + Write-Error "Invalid input. Please enter Y or N." -ForegroundColor Red + exit + } } catch { Write-Error "Error installing: $_" return } - -git config --local alias.auto "!./.git/hooks/auto-commit" -Write-Host "[+] Git alias 'git auto' configured. Now you can run: git auto" diff --git a/watcher.go b/watcher.go new file mode 100644 index 0000000..5a4112c --- /dev/null +++ b/watcher.go @@ -0,0 +1,94 @@ +package main + +import ( + "fmt" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strings" + "syscall" + "time" + + "github.com/fsnotify/fsnotify" +) + +func WatchCommit(path string) { + watcher, err := fsnotify.NewWatcher() + if err != nil { + ErrorLogger(err) + return + } + defer watcher.Close() + + InfoLogger("Started commit watcher...") + + if err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { + if info.IsDir() && !strings.HasPrefix(path, ".git") { + if err := watcher.Add(path); err != nil { + return err + } + } + + return nil + }); err != nil { + ErrorLogger(err) + return + } + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) + go func() { + <-sigs + InfoLogger("Shutdown work watcher...") + os.Exit(0) + }() + + for { + select { + case event := <-watcher.Events: + if strings.Contains(filepath.ToSlash(event.Name), "/.git/") { + continue + } + + if event.Op&fsnotify.Write == fsnotify.Write { + // check need is commit + cmd := exec.Command("git", "diff", "--quiet") + if err := cmd.Run(); err == nil { + continue + } + + if err := exec.Command("git", "add", ".").Run(); err != nil { + ErrorLogger(err) + return + } + + files, err := GetStagedFiles() + if err != nil { + ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error())) + return + } + + if len(files) == 0 { + InfoLogger("No files staged for commit.") + } + + parser, err := Parser(files) + if err != nil { + ErrorLogger(err) + return + } + + if len(strings.Fields(parser)) >= 255 { + if err := Commit(parser); err != nil { + ErrorLogger(err) + } + } + } + case err := <-watcher.Errors: + ErrorLogger(err) + } + + time.Sleep(COMMIT_TIME) + } +}