- 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 customizing
- message structure to 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:
-
- If you're on Linux
- Go to the root of the project and run the command:
-
-
-echo Y | bash <(curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-linux-auto-commit.sh?raw=true)
-
-
Setting up
-
Launch
-
- Everything is ready now, after making changes to the code, just
- run:
-
-
-
1 Option
-
-git add .
-git auto
-git push
-
-
2 Commands
-
-git auto -w # Commit observer: you don't have to think and write anymore, `git auto -w` will figure it out and commit for you!
-git auto -v # Viewing the current version of auto-commit
-git auto -u # Upgrade to the new auto-commit version
+ 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 customizing
+ message structure to 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:
+
+ If you're on Linux
+ Go to the root of the project and run the command:
+
+
+echo Y | bash <(curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-linux-auto-commit.sh?raw=true)
+
+
Setting up
+
Launch
+
+ Everything is ready now, after making changes to the code, just
+ run:
+
+
+
1 Option
+
+git add .
+git auto
+git push
+
+
2 Commands
+
+git auto -w # Commit observer: you don't have to think and write anymore, `git auto -w` will figure it out and commit for you!
+git auto -v # Viewing the current version of auto-commit
+git auto -u # Upgrade to the new auto-commit version
+
+
+
+
+
+
+
diff --git a/LGPL-2 b/LGPL-2
index d38b1b9..747168a 100644
--- a/LGPL-2
+++ b/LGPL-2
@@ -1,511 +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!
+
+ 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/LICENSE b/LICENSE
index 206e83b..339b987 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,21 +1,21 @@
-MIT License
-
-Copyright (c) 2025 Future Industries
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+MIT License
+
+Copyright (c) 2025 Future Industries
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Makefile b/Makefile
index cca3d06..87bcde4 100644
--- a/Makefile
+++ b/Makefile
@@ -1,34 +1,57 @@
-.PHONY: fmt lint test
-
-fmt:
- gofmt -w .
- goimports -w .
-
-lint:
- golangci-lint run
-
-check: fmt lint test
- @echo "All checks passed!"
-build:
- @echo "Running build..."
- @go build -o bin/auto-commit .
-
-buildrelease:
- @echo "Running release build (windows, linux)..."
-
- @go build -ldflags="-s -w" -trimpath -o bin/auto-commit .
- @upx.exe --best --lzma bin/auto-commit
-
- @GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-linux .
- @upx.exe --best --lzma bin/auto-commit-linux
-
-buildrelease-update:
- @echo "Running release build update..."
- @go build -ldflags="-s -w" -trimpath -o bin/auto-commit.update .
- @upx.exe --best --lzma bin/auto-commit.update
-
-test:
- @go test -v ./...
-
-run: build
- @./bin/auto-commit
+.PHONY: fmt lint test
+
+ifeq ($(OS),Windows_NT)
+ RM := del /Q
+ UPX := upx.exe
+ BIN := bin/auto-commit
+else
+ RM := rm -f
+ UPX := upx
+ BIN := ./bin/auto-commit
+endif
+
+fmt:
+ gofmt -w .
+ goimports -w .
+
+lint:
+ golangci-lint run
+
+check: fmt lint test
+ @echo "All checks passed!"
+
+build:
+ @echo "Running build..."
+ @go build -o $(BIN) ./cmd
+
+buildrelease:
+ @echo "Running release build (windows, linux)..."
+
+ # windows
+ @GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-windows-amd64 ./cmd
+ upx.exe --best --lzma bin/auto-commit-windows-amd64 || true
+
+ # linux amd64
+ GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-linux-amd64 ./cmd
+ upx --best --lzma bin/auto-commit-linux-amd64 || true
+
+ # linux arm64
+ GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-linux-arm64 ./cmd
+ upx --best --lzma bin/auto-commit-linux-arm64 || true
+
+ # macOS (Intel)
+ @GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-macos-amd64 ./cmd
+
+ # macOS (Apple Silicon / M1, M2)
+ @GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-macos-arm64 ./cmd
+
+buildrelease-update:
+ @echo "Running release build update..."
+ @go build -ldflags="-s -w" -trimpath -o $(BIN).update ./cmd
+ $(UPX) --best --lzma $(BIN).update || true
+
+test:
+ @go test -v ./...
+
+run: build
+ @./bin/auto-commit
diff --git a/README.md b/README.md
index 4f4f744..7e6aea3 100644
--- a/README.md
+++ b/README.md
@@ -1,52 +1,60 @@
-# Git auto-commit - automatic commit generation tool
-
-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
-echo Y | bash <(curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-linux-auto-commit.sh?raw=true)
-```
-
-## Setting up
-
-### Launch
-
-Everything is ready now, after making changes to the code, just run:
-
-- 1 Option
-
-```bash
-git add .
-git auto
-git push
-```
-
-- 2 Commands
-
-```bash
-git auto -w - Comit observer, you dont have to think and write more `git auto` -w (--watch) will figure it out when to make a comit and commit it yourself!
-git auto -v - Viewing the current version of auto-commit
-git auto -u - Upgrade to the new auto-commit version
-```
+# Git auto-commit - automatic commit generation tool
+
+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
+echo Y | bash <(curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-linux-auto-commit.sh?raw=true)
+```
+
+### If you're on macOS
+
+Go to the root of the project and run the command.
+
+```bash
+echo Y | curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-macos-auto-commit.sh?raw=true | bash
+```
+
+## Setting up
+
+### Launch
+
+Everything is ready now, after making changes to the code, just run:
+
+- 1 Option
+
+```bash
+git add .
+git auto
+git push
+```
+
+- 2 Commands
+
+```bash
+git auto -w - Comit observer, you dont have to think and write more `git auto` -w (--watch) will figure it out when to make a comit and commit it yourself!
+git auto -v - Viewing the current version of auto-commit
+git auto -u - Upgrade to the new auto-commit version
+```
diff --git a/SECURITY.md b/SECURITY.md
index 1a3baf1..c9f564c 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -1,34 +1,34 @@
-# Security Policy
-
-Thanks for helping make Litestar safe for everyone.
-
-## Security
-
-Litestar takes the security of our projects and services seriously, including all of the repositories managed by the [litestar organization](https://github.com/litestar-org).
-
-We will ensure that your finding gets escalated to the appropriate maintainer(s) for remediation.
-
-## Reporting Security Issues
-
-**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**
-
-[Click to Open a Security Advisory Privately](https://github.com/litestar-org/litestar/security/advisories/new)
-
-If you believe you have found a security vulnerability in any Litestar-managed repository, please report it to us through coordinated disclosure:
-
-- In the affected repository, browse to the **Security** tab, select **Advisories**, select "Report a vulnerability"
- - 
-- Please do **NOT** create an issue in the affected repository
-- Please do **NOT** send a private message to and/or tag the "@maintainer" role on our [Discord server](https://discord.gg/MmcwxztmQb)
-
-Please include as much of the information listed below as you can to help us better understand and resolve the issue:
-
-- The type of issue (e.g., buffer overflow, SQL injection, or cross-site scripting)
-- Full paths of source file(s) related to the manifestation of the issue
-- The location of the affected source code (tag/branch/commit or direct URL)
-- Any special configuration required to reproduce the issue
-- Step-by-step instructions to reproduce the issue
-- Proof-of-concept or exploit code (if possible)
-- Impact of the issue, including how an attacker might exploit the issue
-
-This information will help us triage your report more quickly.
+# Security Policy
+
+Thanks for helping make Litestar safe for everyone.
+
+## Security
+
+Litestar takes the security of our projects and services seriously, including all of the repositories managed by the [litestar organization](https://github.com/litestar-org).
+
+We will ensure that your finding gets escalated to the appropriate maintainer(s) for remediation.
+
+## Reporting Security Issues
+
+**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**
+
+[Click to Open a Security Advisory Privately](https://github.com/litestar-org/litestar/security/advisories/new)
+
+If you believe you have found a security vulnerability in any Litestar-managed repository, please report it to us through coordinated disclosure:
+
+- In the affected repository, browse to the **Security** tab, select **Advisories**, select "Report a vulnerability"
+ - 
+- Please do **NOT** create an issue in the affected repository
+- Please do **NOT** send a private message to and/or tag the "@maintainer" role on our [Discord server](https://discord.gg/MmcwxztmQb)
+
+Please include as much of the information listed below as you can to help us better understand and resolve the issue:
+
+- The type of issue (e.g., buffer overflow, SQL injection, or cross-site scripting)
+- Full paths of source file(s) related to the manifestation of the issue
+- The location of the affected source code (tag/branch/commit or direct URL)
+- Any special configuration required to reproduce the issue
+- Step-by-step instructions to reproduce the issue
+- Proof-of-concept or exploit code (if possible)
+- Impact of the issue, including how an attacker might exploit the issue
+
+This information will help us triage your report more quickly.
diff --git a/ac/ac.go b/ac/ac.go
deleted file mode 100644
index ff860d8..0000000
--- a/ac/ac.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package ac
-
-import (
- "fmt"
- "git-auto-commit/achelper"
- "git-auto-commit/achelper/logger"
- "git-auto-commit/diff"
- "git-auto-commit/git"
- "git-auto-commit/parser"
-)
-
-func AutoCommit() {
- achelper.GetVersion(false)
-
- files, err := diff.GetStagedFiles()
- if err != nil {
- logger.ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error()))
- return
- }
-
- if len(files) == 0 {
- logger.InfoLogger("No files staged for commit.")
- return
- }
-
- parserMsg, err := parser.Parser(files)
- if err != nil {
- logger.ErrorLogger(err)
- return
- }
-
- if err := git.Commit(parserMsg); err != nil {
- logger.ErrorLogger(fmt.Errorf("error committing: %s", err.Error()))
- return
- }
-}
diff --git a/achelper/logger/logger.go b/achelper/logger/logger.go
deleted file mode 100644
index d4b380a..0000000
--- a/achelper/logger/logger.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package logger
-
-import (
- "fmt"
- "strings"
-)
-
-var InfoLogger = func(msg string) {
- var builder strings.Builder
- builder.Reset()
- builder.WriteString("[git auto-commit] ")
- builder.WriteString(msg)
- fmt.Println(builder.String())
-}
-
-var GitLogger = func(msg string) {
- 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())
-}
-
-var ErrorLogger = func(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/acpkg/acpkg-comment.go b/acpkg/acpkg-comment.go
deleted file mode 100644
index f3537b5..0000000
--- a/acpkg/acpkg-comment.go
+++ /dev/null
@@ -1 +0,0 @@
-package acpkg
diff --git a/acpkg/acpkg-function.go b/acpkg/acpkg-function.go
deleted file mode 100644
index 64fff20..0000000
--- a/acpkg/acpkg-function.go
+++ /dev/null
@@ -1,290 +0,0 @@
-package acpkg
-
-import (
- "git-auto-commit/constants"
- "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":
- return parseGoFunction(line)
- case "python":
- return parsePythonFunction(line)
- case "typescript", "javascript":
- return parseTSJSFunction(line)
- case "c", "cpp", "java":
- return parseCJavaFunction(line)
- case "csharp":
- return parseCSharpFunction(line)
- default:
- return nil
- }
-}
-
-func FormattedFunction(diff, lang string) string {
- var addedFuncs, deletedFuncs, renamedFuncs, changedParams, changedTypes []string
- var oldFunc, newFunc *types.FunctionSignature
-
- lines := strings.Split(diff, "\n")
- for i := 0; i < len(lines); i++ {
- line := lines[i]
-
- if strings.HasPrefix(line, "-") {
- oldFunc = ParseToStructureFunction(line[1:], lang)
-
- if i+1 < len(lines) && strings.HasPrefix(lines[i+1], "+") {
- newFunc = ParseToStructureFunction(lines[i+1][1:], lang)
- i++
- } else {
- newFunc = nil
-
- if oldFunc != nil {
- deletedFuncs = append(deletedFuncs, oldFunc.Name)
- }
- }
- } else if strings.HasPrefix(line, "+") {
- newFunc = ParseToStructureFunction(line[1:], lang)
-
- if oldFunc == nil && newFunc != nil {
- addedFuncs = append(addedFuncs, newFunc.Name)
- }
- } else {
- oldFunc, newFunc = nil, nil
- continue
- }
-
- if oldFunc != nil && newFunc != nil {
- if 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 {
- changedParams = append(changedParams, oldFunc.Name+" function")
- }
-
- if oldFunc.Params[i].Name == newFunc.Params[i].Name && oldFunc.Params[i].Type != newFunc.Params[i].Type {
- changedTypes = append(changedTypes, oldFunc.Params[i].Name+" in "+oldFunc.Name+" function")
- }
- }
- }
-
- oldFunc, newFunc = nil, nil
- }
- }
-
- 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 ""
- }
-
- parser := strings.Join(results, " | ")
- for len(parser) > int(constants.MAX_COMMIT_LENGTH) && len(results) > 1 {
- results = results[:len(results)-1]
- parser = strings.Join(results, " | ")
- }
-
- if len(parser) > int(constants.MAX_COMMIT_LENGTH) && len(results) == 1 {
- parser = parser[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- return parser
-}
-
-func parseGoFunction(line string) *types.FunctionSignature {
- m := functionRegexGo.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[1]
- paramsString := m[2]
- params := []types.FunctionParameters{}
-
- for _, p := range strings.Split(paramsString, ",") {
- p = strings.TrimSpace(p)
- if p == "" {
- continue
- }
-
- parts := strings.Fields(p)
- if len(parts) == 2 {
- params = append(params, types.FunctionParameters{Name: parts[0], Type: parts[1]})
- }
- }
-
- return &types.FunctionSignature{Name: name, Params: params}
-}
-
-func parsePythonFunction(line string) *types.FunctionSignature {
- m := functionRegexPython.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[1]
- 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: ""})
- }
- }
-
- return &types.FunctionSignature{Name: name, Params: params}
-}
-
-func parseTSJSFunction(line string) *types.FunctionSignature {
- m := functionRegexTSJS.FindStringSubmatch(line)
- if m != nil {
- 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
- }
-
- 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 nil
-}
-
-func parseCJavaFunction(line string) *types.FunctionSignature {
- m := functionRegexCJava.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- returnType := m[1]
- name := m[2]
-
- params := []types.FunctionParameters{}
- for _, p := range strings.Split(m[3], ",") {
- p = strings.TrimSpace(p)
- if p == "" {
- continue
- }
-
- parts := strings.Fields(p)
- if len(parts) == 2 {
- params = append(params, types.FunctionParameters{Name: parts[1], Type: parts[0]})
- } else if len(parts) == 1 {
- params = append(params, types.FunctionParameters{Name: parts[0], Type: ""})
- }
- }
-
- return &types.FunctionSignature{Name: name, Params: params, ReturnType: returnType}
-}
-
-func parseCSharpFunction(line string) *types.FunctionSignature {
- m := functionRegexCSharp.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[4]
- params := []types.FunctionParameters{}
- for _, p := range strings.Split(m[5], ",") {
- p = strings.TrimSpace(p)
- if p == "" {
- continue
- }
-
- parts := strings.Fields(p)
- if len(parts) == 2 {
- params = append(params, types.FunctionParameters{Name: parts[1], Type: parts[0]})
- } else if len(parts) == 1 {
- params = append(params, types.FunctionParameters{Name: parts[0], Type: ""})
- }
- }
-
- return &types.FunctionSignature{Name: name, Params: params, ReturnType: m[3]}
-}
diff --git a/acpkg/acpkg-import.go b/acpkg/acpkg-import.go
deleted file mode 100644
index 26f8413..0000000
--- a/acpkg/acpkg-import.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package acpkg
-
-import (
- "git-auto-commit/constants"
- "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 + "'"
- }
-
- result := "included " + strings.Join(quoted, ", ") + " in " + filename
- for len(result) > int(constants.MAX_COMMIT_LENGTH) && len(quoted) > 1 {
- quoted = quoted[:len(quoted)-1]
- result = "included " + strings.Join(quoted, ", ") + " in " + filename
- }
-
- if len(result) > int(constants.MAX_COMMIT_LENGTH) && len(quoted) == 1 {
- result = result[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- return result
- }
-
- return ""
-}
diff --git a/acpkg/acpkg-logic.go b/acpkg/acpkg-logic.go
deleted file mode 100644
index a190409..0000000
--- a/acpkg/acpkg-logic.go
+++ /dev/null
@@ -1,280 +0,0 @@
-package acpkg
-
-import (
- "git-auto-commit/constants"
- "git-auto-commit/types"
- "regexp"
- "strings"
-)
-
-func extractSwitchBlocks(lines []string, lang string, isNew bool) []types.SwitchSignature {
- var blocks []types.SwitchSignature
- var switchRegex, caseRegex *regexp.Regexp
-
- switch lang {
- case "python":
- switchRegex = regexp.MustCompile(`match\s+([\w\d_]+)\s*:`)
- caseRegex = regexp.MustCompile(`case\s+([^:]+):`)
- case "go":
- switchRegex = regexp.MustCompile(`switch\s*([\w\d_]+)?\s*{`)
- caseRegex = regexp.MustCompile(`case\s+([^:]+):`)
- case "c", "cpp", "java", "csharp":
- switchRegex = regexp.MustCompile(`switch\s*\(([^)]+)\)`)
- caseRegex = regexp.MustCompile(`case\s+([^:]+):`)
- case "typescript", "javascript":
- switchRegex = regexp.MustCompile(`switch\s*\(([^)]+)\)`)
- caseRegex = regexp.MustCompile(`case\s+([^:]+):`)
- default:
- switchRegex = regexp.MustCompile(`switch`)
- caseRegex = regexp.MustCompile(`case`)
- }
-
- for i := 0; i < len(lines); i++ {
- line := lines[i]
- if (isNew && strings.HasPrefix(line, "+")) || (!isNew && strings.HasPrefix(line, "-")) {
- l := line[1:]
- if m := switchRegex.FindStringSubmatch(l); m != nil {
- expr := "switch"
-
- if len(m) > 1 && m[1] != "" {
- expr = strings.TrimSpace(m[1])
- }
-
- cases := []string{}
- for j := i + 1; j < len(lines); j++ {
- cl := lines[j]
- if (isNew && strings.HasPrefix(cl, "+")) || (!isNew && strings.HasPrefix(cl, "-")) {
- cln := cl[1:]
- if caseRegex.MatchString(cln) {
- cm := caseRegex.FindStringSubmatch(cln)
- if len(cm) > 1 {
- cases = append(cases, strings.TrimSpace(cm[1]))
- }
- }
-
- if switchRegex.MatchString(cln) {
- break
- }
- } else {
- break
- }
- }
-
- blocks = append(blocks, types.SwitchSignature{Expr: expr, Cases: cases})
- }
- }
- }
-
- return blocks
-}
-
-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\s+(.*)`)
- 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 describeCondition(expr string) string {
- expr = strings.TrimSpace(expr)
- if idx := strings.Index(expr, "{"); idx != -1 {
- expr = strings.TrimSpace(expr[:idx])
- }
-
- 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"},
- }
-
- // {regexp.MustCompile(`(.+?)\s*==\s*"?(.+?)"?$`), "if $1 is equal to $2"},
- // {regexp.MustCompile(`(.+?)\s*!=\s*"?(.+?)"?$`), "if $1 is not equal to $2"},
- // {regexp.MustCompile(`(.+?)\s*<\s*(.+?)$`), "if $1 is less than $2"},
- // {regexp.MustCompile(`(.+?)\s*>\s*(.+?)$`), "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()
-
- for i, cond := range newIfs {
- if i > 0 {
- builder.WriteString("; ")
- }
-
- builder.WriteString(describeCondition(cond))
- }
-
- result := builder.String()
- for len(result) > int(constants.MAX_COMMIT_LENGTH) && len(newIfs) > 1 {
- newIfs = newIfs[:len(newIfs)-1]
- builder.Reset()
-
- for i, cond := range newIfs {
- if i > 0 {
- builder.WriteString("; ")
- }
-
- builder.WriteString(describeCondition(cond))
- }
-
- result = builder.String()
- }
-
- if len(result) > int(constants.MAX_COMMIT_LENGTH) && len(newIfs) == 1 {
- result = result[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- return result
- }
-
- if len(oldSwitches) > 0 && len(newSwitches) == 0 {
- makeResult := func(switches []types.SwitchSignature) string {
- var b strings.Builder
- b.WriteString("removed switch on ")
- for i, sw := range switches {
- if i > 0 {
- b.WriteString("; ")
- }
- b.WriteString("'" + sw.Expr + "'")
- if len(sw.Cases) > 0 {
- b.WriteString(" with cases: ")
- b.WriteString(strings.ReplaceAll(strings.Join(sw.Cases, ", "), "\"", "'"))
- }
- }
-
- return b.String()
- }
-
- result := makeResult(oldSwitches)
- for len(result) > int(constants.MAX_COMMIT_LENGTH) && len(oldSwitches) > 1 {
- oldSwitches = oldSwitches[:len(oldSwitches)-1]
- result = makeResult(oldSwitches)
- }
-
- if len(result) > int(constants.MAX_COMMIT_LENGTH) && len(oldSwitches) == 1 {
- result = result[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- return result
- }
-
- if len(newSwitches) > 0 && len(oldSwitches) == 0 {
- makeResult := func(switches []types.SwitchSignature) string {
- var b strings.Builder
- b.WriteString("added switch on ")
- for i, sw := range switches {
- if i > 0 {
- b.WriteString("; ")
- }
- b.WriteString("'" + sw.Expr + "'")
- if len(sw.Cases) > 0 {
- b.WriteString(" with cases: ")
- b.WriteString(strings.ReplaceAll(strings.Join(sw.Cases, ", "), "\"", "'"))
- }
- }
-
- return b.String()
- }
-
- result := makeResult(newSwitches)
- for len(result) > int(constants.MAX_COMMIT_LENGTH) && len(newSwitches) > 1 {
- newSwitches = newSwitches[:len(newSwitches)-1]
- result = makeResult(newSwitches)
- }
-
- if len(result) > int(constants.MAX_COMMIT_LENGTH) && len(newSwitches) == 1 {
- result = result[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- return result
- }
-
- if len(oldSwitches) > 0 && len(newSwitches) > 0 {
- osw := oldSwitches[0]
- nsw := newSwitches[0]
-
- makeResult := func(osw, nsw types.SwitchSignature) string {
- var b strings.Builder
- b.WriteString("changed switch from '")
- b.WriteString(osw.Expr)
- b.WriteString("' (cases: ")
- b.WriteString(strings.Join(osw.Cases, ", "))
- b.WriteString(") to '")
- b.WriteString(nsw.Expr)
- b.WriteString("' (cases: ")
- b.WriteString(strings.ReplaceAll(strings.Join(nsw.Cases, ", "), "\"", "'"))
- b.WriteString(")")
-
- return b.String()
- }
-
- result := makeResult(osw, nsw)
- for len(result) > int(constants.MAX_COMMIT_LENGTH) && (len(osw.Cases) > 1 || len(nsw.Cases) > 1) {
- if len(osw.Cases) > len(nsw.Cases) {
- osw.Cases = osw.Cases[:len(osw.Cases)-1]
- } else {
- nsw.Cases = nsw.Cases[:len(nsw.Cases)-1]
- }
-
- result = makeResult(osw, nsw)
- }
-
- if len(result) > int(constants.MAX_COMMIT_LENGTH) && len(osw.Cases) == 1 && len(nsw.Cases) == 1 {
- result = result[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- return result
- }
-
- return ""
-}
diff --git a/acpkg/acpkg-oop.go b/acpkg/acpkg-oop.go
deleted file mode 100644
index 9cd7536..0000000
--- a/acpkg/acpkg-oop.go
+++ /dev/null
@@ -1,232 +0,0 @@
-package acpkg
-
-import (
- "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":
- return parseTSJSClass(line)
- case "python":
- return parsePythonClass(line)
- case "cpp":
- return parseCppClass(line)
- case "csharp":
- return parseCSharpClass(line)
- case "go":
- return parseGoStruct(line)
- case "java":
- return parseJavaClass(line)
- default:
- return nil
- }
-}
-
-func parseTSJSClass(line string) *types.ClassSignature {
- m := classRegexTSJS.FindStringSubmatch(line)
- //nolint
- if m == nil || len(m) < 2 {
- return nil
- }
-
- name := m[1]
- parent := ""
- if len(m) > 2 {
- parent = m[2]
- }
-
- methods := parseAccessModifiers(line, "(public|private|protected)\\s+(\\w+)\\s*\\(")
- return &types.ClassSignature{Name: name, Parent: parent, Methods: methods}
-}
-
-func parsePythonClass(line string) *types.ClassSignature {
- m := classRegexPython.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[1]
- parent := ""
- if len(m) > 2 {
- parent = m[2]
- }
-
- methods := make(map[string]string)
- methodRegex := regexp.MustCompile(`def\s+(_{0,2}\w+)\s*\(`)
- for _, l := range strings.Split(line, "\n") {
- mm := methodRegex.FindStringSubmatch(l)
- if mm != nil {
- mod := "public"
- if strings.HasPrefix(mm[1], "__") {
- mod = "private"
- } else if strings.HasPrefix(mm[1], "_") {
- mod = "protected"
- }
-
- methods[mm[1]] = mod
- }
- }
-
- return &types.ClassSignature{Name: name, Parent: parent, Methods: methods}
-}
-
-func parseCppClass(line string) *types.ClassSignature {
- m := classRegexCpp.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[1]
- parent := ""
- if len(m) > 3 {
- parent = m[3]
- }
-
- methods := parseAccessModifiers(line, "(public|private|protected):\\s*\\w+\\s+(\\w+)\\s*\\(")
- return &types.ClassSignature{Name: name, Parent: parent, Methods: methods}
-}
-
-func parseCSharpClass(line string) *types.ClassSignature {
- m := classRegexCSharp.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[1]
- parent := ""
- if len(m) > 2 {
- parent = m[2]
- }
-
- methods := parseAccessModifiers(line, "(public|private|protected|internal)\\s+\\w+\\s+(\\w+)\\s*\\(")
- return &types.ClassSignature{Name: name, Parent: parent, Methods: methods}
-}
-
-func parseGoStruct(line string) *types.ClassSignature {
- m := classRegexGo.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[1]
- return &types.ClassSignature{Name: name, Parent: "", Methods: make(map[string]string)}
-}
-
-func parseJavaClass(line string) *types.ClassSignature {
- m := classRegexJava.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- name := m[1]
- parent := ""
- if len(m) > 2 {
- parent = m[2]
- }
-
- methods := parseAccessModifiers(line, "(public|private|protected)\\s+(\\w+)\\s*\\(")
- return &types.ClassSignature{Name: name, Parent: parent, Methods: methods}
-}
-
-func parseAccessModifiers(line, regex string) map[string]string {
- methods := make(map[string]string)
- methodRegex := regexp.MustCompile(regex)
-
- for _, l := range strings.Split(line, "\n") {
- mm := methodRegex.FindStringSubmatch(l)
- if mm != nil {
- methods[mm[2]] = mm[1]
- }
- }
-
- return methods
-}
-
-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, "-") {
- oldLines = append(oldLines, line[1:])
- } else if strings.HasPrefix(line, "+") {
- newLines = append(newLines, line[1:])
- }
- }
-
- 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 {
- 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 {
- 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 {
- 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 {
- builder.Reset()
- builder.WriteString("the access modifier of the ")
- builder.WriteString(m)
- builder.WriteString(" method has been changed")
- results = append(results, builder.String())
- }
- }
- }
-
- 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/acpkg/acpkg-structure.go b/acpkg/acpkg-structure.go
deleted file mode 100644
index 7a170fc..0000000
--- a/acpkg/acpkg-structure.go
+++ /dev/null
@@ -1,348 +0,0 @@
-package acpkg
-
-import (
- "git-auto-commit/types"
- "regexp"
- "strings"
-)
-
-func parseStruct(line, lang string) *types.StructureSignature {
- var structRegex *regexp.Regexp
-
- switch lang {
- case "go":
- structRegex = regexp.MustCompile(`type\s+(\w+)\s+struct\s*{`)
- case "csharp":
- structRegex = regexp.MustCompile(`struct\s+(\w+)\s*{`)
- case "c", "cpp":
- structRegex = regexp.MustCompile(`struct\s+(\w+)\s*{`)
- case "typescript":
- structRegex = regexp.MustCompile(`interface\s+(\w+)\s*{`)
- default:
- return nil
- }
-
- m := structRegex.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- return &types.StructureSignature{Name: m[1]}
-}
-
-func parseType(line, lang string) *types.TypeSignature {
- var typeRegex *regexp.Regexp
- switch lang {
- case "go":
- typeRegex = regexp.MustCompile(`type\s+(\w+)\s+`)
- case "typescript":
- typeRegex = regexp.MustCompile(`type\s+(\w+)\s*=`)
- case "csharp":
- typeRegex = regexp.MustCompile(`using\s+(\w+)\s*=`)
- default:
- return nil
- }
-
- m := typeRegex.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- return &types.TypeSignature{Name: m[1]}
-}
-
-func parseInterface(line, lang string) *types.InterfaceSignature {
- var interfaceRegex *regexp.Regexp
- switch lang {
- case "go":
- interfaceRegex = regexp.MustCompile(`type\s+(\w+)\s+interface\s*{`)
- case "typescript", "java", "csharp":
- interfaceRegex = regexp.MustCompile(`interface\s+(\w+)\s*{`)
- default:
- return nil
- }
-
- m := interfaceRegex.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- return &types.InterfaceSignature{Name: m[1]}
-}
-
-func parseEnum(line, lang string) *types.EnumSignature {
- var enumRegex *regexp.Regexp
- switch lang {
- case "typescript", "java", "csharp", "cpp", "c":
- enumRegex = regexp.MustCompile(`enum\s+(\w+)\s*{`)
- default:
- return nil
- }
-
- m := enumRegex.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- return &types.EnumSignature{Name: m[1]}
-}
-
-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")
- for _, line := range lines {
- if strings.HasPrefix(line, "-") {
- oldLines = append(oldLines, line[1:])
- } else if strings.HasPrefix(line, "+") {
- newLines = append(newLines, line[1:])
- }
- }
-
- oldStruct = parseStruct(strings.Join(oldLines, "\n"), lang)
- newStruct = parseStruct(strings.Join(newLines, "\n"), lang)
-
- if oldStruct != nil && newStruct == nil {
- deletedStruct = append(deletedStruct, oldStruct.Name)
- }
-
- if oldStruct == nil && newStruct != nil {
- addedStruct = append(addedStruct, newStruct.Name)
- }
-
- if oldStruct != nil && newStruct != nil && 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 ""
-}
-
-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")
- for _, line := range lines {
- if strings.HasPrefix(line, "-") {
- oldLines = append(oldLines, line[1:])
- } else if strings.HasPrefix(line, "+") {
- newLines = append(newLines, line[1:])
- }
- }
-
- oldType = parseType(strings.Join(oldLines, "\n"), lang)
- newType = parseType(strings.Join(newLines, "\n"), lang)
-
- if oldType != nil && newType == nil {
- deletedType = append(deletedType, oldType.Name)
- }
-
- if oldType == nil && newType != nil {
- addedType = append(addedType, newType.Name)
- }
-
- if oldType != nil && newType != nil && 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 ""
-}
-
-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")
- for _, line := range lines {
- if strings.HasPrefix(line, "-") {
- oldLines = append(oldLines, line[1:])
- } else if strings.HasPrefix(line, "+") {
- newLines = append(newLines, line[1:])
- }
- }
-
- oldInterface = parseInterface(strings.Join(oldLines, "\n"), lang)
- newInterface = parseInterface(strings.Join(newLines, "\n"), lang)
-
- if oldInterface != nil && newInterface == nil {
- deletedInterface = append(deletedInterface, oldInterface.Name)
- }
-
- if oldInterface == nil && newInterface != nil {
- addedInterface = append(addedInterface, newInterface.Name)
- }
-
- if oldInterface != nil && newInterface != nil && 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 ""
-}
-
-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")
- for _, line := range lines {
- if strings.HasPrefix(line, "-") {
- oldLines = append(oldLines, line[1:])
- } else if strings.HasPrefix(line, "+") {
- newLines = append(newLines, line[1:])
- }
- }
-
- oldEnum = parseEnum(strings.Join(oldLines, "\n"), lang)
- newEnum = parseEnum(strings.Join(newLines, "\n"), lang)
-
- if oldEnum != nil && newEnum == nil {
- deletedEnum = append(deletedEnum, oldEnum.Name)
- }
-
- if oldEnum == nil && newEnum != nil {
- addedEnum = append(addedEnum, newEnum.Name)
- }
-
- if oldEnum != nil && newEnum != nil && 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/acpkg/acpkg-variables.go b/acpkg/acpkg-variables.go
deleted file mode 100644
index 46e9d04..0000000
--- a/acpkg/acpkg-variables.go
+++ /dev/null
@@ -1,143 +0,0 @@
-package acpkg
-
-import (
- "git-auto-commit/constants"
- "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":
- m := varRegexPython.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- return &types.VariableSignature{Type: "", Name: m[1], Value: strings.TrimSpace(m[2])}
- case "typescript", "javascript":
- m := varRegexTSJS.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- typ := ""
-
- if len(m) > 4 {
- typ = m[4]
- }
-
- return &types.VariableSignature{Type: typ, Name: m[2], Value: strings.TrimSpace(m[5])}
- case "go":
- 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 {
- 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:
- m := defaultVarRegex.FindStringSubmatch(line)
- if m == nil {
- return nil
- }
-
- return &types.VariableSignature{Type: m[1], Name: m[2], Value: strings.TrimSpace(m[3])}
- }
-}
-
-func FormattedVariables(diff, lang string) string {
- var addedVars, renamedVars, changedTypes, changedValues []string
- var oldVar, newVar *types.VariableSignature
-
- lines := strings.Split(diff, "\n")
- for _, line := range lines {
- if strings.HasPrefix(line, "-") {
- oldVar = ParseToStructureVariable(line[1:], lang)
- } else if strings.HasPrefix(line, "+") {
- newVar = ParseToStructureVariable(line[1:], lang)
- }
-
- if oldVar != nil && newVar != nil {
- if oldVar.Name == newVar.Name && 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 {
- renamedVars = append(renamedVars, oldVar.Name+" -> "+newVar.Name)
- }
-
- if oldVar.Name == newVar.Name && oldVar.Type == newVar.Type && oldVar.Value != newVar.Value {
- changedValues = append(changedValues, oldVar.Name)
- }
-
- oldVar, newVar = nil, nil
- } else if newVar != nil && oldVar == nil {
- addedVars = append(addedVars, newVar.Name)
- newVar = nil
- }
- }
-
- 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 ""
- }
-
- parser := strings.Join(results, " | ")
- for len(parser) > int(constants.MAX_COMMIT_LENGTH) && len(results) > 1 {
- results = results[:len(results)-1]
- parser = strings.Join(results, " | ")
- }
-
- if len(parser) > int(constants.MAX_COMMIT_LENGTH) && len(results) == 1 {
- parser = parser[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- return parser
-}
diff --git a/main.go b/cmd/main.go
similarity index 56%
rename from main.go
rename to cmd/main.go
index 0db4f56..7c91af7 100644
--- a/main.go
+++ b/cmd/main.go
@@ -2,16 +2,22 @@ package main
import (
"fmt"
- "git-auto-commit/ac"
- "git-auto-commit/achelper"
- "git-auto-commit/achelper/logger"
- "git-auto-commit/git"
+ "git-auto-commit/infra/logger"
+ "git-auto-commit/pkg/cli"
+ "git-auto-commit/pkg/code"
+ "git-auto-commit/pkg/git"
+ "git-auto-commit/pkg/parser"
"os"
)
func main() {
+ cli := &cli.CLI{
+ Git: &git.Git{},
+ Parser: &parser.Parser{Code: &code.Code{}},
+ }
+
if len(os.Args) > 1 && (os.Args[1] == "-w" || os.Args[1] == "--watch") {
- path, err := git.GetGitRoot()
+ path, err := cli.Git.GetGitRoot()
if err != nil {
logger.ErrorLogger(err)
return
@@ -21,12 +27,12 @@ func main() {
path = fmt.Sprintf("%s/%s", path, os.Args[2])
}
- achelper.WatchCommit(path)
+ cli.Watch(path)
} else if len(os.Args) > 1 && (os.Args[1] == "-v" || os.Args[1] == "--version") {
- achelper.GetVersion(true)
+ cli.GetVersion(true)
} else if len(os.Args) > 1 && (os.Args[1] == "-u" || os.Args[1] == "--update") {
- achelper.AutoCommitUpdate()
+ cli.Update()
} else {
- ac.AutoCommit()
+ cli.AutoCommit()
}
}
diff --git a/constants/define.go b/constants/define.go
deleted file mode 100644
index ec6ec58..0000000
--- a/constants/define.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package constants
-
-import "time"
-
-const (
- MAX_LINE_LENGTH uint16 = 1024
- MAX_COMMIT_LENGTH uint16 = 300
- MAX_COMMIT_LENGTH_WATCHER uint16 = 25
- COMMIT_TIME time.Duration = 15 * time.Second
-
- GITHUB_API_REPO_URL string = "https://api.github.com/repos/thefuture-industries/git-auto-commit"
- VERSION_FILE string = "auto-commit.version.txt"
- BINARY_AUTO_COMMIT string = "auto-commit"
- GITHUB_REPO_URL string = "https://github.com/thefuture-industries/git-auto-commit"
-)
diff --git a/diff/diff.go b/diff/diff.go
deleted file mode 100644
index c5fcec1..0000000
--- a/diff/diff.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package diff
-
-import (
- "bufio"
- "bytes"
- "os/exec"
- "strings"
- "sync"
-
- "git-auto-commit/git"
-)
-
-var diffBufferPool = sync.Pool{
- New: func() interface{} {
- return new(bytes.Buffer)
- },
-}
-
-var GetDiff = func(file string) (string, error) {
- var builder strings.Builder
- builder.Reset()
-
- root, err := git.GetGitRoot()
- if err != nil {
- return "", err
- }
-
- 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 = buf
- if err := cmd.Run(); err != nil {
- return "", err
- }
-
- return buf.String(), nil
-}
-
-var GetStagedFiles = func() ([]string, error) {
- cmd := exec.Command("git", "diff", "--cached", "--name-only")
-
- stdout, err := cmd.StdoutPipe()
- if err != nil {
- return nil, err
- }
-
- if err := cmd.Start(); err != nil {
- return nil, err
- }
-
- var files []string
- scanner := bufio.NewScanner(stdout)
- for scanner.Scan() {
- files = append(files, scanner.Text())
- }
-
- if err := scanner.Err(); err != nil {
- return nil, err
- }
-
- if err := cmd.Wait(); err != nil {
- return nil, err
- }
-
- return files, nil
-}
diff --git a/go.mod b/go.mod
index 5024f47..33b4807 100644
--- a/go.mod
+++ b/go.mod
@@ -1,11 +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
-)
+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
index 516f010..8687ec0 100644
--- a/go.sum
+++ b/go.sum
@@ -1,16 +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=
+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/infra/constants/auto-commit.go b/infra/constants/auto-commit.go
new file mode 100644
index 0000000..8d6606e
--- /dev/null
+++ b/infra/constants/auto-commit.go
@@ -0,0 +1,10 @@
+package constants
+
+import "time"
+
+const (
+ MAX_LINE_LENGTH uint16 = 1024
+ MAX_COMMIT_LENGTH uint16 = 300
+ MAX_COMMIT_LENGTH_WATCHER uint16 = 25
+ COMMIT_TIME time.Duration = 15 * time.Second
+)
diff --git a/infra/constants/commit-type.go b/infra/constants/commit-type.go
new file mode 100644
index 0000000..2c70560
--- /dev/null
+++ b/infra/constants/commit-type.go
@@ -0,0 +1,16 @@
+package constants
+
+const (
+ Type_CommitFeat = "[feat]"
+ Type_CommitFix = "[fix]"
+ Type_CommitStyle = "[style]"
+ Type_CommitDocs = "[docs]"
+ Type_CommitTest = "[test]"
+ Type_CommitRefactor = "[refactor]"
+)
+
+const (
+ Ch_TypeAdd = "added"
+ Ch_TypeDelete = "deleted"
+ Ch_TypeChanged = "changed"
+)
diff --git a/infra/constants/expanding-notation-folders.go b/infra/constants/expanding-notation-folders.go
new file mode 100644
index 0000000..771c917
--- /dev/null
+++ b/infra/constants/expanding-notation-folders.go
@@ -0,0 +1,108 @@
+package constants
+
+var EXPANDING_NOTATION_FOLDERS = map[string]string{
+ "user": "user management",
+ "legacy": "legacy code",
+ "db": "database layer",
+ "tests": "test suite",
+ "payment": "payment system",
+ "api": "API definitions", // OpenAPI/Swagger specs:contentReference[oaicite:0]{index=0}
+ "auth": "authentication module",
+ "assets": "static assets", // project assets (images, etc.):contentReference[oaicite:1]{index=1}
+ "app": "application code",
+ "bin": "executable scripts",
+ "build": "compiled outputs", // compiled files:contentReference[oaicite:2]{index=2}
+ "cmd": "command-line tools", // main applications:contentReference[oaicite:3]{index=3}
+ "client": "client-side code",
+ "common": "common code",
+ "config": "configuration files", // config templates:contentReference[oaicite:4]{index=4}
+ "controllers": "controller logic", // handles requests:contentReference[oaicite:5]{index=5}
+ "core": "core functionality",
+ "data": "data files",
+ "dist": "distribution packages", // compiled/distribution files:contentReference[oaicite:6]{index=6}
+ "docs": "documentation files", // reference docs:contentReference[oaicite:7]{index=7}
+ "examples": "example applications", // sample code:contentReference[oaicite:8]{index=8}
+ "handlers": "request handlers",
+ "helpers": "helper functions",
+ "internal": "internal packages", // private code:contentReference[oaicite:9]{index=9}
+ "lib": "library code", // reusable libraries:contentReference[oaicite:10]{index=10}
+ "log": "log files",
+ "middleware": "middleware components",
+ "models": "data models", // data schemas:contentReference[oaicite:11]{index=11}
+ "public": "public assets", // static files for web:contentReference[oaicite:12]{index=12}
+ "resources": "resource files",
+ "routes": "route handlers", // API endpoints:contentReference[oaicite:13]{index=13}
+ "scripts": "build scripts", // automation scripts:contentReference[oaicite:14]{index=14}
+ "services": "service layer",
+ "shared": "shared code",
+ "src": "source code files", // main source directory:contentReference[oaicite:15]{index=15}
+ "test": "test suite", // automated tests:contentReference[oaicite:16]{index=16}
+ "tools": "utility tools", // development tools:contentReference[oaicite:17]{index=17}
+ "vendor": "vendor libraries", // third-party dependencies:contentReference[oaicite:18]{index=18}
+ "views": "view templates", // HTML/UI templates:contentReference[oaicite:19]{index=19}
+ "tmp": "temporary files",
+ "pkg": "public reusable packages",
+ "third_party": "third-party source code",
+ "external": "external dependencies",
+ "fixtures": "test fixtures and mock data",
+ "mocks": "mock implementations for testing",
+ "stubs": "stub implementations",
+ "schemas": "database or API schemas",
+ "sql": "SQL migration files",
+ "migrations": "database migration scripts",
+ "seeds": "database seed data",
+ "proto": "Protobuf definitions",
+ "grpc": "gRPC service definitions and stubs",
+ "integration": "integration tests",
+ "functional": "functional tests",
+ "e2e": "end-to-end tests",
+ "ui": "user interface components",
+ "frontend": "frontend source code",
+ "backend": "backend source code",
+ "ops": "operations scripts",
+ "infra": "infrastructure as code",
+ "ci": "continuous integration configs",
+ "cd": "continuous deployment configs",
+ "deployment": "deployment scripts and configs",
+ "k8s": "Kubernetes manifests",
+ "helm": "Helm charts",
+ "ansible": "Ansible playbooks",
+ "terraform": "Terraform configs",
+ "docker": "Dockerfiles and related configs",
+ "monitoring": "monitoring configuration and scripts",
+ "logging": "logging configuration",
+ "analytics": "analytics scripts or configs",
+ "locales": "localization and translation files",
+ "i18n": "internationalization files",
+ "l10n": "localization files",
+ "themes": "UI themes and styles",
+ "styles": "CSS/SCSS style files",
+ "fonts": "font files",
+ "images": "image resources",
+ "audio": "audio resources",
+ "video": "video resources",
+ "reports": "generated reports",
+ "notebooks": "Jupyter or data science notebooks",
+ "research": "research documents or code",
+ "sandbox": "experimental code",
+ "playground": "scratch code for testing ideas",
+ "archive": "archived old code",
+ "deprecated": "deprecated code",
+ ".github": "GitHub configuration files",
+ ".husky": "Git hooks managed by Husky",
+ ".vscode": "VSCode editor settings",
+ ".idea": "JetBrains IDE configuration",
+ ".config": "User or app configuration files",
+ ".docker": "Docker configuration files",
+ ".circleci": "CircleCI configuration files",
+ ".gitlab-ci": "GitLab CI/CD configuration files",
+ ".github_actions": "GitHub Actions workflows",
+ ".terraform": "Terraform state and configs",
+ ".npm": "npm package configs and cache",
+ ".cache": "Cache files",
+ ".env": "Environment variable files",
+ ".eslint": "ESLint configuration files",
+ ".prettier": "Prettier configuration files",
+ ".stylelint": "Stylelint configuration files",
+ ".scripts": "Custom shell or utility scripts",
+}
diff --git a/infra/constants/github.go b/infra/constants/github.go
new file mode 100644
index 0000000..74595fe
--- /dev/null
+++ b/infra/constants/github.go
@@ -0,0 +1,11 @@
+package constants
+
+const (
+ GITHUB_API_REPO_URL string = "https://api.github.com/repos/thefuture-industries/git-auto-commit"
+ VERSION_FILE string = "auto-commit.version.txt"
+ BINARY_AUTO_COMMIT string = "auto-commit"
+ GITHUB_REPO_URL string = "https://github.com/thefuture-industries/git-auto-commit"
+ GITHUB_SCRIPT_AUTOCOMMIT_UPDATE_LINUX string = "update-linux-auto-commit.sh"
+ GITHUB_SCRIPT_AUTOCOMMIT_UPDATE_MACOS string = "update-macos-auto-commit.sh"
+ GITHUB_SCRIPT_AUTOCOMMIT_UPDATE_WIN string = "update-windows-auto-commit.ps1"
+)
diff --git a/infra/constants/name-status.go b/infra/constants/name-status.go
new file mode 100644
index 0000000..49a87da
--- /dev/null
+++ b/infra/constants/name-status.go
@@ -0,0 +1,8 @@
+package constants
+
+const (
+ NameStatus_Added = "A"
+ NameStatus_Modified = "M"
+ NameStatus_Deleted = "D"
+ NameStatus_Renamed = "R"
+)
diff --git a/infra/constants/strings.go b/infra/constants/strings.go
new file mode 100644
index 0000000..f62b9f0
--- /dev/null
+++ b/infra/constants/strings.go
@@ -0,0 +1,13 @@
+package constants
+
+const (
+ Commit_Docs = "Performed comprehensive updates and revisions to the documentation"
+ Commit_Style = "Applied style improvements and formatting fixes"
+ Commit_Test = "Implemented and refined test cases to ensure code quality"
+)
+
+var Ratio_Commit = map[string]string{
+ Type_CommitStyle: Commit_Style,
+ Type_CommitDocs: Commit_Docs,
+ Type_CommitTest: Commit_Test,
+}
diff --git a/infra/gtypes/types.go b/infra/gtypes/types.go
new file mode 100644
index 0000000..79625c3
--- /dev/null
+++ b/infra/gtypes/types.go
@@ -0,0 +1 @@
+package gtypes
diff --git a/infra/logger/logger.go b/infra/logger/logger.go
new file mode 100644
index 0000000..141fd5c
--- /dev/null
+++ b/infra/logger/logger.go
@@ -0,0 +1,48 @@
+package logger
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+var logFile *os.File
+
+func init() {
+ tmpDir := os.TempDir()
+ logPath := filepath.Join(tmpDir, "autocommit.log")
+
+ var err error
+ logFile, err = os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+ if err != nil {
+ return
+ }
+}
+
+func logMessage(prefix, msg, color string) {
+ var builder strings.Builder
+ builder.WriteString(color)
+ builder.WriteString("[git auto-commit] ")
+ builder.WriteString(msg)
+ builder.WriteString("\033[0m\n")
+
+ fmt.Print(builder.String())
+
+ if logFile != nil {
+ fileMsg := fmt.Sprintf("[git auto-commit] %s\n", msg)
+ logFile.WriteString(fileMsg)
+ }
+}
+
+var InfoLogger = func(msg string) {
+ logMessage("", msg, "")
+}
+
+var GitLogger = func(msg string) {
+ logMessage("", msg, "\033[0;34m")
+}
+
+var ErrorLogger = func(err error) {
+ logMessage("", err.Error(), "\033[0;31m")
+}
diff --git a/parser/parser.go b/parser/parser.go
deleted file mode 100644
index d53ca52..0000000
--- a/parser/parser.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package parser
-
-import (
- "fmt"
- "git-auto-commit/achelper/code"
- "git-auto-commit/acpkg"
- "git-auto-commit/constants"
- "git-auto-commit/diff"
- "path/filepath"
- "strings"
- "sync"
-)
-
-func AppendMsg(commitMsg, addition string) string {
- var builder strings.Builder
- builder.Reset()
-
- if len(commitMsg) == 0 {
- return addition
- }
-
- builder.WriteString(commitMsg)
- builder.WriteString(" | ")
- builder.WriteString(addition)
- return builder.String()
-}
-
-var Parser = func(files []string) (string, error) {
- 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(payloadMsg)) > constants.MAX_COMMIT_LENGTH {
- mu.Unlock()
- continue
- }
- mu.Unlock()
-
- diff, err := diff.GetDiff(file)
- if err != nil {
- errChan <- fmt.Errorf("error getting diff for %s: %w", file, err)
- continue
- }
-
- lang := code.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{
- acpkg.FormattedVariables(diff, lang),
- acpkg.FormattedFunction(diff, lang),
- acpkg.FormattedClass(diff, lang),
- acpkg.FormattedLogic(diff, lang, filepath.Base(file)),
- acpkg.FormattedImport(diff, lang, filepath.Base(file)),
- acpkg.FormattedStruct(diff, lang),
- acpkg.FormattedType(diff, lang),
- acpkg.FormattedInterface(diff, lang),
- acpkg.FormattedEnum(diff, lang),
- } {
- if formatted != "" {
- fileChanges = append(fileChanges, formatted)
- } // else -> continue
- }
-
- if len(fileChanges) > 0 {
- mu.Lock()
- for _, change := range fileChanges {
- nextMsg := AppendMsg(payloadMsg, change)
- if len(nextMsg) > int(constants.MAX_COMMIT_LENGTH) {
- if len(payloadMsg) == 0 {
- if len(change) > int(constants.MAX_COMMIT_LENGTH) {
- change = change[:int(constants.MAX_COMMIT_LENGTH)]
- }
-
- payloadMsg = change
- }
-
- break
- }
-
- payloadMsg = nextMsg
- }
- mu.Unlock()
- }
- }
- }()
- }
-
- for _, file := range files {
- jobs <- file
- }
- close(jobs)
-
- wg.Wait()
- close(errChan)
-
- for err := range errChan {
- if err != nil {
- return "", err
- }
- }
-
- if len(payloadMsg) == 0 {
- formattedByRemote, err := acpkg.FormattedByRemote("")
- if err != nil {
- return "", err
- }
-
- formattedByBranch, err := acpkg.FormattedByBranch()
- if err != nil {
- return "", err
- }
-
- if formattedByRemote != "" {
- payloadMsg = AppendMsg(payloadMsg, formattedByRemote)
- } else {
- payloadMsg = AppendMsg(payloadMsg, formattedByBranch)
- }
- }
-
- return payloadMsg, nil
-}
diff --git a/pkg/cli/commit.go b/pkg/cli/commit.go
new file mode 100644
index 0000000..36b2adb
--- /dev/null
+++ b/pkg/cli/commit.go
@@ -0,0 +1,30 @@
+package cli
+
+import (
+ "git-auto-commit/infra/logger"
+ "git-auto-commit/pkg/pkgerror"
+)
+
+func (cli *CLI) AutoCommit() {
+ cli.GetVersion(false)
+
+ directory, err := cli.Git.GetStagedCountDirectory()
+ if err != nil {
+ logger.ErrorLogger(pkgerror.Err_FailedToGetDiff)
+ return
+ }
+
+ if directory == "" {
+ logger.InfoLogger(pkgerror.Err_NoStagedFiles.Error())
+ return
+ }
+
+ parserMsg, err := cli.Parser.ParserIndex(directory)
+ if err != nil {
+ return
+ }
+
+ if err := cli.Git.Commit(parserMsg); err != nil {
+ return
+ }
+}
diff --git a/pkg/cli/types.go b/pkg/cli/types.go
new file mode 100644
index 0000000..378ac75
--- /dev/null
+++ b/pkg/cli/types.go
@@ -0,0 +1,11 @@
+package cli
+
+import (
+ "git-auto-commit/pkg/git"
+ "git-auto-commit/pkg/parser"
+)
+
+type CLI struct {
+ Git git.GitInterface
+ Parser parser.ParserInterface
+}
diff --git a/achelper/update.go b/pkg/cli/update.go
similarity index 70%
rename from achelper/update.go
rename to pkg/cli/update.go
index 90074fd..d1c377e 100644
--- a/achelper/update.go
+++ b/pkg/cli/update.go
@@ -1,12 +1,11 @@
-package achelper
+package cli
import (
"fmt"
- "git-auto-commit/achelper/logger"
"git-auto-commit/config"
- "git-auto-commit/constants"
- "git-auto-commit/git"
- "io"
+ "git-auto-commit/infra/constants"
+ "git-auto-commit/infra/logger"
+ "git-auto-commit/pkg/file"
"net/http"
"os"
"os/exec"
@@ -15,8 +14,8 @@ import (
"strings"
)
-func AutoCommitUpdate() {
- root, err := git.GetGitRoot()
+func (cli *CLI) Update() {
+ root, err := cli.Git.GetGitRoot()
if err != nil {
logger.ErrorLogger(err)
return
@@ -54,16 +53,22 @@ func AutoCommitUpdate() {
var scriptUpdate string
var scriptUpdateExt string
- if runtime.GOOS == "windows" {
- scriptUpdate = "https://github.com/thefuture-industries/git-auto-commit/raw/main/scripts/update-windows-auto-commit.ps1"
+
+ switch runtime.GOOS {
+ case "windows":
+ scriptUpdate = fmt.Sprintf("%s/raw/main/scripts/%s", constants.GITHUB_REPO_URL, constants.GITHUB_SCRIPT_AUTOCOMMIT_UPDATE_WIN)
scriptUpdateExt = ".ps1"
- } else {
- scriptUpdate = "https://github.com/thefuture-industries/git-auto-commit/raw/main/scripts/update-linux-auto-commit.sh"
+ case "darwin":
+ scriptUpdate = fmt.Sprintf("%s/raw/main/scripts/%s", constants.GITHUB_REPO_URL, constants.GITHUB_SCRIPT_AUTOCOMMIT_UPDATE_MACOS)
+ scriptUpdateExt = ".sh"
+ default:
+ scriptUpdate = fmt.Sprintf("%s/raw/main/scripts/%s", constants.GITHUB_REPO_URL, constants.GITHUB_SCRIPT_AUTOCOMMIT_UPDATE_LINUX)
scriptUpdateExt = ".sh"
+
}
tmpFile := filepath.Join(os.TempDir(), "auto-commit-update"+scriptUpdateExt)
- err = downloadFile(scriptUpdate, tmpFile)
+ err = file.DownloadFile(scriptUpdate, tmpFile)
if err != nil {
logger.ErrorLogger(fmt.Errorf("failed to download update script: %v", err))
return
@@ -85,20 +90,3 @@ func AutoCommitUpdate() {
return
}
}
-
-func downloadFile(url, filepath string) error {
- resp, err := http.Get(url)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
-
- out, err := os.Create(filepath)
- if err != nil {
- return err
- }
- defer out.Close()
-
- _, err = io.Copy(out, resp.Body)
- return err
-}
diff --git a/achelper/version.go b/pkg/cli/version.go
similarity index 87%
rename from achelper/version.go
rename to pkg/cli/version.go
index 9c87b59..23c7f4a 100644
--- a/achelper/version.go
+++ b/pkg/cli/version.go
@@ -1,19 +1,18 @@
-package achelper
+package cli
import (
"fmt"
- "git-auto-commit/achelper/logger"
"git-auto-commit/config"
- "git-auto-commit/constants"
- "git-auto-commit/git"
+ "git-auto-commit/infra/constants"
+ "git-auto-commit/infra/logger"
"net/http"
"os"
"path/filepath"
"strings"
)
-var GetVersion = func(isCurrent bool) {
- root, err := git.GetGitRoot()
+func (cli *CLI) GetVersion(isCurrent bool) {
+ root, err := cli.Git.GetGitRoot()
if err != nil {
logger.ErrorLogger(fmt.Errorf("could not get git root: %w", err))
return
diff --git a/achelper/watcher.go b/pkg/cli/watcher.go
similarity index 77%
rename from achelper/watcher.go
rename to pkg/cli/watcher.go
index b7dbd51..83528a2 100644
--- a/achelper/watcher.go
+++ b/pkg/cli/watcher.go
@@ -1,12 +1,9 @@
-package achelper
+package cli
import (
- "fmt"
- "git-auto-commit/achelper/logger"
- "git-auto-commit/constants"
- "git-auto-commit/diff"
- "git-auto-commit/git"
- "git-auto-commit/parser"
+ "errors"
+ "git-auto-commit/infra/constants"
+ "git-auto-commit/infra/logger"
"os"
"os/exec"
"os/signal"
@@ -18,8 +15,8 @@ import (
"github.com/fsnotify/fsnotify"
)
-func WatchCommit(path string) {
- GetVersion(false)
+func (cli *CLI) Watch(path string) {
+ cli.GetVersion(false)
watcher, err := fsnotify.NewWatcher()
if err != nil {
@@ -70,24 +67,25 @@ func WatchCommit(path string) {
return
}
- files, err := diff.GetStagedFiles()
+ directory, err := cli.Git.GetStagedCountDirectory()
if err != nil {
- logger.ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error()))
+ logger.ErrorLogger(errors.New("error getting staged files"))
return
}
- if len(files) == 0 {
+ if directory == "" {
logger.InfoLogger("No files staged for commit.")
+ return
}
- parser, err := parser.Parser(files)
+ parser, err := cli.Parser.ParserIndex(directory)
if err != nil {
logger.ErrorLogger(err)
return
}
if uint16(len(parser)) >= constants.MAX_COMMIT_LENGTH_WATCHER {
- if err := git.Commit(parser); err != nil {
+ if err := cli.Git.Commit(parser); err != nil {
logger.ErrorLogger(err)
}
}
diff --git a/pkg/code/code.go b/pkg/code/code.go
new file mode 100644
index 0000000..84db121
--- /dev/null
+++ b/pkg/code/code.go
@@ -0,0 +1,119 @@
+package code
+
+import (
+ "bufio"
+ "git-auto-commit/infra/constants"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+var ExecCommand = exec.Command
+
+func (c *Code) FormattedCode(files []string) (string, error) {
+ args := append([]string{"diff", "--cached", "--name-status"}, files...)
+ cmd := ExecCommand("git", args...)
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return "", err
+ }
+
+ if err := cmd.Start(); err != nil {
+ return "", err
+ }
+
+ var added, modified, deleted []string
+
+ scanner := bufio.NewScanner(stdout)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" {
+ continue
+ }
+
+ parts := strings.Fields(line)
+ if len(parts) != 2 {
+ continue
+ }
+
+ status, file := parts[0], parts[1]
+ switch status {
+ case constants.NameStatus_Added:
+ added = append(added, file)
+
+ case constants.NameStatus_Modified:
+ modified = append(modified, file)
+
+ case constants.NameStatus_Deleted:
+ deleted = append(deleted, file)
+
+ }
+ }
+
+ if err := scanner.Err(); err != nil {
+ return "", err
+ }
+
+ if err := cmd.Wait(); err != nil {
+ return "", err
+ }
+
+ msg := c.build(added, modified, deleted)
+ return c.WithTag(files, msg, added, modified, deleted), nil
+}
+
+func (c *Code) build(added, modified, deleted []string) string {
+ var parts []string
+
+ if len(added) > 0 {
+ parts = append(parts, "implemented "+c.summarize(added))
+ }
+
+ if len(modified) > 0 {
+ parts = append(parts, "updated "+c.summarize(modified))
+ }
+
+ if len(deleted) > 0 {
+ parts = append(parts, "removed "+c.summarize(deleted))
+ }
+
+ msg := strings.Join(parts, ", ")
+ if len(msg) > 0 {
+ msg = strings.ToUpper(msg[:1]) + msg[1:]
+ }
+
+ return msg
+}
+
+func (c *Code) summarize(files []string) string {
+ folders := map[string]struct{}{}
+ for _, file := range files {
+ directory := strings.Split(filepath.ToSlash(file), "/")[0]
+
+ if directory == "." || directory == "" {
+ directory = strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
+ }
+
+ folders[directory] = struct{}{}
+ }
+
+ names := make([]string, 0, len(folders))
+ for name := range folders {
+ if desc, ok := constants.EXPANDING_NOTATION_FOLDERS[name]; ok {
+ names = append(names, desc)
+ } else {
+ names = append(names, name)
+ }
+ }
+
+ if len(names) == 1 {
+ return names[0]
+ }
+
+ if len(names) == 2 {
+ return names[0] + " and " + names[1]
+ }
+
+ return strings.Join(names[:len(names)-1], ", ") + " and " + names[len(names)-1]
+}
diff --git a/pkg/code/comment.go b/pkg/code/comment.go
new file mode 100644
index 0000000..e85e253
--- /dev/null
+++ b/pkg/code/comment.go
@@ -0,0 +1 @@
+package code
diff --git a/acpkg/acpkg-remote.go b/pkg/code/remote.go
similarity index 63%
rename from acpkg/acpkg-remote.go
rename to pkg/code/remote.go
index f481fac..dd3d36b 100644
--- a/acpkg/acpkg-remote.go
+++ b/pkg/code/remote.go
@@ -1,31 +1,30 @@
-package acpkg
+package code
import (
- "git-auto-commit/git"
"strconv"
"strings"
)
-func FormattedByRemote(token string) (string, error) {
+func (c *Code) FormattedByRemote(token string) (string, error) {
var builder strings.Builder
builder.Reset()
- branch, err := git.GetCurrentBranch()
+ branch, err := c.Git.GetCurrentBranch()
if err != nil {
return "", err
}
- issue := git.ExtractIssueNumber(branch)
+ issue := c.Git.ExtractIssueNumber(branch)
if issue == "" {
return "", nil
}
- owner, repo, err := git.GetOwnerRepository()
+ owner, repo, err := c.Git.GetOwnerRepository()
if err != nil {
return "", err
}
- issueName, issueNumber, err := git.GetIssueData(owner, repo, issue, token)
+ issueName, issueNumber, err := c.Git.GetIssueData(owner, repo, issue, token)
if err != nil {
return "", err
}
@@ -38,11 +37,11 @@ func FormattedByRemote(token string) (string, error) {
return builder.String(), nil
}
-func FormattedByBranch() (string, error) {
+func (c *Code) FormattedByBranch() (string, error) {
var builder strings.Builder
builder.Reset()
- branch, err := git.GetCurrentBranch()
+ branch, err := c.Git.GetCurrentBranch()
if err != nil {
return "", err
}
diff --git a/pkg/code/tag.go b/pkg/code/tag.go
new file mode 100644
index 0000000..5f1442c
--- /dev/null
+++ b/pkg/code/tag.go
@@ -0,0 +1,46 @@
+package code
+
+import (
+ "git-auto-commit/infra/constants"
+ "git-auto-commit/pkg/commit"
+ "path/filepath"
+)
+
+func (c *Code) WithTag(files []string, formatted string, added, modified, deleted []string) string {
+ // check .ext and max count
+ extCount := map[string]int{}
+ maxFile := ""
+ maxExtCount := 0
+
+ for _, file := range files {
+ ext := filepath.Ext(file)
+ extCount[ext]++
+
+ if extCount[ext] > maxExtCount {
+ maxExtCount = extCount[ext]
+ maxFile = file
+ }
+ }
+
+ ptag := commit.DetectTagByFile(&maxFile, "")
+ if ptag != "" {
+ return commit.CreateAutoCommitMsg(&maxFile, &formatted, "")
+ }
+
+ statusCount := map[string]int{
+ constants.NameStatus_Added: len(added),
+ constants.NameStatus_Modified: len(modified),
+ constants.NameStatus_Deleted: len(deleted),
+ }
+
+ maxStatus := ""
+ maxCount := 0
+ for status, count := range statusCount {
+ if count > maxCount {
+ maxCount = count
+ maxStatus = status
+ }
+ }
+
+ return commit.CreateAutoCommitMsg(&maxFile, &formatted, maxStatus)
+}
diff --git a/types/types.go b/pkg/code/types.go
similarity index 67%
rename from types/types.go
rename to pkg/code/types.go
index 18a19a5..dd203a7 100644
--- a/types/types.go
+++ b/pkg/code/types.go
@@ -1,9 +1,22 @@
-package types
+package code
-type VariableSignature struct {
- Type string
- Name string
- Value string
+import (
+ "git-auto-commit/pkg/git"
+)
+
+type Code struct {
+ Git git.GitInterface
+}
+
+type CodeInterface interface {
+ // code.go
+ FormattedCode(files []string) (string, error)
+
+ // comment.go
+
+ // remote.go
+ FormattedByRemote(token string) (string, error)
+ FormattedByBranch() (string, error)
}
type FunctionSignature struct {
@@ -17,17 +30,6 @@ type FunctionParameters struct {
Type string
}
-type ClassSignature struct {
- Name string
- Parent string
- Methods map[string]string
-}
-
-type SwitchSignature struct {
- Expr string
- Cases []string
-}
-
type StructureSignature struct {
Name string
}
@@ -46,7 +48,19 @@ type InterfaceSignature struct {
Methods []string
}
-type GithubIssue struct {
- Title string `json:"title"`
- Number uint32 `json:"number"`
+type VariableSignature struct {
+ Type string
+ Name string
+ Value string
+}
+
+type ClassSignature struct {
+ Name string
+ Parent string
+ Methods map[string]string
+}
+
+type SwitchSignature struct {
+ Expr string
+ Cases []string
}
diff --git a/pkg/commit/create-commit-msg.go b/pkg/commit/create-commit-msg.go
new file mode 100644
index 0000000..4baa48a
--- /dev/null
+++ b/pkg/commit/create-commit-msg.go
@@ -0,0 +1,26 @@
+package commit
+
+import (
+ "fmt"
+ "git-auto-commit/infra/constants"
+ "strings"
+)
+
+func CreateAutoCommitMsg(filename, msg *string, tag string) string {
+ ext := DetectTagByFile(filename, tag)
+
+ msgCommit, ok := constants.Ratio_Commit[ext]
+ if ok {
+ return strings.TrimSpace(ext + " " + msgCommit)
+ }
+
+ if msg != nil {
+ if ext != "" {
+ return strings.TrimSpace(ext + " " + *msg)
+ }
+
+ return strings.TrimSpace(*msg)
+ }
+
+ return fmt.Sprintf("%s Processed file - %s is refactored", constants.Type_CommitRefactor, *filename)
+}
diff --git a/pkg/commit/detect-tag.go b/pkg/commit/detect-tag.go
new file mode 100644
index 0000000..12a3e2a
--- /dev/null
+++ b/pkg/commit/detect-tag.go
@@ -0,0 +1,53 @@
+package commit
+
+import (
+ "git-auto-commit/infra/constants"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+func DetectTagByFile(filename *string, tag string) string {
+ // check type changed
+ switch tag {
+ case constants.NameStatus_Added:
+ return constants.Type_CommitFeat
+
+ case constants.NameStatus_Deleted:
+ return constants.Type_CommitRefactor
+
+ case constants.NameStatus_Modified:
+ return constants.Type_CommitFix
+
+ case constants.NameStatus_Renamed:
+ return constants.Type_CommitRefactor
+
+ }
+
+ if filename == nil {
+ return constants.Type_CommitRefactor
+ }
+
+ ext := filepath.Ext(*filename)
+ base := filepath.Base(*filename)
+
+ // [docs]
+ if ext == ".md" || ext == ".txt" {
+ return constants.Type_CommitDocs
+ }
+
+ // [style]
+ if ext == ".css" || ext == ".scss" || ext == ".sass" || ext == ".less" ||
+ regexp.MustCompile("tailwind.*").MatchString(base) ||
+ regexp.MustCompile("postcss.*").MatchString(base) {
+
+ return constants.Type_CommitStyle
+ }
+
+ // [test]
+ if strings.Contains(base, ".test.") || strings.Contains(base, "_test.") {
+ return constants.Type_CommitTest
+ }
+
+ return ""
+}
diff --git a/files.go b/pkg/file/download.go
similarity index 81%
rename from files.go
rename to pkg/file/download.go
index d7bfe2a..a367138 100644
--- a/files.go
+++ b/pkg/file/download.go
@@ -1,4 +1,4 @@
-package main
+package file
import (
"fmt"
@@ -29,6 +29,23 @@ func DownloadBinAutoCommit(url, destPath string) error {
return err
}
+func DownloadFile(url, filepath string) error {
+ resp, err := http.Get(url)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ out, err := os.Create(filepath)
+ if err != nil {
+ return err
+ }
+ defer out.Close()
+
+ _, err = io.Copy(out, resp.Body)
+ return err
+}
+
func DownloadProgress(resp *http.Response, file *os.File) error {
size := resp.ContentLength
if size <= 0 {
diff --git a/pkg/file/files.go b/pkg/file/files.go
new file mode 100644
index 0000000..9fc061c
--- /dev/null
+++ b/pkg/file/files.go
@@ -0,0 +1,24 @@
+package file
+
+import (
+ "os"
+ "path/filepath"
+)
+
+func GetFilesInDir(directory string) []string {
+ var files []string
+
+ filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return nil
+ }
+
+ if !info.IsDir() {
+ files = append(files, path)
+ }
+
+ return nil
+ })
+
+ return files
+}
diff --git a/git/commit.go b/pkg/git/commit.go
similarity index 74%
rename from git/commit.go
rename to pkg/git/commit.go
index 995974f..f67031d 100644
--- a/git/commit.go
+++ b/pkg/git/commit.go
@@ -2,12 +2,12 @@ package git
import (
"fmt"
- "git-auto-commit/achelper/logger"
+ "git-auto-commit/infra/logger"
"os"
"os/exec"
)
-var Commit = func(commitMsg string) error {
+func (g *Git) Commit(commitMsg string) error {
logger.GitLogger(fmt.Sprintf("commit is: %s", commitMsg))
cmd := exec.Command("git", "commit", "-m", commitMsg)
diff --git a/pkg/git/diff.go b/pkg/git/diff.go
new file mode 100644
index 0000000..a433155
--- /dev/null
+++ b/pkg/git/diff.go
@@ -0,0 +1,148 @@
+package git
+
+import (
+ "bufio"
+ "bytes"
+ "os/exec"
+ "strconv"
+ "strings"
+ "sync"
+)
+
+var diffBufferPool = sync.Pool{
+ New: func() interface{} {
+ return new(bytes.Buffer)
+ },
+}
+
+func (g *Git) GetDiff(file string) (string, error) {
+ var builder strings.Builder
+ builder.Reset()
+
+ root, err := g.GetGitRoot()
+ if err != nil {
+ return "", err
+ }
+
+ 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 = buf
+ if err := cmd.Run(); err != nil {
+ return "", err
+ }
+
+ return buf.String(), nil
+}
+
+func (g *Git) GetStagedCountDirectory() (string, error) {
+ cmd := exec.Command("git", "diff", "--cached", "--numstat")
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return "", err
+ }
+
+ if err := cmd.Start(); err != nil {
+ return "", err
+ }
+
+ directoryChanges := make(map[string]int)
+ rootFileChanges := make(map[string]int)
+
+ scanner := bufio.NewScanner(stdout)
+ for scanner.Scan() {
+ line := scanner.Text()
+ fields := strings.Fields(line)
+ if len(fields) < 3 {
+ continue
+ }
+
+ adds, errAdds := strconv.Atoi(fields[0])
+ dels, errDels := strconv.Atoi(fields[1])
+ if errAdds != nil || errDels != nil {
+ continue
+ }
+
+ file := fields[2]
+ changes := adds + dels
+
+ lastSlash := strings.LastIndex(file, "/")
+ if lastSlash != -1 {
+ dir := file[:lastSlash]
+ directoryChanges[dir] += changes
+ } else {
+ rootFileChanges[file] += changes
+ }
+ }
+
+ if err := cmd.Wait(); err != nil {
+ return "", err
+ }
+
+ var maxDirectory string
+ var maxDirectoryChanges int
+
+ for dir, count := range directoryChanges {
+ if count > maxDirectoryChanges {
+ maxDirectoryChanges = count
+ maxDirectory = dir
+ }
+ }
+
+ var maxRootFile string
+ var maxRootChanges int
+
+ for file, count := range rootFileChanges {
+ if count > maxRootChanges {
+ maxRootChanges = count
+ maxRootFile = file
+ }
+ }
+
+ if maxRootChanges > maxDirectoryChanges {
+ return maxRootFile, nil
+ }
+
+ if maxDirectory != "" {
+ return maxDirectory, nil
+ }
+
+ return "", nil
+}
+
+func (g *Git) GetStagedFiles() ([]string, error) {
+ cmd := exec.Command("git", "diff", "--cached", "--name-only")
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, err
+ }
+
+ if err := cmd.Start(); err != nil {
+ return nil, err
+ }
+
+ var files []string
+ scanner := bufio.NewScanner(stdout)
+ for scanner.Scan() {
+ files = append(files, scanner.Text())
+ }
+
+ if err := scanner.Err(); err != nil {
+ return nil, err
+ }
+
+ if err := cmd.Wait(); err != nil {
+ return nil, err
+ }
+
+ return files, nil
+}
diff --git a/git/git.go b/pkg/git/git.go
similarity index 66%
rename from git/git.go
rename to pkg/git/git.go
index c736261..b0435e2 100644
--- a/git/git.go
+++ b/pkg/git/git.go
@@ -2,28 +2,29 @@ package git
import (
"bytes"
+ "git-auto-commit/pkg/pkgerror"
"os/exec"
"strings"
)
-func GetGitRoot() (string, error) {
+func (g *Git) GetGitRoot() (string, error) {
cmd := exec.Command("git", "rev-parse", "--show-toplevel")
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
- return "", err
+ return "", pkgerror.Err_GitNotRepository
}
root := strings.TrimSpace(out.String())
return root, nil
}
-func GetCurrentBranch() (string, error) {
+func (g *Git) GetCurrentBranch() (string, error) {
cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
out, err := cmd.Output()
if err != nil {
- return "", err
+ return "", pkgerror.Err_GitNotInstalled
}
return strings.TrimSpace(string(out)), nil
diff --git a/git/issues.go b/pkg/git/issues.go
similarity index 86%
rename from git/issues.go
rename to pkg/git/issues.go
index d010753..d050002 100644
--- a/git/issues.go
+++ b/pkg/git/issues.go
@@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"git-auto-commit/config"
- "git-auto-commit/types"
"io"
"net/http"
"os/exec"
@@ -19,7 +18,7 @@ var bufferPool = sync.Pool{
},
}
-func ExtractIssueNumber(branch string) string {
+func (g *Git) ExtractIssueNumber(branch string) string {
re := regexp.MustCompile(`\d+`)
match := re.FindStringSubmatch(branch)
if len(match) > 1 {
@@ -30,7 +29,7 @@ func ExtractIssueNumber(branch string) string {
return ""
}
-func GetOwnerRepository() (string, string, error) {
+func (g *Git) GetOwnerRepository() (string, string, error) {
cmd := exec.Command("git", "remote", "get-url", "origin")
out, err := cmd.Output()
if err != nil {
@@ -48,7 +47,7 @@ func GetOwnerRepository() (string, string, error) {
return "", "", fmt.Errorf("could not parse owner/repository from remote url: %s", url)
}
-func GetIssueData(owner, repo, issue, token string) (string, uint32, error) {
+func (g *Git) GetIssueData(owner, repo, issue, token string) (string, uint32, error) {
var builder strings.Builder
builder.Reset()
@@ -79,7 +78,7 @@ func GetIssueData(owner, repo, issue, token string) (string, uint32, error) {
return "", 0, err
}
- var githubIssue types.GithubIssue
+ var githubIssue GithubIssue
if err := config.JSON.Unmarshal(buf.Bytes(), &githubIssue); err != nil {
return "", 0, err
}
diff --git a/pkg/git/types.go b/pkg/git/types.go
new file mode 100644
index 0000000..34abff7
--- /dev/null
+++ b/pkg/git/types.go
@@ -0,0 +1,28 @@
+package git
+
+type Git struct{}
+
+type GitInterface interface {
+ // deff.go
+ GetDiff(file string) (string, error)
+ GetStagedCountDirectory() (string, error)
+ GetStagedFiles() ([]string, error)
+
+ // commit.go
+ Commit(commitMsg string) error
+
+ // git.go
+ GetGitRoot() (string, error)
+ GetCurrentBranch() (string, error)
+
+ // issues.go
+ ExtractIssueNumber(branch string) string
+ GetOwnerRepository() (string, string, error)
+ GetIssueData(owner, repo, issue, token string) (string, uint32, error)
+}
+
+
+type GithubIssue struct {
+ Title string `json:"title"`
+ Number uint32 `json:"number"`
+}
diff --git a/achelper/code/detected.go b/pkg/language/main.go
similarity index 97%
rename from achelper/code/detected.go
rename to pkg/language/main.go
index e3a7072..c04a0f4 100644
--- a/achelper/code/detected.go
+++ b/pkg/language/main.go
@@ -1,4 +1,4 @@
-package code
+package language
import (
"path/filepath"
diff --git a/pkg/parser/parser.go b/pkg/parser/parser.go
new file mode 100644
index 0000000..ff8c109
--- /dev/null
+++ b/pkg/parser/parser.go
@@ -0,0 +1,54 @@
+package parser
+
+import (
+ "git-auto-commit/pkg/commit"
+ "git-auto-commit/pkg/file"
+ "git-auto-commit/pkg/pkgerror"
+ "os"
+)
+
+func (p *Parser) ParserIndex(directory string) (string, error) {
+ info, err := os.Stat(directory)
+ if err != nil {
+ return "", pkgerror.CreateError(pkgerror.Err_FailedToReadFile)
+ }
+
+ // check this is file
+ if !info.IsDir() {
+ return commit.CreateAutoCommitMsg(&directory, nil, ""), nil
+ }
+
+ files := file.GetFilesInDir(directory)
+ if len(files) == 0 {
+ return "", pkgerror.CreateError(pkgerror.Err_FileNotFound)
+ }
+
+ formatted, err := p.Code.FormattedCode(files)
+ if err != nil {
+ return "", pkgerror.CreateError(err)
+ }
+
+ if formatted == "" {
+ formattedByRemote, err := p.Code.FormattedByRemote("")
+ if err != nil {
+ return "", pkgerror.CreateError(pkgerror.Err_RemoteUnavailable)
+ }
+
+ if formattedByRemote != "" {
+ formatted = formattedByRemote
+ }
+ }
+
+ if formatted == "" {
+ formattedByBranch, err := p.Code.FormattedByBranch()
+ if err != nil {
+ return "", pkgerror.CreateError(pkgerror.Err_BranchNotFound)
+ }
+
+ if formattedByBranch != "" {
+ formatted = formattedByBranch
+ }
+ }
+
+ return formatted, nil
+}
diff --git a/pkg/parser/types.go b/pkg/parser/types.go
new file mode 100644
index 0000000..18b506f
--- /dev/null
+++ b/pkg/parser/types.go
@@ -0,0 +1,12 @@
+package parser
+
+import "git-auto-commit/pkg/code"
+
+type Parser struct {
+ Code code.CodeInterface
+}
+
+type ParserInterface interface {
+ // parser.go
+ ParserIndex(directory string) (string, error)
+}
diff --git a/pkg/pkgerror/pkgerror.go b/pkg/pkgerror/pkgerror.go
new file mode 100644
index 0000000..8e97220
--- /dev/null
+++ b/pkg/pkgerror/pkgerror.go
@@ -0,0 +1,33 @@
+package pkgerror
+
+import (
+ "context"
+ "errors"
+ "net"
+)
+
+func CreateError(err error) error {
+ if err == nil {
+ return nil
+ }
+
+ if errors.Is(err, context.DeadlineExceeded) {
+ return Err_ContextDeadlineExceeded
+ }
+
+ if errors.Is(err, context.Canceled) {
+ return Err_ContextCanceled
+ }
+
+ var netErr net.Error
+ if errors.As(err, &netErr) {
+ if netErr.Timeout() {
+ return Err_Timeout
+ }
+
+ return Err_Network
+ }
+
+ // write to log and return log for user
+ return err
+}
diff --git a/pkg/pkgerror/reestr.go b/pkg/pkgerror/reestr.go
new file mode 100644
index 0000000..73bfa52
--- /dev/null
+++ b/pkg/pkgerror/reestr.go
@@ -0,0 +1,23 @@
+package pkgerror
+
+import "errors"
+
+var (
+ Err_FileNotFound = errors.New("the file was not found")
+ Err_DirectoryNotFound = errors.New("the directory was not found")
+ Err_Timeout = errors.New("connection exceeded the waiting time")
+ Err_NetworkTemporary = errors.New("there is a temporary network problem, please try again")
+ Err_Network = errors.New("network error when connecting")
+ Err_ContextCanceled = errors.New("the operation was cancelled")
+ Err_ContextDeadlineExceeded = errors.New("waiting for a long time, please try again later")
+ Err_GitNotInstalled = errors.New("git is not installed or not found in PATH")
+ Err_GitNotRepository = errors.New("current directory is not a git repository")
+ Err_NoStagedFiles = errors.New("no staged files to commit")
+ Err_FailedToGetDiff = errors.New("failed to get file diff")
+ Err_FailedToCreateCommit = errors.New("failed to create commit")
+ Err_FailedToReadFile = errors.New("error reading file")
+ Err_EmptyCommitMessage = errors.New("commit message is empty")
+ Err_InvalidConfig = errors.New("invalid configuration file")
+ Err_RemoteUnavailable = errors.New("remote repository is unavailable")
+ Err_BranchNotFound = errors.New("current branch not found")
+)
diff --git a/pkg/pkgerror/types.go b/pkg/pkgerror/types.go
new file mode 100644
index 0000000..eab2b68
--- /dev/null
+++ b/pkg/pkgerror/types.go
@@ -0,0 +1 @@
+package pkgerror
\ No newline at end of file
diff --git a/scripts/install-linux-auto-commit.sh b/scripts/install-linux-auto-commit.sh
index 69fdbc9..852e4d4 100644
--- a/scripts/install-linux-auto-commit.sh
+++ b/scripts/install-linux-auto-commit.sh
@@ -1,58 +1,73 @@
-#!/bin/bash
-
-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"
-
-VERSION_URL="https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
-TAG=$(curl -s "$VERSION_URL" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
-
-URL="https://github.com/thefuture-industries/git-auto-commit/releases/download/$TAG/auto-commit"
-VERSION_FILE="$HOOKS_DIR/auto-commit.version.txt"
-
-if [ ! -d .git ]; then
- echo "[!] There is no .git. Run it in the root of the Git repository."
- exit 1
-fi
-
-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 -e "\e[33mFile saved as $HOOK_PATH\e[0m"
-
- git config --local alias.auto '!bash -c ./.git/hooks/auto-commit'
-
- echo "$TAG" > "$VERSION_FILE"
-
- echo -e "\e[32mSuccessful installation version $TAG 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 -e "\e[31mInvalid input. Please enter Y or N.\e[0m"
- exit 1
-fi
+#!/bin/bash
+
+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"
+
+VERSION_URL="https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
+TAG=$(curl -s "$VERSION_URL" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
+
+ARCH=$(uname -m)
+
+case "$ARCH" in
+ x86_64)
+ ARCH="amd64"
+ ;;
+ aarch64|arm64)
+ ARCH="arm64"
+ ;;
+ *)
+ echo "Unsupported architecture: $ARCH"
+ exit 1
+ ;;
+esac
+
+URL="https://github.com/thefuture-industries/git-auto-commit/releases/download/$TAG/${BINARY_NAME}-linux-${ARCH}"
+VERSION_FILE="$HOOKS_DIR/auto-commit.version.txt"
+
+if [ ! -d .git ]; then
+ echo "[!] There is no .git. Run it in the root of the Git repository."
+ exit 1
+fi
+
+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 -e "\e[33mFile saved as $HOOK_PATH\e[0m"
+
+ git config --local alias.auto "!bash -c './.git/hooks/auto-commit \"\$@\"' --"
+
+ echo "$TAG" > "$VERSION_FILE"
+
+ echo -e "\e[32mSuccessful installation version $TAG 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 -e "\e[31mInvalid input. Please enter Y or N.\e[0m"
+ exit 1
+fi
diff --git a/scripts/install-macos-auto-commit.sh b/scripts/install-macos-auto-commit.sh
new file mode 100644
index 0000000..8279be8
--- /dev/null
+++ b/scripts/install-macos-auto-commit.sh
@@ -0,0 +1,74 @@
+#!/bin/bash
+
+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"
+
+HOOKS_DIR=".git/hooks"
+HOOK_NAME="auto-commit"
+HOOK_PATH="$HOOKS_DIR/$HOOK_NAME"
+
+VERSION_URL="https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
+TAG=$(curl -s "$VERSION_URL" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
+
+OS="darwin"
+ARCH=$(uname -m)
+
+case "$ARCH" in
+ x86_64)
+ ARCH="amd64"
+ ;;
+ arm64)
+ ARCH="arm64"
+ ;;
+ *)
+ echo "Unsupported architecture: $ARCH"
+ exit 1
+ ;;
+esac
+
+URL="https://github.com/thefuture-industries/git-auto-commit/releases/download/$TAG/${HOOK_NAME}-macos-$ARCH"
+VERSION_FILE="$HOOKS_DIR/auto-commit.version.txt"
+
+if [ ! -d .git ]; then
+ echo "[!] There is no .git. Run it in the root of the Git repository."
+ exit 1
+fi
+
+read -p "Should I install git auto-commit in the project? (Y/N) " answer
+
+if [[ "$answer" == "Y" || "$answer" == "y" ]]; then
+ echo -e "\e[32mInstalling $URL...\e[0m"
+ curl -L "$URL" -o "$HOOK_PATH"
+ chmod +x "$HOOK_PATH"
+ echo -e "\e[33mFile saved as $HOOK_PATH\e[0m"
+
+ git config --local alias.auto "!bash -c './.git/hooks/auto-commit \"\$@\"' --"
+
+ echo "$TAG" > "$VERSION_FILE"
+
+ echo -e "\e[32mSuccessful installation version $TAG and alias set for auto-commit.\e[0m"
+ echo ""
+ echo -e "\e[33mMore details: 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 -e "\e[31mInvalid input. Please enter Y or N.\e[0m"
+ exit 1
+fi
\ No newline at end of file
diff --git a/scripts/install-windows-auto-commit.ps1 b/scripts/install-windows-auto-commit.ps1
index d132199..19833b7 100644
--- a/scripts/install-windows-auto-commit.ps1
+++ b/scripts/install-windows-auto-commit.ps1
@@ -1,62 +1,62 @@
-# 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
-
-$HookName = "auto-commit"
-
-$versionUrl = "https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
-$tag = (Invoke-RestMethod -Uri $versionUrl -UseBasicParsing).tag_name
-$Url = "https://github.com/thefuture-industries/git-auto-commit/releases/download/$tag/auto-commit-win"
-
-if (-not (Test-Path ".git/hooks")) {
- Write-Error "The current directory is not a Git repository."
- return
-}
-
-$hookPath = Join-Path -Path ".git/hooks" -ChildPath $HookName
-
-try {
- $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'
-
- $versionFile = Join-Path -Path ".git/hooks" -ChildPath "auto-commit.version.txt"
- Set-Content -Path $versionFile -Value $tag
-
- Write-Host "Successful installation version $tag 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
-}
+# 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
+
+$HookName = "auto-commit"
+
+$versionUrl = "https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
+$tag = (Invoke-RestMethod -Uri $versionUrl -UseBasicParsing).tag_name
+$Url = "https://github.com/thefuture-industries/git-auto-commit/releases/download/$tag/auto-commit-windows-amd64"
+
+if (-not (Test-Path ".git/hooks")) {
+ Write-Error "The current directory is not a Git repository."
+ return
+}
+
+$hookPath = Join-Path -Path ".git/hooks" -ChildPath $HookName
+
+try {
+ $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'
+
+ $versionFile = Join-Path -Path ".git/hooks" -ChildPath "auto-commit.version.txt"
+ Set-Content -Path $versionFile -Value $tag
+
+ Write-Host "Successful installation version $tag 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
+}
diff --git a/scripts/update-linux-auto-commit.sh b/scripts/update-linux-auto-commit.sh
index cb9f4c0..137f208 100644
--- a/scripts/update-linux-auto-commit.sh
+++ b/scripts/update-linux-auto-commit.sh
@@ -17,7 +17,23 @@ fi
VERSION_URL="https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
TAG=$(curl -s "$VERSION_URL" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
-URL="https://github.com/thefuture-industries/git-auto-commit/releases/download/$TAG/auto-commit"
+
+ARCH=$(uname -m)
+
+case "$ARCH" in
+ x86_64)
+ ARCH="amd64"
+ ;;
+ aarch64|arm64)
+ ARCH="arm64"
+ ;;
+ *)
+ echo "Unsupported architecture: $ARCH"
+ exit 1
+ ;;
+esac
+
+URL="https://github.com/thefuture-industries/git-auto-commit/releases/download/$TAG/${HOOK_NAME}-linux-${ARCH}"
if [ -f "$VERSION_FILE" ]; then
CURRENT_TAG=$(cat "$VERSION_FILE" | tr -d ' \n\r')
@@ -61,5 +77,5 @@ chmod +x "$HOOK_PATH"
echo "$TAG" > "$VERSION_FILE"
-git config --local alias.auto '!bash -c ./.git/hooks/auto-commit'
+git config --local alias.auto "!bash -c './.git/hooks/auto-commit \"\$@\"' --"
echo "successful upgrade to version $TAG"
diff --git a/scripts/update-macos-auto-commit.sh b/scripts/update-macos-auto-commit.sh
new file mode 100644
index 0000000..f05699c
--- /dev/null
+++ b/scripts/update-macos-auto-commit.sh
@@ -0,0 +1,82 @@
+#!/bin/bash
+
+set -e
+
+GIT_ROOT=$(git rev-parse --show-toplevel)
+cd "$GIT_ROOT"
+
+HOOKS_DIR=".git/hooks"
+HOOK_NAME="auto-commit"
+HOOK_PATH="$HOOKS_DIR/$HOOK_NAME"
+VERSION_FILE="$HOOKS_DIR/auto-commit.version.txt"
+
+if pgrep -f "$HOOK_PATH" > /dev/null; then
+ pkill -f "$HOOK_PATH"
+ sleep 2
+fi
+
+VERSION_URL="https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
+TAG=$(curl -s "$VERSION_URL" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
+
+OS="darwin"
+ARCH=$(uname -m)
+
+case "$ARCH" in
+ x86_64)
+ ARCH="amd64"
+ ;;
+ arm64)
+ ARCH="arm64"
+ ;;
+ *)
+ echo "Unsupported architecture: $ARCH"
+ exit 1
+ ;;
+esac
+
+URL="https://github.com/thefuture-industries/git-auto-commit/releases/download/$TAG/${HOOK_NAME}-macos-${ARCH}"
+
+if [ -f "$VERSION_FILE" ]; then
+ CURRENT_TAG=$(cat "$VERSION_FILE" | tr -d ' \n\r')
+ if [ "$CURRENT_TAG" = "$TAG" ]; then
+ echo -e "\033[33m[!] you have the latest version installed $TAG\033[0m"
+ exit 0
+ fi
+fi
+
+download_with_progress() {
+ local url="$1"
+ local output="$2"
+ local bar_width=60
+
+ content_length=$(curl -sI "$url" | grep -i Content-Length | awk '{print $2}' | tr -d '\r')
+ [ -z "$content_length" ] && content_length=0
+
+ echo -n "auto-commit update ["
+ for ((i=0; i "$VERSION_FILE"
+
+git config --local alias.auto "!bash -c './.git/hooks/auto-commit \"\$@\"' --"
+echo "successful upgrade to version $TAG"
diff --git a/scripts/update-windows-auto-commit.ps1 b/scripts/update-windows-auto-commit.ps1
index 534733a..56eb846 100644
--- a/scripts/update-windows-auto-commit.ps1
+++ b/scripts/update-windows-auto-commit.ps1
@@ -1,70 +1,70 @@
-# auto-commit.psm1
-$ErrorActionPreference = "Stop"
-
-$gitRoot = & git rev-parse --show-toplevel
-Set-Location $gitRoot
-
-$proc = Get-Process "auto-commit" -ErrorAction SilentlyContinue
-if ($proc) {
- $proc | Stop-Process -Force
- Start-Sleep -Seconds 2
-}
-
-$versionUrl = "https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
-$tag = (Invoke-RestMethod -Uri $versionUrl -UseBasicParsing).tag_name
-
-$Url = "https://github.com/thefuture-industries/git-auto-commit/releases/download/$tag/auto-commit-win"
-
-$HookName = "auto-commit"
-$hookPath = Join-Path -Path ".git/hooks" -ChildPath $HookName
-$versionFile = Join-Path -Path ".git/hooks" -ChildPath "auto-commit.version.txt"
-
-if (Test-Path $versionFile) {
- $currentTag = Get-Content $versionFile | ForEach-Object { $_.Trim() }
- if ($currentTag -eq $tag) {
- Write-Host "[!] you have the latest version installed $tag" -ForegroundColor Yellow
- exit 0
- }
-}
-
-function Download-WithProgress {
- param (
- [string]$url,
- [string]$output
- )
-
- $req = [System.Net.HttpWebRequest]::Create($url)
- $req.UserAgent = "git-auto-commit"
- $resp = $req.GetResponse()
- $total = $resp.ContentLength
- $stream = $resp.GetResponseStream()
- $outStream = [System.IO.File]::Open($output, [System.IO.FileMode]::Create)
-
- $buffer = New-Object byte[] 8192
- $read = 0
- $downloaded = 0
- $barWidth = 50
-
- while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) {
- $outStream.Write($buffer, 0, $read)
- $downloaded += $read
- $percent = [math]::Round(($downloaded / $total) * 100)
- $filled = [math]::Floor($barWidth * $percent / 100)
- $empty = $barWidth - $filled
- $bar = ('*' * $filled) + ('.' * $empty)
- Write-Host -NoNewline "`rauto-commit update [$bar] $percent% "
- }
-
- $outStream.Close()
- $stream.Close()
- Write-Host ""
-}
-
-Download-WithProgress -url $Url -output $hookPath
-
-Set-Content -Path $versionFile -Value $tag
-
-git config --local alias.auto '!./.git/hooks/auto-commit'
-
-Write-Host "successful upgrade to version $tag"
-[Environment]::Exit(0)
+# auto-commit.psm1
+$ErrorActionPreference = "Stop"
+
+$gitRoot = & git rev-parse --show-toplevel
+Set-Location $gitRoot
+
+$proc = Get-Process "auto-commit" -ErrorAction SilentlyContinue
+if ($proc) {
+ $proc | Stop-Process -Force
+ Start-Sleep -Seconds 2
+}
+
+$versionUrl = "https://api.github.com/repos/thefuture-industries/git-auto-commit/releases/latest"
+$tag = (Invoke-RestMethod -Uri $versionUrl -UseBasicParsing).tag_name
+
+$Url = "https://github.com/thefuture-industries/git-auto-commit/releases/download/$tag/auto-commit-windows-amd64"
+
+$HookName = "auto-commit"
+$hookPath = Join-Path -Path ".git/hooks" -ChildPath $HookName
+$versionFile = Join-Path -Path ".git/hooks" -ChildPath "auto-commit.version.txt"
+
+if (Test-Path $versionFile) {
+ $currentTag = Get-Content $versionFile | ForEach-Object { $_.Trim() }
+ if ($currentTag -eq $tag) {
+ Write-Host "[!] you have the latest version installed $tag" -ForegroundColor Yellow
+ exit 0
+ }
+}
+
+function Download-WithProgress {
+ param (
+ [string]$url,
+ [string]$output
+ )
+
+ $req = [System.Net.HttpWebRequest]::Create($url)
+ $req.UserAgent = "git-auto-commit"
+ $resp = $req.GetResponse()
+ $total = $resp.ContentLength
+ $stream = $resp.GetResponseStream()
+ $outStream = [System.IO.File]::Open($output, [System.IO.FileMode]::Create)
+
+ $buffer = New-Object byte[] 8192
+ $read = 0
+ $downloaded = 0
+ $barWidth = 50
+
+ while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) {
+ $outStream.Write($buffer, 0, $read)
+ $downloaded += $read
+ $percent = [math]::Round(($downloaded / $total) * 100)
+ $filled = [math]::Floor($barWidth * $percent / 100)
+ $empty = $barWidth - $filled
+ $bar = ('*' * $filled) + ('.' * $empty)
+ Write-Host -NoNewline "`rauto-commit update [$bar] $percent% "
+ }
+
+ $outStream.Close()
+ $stream.Close()
+ Write-Host ""
+}
+
+Download-WithProgress -url $Url -output $hookPath
+
+Set-Content -Path $versionFile -Value $tag
+
+git config --local alias.auto '!./.git/hooks/auto-commit'
+
+Write-Host "successful upgrade to version $tag"
+[Environment]::Exit(0)
diff --git a/tests/ac_test.go b/tests/ac_test.go
deleted file mode 100644
index 6b8bc98..0000000
--- a/tests/ac_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package tests
-
-import (
- "errors"
- "git-auto-commit/ac"
- "git-auto-commit/achelper"
- "git-auto-commit/achelper/logger"
- "git-auto-commit/diff"
- "git-auto-commit/git"
- "git-auto-commit/parser"
- "testing"
-)
-
-func TestAutoCommit_NoStagedFiles(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- calledInfo := ""
- diff.GetStagedFiles = func() ([]string, error) { return []string{}, nil }
- parser.Parser = func(files []string) (string, error) { return "", nil }
- git.Commit = func(msg string) error { return nil }
- logger.ErrorLogger = func(err error) { t.Errorf("unexpected error: %v", err) }
- logger.InfoLogger = func(msg string) { calledInfo = msg }
- achelper.GetVersion = func(show bool) {}
-
- ac.AutoCommit()
-
- if calledInfo != "No files staged for commit." {
- t.Errorf("expected info log 'No files staged for commit.', got '%s'", calledInfo)
- }
-}
-
-func TestAutoCommit_ErrorGettingFiles(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetStagedFiles = func() ([]string, error) { return nil, errors.New("fail") }
- parser.Parser = func(files []string) (string, error) { return "", nil }
- git.Commit = func(msg string) error { return nil }
- logger.InfoLogger = func(msg string) {}
- achelper.GetVersion = func(show bool) {}
-
- var calledErr string
- logger.ErrorLogger = func(err error) { calledErr = err.Error() }
-
- logger.InfoLogger = func(msg string) { calledErr = msg }
-
- ac.AutoCommit()
-
- expected := "error getting staged files: fail"
- if calledErr != expected {
- t.Errorf("expected error log '%s', got '%s'", expected, calledErr)
- }
-}
diff --git a/tests/af_go_test.go b/tests/af_go_test.go
deleted file mode 100644
index 980ec34..0000000
--- a/tests/af_go_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-package tests
-
-import (
- "git-auto-commit/achelper/code"
- "git-auto-commit/diff"
- "git-auto-commit/parser"
- "testing"
-)
-
-func TestFormattedFunction_AddedGoFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+func AddedGoFunction() {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added function AddedGoFunction"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_AddedGoFunctions(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+func AddedGoFunction1()\n+func AddedGoFunction2()\n+func AddedGoFunction3()", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added functions: AddedGoFunction1, AddedGoFunction2, AddedGoFunction3"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_DeletedGoFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-func DeletedGoFunction() {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "deleted function DeletedGoFunction"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_DeletedGoFunctions(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-func DeletedGoFunction1()\n-func DeletedGoFunction2()\n-func DeletedGoFunction3()", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "deleted functions: DeletedGoFunction1, DeletedGoFunction2, DeletedGoFunction3"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_ChangedParamNameGoFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-func ParamTest(a int)\n+func ParamTest(b int)", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed parameter in ParamTest function"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_ChangedParamNameGoFunctions(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-func ParamTest1(a int)\n+func ParamTest1(b int)\n-func ParamTest2(x string)\n+func ParamTest2(y string)", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed parameters in functions: ParamTest1 function, ParamTest2 function"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_ChangedParamTypeGoFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-func TypeTest(a int)\n+func TypeTest(a string)", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed parameter type a in TypeTest function"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
diff --git a/tests/af_ts_test.go b/tests/af_ts_test.go
deleted file mode 100644
index 44ee13f..0000000
--- a/tests/af_ts_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-package tests
-
-import (
- "git-auto-commit/achelper/code"
- "git-auto-commit/diff"
- "git-auto-commit/parser"
- "testing"
-)
-
-func TestFormattedFunction_AddedTSFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+function AddedTSFunction() {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added function AddedTSFunction"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_AddedTSFunctions(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+function AddedTSFunction1() {}\n+function AddedTSFunction2() {}\n+function AddedTSFunction3() {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added functions: AddedTSFunction1, AddedTSFunction2, AddedTSFunction3"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_DeletedTSFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-function DeletedTSFunction() {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "deleted function DeletedTSFunction"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_DeletedTSFunctions(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-function DeletedTSFunction1() {}\n-function DeletedTSFunction2() {}\n-function DeletedTSFunction3() {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "deleted functions: DeletedTSFunction1, DeletedTSFunction2, DeletedTSFunction3"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_ChangedParamNameTSFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-function ParamTest(a: number) {}\n+function ParamTest(b: number) {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed parameter in ParamTest function"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_ChangedParamNameTSFunctions(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-function ParamTest1(a: number) {}\n+function ParamTest1(b: number) {}\n-function ParamTest2(x: string) {}\n+function ParamTest2(y: string) {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed parameters in functions: ParamTest1 function, ParamTest2 function"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedFunction_ChangedParamTypeTSFunction(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-function TypeTest(a: number) {}\n+function TypeTest(a: string) {}", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed parameter type a in TypeTest function"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
diff --git a/tests/ai_go_test.go b/tests/ai_go_test.go
deleted file mode 100644
index b1cac60..0000000
--- a/tests/ai_go_test.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package tests
-
-import (
- "git-auto-commit/achelper/code"
- "git-auto-commit/diff"
- "git-auto-commit/parser"
- "testing"
-)
-
-func TestFormattedImport_AddedGoImport(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+import \"fmt\"", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"main.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "included 'fmt' in main.go"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedImport_AddedGoImports(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+import \"fmt\"\n+import \"os\"", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"main.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "included 'fmt', 'os' in main.go"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedImport_AddedImportsBlockGo(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+import (\n+\"fmt\"\n+\"os\"\n+)", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"main.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "included 'fmt', 'os' in main.go"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedImport_AddedImportBlockGo(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+import (\n+\"fmt\"\n+)", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"main.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "included 'fmt' in main.go"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
diff --git a/tests/autocommit_test.go b/tests/autocommit_test.go
new file mode 100644
index 0000000..783b520
--- /dev/null
+++ b/tests/autocommit_test.go
@@ -0,0 +1,103 @@
+package tests
+
+import (
+ "errors"
+ "git-auto-commit/infra/logger"
+ "git-auto-commit/pkg/cli"
+ "git-auto-commit/pkg/pkgerror"
+ "testing"
+)
+
+func TestAutoCommit(t *testing.T) {
+ tests := []struct {
+ name string
+ stagedDir string
+ stagedErr error
+ parseMsg string
+ parseErr error
+ commitErr error
+ expectInfoLog string
+ expectErrorLog bool
+ }{
+ {
+ name: "No staged files",
+ stagedDir: "",
+ stagedErr: nil,
+ expectInfoLog: pkgerror.Err_NoStagedFiles.Error(),
+ },
+ {
+ name: "Failed to get staged dir",
+ stagedErr: errors.New("fail"),
+ expectErrorLog: true,
+ },
+ {
+ name: "Parser error",
+ stagedDir: "some/dir",
+ parseErr: errors.New("parse fail"),
+ },
+ {
+ name: "Commit error",
+ stagedDir: "some/dir",
+ parseMsg: "commit message",
+ commitErr: errors.New("commit fail"),
+ },
+ {
+ name: "Successful commit",
+ stagedDir: "some/dir",
+ parseMsg: "commit message",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ infoLogged := ""
+ errorLogged := false
+
+ gitMocks := &gitMocks{
+ stagedDir: tt.stagedDir,
+ stagedErr: tt.stagedErr,
+ commitErr: tt.commitErr,
+ }
+
+ parserMocks := &parserMocks{
+ parsedMsg: tt.parseMsg,
+ parseErr: tt.parseErr,
+ }
+
+ cli := &cli.CLI{
+ Git: gitMocks,
+ Parser: parserMocks,
+ }
+
+ infoLogger := logger.InfoLogger
+ errorLogger := logger.ErrorLogger
+ gitLogger := logger.GitLogger
+
+ defer func() {
+ logger.InfoLogger = infoLogger
+ logger.ErrorLogger = errorLogger
+ logger.GitLogger = gitLogger
+ }()
+
+ logger.InfoLogger = func(msg string) {
+ infoLogged = msg
+ }
+
+ logger.ErrorLogger = func(err error) {
+ errorLogged = true
+ }
+
+ logger.GitLogger = func(msg string) {}
+
+ cli.AutoCommit()
+
+ if tt.expectInfoLog != "" && infoLogged != tt.expectInfoLog {
+ t.Errorf("expected info log '%s', got '%s'", tt.expectInfoLog, infoLogged)
+ }
+
+ if tt.expectErrorLog && !errorLogged {
+ t.Errorf("expected error log but none was logged")
+ }
+ })
+ }
+}
diff --git a/tests/av_go_test.go b/tests/av_go_test.go
deleted file mode 100644
index b5822f8..0000000
--- a/tests/av_go_test.go
+++ /dev/null
@@ -1,146 +0,0 @@
-package tests
-
-import (
- "git-auto-commit/achelper/code"
- "git-auto-commit/diff"
- "git-auto-commit/parser"
- "testing"
-)
-
-func TestFormattedVariables_AddedGoVar(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+var testVar int = 5", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added variable testVar"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_AddedGoVarEQ(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+testVar := 5", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added variable testVar"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_AddedGoVars(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+var testVar1 int = 5\n+var testVar2 string\n+testVar3 := 0", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added variables: testVar1, testVar2, testVar3"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_RenamedGoVar(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-var testVar1 int = 5\n+var testVar int = 5", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "renamed variable testVar1 -> testVar"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_ChangedTypeGoVar(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-var testVar int = 5\n+var testVar uint = 5", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed type of variable testVar (int -> uint)"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_ChangedTypeGoVars(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-var testVar uint8 = 5\n+var testVar uint16 = 5\n-var testVar2 uint16 = 5\n+var testVar2 int32 = 5", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "go"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.go"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed types of variables: testVar (uint8 -> uint16), testVar2 (uint16 -> int32)"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
diff --git a/tests/av_ts_test.go b/tests/av_ts_test.go
deleted file mode 100644
index a79ef98..0000000
--- a/tests/av_ts_test.go
+++ /dev/null
@@ -1,123 +0,0 @@
-package tests
-
-import (
- "git-auto-commit/achelper/code"
- "git-auto-commit/diff"
- "git-auto-commit/parser"
- "testing"
-)
-
-func TestFormattedVariables_AddedTSVar(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+let testVar: number = 5;", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added variable testVar"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_AddedTSVars(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "+let testVar1: number = 5;\n+const testVar2: string = 'hi';", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "added variables: testVar1, testVar2"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_RenamedTSVar(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-let testVar1: number = 5;\n+let testVar: number = 5;", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "renamed variable testVar1 -> testVar"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_ChangedTypeTSVar(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-let testVar: number = 5;\n+let testVar: string = 5;", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed type of variable testVar (number -> string)"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
-
-func TestFormattedVariables_ChangedTypesTSVars(t *testing.T) {
- mocks := SaveMocks()
- defer mocks.Apply()
-
- diff.GetDiff = func(file string) (string, error) {
- return "-let testVar: number = 5;\n+let testVar: string = 5;\n-var testVar2: boolean = true;\n+var testVar2: number = true;", nil
- }
-
- code.DetectLanguage = func(filename string) string {
- return "typescript"
- }
-
- msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
-
- expected := "changed types of variables: testVar (number -> string), testVar2 (boolean -> number)"
- if msg != expected {
- t.Errorf("expected '%s', got '%s'", expected, msg)
- }
-}
diff --git a/tests/code/deleted/deleted_test.go b/tests/code/deleted/deleted_test.go
new file mode 100644
index 0000000..96ef104
--- /dev/null
+++ b/tests/code/deleted/deleted_test.go
@@ -0,0 +1,39 @@
+package golang
+
+import (
+ "fmt"
+ "git-auto-commit/pkg/code"
+ "git-auto-commit/tests"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+const deleteExpectedTest string = "[refactor] Removed middleware components"
+
+func TestDeleted(t *testing.T) {
+ gitOutput := `
+ D middleware/rate.del
+ `
+
+ code.ExecCommand = func(name string, args ...string) *exec.Cmd {
+ return tests.FakeExecCommand(gitOutput)
+ }
+ defer func() {
+ code.ExecCommand = exec.Command
+ }()
+
+ c := &code.Code{}
+
+ files := []string{"middleware/rate.del"}
+ msg, err := c.FormattedCode(files)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if !strings.EqualFold(strings.TrimSpace(msg), strings.TrimSpace(deleteExpectedTest)) {
+ t.Errorf("Expected commit message:\n%q\nGot:%q", deleteExpectedTest, msg)
+ }
+
+ fmt.Println("==> Formatted commit message:", msg)
+}
diff --git a/tests/code/implemented/implemented_tag_docs_test.go b/tests/code/implemented/implemented_tag_docs_test.go
new file mode 100644
index 0000000..14fe16e
--- /dev/null
+++ b/tests/code/implemented/implemented_tag_docs_test.go
@@ -0,0 +1,70 @@
+package golang
+
+import (
+ "fmt"
+ "git-auto-commit/infra/constants"
+ "git-auto-commit/pkg/code"
+ "git-auto-commit/tests"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+func TestImplementedTagDoc(t *testing.T) {
+ gitOutput := `
+ A README.md
+ `
+
+ code.ExecCommand = func(name string, args ...string) *exec.Cmd {
+ return tests.FakeExecCommand(gitOutput)
+ }
+ defer func() {
+ code.ExecCommand = exec.Command
+ }()
+
+ c := &code.Code{}
+
+ files := []string{"README.md"}
+ msg, err := c.FormattedCode(files)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if !strings.Contains(msg, constants.Type_CommitDocs) {
+ t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitDocs, msg)
+ }
+
+ fmt.Println("==> Formatted commit message:", msg)
+}
+
+func TestImplementedTagDocs(t *testing.T) {
+ gitNameStatusOutput := `
+ A docs/code/readme.md
+ M docs/code/download.txt
+ M main/docs/security.md
+ D pkg/create-commit-msg.impl
+ A pkg/detect-tag.impl
+ A pkg/parser/types.impl
+ `
+
+ code.ExecCommand = func(name string, args ...string) *exec.Cmd {
+ return tests.FakeExecCommand(gitNameStatusOutput)
+ }
+ defer func() {
+ code.ExecCommand = exec.Command
+ }()
+
+ c := &code.Code{}
+
+ files := []string{"docs/code/readme.md", "docs/code/download.txt"}
+ msg, err := c.FormattedCode(files)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if !strings.Contains(msg, constants.Type_CommitDocs) {
+ t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitDocs, msg)
+ }
+
+ fmt.Println("==> Formatted commit message:", msg)
+}
diff --git a/tests/code/implemented/implemented_tag_style_test.go b/tests/code/implemented/implemented_tag_style_test.go
new file mode 100644
index 0000000..58c4455
--- /dev/null
+++ b/tests/code/implemented/implemented_tag_style_test.go
@@ -0,0 +1,38 @@
+package golang
+
+import (
+ "fmt"
+ "git-auto-commit/infra/constants"
+ "git-auto-commit/pkg/code"
+ "git-auto-commit/tests"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+func TestImplementedTagStyle(t *testing.T) {
+ gitOutput := `
+ A styles/components.css
+ `
+
+ code.ExecCommand = func(name string, args ...string) *exec.Cmd {
+ return tests.FakeExecCommand(gitOutput)
+ }
+ defer func() {
+ code.ExecCommand = exec.Command
+ }()
+
+ c := &code.Code{}
+
+ files := []string{"styles/components.css"}
+ msg, err := c.FormattedCode(files)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if !strings.Contains(msg, constants.Type_CommitStyle) {
+ t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitStyle, msg)
+ }
+
+ fmt.Println("==> Formatted commit message:", msg)
+}
diff --git a/tests/code/implemented/implemented_tag_test_test.go b/tests/code/implemented/implemented_tag_test_test.go
new file mode 100644
index 0000000..d7c57d2
--- /dev/null
+++ b/tests/code/implemented/implemented_tag_test_test.go
@@ -0,0 +1,38 @@
+package golang
+
+import (
+ "fmt"
+ "git-auto-commit/infra/constants"
+ "git-auto-commit/pkg/code"
+ "git-auto-commit/tests"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+func TestImplementedTagTest(t *testing.T) {
+ gitOutput := `
+ A tests/golang_test.impl
+ `
+
+ code.ExecCommand = func(name string, args ...string) *exec.Cmd {
+ return tests.FakeExecCommand(gitOutput)
+ }
+ defer func() {
+ code.ExecCommand = exec.Command
+ }()
+
+ c := &code.Code{}
+
+ files := []string{"tests/golang_test.impl"}
+ msg, err := c.FormattedCode(files)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if !strings.Contains(msg, constants.Type_CommitTest) {
+ t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitTest, msg)
+ }
+
+ fmt.Println("==> Formatted commit message:", msg)
+}
diff --git a/tests/code/implemented/implemented_test.go b/tests/code/implemented/implemented_test.go
new file mode 100644
index 0000000..5636a8a
--- /dev/null
+++ b/tests/code/implemented/implemented_test.go
@@ -0,0 +1,39 @@
+package golang
+
+import (
+ "fmt"
+ "git-auto-commit/pkg/code"
+ "git-auto-commit/tests"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+const implementeExpectedTest string = "[feat] Implemented source code files"
+
+func TestImplemented(t *testing.T) {
+ gitOutput := `
+ A src/main.impl
+ `
+
+ code.ExecCommand = func(name string, args ...string) *exec.Cmd {
+ return tests.FakeExecCommand(gitOutput)
+ }
+ defer func() {
+ code.ExecCommand = exec.Command
+ }()
+
+ c := &code.Code{}
+
+ files := []string{"src/main.impl"}
+ msg, err := c.FormattedCode(files)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if !strings.EqualFold(strings.TrimSpace(msg), strings.TrimSpace(implementeExpectedTest)) {
+ t.Errorf("Expected commit message:\n%q\nGot:\n%q", implementeExpectedTest, msg)
+ }
+
+ fmt.Println("==> Formatted commit message:", msg)
+}
diff --git a/tests/code/modified/modified_golang_test.go b/tests/code/modified/modified_golang_test.go
new file mode 100644
index 0000000..f99c56c
--- /dev/null
+++ b/tests/code/modified/modified_golang_test.go
@@ -0,0 +1,39 @@
+package golang
+
+import (
+ "fmt"
+ "git-auto-commit/pkg/code"
+ "git-auto-commit/tests"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+const modifieExpectedTest string = "[fix] Updated command-line tools"
+
+func TestModified(t *testing.T) {
+ gitOutput := `
+ M cmd/main.mdf
+ `
+
+ code.ExecCommand = func(name string, args ...string) *exec.Cmd {
+ return tests.FakeExecCommand(gitOutput)
+ }
+ defer func() {
+ code.ExecCommand = exec.Command
+ }()
+
+ c := &code.Code{}
+
+ files := []string{"cmd/main.mdf"}
+ msg, err := c.FormattedCode(files)
+ if err != nil {
+ t.Fatalf("Unexpected error: %v", err)
+ }
+
+ if !strings.EqualFold(strings.TrimSpace(msg), strings.TrimSpace(modifieExpectedTest)) {
+ t.Errorf("Expected commit message:\n%q\nGot:%q", modifieExpectedTest, msg)
+ }
+
+ fmt.Println("==> Formatted commit message:", msg)
+}
diff --git a/tests/test.g.go b/tests/test.g.go
index 3b75aad..3c3f61f 100644
--- a/tests/test.g.go
+++ b/tests/test.g.go
@@ -1,38 +1,57 @@
package tests
import (
- "git-auto-commit/achelper"
- "git-auto-commit/achelper/logger"
- "git-auto-commit/diff"
- "git-auto-commit/git"
- "git-auto-commit/parser"
+ "os/exec"
)
-type Mocks struct {
- GetStagedFiles func() ([]string, error)
- Parser func([]string) (string, error)
- Commit func(string) error
- ErrorLogger func(error)
- InfoLogger func(string)
- GetVersion func(bool)
-}
-
-func SaveMocks() *Mocks {
- return &Mocks{
- GetStagedFiles: diff.GetStagedFiles,
- Parser: parser.Parser,
- Commit: git.Commit,
- ErrorLogger: logger.ErrorLogger,
- InfoLogger: logger.InfoLogger,
- GetVersion: achelper.GetVersion,
- }
-}
-
-func (m *Mocks) Apply() {
- diff.GetStagedFiles = m.GetStagedFiles
- parser.Parser = m.Parser
- git.Commit = m.Commit
- logger.ErrorLogger = m.ErrorLogger
- logger.InfoLogger = m.InfoLogger
- achelper.GetVersion = m.GetVersion
+func (m *gitMocks) GetStagedCountDirectory() (string, error) {
+ return m.stagedDir, m.stagedErr
+}
+
+func (m *gitMocks) Commit(msg string) error {
+ return m.commitErr
+}
+
+func (m *gitMocks) GetDiff(file string) (string, error) {
+ return "", nil
+}
+
+func (m *gitMocks) GetStagedFiles() ([]string, error) {
+ return nil, nil
+}
+
+func (m *gitMocks) GetGitRoot() (string, error) {
+ return "", nil
+}
+
+func (m *gitMocks) GetCurrentBranch() (string, error) {
+ return "", nil
+}
+
+func (m *gitMocks) ExtractIssueNumber(branch string) string {
+ return ""
+}
+
+func (m *gitMocks) GetOwnerRepository() (string, string, error) {
+ return "", "", nil
+}
+
+func (m *gitMocks) GetIssueData(owner, repo, issue, token string) (string, uint32, error) {
+ return "", 0, nil
+}
+
+func (m *parserMocks) ParserIndex(directory string) (string, error) {
+ return m.parsedMsg, m.parseErr
+}
+
+func (m *parserMocks) CreateAutoCommitMsg(filename, msg *string, changed string) string {
+ return ""
+}
+
+func (m *parserMocks) DetectTagByFile(filename *string, changed string) string {
+ return ""
+}
+
+func FakeExecCommand(output string) *exec.Cmd {
+ return exec.Command("echo", output)
}
diff --git a/tests/test.g.type.go b/tests/test.g.type.go
new file mode 100644
index 0000000..799e527
--- /dev/null
+++ b/tests/test.g.type.go
@@ -0,0 +1,12 @@
+package tests
+
+type parserMocks struct {
+ parsedMsg string
+ parseErr error
+}
+
+type gitMocks struct {
+ stagedDir string
+ stagedErr error
+ commitErr error
+}
diff --git a/vercel.json b/vercel.json
index f8f5ec0..5bfb0f2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1,14 +1,14 @@
-{
- "builds": [
- {
- "src": "www/**/*",
- "use": "@vercel/static"
- }
- ],
- "routes": [
- {
- "src": "/(.*)",
- "dest": "/www/$1"
- }
- ]
-}
+{
+ "builds": [
+ {
+ "src": "Help/www/**/*",
+ "use": "@vercel/static"
+ }
+ ],
+ "routes": [
+ {
+ "src": "/(.*)",
+ "dest": "/Help/www/$1"
+ }
+ ]
+}
diff --git a/version.md b/version.md
new file mode 100644
index 0000000..87fabf4
--- /dev/null
+++ b/version.md
@@ -0,0 +1,9 @@
+## V3
+
+[ ] HTML for git auto commit
+[ ] CSS for git auto commit
+[ ] TSX/JSX for git auto commit
+[ ] Makefile for git auto commit
+[ ] .md for git auto commit
+[ ] .txt for git auto commit
+[ ] .json for git auto commit
\ No newline at end of file