api_sync/git.go
2026-06-10 16:00:37 +03:00

78 lines
2.2 KiB
Go
Executable file

package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
/* GIT OPERATIONS */
func syncGitRepo() error {
if _, err := os.Stat(gitRepoPath); os.IsNotExist(err) {
log.Printf("[Git] Cloning repository to %s", gitRepoPath)
parentDir := filepath.Dir(gitRepoPath)
if err := os.MkdirAll(parentDir, 0755); err != nil {
return fmt.Errorf("failed to create parent directory: %w", err)
}
cmd := exec.Command("git", "clone", gitRepoURL, gitRepoPath)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("git clone failed: %w, output: %s", err, output)
}
log.Println("[Git] Repository cloned successfully")
} else {
log.Println("[Git] Repository exists, checking for updates")
cmd := exec.Command("git", "-C", gitRepoPath, "pull")
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("git pull failed: %w, output: %s", err, output)
}
outputStr := strings.TrimSpace(string(output))
if strings.Contains(outputStr, "Already up to date") {
log.Println("[Git] Repository already up to date")
} else {
log.Printf("[Git] Repository updated: %s", outputStr)
}
}
// Настраиваем git config если не настроен
cmd := exec.Command("git", "-C", gitRepoPath, "config", "user.email", "waf-sync@cirex.ru")
cmd.CombinedOutput()
cmd = exec.Command("git", "-C", gitRepoPath, "config", "user.name", "WAF Sync Bot")
cmd.CombinedOutput()
return nil
}
func gitCommitAndPush(message string) error {
cmd := exec.Command("git", "-C", gitRepoPath, "add", whitelistFile)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("git add failed: %w, output: %s", err, output)
}
cmd = exec.Command("git", "-C", gitRepoPath, "commit", "-m", message)
output, err := cmd.CombinedOutput()
if err != nil {
if strings.Contains(string(output), "nothing to commit") {
log.Println("[Git] Nothing to commit")
return nil
}
return fmt.Errorf("git commit failed: %w, output: %s", err, output)
}
cmd = exec.Command("git", "-C", gitRepoPath, "push")
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("git push failed: %w, output: %s", err, output)
}
return nil
}