Skip to content

Commit

Permalink
fix default input dir
Browse files Browse the repository at this point in the history
  • Loading branch information
anibaldeboni committed Aug 9, 2024
1 parent 6da6b74 commit 81ec991
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 36 deletions.
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ build: install_deps
@go build -o $(ARTIFACTS) -ldflags "-s -w" ./main.go
$(info Built to $(BUILD_PATH))

build-windows: install_deps
@GOOS=windows GOARCH=amd64 go build -o $(ARTIFACTS).exe -ldflags "-s -w" ./main.go
$(info Built to $(BUILD_PATH))

install: build
@cp $(ARTIFACTS) $(INSTALL_PATH)
$(info Installed to $(INSTALL_PATH)/$(APP_NAME))
Expand Down
43 changes: 33 additions & 10 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"runtime"
"sync"
"time"

"github.com/anibaldeboni/rx/files"
"github.com/anibaldeboni/rx/styles"
Expand All @@ -14,32 +15,39 @@ import (

var Version = "dev"

const ZipExtension = ".zip"
const (
ZipExtension = ".zip"
ErrPathNotExists = "Path %s does not exist"
ErrPathNotDirectory = "Path %s is not a directory"
ErrInvalidPath = "Invalid path %s: %w"
)

type Cli struct {
Workers int
Output string
Version string
Cwd string
Recursive bool
errs chan error
wg *sync.WaitGroup
}

type WorkerFunc func(<-chan string)
type WorkerFunc func(<-chan string, int)

func (c *Cli) SetupWorkers(worker WorkerFunc, path string) {
start := time.Now()
log.Printf("Looking for files at %s\n", styles.DarkPink(path))
files := c.FindFiles()(path, c.errs)

log.Printf("Using %s workers\n", styles.LightBlue(fmt.Sprintf("%d", c.Workers)))

c.wg.Add(c.Workers)
for i := 0; i < c.Workers; i++ {
go worker(files)
go worker(files, i+1)
}

c.wg.Wait()
log.Println(styles.Green("Done!"))
log.Println(styles.Green("Done!"), "Elapsed time:", time.Since(start))
}

func (c *Cli) FindFiles() files.FindFilesFunc {
Expand All @@ -50,6 +58,10 @@ func (c *Cli) FindFiles() files.FindFilesFunc {
return files.FindFilesInRootDirectory
}

func fmtWorker(addr int) string {
return styles.LightGreen(fmt.Sprintf("🛠️ %03d", addr))
}

func HandleErrors(errs <-chan error) {
go func(errs <-chan error) {
for err := range errs {
Expand All @@ -58,26 +70,35 @@ func HandleErrors(errs <-chan error) {
}(errs)
}

func validateCmdPath(cmd *cobra.Command, args []string) error {
func (c *Cli) validatePath(cmd *cobra.Command, args []string) error {
var path string

if len(args) < 1 {
return fmt.Errorf("Path is required")
path = c.Cwd
} else {
path = args[0]
}

if err := checkPath(args[0]); err != nil {
if err := checkPath(path); err != nil {
return fmt.Errorf("Could not run: %w", err)
}

if _, err := os.Stat(c.Output); os.IsNotExist(err) {
os.MkdirAll(c.Output, os.ModePerm)
}

log.Printf("Output directory: %s\n", styles.Green(c.Output))
return nil
}

func checkPath(path string) error {
switch p, err := os.Stat(path); {
case err != nil:
return fmt.Errorf("Invalid path %s: %w", styles.DarkRed(path), err)
case p == nil:
case os.IsNotExist(err):
return fmt.Errorf("Path %s does not exist", styles.DarkRed(path))
case !p.IsDir():
return fmt.Errorf("Path %s is not a directory", styles.DarkRed(path))
case err != nil:
return fmt.Errorf("Invalid path %s: %w", styles.DarkRed(path), err)
default:
return nil
}
Expand All @@ -87,6 +108,7 @@ func Execute() {
errs := make(chan error)
defer close(errs)

log.SetFlags(log.Lmicroseconds)
HandleErrors(errs)

cli := &Cli{
Expand All @@ -108,6 +130,7 @@ It can compress individual rom files into zip files and inflate content files fr

rootCmd.PersistentFlags().BoolVarP(&cli.Recursive, "recursive", "r", false, "walk recursively through directories")
cwd, _ := os.Getwd()
cli.Cwd = cwd
rootCmd.PersistentFlags().StringVarP(&cli.Output, "output", "o", cwd, "output directory")
rootCmd.PersistentFlags().IntVarP(&cli.Workers, "workers", "w", runtime.NumCPU(), "number of workers to use")

Expand Down
20 changes: 10 additions & 10 deletions cmd/unzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@ func (c *Cli) unzipCmd() *cobra.Command {
Use: "unzip [path]",
Short: "inflate rom files.",
Long: `Inflate content files from zip files`,
PreRunE: validateCmdPath,
PreRunE: c.validatePath,
Run: c.unzip,
}
}

func (c *Cli) unzip(cmd *cobra.Command, args []string) {
c.SetupWorkers(c.unzipWorker, args[0])
c.SetupWorkers(c.unzipWorker, c.Cwd)
}

func (c *Cli) unzipWorker(files <-chan string) {
func (c *Cli) unzipWorker(files <-chan string, addr int) {
defer c.wg.Done()

for file := range files {
Expand All @@ -36,36 +36,36 @@ func (c *Cli) unzipWorker(files <-chan string) {

zipFile, err := zip.OpenReader(file)
if err != nil {
c.errs <- fmt.Errorf("Error opening zip archive %s: %w", styles.DarkRed(file), err)
c.errs <- fmt.Errorf("[%s] Error opening zip archive %s: %w", fmtWorker(addr), styles.DarkRed(file), err)
}
defer zipFile.Close()
for _, zipContent := range zipFile.File {
outputFilePath := filepath.Join(c.Output, zipContent.Name)

log.Println("Inflating", styles.LightBlue(filepath.Base(file)))
log.Printf("[%s] Inflating %s\n", fmtWorker(addr), styles.LightBlue(zipContent.Name))

if zipContent.FileInfo().IsDir() {
if err := os.MkdirAll(outputFilePath, os.ModePerm); err != nil {
c.errs <- fmt.Errorf("Error creating directory %s: %w", styles.DarkRed(outputFilePath), err)
c.errs <- fmt.Errorf("[%s] Error creating directory %s: %w", fmtWorker(addr), styles.DarkRed(outputFilePath), err)
}
continue
}

if err := os.MkdirAll(filepath.Dir(outputFilePath), os.ModePerm); err != nil {
c.errs <- fmt.Errorf("Error creating directory %s: %w", styles.DarkRed(filepath.Dir(outputFilePath)), err)
c.errs <- fmt.Errorf("[%s] Error creating directory %s: %w", fmtWorker(addr), styles.DarkRed(filepath.Dir(outputFilePath)), err)
}

dstFile, err := os.OpenFile(outputFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, zipContent.Mode())
if err != nil {
c.errs <- fmt.Errorf("Error creating file %s: %w", styles.DarkRed(outputFilePath), err)
c.errs <- fmt.Errorf("[%s] Error creating file %s: %w", fmtWorker(addr), styles.DarkRed(outputFilePath), err)
}

srcFile, err := zipContent.Open()
if err != nil {
c.errs <- fmt.Errorf("Error compressed file %s: %w", styles.DarkRed(zipContent.Name), err)
c.errs <- fmt.Errorf("[%s] Error compressed file %s: %w", fmtWorker(addr), styles.DarkRed(zipContent.Name), err)
}
if _, err := io.Copy(dstFile, srcFile); err != nil {
c.errs <- fmt.Errorf("Error inflating file %s: %w", styles.DarkRed(zipContent.Name), err)
c.errs <- fmt.Errorf("[%s] Error inflating file %s: %w", fmtWorker(addr), styles.DarkRed(zipContent.Name), err)
}

dstFile.Close()
Expand Down
17 changes: 9 additions & 8 deletions cmd/zip.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"archive/zip"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
Expand All @@ -17,16 +18,16 @@ func (c *Cli) zipCmd() *cobra.Command {
Use: "zip [path]",
Short: "compress rom files.",
Long: `Compress rom files into individual zip files.`,
PreRunE: validateCmdPath,
PreRunE: c.validatePath,
Run: c.zip,
}
}

func (c *Cli) zip(cmd *cobra.Command, args []string) {
c.SetupWorkers(c.zipWorker, args[0])
c.SetupWorkers(c.zipWorker, c.Cwd)
}

func (c *Cli) zipWorker(files <-chan string) {
func (c *Cli) zipWorker(files <-chan string, addr int) {
defer c.wg.Done()

for file := range files {
Expand All @@ -38,29 +39,29 @@ func (c *Cli) zipWorker(files <-chan string) {
outputFile, err := os.Create(outputFilePath)
defer outputFile.Close()
if err != nil {
c.errs <- fmt.Errorf("Error creating file %s: %w", outputFilePath, err)
c.errs <- fmt.Errorf("[%s] Error creating file %s: %w", fmtWorker(addr), outputFileName, err)
return
}

inputFile, err := os.Open(file)
defer inputFile.Close()
if err != nil {
c.errs <- fmt.Errorf("Error opening file %s: %w", file, err)
c.errs <- fmt.Errorf("[%s] Error opening file %s: %w", fmtWorker(addr), file, err)
return
}

zipWriter := zip.NewWriter(outputFile)

fileWriter, err := zipWriter.Create(zipFile)
if err != nil {
c.errs <- fmt.Errorf("Error creating file %s in zip: %w", file, err)
c.errs <- fmt.Errorf("[%s] Error creating file %s in zip: %w", fmtWorker(addr), file, err)
return
}

fmt.Printf("Compressing %s\n", styles.LightBlue(zipFile))
log.Printf("[%s] Compressing %s\n", fmtWorker(addr), styles.LightBlue(zipFile))

if _, err := io.Copy(fileWriter, inputFile); err != nil {
c.errs <- fmt.Errorf("Error compressing file %s to zip: %w", file, err)
c.errs <- fmt.Errorf("[%s] Error compressing file %s to zip: %w", fmtWorker(addr), file, err)
return
}

Expand Down
2 changes: 1 addition & 1 deletion files/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func FindRecursive(path string, errs chan<- error) chan string {
return nil
},
ErrorCallback: func(osPathname string, err error) godirwalk.ErrorAction {
errs <- fmt.Errorf("Error walking %s: %s", osPathname, err)
errs <- fmt.Errorf("Error walking %s: %w", osPathname, err)
return godirwalk.SkipNode
},
Unsorted: true, // set true for faster yet non-deterministic enumeration (see godoc)
Expand Down
9 changes: 6 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@ module github.com/anibaldeboni/rx

go 1.22.1

require (
github.com/charmbracelet/lipgloss v0.12.1
github.com/karrick/godirwalk v1.17.0
github.com/spf13/cobra v1.8.1
)

require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/lipgloss v0.12.1 // indirect
github.com/charmbracelet/x/ansi v0.1.4 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/karrick/godirwalk v1.17.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/cobra v1.8.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/sys v0.22.0 // indirect
)
9 changes: 5 additions & 4 deletions styles/styles.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package styles
import "github.com/charmbracelet/lipgloss"

var (
Green = lipgloss.NewStyle().Foreground(lipgloss.Color("#00FF00")).Render
LightBlue = lipgloss.NewStyle().Foreground(lipgloss.Color("#ADD8E6")).Render
DarkRed = lipgloss.NewStyle().Foreground(lipgloss.Color("#8B0000")).Render
DarkPink = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF1493")).Render
Green = lipgloss.NewStyle().Foreground(lipgloss.Color("#00FF00")).Render
LightGreen = lipgloss.NewStyle().Foreground(lipgloss.Color("#90EE90")).Render
LightBlue = lipgloss.NewStyle().Foreground(lipgloss.Color("#ADD8E6")).Render
DarkRed = lipgloss.NewStyle().Foreground(lipgloss.Color("#8B0000")).Render
DarkPink = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF1493")).Render
)

0 comments on commit 81ec991

Please sign in to comment.