Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: build script #9

Merged
merged 3 commits into from
Dec 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 124 additions & 83 deletions scripts/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,116 +15,166 @@ import (
"github.com/cli/safeexec"
)

// buildConfig is the configuration for the build process
type buildConfig struct {
currentDir string
buildDir string
binDir string
listsDir string
preConfigsDir string
zipPath string
}

func main() {
if !isWindows() {
os.Exit(1)
}

s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)

s.Suffix = " [1/4] Building..."
s.FinalMSG = "[3/4] Building...\n"
s.HideCursor = true
s.Start()
ldflags := os.Getenv("GO_LDFLAGS")
ldflags = fmt.Sprintf("-X main.version=%s %s", version(), ldflags)
_ = os.Mkdir("build", os.ModePerm)
err := run("go", "build", "-ldflags", ldflags, "-o", "build", "./cmd/...")

config, err := initBuildConfig()
if err != nil {
fmt.Println("Build failed:", err)
fmt.Printf("Error initializing build config: %v\n", err)
os.Exit(1)
}

if err := runBuildSteps(config); err != nil {
fmt.Printf("Build failed: %v\n", err)
os.Exit(1)
}
s.Stop()

// Get current directory
fmt.Printf("\nRelease build ready! Check '%s'\n", config.zipPath)
fmt.Println("Press Enter to continue...")
fmt.Scanln()
}

// initBuildConfig initializes the build configuration
func initBuildConfig() (*buildConfig, error) {
currentDir, err := os.Getwd()
if err != nil {
fmt.Printf("Error getting current directory: %v\n", err)
os.Exit(1)
return nil, fmt.Errorf("error getting current directory: %v", err)
}

// Define paths
buildDir := filepath.Join(currentDir, "build")
binDir := filepath.Join(currentDir, "bin")
listsDir := filepath.Join(currentDir, "lists")
preConfigsDir := filepath.Join(currentDir, "pre-configs")
return &buildConfig{
currentDir: currentDir,
buildDir: buildDir,
binDir: filepath.Join(currentDir, "bin"),
listsDir: filepath.Join(currentDir, "lists"),
preConfigsDir: filepath.Join(currentDir, "pre-configs"),
zipPath: filepath.Join(buildDir, "zapret-discord-youtube-ankddev.zip"),
}, nil
}

// runBuildSteps runs the build steps
func runBuildSteps(config *buildConfig) error {
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
s.HideCursor = true

// Step 1: Build
s.Suffix = " [1/4] Building..."
s.FinalMSG = "[1/4] Build successful\n"
s.Start()
if err := buildExecutables(); err != nil {
return fmt.Errorf("build failed: %v", err)
}
s.Stop()

// Step 2: Check paths and create zip
if err := validatePaths(config); err != nil {
return err
}

zipFile, zipWriter, err := createZipFile(config.zipPath)
if err != nil {
return err
}
defer zipFile.Close()
defer zipWriter.Close()

// Step 3: Add directories
s.Suffix = " [2/4] Adding directories..."
s.FinalMSG = "[2/4] Directories added\n"
s.Start()
if err := addDirectories(zipWriter, config); err != nil {
return err
}
s.Stop()

// Check required paths exist
requiredPaths := []string{
buildDir,
listsDir,
preConfigsDir,
// Step 4: Add files
s.Suffix = " [3/4] Adding files..."
s.FinalMSG = "[3/4] Files added\n"
s.Start()
if err := addFiles(zipWriter, config); err != nil {
return err
}
s.Stop()

for _, path := range requiredPaths {
fmt.Println("[4/4] Release archive created successfully!")
return nil
}

// buildExecutables builds the executables
func buildExecutables() error {
_ = os.Mkdir("build", os.ModePerm)
ldflags := fmt.Sprintf("-X main.version=%s %s", version(), os.Getenv("GO_LDFLAGS"))
return run("go", "build", "-ldflags", ldflags, "-o", "build", "./cmd/...")
}

// validatePaths validates the paths
func validatePaths(config *buildConfig) error {
paths := []string{config.buildDir, config.listsDir, config.preConfigsDir}
for _, path := range paths {
if _, err := os.Stat(path); os.IsNotExist(err) {
fmt.Printf("Required directory not found: %s\n", path)
os.Exit(1)
return fmt.Errorf("required directory not found: %s", path)
}
}
return nil
}

// Create zip file
zipPath := filepath.Join(buildDir, "zapret-discord-youtube-ankddev.zip")
// createZipFile creates the zip file
func createZipFile(zipPath string) (*os.File, *zip.Writer, error) {
zipFile, err := os.Create(zipPath)
if err != nil {
fmt.Printf("Error creating zip file: %v\n", err)
os.Exit(1)
return nil, nil, fmt.Errorf("error creating zip file: %v", err)
}
defer zipFile.Close()

zipWriter := zip.NewWriter(zipFile)
defer zipWriter.Close()
return zipFile, zip.NewWriter(zipFile), nil
}

// Add directories to zip
// addDirectories adds the directories to the zip file
func addDirectories(zipWriter *zip.Writer, config *buildConfig) error {
dirsToAdd := map[string]string{
"lists": listsDir,
"pre-configs": preConfigsDir,
"bin": binDir,
"lists": config.listsDir,
"pre-configs": config.preConfigsDir,
"bin": config.binDir,
}

s.Suffix = " [2/4] Adding directories..."
s.FinalMSG = "[2/4] Adding directories...\n"
s.HideCursor = true
s.Start()
for zipPath, fsPath := range dirsToAdd {
err = addDirToZip(zipWriter, zipPath, fsPath)
if err != nil {
fmt.Printf("Error adding directory %s to zip: %v\n", fsPath, err)
os.Exit(1)
if err := addDirToZip(zipWriter, zipPath, fsPath); err != nil {
return fmt.Errorf("error adding directory %s: %v", fsPath, err)
}
}
s.Stop()
return nil
}

// Add individual files
s.Suffix = " [3/4] Adding files..."
s.FinalMSG = "[3/4] Adding files...\n"
s.HideCursor = true
s.Start()
// addFiles adds the files to the zip file
func addFiles(zipWriter *zip.Writer, config *buildConfig) error {
filesToAdd := map[string]string{
"blockcheck.cmd": filepath.Join(currentDir, "blockcheck.cmd"),
"Add to autorun.exe": filepath.Join(buildDir, "add_to_autorun.exe"),
"Automatically search pre-config.exe": filepath.Join(buildDir, "preconfig_tester.exe"),
"Run pre-config.exe": filepath.Join(buildDir, "run_preconfig.exe"),
"Set domain list.exe": filepath.Join(buildDir, "select_domains.exe"),
"Check for updates.exe": filepath.Join(buildDir, "check_for_updates.exe"),
"blockcheck.cmd": filepath.Join(config.currentDir, "blockcheck.cmd"),
"Add to autorun.exe": filepath.Join(config.buildDir, "add_to_autorun.exe"),
"Automatically search pre-config.exe": filepath.Join(config.buildDir, "preconfig_tester.exe"),
"Run pre-config.exe": filepath.Join(config.buildDir, "run_preconfig.exe"),
"Set domain list.exe": filepath.Join(config.buildDir, "select_domains.exe"),
"Check for updates.exe": filepath.Join(config.buildDir, "check_for_updates.exe"),
}

for zipPath, fsPath := range filesToAdd {
err = addFileToZip(zipWriter, zipPath, fsPath)
if err != nil {
fmt.Printf("Error adding file %s to zip: %v\n", fsPath, err)
os.Exit(1)
if err := addFileToZip(zipWriter, zipPath, fsPath); err != nil {
return fmt.Errorf("error adding file %s: %v", fsPath, err)
}
}

s.Stop()

fmt.Println("[4/4] Release archive created successfully!")
fmt.Printf("\nRelease build ready! Check '%s'\n", zipPath)
fmt.Println("Press Enter to continue...")
fmt.Scanln()
return nil
}

// addDirToZip adds the directory to the zip file
func addDirToZip(zipWriter *zip.Writer, zipPath string, fsPath string) error {
return filepath.Walk(fsPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
Expand All @@ -146,6 +196,7 @@ func addDirToZip(zipWriter *zip.Writer, zipPath string, fsPath string) error {
})
}

// addFileToZip adds the file to the zip file
func addFileToZip(zipWriter *zip.Writer, zipPath string, fsPath string) error {
file, err := os.Open(fsPath)
if err != nil {
Expand Down Expand Up @@ -177,6 +228,7 @@ func version() string {
return rev
}

// cmdOutput runs a command and returns its output
func cmdOutput(args ...string) (string, error) {
exe, err := safeexec.LookPath(args[0])
if err != nil {
Expand All @@ -198,6 +250,7 @@ func isWindows() bool {
return false
}

// run runs a command
func run(args ...string) error {
exe, err := safeexec.LookPath(args[0])
if err != nil {
Expand All @@ -208,15 +261,3 @@ func run(args ...string) error {
cmd.Stderr = os.Stderr
return cmd.Run()
}

func shellInspect(args []string) string {
fmtArgs := make([]string, len(args))
for i, arg := range args {
if strings.ContainsAny(arg, " \t'\"") {
fmtArgs[i] = fmt.Sprintf("%q", arg)
} else {
fmtArgs[i] = arg
}
}
return strings.Join(fmtArgs, " ")
}