Skip to content

Commit

Permalink
Cached binaries are prefixed with [c] on 'search' results now.
Browse files Browse the repository at this point in the history
  • Loading branch information
xplshn committed Aug 30, 2024
1 parent 5fe23a7 commit ab342a5
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 93 deletions.
25 changes: 10 additions & 15 deletions fsearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

// fSearch searches for binaries based on the given search term.
func fSearch(metadataURLs []string, installDir, searchTerm string, disableTruncation bool, limit int) error {
func fSearch(metadataURLs []string, installDir, tempDir, searchTerm string, disableTruncation bool, limit int) error {
type tBinary struct {
Architecture string `json:"architecture"`
Name string `json:"name"`
Expand Down Expand Up @@ -59,9 +59,6 @@ func fSearch(metadataURLs []string, installDir, searchTerm string, disableTrunca
searchResults = append(searchResults, entry)
}

// Sort the search results
//searchResults = sortBinaries(searchResults)

// Check if the binary exists in the INSTALL_DIR and print results with installation state indicators
for _, line := range searchResults {
parts := strings.SplitN(line, " - ", 2)
Expand All @@ -71,19 +68,17 @@ func fSearch(metadataURLs []string, installDir, searchTerm string, disableTrunca
name := parts[0]
description := parts[1]

installPath := filepath.Join(installDir, name)
//cachedLocation, _ := returnCachedFile(name)

prefix := "[-]"
if fileExists(installPath) {
// Determine the prefix based on conditions
var prefix string
if installPath := filepath.Join(installDir, name); fileExists(installPath) {
prefix = "[i]"
} else if path, err := exec.LookPath(name); err == nil && path != "" {
prefix = "[\033[4mi\033[0m]" // Print [i],'i' is underlined
} /*
else if cachedLocation != "" && isExecutable(cachedLocation) {
prefix = "[c]"
}
*/
prefix = "[\033[4mi\033[0m]" // Print [i], 'i' is underlined
} else if cachedLocation, _ := ReturnCachedFile(tempDir, filepath.Base(name)); cachedLocation != "" {
prefix = "[c]"
} else {
prefix = "[-]"
}

truncatePrintf(disableTruncation, true, "%s %s - %s ", prefix, name, description)
}
Expand Down
47 changes: 23 additions & 24 deletions install.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,33 @@ import (
"context"
"fmt"
"path/filepath"
"strings"
"sync"
)

// installBinary fetches and installs the binary, logging based on verbosity levels.
func installBinary(ctx context.Context, binaryName, installDir, trackerFile string, verbosityLevel Verbosity, repositories []string) error {
url, err := findURL(binaryName, trackerFile, repositories)
if err != nil {
if verbosityLevel >= silentVerbosityWithErrors {
return err
}
// Return the error directly without printing/logging
return err
}

destination := filepath.Join(installDir, filepath.Base(binaryName))
_, err = fetchBinaryFromURLToDest(ctx, url, destination)
if err != nil {
if verbosityLevel >= silentVerbosityWithErrors {
return fmt.Errorf("error fetching binary %s: %v", binaryName, err)
}
// Return the error directly without printing/logging
return fmt.Errorf("error fetching binary %s: %v", binaryName, err)
}

if verbosityLevel >= normalVerbosity {
fmt.Printf("Successfully downloaded %s and put it at %s\n", binaryName, destination)
}

if err := addToTrackerFile(trackerFile, binaryName, installDir); err != nil && verbosityLevel >= normalVerbosity {
if verbosityLevel >= silentVerbosityWithErrors {
return fmt.Errorf("failed to update tracker file for %s: %v", binaryName, err)
}
err = addToTrackerFile(trackerFile, binaryName, installDir)
if err != nil {
// Return the error directly without printing/logging
return fmt.Errorf("failed to update tracker file for %s: %v", binaryName, err)
}

return nil
Expand All @@ -42,11 +41,6 @@ func multipleInstall(ctx context.Context, binaries []string, installDir, tracker
var wg sync.WaitGroup
errChan := make(chan error, len(binaries))

go func() {
wg.Wait()
close(errChan)
}()

for _, binaryName := range binaries {
wg.Add(1)
go func(binaryName string) {
Expand All @@ -57,20 +51,25 @@ func multipleInstall(ctx context.Context, binaries []string, installDir, tracker
}(binaryName)
}

var finalErr error
go func() {
wg.Wait()
close(errChan)
}()

var errors []string
for err := range errChan {
if finalErr == nil {
finalErr = err
} else {
finalErr = fmt.Errorf("%v; %v", finalErr, err)
}
errors = append(errors, err.Error())
}

if verbosityLevel >= normalVerbosity && finalErr != nil {
fmt.Printf("Final errors: %v\n", finalErr)
if len(errors) > 0 {
// Join errors with newline character
finalErr := strings.Join(errors, "\n")
if verbosityLevel >= silentVerbosityWithErrors {
return fmt.Errorf(finalErr)
}
}

return finalErr
return nil
}

// installCommand installs one or more binaries based on the verbosity level.
Expand Down
14 changes: 7 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,11 @@ run Run a specified binary from cache
info Show information about a specific binary OR display installed binaries
search Search for a binary - (not all binaries have metadata. Use list to see all binaries)
tldr Equivalent to "run --transparent --silent tlrc"`,
"Variables": `DBIN_CACHEDIR If present, it must contain a valid directory path
"3_Variables": `DBIN_CACHEDIR If present, it must contain a valid directory path
DBIN_INSTALL_DIR If present, it must contain a valid directory path
DBIN_NOTRUNCATION If present, and set to ONE (1), string truncation will be disabled
DBIN_TRACKERFILE If present, it must point to a valid file path, in an existing directory`,
"3_Examples": `dbin search editor
"4_Examples": `dbin search editor
dbin install micro.upx
dbin install lux kakoune aretext shfmt
dbin --silent install bed && echo "[bed] was installed to $INSTALL_DIR/bed"
Expand Down Expand Up @@ -237,7 +237,7 @@ dbin run btop`,
fmt.Printf("%v\n", err)
os.Exit(1)
}
//fmt.Println("Installation completed successfully.")
// fmt.Println("Installation completed successfully.")
case "remove", "del":
if len(args) < 1 {
fmt.Println("No binary name provided for remove command.")
Expand All @@ -249,12 +249,12 @@ dbin run btop`,
fmt.Printf("%v\n", err)
os.Exit(1)
}
//fmt.Println("Removal completed successfully.")
// fmt.Println("Removal completed successfully.")
case "list", "l":
if len(os.Args) == 3 {
if os.Args[2] == "--described" || os.Args[2] == "-d" {
// Call fSearch with an empty query and a large limit to list all described binaries
fSearch(metadataURLs, installDir, "", disableTruncation, 99999)
fSearch(metadataURLs, installDir, tempDir, "", disableTruncation, 99999)
} else {
errorOut("dbin: Unknown command.\n")
}
Expand Down Expand Up @@ -298,7 +298,7 @@ dbin run btop`,
}

query := args[queryIndex]
err := fSearch(metadataURLs, installDir, query, disableTruncation, limit)
err := fSearch(metadataURLs, installDir, tempDir, query, disableTruncation, limit)
if err != nil {
fmt.Printf("error searching binaries: %v\n", err)
os.Exit(1)
Expand Down Expand Up @@ -349,7 +349,7 @@ dbin run btop`,
}
case "run", "r":
if len(args) < 1 {
fmt.Println("Usage: dbin run <--silent, --transparent> [binary] <args>")
fmt.Println("Usage: dbin run <--transparent> [binary] <args>")
os.Exit(1)
}

Expand Down
76 changes: 29 additions & 47 deletions utility.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,14 @@ downloadLoop:
speed := float64(downloaded) / elapsed // bytes per second

// Adjust spinner speed based on download speed
if speed > 1024*1024 { // more than 1MB/s
switch {
case speed > 1024*1024: // more than 1MB/s
spinner.SetSpeed(150 * time.Millisecond)
} else if speed > 512*1024 { // more than 512KB/s
case speed > 512*1024: // more than 512KB/s
spinner.SetSpeed(100 * time.Millisecond)
} else if speed > 256*1024 { // more than 256KB/s
case speed > 256*1024: // more than 256KB/s
spinner.SetSpeed(80 * time.Millisecond)
} else {
default:
spinner.SetSpeed(50 * time.Millisecond)
}
}
Expand Down Expand Up @@ -481,62 +482,43 @@ func writeTrackerFile(trackerFile string, tracker map[string]string) error {
return nil
}

// removeNixGarbageFoundInTheRepos corrects any /nix/store/ or /bin/ binary path in the file.
func removeNixGarbageFoundInTheRepos(filePath string) error {
// Open the file for reading
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open file %s: %v", filePath, err)
}
defer file.Close()

// Read the first few bytes to check for a shebang
buf := make([]byte, 2)
if _, err := file.Read(buf); err != nil {
return fmt.Errorf("failed to read file %s: %v", filePath, err)
}

// If the file does not start with a shebang, skip processing
if string(buf) != "#!" {
return nil
}

// Read the entire file content after confirming it's a script
// Read the entire file content
content, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("failed to read file %s for shebang and exec modification: %v", filePath, err)
return fmt.Errorf("failed to read file %s: %v", filePath, err)
}

// Regex to match and remove the /nix/store/*/ prefix in shebang
nixShebangRegex := regexp.MustCompile(`^#!\s*/nix/store/[^/]+/(bin|usr/bin)/(\S+)\s*(.*)`)
// Regex to match and remove the /nix/store/*/ prefix in the exec line, keeping only the program name
nixExecRegex := regexp.MustCompile(`^exec\s+"/nix/store/[^/]+/(bin|usr/bin)/(\S+)"(.*)`)
// Regex to match and remove the /nix/store/*/ prefix in the shebang line, preserving the rest of the path
nixShebangRegex := regexp.MustCompile(`^#!\s*/nix/store/[^/]+/`)
// Regex to match and remove the /nix/store/*/bin/ prefix in other lines
nixBinPathRegex := regexp.MustCompile(`/nix/store/[^/]+/bin/`)

// Split content by lines
lines := strings.Split(string(content), "\n")

// Modify the shebang line if it matches
if nixShebangRegex.MatchString(lines[0]) {
matches := nixShebangRegex.FindStringSubmatch(lines[0])
lines[0] = fmt.Sprintf("#!/%s/%s", matches[1], matches[2])
if matches[3] != "" {
lines[0] += " " + matches[3]
}
fmt.Println("This binary is a nix object. Corrections have been made to its shebang.")
}
// Flag to track if any corrections were made
correctionsMade := false

// Modify the exec line if it matches
for i := 1; i < len(lines); i++ {
if nixExecRegex.MatchString(lines[i]) {
matches := nixExecRegex.FindStringSubmatch(lines[i])
lines[i] = fmt.Sprintf(`exec "%s"%s`, matches[2], matches[3])
fmt.Println("This binary is a nix object. Corrections have been made to its exec line.")
break
// Handle the shebang line separately if it exists and matches the nix pattern
if len(lines) > 0 && nixShebangRegex.MatchString(lines[0]) {
lines[0] = nixShebangRegex.ReplaceAllString(lines[0], "#!/")
// Iterate through the rest of the lines and correct any /nix/store/*/bin/ path
for i := 1; i < len(lines); i++ {
if nixBinPathRegex.MatchString(lines[i]) {
lines[i] = nixBinPathRegex.ReplaceAllString(lines[i], "")
}
}
correctionsMade = true
}

// Write the modified content back to the file
if err := os.WriteFile(filePath, []byte(strings.Join(lines, "\n")), 0644); err != nil {
return fmt.Errorf("failed to write modified content to file %s: %v", filePath, err)
// If any corrections were made, write the modified content back to the file
if correctionsMade {
if err := os.WriteFile(filePath, []byte(strings.Join(lines, "\n")), 0644); err != nil {
return fmt.Errorf("failed to correct nix object [%s]: %v", filepath.Base(filePath), err)
}
fmt.Printf("[%s] is a nix object. Corrections have been made.\n", filepath.Base(filePath))
}

return nil
Expand Down

0 comments on commit ab342a5

Please sign in to comment.