Skip to content

Commit

Permalink
1.6.7 is out! (#72)
Browse files Browse the repository at this point in the history
* Use the basename of files in run.go, install.go, remove.go. (0/3)

* Groundwork for Android AND Windows compatibility

* Fixed info.go.

* typo

* Update fsearch.go

* move fetchJson to helperFunctions.go -> emply fetchJson in fsearch.go.

* Great improvements! Reduced cyclic complexity!

* Modified main.go to work with Termux + Modified help message to show available env variables

* Get rid of redundant function and use os/exec instead.

* Adapt to the new format. (1/3)

* Fix fsearch.go to comply with the new format (1/3)

* Prepare for a pre-release

* Tweaks

* Fix info.go

* Version bump

---------
  • Loading branch information
xplshn committed May 26, 2024
1 parent 124e2f0 commit ddba085
Show file tree
Hide file tree
Showing 12 changed files with 233 additions and 319 deletions.
4 changes: 2 additions & 2 deletions findURL.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
func findURLCommand(binaryName string) {
url, err := findURL(binaryName)
if err != nil {
errorOut("Error: %v\n", err)
errorOut("error: %v\n", err)
}

fmt.Println(url)
Expand All @@ -30,5 +30,5 @@ func findURL(binaryName string) (string, error) {
}
}

return "", fmt.Errorf("Binary's SOURCE_URL was not found")
return "", fmt.Errorf("binary's SOURCE_URL was not found")
}
49 changes: 14 additions & 35 deletions fsearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,32 @@
package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"path/filepath"
"strings"
)

// fSearch searches for binaries based on the given search term.
func fSearch(searchTerm string, limit int) {
// Fetch metadata
response, err := http.Get(RMetadataURL)
if err != nil {
fmt.Println("Failed to fetch binary information.")
return
type tBinary struct {
Architecture string `json:"architecture"`
Name string `json:"name"`
Description string `json:"description"`
}
defer response.Body.Close()

body, err := ioutil.ReadAll(response.Body)
// Fetch metadata
var binaries []tBinary
err := fetchJSON(RNMetadataURL, &binaries)
if err != nil {
fmt.Println("Failed to read metadata.")
fmt.Println("Failed to fetch and decode binary information:", err)
return
}

// Define a struct to match the JSON structure from RMetadataURL
type Binary struct {
Name string `json:"name"`
Description string `json:"description"`
// Include other fields if needed
}

type RMetadata struct {
Binaries []Binary `json:"packages"`
}

// Unmarshal the description as an RMetadata object
var rMetadata RMetadata
if err := json.Unmarshal(body, &rMetadata); err != nil {
errorOut("Error while decoding metadata from %s: %v\n", RMetadataURL, err)
}

// Filter binaries based on the search term and architecture
searchResultsSet := make(map[string]struct{})
for _, binary := range rMetadata.Binaries {
if strings.Contains(strings.ToLower(binary.Name+binary.Description), strings.ToLower(searchTerm)) {
for _, binary := range binaries {
if strings.Contains(strings.ToLower(binary.Name), strings.ToLower(searchTerm)) || strings.Contains(strings.ToLower(binary.Description), strings.ToLower(searchTerm)) {
ext := strings.ToLower(filepath.Ext(binary.Name))
base := filepath.Base(binary.Name)
if _, excluded := excludedFileTypes[ext]; excluded {
Expand Down Expand Up @@ -92,11 +73,9 @@ func fSearch(searchTerm string, limit int) {
if fileExists(installPath) {
prefix = "[i]"
} else {
binaryPath, err := isBinaryInPath(name) // Capture both the path and error
if err != nil {
errorOut("Error checking the existence of a binary in the user's $PATH\n")
} else if binaryPath != "" {
prefix = "[I]"
binaryPath, _ := exec.LookPath(name) // is it okay to ignore the err channel of LookPath?
if binaryPath != "" {
prefix = "[\033[4mi\033[0m]" // Print [i], I is underlined.
} else if cachedLocation != "" && isExecutable(cachedLocation) {
prefix = "[c]"
} else {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module github.com/xplshn/bigdl

go 1.22.0

require github.com/schollz/progressbar/v3 v3.14.2
require github.com/schollz/progressbar/v3 v3.14.3

require (
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
Expand Down
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/schollz/progressbar/v3 v3.14.2 h1:EducH6uNLIWsr560zSV1KrTeUb/wZGAHqyMFIEa99ks=
github.com/schollz/progressbar/v3 v3.14.2/go.mod h1:aQAZQnhF4JGFtRJiw/eobaXpsqpVQAftEQ+hLGXaRc4=
github.com/schollz/progressbar/v3 v3.14.3 h1:oOuWW19ka12wxYU1XblR4n16wF/2Y1dBLMarMo6p4xU=
github.com/schollz/progressbar/v3 v3.14.3/go.mod h1:aT3UQ7yGm+2ZjeXPqsjTenwL3ddUiuZ0kfQ/2tHlyNI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
95 changes: 41 additions & 54 deletions helperFunctions.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -168,6 +169,25 @@ func copyFile(src, dst string) error {
return nil
}

func fetchJSON(url string, v interface{}) error {
response, err := http.Get(url)
if err != nil {
return fmt.Errorf("error fetching from %s: %v", url, err)
}
defer response.Body.Close()

body, err := io.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("error reading from %s: %v", url, err)
}

if err := json.Unmarshal(body, v); err != nil {
return fmt.Errorf("error decoding from %s: %v", url, err)
}

return nil
}

// removeDuplicates removes duplicate elements from the input slice.
func removeDuplicates(input []string) []string {
seen := make(map[string]bool)
Expand Down Expand Up @@ -197,33 +217,6 @@ func fileExists(filePath string) bool {
return !os.IsNotExist(err)
}

// appendLineToFile appends a line to the end of a file.
func appendLineToFile(filePath, line string) error {
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil {
return err
}
defer file.Close()
_, err = fmt.Fprintln(file, line)
return err
}

// fileSize returns the size of the file at the specified path.
func fileSize(filePath string) int64 {
file, err := os.Open(filePath)
if err != nil {
return 0
}
defer file.Close()

stat, err := file.Stat()
if err != nil {
return 0
}

return stat.Size()
}

// isExecutable checks if the file at the specified path is executable.
func isExecutable(filePath string) bool {
info, err := os.Stat(filePath)
Expand All @@ -249,7 +242,7 @@ func listFilesInDir(dir string) ([]string, error) {
}

func spawnProgressBar(contentLength int64) *progressbar.ProgressBar {
if useProgressBar {
if UseProgressBar {
return progressbar.NewOptions(int(contentLength),
progressbar.OptionClearOnFinish(),
progressbar.OptionFullWidth(),
Expand All @@ -263,7 +256,10 @@ func spawnProgressBar(contentLength int64) *progressbar.ProgressBar {
}),
)
}
return progressbar.NewOptions(0, progressbar.OptionClearOnFinish()) // A dummy
return progressbar.NewOptions(
-1,
progressbar.OptionSetWriter(io.Discard),
)
}

// sanitizeString removes certain punctuation from the end of the string and converts it to lower case.
Expand All @@ -276,14 +272,22 @@ func sanitizeString(s string) string {

// Remove specified punctuation from the end of the string
for _, p := range punctuation {
if strings.HasSuffix(s, p) {
s = s[:len(s)-len(p)]
}
s = s[:len(s)-len(p)]
}

return s
}

// contanins will return true if the provided slice of []strings contains the word str
func contains(slice []string, str string) bool {
for _, v := range slice {
if v == str {
return true
}
}
return false
}

// errorEncoder generates a unique error code based on the sum of ASCII values of the error message.
func errorEncoder(format string, args ...interface{}) int {
formattedErrorMessage := fmt.Sprintf(format, args...)
Expand Down Expand Up @@ -313,10 +317,8 @@ func getTerminalWidth() int {
// stty size returns rows and columns
parts := strings.Split(strings.TrimSpace(string(out)), " ")
if len(parts) == 2 {
width, err := strconv.Atoi(parts[1])
if err == nil {
return width
}
width, _ := strconv.Atoi(parts[1])
return width
}
}

Expand All @@ -325,10 +327,8 @@ func getTerminalWidth() int {
cmd.Stdin = os.Stdin
out, err = cmd.Output()
if err == nil {
width, err := strconv.Atoi(strings.TrimSpace(string(out)))
if err == nil {
return width
}
width, _ := strconv.Atoi(strings.TrimSpace(string(out)))
return width
}

// Fallback to 80 columns
Expand All @@ -355,7 +355,7 @@ func truncateSprintf(format string, a ...interface{}) string {

// truncatePrintf is a drop-in replacement for fmt.Printf that truncates the input string if it exceeds a certain length.
func truncatePrintf(format string, a ...interface{}) (n int, err error) {
if disableTruncation {
if DisableTruncation {
return fmt.Print(fmt.Sprintf(format, a...))
}
return fmt.Print(truncateSprintf(format, a...))
Expand Down Expand Up @@ -418,16 +418,3 @@ func validateProgramsFrom(InstallDir string, programsToValidate []string) ([]str
}
return validPrograms, nil
}

// isBinaryInPath checks if the binary is in the user's PATH, and it returns the path to it if so
func isBinaryInPath(binaryName string) (string, error) {
pathEnv := os.Getenv("PATH")
paths := strings.Split(pathEnv, string(os.PathListSeparator))
for _, path := range paths {
binaryPath := filepath.Join(path, binaryName)
if fileExists(binaryPath) && isExecutable(binaryPath) {
return binaryPath, nil // Return the path to the binary if found
}
}
return "", nil // Return an empty string and no error if the binary is not found
}
Loading

0 comments on commit ddba085

Please sign in to comment.