Skip to content

Commit

Permalink
Code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
viniciussanchez committed Nov 26, 2021
1 parent 20588d6 commit f6049f1
Show file tree
Hide file tree
Showing 6 changed files with 235 additions and 256 deletions.
98 changes: 96 additions & 2 deletions cmd/dependencies.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
package cmd

import (
"github.com/hashload/boss/core"
"os"
"path/filepath"

"github.com/hashload/boss/consts"
"github.com/hashload/boss/core/installer"
"github.com/hashload/boss/env"
"github.com/hashload/boss/models"
"github.com/hashload/boss/msg"
"github.com/hashload/boss/utils"
"github.com/masterminds/semver"
"github.com/spf13/cobra"
"github.com/xlab/treeprint"
)

const (
updated = 0
outdated = 1
usingMaster = 2
)

var showVersion bool
var tree = treeprint.New()

var dependenciesCmd = &cobra.Command{
Use: "dependencies",
Expand All @@ -24,11 +41,88 @@ var dependenciesCmd = &cobra.Command{
List package dependencies with version control:
boss dependencies <pkg> --version`,
Run: func(cmd *cobra.Command, args []string) {
core.PrintDependencies(showVersion)
printDependencies(showVersion)
},
}

func init() {
RootCmd.AddCommand(dependenciesCmd)
dependenciesCmd.Flags().BoolVarP(&showVersion, "version", "v", false, "show dependency version")
}

func printDependencies(showVersion bool) {
pkg, err := models.LoadPackage(false)
if err != nil {
if os.IsNotExist(err) {
msg.Die("boss.json not exists in " + env.GetCurrentDir())
} else {
msg.Die("Fail on open dependencies file: %s", err)
}
}

master := tree.AddBranch(pkg.Name + ":")
deps := pkg.GetParsedDependencies()
printDeps(nil, deps, pkg.Lock, master, showVersion)
print(tree.String())
}

func printDeps(dep *models.Dependency, deps []models.Dependency, lock models.PackageLock, tree treeprint.Tree, showVersion bool) {
var localTree treeprint.Tree

if dep != nil {
localTree = printSingleDependency(dep, lock, tree, showVersion)
} else {
localTree = tree
}

for _, dep := range deps {
pkgModule, err := models.LoadPackageOther(filepath.Join(env.GetModulesDir(), dep.GetName(), consts.FilePackage))
if err != nil {
printSingleDependency(&dep, lock, localTree, showVersion)
} else {
deps := pkgModule.GetParsedDependencies()
printDeps(&dep, deps, lock, localTree, showVersion)
}
}
}

func printSingleDependency(dep *models.Dependency, lock models.PackageLock, tree treeprint.Tree, showVersion bool) treeprint.Tree {
var output = dep.GetName()

if showVersion {
output += "@"
output += lock.GetInstalled(*dep).Version
}

switch isOutdated(*dep, lock.GetInstalled(*dep).Version) {
case outdated:
output += " outdated"
break
case usingMaster:
output += " using master"
break
}

return tree.AddBranch(output)
}

func isOutdated(dependency models.Dependency, version string) int {
installer.GetDependency(dependency)
info, err := models.RepoData(dependency.GetHashName())
if err != nil {
utils.HandleError(err)
} else {
locked, err := semver.NewVersion(version)
if err != nil {
return usingMaster
}
constraint, _ := semver.NewConstraint(dependency.GetVersion())
for _, value := range info.Versions {
version, err := semver.NewVersion(value)
if err == nil && version.GreaterThan(locked) && constraint.Check(version) {
return outdated
}
}
}
return updated
}
70 changes: 68 additions & 2 deletions cmd/init.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
package cmd

import (
"github.com/hashload/boss/core"
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/hashload/boss/env"
"github.com/hashload/boss/models"
"github.com/spf13/cobra"
)

Expand All @@ -17,11 +25,69 @@ var initCmd = &cobra.Command{
Initialize a new project without having it ask any questions:
boss init --quiet`,
Run: func(cmd *cobra.Command, args []string) {
core.InitializeBossPackage(quiet)
doInitialization(quiet)
},
}

func init() {
RootCmd.AddCommand(initCmd)
initCmd.Flags().BoolVarP(&quiet, "quiet", "q", false, "without asking questions")
}

func doInitialization(quiet bool) {
if !quiet {
printHead()
}

pkgJson, _ := models.LoadPackage(true)

var folderName = ""
rxp, err := regexp.Compile(`^.+\` + string(filepath.Separator) + `([^\\]+)$`)
if err == nil {
allString := rxp.FindAllStringSubmatch(env.GetCurrentDir(), -1)
folderName = allString[0][1]
}

if quiet {
pkgJson.Name = folderName
pkgJson.Version = "1.0.0"
pkgJson.MainSrc = "./"
} else {
pkgJson.Name = getParamOrDef("Package name ("+folderName+")", folderName)
pkgJson.Homepage = getParamOrDef("Homepage", "")
pkgJson.Version = getParamOrDef("Version (1.0.0)", "1.0.0")
pkgJson.Description = getParamOrDef("Description", "")
pkgJson.MainSrc = getParamOrDef("Source folder (./src)", "./src")
}

json := pkgJson.Save()
fmt.Println("\n" + string([]byte(json)))
}

func getParamOrDef(msg string, def string) string {
fmt.Print(msg + ": ")
rr := bufio.NewReader(os.Stdin)
if res, e := rr.ReadString('\n'); e == nil && res != "\n" {
res = strings.ReplaceAll(res, "\t", "")
res = strings.ReplaceAll(res, "\n", "")
res = strings.ReplaceAll(res, "\r", "")
if res == "" {
return def
} else {
return res
}
}
return def
}

func printHead() {
println(`
This utility will walk you through creating a boss.json file.
It only covers the most common items, and tries to guess sensible defaults.
Use 'boss install <pkg>' afterwards to install a package and
save it as a dependency in the boss.json file.
Press ^C at any time to quit.
`)
}
73 changes: 71 additions & 2 deletions cmd/login.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
package cmd

import (
"github.com/hashload/boss/core"
"fmt"
"log"
"os/user"
"path/filepath"
"syscall"

"github.com/hashload/boss/env"
"github.com/hashload/boss/msg"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)

var removeLogin bool
Expand All @@ -14,7 +22,7 @@ var loginCmd = &cobra.Command{
boss login <repo>`,
Aliases: []string{"adduser", "add-user"},
Run: func(cmd *cobra.Command, args []string) {
core.Login(removeLogin, args)
login(removeLogin, args)
},
}

Expand All @@ -23,3 +31,64 @@ func init() {
loginCmd.Flags().BoolVarP(&removeLogin, "rm", "r", false, "remove login")
RootCmd.AddCommand(loginCmd)
}

func login(removeLogin bool, args []string) {
configuration := env.GlobalConfiguration

if removeLogin {
delete(configuration.Auth, args[0])
configuration.SaveConfiguration()
return
}

var auth *env.Auth
var repo string
if len(args) > 0 && args[0] != "" {
repo = args[0]
auth = configuration.Auth[args[0]]
} else {
repo = getParamOrDef("Url to login (ex: github.com)", "")
if repo == "" {
msg.Die("Empty is not valid!!")
}
auth = configuration.Auth[repo]
}

if auth == nil {
auth = &env.Auth{}
}

auth.UseSsh = getParamBoolean("Use SSH")
if auth.UseSsh {
auth.Path = getParamOrDef("Path of ssh private key("+getSshKeyPath()+")", getSshKeyPath())
} else {
auth.SetUser(getParamOrDef("Username", ""))
auth.SetPass(getPass("Password"))
}
configuration.Auth[repo] = auth
configuration.SaveConfiguration()

}

func getPass(description string) string {
fmt.Print(description + ": ")

bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
msg.Die("Error on get pass: %s", err)
}
return string(bytePassword)
}

func getSshKeyPath() string {
usr, e := user.Current()
if e != nil {
log.Fatal(e)
}
return filepath.Join(usr.HomeDir, ".ssh", "id_rsa")
}

func getParamBoolean(msgS string) bool {
msg.Print(msgS + "(y or n): ")
return msg.PromptUntilYorN()
}
Loading

0 comments on commit f6049f1

Please sign in to comment.