-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathdiff-contract.go
More file actions
252 lines (217 loc) · 6.72 KB
/
Copy pathdiff-contract.go
File metadata and controls
252 lines (217 loc) · 6.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
* Flow CLI
*
* Copyright Flow Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package diffcontract
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/pmezard/go-difflib/difflib"
"github.com/spf13/cobra"
flowsdk "github.com/onflow/flow-go-sdk"
"github.com/onflow/flowkit/v2"
"github.com/onflow/flowkit/v2/output"
"github.com/onflow/flowkit/v2/project"
"github.com/onflow/flow-cli/internal/command"
"github.com/onflow/flow-cli/internal/util"
)
type diffContractFlags struct {
Quiet bool `default:"false" flag:"quiet,q" info:"Exit with non-zero code if contracts differ, without output"`
}
var diffFlags = diffContractFlags{}
var DiffContractCommand = &command.Command{
Cmd: &cobra.Command{
Use: "diff-contract <file-or-url> [address]",
Short: "Diff a local contract against a deployed one",
Example: "flow diff-contract ./MyContract.cdc\nflow diff-contract ./MyContract.cdc 0xf8d6e0586b0a20c7\nflow diff-contract https://example.com/MyContract.cdc my-account --network testnet",
Args: cobra.RangeArgs(1, 2),
GroupID: "tools",
},
Flags: &diffFlags,
RunS: diffContract,
}
func diffContract(
args []string,
globalFlags command.GlobalFlags,
logger output.Logger,
flow flowkit.Services,
state *flowkit.State,
) (command.Result, error) {
source := args[0]
// Read source code from file or URL
var code []byte
var err error
if strings.HasPrefix(source, "http://") || strings.HasPrefix(source, "https://") {
code, err = fetchURL(source)
if err != nil {
return nil, fmt.Errorf("error fetching contract from URL: %w", err)
}
} else {
code, err = state.ReadFile(source)
if err != nil {
return nil, fmt.Errorf("error loading contract file: %w", err)
}
}
// Extract contract name from source
program, err := project.NewProgram(code, nil, source)
if err != nil {
return nil, fmt.Errorf("error parsing contract source: %w", err)
}
contractName, err := program.Name()
if err != nil {
return nil, fmt.Errorf("error extracting contract name: %w", err)
}
// Resolve imports in source code
ctx := context.Background()
resolved, err := flow.ReplaceImportsInScript(ctx, flowkit.Script{
Code: code,
Location: source,
})
if err != nil {
return nil, fmt.Errorf("error resolving imports: %w", err)
}
// Resolve target address: from argument or from flow.json deployments
var address flowsdk.Address
if len(args) >= 2 {
address, err = util.ResolveAddressOrAccountNameForNetworks(args[1], state, []string{globalFlags.Network})
if err != nil {
return nil, err
}
} else {
address, err = resolveAddressFromConfig(state, contractName, globalFlags.Network)
if err != nil {
return nil, err
}
}
// Fetch deployed contract
logger.StartProgress(fmt.Sprintf("Fetching contract '%s' from %s...", contractName, address.HexWithPrefix()))
defer logger.StopProgress()
account, err := flow.GetAccount(ctx, address)
if err != nil {
return nil, fmt.Errorf("error fetching account: %w", err)
}
deployedCode, ok := account.Contracts[contractName]
if !ok {
return nil, fmt.Errorf("contract '%s' not found on account %s", contractName, address.HexWithPrefix())
}
// Normalize and diff
localCode := util.NormalizeLineEndings(string(resolved.Code))
remoteCode := util.NormalizeLineEndings(string(deployedCode))
identical := localCode == remoteCode
diffText := ""
if !identical {
diff := difflib.UnifiedDiff{
A: difflib.SplitLines(remoteCode),
B: difflib.SplitLines(localCode),
FromFile: fmt.Sprintf("%s/%s (deployed)", address.HexWithPrefix(), contractName),
ToFile: source,
Context: 3,
}
diffText, err = difflib.GetUnifiedDiffString(diff)
if err != nil {
return nil, fmt.Errorf("error computing diff: %w", err)
}
}
return &diffContractResult{
diff: diffText,
contractName: contractName,
address: address.HexWithPrefix(),
identical: identical,
quiet: diffFlags.Quiet,
}, nil
}
// resolveAddressFromConfig looks up the address for a contract in flow.json
// by checking deployments first, then contract aliases for the given network.
func resolveAddressFromConfig(state *flowkit.State, contractName string, network string) (flowsdk.Address, error) {
// Check deployments
deployments := state.Deployments().ByNetwork(network)
for _, deployment := range deployments {
for _, contract := range deployment.Contracts {
if contract.Name == contractName {
account, err := state.Accounts().ByName(deployment.Account)
if err != nil {
return flowsdk.EmptyAddress, fmt.Errorf("account '%s' from deployment not found in configuration: %w", deployment.Account, err)
}
return account.Address, nil
}
}
}
// Check contract aliases
contract, err := state.Contracts().ByName(contractName)
if err == nil && contract != nil {
if alias := contract.Aliases.ByNetwork(network); alias != nil {
return alias.Address, nil
}
}
return flowsdk.EmptyAddress, fmt.Errorf("contract '%s' not found in deployments or aliases for network '%s' in flow.json, specify an address explicitly", contractName, network)
}
func fetchURL(url string) ([]byte, error) {
client := http.Client{Timeout: 30 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status)
}
return io.ReadAll(resp.Body)
}
// diffContractResult implements command.ResultWithExitCode
type diffContractResult struct {
diff string
contractName string
address string
identical bool
quiet bool
}
var _ command.ResultWithExitCode = &diffContractResult{}
func (r *diffContractResult) String() string {
if r.quiet {
return ""
}
if r.identical {
return fmt.Sprintf("Contract '%s' on %s is up to date", r.contractName, r.address)
}
return r.diff
}
func (r *diffContractResult) Oneliner() string {
if r.identical {
return "identical"
}
return "different"
}
func (r *diffContractResult) JSON() any {
result := map[string]any{
"contract": r.contractName,
"address": r.address,
"identical": r.identical,
}
if !r.identical {
result["diff"] = r.diff
}
return result
}
func (r *diffContractResult) ExitCode() int {
if r.identical {
return 0
}
return 1
}