Skip to content

Commit

Permalink
prepared to frist release
Browse files Browse the repository at this point in the history
  • Loading branch information
andrearaponi committed Jan 29, 2024
1 parent 4ac1413 commit 706ad70
Show file tree
Hide file tree
Showing 13 changed files with 389 additions and 60 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/bin
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Andrea Raponi

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.
91 changes: 90 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,90 @@
# wslSnappy
# WSL Snappy Backup

![Version](https://img.shields.io/badge/version-1.0.0-green.svg)

WSL Snappy Backup is a utility tool for backing up Windows Subsystem for Linux (WSL) distributions. It supports both sequential and parallel backup modes, providing flexibility and efficiency.

## Features

- Backup WSL distributions to a specified directory.
- Run backups either sequentially or in parallel ("rocket mode") for increased speed.
- Environment variable configuration for easy setup.
- Notification alerts on backup completion or failure.

## Prerequisites

Before you start using WSL Snappy Backup, make sure you have:

- Windows 10 or higher with WSL installed.
- Go programming language environment.
- WSL distributions that you want to back up.

## Installation

1. Clone the repository or download the source code.

2. Navigate to the source code directory.

3. Compile the program:

bash


1. `GOOS=windows GOARCH=amd64 go build -ldflags="-H windowsgui" -o bin/WSLSnappy.exe cmd/main.go`


## Configuration

Set the following environment variables according to your system setup:

- `WSL_BACKUP_DIR`: The directory where the WSL distributions will be backed up.
- `WSL_DISTRIBUTIONS`: The list of WSL distribution names to back up, separated by commas (e.g., `Ubuntu,Debian`).

You can set these variables using the Windows Command Prompt:

```bash

`setx WSL_BACKUP_DIR "C:\path\to\your\backup\directory" setx WSL_DISTRIBUTIONS "Ubuntu,Debian"`
```

## Usage

Run the compiled executable from the command line:

- To perform a sequential backup:

```bash


- `.\bin\WSLSnappy.exe`
```

- To perform backups in parallel (rocket mode):

```bash


- `.\bin\WSLSnappy.exe --rocket`

```

The program will start the backup process based on your configuration and display the time taken to complete the backups.

## Notifications

Upon completion or failure of a backup, a desktop notification will be shown, informing you of the status.

## Contributing

Contributions, issues, and feature requests are welcome.
Please feel free to submit issues and pull requests.

## Buy me a coffee

Whether you use this project, have learned something from it, or just like it, please consider supporting it by buying me a coffee, so I can dedicate more time on open-source projects like this

<a href="https://www.buymeacoffee.com/andrearapoA" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>

## License

This project is licensed under the [MIT License](https://github.com/andrearaponi/wslSnappy/blob/main/LICENSE).
40 changes: 40 additions & 0 deletions backup/backup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package backup

import (
"fmt"
"os"
"os/exec"
"syscall"
"time"
)

type BackupResult struct {
DistributionName string
Success bool
ErrorMessage string
}

func RunBackup(distributionName, backupDirectory string) BackupResult {

currentDate := time.Now()
backupFileName := fmt.Sprintf("%s_%s.tar", distributionName, currentDate.Format("20060102"))
backupFilePath := backupDirectory + "\\" + backupFileName

cmd := exec.Command("wsl", "--export", distributionName, backupFilePath)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

err := cmd.Run()
var result BackupResult
result.DistributionName = distributionName

if err != nil {
result.Success = false
result.ErrorMessage = fmt.Sprintf("%v", err)
} else {
result.Success = true
}

return result
}
59 changes: 59 additions & 0 deletions backup/backup_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package backup

import (
"testing"
)

func TestRunBackupSuccess(t *testing.T) {
// Replace with a valid distribution name and backup directory
distributionName := "Debian"
backupDirectory := "/path/to/backup"

result := RunBackup(distributionName, backupDirectory)

if !result.Success {
t.Errorf("Expected success, but got failure. Error message: %s", result.ErrorMessage)
}
if result.DistributionName != distributionName {
t.Errorf("Expected DistributionName to be %s, but got %s", distributionName, result.DistributionName)
}
if result.ErrorMessage != "" {
t.Errorf("Expected ErrorMessage to be empty, but got %s", result.ErrorMessage)
}
}

func TestRunBackupFailure(t *testing.T) {
// Replace with an invalid distribution name and backup directory
distributionName := "InvalidDistribution"
backupDirectory := "/path/to/backup"

result := RunBackup(distributionName, backupDirectory)

if result.Success {
t.Errorf("Expected failure, but got success")
}
if result.DistributionName != distributionName {
t.Errorf("Expected DistributionName to be %s, but got %s", distributionName, result.DistributionName)
}
if result.ErrorMessage == "" {
t.Errorf("Expected ErrorMessage to be non-empty, but got empty")
}
}

func TestRunBackupWithEmptyDistributionName(t *testing.T) {
// Replace with an empty distribution name and valid backup directory
distributionName := ""
backupDirectory := "/path/to/backup"

result := RunBackup(distributionName, backupDirectory)

if result.Success {
t.Errorf("Expected failure, but got success")
}
if result.DistributionName != distributionName {
t.Errorf("Expected DistributionName to be empty, but got %s", result.DistributionName)
}
if result.ErrorMessage == "" {
t.Errorf("Expected ErrorMessage to be non-empty, but got empty")
}
}
Binary file modified bin/WSLSnappy.exe
Binary file not shown.
79 changes: 79 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package main

import (
"flag"
"fmt"
"os"
"sync"
"time"
"wslSnappy/backup"
"wslSnappy/config"

"github.com/gen2brain/beeep"
)

func main() {
// Parse command-line flags
rocketMode := flag.Bool("rocket", false, "Run backups in parallel using goroutines")

flag.Parse()

start := time.Now()
beeep.Alert("WSLSnappy", "Backup Started", "")

// Load configuration settings
cfg, err := config.NewConfig()
if err != nil {
os.Exit(1)
}

// Create a channel to receive backup results
resultsChan := make(chan backup.BackupResult, len(cfg.Distributions))
var wg sync.WaitGroup

// Start backup routines for each distribution
for _, distributionName := range cfg.Distributions {
if *rocketMode {
wg.Add(1)
go func(name string) {
defer wg.Done()
result := backup.RunBackup(name, cfg.BackupDirectory)
resultsChan <- result
}(distributionName)
} else {
result := backup.RunBackup(distributionName, cfg.BackupDirectory)
resultsChan <- result
}
}

// If in rocket mode, wait for goroutines to complete
if *rocketMode {
wg.Wait()
}
close(resultsChan)
elapsed := time.Since(start)

// Process backup results
var successMsg, errorMsg string
for result := range resultsChan {
if result.Success {
successMsg += result.DistributionName + " backup succeeded\n"
} else {
errorMsg += result.DistributionName + ": backup failures" + result.ErrorMessage + "\n"
}
}

// If there were successful backups, display the total time taken
if successMsg != "" {
timeTaken := fmt.Sprintf("Total time taken for backup: %s", elapsed)

// Print the time and send a notification
fmt.Println(timeTaken)
beeep.Notify("WSLSnappy", successMsg+"\n"+timeTaken, "")
}

// If there were backup failures, display an alert with error messages
if errorMsg != "" {
beeep.Alert("WSLSnappy", errorMsg, "")
}
}
33 changes: 33 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package config

import (
"fmt"
"os"
"strings"

"github.com/gen2brain/beeep"
)

type Config struct {
BackupDirectory string
Distributions []string
}

func NewConfig() (*Config, error) {
backupDir := os.Getenv("WSL_BACKUP_DIR")
if backupDir == "" {
beeep.Alert("WSL Snappy Alert", "Environment variable WSL_BACKUP_DIR is not set.", "")
return nil, fmt.Errorf("environment variable WSL_BACKUP_DIR is not set")
}

distributions := os.Getenv("WSL_DISTRIBUTIONS")
if distributions == "" {
beeep.Alert("WSL Snappy Alert", "Environment variable WSL_DISTRIBUTIONS is not set.", "")
return nil, fmt.Errorf("environment variable WSL_DISTRIBUTIONS is not set")
}

return &Config{
BackupDirectory: backupDir,
Distributions: strings.Split(distributions, ","),
}, nil
}
63 changes: 63 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package config

import (
"os"
"testing"
)

func TestNewConfigWithValidEnvVars(t *testing.T) {
// Set valid environment variables for testing
os.Setenv("WSL_BACKUP_DIR", "/path/to/backup")
os.Setenv("WSL_DISTRIBUTIONS", "Debian,Kali,Ubuntu")

config, err := NewConfig()

if err != nil {
t.Errorf("Expected no error, got %v", err)
}

expectedBackupDir := "/path/to/backup"
if config.BackupDirectory != expectedBackupDir {
t.Errorf("Expected BackupDirectory to be %s, but got %s", expectedBackupDir, config.BackupDirectory)
}

expectedDistributions := []string{"Debian", "Kali", "Ubuntu"}
for i, dist := range expectedDistributions {
if config.Distributions[i] != dist {
t.Errorf("Expected Distributions[%d] to be %s, but got %s", i, dist, config.Distributions[i])
}
}
}

func TestNewConfigWithMissingBackupDirEnvVar(t *testing.T) {
// Unset the environment variable
os.Unsetenv("WSL_BACKUP_DIR")

_, err := NewConfig()

if err == nil {
t.Errorf("Expected an error, but got nil")
}

expectedErrorMessage := "environment variable WSL_BACKUP_DIR is not set"
if err.Error() != expectedErrorMessage {
t.Errorf("Expected error message to be %s, but got %s", expectedErrorMessage, err.Error())
}
}

func TestNewConfigWithMissingDistributionsEnvVar(t *testing.T) {
// Set valid backup directory but unset distributions
os.Setenv("WSL_BACKUP_DIR", "/path/to/backup")
os.Unsetenv("WSL_DISTRIBUTIONS")

_, err := NewConfig()

if err == nil {
t.Errorf("Expected an error, but got nil")
}

expectedErrorMessage := "environment variable WSL_DISTRIBUTIONS is not set"
if err.Error() != expectedErrorMessage {
t.Errorf("Expected error message to be %s, but got %s", expectedErrorMessage, err.Error())
}
}
Loading

0 comments on commit 706ad70

Please sign in to comment.