refactor: replace fmt by log or plain concat (#15)

This commit is contained in:
Marc 2023-11-29 00:06:55 -05:00 committed by GitHub
parent 1bbd6c1050
commit 61847e532b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 48 additions and 53 deletions

12
cli.go
View file

@ -1,7 +1,6 @@
package main
import (
"fmt"
"strings"
)
@ -69,18 +68,11 @@ func (c CLI) Run(args []string, currentState State) error {
// Prints autogenerated help documentation specifying command usage
// and descriptions based on registered commands (see: AddCommand).
func (c CLI) Help() {
usageStrings := []string{}
InfoLogger.Printf("v: A simple version manager. (v%s)\n---", Version)
for _, commandLabel := range c.OrderedCommands {
command := c.Commands[commandLabel]
usageStrings = append(usageStrings, fmt.Sprintf("\033[1m%-30s\033[0m%s", command.Usage, command.Description))
InfoLogger.Printf("\033[1m%-30s\033[0m%s\n", command.Usage, command.Description)
}
helpString := fmt.Sprintf(`v: A simple version manager. (v%s)
---
%s`, c.Metadata["Version"], strings.Join(usageStrings, "\n"))
fmt.Println(helpString)
}
// Traverses input arguments and extracts flags of

View file

@ -1,7 +1,6 @@
package main
import (
"fmt"
"os"
"slices"
)
@ -32,7 +31,7 @@ func writeShim(shimPath string) error {
// installed runtimes and metadata.
func Initialize(args []string, flags Flags, currentState State) error {
if flags.AddPath {
fmt.Printf("export PATH=%s:$PATH\n", GetStatePath("shims"))
InfoLogger.Printf("export PATH=%s:$PATH\n", GetStatePath("shims"))
return nil
}
@ -48,7 +47,7 @@ func Initialize(args []string, flags Flags, currentState State) error {
return nil
}
func UninstallPython(args []string, flags Flags, currentState State) error {
runtimePath := GetStatePath("runtimes", fmt.Sprintf("py-%s", args[1]))
runtimePath := GetStatePath("runtimes", "py-"+args[1])
err := os.RemoveAll(runtimePath)
return err
}
@ -76,12 +75,12 @@ func Use(args []string, flags Flags, currentState State) error {
}
if !found {
fmt.Println("Version not installed. Installing it first.")
InfoLogger.Println("Version not installed. Installing it first.")
InstallPythonDistribution(version, flags.NoCache, flags.Verbose)
}
WriteState(version)
fmt.Printf("Now using Python %s\n", version)
InfoLogger.Printf("Now using Python %s\n", version)
return nil
}
@ -93,12 +92,12 @@ func ListVersions(args []string, flags Flags, currentState State) error {
}
if len(installedVersions) == 0 {
fmt.Println("No versions installed!")
InfoLogger.Println("No versions installed!")
return nil
}
for _, d := range installedVersions {
fmt.Println(d)
InfoLogger.Println(d)
}
return nil
@ -114,12 +113,12 @@ func Which(args []string, flags Flags, currentState State) error {
if selectedVersion.Source == "system" {
_, sysPath := DetermineSystemPython()
printedPath = fmt.Sprintf("%s (system)", sysPath)
printedPath = sysPath + " (system)"
} else if isInstalled {
tag := VersionStringToStruct(selectedVersion.Version)
printedPath = GetStatePath("runtimes", fmt.Sprintf("py-%s", selectedVersion.Version), "bin", fmt.Sprintf("python%s", tag.MajorMinor()))
printedPath = GetStatePath("runtimes", "py-"+selectedVersion.Version, "bin", "python"+tag.MajorMinor())
} else {
fmt.Printf("The desired version (%s) is not installed.\n", selectedVersion.Version)
InfoLogger.Printf("The desired version (%s) is not installed.\n", selectedVersion.Version)
return nil
}
@ -131,7 +130,7 @@ func Which(args []string, flags Flags, currentState State) error {
printedPath = Bold(printedPath)
}
fmt.Printf("%s%s\n", prefix, printedPath)
InfoLogger.Printf("%s%s\n", prefix, printedPath)
return nil
}
@ -144,14 +143,14 @@ func CurrentVersion(args []string, flags Flags, currentState State) error {
isInstalled := slices.Contains(installedVersions, selectedVersion.Version)
if !isInstalled {
fmt.Println(Bold(Yellow("WARNING: This version is not installed.")))
InfoLogger.Println(Bold(Yellow("WARNING: This version is not installed.")))
}
if flags.RawOutput {
fmt.Println(selectedVersion.Version)
InfoLogger.Println(selectedVersion.Version)
return nil
}
fmt.Printf("Python version: %s\nSource: %s\n", Bold(selectedVersion.Version), Bold(selectedVersion.Source))
InfoLogger.Printf("Python version: %s\nSource: %s\n", Bold(selectedVersion.Version), Bold(selectedVersion.Source))
return nil
}

View file

@ -2,7 +2,6 @@ package main
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
@ -27,7 +26,7 @@ type VersionTag struct {
}
func (t VersionTag) MajorMinor() string {
return fmt.Sprintf("%s.%s", t.Major, t.Minor)
return t.Major + "." + t.Minor
}
func InstallPythonDistribution(version string, noCache bool, verbose bool) error {
@ -51,18 +50,21 @@ func InstallPythonDistribution(version string, noCache bool, verbose bool) error
// Fetches the Python tarball for version <version> from python.org.
func downloadSource(version string, skipCache bool) (PackageMetadata, error) {
archiveName := fmt.Sprintf("Python-%s.tgz", version)
archiveName := "Python-" + version + ".tgz"
archivePath := GetStatePath("cache", archiveName)
sourceUrl, _ := url.JoinPath(pythonReleasesBaseURL, version, archiveName)
client := http.Client{}
dlPrint := StartFmtGroup(fmt.Sprintf("Downloading source for Python %s", version))
InfoLogger.Println(Bold("Downloading source for Python " + version))
InfoLogger.SetPrefix(" ")
defer InfoLogger.SetPrefix("")
start := time.Now()
_, err := os.Stat(archivePath)
if errors.Is(err, os.ErrNotExist) || skipCache {
dlPrint(fmt.Sprintf("Fetching from %s", sourceUrl))
InfoLogger.Println("Fetching from " + sourceUrl)
resp, err := client.Get(sourceUrl)
@ -76,18 +78,21 @@ func downloadSource(version string, skipCache bool) (PackageMetadata, error) {
defer file.Close()
} else {
dlPrint(fmt.Sprintf("Found in cache: %s", archivePath))
InfoLogger.Println("Found in cache: " + archivePath)
}
dlPrint(fmt.Sprintf("✅ Done (%s)", time.Since(start)))
InfoLogger.Printf("✅ Done (%s)\n", time.Since(start))
return PackageMetadata{ArchivePath: archivePath, Version: version}, nil
}
func buildFromSource(pkgMeta PackageMetadata, verbose bool) (PackageMetadata, error) {
buildPrint := StartFmtGroup(fmt.Sprintf("Building from source"))
InfoLogger.Println(Bold("Building from source"))
InfoLogger.SetPrefix(" ")
defer InfoLogger.SetPrefix("")
start := time.Now()
buildPrint(fmt.Sprintf("Unpacking source for %s", pkgMeta.ArchivePath))
InfoLogger.Println("Unpacking source for " + pkgMeta.ArchivePath)
_, untarErr := RunCommand([]string{"tar", "zxvf", pkgMeta.ArchivePath}, GetStatePath("cache"), !verbose)
@ -97,17 +102,17 @@ func buildFromSource(pkgMeta PackageMetadata, verbose bool) (PackageMetadata, er
unzippedRoot := strings.TrimSuffix(pkgMeta.ArchivePath, path.Ext(pkgMeta.ArchivePath))
buildPrint("Configuring installer")
InfoLogger.Println("Configuring installer")
targetDirectory := GetStatePath("runtimes", fmt.Sprintf("py-%s", pkgMeta.Version))
targetDirectory := GetStatePath("runtimes", "py-"+pkgMeta.Version)
_, configureErr := RunCommand([]string{"./configure", fmt.Sprintf("--prefix=%s", targetDirectory), "--enable-optimizations"}, unzippedRoot, !verbose)
_, configureErr := RunCommand([]string{"./configure", "--prefix=" + targetDirectory, "--enable-optimizations"}, unzippedRoot, !verbose)
if configureErr != nil {
return pkgMeta, configureErr
}
buildPrint("Building")
InfoLogger.Println("Building")
_, buildErr := RunCommand([]string{"make", "altinstall", "-j4"}, unzippedRoot, !verbose)
if buildErr != nil {
@ -120,7 +125,7 @@ func buildFromSource(pkgMeta PackageMetadata, verbose bool) (PackageMetadata, er
pkgMeta.InstallPath = targetDirectory
buildPrint(fmt.Sprintf("Installed Python %s at %s", pkgMeta.Version, pkgMeta.InstallPath))
buildPrint(fmt.Sprintf("✅ Done (%s)", time.Since(start)))
InfoLogger.Printf("Installed Python %s at %s\n", pkgMeta.Version, pkgMeta.InstallPath)
InfoLogger.Printf("✅ Done (%s)\n", time.Since(start))
return pkgMeta, nil
}

10
logger.go Normal file
View file

@ -0,0 +1,10 @@
package main
import (
"log"
"os"
)
var (
InfoLogger = log.New(os.Stdout, "", 0)
)

View file

@ -1,4 +1,4 @@
#!/bin/bash
go get golang.org/x/tools/cmd/cover
go test -cover -v
go test -cover -v -coverprofile=cov.out

View file

@ -1,7 +1,5 @@
package main
import "fmt"
const (
RESET = "\033[0m"
BOLD = "\033[1m"
@ -9,9 +7,9 @@ const (
)
func Yellow(text string) string {
return fmt.Sprintf("%s%s%s", YELLOW, text, RESET)
return YELLOW + text + RESET
}
func Bold(text string) string {
return fmt.Sprintf("%s%s%s", BOLD, text, RESET)
return BOLD + text + RESET
}

View file

@ -2,20 +2,11 @@ package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
func StartFmtGroup(label string) func(string) {
fmt.Printf("\033[1m%s\033[0m\n", label)
return func(message string) {
fmt.Printf(" %s\n", message)
}
}
func VersionStringToStruct(version string) VersionTag {
splitVersion := strings.Split(version, ".")