From 1f49a2c19d6b7ba764e50f3e868186531d201fdb Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sat, 9 Aug 2025 13:04:56 -0400 Subject: [PATCH 01/20] the '.gitignore' file has been changed | the 'release.yml' file has been changed | the 'go-check.yml' file has been changed | the 'pre-push' file has been changed | the '.prettierrc' file has been changed | the 'LGPL-2' file has been changed | the 'LICENSE' file has been changed | the 'Makefile' file has been changed | the 'README.md' file has been changed | the 'SECURITY.md' file has been changed --- .github/workflows/go-check.yml | 106 +-- .github/workflows/release.yml | 460 +++++----- .gitignore | 72 +- .husky/pre-push | 32 +- .prettierrc | 18 +- LGPL-2 | 1022 +++++++++++------------ LICENSE | 42 +- Makefile | 69 +- README.md | 104 +-- SECURITY.md | 68 +- go.mod | 22 +- go.sum | 32 +- scripts/install-linux-auto-commit.sh | 116 +-- scripts/install-windows-auto-commit.ps1 | 124 +-- scripts/update-windows-auto-commit.ps1 | 140 ++-- vercel.json | 28 +- www/index.html | 348 ++++---- 17 files changed, 1402 insertions(+), 1401 deletions(-) diff --git a/.github/workflows/go-check.yml b/.github/workflows/go-check.yml index bc0226e..086c6cb 100644 --- a/.github/workflows/go-check.yml +++ b/.github/workflows/go-check.yml @@ -1,53 +1,53 @@ -name: Static Go Check - -on: - pull_request: - branches: [main] - -jobs: - go_check: - runs-on: ubuntu-latest - - steps: - - name: Clone repository - uses: actions/checkout@v3 - - - name: Install Go - uses: actions/setup-go@v4 - with: - go-version: '1.23.0' - - - name: Install dependencies - run: | - go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest - go install golang.org/x/tools/cmd/goimports@latest - - - name: Go mod tidy & download - run: | - go mod tidy - go mod download - - - name: Check formatting (gofmt) - run: | - if [ -n "$(gofmt -l .)" ]; then - echo "Файлы не отформатированы. Запустите 'gofmt -w .'" - gofmt -l . - exit 1 - fi - - - name: Check imports (goimports) - run: | - if [ -n "$(goimports -l .)" ]; then - echo "Неверный импорт. Запустите 'goimports -w .'" - goimports -l . - exit 1 - fi - - - name: Lint (golangci-lint) - run: | - make lint - - - name: Build binary - run: | - mkdir -p bin - make build +name: Static Go Check + +on: + pull_request: + branches: [main] + +jobs: + go_check: + runs-on: ubuntu-latest + + steps: + - name: Clone repository + uses: actions/checkout@v3 + + - name: Install Go + uses: actions/setup-go@v4 + with: + go-version: '1.23.0' + + - name: Install dependencies + run: | + go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + go install golang.org/x/tools/cmd/goimports@latest + + - name: Go mod tidy & download + run: | + go mod tidy + go mod download + + - name: Check formatting (gofmt) + run: | + if [ -n "$(gofmt -l .)" ]; then + echo "Файлы не отформатированы. Запустите 'gofmt -w .'" + gofmt -l . + exit 1 + fi + + - name: Check imports (goimports) + run: | + if [ -n "$(goimports -l .)" ]; then + echo "Неверный импорт. Запустите 'goimports -w .'" + goimports -l . + exit 1 + fi + + - name: Lint (golangci-lint) + run: | + make lint + + - name: Build binary + run: | + mkdir -p bin + make build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6f07518..f268bd0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,230 +1,230 @@ -name: Release - -on: - push: - branches: [main] - -jobs: - release: - runs-on: ubuntu-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - tags: true - - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: '1.23.0' - - - name: Build auto-commit binary (Windows) - run: | - GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o ./bin/auto-commit-win . - upx --best --lzma ./bin/auto-commit-win - - - name: Build auto-commit binary (Linux) - run: | - sudo apt-get update && sudo apt-get install upx -y - go build -ldflags="-s -w" -trimpath -o ./bin/auto-commit . - upx --best --lzma ./bin/auto-commit - - - name: Set up Git - run: | - git config user.name "github-actions" - git config user.email "github-actions@github.com" - - - name: Get current date - id: date - run: echo "date=$(date +'%Y/%m/%d')" >> $GITHUB_OUTPUT - - - name: Get next version tag - id: version - run: | - latest=$(git tag --sort=-v:refname | grep '^v' | head -n 1) - echo "Последний тег: $latest" - - if [ -z "$latest" ]; then - version="v0.1.0" - else - raw_version=${latest#v} - major=$(echo "$raw_version" | cut -d. -f1) - minor=$(echo "$raw_version" | cut -d. -f2) - patch=$(echo "$raw_version" | cut -d. -f3) - - bug_count=0 - dependencies_count=0 - - issues=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - "https://api.github.com/repos/${{ github.repository }}/issues?state=closed&per_page=100") - - bug_count=$(echo "$issues" | jq '[.[] | select(.labels? != null) | select((.labels[]?.name // "") == "bug")] | length') - dependencies_count=$(echo "$issues" | jq '[.[] | select(.labels? != null) | select((.labels[]?.name // "") == "dependencies")] | length') - - if [ $bug_count -gt 0 ] || [ $dependencies_count -gt 0 ]; then - patch=$((patch + bug_count + dependencies_count)) - fi - - minor=$((minor + 1)) - version="v$major.$minor.$patch" - fi - - echo "version=$version" >> $GITHUB_OUTPUT - - - name: Create tag - run: | - git tag ${{ steps.version.outputs.version }} - git push origin ${{ steps.version.outputs.version }} - - - name: Generate changelog from merged PRs and closed issues - id: changelog - uses: actions/github-script@v7 - with: - script: | - const currentVersion = "${{ steps.version.outputs.version }}"; - const { data: releases } = await github.rest.repos.listReleases({ - owner: context.repo.owner, - repo: context.repo.repo, - }); - - const lastRelease = releases.find(r => !r.prerelease && r.tag_name !== currentVersion); - let since; - if (lastRelease) { - since = new Date(lastRelease.created_at).toISOString(); - } else { - since = "1970-01-01T00:00:00Z"; - } - - const { data: pulls } = await github.rest.pulls.list({ - owner: context.repo.owner, - repo: context.repo.repo, - state: "closed", - sort: "updated", - direction: "desc", - per_page: 100 - }); - const mergedPRs = pulls.filter(pr => pr.merged_at && pr.merged_at > since); - const prChangelog = mergedPRs.map(pr => `- ${pr.title} (#${pr.number})`).join("\n"); - - const { data: issues } = await github.rest.issues.listForRepo({ - owner: context.repo.owner, - repo: context.repo.repo, - state: "closed", - sort: "updated", - direction: "desc", - per_page: 100 - }); - - const closedIssues = issues.filter(issue => !issue.pull_request && new Date(issue.closed_at) > new Date(since)); - - const labelGroups = {}; - closedIssues.forEach(issue => { - if (issue.labels.length === 0) { - if (!labelGroups["Other"]) labelGroups["Other"] = []; - labelGroups["Other"].push(issue); - } else { - issue.labels.forEach(label => { - const name = label.name; - if (!labelGroups[name]) labelGroups[name] = []; - labelGroups[name].push(issue); - }); - } - }); - - let issueChangelogByLabel = ""; - const labelTitles = { - new: "## Enhancements", - bug: "## Bug Fixes", - git: "## Git", - Other: "## Other" - }; - - for (const [label, items] of Object.entries(labelGroups)) { - const title = labelTitles[label] || `## ${label.charAt(0).toUpperCase() + label.slice(1)}`; - const list = items.map(issue => `- ${issue.title} (#${issue.number})`).join("\n"); - issueChangelogByLabel += `${title}\n\n${list}\n\n`; - } - - core.setOutput("changelog_pr", prChangelog); - core.setOutput("changelog_issues_by_label", issueChangelogByLabel.trim()); - - - name: Create GitHub Release - uses: softprops/action-gh-release@v1 - with: - tag_name: ${{ steps.version.outputs.version }} - name: '${{ steps.version.outputs.version }}' - body: | - ## Git auto-commit - automatic commit generation tool - - > A new version of git-auto-commit is available `${{ steps.version.outputs.version }}`! A command-line utility that analyzes changes and automatically generates the name of the commit it. - - Git Auto-Commit is an extension for the Git version control system designed to automatically generate meaningful and context—sensitive commit messages based on changes made to the codebase. The tool simplifies developers' workflows by allowing them to focus on the content of edits rather than on the formulation of descriptions for commits. - - The development is conducted as an open source project and is distributed under the MIT license (or other compatible licensing, depending on the implementation). Git Auto-Commit can be integrated into CI/CD pipelines, hook scripts, or used manually via the command line. - - Main features: - - - Analysis of changes in the work tree and automatic generation of commit messages in natural language. - - Integration with Git via the `git auto` sub-command or configuration of user aliases. - - Support for templates and configurations for configuring the message structure in accordance with project standards (Conventional Commits, Semantic Commit Messages, etc.). - - Scalability: works both in small projects and in large monorepositories. - - ### Install - - #### If you're on windows - - Go to the root of the project and run the command. - - ```bash - iex ((New-Object Net.WebClient).DownloadString('https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-windows-auto-commit.ps1?raw=true')) - ``` - - #### If you're on linux - - Go to the root of the project and run the command. - - ```bash - curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-linux-auto-commit.sh?raw=true | bash - ``` - - ### Setting up - - #### Launch - - Everything is ready now, after making changes to the code, just run: - - ```bash - git add . - git auto - git push - ``` - - ${{ steps.changelog.outputs.changelog_issues_by_label }} - - ### Pull Requests - - ${{ steps.changelog.outputs.changelog_pr }} - - [©thefuture-industries](https://github.com/thefuture-industries) - files: | - ./bin/auto-commit - ./bin/auto-commit-win - ./scripts/install-linux-auto-commit.sh - ./scripts/install-windows-auto-commit.ps1 - ./scripts/update-windows-auto-commit.ps1 - ./scripts/update-linux-auto-commit.sh - - - name: Create new branch for next version - run: | - raw_version="${{ steps.version.outputs.version }}" - raw_version=${raw_version#v} - major=$(echo "$raw_version" | cut -d. -f1) - minor=$(echo "$raw_version" | cut -d. -f2) - - next_minor=$((minor + 1)) - next_version="v$major.$next_minor.x" - - git checkout -b "$next_version" - git push origin "$next_version" || git push origin "$next_version" +name: Release + +on: + push: + branches: [main] + +jobs: + release: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + tags: true + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.23.0' + + - name: Build auto-commit binary (Windows) + run: | + GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o ./bin/auto-commit-win . + upx --best --lzma ./bin/auto-commit-win + + - name: Build auto-commit binary (Linux) + run: | + sudo apt-get update && sudo apt-get install upx -y + go build -ldflags="-s -w" -trimpath -o ./bin/auto-commit . + upx --best --lzma ./bin/auto-commit + + - name: Set up Git + run: | + git config user.name "github-actions" + git config user.email "github-actions@github.com" + + - name: Get current date + id: date + run: echo "date=$(date +'%Y/%m/%d')" >> $GITHUB_OUTPUT + + - name: Get next version tag + id: version + run: | + latest=$(git tag --sort=-v:refname | grep '^v' | head -n 1) + echo "Последний тег: $latest" + + if [ -z "$latest" ]; then + version="v0.1.0" + else + raw_version=${latest#v} + major=$(echo "$raw_version" | cut -d. -f1) + minor=$(echo "$raw_version" | cut -d. -f2) + patch=$(echo "$raw_version" | cut -d. -f3) + + bug_count=0 + dependencies_count=0 + + issues=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + "https://api.github.com/repos/${{ github.repository }}/issues?state=closed&per_page=100") + + bug_count=$(echo "$issues" | jq '[.[] | select(.labels? != null) | select((.labels[]?.name // "") == "bug")] | length') + dependencies_count=$(echo "$issues" | jq '[.[] | select(.labels? != null) | select((.labels[]?.name // "") == "dependencies")] | length') + + if [ $bug_count -gt 0 ] || [ $dependencies_count -gt 0 ]; then + patch=$((patch + bug_count + dependencies_count)) + fi + + minor=$((minor + 1)) + version="v$major.$minor.$patch" + fi + + echo "version=$version" >> $GITHUB_OUTPUT + + - name: Create tag + run: | + git tag ${{ steps.version.outputs.version }} + git push origin ${{ steps.version.outputs.version }} + + - name: Generate changelog from merged PRs and closed issues + id: changelog + uses: actions/github-script@v7 + with: + script: | + const currentVersion = "${{ steps.version.outputs.version }}"; + const { data: releases } = await github.rest.repos.listReleases({ + owner: context.repo.owner, + repo: context.repo.repo, + }); + + const lastRelease = releases.find(r => !r.prerelease && r.tag_name !== currentVersion); + let since; + if (lastRelease) { + since = new Date(lastRelease.created_at).toISOString(); + } else { + since = "1970-01-01T00:00:00Z"; + } + + const { data: pulls } = await github.rest.pulls.list({ + owner: context.repo.owner, + repo: context.repo.repo, + state: "closed", + sort: "updated", + direction: "desc", + per_page: 100 + }); + const mergedPRs = pulls.filter(pr => pr.merged_at && pr.merged_at > since); + const prChangelog = mergedPRs.map(pr => `- ${pr.title} (#${pr.number})`).join("\n"); + + const { data: issues } = await github.rest.issues.listForRepo({ + owner: context.repo.owner, + repo: context.repo.repo, + state: "closed", + sort: "updated", + direction: "desc", + per_page: 100 + }); + + const closedIssues = issues.filter(issue => !issue.pull_request && new Date(issue.closed_at) > new Date(since)); + + const labelGroups = {}; + closedIssues.forEach(issue => { + if (issue.labels.length === 0) { + if (!labelGroups["Other"]) labelGroups["Other"] = []; + labelGroups["Other"].push(issue); + } else { + issue.labels.forEach(label => { + const name = label.name; + if (!labelGroups[name]) labelGroups[name] = []; + labelGroups[name].push(issue); + }); + } + }); + + let issueChangelogByLabel = ""; + const labelTitles = { + new: "## Enhancements", + bug: "## Bug Fixes", + git: "## Git", + Other: "## Other" + }; + + for (const [label, items] of Object.entries(labelGroups)) { + const title = labelTitles[label] || `## ${label.charAt(0).toUpperCase() + label.slice(1)}`; + const list = items.map(issue => `- ${issue.title} (#${issue.number})`).join("\n"); + issueChangelogByLabel += `${title}\n\n${list}\n\n`; + } + + core.setOutput("changelog_pr", prChangelog); + core.setOutput("changelog_issues_by_label", issueChangelogByLabel.trim()); + + - name: Create GitHub Release + uses: softprops/action-gh-release@v1 + with: + tag_name: ${{ steps.version.outputs.version }} + name: '${{ steps.version.outputs.version }}' + body: | + ## Git auto-commit - automatic commit generation tool + + > A new version of git-auto-commit is available `${{ steps.version.outputs.version }}`! A command-line utility that analyzes changes and automatically generates the name of the commit it. + + Git Auto-Commit is an extension for the Git version control system designed to automatically generate meaningful and context—sensitive commit messages based on changes made to the codebase. The tool simplifies developers' workflows by allowing them to focus on the content of edits rather than on the formulation of descriptions for commits. + + The development is conducted as an open source project and is distributed under the MIT license (or other compatible licensing, depending on the implementation). Git Auto-Commit can be integrated into CI/CD pipelines, hook scripts, or used manually via the command line. + + Main features: + + - Analysis of changes in the work tree and automatic generation of commit messages in natural language. + - Integration with Git via the `git auto` sub-command or configuration of user aliases. + - Support for templates and configurations for configuring the message structure in accordance with project standards (Conventional Commits, Semantic Commit Messages, etc.). + - Scalability: works both in small projects and in large monorepositories. + + ### Install + + #### If you're on windows + + Go to the root of the project and run the command. + + ```bash + iex ((New-Object Net.WebClient).DownloadString('https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-windows-auto-commit.ps1?raw=true')) + ``` + + #### If you're on linux + + Go to the root of the project and run the command. + + ```bash + curl -fsSL https://github.com/thefuture-industries/git-auto-commit/blob/main/scripts/install-linux-auto-commit.sh?raw=true | bash + ``` + + ### Setting up + + #### Launch + + Everything is ready now, after making changes to the code, just run: + + ```bash + git add . + git auto + git push + ``` + + ${{ steps.changelog.outputs.changelog_issues_by_label }} + + ### Pull Requests + + ${{ steps.changelog.outputs.changelog_pr }} + + [©thefuture-industries](https://github.com/thefuture-industries) + files: | + ./bin/auto-commit + ./bin/auto-commit-win + ./scripts/install-linux-auto-commit.sh + ./scripts/install-windows-auto-commit.ps1 + ./scripts/update-windows-auto-commit.ps1 + ./scripts/update-linux-auto-commit.sh + + - name: Create new branch for next version + run: | + raw_version="${{ steps.version.outputs.version }}" + raw_version=${raw_version#v} + major=$(echo "$raw_version" | cut -d. -f1) + minor=$(echo "$raw_version" | cut -d. -f2) + + next_minor=$((minor + 1)) + next_version="v$major.$next_minor.x" + + git checkout -b "$next_version" + git push origin "$next_version" || git push origin "$next_version" diff --git a/.gitignore b/.gitignore index a117e26..4e4178f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,36 +1,36 @@ -*+ -/config.mak -/autom4te.cache -/config.cache -/config.log -/config.status -/config.mak.autogen -/config.mak.append -/configure -/.vscode/ -/tags -/TAGS -/cscope* -/compile_commands.json -/.cache/ -*.hcc -*.obj -*.lib -*.sln -*.sp -*.suo -*.ncb -*.vcproj -*.user -*.idb -*.pdb -*.ilk -*.iobj -*.ipdb -*.dll -.vs/ -Debug/ -Release/ -*.exe -bindir/ -bin/ +*+ +/config.mak +/autom4te.cache +/config.cache +/config.log +/config.status +/config.mak.autogen +/config.mak.append +/configure +/.vscode/ +/tags +/TAGS +/cscope* +/compile_commands.json +/.cache/ +*.hcc +*.obj +*.lib +*.sln +*.sp +*.suo +*.ncb +*.vcproj +*.user +*.idb +*.pdb +*.ilk +*.iobj +*.ipdb +*.dll +.vs/ +Debug/ +Release/ +*.exe +bindir/ +bin/ diff --git a/.husky/pre-push b/.husky/pre-push index 6a35828..8ab59e8 100644 --- a/.husky/pre-push +++ b/.husky/pre-push @@ -1,16 +1,16 @@ -#!/bin/sh -set -e - -REPO_ROOT=$(git rev-parse --show-toplevel) - -echo "Running pre-push hook..." - -cd "$REPO_ROOT" -make fmt -make lint -make check - -git add . -# git commit -m "build 'binary file' for release/push bin/auto-commit" - -echo "[+] Success pre-push!" +#!/bin/sh +set -e + +REPO_ROOT=$(git rev-parse --show-toplevel) + +echo "Running pre-push hook..." + +cd "$REPO_ROOT" +make fmt +make lint +make check + +git add . +# git commit -m "build 'binary file' for release/push bin/auto-commit" + +echo "[+] Success pre-push!" diff --git a/.prettierrc b/.prettierrc index b417ca6..e4f39be 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,9 +1,9 @@ -{ - "tabWidth": 4, - "useTabs": true, - "semi": true, - "singleQuote": true, - "trailingComma": "es5", - "bracketSpacing": true, - "endOfLine": "auto" -} +{ + "tabWidth": 4, + "useTabs": true, + "semi": true, + "singleQuote": true, + "trailingComma": "es5", + "bracketSpacing": true, + "endOfLine": "auto" +} 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..5e58cb1 100644 --- a/Makefile +++ b/Makefile @@ -1,34 +1,35 @@ -.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 + +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 diff --git a/README.md b/README.md index 4f4f744..af5f600 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,52 @@ -# 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) +``` + +## 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" - - ![image](https://user-images.githubusercontent.com/45884264/217041010-8fd6b96b-329d-4d8e-8838-9b5bf4e1a78d.png) -- 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" + - ![image](https://user-images.githubusercontent.com/45884264/217041010-8fd6b96b-329d-4d8e-8838-9b5bf4e1a78d.png) +- 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/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/scripts/install-linux-auto-commit.sh b/scripts/install-linux-auto-commit.sh index 69fdbc9..67d4279 100644 --- a/scripts/install-linux-auto-commit.sh +++ b/scripts/install-linux-auto-commit.sh @@ -1,58 +1,58 @@ -#!/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/') + +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 diff --git a/scripts/install-windows-auto-commit.ps1 b/scripts/install-windows-auto-commit.ps1 index d132199..494d0d9 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-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 +} diff --git a/scripts/update-windows-auto-commit.ps1 b/scripts/update-windows-auto-commit.ps1 index 534733a..8fd22b0 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-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) diff --git a/vercel.json b/vercel.json index f8f5ec0..ca9179f 100644 --- a/vercel.json +++ b/vercel.json @@ -1,14 +1,14 @@ -{ - "builds": [ - { - "src": "www/**/*", - "use": "@vercel/static" - } - ], - "routes": [ - { - "src": "/(.*)", - "dest": "/www/$1" - } - ] -} +{ + "builds": [ + { + "src": "www/**/*", + "use": "@vercel/static" + } + ], + "routes": [ + { + "src": "/(.*)", + "dest": "/www/$1" + } + ] +} diff --git a/www/index.html b/www/index.html index 46c006b..9439637 100644 --- a/www/index.html +++ b/www/index.html @@ -1,174 +1,174 @@ - - - - - - Git Auto-Commit - The Future Industries - - - - - - - - - - - - - - - - -
-

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 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: -

-
-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: -

-
-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
- -
- Distributed under the MIT License • © 2025 The Future - Industries -
-
- - - - + + + + + + Git Auto-Commit - The Future Industries + + + + + + + + + + + + + + + + +
+

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 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: +

+
+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: +

+
+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
+ +
+ Distributed under the MIT License • © 2025 The Future + Industries +
+
+ + + + From 8d9632613e192468b79074f6ea9f843342a35e49 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sat, 9 Aug 2025 15:33:12 -0400 Subject: [PATCH 02/20] changed architecture git-auto-commit and worked in v3 --- .husky/pre-push | 16 ----- {www => Help/www}/index.html | 0 Makefile | 26 ++++++-- acpkg/acpkg-comment.go | 1 - ac/ac.go => autocommit/autocommit.go | 18 +++-- .../autocommitupdate.go | 31 ++------- .../autocommitversion.go | 8 +-- .../autocommitwatcher.go | 17 +++-- main.go => cmd/main.go | 15 ++--- infra/constants/auto-commit.go | 10 +++ .../define.go => infra/constants/github.go | 7 -- infra/gtypes/types.go | 1 + {achelper => infra}/logger/logger.go | 0 pkg/code/comment.go | 1 + .../acpkg-function.go => pkg/code/function.go | 65 +++++++++---------- acpkg/acpkg-import.go => pkg/code/import.go | 4 +- acpkg/acpkg-logic.go => pkg/code/logic.go | 17 +++-- acpkg/acpkg-oop.go => pkg/code/oop.go | 31 +++++---- acpkg/acpkg-remote.go => pkg/code/remote.go | 4 +- .../code/structure.go | 27 ++++---- {types => pkg/code}/types.go | 37 +++++------ .../code/variables.go | 23 ++++--- files.go => pkg/file/download.go | 19 +++++- {git => pkg/git}/commit.go | 2 +- {diff => pkg/git}/diff.go | 6 +- {git => pkg/git}/git.go | 0 {git => pkg/git}/issues.go | 3 +- pkg/git/types.go | 6 ++ .../code/detected.go => pkg/language/main.go | 2 +- {parser => pkg}/parser.go | 36 +++++----- tests/ac_test.go | 25 ++++--- tests/af_go_test.go | 48 +++++++------- tests/af_ts_test.go | 48 +++++++------- tests/ai_go_test.go | 30 ++++----- tests/av_go_test.go | 42 ++++++------ tests/av_ts_test.go | 36 +++++----- tests/test.g.go | 20 +++--- vercel.json | 4 +- 38 files changed, 335 insertions(+), 351 deletions(-) delete mode 100644 .husky/pre-push rename {www => Help/www}/index.html (100%) delete mode 100644 acpkg/acpkg-comment.go rename ac/ac.go => autocommit/autocommit.go (62%) rename achelper/update.go => autocommit/autocommitupdate.go (82%) rename achelper/version.go => autocommit/autocommitversion.go (91%) rename achelper/watcher.go => autocommit/autocommitwatcher.go (86%) rename main.go => cmd/main.go (69%) create mode 100644 infra/constants/auto-commit.go rename constants/define.go => infra/constants/github.go (59%) create mode 100644 infra/gtypes/types.go rename {achelper => infra}/logger/logger.go (100%) create mode 100644 pkg/code/comment.go rename acpkg/acpkg-function.go => pkg/code/function.go (72%) rename acpkg/acpkg-import.go => pkg/code/import.go (98%) rename acpkg/acpkg-logic.go => pkg/code/logic.go (94%) rename acpkg/acpkg-oop.go => pkg/code/oop.go (83%) rename acpkg/acpkg-remote.go => pkg/code/remote.go (96%) rename acpkg/acpkg-structure.go => pkg/code/structure.go (92%) rename {types => pkg/code}/types.go (85%) rename acpkg/acpkg-variables.go => pkg/code/variables.go (81%) rename files.go => pkg/file/download.go (81%) rename {git => pkg/git}/commit.go (88%) rename {diff => pkg/git}/diff.go (94%) rename {git => pkg/git}/git.go (100%) rename {git => pkg/git}/issues.go (96%) create mode 100644 pkg/git/types.go rename achelper/code/detected.go => pkg/language/main.go (97%) rename {parser => pkg}/parser.go (75%) diff --git a/.husky/pre-push b/.husky/pre-push deleted file mode 100644 index 8ab59e8..0000000 --- a/.husky/pre-push +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -set -e - -REPO_ROOT=$(git rev-parse --show-toplevel) - -echo "Running pre-push hook..." - -cd "$REPO_ROOT" -make fmt -make lint -make check - -git add . -# git commit -m "build 'binary file' for release/push bin/auto-commit" - -echo "[+] Success pre-push!" diff --git a/www/index.html b/Help/www/index.html similarity index 100% rename from www/index.html rename to Help/www/index.html diff --git a/Makefile b/Makefile index 5e58cb1..1e23b72 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,15 @@ .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 . @@ -12,21 +22,23 @@ check: fmt lint test build: @echo "Running build..." - @go build -o bin/auto-commit . + @go build -o $(BIN) ./cmd buildrelease: @echo "Running release build (windows, linux)..." - @go build -ldflags="-s -w" -trimpath -o bin/auto-commit . - @upx.exe --best --lzma bin/auto-commit + # windows + @GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit ./cmd + upx.exe --best --lzma bin/auto-commit || true - @GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-linux . - @upx.exe --best --lzma bin/auto-commit-linux + # linux + @GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-linux ./cmd + upx --best --lzma bin/auto-commit-linux || true 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 + @go build -ldflags="-s -w" -trimpath -o $(BIN).update ./cmd + $(UPX) --best --lzma $(BIN).update || true test: @go test -v ./... 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/ac/ac.go b/autocommit/autocommit.go similarity index 62% rename from ac/ac.go rename to autocommit/autocommit.go index ff860d8..ea808f5 100644 --- a/ac/ac.go +++ b/autocommit/autocommit.go @@ -1,18 +1,16 @@ -package ac +package autocommit import ( "fmt" - "git-auto-commit/achelper" - "git-auto-commit/achelper/logger" - "git-auto-commit/diff" - "git-auto-commit/git" - "git-auto-commit/parser" + "git-auto-commit/infra/logger" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" ) func AutoCommit() { - achelper.GetVersion(false) + GetVersion(false) - files, err := diff.GetStagedFiles() + files, err := git.GetStagedFiles() if err != nil { logger.ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error())) return @@ -23,7 +21,7 @@ func AutoCommit() { return } - parserMsg, err := parser.Parser(files) + parserMsg, err := pkg.Parser(files) if err != nil { logger.ErrorLogger(err) return @@ -33,4 +31,4 @@ func AutoCommit() { logger.ErrorLogger(fmt.Errorf("error committing: %s", err.Error())) return } -} +} \ No newline at end of file diff --git a/achelper/update.go b/autocommit/autocommitupdate.go similarity index 82% rename from achelper/update.go rename to autocommit/autocommitupdate.go index 90074fd..d83ebd3 100644 --- a/achelper/update.go +++ b/autocommit/autocommitupdate.go @@ -1,12 +1,12 @@ -package achelper +package autocommit 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" + "git-auto-commit/pkg/git" "net/http" "os" "os/exec" @@ -15,7 +15,7 @@ import ( "strings" ) -func AutoCommitUpdate() { +func Update() { root, err := git.GetGitRoot() if err != nil { logger.ErrorLogger(err) @@ -63,7 +63,7 @@ func AutoCommitUpdate() { } 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 +85,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/autocommit/autocommitversion.go similarity index 91% rename from achelper/version.go rename to autocommit/autocommitversion.go index 9c87b59..a105351 100644 --- a/achelper/version.go +++ b/autocommit/autocommitversion.go @@ -1,11 +1,11 @@ -package achelper +package autocommit 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" + "git-auto-commit/pkg/git" "net/http" "os" "path/filepath" diff --git a/achelper/watcher.go b/autocommit/autocommitwatcher.go similarity index 86% rename from achelper/watcher.go rename to autocommit/autocommitwatcher.go index b7dbd51..29155fe 100644 --- a/achelper/watcher.go +++ b/autocommit/autocommitwatcher.go @@ -1,12 +1,11 @@ -package achelper +package autocommit import ( "fmt" - "git-auto-commit/achelper/logger" - "git-auto-commit/constants" - "git-auto-commit/diff" - "git-auto-commit/git" - "git-auto-commit/parser" + "git-auto-commit/infra/constants" + "git-auto-commit/infra/logger" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" "os" "os/exec" "os/signal" @@ -18,7 +17,7 @@ import ( "github.com/fsnotify/fsnotify" ) -func WatchCommit(path string) { +func Watch(path string) { GetVersion(false) watcher, err := fsnotify.NewWatcher() @@ -70,7 +69,7 @@ func WatchCommit(path string) { return } - files, err := diff.GetStagedFiles() + files, err := git.GetStagedFiles() if err != nil { logger.ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error())) return @@ -80,7 +79,7 @@ func WatchCommit(path string) { logger.InfoLogger("No files staged for commit.") } - parser, err := parser.Parser(files) + parser, err := pkg.Parser(files) if err != nil { logger.ErrorLogger(err) return diff --git a/main.go b/cmd/main.go similarity index 69% rename from main.go rename to cmd/main.go index 0db4f56..4fd8a38 100644 --- a/main.go +++ b/cmd/main.go @@ -2,10 +2,9 @@ package main import ( "fmt" - "git-auto-commit/ac" - "git-auto-commit/achelper" - "git-auto-commit/achelper/logger" - "git-auto-commit/git" + "git-auto-commit/autocommit" + "git-auto-commit/infra/logger" + "git-auto-commit/pkg/git" "os" ) @@ -21,12 +20,12 @@ func main() { path = fmt.Sprintf("%s/%s", path, os.Args[2]) } - achelper.WatchCommit(path) + autocommit.Watch(path) } else if len(os.Args) > 1 && (os.Args[1] == "-v" || os.Args[1] == "--version") { - achelper.GetVersion(true) + autocommit.GetVersion(true) } else if len(os.Args) > 1 && (os.Args[1] == "-u" || os.Args[1] == "--update") { - achelper.AutoCommitUpdate() + autocommit.Update() } else { - ac.AutoCommit() + autocommit.AutoCommit() } } 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/constants/define.go b/infra/constants/github.go similarity index 59% rename from constants/define.go rename to infra/constants/github.go index ec6ec58..b027086 100644 --- a/constants/define.go +++ b/infra/constants/github.go @@ -1,13 +1,6 @@ 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" diff --git a/infra/gtypes/types.go b/infra/gtypes/types.go new file mode 100644 index 0000000..b01bb44 --- /dev/null +++ b/infra/gtypes/types.go @@ -0,0 +1 @@ +package gtypes \ No newline at end of file diff --git a/achelper/logger/logger.go b/infra/logger/logger.go similarity index 100% rename from achelper/logger/logger.go rename to infra/logger/logger.go 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-function.go b/pkg/code/function.go similarity index 72% rename from acpkg/acpkg-function.go rename to pkg/code/function.go index 64fff20..9751d05 100644 --- a/acpkg/acpkg-function.go +++ b/pkg/code/function.go @@ -1,8 +1,7 @@ -package acpkg +package code import ( - "git-auto-commit/constants" - "git-auto-commit/types" + "git-auto-commit/infra/constants" "regexp" "strings" ) @@ -16,7 +15,7 @@ var ( functionRegexCSharp = regexp.MustCompile(`(public|private|protected|internal)?\s*(static)?\s*(\w+)\s+(\w+)\s*\(([^)]*)\)`) ) -func ParseToStructureFunction(line, lang string) *types.FunctionSignature { +func ParseToStructureFunction(line, lang string) *FunctionSignature { switch lang { case "go": return parseGoFunction(line) @@ -35,7 +34,7 @@ func ParseToStructureFunction(line, lang string) *types.FunctionSignature { func FormattedFunction(diff, lang string) string { var addedFuncs, deletedFuncs, renamedFuncs, changedParams, changedTypes []string - var oldFunc, newFunc *types.FunctionSignature + var oldFunc, newFunc *FunctionSignature lines := strings.Split(diff, "\n") for i := 0; i < len(lines); i++ { @@ -134,7 +133,7 @@ func FormattedFunction(diff, lang string) string { return parser } -func parseGoFunction(line string) *types.FunctionSignature { +func parseGoFunction(line string) *FunctionSignature { m := functionRegexGo.FindStringSubmatch(line) if m == nil { return nil @@ -142,7 +141,7 @@ func parseGoFunction(line string) *types.FunctionSignature { name := m[1] paramsString := m[2] - params := []types.FunctionParameters{} + params := []FunctionParameters{} for _, p := range strings.Split(paramsString, ",") { p = strings.TrimSpace(p) @@ -152,21 +151,21 @@ func parseGoFunction(line string) *types.FunctionSignature { parts := strings.Fields(p) if len(parts) == 2 { - params = append(params, types.FunctionParameters{Name: parts[0], Type: parts[1]}) + params = append(params, FunctionParameters{Name: parts[0], Type: parts[1]}) } } - return &types.FunctionSignature{Name: name, Params: params} + return &FunctionSignature{Name: name, Params: params} } -func parsePythonFunction(line string) *types.FunctionSignature { +func parsePythonFunction(line string) *FunctionSignature { m := functionRegexPython.FindStringSubmatch(line) if m == nil { return nil } name := m[1] - params := []types.FunctionParameters{} + params := []FunctionParameters{} for _, p := range strings.Split(m[2], ",") { p = strings.TrimSpace(p) @@ -176,16 +175,16 @@ func parsePythonFunction(line string) *types.FunctionSignature { parts := strings.Split(p, ":") if len(parts) == 2 { - params = append(params, types.FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) + params = append(params, FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) } else { - params = append(params, types.FunctionParameters{Name: p, Type: ""}) + params = append(params, FunctionParameters{Name: p, Type: ""}) } } - return &types.FunctionSignature{Name: name, Params: params} + return &FunctionSignature{Name: name, Params: params} } -func parseTSJSFunction(line string) *types.FunctionSignature { +func parseTSJSFunction(line string) *FunctionSignature { m := functionRegexTSJS.FindStringSubmatch(line) if m != nil { name := m[1] @@ -194,7 +193,7 @@ func parseTSJSFunction(line string) *types.FunctionSignature { returnType = m[4] } - params := []types.FunctionParameters{} + params := []FunctionParameters{} for _, p := range strings.Split(m[2], ",") { p = strings.TrimSpace(p) if p == "" { @@ -203,20 +202,20 @@ func parseTSJSFunction(line string) *types.FunctionSignature { parts := strings.Split(p, ":") if len(parts) == 2 { - params = append(params, types.FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) + params = append(params, FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) } else { - params = append(params, types.FunctionParameters{Name: p, Type: ""}) + params = append(params, FunctionParameters{Name: p, Type: ""}) } } - return &types.FunctionSignature{Name: name, Params: params, ReturnType: returnType} + return &FunctionSignature{Name: name, Params: params, ReturnType: returnType} } m = functionRegexTSJSConst.FindStringSubmatch(line) if m != nil { name := m[2] - params := []types.FunctionParameters{} + params := []FunctionParameters{} for _, p := range strings.Split(m[3], ",") { p = strings.TrimSpace(p) if p == "" { @@ -225,19 +224,19 @@ func parseTSJSFunction(line string) *types.FunctionSignature { parts := strings.Split(p, ":") if len(parts) == 2 { - params = append(params, types.FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) + params = append(params, FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) } else { - params = append(params, types.FunctionParameters{Name: p, Type: ""}) + params = append(params, FunctionParameters{Name: p, Type: ""}) } } - return &types.FunctionSignature{Name: name, Params: params, ReturnType: ""} + return &FunctionSignature{Name: name, Params: params, ReturnType: ""} } return nil } -func parseCJavaFunction(line string) *types.FunctionSignature { +func parseCJavaFunction(line string) *FunctionSignature { m := functionRegexCJava.FindStringSubmatch(line) if m == nil { return nil @@ -246,7 +245,7 @@ func parseCJavaFunction(line string) *types.FunctionSignature { returnType := m[1] name := m[2] - params := []types.FunctionParameters{} + params := []FunctionParameters{} for _, p := range strings.Split(m[3], ",") { p = strings.TrimSpace(p) if p == "" { @@ -255,23 +254,23 @@ func parseCJavaFunction(line string) *types.FunctionSignature { parts := strings.Fields(p) if len(parts) == 2 { - params = append(params, types.FunctionParameters{Name: parts[1], Type: parts[0]}) + params = append(params, FunctionParameters{Name: parts[1], Type: parts[0]}) } else if len(parts) == 1 { - params = append(params, types.FunctionParameters{Name: parts[0], Type: ""}) + params = append(params, FunctionParameters{Name: parts[0], Type: ""}) } } - return &types.FunctionSignature{Name: name, Params: params, ReturnType: returnType} + return &FunctionSignature{Name: name, Params: params, ReturnType: returnType} } -func parseCSharpFunction(line string) *types.FunctionSignature { +func parseCSharpFunction(line string) *FunctionSignature { m := functionRegexCSharp.FindStringSubmatch(line) if m == nil { return nil } name := m[4] - params := []types.FunctionParameters{} + params := []FunctionParameters{} for _, p := range strings.Split(m[5], ",") { p = strings.TrimSpace(p) if p == "" { @@ -280,11 +279,11 @@ func parseCSharpFunction(line string) *types.FunctionSignature { parts := strings.Fields(p) if len(parts) == 2 { - params = append(params, types.FunctionParameters{Name: parts[1], Type: parts[0]}) + params = append(params, FunctionParameters{Name: parts[1], Type: parts[0]}) } else if len(parts) == 1 { - params = append(params, types.FunctionParameters{Name: parts[0], Type: ""}) + params = append(params, FunctionParameters{Name: parts[0], Type: ""}) } } - return &types.FunctionSignature{Name: name, Params: params, ReturnType: m[3]} + return &FunctionSignature{Name: name, Params: params, ReturnType: m[3]} } diff --git a/acpkg/acpkg-import.go b/pkg/code/import.go similarity index 98% rename from acpkg/acpkg-import.go rename to pkg/code/import.go index 26f8413..cd88cf2 100644 --- a/acpkg/acpkg-import.go +++ b/pkg/code/import.go @@ -1,7 +1,7 @@ -package acpkg +package code import ( - "git-auto-commit/constants" + "git-auto-commit/infra/constants" "regexp" "strings" ) diff --git a/acpkg/acpkg-logic.go b/pkg/code/logic.go similarity index 94% rename from acpkg/acpkg-logic.go rename to pkg/code/logic.go index a190409..9d0565b 100644 --- a/acpkg/acpkg-logic.go +++ b/pkg/code/logic.go @@ -1,14 +1,13 @@ -package acpkg +package code import ( - "git-auto-commit/constants" - "git-auto-commit/types" + "git-auto-commit/infra/constants" "regexp" "strings" ) -func extractSwitchBlocks(lines []string, lang string, isNew bool) []types.SwitchSignature { - var blocks []types.SwitchSignature +func extractSwitchBlocks(lines []string, lang string, isNew bool) []SwitchSignature { + var blocks []SwitchSignature var switchRegex, caseRegex *regexp.Regexp switch lang { @@ -60,7 +59,7 @@ func extractSwitchBlocks(lines []string, lang string, isNew bool) []types.Switch } } - blocks = append(blocks, types.SwitchSignature{Expr: expr, Cases: cases}) + blocks = append(blocks, SwitchSignature{Expr: expr, Cases: cases}) } } } @@ -178,7 +177,7 @@ func FormattedLogic(line, lang, filename string) string { } if len(oldSwitches) > 0 && len(newSwitches) == 0 { - makeResult := func(switches []types.SwitchSignature) string { + makeResult := func(switches []SwitchSignature) string { var b strings.Builder b.WriteString("removed switch on ") for i, sw := range switches { @@ -209,7 +208,7 @@ func FormattedLogic(line, lang, filename string) string { } if len(newSwitches) > 0 && len(oldSwitches) == 0 { - makeResult := func(switches []types.SwitchSignature) string { + makeResult := func(switches []SwitchSignature) string { var b strings.Builder b.WriteString("added switch on ") for i, sw := range switches { @@ -243,7 +242,7 @@ func FormattedLogic(line, lang, filename string) string { osw := oldSwitches[0] nsw := newSwitches[0] - makeResult := func(osw, nsw types.SwitchSignature) string { + makeResult := func(osw, nsw SwitchSignature) string { var b strings.Builder b.WriteString("changed switch from '") b.WriteString(osw.Expr) diff --git a/acpkg/acpkg-oop.go b/pkg/code/oop.go similarity index 83% rename from acpkg/acpkg-oop.go rename to pkg/code/oop.go index 9cd7536..239d2f8 100644 --- a/acpkg/acpkg-oop.go +++ b/pkg/code/oop.go @@ -1,7 +1,6 @@ -package acpkg +package code import ( - "git-auto-commit/types" "regexp" "strings" ) @@ -15,7 +14,7 @@ var ( classRegexJava = regexp.MustCompile(`(?:public\\s+)?class\\s+(\\w+)(?:\\s+extends\\s+(\\w+))?`) ) -func ParseToStructureClass(line, lang string) *types.ClassSignature { +func ParseToStructureClass(line, lang string) *ClassSignature { switch lang { case "typescript", "javascript": return parseTSJSClass(line) @@ -34,7 +33,7 @@ func ParseToStructureClass(line, lang string) *types.ClassSignature { } } -func parseTSJSClass(line string) *types.ClassSignature { +func parseTSJSClass(line string) *ClassSignature { m := classRegexTSJS.FindStringSubmatch(line) //nolint if m == nil || len(m) < 2 { @@ -48,10 +47,10 @@ func parseTSJSClass(line string) *types.ClassSignature { } methods := parseAccessModifiers(line, "(public|private|protected)\\s+(\\w+)\\s*\\(") - return &types.ClassSignature{Name: name, Parent: parent, Methods: methods} + return &ClassSignature{Name: name, Parent: parent, Methods: methods} } -func parsePythonClass(line string) *types.ClassSignature { +func parsePythonClass(line string) *ClassSignature { m := classRegexPython.FindStringSubmatch(line) if m == nil { return nil @@ -79,10 +78,10 @@ func parsePythonClass(line string) *types.ClassSignature { } } - return &types.ClassSignature{Name: name, Parent: parent, Methods: methods} + return &ClassSignature{Name: name, Parent: parent, Methods: methods} } -func parseCppClass(line string) *types.ClassSignature { +func parseCppClass(line string) *ClassSignature { m := classRegexCpp.FindStringSubmatch(line) if m == nil { return nil @@ -95,10 +94,10 @@ func parseCppClass(line string) *types.ClassSignature { } methods := parseAccessModifiers(line, "(public|private|protected):\\s*\\w+\\s+(\\w+)\\s*\\(") - return &types.ClassSignature{Name: name, Parent: parent, Methods: methods} + return &ClassSignature{Name: name, Parent: parent, Methods: methods} } -func parseCSharpClass(line string) *types.ClassSignature { +func parseCSharpClass(line string) *ClassSignature { m := classRegexCSharp.FindStringSubmatch(line) if m == nil { return nil @@ -111,20 +110,20 @@ func parseCSharpClass(line string) *types.ClassSignature { } methods := parseAccessModifiers(line, "(public|private|protected|internal)\\s+\\w+\\s+(\\w+)\\s*\\(") - return &types.ClassSignature{Name: name, Parent: parent, Methods: methods} + return &ClassSignature{Name: name, Parent: parent, Methods: methods} } -func parseGoStruct(line string) *types.ClassSignature { +func parseGoStruct(line string) *ClassSignature { m := classRegexGo.FindStringSubmatch(line) if m == nil { return nil } name := m[1] - return &types.ClassSignature{Name: name, Parent: "", Methods: make(map[string]string)} + return &ClassSignature{Name: name, Parent: "", Methods: make(map[string]string)} } -func parseJavaClass(line string) *types.ClassSignature { +func parseJavaClass(line string) *ClassSignature { m := classRegexJava.FindStringSubmatch(line) if m == nil { return nil @@ -137,7 +136,7 @@ func parseJavaClass(line string) *types.ClassSignature { } methods := parseAccessModifiers(line, "(public|private|protected)\\s+(\\w+)\\s*\\(") - return &types.ClassSignature{Name: name, Parent: parent, Methods: methods} + return &ClassSignature{Name: name, Parent: parent, Methods: methods} } func parseAccessModifiers(line, regex string) map[string]string { @@ -155,7 +154,7 @@ func parseAccessModifiers(line, regex string) map[string]string { } func FormattedClass(diff, lang string) string { - var oldClass, newClass *types.ClassSignature + var oldClass, newClass *ClassSignature var builder strings.Builder var oldLines, newLines []string diff --git a/acpkg/acpkg-remote.go b/pkg/code/remote.go similarity index 96% rename from acpkg/acpkg-remote.go rename to pkg/code/remote.go index f481fac..1d28b96 100644 --- a/acpkg/acpkg-remote.go +++ b/pkg/code/remote.go @@ -1,7 +1,7 @@ -package acpkg +package code import ( - "git-auto-commit/git" + "git-auto-commit/pkg/git" "strconv" "strings" ) diff --git a/acpkg/acpkg-structure.go b/pkg/code/structure.go similarity index 92% rename from acpkg/acpkg-structure.go rename to pkg/code/structure.go index 7a170fc..1545d76 100644 --- a/acpkg/acpkg-structure.go +++ b/pkg/code/structure.go @@ -1,12 +1,11 @@ -package acpkg +package code import ( - "git-auto-commit/types" "regexp" "strings" ) -func parseStruct(line, lang string) *types.StructureSignature { +func parseStruct(line, lang string) *StructureSignature { var structRegex *regexp.Regexp switch lang { @@ -27,10 +26,10 @@ func parseStruct(line, lang string) *types.StructureSignature { return nil } - return &types.StructureSignature{Name: m[1]} + return &StructureSignature{Name: m[1]} } -func parseType(line, lang string) *types.TypeSignature { +func parseType(line, lang string) *TypeSignature { var typeRegex *regexp.Regexp switch lang { case "go": @@ -48,10 +47,10 @@ func parseType(line, lang string) *types.TypeSignature { return nil } - return &types.TypeSignature{Name: m[1]} + return &TypeSignature{Name: m[1]} } -func parseInterface(line, lang string) *types.InterfaceSignature { +func parseInterface(line, lang string) *InterfaceSignature { var interfaceRegex *regexp.Regexp switch lang { case "go": @@ -67,10 +66,10 @@ func parseInterface(line, lang string) *types.InterfaceSignature { return nil } - return &types.InterfaceSignature{Name: m[1]} + return &InterfaceSignature{Name: m[1]} } -func parseEnum(line, lang string) *types.EnumSignature { +func parseEnum(line, lang string) *EnumSignature { var enumRegex *regexp.Regexp switch lang { case "typescript", "java", "csharp", "cpp", "c": @@ -84,11 +83,11 @@ func parseEnum(line, lang string) *types.EnumSignature { return nil } - return &types.EnumSignature{Name: m[1]} + return &EnumSignature{Name: m[1]} } func FormattedStruct(diff, lang string) string { - var oldStruct, newStruct *types.StructureSignature + var oldStruct, newStruct *StructureSignature var addedStruct, deletedStruct, renamedStruct []string var oldLines, newLines []string @@ -153,7 +152,7 @@ func FormattedStruct(diff, lang string) string { } func FormattedType(diff, lang string) string { - var oldType, newType *types.TypeSignature + var oldType, newType *TypeSignature var addedType, deletedType, renamedType []string var oldLines, newLines []string @@ -218,7 +217,7 @@ func FormattedType(diff, lang string) string { } func FormattedInterface(diff, lang string) string { - var oldInterface, newInterface *types.InterfaceSignature + var oldInterface, newInterface *InterfaceSignature var addedInterface, deletedInterface, renamedInterface []string var oldLines, newLines []string @@ -283,7 +282,7 @@ func FormattedInterface(diff, lang string) string { } func FormattedEnum(diff, lang string) string { - var oldEnum, newEnum *types.EnumSignature + var oldEnum, newEnum *EnumSignature var addedEnum, deletedEnum, renamedEnum []string var oldLines, newLines []string diff --git a/types/types.go b/pkg/code/types.go similarity index 85% rename from types/types.go rename to pkg/code/types.go index 18a19a5..de2e4c6 100644 --- a/types/types.go +++ b/pkg/code/types.go @@ -1,10 +1,4 @@ -package types - -type VariableSignature struct { - Type string - Name string - Value string -} +package code type FunctionSignature struct { Name string @@ -17,17 +11,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 +29,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 +} \ No newline at end of file diff --git a/acpkg/acpkg-variables.go b/pkg/code/variables.go similarity index 81% rename from acpkg/acpkg-variables.go rename to pkg/code/variables.go index 46e9d04..bdedd24 100644 --- a/acpkg/acpkg-variables.go +++ b/pkg/code/variables.go @@ -1,8 +1,7 @@ -package acpkg +package code import ( - "git-auto-commit/constants" - "git-auto-commit/types" + "git-auto-commit/infra/constants" "regexp" "strings" ) @@ -16,7 +15,7 @@ var ( defaultVarRegex = regexp.MustCompile(`^\s*(\w+)\s+(\w+)\s*=\s*([^;]+);`) ) -func ParseToStructureVariable(line, lang string) *types.VariableSignature { +func ParseToStructureVariable(line, lang string) *VariableSignature { switch lang { case "python": m := varRegexPython.FindStringSubmatch(line) @@ -24,7 +23,7 @@ func ParseToStructureVariable(line, lang string) *types.VariableSignature { return nil } - return &types.VariableSignature{Type: "", Name: m[1], Value: strings.TrimSpace(m[2])} + return &VariableSignature{Type: "", Name: m[1], Value: strings.TrimSpace(m[2])} case "typescript", "javascript": m := varRegexTSJS.FindStringSubmatch(line) if m == nil { @@ -37,24 +36,24 @@ func ParseToStructureVariable(line, lang string) *types.VariableSignature { typ = m[4] } - return &types.VariableSignature{Type: typ, Name: m[2], Value: strings.TrimSpace(m[5])} + return &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])} + // return &VariableSignature{Type: "", Name: strings.TrimSpace(names[0]), Value: value} + return &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])} + return &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 &VariableSignature{Type: m[2], Name: m[1], Value: ""} } return nil @@ -64,13 +63,13 @@ func ParseToStructureVariable(line, lang string) *types.VariableSignature { return nil } - return &types.VariableSignature{Type: m[1], Name: m[2], Value: strings.TrimSpace(m[3])} + return &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 + var oldVar, newVar *VariableSignature lines := strings.Split(diff, "\n") for _, line := range lines { 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/git/commit.go b/pkg/git/commit.go similarity index 88% rename from git/commit.go rename to pkg/git/commit.go index 995974f..1e0912f 100644 --- a/git/commit.go +++ b/pkg/git/commit.go @@ -2,7 +2,7 @@ package git import ( "fmt" - "git-auto-commit/achelper/logger" + "git-auto-commit/infra/logger" "os" "os/exec" ) diff --git a/diff/diff.go b/pkg/git/diff.go similarity index 94% rename from diff/diff.go rename to pkg/git/diff.go index c5fcec1..cc9228e 100644 --- a/diff/diff.go +++ b/pkg/git/diff.go @@ -1,4 +1,4 @@ -package diff +package git import ( "bufio" @@ -6,8 +6,6 @@ import ( "os/exec" "strings" "sync" - - "git-auto-commit/git" ) var diffBufferPool = sync.Pool{ @@ -20,7 +18,7 @@ var GetDiff = func(file string) (string, error) { var builder strings.Builder builder.Reset() - root, err := git.GetGitRoot() + root, err := GetGitRoot() if err != nil { return "", err } diff --git a/git/git.go b/pkg/git/git.go similarity index 100% rename from git/git.go rename to pkg/git/git.go diff --git a/git/issues.go b/pkg/git/issues.go similarity index 96% rename from git/issues.go rename to pkg/git/issues.go index d010753..d585f55 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" @@ -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..aa39796 --- /dev/null +++ b/pkg/git/types.go @@ -0,0 +1,6 @@ +package git + +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/parser/parser.go b/pkg/parser.go similarity index 75% rename from parser/parser.go rename to pkg/parser.go index d53ca52..b4127e4 100644 --- a/parser/parser.go +++ b/pkg/parser.go @@ -1,11 +1,11 @@ -package parser +package pkg import ( "fmt" - "git-auto-commit/achelper/code" - "git-auto-commit/acpkg" - "git-auto-commit/constants" - "git-auto-commit/diff" + "git-auto-commit/infra/constants" + "git-auto-commit/pkg/code" + "git-auto-commit/pkg/git" + "git-auto-commit/pkg/language" "path/filepath" "strings" "sync" @@ -49,13 +49,13 @@ var Parser = func(files []string) (string, error) { } mu.Unlock() - diff, err := diff.GetDiff(file) + diff, err := git.GetDiff(file) if err != nil { errChan <- fmt.Errorf("error getting diff for %s: %w", file, err) continue } - lang := code.DetectLanguage(file) + lang := language.DetectLanguage(file) if lang == "" { mu.Lock() payloadMsg = AppendMsg(payloadMsg, fmt.Sprintf("the '%s' file has been changed", filepath.Base(file))) @@ -65,15 +65,15 @@ var Parser = func(files []string) (string, error) { 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), + code.FormattedVariables(diff, lang), + code.FormattedFunction(diff, lang), + code.FormattedClass(diff, lang), + code.FormattedLogic(diff, lang, filepath.Base(file)), + code.FormattedImport(diff, lang, filepath.Base(file)), + code.FormattedStruct(diff, lang), + code.FormattedType(diff, lang), + code.FormattedInterface(diff, lang), + code.FormattedEnum(diff, lang), } { if formatted != "" { fileChanges = append(fileChanges, formatted) @@ -119,12 +119,12 @@ var Parser = func(files []string) (string, error) { } if len(payloadMsg) == 0 { - formattedByRemote, err := acpkg.FormattedByRemote("") + formattedByRemote, err := code.FormattedByRemote("") if err != nil { return "", err } - formattedByBranch, err := acpkg.FormattedByBranch() + formattedByBranch, err := code.FormattedByBranch() if err != nil { return "", err } diff --git a/tests/ac_test.go b/tests/ac_test.go index 6b8bc98..97f9e22 100644 --- a/tests/ac_test.go +++ b/tests/ac_test.go @@ -2,12 +2,10 @@ 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" + "git-auto-commit/autocommit" + "git-auto-commit/infra/logger" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" "testing" ) @@ -16,14 +14,13 @@ func TestAutoCommit_NoStagedFiles(t *testing.T) { defer mocks.Apply() calledInfo := "" - diff.GetStagedFiles = func() ([]string, error) { return []string{}, nil } - parser.Parser = func(files []string) (string, error) { return "", nil } + git.GetStagedFiles = func() ([]string, error) { return []string{}, nil } + pkg.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() + autocommit.AutoCommit() if calledInfo != "No files staged for commit." { t.Errorf("expected info log 'No files staged for commit.', got '%s'", calledInfo) @@ -34,18 +31,18 @@ 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.GetStagedFiles = func() ([]string, error) { return nil, errors.New("fail") } + pkg.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) {} + autocommit.GetVersion = func(show bool) {} var calledErr string logger.ErrorLogger = func(err error) { calledErr = err.Error() } logger.InfoLogger = func(msg string) { calledErr = msg } - ac.AutoCommit() + autocommit.AutoCommit() expected := "error getting staged files: fail" if calledErr != expected { diff --git a/tests/af_go_test.go b/tests/af_go_test.go index 980ec34..bda3838 100644 --- a/tests/af_go_test.go +++ b/tests/af_go_test.go @@ -1,9 +1,9 @@ package tests import ( - "git-auto-commit/achelper/code" - "git-auto-commit/diff" - "git-auto-commit/parser" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" + "git-auto-commit/pkg/language" "testing" ) @@ -11,15 +11,15 @@ func TestFormattedFunction_AddedGoFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+func AddedGoFunction() {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -34,15 +34,15 @@ func TestFormattedFunction_AddedGoFunctions(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+func AddedGoFunction1()\n+func AddedGoFunction2()\n+func AddedGoFunction3()", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -57,15 +57,15 @@ func TestFormattedFunction_DeletedGoFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-func DeletedGoFunction() {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -80,15 +80,15 @@ func TestFormattedFunction_DeletedGoFunctions(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-func DeletedGoFunction1()\n-func DeletedGoFunction2()\n-func DeletedGoFunction3()", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -103,15 +103,15 @@ func TestFormattedFunction_ChangedParamNameGoFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-func ParamTest(a int)\n+func ParamTest(b int)", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -126,15 +126,15 @@ func TestFormattedFunction_ChangedParamNameGoFunctions(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.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 { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -149,15 +149,15 @@ func TestFormattedFunction_ChangedParamTypeGoFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-func TypeTest(a int)\n+func TypeTest(a string)", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/tests/af_ts_test.go b/tests/af_ts_test.go index 44ee13f..1bdbb65 100644 --- a/tests/af_ts_test.go +++ b/tests/af_ts_test.go @@ -1,9 +1,9 @@ package tests import ( - "git-auto-commit/achelper/code" - "git-auto-commit/diff" - "git-auto-commit/parser" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" + "git-auto-commit/pkg/language" "testing" ) @@ -11,15 +11,15 @@ func TestFormattedFunction_AddedTSFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+function AddedTSFunction() {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -34,15 +34,15 @@ func TestFormattedFunction_AddedTSFunctions(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+function AddedTSFunction1() {}\n+function AddedTSFunction2() {}\n+function AddedTSFunction3() {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -57,15 +57,15 @@ func TestFormattedFunction_DeletedTSFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-function DeletedTSFunction() {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -80,15 +80,15 @@ func TestFormattedFunction_DeletedTSFunctions(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-function DeletedTSFunction1() {}\n-function DeletedTSFunction2() {}\n-function DeletedTSFunction3() {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -103,15 +103,15 @@ func TestFormattedFunction_ChangedParamNameTSFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-function ParamTest(a: number) {}\n+function ParamTest(b: number) {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -126,15 +126,15 @@ func TestFormattedFunction_ChangedParamNameTSFunctions(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.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 { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -149,15 +149,15 @@ func TestFormattedFunction_ChangedParamTypeTSFunction(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-function TypeTest(a: number) {}\n+function TypeTest(a: string) {}", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/tests/ai_go_test.go b/tests/ai_go_test.go index b1cac60..ded371e 100644 --- a/tests/ai_go_test.go +++ b/tests/ai_go_test.go @@ -1,9 +1,9 @@ package tests import ( - "git-auto-commit/achelper/code" - "git-auto-commit/diff" - "git-auto-commit/parser" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" + "git-auto-commit/pkg/language" "testing" ) @@ -11,15 +11,15 @@ func TestFormattedImport_AddedGoImport(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+import \"fmt\"", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"main.go"}) + msg, err := pkg.Parser([]string{"main.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -34,15 +34,15 @@ func TestFormattedImport_AddedGoImports(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+import \"fmt\"\n+import \"os\"", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"main.go"}) + msg, err := pkg.Parser([]string{"main.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -57,15 +57,15 @@ func TestFormattedImport_AddedImportsBlockGo(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+import (\n+\"fmt\"\n+\"os\"\n+)", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"main.go"}) + msg, err := pkg.Parser([]string{"main.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -80,15 +80,15 @@ func TestFormattedImport_AddedImportBlockGo(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+import (\n+\"fmt\"\n+)", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"main.go"}) + msg, err := pkg.Parser([]string{"main.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/tests/av_go_test.go b/tests/av_go_test.go index b5822f8..2a34e58 100644 --- a/tests/av_go_test.go +++ b/tests/av_go_test.go @@ -1,9 +1,9 @@ package tests import ( - "git-auto-commit/achelper/code" - "git-auto-commit/diff" - "git-auto-commit/parser" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" + "git-auto-commit/pkg/language" "testing" ) @@ -11,15 +11,15 @@ func TestFormattedVariables_AddedGoVar(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+var testVar int = 5", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -34,15 +34,15 @@ func TestFormattedVariables_AddedGoVarEQ(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+testVar := 5", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -57,15 +57,15 @@ func TestFormattedVariables_AddedGoVars(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.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 { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -80,15 +80,15 @@ func TestFormattedVariables_RenamedGoVar(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-var testVar1 int = 5\n+var testVar int = 5", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -103,15 +103,15 @@ func TestFormattedVariables_ChangedTypeGoVar(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-var testVar int = 5\n+var testVar uint = 5", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -126,15 +126,15 @@ func TestFormattedVariables_ChangedTypeGoVars(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.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 { + language.DetectLanguage = func(filename string) string { return "go" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.go"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.go"}) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/tests/av_ts_test.go b/tests/av_ts_test.go index a79ef98..84912a6 100644 --- a/tests/av_ts_test.go +++ b/tests/av_ts_test.go @@ -1,9 +1,9 @@ package tests import ( - "git-auto-commit/achelper/code" - "git-auto-commit/diff" - "git-auto-commit/parser" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" + "git-auto-commit/pkg/language" "testing" ) @@ -11,15 +11,15 @@ func TestFormattedVariables_AddedTSVar(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+let testVar: number = 5;", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -34,15 +34,15 @@ func TestFormattedVariables_AddedTSVars(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "+let testVar1: number = 5;\n+const testVar2: string = 'hi';", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -57,15 +57,15 @@ func TestFormattedVariables_RenamedTSVar(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-let testVar1: number = 5;\n+let testVar: number = 5;", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -80,15 +80,15 @@ func TestFormattedVariables_ChangedTypeTSVar(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.GetDiff = func(file string) (string, error) { return "-let testVar: number = 5;\n+let testVar: string = 5;", nil } - code.DetectLanguage = func(filename string) string { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -103,15 +103,15 @@ func TestFormattedVariables_ChangedTypesTSVars(t *testing.T) { mocks := SaveMocks() defer mocks.Apply() - diff.GetDiff = func(file string) (string, error) { + git.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 { + language.DetectLanguage = func(filename string) string { return "typescript" } - msg, err := parser.Parser([]string{"auto-commit-parser-test.ts"}) + msg, err := pkg.Parser([]string{"auto-commit-parser-test.ts"}) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/tests/test.g.go b/tests/test.g.go index 3b75aad..c67371a 100644 --- a/tests/test.g.go +++ b/tests/test.g.go @@ -1,11 +1,10 @@ package tests import ( - "git-auto-commit/achelper" - "git-auto-commit/achelper/logger" - "git-auto-commit/diff" - "git-auto-commit/git" - "git-auto-commit/parser" + "git-auto-commit/autocommit" + "git-auto-commit/infra/logger" + "git-auto-commit/pkg" + "git-auto-commit/pkg/git" ) type Mocks struct { @@ -19,20 +18,19 @@ type Mocks struct { func SaveMocks() *Mocks { return &Mocks{ - GetStagedFiles: diff.GetStagedFiles, - Parser: parser.Parser, + GetStagedFiles: git.GetStagedFiles, + Parser: pkg.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.GetStagedFiles = m.GetStagedFiles + pkg.Parser = m.Parser git.Commit = m.Commit logger.ErrorLogger = m.ErrorLogger logger.InfoLogger = m.InfoLogger - achelper.GetVersion = m.GetVersion + autocommit.GetVersion = m.GetVersion } diff --git a/vercel.json b/vercel.json index ca9179f..5bfb0f2 100644 --- a/vercel.json +++ b/vercel.json @@ -1,14 +1,14 @@ { "builds": [ { - "src": "www/**/*", + "src": "Help/www/**/*", "use": "@vercel/static" } ], "routes": [ { "src": "/(.*)", - "dest": "/www/$1" + "dest": "/Help/www/$1" } ] } From af3bdef4396b907395e55f16460054207459cad3 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 03:22:32 -0400 Subject: [PATCH 03/20] the 'version.md' file has been changed --- pkg/git/diff.go | 3 ++- version.md | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 version.md diff --git a/pkg/git/diff.go b/pkg/git/diff.go index cc9228e..ce55495 100644 --- a/pkg/git/diff.go +++ b/pkg/git/diff.go @@ -44,10 +44,11 @@ var GetDiff = func(file string) (string, error) { var GetStagedFiles = func() ([]string, error) { cmd := exec.Command("git", "diff", "--cached", "--name-only") - stdout, err := cmd.StdoutPipe() + stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } + if err := cmd.Start(); err != nil { return nil, err 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 From 82abade70fb299ccb1dfa037bd9cd7d4a4035807 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 07:49:19 -0400 Subject: [PATCH 04/20] added new base parser and ahothers mini changes --- autocommit/autocommit.go | 10 ++-- infra/constants/commit-type.go | 16 +++++++ infra/constants/strings.go | 13 ++++++ pkg/file/files.go | 24 ++++++++++ pkg/git/diff.go | 81 ++++++++++++++++++++++++++++++++- pkg/parser/create-commit-msg.go | 21 +++++++++ pkg/parser/detect-tag.go | 50 ++++++++++++++++++++ pkg/parser/parser.go | 24 ++++++++++ pkg/pkgerror/pkgerror.go | 33 ++++++++++++++ pkg/pkgerror/reestr.go | 13 ++++++ pkg/pkgerror/types.go | 1 + 11 files changed, 279 insertions(+), 7 deletions(-) create mode 100644 infra/constants/commit-type.go create mode 100644 infra/constants/strings.go create mode 100644 pkg/file/files.go create mode 100644 pkg/parser/create-commit-msg.go create mode 100644 pkg/parser/detect-tag.go create mode 100644 pkg/parser/parser.go create mode 100644 pkg/pkgerror/pkgerror.go create mode 100644 pkg/pkgerror/reestr.go create mode 100644 pkg/pkgerror/types.go diff --git a/autocommit/autocommit.go b/autocommit/autocommit.go index ea808f5..799b3f8 100644 --- a/autocommit/autocommit.go +++ b/autocommit/autocommit.go @@ -3,25 +3,25 @@ package autocommit import ( "fmt" "git-auto-commit/infra/logger" - "git-auto-commit/pkg" "git-auto-commit/pkg/git" + "git-auto-commit/pkg/parser" ) func AutoCommit() { GetVersion(false) - files, err := git.GetStagedFiles() + directory, err := git.GetStagedCountDirectory() if err != nil { logger.ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error())) return } - if len(files) == 0 { + if directory == "" { logger.InfoLogger("No files staged for commit.") return } - parserMsg, err := pkg.Parser(files) + parserMsg, err := parser.Parser(directory) if err != nil { logger.ErrorLogger(err) return @@ -31,4 +31,4 @@ func AutoCommit() { logger.ErrorLogger(fmt.Errorf("error committing: %s", err.Error())) return } -} \ No newline at end of file +} 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/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/pkg/file/files.go b/pkg/file/files.go new file mode 100644 index 0000000..ea58398 --- /dev/null +++ b/pkg/file/files.go @@ -0,0 +1,24 @@ +package file + +import ( + "os" + "path/filepath" +) + +var GetFilesInDir = func(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/pkg/git/diff.go b/pkg/git/diff.go index ce55495..aab010c 100644 --- a/pkg/git/diff.go +++ b/pkg/git/diff.go @@ -3,7 +3,9 @@ package git import ( "bufio" "bytes" + "fmt" "os/exec" + "strconv" "strings" "sync" ) @@ -41,14 +43,89 @@ var GetDiff = func(file string) (string, error) { return buf.String(), nil } +var GetStagedCountDirectory = func() (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 "", fmt.Errorf("") +} + var GetStagedFiles = func() ([]string, error) { cmd := exec.Command("git", "diff", "--cached", "--name-only") - stdout, err := cmd.StdoutPipe() + stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } - if err := cmd.Start(); err != nil { return nil, err diff --git a/pkg/parser/create-commit-msg.go b/pkg/parser/create-commit-msg.go new file mode 100644 index 0000000..bb73d53 --- /dev/null +++ b/pkg/parser/create-commit-msg.go @@ -0,0 +1,21 @@ +package parser + +import ( + "fmt" + "git-auto-commit/infra/constants" +) + +var CreateAutoCommitMsg = func(filename, msg *string, changed string) string { + ext := DetectTagByFile(filename, changed) + + msgCommit, ok := constants.Ratio_Commit[ext] + if ok { + return ext + " " + msgCommit + } + + if msg != nil { + return ext + " " + *msg + } + + return fmt.Sprintf("%s Processed file - %s is refactored", constants.Type_CommitRefactor, filename) +} diff --git a/pkg/parser/detect-tag.go b/pkg/parser/detect-tag.go new file mode 100644 index 0000000..7707200 --- /dev/null +++ b/pkg/parser/detect-tag.go @@ -0,0 +1,50 @@ +package parser + +import ( + "git-auto-commit/infra/constants" + "path/filepath" + "regexp" + "strings" +) + +var DetectTagByFile = func(filename *string, changed string) string { + // check type changed + switch changed { + case constants.Ch_TypeAdd: + return constants.Type_CommitFeat + + case constants.Ch_TypeDelete: + return constants.Type_CommitRefactor + + case constants.Ch_TypeChanged: + return constants.Type_CommitFix + + } + + 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/pkg/parser/parser.go b/pkg/parser/parser.go new file mode 100644 index 0000000..2d8a69c --- /dev/null +++ b/pkg/parser/parser.go @@ -0,0 +1,24 @@ +package parser + +import ( + "fmt" + "git-auto-commit/pkg/file" + "git-auto-commit/pkg/pkgerror" + "os" +) + +var Parser = func(directory string) (string, error) { + info, err := os.Stat(directory) + if err != nil { + return "", fmt.Errorf("errir getting file info") + } + + if !info.IsDir() { + return CreateAutoCommitMsg(&directory, nil, ""), nil + } + + files := file.GetFilesInDir(directory) + if len(files) == 0 { + return "", pkgerror.CreateError(pkgerror.Err_FileNotFound) + } +} 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..816118b --- /dev/null +++ b/pkg/pkgerror/reestr.go @@ -0,0 +1,13 @@ +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") +) 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 From af52802fbe49330836952a85547d02979c342963 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 15:40:22 -0400 Subject: [PATCH 05/20] Implemented pkg --- autocommit/autocommitwatcher.go | 9 +- infra/constants/expanding-notation-folders.go | 44 +++ infra/constants/name-status.go | 7 + pkg/code/code.go | 119 ++++++ pkg/code/function.go | 289 --------------- pkg/code/import.go | 103 ------ pkg/code/logic.go | 279 -------------- pkg/code/oop.go | 231 ------------ pkg/code/structure.go | 347 ------------------ pkg/code/variables.go | 142 ------- pkg/parser.go | 140 ------- pkg/parser/parser.go | 30 ++ tests/ac_test.go | 51 --- tests/af_go_test.go | 169 --------- tests/af_ts_test.go | 169 --------- tests/ai_go_test.go | 100 ----- tests/av_go_test.go | 146 -------- tests/av_ts_test.go | 123 ------- .../golang/implemented_golang_test.go | 11 + tests/test.g.go | 8 +- 20 files changed, 220 insertions(+), 2297 deletions(-) create mode 100644 infra/constants/expanding-notation-folders.go create mode 100644 infra/constants/name-status.go create mode 100644 pkg/code/code.go delete mode 100644 pkg/code/function.go delete mode 100644 pkg/code/import.go delete mode 100644 pkg/code/logic.go delete mode 100644 pkg/code/oop.go delete mode 100644 pkg/code/structure.go delete mode 100644 pkg/code/variables.go delete mode 100644 pkg/parser.go delete mode 100644 tests/ac_test.go delete mode 100644 tests/af_go_test.go delete mode 100644 tests/af_ts_test.go delete mode 100644 tests/ai_go_test.go delete mode 100644 tests/av_go_test.go delete mode 100644 tests/av_ts_test.go create mode 100644 tests/code/implemented/golang/implemented_golang_test.go diff --git a/autocommit/autocommitwatcher.go b/autocommit/autocommitwatcher.go index 29155fe..82f8e79 100644 --- a/autocommit/autocommitwatcher.go +++ b/autocommit/autocommitwatcher.go @@ -4,8 +4,8 @@ import ( "fmt" "git-auto-commit/infra/constants" "git-auto-commit/infra/logger" - "git-auto-commit/pkg" "git-auto-commit/pkg/git" + "git-auto-commit/pkg/parser" "os" "os/exec" "os/signal" @@ -69,17 +69,18 @@ func Watch(path string) { return } - files, err := git.GetStagedFiles() + directory, err := git.GetStagedCountDirectory() if err != nil { logger.ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error())) return } - if len(files) == 0 { + if directory == "" { logger.InfoLogger("No files staged for commit.") + return } - parser, err := pkg.Parser(files) + parser, err := parser.Parser(directory) if err != nil { logger.ErrorLogger(err) return diff --git a/infra/constants/expanding-notation-folders.go b/infra/constants/expanding-notation-folders.go new file mode 100644 index 0000000..e102cba --- /dev/null +++ b/infra/constants/expanding-notation-folders.go @@ -0,0 +1,44 @@ +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", +} diff --git a/infra/constants/name-status.go b/infra/constants/name-status.go new file mode 100644 index 0000000..c4c4371 --- /dev/null +++ b/infra/constants/name-status.go @@ -0,0 +1,7 @@ +package constants + +const ( + NameStatus_Added = "A" + NameStatus_Modified = "M" + NameStatus_Deleted = "D" +) diff --git a/pkg/code/code.go b/pkg/code/code.go new file mode 100644 index 0000000..e07910c --- /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 + +var FormattedCode = func(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 := build(added, modified, deleted) + return msg, nil +} + +func build(added, modified, deleted []string) string { + var parts []string + + if len(added) > 0 { + parts = append(parts, "implemented "+summarize(added)) + } + + if len(modified) > 0 { + parts = append(parts, "updated "+summarize(modified)) + } + + if len(deleted) > 0 { + parts = append(parts, "removed "+summarize(deleted)) + } + + msg := strings.Join(parts, ", ") + if len(msg) > 0 { + msg = strings.ToUpper(msg[:1]) + msg[1:] + } + + return msg +} + +func 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/function.go b/pkg/code/function.go deleted file mode 100644 index 9751d05..0000000 --- a/pkg/code/function.go +++ /dev/null @@ -1,289 +0,0 @@ -package code - -import ( - "git-auto-commit/infra/constants" - "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) *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 *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) *FunctionSignature { - m := functionRegexGo.FindStringSubmatch(line) - if m == nil { - return nil - } - - name := m[1] - paramsString := m[2] - params := []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, FunctionParameters{Name: parts[0], Type: parts[1]}) - } - } - - return &FunctionSignature{Name: name, Params: params} -} - -func parsePythonFunction(line string) *FunctionSignature { - m := functionRegexPython.FindStringSubmatch(line) - if m == nil { - return nil - } - - name := m[1] - params := []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, FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) - } else { - params = append(params, FunctionParameters{Name: p, Type: ""}) - } - } - - return &FunctionSignature{Name: name, Params: params} -} - -func parseTSJSFunction(line string) *FunctionSignature { - m := functionRegexTSJS.FindStringSubmatch(line) - if m != nil { - name := m[1] - returnType := "" - if len(m) > 4 { - returnType = m[4] - } - - params := []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, FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) - } else { - params = append(params, FunctionParameters{Name: p, Type: ""}) - } - } - - return &FunctionSignature{Name: name, Params: params, ReturnType: returnType} - } - - m = functionRegexTSJSConst.FindStringSubmatch(line) - if m != nil { - name := m[2] - - params := []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, FunctionParameters{Name: strings.TrimSpace(parts[0]), Type: strings.TrimSpace(parts[1])}) - } else { - params = append(params, FunctionParameters{Name: p, Type: ""}) - } - } - - return &FunctionSignature{Name: name, Params: params, ReturnType: ""} - } - - return nil -} - -func parseCJavaFunction(line string) *FunctionSignature { - m := functionRegexCJava.FindStringSubmatch(line) - if m == nil { - return nil - } - - returnType := m[1] - name := m[2] - - params := []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, FunctionParameters{Name: parts[1], Type: parts[0]}) - } else if len(parts) == 1 { - params = append(params, FunctionParameters{Name: parts[0], Type: ""}) - } - } - - return &FunctionSignature{Name: name, Params: params, ReturnType: returnType} -} - -func parseCSharpFunction(line string) *FunctionSignature { - m := functionRegexCSharp.FindStringSubmatch(line) - if m == nil { - return nil - } - - name := m[4] - params := []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, FunctionParameters{Name: parts[1], Type: parts[0]}) - } else if len(parts) == 1 { - params = append(params, FunctionParameters{Name: parts[0], Type: ""}) - } - } - - return &FunctionSignature{Name: name, Params: params, ReturnType: m[3]} -} diff --git a/pkg/code/import.go b/pkg/code/import.go deleted file mode 100644 index cd88cf2..0000000 --- a/pkg/code/import.go +++ /dev/null @@ -1,103 +0,0 @@ -package code - -import ( - "git-auto-commit/infra/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/pkg/code/logic.go b/pkg/code/logic.go deleted file mode 100644 index 9d0565b..0000000 --- a/pkg/code/logic.go +++ /dev/null @@ -1,279 +0,0 @@ -package code - -import ( - "git-auto-commit/infra/constants" - "regexp" - "strings" -) - -func extractSwitchBlocks(lines []string, lang string, isNew bool) []SwitchSignature { - var blocks []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, 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 []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 []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 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/pkg/code/oop.go b/pkg/code/oop.go deleted file mode 100644 index 239d2f8..0000000 --- a/pkg/code/oop.go +++ /dev/null @@ -1,231 +0,0 @@ -package code - -import ( - "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) *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) *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 &ClassSignature{Name: name, Parent: parent, Methods: methods} -} - -func parsePythonClass(line string) *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 &ClassSignature{Name: name, Parent: parent, Methods: methods} -} - -func parseCppClass(line string) *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 &ClassSignature{Name: name, Parent: parent, Methods: methods} -} - -func parseCSharpClass(line string) *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 &ClassSignature{Name: name, Parent: parent, Methods: methods} -} - -func parseGoStruct(line string) *ClassSignature { - m := classRegexGo.FindStringSubmatch(line) - if m == nil { - return nil - } - - name := m[1] - return &ClassSignature{Name: name, Parent: "", Methods: make(map[string]string)} -} - -func parseJavaClass(line string) *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 &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 *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/pkg/code/structure.go b/pkg/code/structure.go deleted file mode 100644 index 1545d76..0000000 --- a/pkg/code/structure.go +++ /dev/null @@ -1,347 +0,0 @@ -package code - -import ( - "regexp" - "strings" -) - -func parseStruct(line, lang string) *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 &StructureSignature{Name: m[1]} -} - -func parseType(line, lang string) *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 &TypeSignature{Name: m[1]} -} - -func parseInterface(line, lang string) *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 &InterfaceSignature{Name: m[1]} -} - -func parseEnum(line, lang string) *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 &EnumSignature{Name: m[1]} -} - -func FormattedStruct(diff, lang string) string { - var oldStruct, newStruct *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 *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 *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 *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/pkg/code/variables.go b/pkg/code/variables.go deleted file mode 100644 index bdedd24..0000000 --- a/pkg/code/variables.go +++ /dev/null @@ -1,142 +0,0 @@ -package code - -import ( - "git-auto-commit/infra/constants" - "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) *VariableSignature { - switch lang { - case "python": - m := varRegexPython.FindStringSubmatch(line) - if m == nil { - return nil - } - - return &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 &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 &VariableSignature{Type: "", Name: strings.TrimSpace(names[0]), Value: value} - return &VariableSignature{Type: m[2], Name: m[1], Value: strings.TrimSpace(m[3])} - } - - m = varRegexGoShort.FindStringSubmatch(line) - if m != nil { - return &VariableSignature{Type: "", Name: m[1], Value: strings.TrimSpace(m[2])} - } - - m = varRegexGoNoValue.FindStringSubmatch(line) - if m != nil { - return &VariableSignature{Type: m[2], Name: m[1], Value: ""} - } - - return nil - default: - m := defaultVarRegex.FindStringSubmatch(line) - if m == nil { - return nil - } - - return &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 *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/pkg/parser.go b/pkg/parser.go deleted file mode 100644 index b4127e4..0000000 --- a/pkg/parser.go +++ /dev/null @@ -1,140 +0,0 @@ -package pkg - -import ( - "fmt" - "git-auto-commit/infra/constants" - "git-auto-commit/pkg/code" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/language" - "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 := git.GetDiff(file) - if err != nil { - errChan <- fmt.Errorf("error getting diff for %s: %w", file, err) - continue - } - - lang := language.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{ - code.FormattedVariables(diff, lang), - code.FormattedFunction(diff, lang), - code.FormattedClass(diff, lang), - code.FormattedLogic(diff, lang, filepath.Base(file)), - code.FormattedImport(diff, lang, filepath.Base(file)), - code.FormattedStruct(diff, lang), - code.FormattedType(diff, lang), - code.FormattedInterface(diff, lang), - code.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 := code.FormattedByRemote("") - if err != nil { - return "", err - } - - formattedByBranch, err := code.FormattedByBranch() - if err != nil { - return "", err - } - - if formattedByRemote != "" { - payloadMsg = AppendMsg(payloadMsg, formattedByRemote) - } else { - payloadMsg = AppendMsg(payloadMsg, formattedByBranch) - } - } - - return payloadMsg, nil -} diff --git a/pkg/parser/parser.go b/pkg/parser/parser.go index 2d8a69c..3cd068c 100644 --- a/pkg/parser/parser.go +++ b/pkg/parser/parser.go @@ -2,6 +2,7 @@ package parser import ( "fmt" + "git-auto-commit/pkg/code" "git-auto-commit/pkg/file" "git-auto-commit/pkg/pkgerror" "os" @@ -21,4 +22,33 @@ var Parser = func(directory string) (string, error) { if len(files) == 0 { return "", pkgerror.CreateError(pkgerror.Err_FileNotFound) } + + formatted, err := code.FormattedCode(files) + if err != nil { + return "", err + } + + if formatted == "" { + formattedByRemote, err := code.FormattedByRemote("") + if err != nil { + return "", fmt.Errorf("failed to format by remote: %w", err) + } + + if formattedByRemote != "" { + formatted = formattedByRemote + } + } + + if formatted == "" { + formattedByBranch, err := code.FormattedByBranch() + if err != nil { + return "", fmt.Errorf("failed to format by branch: %w", err) + } + + if formattedByBranch != "" { + formatted = formattedByBranch + } + } + + return formatted, nil } diff --git a/tests/ac_test.go b/tests/ac_test.go deleted file mode 100644 index 97f9e22..0000000 --- a/tests/ac_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package tests - -import ( - "errors" - "git-auto-commit/autocommit" - "git-auto-commit/infra/logger" - "git-auto-commit/pkg" - "git-auto-commit/pkg/git" - "testing" -) - -func TestAutoCommit_NoStagedFiles(t *testing.T) { - mocks := SaveMocks() - defer mocks.Apply() - - calledInfo := "" - git.GetStagedFiles = func() ([]string, error) { return []string{}, nil } - pkg.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 } - - autocommit.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() - - git.GetStagedFiles = func() ([]string, error) { return nil, errors.New("fail") } - pkg.Parser = func(files []string) (string, error) { return "", nil } - git.Commit = func(msg string) error { return nil } - logger.InfoLogger = func(msg string) {} - autocommit.GetVersion = func(show bool) {} - - var calledErr string - logger.ErrorLogger = func(err error) { calledErr = err.Error() } - - logger.InfoLogger = func(msg string) { calledErr = msg } - - autocommit.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 bda3838..0000000 --- a/tests/af_go_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package tests - -import ( - "git-auto-commit/pkg" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/language" - "testing" -) - -func TestFormattedFunction_AddedGoFunction(t *testing.T) { - mocks := SaveMocks() - defer mocks.Apply() - - git.GetDiff = func(file string) (string, error) { - return "+func AddedGoFunction() {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+func AddedGoFunction1()\n+func AddedGoFunction2()\n+func AddedGoFunction3()", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-func DeletedGoFunction() {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-func DeletedGoFunction1()\n-func DeletedGoFunction2()\n-func DeletedGoFunction3()", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-func ParamTest(a int)\n+func ParamTest(b int)", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.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 - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-func TypeTest(a int)\n+func TypeTest(a string)", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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 1bdbb65..0000000 --- a/tests/af_ts_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package tests - -import ( - "git-auto-commit/pkg" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/language" - "testing" -) - -func TestFormattedFunction_AddedTSFunction(t *testing.T) { - mocks := SaveMocks() - defer mocks.Apply() - - git.GetDiff = func(file string) (string, error) { - return "+function AddedTSFunction() {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+function AddedTSFunction1() {}\n+function AddedTSFunction2() {}\n+function AddedTSFunction3() {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-function DeletedTSFunction() {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-function DeletedTSFunction1() {}\n-function DeletedTSFunction2() {}\n-function DeletedTSFunction3() {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-function ParamTest(a: number) {}\n+function ParamTest(b: number) {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.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 - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-function TypeTest(a: number) {}\n+function TypeTest(a: string) {}", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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 ded371e..0000000 --- a/tests/ai_go_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package tests - -import ( - "git-auto-commit/pkg" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/language" - "testing" -) - -func TestFormattedImport_AddedGoImport(t *testing.T) { - mocks := SaveMocks() - defer mocks.Apply() - - git.GetDiff = func(file string) (string, error) { - return "+import \"fmt\"", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+import \"fmt\"\n+import \"os\"", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+import (\n+\"fmt\"\n+\"os\"\n+)", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+import (\n+\"fmt\"\n+)", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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/av_go_test.go b/tests/av_go_test.go deleted file mode 100644 index 2a34e58..0000000 --- a/tests/av_go_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package tests - -import ( - "git-auto-commit/pkg" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/language" - "testing" -) - -func TestFormattedVariables_AddedGoVar(t *testing.T) { - mocks := SaveMocks() - defer mocks.Apply() - - git.GetDiff = func(file string) (string, error) { - return "+var testVar int = 5", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+testVar := 5", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+var testVar1 int = 5\n+var testVar2 string\n+testVar3 := 0", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-var testVar1 int = 5\n+var testVar int = 5", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-var testVar int = 5\n+var testVar uint = 5", nil - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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() - - git.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 - } - - language.DetectLanguage = func(filename string) string { - return "go" - } - - msg, err := pkg.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 84912a6..0000000 --- a/tests/av_ts_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package tests - -import ( - "git-auto-commit/pkg" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/language" - "testing" -) - -func TestFormattedVariables_AddedTSVar(t *testing.T) { - mocks := SaveMocks() - defer mocks.Apply() - - git.GetDiff = func(file string) (string, error) { - return "+let testVar: number = 5;", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "+let testVar1: number = 5;\n+const testVar2: string = 'hi';", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-let testVar1: number = 5;\n+let testVar: number = 5;", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.GetDiff = func(file string) (string, error) { - return "-let testVar: number = 5;\n+let testVar: string = 5;", nil - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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() - - git.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 - } - - language.DetectLanguage = func(filename string) string { - return "typescript" - } - - msg, err := pkg.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/implemented/golang/implemented_golang_test.go b/tests/code/implemented/golang/implemented_golang_test.go new file mode 100644 index 0000000..77e01fa --- /dev/null +++ b/tests/code/implemented/golang/implemented_golang_test.go @@ -0,0 +1,11 @@ +package golang + +import ( + "git-auto-commit/tests" + "testing" +) + +func TestImplementedGolang(t *testing.T) { + mocks := tests.SaveMocks() + defer mocks.Apply() +} diff --git a/tests/test.g.go b/tests/test.g.go index c67371a..af3f536 100644 --- a/tests/test.g.go +++ b/tests/test.g.go @@ -3,13 +3,13 @@ package tests import ( "git-auto-commit/autocommit" "git-auto-commit/infra/logger" - "git-auto-commit/pkg" "git-auto-commit/pkg/git" + "git-auto-commit/pkg/parser" ) type Mocks struct { GetStagedFiles func() ([]string, error) - Parser func([]string) (string, error) + Parser func(string) (string, error) Commit func(string) error ErrorLogger func(error) InfoLogger func(string) @@ -19,7 +19,7 @@ type Mocks struct { func SaveMocks() *Mocks { return &Mocks{ GetStagedFiles: git.GetStagedFiles, - Parser: pkg.Parser, + Parser: parser.Parser, Commit: git.Commit, ErrorLogger: logger.ErrorLogger, InfoLogger: logger.InfoLogger, @@ -28,7 +28,7 @@ func SaveMocks() *Mocks { func (m *Mocks) Apply() { git.GetStagedFiles = m.GetStagedFiles - pkg.Parser = m.Parser + parser.Parser = m.Parser git.Commit = m.Commit logger.ErrorLogger = m.ErrorLogger logger.InfoLogger = m.InfoLogger From 0506f15bc3be252b24ef27206fe8dbd194b3e908 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 15:55:18 -0400 Subject: [PATCH 06/20] Updated infrastructure as code --- infra/constants/expanding-notation-folders.go | 47 +++++++++++++++++++ infra/logger/logger.go | 46 ++++++++++++------ 2 files changed, 78 insertions(+), 15 deletions(-) diff --git a/infra/constants/expanding-notation-folders.go b/infra/constants/expanding-notation-folders.go index e102cba..8adf9ee 100644 --- a/infra/constants/expanding-notation-folders.go +++ b/infra/constants/expanding-notation-folders.go @@ -41,4 +41,51 @@ var EXPANDING_NOTATION_FOLDERS = map[string]string{ "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", } diff --git a/infra/logger/logger.go b/infra/logger/logger.go index d4b380a..141fd5c 100644 --- a/infra/logger/logger.go +++ b/infra/logger/logger.go @@ -2,31 +2,47 @@ package logger import ( "fmt" + "os" + "path/filepath" "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 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 + } } -var GitLogger = func(msg string) { +func logMessage(prefix, msg, color string) { var builder strings.Builder - builder.Reset() - builder.WriteString("\033[0;34m[git auto-commit] ") + 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) { - 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()) + logMessage("", err.Error(), "\033[0;31m") } From 6a67c39421e78507acb147d6b6decda60acbe758 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 16:22:53 -0400 Subject: [PATCH 07/20] Updated autocommit --- autocommit/autocommit.go | 8 +++----- autocommit/autocommitupdate.go | 4 ++-- autocommit/autocommitwatcher.go | 4 ++-- cmd/main.go | 13 ++++++++----- infra/constants/github.go | 10 ++++++---- pkg/git/git.go | 5 +++-- pkg/parser/parser.go | 11 +++++------ pkg/pkgerror/reestr.go | 10 ++++++++++ 8 files changed, 39 insertions(+), 26 deletions(-) diff --git a/autocommit/autocommit.go b/autocommit/autocommit.go index 799b3f8..4eafced 100644 --- a/autocommit/autocommit.go +++ b/autocommit/autocommit.go @@ -1,10 +1,10 @@ package autocommit import ( - "fmt" "git-auto-commit/infra/logger" "git-auto-commit/pkg/git" "git-auto-commit/pkg/parser" + "git-auto-commit/pkg/pkgerror" ) func AutoCommit() { @@ -12,23 +12,21 @@ func AutoCommit() { directory, err := git.GetStagedCountDirectory() if err != nil { - logger.ErrorLogger(fmt.Errorf("error getting staged files: %s", err.Error())) + logger.ErrorLogger(pkgerror.Err_FailedToGetDiff) return } if directory == "" { - logger.InfoLogger("No files staged for commit.") + logger.InfoLogger(pkgerror.Err_NoStagedFiles.Error()) return } parserMsg, err := parser.Parser(directory) 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/autocommit/autocommitupdate.go b/autocommit/autocommitupdate.go index d83ebd3..760e1d7 100644 --- a/autocommit/autocommitupdate.go +++ b/autocommit/autocommitupdate.go @@ -55,10 +55,10 @@ func Update() { 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" + 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" + scriptUpdate = fmt.Sprintf("%s/raw/main/scripts/%s", constants.GITHUB_REPO_URL, constants.GITHUB_SCRIPT_AUTOCOMMIT_UPDATE_LINUX) scriptUpdateExt = ".sh" } diff --git a/autocommit/autocommitwatcher.go b/autocommit/autocommitwatcher.go index 82f8e79..95a97ae 100644 --- a/autocommit/autocommitwatcher.go +++ b/autocommit/autocommitwatcher.go @@ -1,7 +1,7 @@ package autocommit import ( - "fmt" + "errors" "git-auto-commit/infra/constants" "git-auto-commit/infra/logger" "git-auto-commit/pkg/git" @@ -71,7 +71,7 @@ func Watch(path string) { directory, err := 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 } diff --git a/cmd/main.go b/cmd/main.go index 4fd8a38..4165212 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -9,21 +9,24 @@ import ( ) func main() { - if len(os.Args) > 1 && (os.Args[1] == "-w" || os.Args[1] == "--watch") { + args := os.Args[1:] + fmt.Println(args) + + if len(args) > 1 && (args[0] == "-w" || args[0] == "--watch") { path, err := git.GetGitRoot() if err != nil { logger.ErrorLogger(err) return } - if len(os.Args) > 2 { - path = fmt.Sprintf("%s/%s", path, os.Args[2]) + if len(args) > 2 { + path = fmt.Sprintf("%s/%s", path, args[1]) } autocommit.Watch(path) - } else if len(os.Args) > 1 && (os.Args[1] == "-v" || os.Args[1] == "--version") { + } else if len(args) > 1 && (args[0] == "-v" || args[0] == "--version") { autocommit.GetVersion(true) - } else if len(os.Args) > 1 && (os.Args[1] == "-u" || os.Args[1] == "--update") { + } else if len(args) > 1 && (args[0] == "-u" || args[0] == "--update") { autocommit.Update() } else { autocommit.AutoCommit() diff --git a/infra/constants/github.go b/infra/constants/github.go index b027086..bf8191a 100644 --- a/infra/constants/github.go +++ b/infra/constants/github.go @@ -1,8 +1,10 @@ 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_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_WIN string = "update-windows-auto-commit.ps1" ) diff --git a/pkg/git/git.go b/pkg/git/git.go index c736261..48d85e3 100644 --- a/pkg/git/git.go +++ b/pkg/git/git.go @@ -2,6 +2,7 @@ package git import ( "bytes" + "git-auto-commit/pkg/pkgerror" "os/exec" "strings" ) @@ -12,7 +13,7 @@ func GetGitRoot() (string, error) { cmd.Stdout = &out if err := cmd.Run(); err != nil { - return "", err + return "", pkgerror.Err_GitNotRepository } root := strings.TrimSpace(out.String()) @@ -23,7 +24,7 @@ func 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/pkg/parser/parser.go b/pkg/parser/parser.go index 3cd068c..1ac8f6f 100644 --- a/pkg/parser/parser.go +++ b/pkg/parser/parser.go @@ -1,7 +1,6 @@ package parser import ( - "fmt" "git-auto-commit/pkg/code" "git-auto-commit/pkg/file" "git-auto-commit/pkg/pkgerror" @@ -11,7 +10,7 @@ import ( var Parser = func(directory string) (string, error) { info, err := os.Stat(directory) if err != nil { - return "", fmt.Errorf("errir getting file info") + return "", pkgerror.CreateError(pkgerror.Err_FailedToReadFile) } if !info.IsDir() { @@ -25,13 +24,13 @@ var Parser = func(directory string) (string, error) { formatted, err := code.FormattedCode(files) if err != nil { - return "", err + return "", pkgerror.CreateError(err) } if formatted == "" { formattedByRemote, err := code.FormattedByRemote("") if err != nil { - return "", fmt.Errorf("failed to format by remote: %w", err) + return "", pkgerror.CreateError(pkgerror.Err_RemoteUnavailable) } if formattedByRemote != "" { @@ -42,9 +41,9 @@ var Parser = func(directory string) (string, error) { if formatted == "" { formattedByBranch, err := code.FormattedByBranch() if err != nil { - return "", fmt.Errorf("failed to format by branch: %w", err) + return "", pkgerror.CreateError(pkgerror.Err_BranchNotFound) } - + if formattedByBranch != "" { formatted = formattedByBranch } diff --git a/pkg/pkgerror/reestr.go b/pkg/pkgerror/reestr.go index 816118b..73bfa52 100644 --- a/pkg/pkgerror/reestr.go +++ b/pkg/pkgerror/reestr.go @@ -10,4 +10,14 @@ var ( 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") ) From dd971a9f08dd0934514e7b1efe383a0ecd7969ae Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 16:33:24 -0400 Subject: [PATCH 08/20] Updated command-line tools --- cmd/main.go | 13 +++++-------- pkg/code/code.go | 2 +- pkg/file/files.go | 2 +- scripts/install-linux-auto-commit.sh | 2 +- scripts/update-linux-auto-commit.sh | 2 +- 5 files changed, 9 insertions(+), 12 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 4165212..4fd8a38 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -9,24 +9,21 @@ import ( ) func main() { - args := os.Args[1:] - fmt.Println(args) - - if len(args) > 1 && (args[0] == "-w" || args[0] == "--watch") { + if len(os.Args) > 1 && (os.Args[1] == "-w" || os.Args[1] == "--watch") { path, err := git.GetGitRoot() if err != nil { logger.ErrorLogger(err) return } - if len(args) > 2 { - path = fmt.Sprintf("%s/%s", path, args[1]) + if len(os.Args) > 2 { + path = fmt.Sprintf("%s/%s", path, os.Args[2]) } autocommit.Watch(path) - } else if len(args) > 1 && (args[0] == "-v" || args[0] == "--version") { + } else if len(os.Args) > 1 && (os.Args[1] == "-v" || os.Args[1] == "--version") { autocommit.GetVersion(true) - } else if len(args) > 1 && (args[0] == "-u" || args[0] == "--update") { + } else if len(os.Args) > 1 && (os.Args[1] == "-u" || os.Args[1] == "--update") { autocommit.Update() } else { autocommit.AutoCommit() diff --git a/pkg/code/code.go b/pkg/code/code.go index e07910c..a0c29b6 100644 --- a/pkg/code/code.go +++ b/pkg/code/code.go @@ -10,7 +10,7 @@ import ( var ExecCommand = exec.Command -var FormattedCode = func(files []string) (string, error) { +func FormattedCode(files []string) (string, error) { args := append([]string{"diff", "--cached", "--name-status"}, files...) cmd := ExecCommand("git", args...) diff --git a/pkg/file/files.go b/pkg/file/files.go index ea58398..9fc061c 100644 --- a/pkg/file/files.go +++ b/pkg/file/files.go @@ -5,7 +5,7 @@ import ( "path/filepath" ) -var GetFilesInDir = func(directory string) []string { +func GetFilesInDir(directory string) []string { var files []string filepath.Walk(directory, func(path string, info os.FileInfo, err error) error { diff --git a/scripts/install-linux-auto-commit.sh b/scripts/install-linux-auto-commit.sh index 67d4279..8641ed2 100644 --- a/scripts/install-linux-auto-commit.sh +++ b/scripts/install-linux-auto-commit.sh @@ -41,7 +41,7 @@ if [[ "$answer" == "Y" || "$answer" == "y" ]]; then 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' + git config --local alias.auto "!bash -c './.git/hooks/auto-commit \"\$@\"' --" echo "$TAG" > "$VERSION_FILE" diff --git a/scripts/update-linux-auto-commit.sh b/scripts/update-linux-auto-commit.sh index cb9f4c0..b0f210a 100644 --- a/scripts/update-linux-auto-commit.sh +++ b/scripts/update-linux-auto-commit.sh @@ -61,5 +61,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" From 305aba0215853c902378b46dd0d216818bd7487b Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 18:55:48 -0400 Subject: [PATCH 09/20] Implemented test suite, updated test suite --- cmd/main.go | 19 +++- infra/gtypes/types.go | 2 +- autocommit/autocommit.go => pkg/cli/commit.go | 14 +-- pkg/cli/types.go | 11 ++ .../autocommitupdate.go => pkg/cli/update.go | 7 +- .../cli/version.go | 7 +- .../cli/watcher.go | 14 +-- pkg/code/code.go | 2 +- pkg/code/remote.go | 15 ++- pkg/code/types.go | 19 +++- pkg/git/commit.go | 2 +- pkg/git/diff.go | 8 +- pkg/git/git.go | 4 +- pkg/git/issues.go | 6 +- pkg/git/types.go | 22 ++++ pkg/parser/create-commit-msg.go | 6 +- pkg/parser/detect-tag.go | 2 +- pkg/parser/parser.go | 11 +- pkg/parser/types.go | 18 +++ tests/autocommit_test.go | 103 ++++++++++++++++++ .../golang/implemented_golang_test.go | 4 +- tests/test.g.go | 79 ++++++++------ tests/test.g.type.go | 12 ++ 23 files changed, 290 insertions(+), 97 deletions(-) rename autocommit/autocommit.go => pkg/cli/commit.go (53%) create mode 100644 pkg/cli/types.go rename autocommit/autocommitupdate.go => pkg/cli/update.go (96%) rename autocommit/autocommitversion.go => pkg/cli/version.go (91%) rename autocommit/autocommitwatcher.go => pkg/cli/watcher.go (86%) create mode 100644 pkg/parser/types.go create mode 100644 tests/autocommit_test.go create mode 100644 tests/test.g.type.go diff --git a/cmd/main.go b/cmd/main.go index 4fd8a38..7c91af7 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,15 +2,22 @@ package main import ( "fmt" - "git-auto-commit/autocommit" "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 @@ -20,12 +27,12 @@ func main() { path = fmt.Sprintf("%s/%s", path, os.Args[2]) } - autocommit.Watch(path) + cli.Watch(path) } else if len(os.Args) > 1 && (os.Args[1] == "-v" || os.Args[1] == "--version") { - autocommit.GetVersion(true) + cli.GetVersion(true) } else if len(os.Args) > 1 && (os.Args[1] == "-u" || os.Args[1] == "--update") { - autocommit.Update() + cli.Update() } else { - autocommit.AutoCommit() + cli.AutoCommit() } } diff --git a/infra/gtypes/types.go b/infra/gtypes/types.go index b01bb44..79625c3 100644 --- a/infra/gtypes/types.go +++ b/infra/gtypes/types.go @@ -1 +1 @@ -package gtypes \ No newline at end of file +package gtypes diff --git a/autocommit/autocommit.go b/pkg/cli/commit.go similarity index 53% rename from autocommit/autocommit.go rename to pkg/cli/commit.go index 4eafced..36b2adb 100644 --- a/autocommit/autocommit.go +++ b/pkg/cli/commit.go @@ -1,16 +1,14 @@ -package autocommit +package cli import ( "git-auto-commit/infra/logger" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/parser" "git-auto-commit/pkg/pkgerror" ) -func AutoCommit() { - GetVersion(false) +func (cli *CLI) AutoCommit() { + cli.GetVersion(false) - directory, err := git.GetStagedCountDirectory() + directory, err := cli.Git.GetStagedCountDirectory() if err != nil { logger.ErrorLogger(pkgerror.Err_FailedToGetDiff) return @@ -21,12 +19,12 @@ func AutoCommit() { return } - parserMsg, err := parser.Parser(directory) + parserMsg, err := cli.Parser.ParserIndex(directory) if err != nil { return } - if err := git.Commit(parserMsg); err != nil { + 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/autocommit/autocommitupdate.go b/pkg/cli/update.go similarity index 96% rename from autocommit/autocommitupdate.go rename to pkg/cli/update.go index 760e1d7..a54d82f 100644 --- a/autocommit/autocommitupdate.go +++ b/pkg/cli/update.go @@ -1,4 +1,4 @@ -package autocommit +package cli import ( "fmt" @@ -6,7 +6,6 @@ import ( "git-auto-commit/infra/constants" "git-auto-commit/infra/logger" "git-auto-commit/pkg/file" - "git-auto-commit/pkg/git" "net/http" "os" "os/exec" @@ -15,8 +14,8 @@ import ( "strings" ) -func Update() { - root, err := git.GetGitRoot() +func (cli *CLI) Update() { + root, err := cli.Git.GetGitRoot() if err != nil { logger.ErrorLogger(err) return diff --git a/autocommit/autocommitversion.go b/pkg/cli/version.go similarity index 91% rename from autocommit/autocommitversion.go rename to pkg/cli/version.go index a105351..23c7f4a 100644 --- a/autocommit/autocommitversion.go +++ b/pkg/cli/version.go @@ -1,19 +1,18 @@ -package autocommit +package cli import ( "fmt" "git-auto-commit/config" "git-auto-commit/infra/constants" "git-auto-commit/infra/logger" - "git-auto-commit/pkg/git" "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/autocommit/autocommitwatcher.go b/pkg/cli/watcher.go similarity index 86% rename from autocommit/autocommitwatcher.go rename to pkg/cli/watcher.go index 95a97ae..83528a2 100644 --- a/autocommit/autocommitwatcher.go +++ b/pkg/cli/watcher.go @@ -1,11 +1,9 @@ -package autocommit +package cli import ( "errors" "git-auto-commit/infra/constants" "git-auto-commit/infra/logger" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/parser" "os" "os/exec" "os/signal" @@ -17,8 +15,8 @@ import ( "github.com/fsnotify/fsnotify" ) -func Watch(path string) { - GetVersion(false) +func (cli *CLI) Watch(path string) { + cli.GetVersion(false) watcher, err := fsnotify.NewWatcher() if err != nil { @@ -69,7 +67,7 @@ func Watch(path string) { return } - directory, err := git.GetStagedCountDirectory() + directory, err := cli.Git.GetStagedCountDirectory() if err != nil { logger.ErrorLogger(errors.New("error getting staged files")) return @@ -80,14 +78,14 @@ func Watch(path string) { return } - parser, err := parser.Parser(directory) + 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 index a0c29b6..a5a3181 100644 --- a/pkg/code/code.go +++ b/pkg/code/code.go @@ -10,7 +10,7 @@ import ( var ExecCommand = exec.Command -func FormattedCode(files []string) (string, error) { +func (c *Code) FormattedCode(files []string) (string, error) { args := append([]string{"diff", "--cached", "--name-status"}, files...) cmd := ExecCommand("git", args...) diff --git a/pkg/code/remote.go b/pkg/code/remote.go index 1d28b96..dd3d36b 100644 --- a/pkg/code/remote.go +++ b/pkg/code/remote.go @@ -1,31 +1,30 @@ package code import ( - "git-auto-commit/pkg/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/types.go b/pkg/code/types.go index de2e4c6..eb8bf64 100644 --- a/pkg/code/types.go +++ b/pkg/code/types.go @@ -1,5 +1,22 @@ package code +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 { Name string Params []FunctionParameters @@ -44,4 +61,4 @@ type ClassSignature struct { type SwitchSignature struct { Expr string Cases []string -} \ No newline at end of file +} diff --git a/pkg/git/commit.go b/pkg/git/commit.go index 1e0912f..f67031d 100644 --- a/pkg/git/commit.go +++ b/pkg/git/commit.go @@ -7,7 +7,7 @@ import ( "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 index aab010c..539984e 100644 --- a/pkg/git/diff.go +++ b/pkg/git/diff.go @@ -16,11 +16,11 @@ var diffBufferPool = sync.Pool{ }, } -var GetDiff = func(file string) (string, error) { +func (g *Git) GetDiff(file string) (string, error) { var builder strings.Builder builder.Reset() - root, err := GetGitRoot() + root, err := g.GetGitRoot() if err != nil { return "", err } @@ -43,7 +43,7 @@ var GetDiff = func(file string) (string, error) { return buf.String(), nil } -var GetStagedCountDirectory = func() (string, error) { +func (g *Git) GetStagedCountDirectory() (string, error) { cmd := exec.Command("git", "diff", "--cached", "--numstat") stdout, err := cmd.StdoutPipe() @@ -119,7 +119,7 @@ var GetStagedCountDirectory = func() (string, error) { return "", fmt.Errorf("") } -var GetStagedFiles = func() ([]string, error) { +func (g *Git) GetStagedFiles() ([]string, error) { cmd := exec.Command("git", "diff", "--cached", "--name-only") stdout, err := cmd.StdoutPipe() diff --git a/pkg/git/git.go b/pkg/git/git.go index 48d85e3..b0435e2 100644 --- a/pkg/git/git.go +++ b/pkg/git/git.go @@ -7,7 +7,7 @@ import ( "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 @@ -20,7 +20,7 @@ func GetGitRoot() (string, error) { 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 { diff --git a/pkg/git/issues.go b/pkg/git/issues.go index d585f55..d050002 100644 --- a/pkg/git/issues.go +++ b/pkg/git/issues.go @@ -18,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 { @@ -29,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 { @@ -47,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() diff --git a/pkg/git/types.go b/pkg/git/types.go index aa39796..34abff7 100644 --- a/pkg/git/types.go +++ b/pkg/git/types.go @@ -1,5 +1,27 @@ 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/pkg/parser/create-commit-msg.go b/pkg/parser/create-commit-msg.go index bb73d53..fc39419 100644 --- a/pkg/parser/create-commit-msg.go +++ b/pkg/parser/create-commit-msg.go @@ -5,8 +5,8 @@ import ( "git-auto-commit/infra/constants" ) -var CreateAutoCommitMsg = func(filename, msg *string, changed string) string { - ext := DetectTagByFile(filename, changed) +func (p *Parser) CreateAutoCommitMsg(filename, msg *string, changed string) string { + ext := p.DetectTagByFile(filename, changed) msgCommit, ok := constants.Ratio_Commit[ext] if ok { @@ -17,5 +17,5 @@ var CreateAutoCommitMsg = func(filename, msg *string, changed string) string { return ext + " " + *msg } - return fmt.Sprintf("%s Processed file - %s is refactored", constants.Type_CommitRefactor, filename) + return fmt.Sprintf("%s Processed file - %s is refactored", constants.Type_CommitRefactor, *filename) } diff --git a/pkg/parser/detect-tag.go b/pkg/parser/detect-tag.go index 7707200..094131c 100644 --- a/pkg/parser/detect-tag.go +++ b/pkg/parser/detect-tag.go @@ -7,7 +7,7 @@ import ( "strings" ) -var DetectTagByFile = func(filename *string, changed string) string { +func (p *Parser) DetectTagByFile(filename *string, changed string) string { // check type changed switch changed { case constants.Ch_TypeAdd: diff --git a/pkg/parser/parser.go b/pkg/parser/parser.go index 1ac8f6f..52172e2 100644 --- a/pkg/parser/parser.go +++ b/pkg/parser/parser.go @@ -1,20 +1,19 @@ package parser import ( - "git-auto-commit/pkg/code" "git-auto-commit/pkg/file" "git-auto-commit/pkg/pkgerror" "os" ) -var Parser = func(directory string) (string, error) { +func (p *Parser) ParserIndex(directory string) (string, error) { info, err := os.Stat(directory) if err != nil { return "", pkgerror.CreateError(pkgerror.Err_FailedToReadFile) } if !info.IsDir() { - return CreateAutoCommitMsg(&directory, nil, ""), nil + return p.CreateAutoCommitMsg(&directory, nil, ""), nil } files := file.GetFilesInDir(directory) @@ -22,13 +21,13 @@ var Parser = func(directory string) (string, error) { return "", pkgerror.CreateError(pkgerror.Err_FileNotFound) } - formatted, err := code.FormattedCode(files) + formatted, err := p.Code.FormattedCode(files) if err != nil { return "", pkgerror.CreateError(err) } if formatted == "" { - formattedByRemote, err := code.FormattedByRemote("") + formattedByRemote, err := p.Code.FormattedByRemote("") if err != nil { return "", pkgerror.CreateError(pkgerror.Err_RemoteUnavailable) } @@ -39,7 +38,7 @@ var Parser = func(directory string) (string, error) { } if formatted == "" { - formattedByBranch, err := code.FormattedByBranch() + formattedByBranch, err := p.Code.FormattedByBranch() if err != nil { return "", pkgerror.CreateError(pkgerror.Err_BranchNotFound) } diff --git a/pkg/parser/types.go b/pkg/parser/types.go new file mode 100644 index 0000000..ab07996 --- /dev/null +++ b/pkg/parser/types.go @@ -0,0 +1,18 @@ +package parser + +import "git-auto-commit/pkg/code" + +type Parser struct { + Code code.CodeInterface +} + +type ParserInterface interface { + // create-commit-msg.go + CreateAutoCommitMsg(filename, msg *string, changed string) string + + // detect-tag.go + DetectTagByFile(filename *string, changed string) string + + // parser.go + ParserIndex(directory string) (string, error) +} 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/code/implemented/golang/implemented_golang_test.go b/tests/code/implemented/golang/implemented_golang_test.go index 77e01fa..18d070d 100644 --- a/tests/code/implemented/golang/implemented_golang_test.go +++ b/tests/code/implemented/golang/implemented_golang_test.go @@ -1,11 +1,9 @@ package golang import ( - "git-auto-commit/tests" "testing" ) func TestImplementedGolang(t *testing.T) { - mocks := tests.SaveMocks() - defer mocks.Apply() + } diff --git a/tests/test.g.go b/tests/test.g.go index af3f536..7a00116 100644 --- a/tests/test.g.go +++ b/tests/test.g.go @@ -1,36 +1,49 @@ package tests -import ( - "git-auto-commit/autocommit" - "git-auto-commit/infra/logger" - "git-auto-commit/pkg/git" - "git-auto-commit/pkg/parser" -) - -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: git.GetStagedFiles, - Parser: parser.Parser, - Commit: git.Commit, - ErrorLogger: logger.ErrorLogger, - InfoLogger: logger.InfoLogger, - } -} - -func (m *Mocks) Apply() { - git.GetStagedFiles = m.GetStagedFiles - parser.Parser = m.Parser - git.Commit = m.Commit - logger.ErrorLogger = m.ErrorLogger - logger.InfoLogger = m.InfoLogger - autocommit.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 "" } 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 +} From 726e0a35ca31d27c32ff5cde2b21d3d8d77928e1 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 19:14:19 -0400 Subject: [PATCH 10/20] Updated public reusable packages --- pkg/parser/parser.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/pkg/parser/parser.go b/pkg/parser/parser.go index 52172e2..8f0e4e8 100644 --- a/pkg/parser/parser.go +++ b/pkg/parser/parser.go @@ -1,9 +1,11 @@ package parser import ( + "fmt" "git-auto-commit/pkg/file" "git-auto-commit/pkg/pkgerror" "os" + "path/filepath" ) func (p *Parser) ParserIndex(directory string) (string, error) { @@ -12,6 +14,7 @@ func (p *Parser) ParserIndex(directory string) (string, error) { return "", pkgerror.CreateError(pkgerror.Err_FailedToReadFile) } + // check this is file if !info.IsDir() { return p.CreateAutoCommitMsg(&directory, nil, ""), nil } @@ -21,6 +24,21 @@ func (p *Parser) ParserIndex(directory string) (string, error) { return "", pkgerror.CreateError(pkgerror.Err_FileNotFound) } + // check .ext and max count + extCount := map[string]int{} + maxExt := "" + maxCount := 0 + + for _, file := range files { + ext := filepath.Ext(file) + extCount[ext]++ + + if extCount[ext] > maxCount { + maxCount = extCount[ext] + maxExt = ext + } + } + formatted, err := p.Code.FormattedCode(files) if err != nil { return "", pkgerror.CreateError(err) @@ -48,5 +66,6 @@ func (p *Parser) ParserIndex(directory string) (string, error) { } } - return formatted, nil + maxExt = fmt.Sprintf("file%s", maxExt) + return p.CreateAutoCommitMsg(&maxExt, &formatted, ""), nil } From 5c36e823a207258b59f0dfd24d63ebcad1370ce7 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Sun, 10 Aug 2025 19:20:19 -0400 Subject: [PATCH 11/20] Updated test suite --- .../golang/implemented_golang_test.go | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/code/implemented/golang/implemented_golang_test.go b/tests/code/implemented/golang/implemented_golang_test.go index 18d070d..b972cea 100644 --- a/tests/code/implemented/golang/implemented_golang_test.go +++ b/tests/code/implemented/golang/implemented_golang_test.go @@ -1,9 +1,56 @@ package golang import ( + "fmt" + "git-auto-commit/pkg/code" + "os/exec" + "strings" "testing" ) func TestImplementedGolang(t *testing.T) { + gitOutput := ` + A src/main.go + M src/utils.go + D docs/readme.md + ` + code.ExecCommand = func(name string, args ...string) *exec.Cmd { + return fakeExecCommand(gitOutput) + } + defer func() { + code.ExecCommand = exec.Command + }() + + c := &code.Code{} + + files := []string{"src/main.go", "src/utils.go", "docs/readme.md"} + msg, err := c.FormattedCode(files) + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + + if !strings.Contains(strings.ToLower(msg), "implemented") || !strings.Contains(strings.ToLower(msg), "updated") || !strings.Contains(strings.ToLower(msg), "removed") { + t.Errorf("Expected message to contain implemented, updated and removed parts, got: %s", msg) + } + + if msg == "" { + t.Errorf("Got empty message") + } + + fmt.Println("Formatted commit message:", msg) +} + +func fakeExecCommand(output string) *exec.Cmd { + return &exec.Cmd{ + // Используем Stdin/Stdout подключение через pipe в тесте + // Здесь обман: мы используем os/exec/CommandContext с запуском echo + // но проще - используем встроенный тестовый подход: + + // Для удобства подменяем метод StdoutPipe с помощью интерфейса, а не exec.Cmd. + // В Go это сделать сложно, поэтому можно использовать os/exec.Command с echo: + + // Но тут можно пойти обходным путём (если можно изменить код функции), + // или использовать библиотеку "github.com/Netflix/go-expect" для более сложного мока. + } } From 1d85ef1abe3b9912aea0c1509308eacf88960fe3 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 04:41:21 -0400 Subject: [PATCH 12/20] added tests for golang implemented/modified/delete --- pkg/code/code.go | 14 ++-- pkg/code/tag.go | 25 +++++++ pkg/code/types.go | 4 +- pkg/{parser => commit}/create-commit-msg.go | 6 +- pkg/{parser => commit}/detect-tag.go | 4 +- pkg/parser/parser.go | 23 +----- pkg/parser/types.go | 6 -- .../deleted/golang/deleted_golang_test.go | 39 +++++++++++ .../golang/implemented_docs_golang_test.go | 70 +++++++++++++++++++ .../golang/implemented_golang_test.go | 31 ++------ .../golang/implemented_style_golang_test.go | 38 ++++++++++ .../golang/implemented_test_golang_test.go | 38 ++++++++++ .../modified/golang/modified_golang_test.go | 39 +++++++++++ tests/test.g.go | 8 +++ 14 files changed, 282 insertions(+), 63 deletions(-) create mode 100644 pkg/code/tag.go rename pkg/{parser => commit}/create-commit-msg.go (67%) rename pkg/{parser => commit}/detect-tag.go (91%) create mode 100644 tests/code/deleted/golang/deleted_golang_test.go create mode 100644 tests/code/implemented/golang/implemented_docs_golang_test.go create mode 100644 tests/code/implemented/golang/implemented_style_golang_test.go create mode 100644 tests/code/implemented/golang/implemented_test_golang_test.go create mode 100644 tests/code/modified/golang/modified_golang_test.go diff --git a/pkg/code/code.go b/pkg/code/code.go index a5a3181..3a427d4 100644 --- a/pkg/code/code.go +++ b/pkg/code/code.go @@ -59,23 +59,23 @@ func (c *Code) FormattedCode(files []string) (string, error) { return "", err } - msg := build(added, modified, deleted) - return msg, nil + msg := c.build(added, modified, deleted) + return c.WithTag(files, msg), nil } -func build(added, modified, deleted []string) string { +func (c *Code) build(added, modified, deleted []string) string { var parts []string if len(added) > 0 { - parts = append(parts, "implemented "+summarize(added)) + parts = append(parts, "implemented "+c.summarize(added)) } if len(modified) > 0 { - parts = append(parts, "updated "+summarize(modified)) + parts = append(parts, "updated "+c.summarize(modified)) } if len(deleted) > 0 { - parts = append(parts, "removed "+summarize(deleted)) + parts = append(parts, "removed "+c.summarize(deleted)) } msg := strings.Join(parts, ", ") @@ -86,7 +86,7 @@ func build(added, modified, deleted []string) string { return msg } -func summarize(files []string) string { +func (c *Code) summarize(files []string) string { folders := map[string]struct{}{} for _, file := range files { directory := strings.Split(filepath.ToSlash(file), "/")[0] diff --git a/pkg/code/tag.go b/pkg/code/tag.go new file mode 100644 index 0000000..803a694 --- /dev/null +++ b/pkg/code/tag.go @@ -0,0 +1,25 @@ +package code + +import ( + "git-auto-commit/pkg/commit" + "path/filepath" +) + +func (c *Code) WithTag(files []string, formatted string) string { + // check .ext and max count + extCount := map[string]int{} + maxFile := "" + maxCount := 0 + + for _, file := range files { + ext := filepath.Ext(file) + extCount[ext]++ + + if extCount[ext] > maxCount { + maxCount = extCount[ext] + maxFile = file + } + } + + return commit.CreateAutoCommitMsg(&maxFile, &formatted, "") +} diff --git a/pkg/code/types.go b/pkg/code/types.go index eb8bf64..dd203a7 100644 --- a/pkg/code/types.go +++ b/pkg/code/types.go @@ -1,6 +1,8 @@ package code -import "git-auto-commit/pkg/git" +import ( + "git-auto-commit/pkg/git" +) type Code struct { Git git.GitInterface diff --git a/pkg/parser/create-commit-msg.go b/pkg/commit/create-commit-msg.go similarity index 67% rename from pkg/parser/create-commit-msg.go rename to pkg/commit/create-commit-msg.go index fc39419..ec51d5c 100644 --- a/pkg/parser/create-commit-msg.go +++ b/pkg/commit/create-commit-msg.go @@ -1,12 +1,12 @@ -package parser +package commit import ( "fmt" "git-auto-commit/infra/constants" ) -func (p *Parser) CreateAutoCommitMsg(filename, msg *string, changed string) string { - ext := p.DetectTagByFile(filename, changed) +func CreateAutoCommitMsg(filename, msg *string, changed string) string { + ext := DetectTagByFile(filename, changed) msgCommit, ok := constants.Ratio_Commit[ext] if ok { diff --git a/pkg/parser/detect-tag.go b/pkg/commit/detect-tag.go similarity index 91% rename from pkg/parser/detect-tag.go rename to pkg/commit/detect-tag.go index 094131c..4712a0b 100644 --- a/pkg/parser/detect-tag.go +++ b/pkg/commit/detect-tag.go @@ -1,4 +1,4 @@ -package parser +package commit import ( "git-auto-commit/infra/constants" @@ -7,7 +7,7 @@ import ( "strings" ) -func (p *Parser) DetectTagByFile(filename *string, changed string) string { +func DetectTagByFile(filename *string, changed string) string { // check type changed switch changed { case constants.Ch_TypeAdd: diff --git a/pkg/parser/parser.go b/pkg/parser/parser.go index 8f0e4e8..ff8c109 100644 --- a/pkg/parser/parser.go +++ b/pkg/parser/parser.go @@ -1,11 +1,10 @@ package parser import ( - "fmt" + "git-auto-commit/pkg/commit" "git-auto-commit/pkg/file" "git-auto-commit/pkg/pkgerror" "os" - "path/filepath" ) func (p *Parser) ParserIndex(directory string) (string, error) { @@ -16,7 +15,7 @@ func (p *Parser) ParserIndex(directory string) (string, error) { // check this is file if !info.IsDir() { - return p.CreateAutoCommitMsg(&directory, nil, ""), nil + return commit.CreateAutoCommitMsg(&directory, nil, ""), nil } files := file.GetFilesInDir(directory) @@ -24,21 +23,6 @@ func (p *Parser) ParserIndex(directory string) (string, error) { return "", pkgerror.CreateError(pkgerror.Err_FileNotFound) } - // check .ext and max count - extCount := map[string]int{} - maxExt := "" - maxCount := 0 - - for _, file := range files { - ext := filepath.Ext(file) - extCount[ext]++ - - if extCount[ext] > maxCount { - maxCount = extCount[ext] - maxExt = ext - } - } - formatted, err := p.Code.FormattedCode(files) if err != nil { return "", pkgerror.CreateError(err) @@ -66,6 +50,5 @@ func (p *Parser) ParserIndex(directory string) (string, error) { } } - maxExt = fmt.Sprintf("file%s", maxExt) - return p.CreateAutoCommitMsg(&maxExt, &formatted, ""), nil + return formatted, nil } diff --git a/pkg/parser/types.go b/pkg/parser/types.go index ab07996..18b506f 100644 --- a/pkg/parser/types.go +++ b/pkg/parser/types.go @@ -7,12 +7,6 @@ type Parser struct { } type ParserInterface interface { - // create-commit-msg.go - CreateAutoCommitMsg(filename, msg *string, changed string) string - - // detect-tag.go - DetectTagByFile(filename *string, changed string) string - // parser.go ParserIndex(directory string) (string, error) } diff --git a/tests/code/deleted/golang/deleted_golang_test.go b/tests/code/deleted/golang/deleted_golang_test.go new file mode 100644 index 0000000..8e9d10c --- /dev/null +++ b/tests/code/deleted/golang/deleted_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 deleteExpectedTest string = "Removed middleware components" + +func TestDeletedGolang(t *testing.T) { + gitOutput := ` + D middleware/rate.go + ` + + 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.go"} + 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/golang/implemented_docs_golang_test.go b/tests/code/implemented/golang/implemented_docs_golang_test.go new file mode 100644 index 0000000..f07163b --- /dev/null +++ b/tests/code/implemented/golang/implemented_docs_golang_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 TestImplementedDocGolang(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 TestImplementedDocsGolang(t *testing.T) { + gitNameStatusOutput := ` + A docs/code/readme.md + M docs/code/download.txt + M main/docs/security.md + D pkg/create-commit-msg.go + A pkg/detect-tag.go + A pkg/parser/types.go + ` + + 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/golang/implemented_golang_test.go b/tests/code/implemented/golang/implemented_golang_test.go index b972cea..1272f2c 100644 --- a/tests/code/implemented/golang/implemented_golang_test.go +++ b/tests/code/implemented/golang/implemented_golang_test.go @@ -3,20 +3,21 @@ package golang import ( "fmt" "git-auto-commit/pkg/code" + "git-auto-commit/tests" "os/exec" "strings" "testing" ) +const implementeExpectedTest string = "Implemented source code files" + func TestImplementedGolang(t *testing.T) { gitOutput := ` A src/main.go - M src/utils.go - D docs/readme.md ` code.ExecCommand = func(name string, args ...string) *exec.Cmd { - return fakeExecCommand(gitOutput) + return tests.FakeExecCommand(gitOutput) } defer func() { code.ExecCommand = exec.Command @@ -24,33 +25,15 @@ func TestImplementedGolang(t *testing.T) { c := &code.Code{} - files := []string{"src/main.go", "src/utils.go", "docs/readme.md"} + files := []string{"src/main.go"} msg, err := c.FormattedCode(files) if err != nil { t.Fatalf("Unexpected error: %v", err) } - if !strings.Contains(strings.ToLower(msg), "implemented") || !strings.Contains(strings.ToLower(msg), "updated") || !strings.Contains(strings.ToLower(msg), "removed") { - t.Errorf("Expected message to contain implemented, updated and removed parts, got: %s", msg) - } - - if msg == "" { - t.Errorf("Got empty message") + 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) } - -func fakeExecCommand(output string) *exec.Cmd { - return &exec.Cmd{ - // Используем Stdin/Stdout подключение через pipe в тесте - // Здесь обман: мы используем os/exec/CommandContext с запуском echo - // но проще - используем встроенный тестовый подход: - - // Для удобства подменяем метод StdoutPipe с помощью интерфейса, а не exec.Cmd. - // В Go это сделать сложно, поэтому можно использовать os/exec.Command с echo: - - // Но тут можно пойти обходным путём (если можно изменить код функции), - // или использовать библиотеку "github.com/Netflix/go-expect" для более сложного мока. - } -} diff --git a/tests/code/implemented/golang/implemented_style_golang_test.go b/tests/code/implemented/golang/implemented_style_golang_test.go new file mode 100644 index 0000000..5c5c584 --- /dev/null +++ b/tests/code/implemented/golang/implemented_style_golang_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 TestImplementedStyleGolang(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/golang/implemented_test_golang_test.go b/tests/code/implemented/golang/implemented_test_golang_test.go new file mode 100644 index 0000000..054609b --- /dev/null +++ b/tests/code/implemented/golang/implemented_test_golang_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 TestImplementedTestGolang(t *testing.T) { + gitOutput := ` + A tests/golang_test.go + ` + + 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.go"} + 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/modified/golang/modified_golang_test.go b/tests/code/modified/golang/modified_golang_test.go new file mode 100644 index 0000000..45b4b21 --- /dev/null +++ b/tests/code/modified/golang/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 = "Updated command-line tools" + +func TestModifiedGolang(t *testing.T) { + gitOutput := ` + M cmd/main.go + ` + + 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.go"} + 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 7a00116..3c3f61f 100644 --- a/tests/test.g.go +++ b/tests/test.g.go @@ -1,5 +1,9 @@ package tests +import ( + "os/exec" +) + func (m *gitMocks) GetStagedCountDirectory() (string, error) { return m.stagedDir, m.stagedErr } @@ -47,3 +51,7 @@ func (m *parserMocks) CreateAutoCommitMsg(filename, msg *string, changed string) func (m *parserMocks) DetectTagByFile(filename *string, changed string) string { return "" } + +func FakeExecCommand(output string) *exec.Cmd { + return exec.Command("echo", output) +} From 14a45c008517c24a8dbf401346ae7a20cc62d6d9 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 04:49:19 -0400 Subject: [PATCH 13/20] [test] Implemented and refined test cases to ensure code quality --- .../code/implemented/c/implemented_c_test.go | 39 +++++++++++ .../implemented/c/implemented_docs_c_test.go | 70 +++++++++++++++++++ .../implemented/c/implemented_style_c_test.go | 38 ++++++++++ .../implemented/c/implemented_test_c_test.go | 38 ++++++++++ 4 files changed, 185 insertions(+) create mode 100644 tests/code/implemented/c/implemented_c_test.go create mode 100644 tests/code/implemented/c/implemented_docs_c_test.go create mode 100644 tests/code/implemented/c/implemented_style_c_test.go create mode 100644 tests/code/implemented/c/implemented_test_c_test.go diff --git a/tests/code/implemented/c/implemented_c_test.go b/tests/code/implemented/c/implemented_c_test.go new file mode 100644 index 0000000..f550ce8 --- /dev/null +++ b/tests/code/implemented/c/implemented_c_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 = "Implemented source code files" + +func TestImplementedGolang(t *testing.T) { + gitOutput := ` + A src/main.c + ` + + 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.c"} + 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/implemented/c/implemented_docs_c_test.go b/tests/code/implemented/c/implemented_docs_c_test.go new file mode 100644 index 0000000..728ee6a --- /dev/null +++ b/tests/code/implemented/c/implemented_docs_c_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 TestImplementedDocGolang(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 TestImplementedDocsGolang(t *testing.T) { + gitNameStatusOutput := ` + A docs/code/readme.md + M docs/code/download.txt + M main/docs/security.md + D pkg/create-commit-msg.c + A pkg/detect-tag.c + A pkg/parser/types.c + ` + + 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/c/implemented_style_c_test.go b/tests/code/implemented/c/implemented_style_c_test.go new file mode 100644 index 0000000..5c5c584 --- /dev/null +++ b/tests/code/implemented/c/implemented_style_c_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 TestImplementedStyleGolang(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/c/implemented_test_c_test.go b/tests/code/implemented/c/implemented_test_c_test.go new file mode 100644 index 0000000..f06d05f --- /dev/null +++ b/tests/code/implemented/c/implemented_test_c_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 TestImplementedTestGolang(t *testing.T) { + gitOutput := ` + A tests/c.test.c + ` + + 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/c.test.c"} + 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) +} From 7b30f905054cf02727309190800574cc2fdcfae8 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 05:05:42 -0400 Subject: [PATCH 14/20] Updated public reusable packages --- infra/constants/name-status.go | 1 + pkg/code/code.go | 2 +- pkg/code/tag.go | 82 ++++++++++++++++++++++++++++----- pkg/commit/create-commit-msg.go | 4 +- pkg/commit/detect-tag.go | 13 ++++-- 5 files changed, 83 insertions(+), 19 deletions(-) diff --git a/infra/constants/name-status.go b/infra/constants/name-status.go index c4c4371..49a87da 100644 --- a/infra/constants/name-status.go +++ b/infra/constants/name-status.go @@ -4,4 +4,5 @@ const ( NameStatus_Added = "A" NameStatus_Modified = "M" NameStatus_Deleted = "D" + NameStatus_Renamed = "R" ) diff --git a/pkg/code/code.go b/pkg/code/code.go index 3a427d4..84db121 100644 --- a/pkg/code/code.go +++ b/pkg/code/code.go @@ -60,7 +60,7 @@ func (c *Code) FormattedCode(files []string) (string, error) { } msg := c.build(added, modified, deleted) - return c.WithTag(files, msg), nil + return c.WithTag(files, msg, added, modified, deleted), nil } func (c *Code) build(added, modified, deleted []string) string { diff --git a/pkg/code/tag.go b/pkg/code/tag.go index 803a694..79ec962 100644 --- a/pkg/code/tag.go +++ b/pkg/code/tag.go @@ -1,25 +1,85 @@ package code import ( + "git-auto-commit/infra/constants" "git-auto-commit/pkg/commit" "path/filepath" ) -func (c *Code) WithTag(files []string, formatted string) string { - // check .ext and max count - extCount := map[string]int{} - maxFile := "" +func (c *Code) WithTag(files []string, formatted string, added, modified, deleted []string) string { + // 1) ищем file-type теги по всем файлам (docs/style/test и т.п.) + fileTagCount := map[string]int{} + reprFileForTag := map[string]string{} // для выбранного тега — пример файла + + for _, f := range files { + t := commit.DetectTagByFile(&f, "") // передаём пустой статус, чтобы DetectTagByFile смотрел только на имя/расширение + if t == "" { + continue + } + fileTagCount[t]++ + if _, ok := reprFileForTag[t]; !ok { + reprFileForTag[t] = f + } + } + + if len(fileTagCount) > 0 { + // выбираем самый "частый" file-type тег + chosenTag := "" + maxCnt := 0 + for tg, cnt := range fileTagCount { + if cnt > maxCnt { + maxCnt = cnt + chosenTag = tg + } + } + // используем representative file для сообщения + fileForMsg := reprFileForTag[chosenTag] + return commit.CreateAutoCommitMsg(&fileForMsg, &formatted, chosenTag) + } + + // 2) если file-type тега нет — смотрим на статусы A/M/D/R + statusCount := map[string]int{ + constants.NameStatus_Added: len(added), + constants.NameStatus_Modified: len(modified), + constants.NameStatus_Deleted: len(deleted), + } + + maxStatus := "" maxCount := 0 + for st, cnt := range statusCount { + if cnt > maxCount { + maxCount = cnt + maxStatus = st + } + } - for _, file := range files { - ext := filepath.Ext(file) - extCount[ext]++ + // маппим статус в тип коммита + var tag string + switch maxStatus { + case constants.NameStatus_Added: + tag = constants.Type_CommitFeat + case constants.NameStatus_Modified: + tag = constants.Type_CommitRefactor + case constants.NameStatus_Deleted: + tag = constants.Type_CommitFix + case constants.NameStatus_Renamed: + tag = constants.Type_CommitRefactor + default: + tag = constants.Type_CommitRefactor + } - if extCount[ext] > maxCount { - maxCount = extCount[ext] - maxFile = file + // выбираем файл для CreateAutoCommitMsg по частоте расширений (как раньше) + extCount := map[string]int{} + maxFile := "" + maxExtCount := 0 + for _, f := range files { + ext := filepath.Ext(f) + extCount[ext]++ + if extCount[ext] > maxExtCount { + maxExtCount = extCount[ext] + maxFile = f } } - return commit.CreateAutoCommitMsg(&maxFile, &formatted, "") + return commit.CreateAutoCommitMsg(&maxFile, &formatted, tag) } diff --git a/pkg/commit/create-commit-msg.go b/pkg/commit/create-commit-msg.go index ec51d5c..df0c939 100644 --- a/pkg/commit/create-commit-msg.go +++ b/pkg/commit/create-commit-msg.go @@ -5,8 +5,8 @@ import ( "git-auto-commit/infra/constants" ) -func CreateAutoCommitMsg(filename, msg *string, changed string) string { - ext := DetectTagByFile(filename, changed) +func CreateAutoCommitMsg(filename, msg *string, tag string) string { + ext := DetectTagByFile(filename, tag) msgCommit, ok := constants.Ratio_Commit[ext] if ok { diff --git a/pkg/commit/detect-tag.go b/pkg/commit/detect-tag.go index 4712a0b..12a3e2a 100644 --- a/pkg/commit/detect-tag.go +++ b/pkg/commit/detect-tag.go @@ -7,18 +7,21 @@ import ( "strings" ) -func DetectTagByFile(filename *string, changed string) string { +func DetectTagByFile(filename *string, tag string) string { // check type changed - switch changed { - case constants.Ch_TypeAdd: + switch tag { + case constants.NameStatus_Added: return constants.Type_CommitFeat - case constants.Ch_TypeDelete: + case constants.NameStatus_Deleted: return constants.Type_CommitRefactor - case constants.Ch_TypeChanged: + case constants.NameStatus_Modified: return constants.Type_CommitFix + case constants.NameStatus_Renamed: + return constants.Type_CommitRefactor + } if filename == nil { From f085c05a005ef97d8ccc16c996ea51de4638f102 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 05:20:13 -0400 Subject: [PATCH 15/20] [fix] Updated public reusable packages --- pkg/code/tag.go | 77 +++++-------------- pkg/commit/create-commit-msg.go | 9 ++- .../deleted/golang/deleted_golang_test.go | 2 +- .../code/implemented/c/implemented_c_test.go | 2 +- .../golang/implemented_golang_test.go | 2 +- .../modified/golang/modified_golang_test.go | 2 +- 6 files changed, 30 insertions(+), 64 deletions(-) diff --git a/pkg/code/tag.go b/pkg/code/tag.go index 79ec962..5f1442c 100644 --- a/pkg/code/tag.go +++ b/pkg/code/tag.go @@ -7,37 +7,26 @@ import ( ) func (c *Code) WithTag(files []string, formatted string, added, modified, deleted []string) string { - // 1) ищем file-type теги по всем файлам (docs/style/test и т.п.) - fileTagCount := map[string]int{} - reprFileForTag := map[string]string{} // для выбранного тега — пример файла + // check .ext and max count + extCount := map[string]int{} + maxFile := "" + maxExtCount := 0 - for _, f := range files { - t := commit.DetectTagByFile(&f, "") // передаём пустой статус, чтобы DetectTagByFile смотрел только на имя/расширение - if t == "" { - continue - } - fileTagCount[t]++ - if _, ok := reprFileForTag[t]; !ok { - reprFileForTag[t] = f + for _, file := range files { + ext := filepath.Ext(file) + extCount[ext]++ + + if extCount[ext] > maxExtCount { + maxExtCount = extCount[ext] + maxFile = file } } - if len(fileTagCount) > 0 { - // выбираем самый "частый" file-type тег - chosenTag := "" - maxCnt := 0 - for tg, cnt := range fileTagCount { - if cnt > maxCnt { - maxCnt = cnt - chosenTag = tg - } - } - // используем representative file для сообщения - fileForMsg := reprFileForTag[chosenTag] - return commit.CreateAutoCommitMsg(&fileForMsg, &formatted, chosenTag) + ptag := commit.DetectTagByFile(&maxFile, "") + if ptag != "" { + return commit.CreateAutoCommitMsg(&maxFile, &formatted, "") } - // 2) если file-type тега нет — смотрим на статусы A/M/D/R statusCount := map[string]int{ constants.NameStatus_Added: len(added), constants.NameStatus_Modified: len(modified), @@ -46,40 +35,12 @@ func (c *Code) WithTag(files []string, formatted string, added, modified, delete maxStatus := "" maxCount := 0 - for st, cnt := range statusCount { - if cnt > maxCount { - maxCount = cnt - maxStatus = st - } - } - - // маппим статус в тип коммита - var tag string - switch maxStatus { - case constants.NameStatus_Added: - tag = constants.Type_CommitFeat - case constants.NameStatus_Modified: - tag = constants.Type_CommitRefactor - case constants.NameStatus_Deleted: - tag = constants.Type_CommitFix - case constants.NameStatus_Renamed: - tag = constants.Type_CommitRefactor - default: - tag = constants.Type_CommitRefactor - } - - // выбираем файл для CreateAutoCommitMsg по частоте расширений (как раньше) - extCount := map[string]int{} - maxFile := "" - maxExtCount := 0 - for _, f := range files { - ext := filepath.Ext(f) - extCount[ext]++ - if extCount[ext] > maxExtCount { - maxExtCount = extCount[ext] - maxFile = f + for status, count := range statusCount { + if count > maxCount { + maxCount = count + maxStatus = status } } - return commit.CreateAutoCommitMsg(&maxFile, &formatted, tag) + return commit.CreateAutoCommitMsg(&maxFile, &formatted, maxStatus) } diff --git a/pkg/commit/create-commit-msg.go b/pkg/commit/create-commit-msg.go index df0c939..4baa48a 100644 --- a/pkg/commit/create-commit-msg.go +++ b/pkg/commit/create-commit-msg.go @@ -3,6 +3,7 @@ package commit import ( "fmt" "git-auto-commit/infra/constants" + "strings" ) func CreateAutoCommitMsg(filename, msg *string, tag string) string { @@ -10,11 +11,15 @@ func CreateAutoCommitMsg(filename, msg *string, tag string) string { msgCommit, ok := constants.Ratio_Commit[ext] if ok { - return ext + " " + msgCommit + return strings.TrimSpace(ext + " " + msgCommit) } if msg != nil { - return ext + " " + *msg + 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/tests/code/deleted/golang/deleted_golang_test.go b/tests/code/deleted/golang/deleted_golang_test.go index 8e9d10c..2b9c431 100644 --- a/tests/code/deleted/golang/deleted_golang_test.go +++ b/tests/code/deleted/golang/deleted_golang_test.go @@ -9,7 +9,7 @@ import ( "testing" ) -const deleteExpectedTest string = "Removed middleware components" +const deleteExpectedTest string = "[refactor] Removed middleware components" func TestDeletedGolang(t *testing.T) { gitOutput := ` diff --git a/tests/code/implemented/c/implemented_c_test.go b/tests/code/implemented/c/implemented_c_test.go index f550ce8..3e918b0 100644 --- a/tests/code/implemented/c/implemented_c_test.go +++ b/tests/code/implemented/c/implemented_c_test.go @@ -9,7 +9,7 @@ import ( "testing" ) -const implementeExpectedTest string = "Implemented source code files" +const implementeExpectedTest string = "[feat] Implemented source code files" func TestImplementedGolang(t *testing.T) { gitOutput := ` diff --git a/tests/code/implemented/golang/implemented_golang_test.go b/tests/code/implemented/golang/implemented_golang_test.go index 1272f2c..1170ef8 100644 --- a/tests/code/implemented/golang/implemented_golang_test.go +++ b/tests/code/implemented/golang/implemented_golang_test.go @@ -9,7 +9,7 @@ import ( "testing" ) -const implementeExpectedTest string = "Implemented source code files" +const implementeExpectedTest string = "[feat] Implemented source code files" func TestImplementedGolang(t *testing.T) { gitOutput := ` diff --git a/tests/code/modified/golang/modified_golang_test.go b/tests/code/modified/golang/modified_golang_test.go index 45b4b21..c8334f8 100644 --- a/tests/code/modified/golang/modified_golang_test.go +++ b/tests/code/modified/golang/modified_golang_test.go @@ -9,7 +9,7 @@ import ( "testing" ) -const modifieExpectedTest string = "Updated command-line tools" +const modifieExpectedTest string = "[fix] Updated command-line tools" func TestModifiedGolang(t *testing.T) { gitOutput := ` From efda7fcaf74d772e06d5fe4de852e658fe1bde1b Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 07:04:16 -0400 Subject: [PATCH 16/20] added binary makefile building --- .github/workflows/release.yml | 28 ++++++-- Makefile | 20 ++++-- ...deleted_golang_test.go => deleted_test.go} | 8 +-- .../implemented/c/implemented_style_c_test.go | 38 ---------- .../implemented/c/implemented_test_c_test.go | 38 ---------- .../golang/implemented_docs_golang_test.go | 70 ------------------- .../golang/implemented_golang_test.go | 39 ----------- ...c_test.go => implemented_tag_docs_test.go} | 14 ++-- ..._test.go => implemented_tag_style_test.go} | 4 +- ...g_test.go => implemented_tag_test_test.go} | 8 +-- ...lemented_c_test.go => implemented_test.go} | 8 +-- .../{golang => }/modified_golang_test.go | 8 +-- 12 files changed, 62 insertions(+), 221 deletions(-) rename tests/code/deleted/{golang/deleted_golang_test.go => deleted_test.go} (81%) delete mode 100644 tests/code/implemented/c/implemented_style_c_test.go delete mode 100644 tests/code/implemented/c/implemented_test_c_test.go delete mode 100644 tests/code/implemented/golang/implemented_docs_golang_test.go delete mode 100644 tests/code/implemented/golang/implemented_golang_test.go rename tests/code/implemented/{c/implemented_docs_c_test.go => implemented_tag_docs_test.go} (81%) rename tests/code/implemented/{golang/implemented_style_golang_test.go => implemented_tag_style_test.go} (87%) rename tests/code/implemented/{golang/implemented_test_golang_test.go => implemented_tag_test_test.go} (78%) rename tests/code/implemented/{c/implemented_c_test.go => implemented_test.go} (82%) rename tests/code/modified/{golang => }/modified_golang_test.go (82%) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f268bd0..03eefc5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,16 +20,32 @@ jobs: with: go-version: '1.23.0' - - name: Build auto-commit binary (Windows) + - name: Build auto-commit binary (windows adm64) run: | - GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o ./bin/auto-commit-win . - upx --best --lzma ./bin/auto-commit-win + GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-windows-amd64 ./cmd + upx --best --lzma bin/auto-commit-windows-amd64 || true - - name: Build auto-commit binary (Linux) + - name: Build auto-commit binary (linux adm64) run: | sudo apt-get update && sudo apt-get install upx -y - go build -ldflags="-s -w" -trimpath -o ./bin/auto-commit . - upx --best --lzma ./bin/auto-commit + 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 + + - name: Build auto-commit binary (linux arm64) + run: | + sudo apt-get update && sudo apt-get install upx -y + 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 + + - name: Build auto-commit binary (macOS intel) + run: | + sudo apt-get update && sudo apt-get install upx -y + GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-macos-amd64 ./cmd + + - name: Build auto-commit binary (macOS Apple Silicon / M1, M2) + run: | + sudo apt-get update && sudo apt-get install upx -y + GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-macos-arm64 ./cmd - name: Set up Git run: | diff --git a/Makefile b/Makefile index 1e23b72..87bcde4 100644 --- a/Makefile +++ b/Makefile @@ -28,12 +28,22 @@ buildrelease: @echo "Running release build (windows, linux)..." # windows - @GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit ./cmd - upx.exe --best --lzma bin/auto-commit || true + @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 - @GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o bin/auto-commit-linux ./cmd - upx --best --lzma bin/auto-commit-linux || 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..." diff --git a/tests/code/deleted/golang/deleted_golang_test.go b/tests/code/deleted/deleted_test.go similarity index 81% rename from tests/code/deleted/golang/deleted_golang_test.go rename to tests/code/deleted/deleted_test.go index 2b9c431..96ef104 100644 --- a/tests/code/deleted/golang/deleted_golang_test.go +++ b/tests/code/deleted/deleted_test.go @@ -11,9 +11,9 @@ import ( const deleteExpectedTest string = "[refactor] Removed middleware components" -func TestDeletedGolang(t *testing.T) { +func TestDeleted(t *testing.T) { gitOutput := ` - D middleware/rate.go + D middleware/rate.del ` code.ExecCommand = func(name string, args ...string) *exec.Cmd { @@ -25,7 +25,7 @@ func TestDeletedGolang(t *testing.T) { c := &code.Code{} - files := []string{"middleware/rate.go"} + files := []string{"middleware/rate.del"} msg, err := c.FormattedCode(files) if err != nil { t.Fatalf("Unexpected error: %v", err) @@ -35,5 +35,5 @@ func TestDeletedGolang(t *testing.T) { t.Errorf("Expected commit message:\n%q\nGot:%q", deleteExpectedTest, msg) } - fmt.Println("Formatted commit message:", msg) + fmt.Println("==> Formatted commit message:", msg) } diff --git a/tests/code/implemented/c/implemented_style_c_test.go b/tests/code/implemented/c/implemented_style_c_test.go deleted file mode 100644 index 5c5c584..0000000 --- a/tests/code/implemented/c/implemented_style_c_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package golang - -import ( - "fmt" - "git-auto-commit/infra/constants" - "git-auto-commit/pkg/code" - "git-auto-commit/tests" - "os/exec" - "strings" - "testing" -) - -func TestImplementedStyleGolang(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/c/implemented_test_c_test.go b/tests/code/implemented/c/implemented_test_c_test.go deleted file mode 100644 index f06d05f..0000000 --- a/tests/code/implemented/c/implemented_test_c_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package golang - -import ( - "fmt" - "git-auto-commit/infra/constants" - "git-auto-commit/pkg/code" - "git-auto-commit/tests" - "os/exec" - "strings" - "testing" -) - -func TestImplementedTestGolang(t *testing.T) { - gitOutput := ` - A tests/c.test.c - ` - - 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/c.test.c"} - 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/golang/implemented_docs_golang_test.go b/tests/code/implemented/golang/implemented_docs_golang_test.go deleted file mode 100644 index f07163b..0000000 --- a/tests/code/implemented/golang/implemented_docs_golang_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package golang - -import ( - "fmt" - "git-auto-commit/infra/constants" - "git-auto-commit/pkg/code" - "git-auto-commit/tests" - "os/exec" - "strings" - "testing" -) - -func TestImplementedDocGolang(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 TestImplementedDocsGolang(t *testing.T) { - gitNameStatusOutput := ` - A docs/code/readme.md - M docs/code/download.txt - M main/docs/security.md - D pkg/create-commit-msg.go - A pkg/detect-tag.go - A pkg/parser/types.go - ` - - 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/golang/implemented_golang_test.go b/tests/code/implemented/golang/implemented_golang_test.go deleted file mode 100644 index 1170ef8..0000000 --- a/tests/code/implemented/golang/implemented_golang_test.go +++ /dev/null @@ -1,39 +0,0 @@ -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 TestImplementedGolang(t *testing.T) { - gitOutput := ` - A src/main.go - ` - - 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.go"} - 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/implemented/c/implemented_docs_c_test.go b/tests/code/implemented/implemented_tag_docs_test.go similarity index 81% rename from tests/code/implemented/c/implemented_docs_c_test.go rename to tests/code/implemented/implemented_tag_docs_test.go index 728ee6a..14fe16e 100644 --- a/tests/code/implemented/c/implemented_docs_c_test.go +++ b/tests/code/implemented/implemented_tag_docs_test.go @@ -10,7 +10,7 @@ import ( "testing" ) -func TestImplementedDocGolang(t *testing.T) { +func TestImplementedTagDoc(t *testing.T) { gitOutput := ` A README.md ` @@ -34,17 +34,17 @@ func TestImplementedDocGolang(t *testing.T) { t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitDocs, msg) } - fmt.Println("Formatted commit message:", msg) + fmt.Println("==> Formatted commit message:", msg) } -func TestImplementedDocsGolang(t *testing.T) { +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.c - A pkg/detect-tag.c - A pkg/parser/types.c + 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 { @@ -66,5 +66,5 @@ func TestImplementedDocsGolang(t *testing.T) { t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitDocs, msg) } - fmt.Println("Formatted commit message:", msg) + fmt.Println("==> Formatted commit message:", msg) } diff --git a/tests/code/implemented/golang/implemented_style_golang_test.go b/tests/code/implemented/implemented_tag_style_test.go similarity index 87% rename from tests/code/implemented/golang/implemented_style_golang_test.go rename to tests/code/implemented/implemented_tag_style_test.go index 5c5c584..58c4455 100644 --- a/tests/code/implemented/golang/implemented_style_golang_test.go +++ b/tests/code/implemented/implemented_tag_style_test.go @@ -10,7 +10,7 @@ import ( "testing" ) -func TestImplementedStyleGolang(t *testing.T) { +func TestImplementedTagStyle(t *testing.T) { gitOutput := ` A styles/components.css ` @@ -34,5 +34,5 @@ func TestImplementedStyleGolang(t *testing.T) { t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitStyle, msg) } - fmt.Println("Formatted commit message:", msg) + fmt.Println("==> Formatted commit message:", msg) } diff --git a/tests/code/implemented/golang/implemented_test_golang_test.go b/tests/code/implemented/implemented_tag_test_test.go similarity index 78% rename from tests/code/implemented/golang/implemented_test_golang_test.go rename to tests/code/implemented/implemented_tag_test_test.go index 054609b..d7c57d2 100644 --- a/tests/code/implemented/golang/implemented_test_golang_test.go +++ b/tests/code/implemented/implemented_tag_test_test.go @@ -10,9 +10,9 @@ import ( "testing" ) -func TestImplementedTestGolang(t *testing.T) { +func TestImplementedTagTest(t *testing.T) { gitOutput := ` - A tests/golang_test.go + A tests/golang_test.impl ` code.ExecCommand = func(name string, args ...string) *exec.Cmd { @@ -24,7 +24,7 @@ func TestImplementedTestGolang(t *testing.T) { c := &code.Code{} - files := []string{"tests/golang_test.go"} + files := []string{"tests/golang_test.impl"} msg, err := c.FormattedCode(files) if err != nil { t.Fatalf("Unexpected error: %v", err) @@ -34,5 +34,5 @@ func TestImplementedTestGolang(t *testing.T) { t.Errorf("Expected commit message including:%q Got: %q", constants.Type_CommitTest, msg) } - fmt.Println("Formatted commit message:", msg) + fmt.Println("==> Formatted commit message:", msg) } diff --git a/tests/code/implemented/c/implemented_c_test.go b/tests/code/implemented/implemented_test.go similarity index 82% rename from tests/code/implemented/c/implemented_c_test.go rename to tests/code/implemented/implemented_test.go index 3e918b0..5636a8a 100644 --- a/tests/code/implemented/c/implemented_c_test.go +++ b/tests/code/implemented/implemented_test.go @@ -11,9 +11,9 @@ import ( const implementeExpectedTest string = "[feat] Implemented source code files" -func TestImplementedGolang(t *testing.T) { +func TestImplemented(t *testing.T) { gitOutput := ` - A src/main.c + A src/main.impl ` code.ExecCommand = func(name string, args ...string) *exec.Cmd { @@ -25,7 +25,7 @@ func TestImplementedGolang(t *testing.T) { c := &code.Code{} - files := []string{"src/main.c"} + files := []string{"src/main.impl"} msg, err := c.FormattedCode(files) if err != nil { t.Fatalf("Unexpected error: %v", err) @@ -35,5 +35,5 @@ func TestImplementedGolang(t *testing.T) { t.Errorf("Expected commit message:\n%q\nGot:\n%q", implementeExpectedTest, msg) } - fmt.Println("Formatted commit message:", msg) + fmt.Println("==> Formatted commit message:", msg) } diff --git a/tests/code/modified/golang/modified_golang_test.go b/tests/code/modified/modified_golang_test.go similarity index 82% rename from tests/code/modified/golang/modified_golang_test.go rename to tests/code/modified/modified_golang_test.go index c8334f8..f99c56c 100644 --- a/tests/code/modified/golang/modified_golang_test.go +++ b/tests/code/modified/modified_golang_test.go @@ -11,9 +11,9 @@ import ( const modifieExpectedTest string = "[fix] Updated command-line tools" -func TestModifiedGolang(t *testing.T) { +func TestModified(t *testing.T) { gitOutput := ` - M cmd/main.go + M cmd/main.mdf ` code.ExecCommand = func(name string, args ...string) *exec.Cmd { @@ -25,7 +25,7 @@ func TestModifiedGolang(t *testing.T) { c := &code.Code{} - files := []string{"cmd/main.go"} + files := []string{"cmd/main.mdf"} msg, err := c.FormattedCode(files) if err != nil { t.Fatalf("Unexpected error: %v", err) @@ -35,5 +35,5 @@ func TestModifiedGolang(t *testing.T) { t.Errorf("Expected commit message:\n%q\nGot:%q", modifieExpectedTest, msg) } - fmt.Println("Formatted commit message:", msg) + fmt.Println("==> Formatted commit message:", msg) } From cde1b25f79c890f725ac430e0212ec7ceea4e635 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 07:05:52 -0400 Subject: [PATCH 17/20] [fix] Updated infrastructure as code --- infra/constants/expanding-notation-folders.go | 191 ++++++++++-------- 1 file changed, 104 insertions(+), 87 deletions(-) diff --git a/infra/constants/expanding-notation-folders.go b/infra/constants/expanding-notation-folders.go index 8adf9ee..771c917 100644 --- a/infra/constants/expanding-notation-folders.go +++ b/infra/constants/expanding-notation-folders.go @@ -1,91 +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", + "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", } From 37fea8494eb93a5f9473c846096d365b08ce5c97 Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 08:08:59 -0400 Subject: [PATCH 18/20] [fix] Implemented build scripts, updated build scripts --- .github/workflows/release.yml | 12 ++-- infra/constants/github.go | 1 + pkg/cli/update.go | 10 ++- scripts/install-linux-auto-commit.sh | 17 ++++- scripts/install-macos-auto-commit.sh | 74 ++++++++++++++++++++++ scripts/install-windows-auto-commit.ps1 | 2 +- scripts/update-linux-auto-commit.sh | 18 +++++- scripts/update-macos-auto-commit.sh | 82 +++++++++++++++++++++++++ scripts/update-windows-auto-commit.ps1 | 2 +- 9 files changed, 207 insertions(+), 11 deletions(-) create mode 100644 scripts/install-macos-auto-commit.sh create mode 100644 scripts/update-macos-auto-commit.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 03eefc5..66fdbad 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -225,12 +225,14 @@ jobs: [©thefuture-industries](https://github.com/thefuture-industries) files: | - ./bin/auto-commit - ./bin/auto-commit-win - ./scripts/install-linux-auto-commit.sh + ./bin/auto-commit-windows-amd64 + ./bin/auto-commit-linux-amd64 + ./bin/auto-commit-linux-arm64 + ./bin/auto-commit-macos-amd64 + ./bin/auto-commit-macos-arm64 ./scripts/install-windows-auto-commit.ps1 - ./scripts/update-windows-auto-commit.ps1 - ./scripts/update-linux-auto-commit.sh + ./scripts/install-linux-auto-commit.sh + ./scripts/install-macos-auto-commit.sh - name: Create new branch for next version run: | diff --git a/infra/constants/github.go b/infra/constants/github.go index bf8191a..74595fe 100644 --- a/infra/constants/github.go +++ b/infra/constants/github.go @@ -6,5 +6,6 @@ const ( 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/pkg/cli/update.go b/pkg/cli/update.go index a54d82f..d1c377e 100644 --- a/pkg/cli/update.go +++ b/pkg/cli/update.go @@ -53,12 +53,18 @@ func (cli *CLI) Update() { var scriptUpdate string var scriptUpdateExt string - if runtime.GOOS == "windows" { + + 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 { + 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) diff --git a/scripts/install-linux-auto-commit.sh b/scripts/install-linux-auto-commit.sh index 8641ed2..852e4d4 100644 --- a/scripts/install-linux-auto-commit.sh +++ b/scripts/install-linux-auto-commit.sh @@ -25,7 +25,22 @@ 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" +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 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 494d0d9..19833b7 100644 --- a/scripts/install-windows-auto-commit.ps1 +++ b/scripts/install-windows-auto-commit.ps1 @@ -21,7 +21,7 @@ $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" +$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." diff --git a/scripts/update-linux-auto-commit.sh b/scripts/update-linux-auto-commit.sh index b0f210a..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') 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 8fd22b0..56eb846 100644 --- a/scripts/update-windows-auto-commit.ps1 +++ b/scripts/update-windows-auto-commit.ps1 @@ -13,7 +13,7 @@ if ($proc) { $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" +$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 From cc4f8d794bd15164cce3cb93be5eff102d6e407b Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 08:13:57 -0400 Subject: [PATCH 19/20] [docs] Performed comprehensive updates and revisions to the documentation --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index af5f600..7e6aea3 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,14 @@ 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) ``` +### 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 From 96df11b7be79e91787186ba22edd9a4099f3e3ed Mon Sep 17 00:00:00 2001 From: noneandundefined Date: Tue, 12 Aug 2025 08:20:38 -0400 Subject: [PATCH 20/20] [fix] Updated public reusable packages --- pkg/git/diff.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pkg/git/diff.go b/pkg/git/diff.go index 539984e..a433155 100644 --- a/pkg/git/diff.go +++ b/pkg/git/diff.go @@ -3,7 +3,6 @@ package git import ( "bufio" "bytes" - "fmt" "os/exec" "strconv" "strings" @@ -116,7 +115,7 @@ func (g *Git) GetStagedCountDirectory() (string, error) { return maxDirectory, nil } - return "", fmt.Errorf("") + return "", nil } func (g *Git) GetStagedFiles() ([]string, error) {