Skip to content

Commit

Permalink
Merge pull request #1584 from onflow/cf/demo
Browse files Browse the repository at this point in the history
Misc interactive init changes
  • Loading branch information
chasefleming authored May 15, 2024
2 parents 3a4f939 + 40dd865 commit 008cf31
Show file tree
Hide file tree
Showing 15 changed files with 98 additions and 162 deletions.
1 change: 0 additions & 1 deletion cmd/flow/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ func main() {
}

// quick commands
quick.InitCommand.AddToParent(cmd)
quick.DeployCommand.AddToParent(cmd)
quick.RunCommand.AddToParent(cmd)

Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ require (
github.com/onflow/cadence-tools/lint v0.14.2
github.com/onflow/cadence-tools/test v0.14.7
github.com/onflow/fcl-dev-wallet v0.7.4
github.com/onflow/flixkit-go v1.1.3
github.com/onflow/flixkit-go v1.1.4-0.20240507174933-7a1de7bbf70f
github.com/onflow/flow-core-contracts/lib/go/templates v1.2.4-0.20231016154253-a00dbf7c061f
github.com/onflow/flow-emulator v0.62.1
github.com/onflow/flow-go v0.33.2-0.20240412174857-015156b297b5
github.com/onflow/flow-go-sdk v0.46.3
github.com/onflow/flowkit v1.17.3
github.com/onflow/flowkit v1.17.4-0.20240507180449-b565ca87f6b8
github.com/onflowser/flowser/v3 v3.1.3
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
github.com/pkg/errors v0.9.1
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -936,8 +936,8 @@ github.com/onflow/crypto v0.25.1 h1:0txy2PKPMM873JbpxQNbJmuOJtD56bfs48RQfm0ts5A=
github.com/onflow/crypto v0.25.1/go.mod h1:C8FbaX0x8y+FxWjbkHy0Q4EASCDR9bSPWZqlpCLYyVI=
github.com/onflow/fcl-dev-wallet v0.7.4 h1:vI6t3U0AO88R/Iitn5KsnniSpbN9Lqsqwvi9EJT4C0k=
github.com/onflow/fcl-dev-wallet v0.7.4/go.mod h1:kc42jkiuoPJmxMRFjfbRO9XvnR/3XLheaOerxVMDTiw=
github.com/onflow/flixkit-go v1.1.3 h1:td94mkklIwXvDP075D0eofPE04oKse24PxvFTyOvMJI=
github.com/onflow/flixkit-go v1.1.3/go.mod h1:qOYI1l7r3gSPk6luTnk95ni020UeTY+E48GuB3Tl0xk=
github.com/onflow/flixkit-go v1.1.4-0.20240507174933-7a1de7bbf70f h1:8UEBHYC6mgc2c7U3p2ZoC3R6gupn1oqU61/jURZTsjI=
github.com/onflow/flixkit-go v1.1.4-0.20240507174933-7a1de7bbf70f/go.mod h1:KUk8ODCdwNYF8PBYdu+VBTTrZ1IPWKvVJsdsGsEAtA0=
github.com/onflow/flow-core-contracts/lib/go/contracts v1.2.4-0.20231016154253-a00dbf7c061f h1:S8yIZw9LFXfYD1V5H9BiixihHw3GrXVPrmfplSzYaww=
github.com/onflow/flow-core-contracts/lib/go/contracts v1.2.4-0.20231016154253-a00dbf7c061f/go.mod h1:jM6GMAL+m0hjusUgiYDNrixPQ6b9s8xjoJQoEu5bHQI=
github.com/onflow/flow-core-contracts/lib/go/templates v1.2.4-0.20231016154253-a00dbf7c061f h1:Ep+Mpo2miWMe4pjPGIaEvEzshRep30dvNgxqk+//FrQ=
Expand All @@ -957,8 +957,8 @@ github.com/onflow/flow-nft/lib/go/contracts v1.1.0/go.mod h1:YsvzYng4htDgRB9sa9j
github.com/onflow/flow/protobuf/go/flow v0.2.2/go.mod h1:gQxYqCfkI8lpnKsmIjwtN2mV/N2PIwc1I+RUK4HPIc8=
github.com/onflow/flow/protobuf/go/flow v0.4.0 h1:5TGmPwRmnSt7aawgtPGF9ehoGHHir9Cy9LVoAiU9t/E=
github.com/onflow/flow/protobuf/go/flow v0.4.0/go.mod h1:NA2pX2nw8zuaxfKphhKsk00kWLwfd+tv8mS23YXO4Sk=
github.com/onflow/flowkit v1.17.3 h1:0Fi3tLnieWOYq95A3ySk3TZ0GUPtKaX8ofssgve9e58=
github.com/onflow/flowkit v1.17.3/go.mod h1:laapt1diM4Pbqt0dotKMH+LbUAOEqgugpH1p4+sPhcw=
github.com/onflow/flowkit v1.17.4-0.20240507180449-b565ca87f6b8 h1:59gqw1cXdvyV+jYbItoqULLxcA1MWrTSzcSsgRIXEto=
github.com/onflow/flowkit v1.17.4-0.20240507180449-b565ca87f6b8/go.mod h1:laapt1diM4Pbqt0dotKMH+LbUAOEqgugpH1p4+sPhcw=
github.com/onflow/go-ethereum v1.13.4 h1:iNO86fm8RbBbhZ87ZulblInqCdHnAQVY8okBrNsTevc=
github.com/onflow/go-ethereum v1.13.4/go.mod h1:cE/gEUkAffhwbVmMJYz+t1dAfVNHNwZCgc3BWtZxBGY=
github.com/onflow/nft-storefront/lib/go/contracts v0.0.0-20221222181731-14b90207cead h1:2j1Unqs76Z1b95Gu4C3Y28hzNUHBix7wL490e61SMSw=
Expand Down
2 changes: 1 addition & 1 deletion internal/accounts/create-interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func createInteractive(state *flowkit.State) (*accountResult, error) {
log := output.NewStdoutLogger(output.InfoLog)
name := prompt.AccountNamePrompt(state.Accounts().Names())
networkName, selectedNetwork := prompt.CreateAccountNetworkPrompt()
privateFile := accounts.PrivateKeyFile(name)
privateFile := accounts.PrivateKeyFile(name, "")

// create new gateway based on chosen network
gw, err := gateway.NewGrpcGateway(selectedNetwork)
Expand Down
2 changes: 1 addition & 1 deletion internal/cadence/lint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ func setupMockState(t *testing.T) *flowkit.State {
}`), 0644)

rw := afero.Afero{Fs: mockFs}
state, err := flowkit.Init(rw, crypto.ECDSA_P256, crypto.SHA3_256)
state, err := flowkit.Init(rw, crypto.ECDSA_P256, crypto.SHA3_256, "")
require.NoError(t, err)

// Mock flowkit contracts
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ var Cmd = &cobra.Command{
}

func init() {
initCommand.AddToParent(Cmd)
//initCommand.AddToParent(Cmd)
Cmd.AddCommand(addCmd)
Cmd.AddCommand(removeCmd)
}
Expand Down
139 changes: 38 additions & 101 deletions internal/config/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,32 @@
package config

import (
"bytes"
"fmt"
"os"

"github.com/onflow/flow-go-sdk/crypto"
"github.com/spf13/cobra"

"github.com/onflow/flowkit"
"github.com/onflow/flowkit/config"
"github.com/onflow/flowkit/output"

"github.com/onflow/flow-cli/internal/command"
"github.com/onflow/flow-cli/internal/util"
)

type flagsInit struct {
ServicePrivateKey string `flag:"service-private-key" info:"Service account private key"`
ServiceKeySigAlgo string `default:"ECDSA_P256" flag:"service-sig-algo" info:"Service account key signature algorithm"`
ServiceKeyHashAlgo string `default:"SHA3_256" flag:"service-hash-algo" info:"Service account key hash algorithm"`
Reset bool `default:"false" flag:"reset" info:"Reset configuration file"`
Global bool `default:"false" flag:"global" info:"Initialize global user configuration"`
}

var InitFlag = flagsInit{}

var initCommand = &command.Command{
Cmd: &cobra.Command{
Use: "init",
Short: "Initialize a new configuration",
},
Flags: &InitFlag,
Run: Initialise,
}
//type flagsInit struct {
// ServicePrivateKey string `flag:"service-private-key" info:"Service account private key"`
// ServiceKeySigAlgo string `default:"ECDSA_P256" flag:"service-sig-algo" info:"Service account key signature algorithm"`
// ServiceKeyHashAlgo string `default:"SHA3_256" flag:"service-hash-algo" info:"Service account key hash algorithm"`
// Reset bool `default:"false" flag:"reset" info:"Reset configuration file"`
// Global bool `default:"false" flag:"global" info:"Initialize global user configuration"`
//}
//
//var InitFlag = flagsInit{}

//var initCommand = &command.Command{
// Cmd: &cobra.Command{
// Use: "init",
// Short: "Initialize a new configuration",
// },
// Flags: &InitFlag,
// Run: Initialise,
//}

// InitConfigParameters holds all necessary parameters for initializing the configuration.
type InitConfigParameters struct {
Expand All @@ -64,7 +57,25 @@ type InitConfigParameters struct {
}

// InitializeConfiguration creates the Flow configuration json file based on the provided parameters.
func InitializeConfiguration(params InitConfigParameters, logger output.Logger, readerWriter flowkit.ReaderWriter) (*flowkit.State, error) {
func InitializeConfiguration(params InitConfigParameters, readerWriter flowkit.ReaderWriter) (*flowkit.State, error) {
var path string
if params.TargetDirectory != "" {
path = fmt.Sprintf("%s/flow.json", params.TargetDirectory)

// Create the directory if it doesn't exist
err := readerWriter.MkdirAll(params.TargetDirectory, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("failed to create target directory: %w", err)
}
} else {
// Otherwise, choose between the default and global paths
if params.Global {
path = config.GlobalPath()
} else {
path = config.DefaultPath
}
}

sigAlgo := crypto.StringToSignatureAlgorithm(params.ServiceKeySigAlgo)
if sigAlgo == crypto.UnknownSignatureAlgorithm {
return nil, fmt.Errorf("invalid signature algorithm: %s", params.ServiceKeySigAlgo)
Expand All @@ -75,7 +86,7 @@ func InitializeConfiguration(params InitConfigParameters, logger output.Logger,
return nil, fmt.Errorf("invalid hash algorithm: %s", params.ServiceKeyHashAlgo)
}

state, err := flowkit.Init(readerWriter, sigAlgo, hashAlgo)
state, err := flowkit.Init(readerWriter, sigAlgo, hashAlgo, params.TargetDirectory)
if err != nil {
return nil, err
}
Expand All @@ -89,86 +100,12 @@ func InitializeConfiguration(params InitConfigParameters, logger output.Logger,
state.SetEmulatorKey(privateKey)
}

var path string
if params.TargetDirectory != "" {
path = fmt.Sprintf("%s/flow.json", params.TargetDirectory)

// Create the directory if it doesn't exist
err := state.ReaderWriter().MkdirAll(params.TargetDirectory, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("failed to create target directory: %w", err)
}
} else {
// Otherwise, choose between the default and global paths
if params.Global {
path = config.GlobalPath()
} else {
path = config.DefaultPath
}
}

if config.Exists(path) && !params.Reset {
return nil, fmt.Errorf(
"configuration already exists at: %s, if you want to reset configuration use the reset flag",
path,
)
}

err = state.Save(path)
if err != nil {
return nil, err
}

return state, nil
}

func Initialise(
_ []string,
_ command.GlobalFlags,
logger output.Logger,
readerWriter flowkit.ReaderWriter,
_ flowkit.Services,
) (command.Result, error) {
params := InitConfigParameters{
ServicePrivateKey: InitFlag.ServicePrivateKey,
ServiceKeySigAlgo: InitFlag.ServiceKeySigAlgo,
ServiceKeyHashAlgo: InitFlag.ServiceKeyHashAlgo,
Reset: InitFlag.Reset,
Global: InitFlag.Global,
}
state, err := InitializeConfiguration(params, logger, readerWriter)
if err != nil {
return nil, err
}

return &InitResult{State: state}, nil
}

type InitResult struct {
*flowkit.State
}

func (r *InitResult) JSON() any {
return r
}

func (r *InitResult) String() string {
var b bytes.Buffer
writer := util.CreateTabWriter(&b)
account, _ := r.State.EmulatorServiceAccount()

_, _ = fmt.Fprintf(writer, "Configuration initialized\n")
_, _ = fmt.Fprintf(writer, "Service account: %s\n\n", output.Bold("0x"+account.Address.String()))
_, _ = fmt.Fprintf(writer,
"Start emulator by running: %s \nReset configuration using: %s\n",
output.Bold("'flow emulator'"),
output.Bold("'flow init --reset'"),
)

_ = writer.Flush()
return b.String()
}

func (r *InitResult) Oneliner() string {
return ""
}
2 changes: 1 addition & 1 deletion internal/emulator/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func configuredServiceKey(
hashAlgo = emulator.DefaultServiceKeyHashAlgo
}

state, err = flowkit.Init(loader, sigAlgo, hashAlgo)
state, err = flowkit.Init(loader, sigAlgo, hashAlgo, "")
if err != nil {
exitf(1, err.Error())
} else {
Expand Down
2 changes: 1 addition & 1 deletion internal/prompt/select-options.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func (m optionSelectModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
func (m optionSelectModel) View() string {
var b strings.Builder
b.WriteString(fmt.Sprintf("%s\n", m.message))
b.WriteString("Use arrow keys to navigate, space to select, enter to confirm, q to quit:\n\n")
b.WriteString("Use arrow keys to navigate, space to select, enter to confirm or skip, q to quit:\n\n")
for i, choice := range m.choices {
if m.cursor == i {
b.WriteString("> ")
Expand Down
27 changes: 10 additions & 17 deletions internal/quick/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,15 @@

package quick

import (
"github.com/spf13/cobra"

"github.com/onflow/flow-cli/internal/command"
"github.com/onflow/flow-cli/internal/config"
)

// TODO(sideninja) workaround - init needed to be copied in order to work else there is flag duplicate error

var InitCommand = &command.Command{
Cmd: &cobra.Command{
Use: "init",
Short: "Initialize a new configuration",
Example: "flow project init",
GroupID: "project",
},
Flags: &config.InitFlag,
Run: config.Initialise, // TODO(sideninja) workaround - init needed to be copied in order to work else there is flag duplicate error
}
//var InitCommand = &command.Command{
// Cmd: &cobra.Command{
// Use: "init",
// Short: "Initialize a new configuration",
// Example: "flow project init",
// GroupID: "project",
// },
// Flags: &config.InitFlag,
// Run: config.Initialise, // TODO(sideninja) workaround - init needed to be copied in order to work else there is flag duplicate error
//}
2 changes: 1 addition & 1 deletion internal/super/flix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ func Test_GenerateFlixPrefill(t *testing.T) {
var rw = afero.Afero{Fs: mockFS}
err := rw.WriteFile(cadenceFile, []byte(CADENCE_SCRIPT), 0644)
assert.NoError(t, err)
state, _ := flowkit.Init(rw, crypto.ECDSA_P256, crypto.SHA3_256)
state, _ := flowkit.Init(rw, crypto.ECDSA_P256, crypto.SHA3_256, "")

mockFlixService := new(MockFlixService)
ctx := context.Background()
Expand Down
19 changes: 12 additions & 7 deletions internal/super/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func generateContract(
_ flowkit.Services,
state *flowkit.State,
) (result command.Result, err error) {
generator := NewGenerator(DefaultCadenceDirectory, state, logger, false)
generator := NewGenerator(DefaultCadenceDirectory, state, logger, false, true)
contract := Contract{Name: args[0], Account: args[1]}
err = generator.Create(TemplateMap{ContractType: []TemplateItem{contract}})
return nil, err
Expand All @@ -122,7 +122,7 @@ func generateTransaction(
_ flowkit.Services,
state *flowkit.State,
) (result command.Result, err error) {
generator := NewGenerator(DefaultCadenceDirectory, state, logger, false)
generator := NewGenerator(DefaultCadenceDirectory, state, logger, false, true)
transaction := OtherTemplate{Name: args[0]}
err = generator.Create(TemplateMap{TransactionType: []TemplateItem{transaction}})
return nil, err
Expand All @@ -135,7 +135,7 @@ func generateScript(
_ flowkit.Services,
state *flowkit.State,
) (result command.Result, err error) {
generator := NewGenerator(DefaultCadenceDirectory, state, logger, false)
generator := NewGenerator(DefaultCadenceDirectory, state, logger, false, true)
script := OtherTemplate{Name: args[0]}
err = generator.Create(TemplateMap{ScriptType: []TemplateItem{script}})
return nil, err
Expand Down Expand Up @@ -186,14 +186,16 @@ type Generator struct {
state *flowkit.State
logger output.Logger
disableLogs bool
saveState bool
}

func NewGenerator(directory string, state *flowkit.State, logger output.Logger, disableLogs bool) *Generator {
func NewGenerator(directory string, state *flowkit.State, logger output.Logger, disableLogs, saveState bool) *Generator {
return &Generator{
directory: directory,
state: state,
logger: logger,
disableLogs: disableLogs,
saveState: saveState,
}
}

Expand Down Expand Up @@ -327,9 +329,12 @@ func (g *Generator) updateContractsState(name, location string) error {
}

g.state.Contracts().AddOrUpdate(contract)
err := g.state.SaveDefault()
if err != nil {
return fmt.Errorf("error saving to flow.json: %w", err)

if g.saveState {
err := g.state.SaveDefault() // TODO: Support adding a target project directory
if err != nil {
return fmt.Errorf("error saving to flow.json: %w", err)
}
}

return nil
Expand Down
Loading

0 comments on commit 008cf31

Please sign in to comment.