Skip to content

Commit

Permalink
use errgroup
Browse files Browse the repository at this point in the history
  • Loading branch information
notJoon committed Jan 23, 2025
1 parent 5f79829 commit 691d60d
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 26 deletions.
37 changes: 19 additions & 18 deletions gnovm/cmd/gno/doctest.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

dt "github.com/gnolang/gno/gnovm/pkg/doctest"
"github.com/gnolang/gno/tm2/pkg/commands"
"golang.org/x/sync/errgroup"
)

type doctestCfg struct {
Expand Down Expand Up @@ -68,32 +69,32 @@ func execDoctest(cfg *doctestCfg, _ []string, io commands.IO) error {
ctx, cancel := context.WithTimeout(context.Background(), cfg.timeout)
defer cancel()

resultChan := make(chan []string)
errChan := make(chan error)
g, gctx := errgroup.WithContext(ctx)

go func() {
results, err := dt.ExecuteMatchingCodeBlock(ctx, content, cfg.runPattern)
var results []string
g.Go(func() error {
res, err := dt.ExecuteMatchingCodeBlock(gctx, content, cfg.runPattern)
if err != nil {
errChan <- err
} else {
resultChan <- results
return err
}

Check warning on line 79 in gnovm/cmd/gno/doctest.go

View check run for this annotation

Codecov / codecov/patch

gnovm/cmd/gno/doctest.go#L78-L79

Added lines #L78 - L79 were not covered by tests
}()
results = res
return nil
})

select {
case results := <-resultChan:
if len(results) == 0 {
io.Println("No code blocks matched the pattern")
return nil
if err := g.Wait(); err != nil {
if ctx.Err() == context.DeadlineExceeded {
return fmt.Errorf("execution timed out after %v", cfg.timeout)
}
io.Println("Execution Result:")
io.Println(strings.Join(results, "\n\n"))
case err := <-errChan:
return fmt.Errorf("failed to execute code block: %w", err)

Check warning on line 88 in gnovm/cmd/gno/doctest.go

View check run for this annotation

Codecov / codecov/patch

gnovm/cmd/gno/doctest.go#L85-L88

Added lines #L85 - L88 were not covered by tests
case <-ctx.Done():
return fmt.Errorf("execution timed out after %v", cfg.timeout)
}

if len(results) == 0 {
io.Println("No code blocks matched the pattern")
return nil
}

Check warning on line 94 in gnovm/cmd/gno/doctest.go

View check run for this annotation

Codecov / codecov/patch

gnovm/cmd/gno/doctest.go#L92-L94

Added lines #L92 - L94 were not covered by tests

io.Println("Execution Result:")
io.Println(strings.Join(results, "\n\n"))
return nil
}

Expand Down
4 changes: 2 additions & 2 deletions gnovm/cmd/gno/doctest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ func main() {
stdoutShouldContain: "=== StringReversal ===\n\n!oG ,olleH",
},
{
args: []string{"doctest", "-path", mdFilePath, "-run", "StdPackage"},
stdoutShouldContain: "=== StdPackage ===\n\ng14ch5q26mhx3jk5cxl88t278nper264ces4m8nt",
args: []string{"doctest", "-path", mdFilePath, "-run", "StdPackage"},
stdoutShouldMatch: `g[a-z0-9]+\n`,
},
}

Expand Down
6 changes: 5 additions & 1 deletion gnovm/cmd/gno/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type testMainCase struct {
stderrShouldContain string
stdoutShouldBe string
stdoutShouldContain string
stdoutShouldMatch string
stderrShouldBe string
recoverShouldContain string
recoverShouldBe string
Expand All @@ -48,7 +49,7 @@ func testMainCaseRun(t *testing.T, tc []testMainCase) {

for _, test := range tc {
errShouldBeEmpty := test.errShouldContain == "" && test.errShouldBe == ""
stdoutShouldBeEmpty := test.stdoutShouldContain == "" && test.stdoutShouldBe == ""
stdoutShouldBeEmpty := test.stdoutShouldContain == "" && test.stdoutShouldBe == "" && test.stdoutShouldMatch == ""
stderrShouldBeEmpty := test.stderrShouldContain == "" && test.stderrShouldBe == ""
recoverShouldBeEmpty := test.recoverShouldContain == "" && test.recoverShouldBe == ""

Expand All @@ -73,6 +74,9 @@ func testMainCaseRun(t *testing.T, tc []testMainCase) {
if test.stdoutShouldContain != "" {
require.Contains(t, mockOut.String(), test.stdoutShouldContain, "stdout should contain")
}
if test.stdoutShouldMatch != "" {
require.Regexp(t, test.stdoutShouldMatch, mockOut.String(), "stdout should match pattern")
}
if test.stdoutShouldBe != "" {
require.Equal(t, test.stdoutShouldBe, mockOut.String(), "stdout should be")
}
Expand Down
17 changes: 12 additions & 5 deletions gnovm/pkg/doctest/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/gnolang/gno/gno.land/pkg/sdk/vm"
"github.com/gnolang/gno/gnovm"
bft "github.com/gnolang/gno/tm2/pkg/bft/types"
"github.com/gnolang/gno/tm2/pkg/crypto"
"github.com/gnolang/gno/tm2/pkg/crypto/ed25519"
"github.com/gnolang/gno/tm2/pkg/db/memdb"
"github.com/gnolang/gno/tm2/pkg/log"
"github.com/gnolang/gno/tm2/pkg/sdk"
Expand All @@ -38,7 +38,7 @@ var (
cache = newCache(maxCacheSize)
regexCache = make(map[string]*regexp.Regexp)

addrRegex = regexp.MustCompile(`gno\.land/r/g[a-z0-9]+/[a-z.]+`)
addrRegex = regexp.MustCompile(`gno\.land/r/[a-z0-9]+/[a-z_/.]+`)
)

// ExecuteCodeBlock executes a parsed code block and executes it in a gno VM.
Expand Down Expand Up @@ -66,7 +66,9 @@ func ExecuteCodeBlock(c codeBlock, stdlibDir string) (string, error) {
{Name: fmt.Sprintf("%d.%s", c.index, lang), Body: c.content},
}

addr := crypto.AddressFromPreimage([]byte("addr1"))
// create a freash account for the code block
privKey := ed25519.GenPrivKey()
addr := privKey.PubKey().Address()
acc := acck.NewAccountWithAddress(ctx, addr)
acck.SetAccount(ctx, acc)

Expand Down Expand Up @@ -128,6 +130,11 @@ func ExecuteMatchingCodeBlock(
return results, nil
}

// setupEnv creates and initializes the execution environment for running extracted code blocks.
// It sets up necessary keepers (account, bank, VM), initializes a test chain context,
// and loads standard libraries. The function returns the context, keepers, and stdlib context
// needed for code execution.
//
// ref: gno.land/pkg/sdk/vm/common_test.go
func setupEnv() (
sdk.Context,
Expand Down Expand Up @@ -155,14 +162,14 @@ func setupEnv() (
prmk := paramsm.NewParamsKeeper(iavlKey, "params")
acck := authm.NewAccountKeeper(iavlKey, prmk, std.ProtoBaseAccount)
bank := bankm.NewBankKeeper(acck)
stdlibsDir := GetStdlibsDir()
vmk := vm.NewVMKeeper(baseKey, iavlKey, acck, bank, prmk)

mcw := ms.MultiCacheWrap()

vmk := vm.NewVMKeeper(baseKey, iavlKey, acck, bank, prmk)
vmk.Initialize(log.NewNoopLogger(), mcw)

stdlibCtx := vmk.MakeGnoTransactionStore(ctx.WithMultiStore(mcw))
stdlibsDir := GetStdlibsDir()
vmk.LoadStdlib(stdlibCtx, stdlibsDir)
vmk.CommitGnoTransactionStore(stdlibCtx)

Expand Down

0 comments on commit 691d60d

Please sign in to comment.