Skip to content

Commit

Permalink
Merge branch 'master' into dev/moul/examples
Browse files Browse the repository at this point in the history
  • Loading branch information
moul committed Sep 21, 2024
2 parents 23856d2 + 9897b66 commit 2e476af
Show file tree
Hide file tree
Showing 14 changed files with 251 additions and 25 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/fossa.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
uses: coursier/cache-action@v6.4.6

- name: Set up JDK 17
uses: coursier/setup-action@v1.3.5
uses: coursier/setup-action@v1.3.6
with:
jvm: temurin:1.17

Expand Down
66 changes: 59 additions & 7 deletions contribs/gnodev/cmd/gnobro/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net"
"net/url"
Expand All @@ -21,7 +22,6 @@ import (
"github.com/charmbracelet/wish"
"github.com/charmbracelet/wish/activeterm"
"github.com/charmbracelet/wish/bubbletea"
"github.com/charmbracelet/wish/logging"
"golang.org/x/sync/errgroup"

"github.com/gnolang/gno/contribs/gnodev/pkg/browser"
Expand All @@ -47,6 +47,7 @@ type broCfg struct {
sshListener string
sshHostKeyPath string
banner bool
jsonlog bool
}

var defaultBroOptions = broCfg{
Expand Down Expand Up @@ -152,6 +153,13 @@ func (c *broCfg) RegisterFlags(fs *flag.FlagSet) {
defaultBroOptions.readonly,
"readonly mode, no commands allowed",
)

fs.BoolVar(
&c.jsonlog,
"jsonlog",
defaultBroOptions.jsonlog,
"display server log as json format",
)
}

func execBrowser(cfg *broCfg, args []string, cio commands.IO) error {
Expand Down Expand Up @@ -277,9 +285,7 @@ func runLocal(ctx context.Context, gnocl *gnoclient.Client, cfg *broCfg, bcfg br

func runServer(ctx context.Context, gnocl *gnoclient.Client, cfg *broCfg, bcfg browser.Config, io commands.IO) error {
// setup logger
charmlogger := charmlog.New(io.Out())
charmlogger.SetLevel(charmlog.DebugLevel)
logger := slog.New(charmlogger)
logger := newLogger(io.Out(), cfg.jsonlog)

teaHandler := func(s ssh.Session) (tea.Model, []tea.ProgramOption) {
shortid := fmt.Sprintf("%.10s", s.Context().SessionID())
Expand Down Expand Up @@ -326,8 +332,8 @@ func runServer(ctx context.Context, gnocl *gnoclient.Client, cfg *broCfg, bcfg b
bubbletea.Middleware(teaHandler),
activeterm.Middleware(), // ensure PTY
ValidatePathCommandMiddleware(bcfg.URLPrefix),
logging.StructuredMiddlewareWithLogger(
charmlogger, charmlog.DebugLevel,
StructuredMiddlewareWithLogger(
ctx, logger, slog.LevelInfo,
),
// XXX: add ip throttler
),
Expand Down Expand Up @@ -358,7 +364,9 @@ func runServer(ctx context.Context, gnocl *gnoclient.Client, cfg *broCfg, bcfg b
return err
}

io.Println("Bye!")
if !cfg.jsonlog {
io.Println("Bye!")
}
return nil
}

Expand Down Expand Up @@ -460,3 +468,47 @@ func ValidatePathCommandMiddleware(pathPrefix string) wish.Middleware {
}
}
}

func StructuredMiddlewareWithLogger(ctx context.Context, logger *slog.Logger, level slog.Level) wish.Middleware {
return func(next ssh.Handler) ssh.Handler {
return func(sess ssh.Session) {
ct := time.Now()
hpk := sess.PublicKey() != nil
pty, _, _ := sess.Pty()
logger.Log(
ctx,
level,
"connect",
"user", sess.User(),
"remote-addr", sess.RemoteAddr().String(),
"public-key", hpk,
"command", sess.Command(),
"term", pty.Term,
"width", pty.Window.Width,
"height", pty.Window.Height,
"client-version", sess.Context().ClientVersion(),
)
next(sess)
logger.Log(
ctx,
level,
"disconnect",
"user", sess.User(),
"remote-addr", sess.RemoteAddr().String(),
"duration", time.Since(ct),
)
}
}
}

func newLogger(out io.Writer, json bool) *slog.Logger {
if json {
return slog.New(slog.NewJSONHandler(out, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
}

charmlogger := charmlog.New(out)
charmlogger.SetLevel(charmlog.DebugLevel)
return slog.New(charmlogger)
}
25 changes: 25 additions & 0 deletions contribs/gnofaucet/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Start a local faucet

## Step1:

Make sure you have started gnoland

../../gno.land/build/gnoland start -lazy

## Step2:

Start the faucet.

./build/gnofaucet serve -chain-id dev -mnemonic "source bonus chronic canvas draft south burst lottery vacant surface solve popular case indicate oppose farm nothing bullet exhibit title speed wink action roast"

By default, the faucet sends out 10,000,000ugnot (10gnot) per request.

## Step3:

Make sure you have started website

../../gno.land/build/gnoweb

Request testing tokens from following URL, Have fun!

http://localhost:8888/faucet
2 changes: 1 addition & 1 deletion docs/reference/gno-js-client/gno-provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ Returns **Promise<string\>**
#### Usage

```ts
await provider.getFileContent('gno.land/r/demo/foo20', 'TotalSupply()')
await provider.getFileContent('gno.land/r/demo/foo20')
/*
foo20.gno
foo20_test.gno
Expand Down
1 change: 1 addition & 0 deletions examples/gno.land/p/demo/fqname/fqname.gno
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func Parse(fqname string) (pkgpath, name string) {
// fmt.Println("Fully Qualified Name:", fqName)
// // Output: gno.land/r/demo/foo20.GRC20
func Construct(pkgpath, name string) string {
// TODO: ensure pkgpath is valid - and as such last part does not contain a dot.
if name == "" {
return pkgpath
}
Expand Down
81 changes: 81 additions & 0 deletions examples/gno.land/p/moul/printfdebugging/color.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package printfdebugging

// consts copied from https://github.com/fatih/color/blob/main/color.go

// Attribute defines a single SGR Code
type Attribute int

const Escape = "\x1b"

// Base attributes
const (
Reset Attribute = iota
Bold
Faint
Italic
Underline
BlinkSlow
BlinkRapid
ReverseVideo
Concealed
CrossedOut
)

const (
ResetBold Attribute = iota + 22
ResetItalic
ResetUnderline
ResetBlinking
_
ResetReversed
ResetConcealed
ResetCrossedOut
)

// Foreground text colors
const (
FgBlack Attribute = iota + 30
FgRed
FgGreen
FgYellow
FgBlue
FgMagenta
FgCyan
FgWhite
)

// Foreground Hi-Intensity text colors
const (
FgHiBlack Attribute = iota + 90
FgHiRed
FgHiGreen
FgHiYellow
FgHiBlue
FgHiMagenta
FgHiCyan
FgHiWhite
)

// Background text colors
const (
BgBlack Attribute = iota + 40
BgRed
BgGreen
BgYellow
BgBlue
BgMagenta
BgCyan
BgWhite
)

// Background Hi-Intensity text colors
const (
BgHiBlack Attribute = iota + 100
BgHiRed
BgHiGreen
BgHiYellow
BgHiBlue
BgHiMagenta
BgHiCyan
BgHiWhite
)
3 changes: 3 additions & 0 deletions examples/gno.land/p/moul/printfdebugging/gno.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module gno.land/p/demo/printfdebugging

require gno.land/p/demo/ufmt v0.0.0-latest
19 changes: 19 additions & 0 deletions examples/gno.land/p/moul/printfdebugging/printfdebugging.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// this package is a joke... or not.
package printfdebugging

import (
"strings"

"gno.land/p/demo/ufmt"
)

func BigRedLine(args ...string) {
println(ufmt.Sprintf("%s[%dm####################################%s[%dm %s",
Escape, int(BgRed), Escape, int(Reset),
strings.Join(args, " "),
))
}

func Success() {
println(" \033[31mS\033[33mU\033[32mC\033[36mC\033[34mE\033[35mS\033[31mS\033[0m ")
}
3 changes: 2 additions & 1 deletion examples/gno.land/r/demo/boards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ your `ACCOUNT_ADDR` and `KEYNAME`

Instead of editing `gno.land/genesis/genesis_balances.txt`, a more general solution (with more steps)
is to run a local "faucet" and use the web browser to add $GNOT. (This can be done at any time.)
See this page: https://github.com/gnolang/gno/blob/master/gno.land/cmd/gnofaucet/README.md
See this page: https://github.com/gnolang/gno/blob/master/contribs/gnofaucet/README.md


### Start the `gnoland` node.

Expand Down
14 changes: 14 additions & 0 deletions examples/gno.land/r/demo/counter/counter.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package counter

import "strconv"

var counter int

func Increment() int {
counter++
return counter
}

func Render(_ string) string {
return strconv.Itoa(counter)
}
22 changes: 22 additions & 0 deletions examples/gno.land/r/demo/counter/counter_test.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package counter

import "testing"

func TestIncrement(t *testing.T) {
counter = 0
val := Increment()
if val != 1 {
t.Fatalf("result from Increment(): %d != 1", val)
}
if counter != val {
t.Fatalf("counter (%d) != val (%d)", counter, val)
}
}

func TestRender(t *testing.T) {
counter = 1337
res := Render("")
if res != "1337" {
t.Fatalf("render result %q != %q", res, "1337")
}
}
1 change: 1 addition & 0 deletions examples/gno.land/r/demo/counter/gno.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module gno.land/r/demo/counter
24 changes: 13 additions & 11 deletions tm2/pkg/bft/fail/fail.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,33 @@ import (
"fmt"
"os"
"strconv"
"sync"
)

func envSet() int {
func setFromEnv() {
callIndexToFailS := os.Getenv("FAIL_TEST_INDEX")

if callIndexToFailS == "" {
return -1
callIndexToFail = -1
} else {
var err error
callIndexToFail, err := strconv.Atoi(callIndexToFailS)
callIndexToFail, err = strconv.Atoi(callIndexToFailS)
if err != nil {
return -1
callIndexToFail = -1
}
return callIndexToFail
}
}

// Fail when FAIL_TEST_INDEX == callIndex
var callIndex int // indexes Fail calls
var (
callIndex int // indexes Fail calls
callIndexToFail int // index of call which should fail
callIndexToFailOnce sync.Once // sync.Once to set the value of the above
)

// Fail exits the program when after being called the same number of times as
// that passed as the FAIL_TEST_INDEX environment variable.
func Fail() {
callIndexToFail := envSet()
if callIndexToFail < 0 {
return
}
callIndexToFailOnce.Do(setFromEnv)

if callIndex == callIndexToFail {
Exit()
Expand Down
Loading

0 comments on commit 2e476af

Please sign in to comment.