Skip to content

Commit

Permalink
Best version yet of nameManager
Browse files Browse the repository at this point in the history
  • Loading branch information
tjayrush committed Sep 13, 2024
1 parent 9ef40bf commit f1eb168
Show file tree
Hide file tree
Showing 10 changed files with 146 additions and 90 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@
*.out
go.work
go.work.sum
.env
.key
2 changes: 1 addition & 1 deletion nameManager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

```bash
cd ./nameManager
go build -o nameManager main.go actions.go help.go parseArgs.go
go build -o nameManager ./...
./nameManager --help
```

Expand Down
47 changes: 16 additions & 31 deletions nameManager/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,94 +21,79 @@ const (
Publish Action = "publish"
)

func autoName(args []string) {
// AutoName implements the chifra names --autoname <address> command.
func (a *App) AutoName(args []string) {
opts := sdk.NamesOptions{
Regular: os.Getenv("TB_NAMEMANAGER_REGULAR") == "true",
Regular: a.IsRegular(),
}
address := base.HexToAddress(args[2])
if result, _, err := opts.NamesAutoname(address); err != nil {
printError(err.Error())
printHelp(err)
} else {
sortNames()
for _, name := range result {
fmt.Printf("Name auto updated: %v\n", name.String())
}
}
}

func deleteName(args []string) {
// DeleteName implements the chifra names --delete <address> command.
func (a *App) DeleteName(args []string) {
opts := sdk.NamesOptions{
Regular: os.Getenv("TB_NAMEMANAGER_REGULAR") == "true",
}
address := base.HexToAddress(args[2])
cd := crud.CrudFromName(types.Name{Address: address})
if result, _, err := opts.ModifyName(crud.Delete, cd); err != nil {
printError(err.Error())
printHelp(err)
} else {
sortNames()
for _, name := range result {
fmt.Printf("Name deleted: %v\n", name.String())
}
}
}

func undeleteName(args []string) {
// UndeleteName implements the chifra names --undelete <address> command.
func (a *App) UndeleteName(args []string) {
opts := sdk.NamesOptions{
Regular: os.Getenv("TB_NAMEMANAGER_REGULAR") == "true",
}
address := base.HexToAddress(args[2])
cd := crud.CrudFromName(types.Name{Address: address})
if result, _, err := opts.ModifyName(crud.Undelete, cd); err != nil {
printError(err.Error())
printHelp(err)
} else {
sortNames()
for _, name := range result {
fmt.Printf("Name undeleted: %v\n", name.String())
}
}
}

func removeNode(args []string) {
// RemoveName implements the chifra names --remove <address> command.
func (a *App) RemoveName(args []string) {
opts := sdk.NamesOptions{
Regular: os.Getenv("TB_NAMEMANAGER_REGULAR") == "true",
}
address := base.HexToAddress(args[2])
cd := crud.CrudFromName(types.Name{Address: address})
if result, _, err := opts.ModifyName(crud.Remove, cd); err != nil {
printError(err.Error())
printHelp(err)
} else {
sortNames()
for _, name := range result {
fmt.Printf("Name removed: %v\n", name.String())
}
}
}

func cleanNames() {
// CleanNames implements the chifra names --clean command.
func (a *App) CleanNames() {
opts := sdk.NamesOptions{
Regular: os.Getenv("TB_NAMEMANAGER_REGULAR") == "true",
}
if msgs, _, err := opts.NamesClean(); err != nil {
printError(err.Error())
printHelp(err)
} else {
for i, msg := range msgs {
fmt.Println(i, msg.String())
}
}
}

func sortNames() {
// fn :=
// opts := sdk.NamesOptions{
// Regular: os.Getenv("TB_NAMEMANAGER_REGULAR") == "true",
// Custom: os.Getenv("TB_NAMEMANAGER_REGULAR") != "true",
// DryRun: true,
// }
// if names, _, err := opts.Names(); err != nil {
// printError(err.Error())
// } else {
// for _, name := range names {
// fmt.Println(name)
// }
// }
}
60 changes: 60 additions & 0 deletions nameManager/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"io"
"log/slog"
"os"
"strings"

"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger"
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/names"
)

// App is the main structure carrying the command line options, loggers, and application state
type App struct {
logger *slog.Logger
database names.DatabaseType
action Action
}

// NewApp returns a new application ready to be used.
func NewApp() *App {
logger.SetLoggerWriter(io.Discard) // we never want core to log anything
logLevel := slog.LevelInfo
if ll, ok := os.LookupEnv("TB_LOGLEVEL"); ok {
switch strings.ToLower(ll) {
case "debug":
logLevel = slog.LevelDebug
case "info":
logLevel = slog.LevelInfo
case "warn":
logLevel = slog.LevelWarn
case "error":
logLevel = slog.LevelError
}
}
opts := slog.HandlerOptions{
Level: logLevel,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
a.Value = slog.StringValue(a.Value.Time().Format("15:04:05"))
}
return a
},
}

app := App{
logger: slog.New(slog.NewTextHandler(os.Stderr, &opts)),
database: names.DatabaseCustom,
}

if os.Getenv("TB_NAMEMANAGER_REGULAR") == "true" {
app.database = names.DatabaseRegular
}

return &app
}

func (a *App) IsRegular() bool {
return a.database == names.DatabaseRegular
}
2 changes: 1 addition & 1 deletion nameManager/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module github.com/TrueBlocks/trueblocks-core/examples/nameManager
go 1.22

require (
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240901212707-3b0228642466
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240910133800-32057ca62fe7
github.com/TrueBlocks/trueblocks-sdk/v3 v3.3.2
)

Expand Down
4 changes: 4 additions & 0 deletions nameManager/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAE
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240901212707-3b0228642466 h1:DNH7mYWEEehKLRiFjBoiMoZJMdpuVNiLnFvsstQW2To=
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240901212707-3b0228642466/go.mod h1:YKuaek8RSyh681TFMK6Ua8MsHtuY+c1VJWi78Y35+J8=
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240906195947-7a9af20ce595 h1:NCGoHSqcQonbS+uGiuIhvdMI80bw1OFqVsz0gXAGLIg=
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240906195947-7a9af20ce595/go.mod h1:YKuaek8RSyh681TFMK6Ua8MsHtuY+c1VJWi78Y35+J8=
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240910133800-32057ca62fe7 h1:M1KM1VwdlwgXLXi2ETH4spbwssfkdK2ux/qvC5wv2AM=
github.com/TrueBlocks/trueblocks-core/src/apps/chifra v0.0.0-20240910133800-32057ca62fe7/go.mod h1:YKuaek8RSyh681TFMK6Ua8MsHtuY+c1VJWi78Y35+J8=
github.com/TrueBlocks/trueblocks-sdk/v3 v3.3.2 h1:SVemhtXxeYuOV/dQlQ/ECr66RiIPBS38rZ+WCqrXDSQ=
github.com/TrueBlocks/trueblocks-sdk/v3 v3.3.2/go.mod h1:GFP6A7O1tNgun1f/CrrhJkro9cbqu5t1prt5aboKqJU=
github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw=
Expand Down
11 changes: 6 additions & 5 deletions nameManager/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/colors"
)

func printHelp() {
func printHelp(err error) {
helpText := `
Usage: nameManager [options] address name [tags [source [symbol [decimals]]]]
nameManager --autoname address
Expand Down Expand Up @@ -36,10 +36,11 @@ Options:
--publish Share any customized names you've created with the community via the Unchained Index
--clean Clean the names database including sorting and removing dups (if any)
`

if err != nil {
fmt.Fprintf(os.Stderr, "%sError: %s%s\n", colors.Red, err.Error(), colors.Off)
}
fmt.Fprintf(os.Stderr, "%s", helpText)
os.Exit(0)
}

func printError(msg string) {
fmt.Fprintf(os.Stderr, "%sError: %s%s\n", colors.Red, msg, colors.Off)
os.Exit(0)
}
56 changes: 28 additions & 28 deletions nameManager/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,42 @@ import (
"os"

"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/crud"
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/names"
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/types"
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/usage"
sdk "github.com/TrueBlocks/trueblocks-sdk/v3"
)

func main() {
if ok, action := parseArgs(); !ok {
return
} else {
if os.Getenv("TB_NAMEMANAGER_REGULAR") == "true" {
if !usage.QueryUser("Are you sure you want to operate against the Regular names database (Y/n)?", "Quitting...") {
os.Exit(0)
}
}
app := ParseArgs()

switch action {
case AutoName:
autoName(os.Args)
return
case Delete:
deleteName(os.Args)
return
case Undelete:
undeleteName(os.Args)
return
case Remove:
removeNode(os.Args)
return
case Clean:
cleanNames()
return
case Publish:
publishNames()
return
if app.database == names.DatabaseRegular {
if !usage.QueryUser("Are you sure you want to operate against the Regular names database (Y/n)?", "Quitting...") {
os.Exit(0)
}
}

switch app.action {
case AutoName:
app.AutoName(os.Args)
return
case Delete:
app.DeleteName(os.Args)
return
case Undelete:
app.UndeleteName(os.Args)
return
case Remove:
app.RemoveName(os.Args)
return
case Clean:
app.CleanNames()
return
case Publish:
app.PublishNames()
return
}

var name types.Name

name.Address, _, _ = getValue(1, "address", "0xf503017d7baf7fbc0fff7492b751025c6a78179b")
Expand All @@ -54,7 +53,8 @@ func main() {
opts := sdk.NamesOptions{}
cd := crud.CrudFromName(name)
if names, _, err := opts.ModifyName(crud.Update, cd); err != nil {
printError(err.Error())
printHelp(err)

} else {
for _, name := range names {
fmt.Printf("Names: %v\n", name.String())
Expand Down
49 changes: 26 additions & 23 deletions nameManager/parseArgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,49 +9,52 @@ import (
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/base"
)

func parseArgs() (ok bool, action Action) {
func ParseArgs() *App {
if len(os.Args) < 2 {
printError("not enough arguments")
printHelp()
return false, ""
printHelp(fmt.Errorf("not enough arguments"))
}

app := NewApp()

switch os.Args[1] {
case "--help", "-h":
printHelp()
return false, ""
printHelp(nil)

case "--autoname", "--delete", "--undelete", "--remove":
if len(os.Args) != 3 {
printError("'" + os.Args[1] + "' accepts only a single argument: address")
printHelp()
return false, ""
printHelp(fmt.Errorf("'" + os.Args[1] + "' expects an address"))
}

addr := os.Args[2]
if !base.IsValidAddress(addr) {
printError("Invalid address: " + addr)
printHelp()
return false, ""
printHelp(fmt.Errorf("invalid address: " + addr))
}
return true, Action(strings.TrimPrefix(os.Args[1], "--"))

case "--clean", "--pin", "--publish":
return true, Action(strings.TrimPrefix(os.Args[1], "--"))
app.action = Action(strings.TrimPrefix(os.Args[1], "--"))
return app

case "--clean", "--publish":
app.action = Action(strings.TrimPrefix(os.Args[1], "--"))
return app

default:
if len(os.Args) < 3 {
printError("not enough arguments (missing address, name, or both)")
printHelp()
return false, ""
printHelp(fmt.Errorf("not enough arguments (missing address, name, or both)"))
}

for _, arg := range os.Args {
if arg == "--autoname" || arg == "--delete" || arg == "--undelete" || arg == "--remove" {
printError("'" + arg + "', if present, must appear first in the argument list")
printHelp()
return false, ""
if arg == "--autoname" ||
arg == "--delete" ||
arg == "--undelete" ||
arg == "--remove" ||
arg == "--clean" ||
arg == "--publish" {
printHelp(fmt.Errorf("'" + arg + "', if present, must appear first in the argument list"))
}
}
return true, ""
}

return app
}

func getValue(index int, field, def string) (base.Address, string, uint64) {
Expand Down
3 changes: 2 additions & 1 deletion nameManager/publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import (
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/names"
)

func publishNames() {
// PublishNames implements the chifra names --publish command.
func (a *App) PublishNames() {
filePath := filepath.Join(config.MustGetPathToChainConfig("mainnet"), string(names.DatabaseCustom))
if os.Getenv("TB_NAMEMANAGER_REGULAR") == "true" {
filePath = filepath.Join(config.MustGetPathToChainConfig("mainnet"), string(names.DatabaseRegular))
Expand Down

0 comments on commit f1eb168

Please sign in to comment.