@graphprotocol/graph-cli 0.26.0 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/chain/ethereum.ts +1 -1
  2. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/chain/tendermint.ts +554 -0
  3. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/common/collections.ts +52 -2
  4. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/common/numbers.ts +11 -0
  5. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/common/value.ts +47 -0
  6. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/global/global.ts +150 -1
  7. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/index.ts +2 -0
  8. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/package.json +2 -1
  9. package/examples/basic-event-handlers/node_modules/@graphprotocol/graph-ts/test/test.js +2 -0
  10. package/examples/basic-event-handlers/node_modules/keccak/build/Makefile +1 -1
  11. package/examples/basic-event-handlers/node_modules/keccak/build/Release/.deps/Release/obj.target/keccak/src/addon.o.d.raw +16 -16
  12. package/examples/basic-event-handlers/node_modules/keccak/build/config.gypi +4 -4
  13. package/examples/basic-event-handlers/node_modules/keccak/build/keccak.target.mk +14 -14
  14. package/examples/basic-event-handlers/node_modules/websocket/build/Makefile +1 -1
  15. package/examples/basic-event-handlers/node_modules/websocket/build/Release/.deps/Release/obj.target/bufferutil/src/bufferutil.o.d.raw +16 -16
  16. package/examples/basic-event-handlers/node_modules/websocket/build/bufferutil.target.mk +14 -14
  17. package/examples/basic-event-handlers/node_modules/websocket/build/config.gypi +1 -1
  18. package/examples/basic-event-handlers/node_modules/websocket/build/validation.target.mk +14 -14
  19. package/examples/basic-event-handlers/package.json +4 -4
  20. package/examples/basic-event-handlers/yarn.lock +8 -8
  21. package/package.json +27 -24
  22. package/src/codegen/schema.js +5 -46
  23. package/src/codegen/schema.test.js +0 -6
  24. package/src/codegen/types/conversions.js +19 -19
  25. package/src/codegen/types/index.js +0 -25
  26. package/src/codegen/types/index.test.js +0 -22
  27. package/src/commands/deploy.js +3 -1
  28. package/src/commands/init.js +2 -0
  29. package/src/commands/test.js +82 -59
  30. package/src/protocols/ethereum/codegen/abi.js +72 -2
  31. package/src/protocols/ethereum/manifest.graphql +92 -0
  32. package/src/protocols/index.js +17 -7
  33. package/src/protocols/near/manifest.graphql +57 -0
  34. package/src/subgraph.js +18 -13
  35. package/src/validation/manifest.js +12 -8
  36. package/tests/cli/validation/example-values-found.stderr +2 -2
  37. package/tests/cli/validation/invalid-manifest/subgraph.yaml +2 -1
  38. package/tests/cli/validation/invalid-manifest-cannot-infer-protocol/subgraph.yaml +12 -0
  39. package/tests/cli/validation/invalid-manifest-cannot-infer-protocol.stderr +5 -0
  40. package/tests/cli/validation/invalid-manifest.stderr +0 -3
  41. package/tests/cli/validation.test.js +8 -0
  42. package/manifest-schema.graphql +0 -122
package/package.json CHANGED
@@ -1,41 +1,44 @@
1
1
  {
2
2
  "name": "@graphprotocol/graph-cli",
3
- "version": "0.26.0",
3
+ "version": "0.27.1",
4
+ "license": "(Apache-2.0 OR MIT)",
4
5
  "description": "CLI for building for and deploying to The Graph",
5
6
  "dependencies": {
6
7
  "assemblyscript": "0.19.10",
7
8
  "binary-install-raw": "0.0.13",
8
- "chalk": "^3.0.0",
9
- "chokidar": "^3.0.2",
10
- "debug": "^4.1.1",
11
- "docker-compose": "^0.23.2",
12
- "dockerode": "^2.5.8",
13
- "fs-extra": "^9.0.0",
14
- "glob": "^7.1.2",
9
+ "chalk": "3.0.0",
10
+ "chokidar": "3.5.1",
11
+ "debug": "4.1.1",
12
+ "docker-compose": "0.23.4",
13
+ "dockerode": "2.5.8",
14
+ "fs-extra": "9.0.0",
15
+ "glob": "7.1.6",
15
16
  "gluegun": "https://github.com/edgeandnode/gluegun#v4.3.1-pin-colors-dep",
16
- "graphql": "^15.5.0",
17
- "immutable": "^3.8.2",
18
- "ipfs-http-client": "^34.0.0",
19
- "jayson": "^3.0.2",
20
- "js-yaml": "^3.13.1",
21
- "node-fetch": "^2.3.0",
22
- "pkginfo": "^0.4.1",
23
- "prettier": "^1.13.5",
24
- "request": "^2.88.0",
17
+ "graphql": "15.5.0",
18
+ "immutable": "3.8.2",
19
+ "ipfs-http-client": "34.0.0",
20
+ "jayson": "3.2.0",
21
+ "js-yaml": "3.13.1",
22
+ "node-fetch": "2.6.0",
23
+ "pkginfo": "0.4.1",
24
+ "prettier": "1.19.1",
25
+ "request": "2.88.2",
25
26
  "semver": "7.3.5",
26
- "tmp-promise": "^3.0.2",
27
+ "sync-request": "6.1.0",
28
+ "tmp-promise": "3.0.2",
29
+ "web3-eth-abi": "1.7.0",
27
30
  "which": "2.0.2",
28
- "yaml": "^1.5.1"
31
+ "yaml": "1.9.2"
29
32
  },
30
33
  "bin": {
31
34
  "graph": "bin/graph"
32
35
  },
33
36
  "devDependencies": {
34
- "eslint": "^6.0.1",
35
- "jest": "^26.0.0",
36
- "spawn-command": "^0.0.2-1",
37
- "strip-ansi": "^6.0.0",
38
- "tern": "^0.24.0"
37
+ "eslint": "6.8.0",
38
+ "jest": "26.0.0",
39
+ "spawn-command": "0.0.2-1",
40
+ "strip-ansi": "6.0.0",
41
+ "tern": "0.24.3"
39
42
  },
40
43
  "scripts": {
41
44
  "test": "jest --verbose",
@@ -54,7 +54,7 @@ module.exports = class SchemaCodeGenerator {
54
54
  let klass = tsCodegen.klass(name, { export: true, extends: 'Entity' })
55
55
 
56
56
  // Generate and add a constructor
57
- klass.addMethod(this._generateConstructor(name, def.get('fields')))
57
+ klass.addMethod(this._generateConstructor(name))
58
58
 
59
59
  // Generate and add save() and getById() methods
60
60
  this._generateStoreMethods(name).forEach(method => klass.addMethod(method))
@@ -71,42 +71,7 @@ module.exports = class SchemaCodeGenerator {
71
71
  return klass
72
72
  }
73
73
 
74
- // Fields that are non-nullable get an empty/zero value set in the class constructor.
75
- _generateDefaultFieldValues(fields) {
76
- const indexOfIdField = fields.findIndex(field => field.getIn(['name', 'value']) === 'id')
77
- const fieldsWithoutId = fields.remove(indexOfIdField)
78
-
79
- const fieldsSetCalls = fieldsWithoutId
80
- .map(field => {
81
- const name = field.getIn(['name', 'value'])
82
- const type = this._typeFromGraphQl(field.get('type'), true, true)
83
-
84
- const isNullable = type instanceof tsCodegen.NullableType
85
-
86
- const directives = field.get('directives')
87
- const isDerivedFrom = directives.some(directive => directive.getIn(['name', 'value']) === 'derivedFrom')
88
-
89
- return { name, type, isNullable, isDerivedFrom }
90
- })
91
- // We only call the setter with the default value in the constructor for fields that are:
92
- // - Not nullable, so that AS doesn't break when subgraph developers try to access them before a `set`
93
- // - It doesn't matter if it's primitive or not
94
- // - Not tagged as `derivedFrom`, because they only exist in query time
95
- .filter(({
96
- isNullable,
97
- isDerivedFrom,
98
- }) => !isNullable && !isDerivedFrom)
99
- .map(({ name, type, isNullable }) => {
100
- const fieldTypeString = isNullable ? type.inner.toString() : type.toString()
101
-
102
- return `
103
- this.set('${name}', ${typesCodegen.initializedValueFromAsc(fieldTypeString)})`
104
- })
105
-
106
- return fieldsSetCalls.join('')
107
- }
108
-
109
- _generateConstructor(entityName, fields) {
74
+ _generateConstructor(entityName) {
110
75
  return tsCodegen.method(
111
76
  'constructor',
112
77
  [tsCodegen.param('id', tsCodegen.namedType('string'))],
@@ -114,7 +79,6 @@ module.exports = class SchemaCodeGenerator {
114
79
  `
115
80
  super()
116
81
  this.set('id', Value.fromString(id))
117
- ${this._generateDefaultFieldValues(fields)}
118
82
  `,
119
83
  )
120
84
  }
@@ -234,7 +198,7 @@ Suggestion: add an '!' to the member type of the List, change from '${fieldValue
234
198
  : gqlType.getIn(['name', 'value'])
235
199
  }
236
200
 
237
- _typeFromGraphQl(gqlType, nullable = true, nullablePrimitive = false) {
201
+ _typeFromGraphQl(gqlType, nullable = true) {
238
202
  if (gqlType.get('kind') === 'NonNullType') {
239
203
  return this._typeFromGraphQl(gqlType.get('type'), false)
240
204
  } else if (gqlType.get('kind') === 'ListType') {
@@ -245,13 +209,8 @@ Suggestion: add an '!' to the member type of the List, change from '${fieldValue
245
209
  let type = tsCodegen.namedType(
246
210
  typesCodegen.ascTypeForValue(gqlType.getIn(['name', 'value'])),
247
211
  )
248
-
249
- // Will not wrap primitives into NullableType by default.
250
- if (!nullablePrimitive && type.isPrimitive()) {
251
- return type
252
- }
253
-
254
- return nullable ? tsCodegen.nullableType(type) : type
212
+ // In AssemblyScript, primitives cannot be nullable.
213
+ return nullable && !type.isPrimitive() ? tsCodegen.nullableType(type) : type
255
214
  }
256
215
  }
257
216
  }
@@ -114,9 +114,6 @@ describe('Schema code generator', () => {
114
114
  body: `
115
115
  super()
116
116
  this.set('id', Value.fromString(id))
117
-
118
- this.set('name', Value.fromString(''))
119
- this.set('count', Value.fromI32(0))
120
117
  `,
121
118
  },
122
119
  {
@@ -279,9 +276,6 @@ describe('Schema code generator', () => {
279
276
  body: `
280
277
  super()
281
278
  this.set('id', Value.fromString(id))
282
-
283
- this.set('amount', Value.fromBigInt(BigInt.zero()))
284
- this.set('account', Value.fromString(''))
285
279
  `,
286
280
  },
287
281
  {
@@ -188,28 +188,28 @@ const VALUE_TO_ASSEMBLYSCRIPT = [
188
188
  const ASSEMBLYSCRIPT_TO_VALUE = [
189
189
  // Arrays
190
190
 
191
- ['Array<Address>', '[Bytes]', code => `Value.fromBytesArray(${code})`, 'new Array(0)'],
192
- ['Array<Bytes>', '[Bytes]', code => `Value.fromBytesArray(${code})`, 'new Array(0)'],
193
- ['Array<boolean>', '[Boolean]', code => `Value.fromBooleanArray(${code})`, 'new Array(0)'],
194
- ['Array<i32>', '[Int]', code => `Value.fromI32Array(${code})`, 'new Array(0)'],
195
- ['Array<BigInt>', '[BigInt]', code => `Value.fromBigIntArray(${code})`, 'new Array(0)'],
196
- ['Array<string>', '[String]', code => `Value.fromStringArray(${code})`, 'new Array(0)'],
197
- ['Array<string>', '[ID]', code => `Value.fromStringArray(${code})`, 'new Array(0)'],
198
- ['Array<BigDecimal>', '[BigDecimal]', code => `Value.fromBigDecimalArray(${code})`, 'new Array(0)'],
199
- ['Array<string>', /\[.*\]/, code => `Value.fromStringArray(${code})`, 'new Array(0)'],
200
- ['Array<string | null>', null, code => `Value.fromStringArray(${code})`, 'new Array(0)'],
191
+ ['Array<Address>', '[Bytes]', code => `Value.fromBytesArray(${code})`],
192
+ ['Array<Bytes>', '[Bytes]', code => `Value.fromBytesArray(${code})`],
193
+ ['Array<boolean>', '[Boolean]', code => `Value.fromBooleanArray(${code})`],
194
+ ['Array<i32>', '[Int]', code => `Value.fromI32Array(${code})`],
195
+ ['Array<BigInt>', '[BigInt]', code => `Value.fromBigIntArray(${code})`],
196
+ ['Array<string>', '[String]', code => `Value.fromStringArray(${code})`],
197
+ ['Array<string>', '[ID]', code => `Value.fromStringArray(${code})`],
198
+ ['Array<BigDecimal>', '[BigDecimal]', code => `Value.fromBigDecimalArray(${code})`],
199
+ ['Array<string>', /\[.*\]/, code => `Value.fromStringArray(${code})`],
200
+ ['Array<string | null>', null, code => `Value.fromStringArray(${code})`],
201
201
 
202
202
  // Scalar values
203
203
 
204
- ['Address', 'Bytes', code => `Value.fromBytes(${code})`, 'Address.zero()'],
205
- ['Bytes', 'Bytes', code => `Value.fromBytes(${code})`, 'Bytes.empty()'],
206
- ['boolean', 'Boolean', code => `Value.fromBoolean(${code})`, 'false'],
207
- ['i32', 'Int', code => `Value.fromI32(${code})`, '0'],
208
- ['BigInt', 'BigInt', code => `Value.fromBigInt(${code})`, 'BigInt.zero()'],
209
- ['string', 'String', code => `Value.fromString(${code})`, "''"],
210
- ['string', 'ID', code => `Value.fromString(${code})`, "''"],
211
- ['BigDecimal', 'BigDecimal', code => `Value.fromBigDecimal(${code})`, 'BigDecimal.zero()'],
212
- ['string', /.*/, code => `Value.fromString(${code})`, "''"],
204
+ ['Address', 'Bytes', code => `Value.fromBytes(${code})`],
205
+ ['Bytes', 'Bytes', code => `Value.fromBytes(${code})`],
206
+ ['boolean', 'Boolean', code => `Value.fromBoolean(${code})`],
207
+ ['i32', 'Int', code => `Value.fromI32(${code})`],
208
+ ['BigInt', 'BigInt', code => `Value.fromBigInt(${code})`],
209
+ ['string', 'String', code => `Value.fromString(${code})`],
210
+ ['string', 'ID', code => `Value.fromString(${code})`],
211
+ ['BigDecimal', 'BigDecimal', code => `Value.fromBigDecimal(${code})`],
212
+ ['string', /.*/, code => `Value.fromString(${code})`],
213
213
  ]
214
214
 
215
215
  /**
@@ -66,27 +66,6 @@ const findConversionToType = (fromTypeSystem, toTypeSystem, toType) => {
66
66
  return objectifyConversion(fromTypeSystem, toTypeSystem, conversion)
67
67
  }
68
68
 
69
- const findInitializationForType = (fromTypeSystem, toTypeSystem, ascType) => {
70
- const conversions = conversionsForTypeSystems(fromTypeSystem, toTypeSystem)
71
-
72
- const conversion = conversions.find(conversion =>
73
- typeof conversion.get(0) === 'string'
74
- ? conversion.get(0) === ascType
75
- : ascType.match(conversion.get(0)),
76
- )
77
-
78
- if (conversion === undefined) {
79
- throw new Error(
80
- `Conversion from '${fromTypeSystem}' to '${toTypeSystem}' for ` +
81
- `target type '${ascType}' is not supported`,
82
- )
83
- }
84
-
85
- const conversionObj = objectifyConversion(fromTypeSystem, toTypeSystem, conversion)
86
-
87
- return conversionObj.get('convert')(conversion.get(3))
88
- }
89
-
90
69
  // High-level type system API
91
70
 
92
71
  const ascTypeForProtocol = (protocol, protocolType) =>
@@ -120,9 +99,6 @@ const valueToAsc = (code, valueType) =>
120
99
  const valueFromAsc = (code, valueType) =>
121
100
  findConversionToType('AssemblyScript', 'Value', valueType).get('convert')(code)
122
101
 
123
- const initializedValueFromAsc = ascType =>
124
- findInitializationForType('AssemblyScript', 'Value', ascType)
125
-
126
102
  module.exports = {
127
103
  // protocol <-> AssemblyScript
128
104
  ascTypeForProtocol,
@@ -138,5 +114,4 @@ module.exports = {
138
114
  valueTypeForAsc,
139
115
  valueToAsc,
140
116
  valueFromAsc,
141
- initializedValueFromAsc,
142
117
  }
@@ -449,26 +449,4 @@ describe('AssemblyScript -> Value', () => {
449
449
  expect(codegen.valueFromAsc('x', '[String]')).toBe('Value.fromStringArray(x)')
450
450
  expect(codegen.valueTypeForAsc('Array<string>')).toBe('[String]')
451
451
  })
452
-
453
- describe('Initialization for zero/empty values', () => {
454
- test('Array<string>', () => {
455
- expect(codegen.initializedValueFromAsc('Array<string>')).toBe('Value.fromStringArray(new Array(0))')
456
- })
457
-
458
- test('Array<string | null>', () => {
459
- expect(codegen.initializedValueFromAsc('Array<string | null>')).toBe('Value.fromStringArray(new Array(0))')
460
- })
461
-
462
- test('i32', () => {
463
- expect(codegen.initializedValueFromAsc('i32')).toBe('Value.fromI32(0)')
464
- })
465
-
466
- test('string', () => {
467
- expect(codegen.initializedValueFromAsc('string')).toBe("Value.fromString('')")
468
- })
469
-
470
- test('BigInt', () => {
471
- expect(codegen.initializedValueFromAsc('BigInt')).toBe('Value.fromBigInt(BigInt.zero())')
472
- })
473
- })
474
452
  })
@@ -30,6 +30,7 @@ Options:
30
30
  -l --version-label <label> Version label used for the deployment
31
31
  -h, --help Show usage information
32
32
  -i, --ipfs <node> Upload build results to an IPFS node (default: ${DEFAULT_IPFS_URL})
33
+ --debug-fork ID of a remote subgraph whose store will be GraphQL queried
33
34
  -o, --output-dir <path> Output directory for build results (default: build/)
34
35
  --skip-migrations Skip subgraph migrations (default: false)
35
36
  -w, --watch Regenerate types when subgraph files change (default: false)
@@ -96,6 +97,7 @@ module.exports = {
96
97
  skipMigrations,
97
98
  w,
98
99
  watch,
100
+ debugFork,
99
101
  } = toolbox.parameters.options
100
102
 
101
103
  // Support both long and short option variants
@@ -264,7 +266,7 @@ module.exports = {
264
266
  // `Failed to deploy to Graph node ${requestUrl}`,
265
267
  client.request(
266
268
  'subgraph_deploy',
267
- { name: subgraphName, ipfs_hash: ipfsHash, version_label: versionLabel },
269
+ { name: subgraphName, ipfs_hash: ipfsHash, version_label: versionLabel, debug_fork: debugFork },
268
270
  async (requestError, jsonRpcError, res) => {
269
271
  if (jsonRpcError) {
270
272
  spinner.fail(
@@ -283,6 +283,8 @@ const getEtherscanLikeAPIUrl = (network) => {
283
283
  case "bsc": return `https://api.bscscan.com/api`;
284
284
  case "matic": return `https://api.polygonscan.com/api`;
285
285
  case "mumbai": return `https://api-testnet.polygonscan.com/api`;
286
+ case "aurora": return `https://api.aurorascan.dev/api`;
287
+ case "aurora-testnet": return `https://api-testnet.aurorascan.dev/api`;
286
288
  default: return `https://api-${network}.etherscan.io/api`;
287
289
  }
288
290
  }
@@ -2,8 +2,9 @@ const { Binary } = require('binary-install-raw')
2
2
  const os = require('os')
3
3
  const chalk = require('chalk')
4
4
  const fetch = require('node-fetch')
5
- const { filesystem, print } = require('gluegun')
5
+ const { filesystem, patching, print, system } = require('gluegun')
6
6
  const { fixParameters } = require('../command-helpers/gluegun')
7
+ const path = require('path')
7
8
  const semver = require('semver')
8
9
  const { spawn, exec } = require('child_process')
9
10
  const yaml = require('js-yaml')
@@ -102,7 +103,7 @@ async function runBinary(datasource, opts) {
102
103
  let latestVersion = opts.get("latestVersion")
103
104
  let recompileOpt = opts.get("recompile")
104
105
 
105
- const platform = getPlatform(logsOpt)
106
+ const platform = await getPlatform(logsOpt)
106
107
 
107
108
  const url = `https://github.com/LimeChain/matchstick/releases/download/${versionOpt || latestVersion}/${platform}`
108
109
 
@@ -120,19 +121,21 @@ async function runBinary(datasource, opts) {
120
121
  args.length > 0 ? binary.run(...args) : binary.run()
121
122
  }
122
123
 
123
- function getPlatform(logsOpt) {
124
+ async function getPlatform(logsOpt) {
124
125
  const type = os.type()
125
126
  const arch = os.arch()
126
- const release = os.release()
127
127
  const cpuCore = os.cpus()[0]
128
- const majorVersion = semver.major(release)
129
- const isM1 = cpuCore.model.includes("Apple M1")
128
+ const isM1 = (arch === 'arm64' && /Apple (M1|processor)/.test(cpuCore.model))
129
+ const linuxInfo = type === 'Linux' ? await getLinuxInfo() : new Map()
130
+ const linuxDistro = linuxInfo.get('name')
131
+ const release = linuxInfo.get('version') || os.release()
132
+ const majorVersion = parseInt(linuxInfo.get('version'), 10) || semver.major(release)
130
133
 
131
134
  if (logsOpt) {
132
- print.info(`OS type: ${type}\nOS arch: ${arch}\nOS release: ${release}\nOS major version: ${majorVersion}\nCPU model: ${cpuCore.model}`)
135
+ print.info(`OS type: ${linuxDistro || type}\nOS arch: ${arch}\nOS release: ${release}\nOS major version: ${majorVersion}\nCPU model: ${cpuCore.model}`)
133
136
  }
134
137
 
135
- if (arch === 'x64' || (arch === 'arm64' && isM1)) {
138
+ if (arch === 'x64' || isM1) {
136
139
  if (type === 'Darwin') {
137
140
  if (majorVersion === 19) {
138
141
  return 'binary-macos-10.15'
@@ -145,8 +148,9 @@ function getPlatform(logsOpt) {
145
148
  } else if (type === 'Linux') {
146
149
  if (majorVersion === 18) {
147
150
  return 'binary-linux-18'
151
+ } else {
152
+ return 'binary-linux-20'
148
153
  }
149
- return 'binary-linux-20'
150
154
  } else if (type === 'Windows_NT') {
151
155
  return 'binary-windows'
152
156
  }
@@ -155,6 +159,23 @@ function getPlatform(logsOpt) {
155
159
  throw new Error(`Unsupported platform: ${type} ${arch} ${majorVersion}`)
156
160
  }
157
161
 
162
+ async function getLinuxInfo() {
163
+ try {
164
+ let result = await system.run("cat /etc/*-release | grep -E '(^VERSION|^NAME)='", {trim: true})
165
+ let infoArray = result.replace(/['"]+/g, '').split('\n').map(p => p.split('='))
166
+ let infoMap = new Map();
167
+
168
+ infoArray.forEach((val) => {
169
+ infoMap.set(val[0].toLowerCase(), val[1])
170
+ });
171
+
172
+ return infoMap
173
+ } catch (error) {
174
+ print.error(`Error fetching the Linux version:\n ${error}`)
175
+ process.exit(1)
176
+ }
177
+ }
178
+
158
179
  async function runDocker(datasource, opts) {
159
180
  let coverageOpt = opts.get("coverage")
160
181
  let forceOpt = opts.get("force")
@@ -169,27 +190,34 @@ async function runDocker(datasource, opts) {
169
190
  // Get current working directory
170
191
  let current_folder = await filesystem.cwd()
171
192
 
172
- // Build the Dockerfile location. Defaults to ./tests/.docker if
173
- // a custom testsFolder is not declared in the subgraph.yaml
174
- let dockerDir = ""
193
+ // Declate dockerfilePath with default location
194
+ let dockerfilePath = "./tests/.docker/Dockerfile"
175
195
 
176
- try {
177
- let doc = await yaml.load(filesystem.read('subgraph.yaml', 'utf8'))
178
- testsFolder = doc.testsFolder || './tests'
179
- dockerDir = testsFolder.endsWith('/') ? testsFolder + '.docker' : testsFolder + '/.docker'
180
- } catch (error) {
181
- print.error(error.message)
182
- return
196
+ // Check if matchstick.yaml config exists
197
+ if(filesystem.exists('matchstick.yaml')) {
198
+ try {
199
+ // Load the config
200
+ let config = await yaml.load(filesystem.read('matchstick.yaml', 'utf8'))
201
+
202
+ // Check if matchstick.yaml is not empty
203
+ if(config != null) {
204
+ // If a custom tests folder is declared update dockerfilePath
205
+ dockerfilePath = path.join(config.testsFolder || 'tests', '.docker/Dockerfile')
206
+ }
207
+ } catch (error) {
208
+ print.info('A problem occurred while reading matchstick.yaml. Please attend to the errors below:')
209
+ print.error(error.message)
210
+ process.exit(1)
211
+ }
183
212
  }
184
213
 
185
- // Create the Dockerfile
186
- try {
187
- await filesystem.write(`${dockerDir}/Dockerfile`, dockerfile(versionOpt, latestVersion))
188
- print.info('Successfully generated Dockerfile.')
189
- } catch (error) {
190
- print.info('A problem occurred while generating the Dockerfile. Please attend to the errors below:')
191
- print.error(error.message)
192
- return
214
+ // Check if the Dockerfil already exists
215
+ let dockerfileExists = filesystem.exists(dockerfilePath)
216
+
217
+ // Generate the Dockerfile only if it doesn't exists,
218
+ // version flag and/or force flag is passed.
219
+ if(!dockerfileExists || versionOpt || forceOpt) {
220
+ await dockerfile(dockerfilePath, versionOpt, latestVersion)
193
221
  }
194
222
 
195
223
  // Run a command to check if matchstick image already exists
@@ -212,10 +240,10 @@ async function runDocker(datasource, opts) {
212
240
 
213
241
  // If a matchstick image does not exists, the command returns an empty string,
214
242
  // else it'll return the image ID. Skip `docker build` if an image already exists
215
- // If `-v/--version` is specified, delete current image(if any) and rebuild.
243
+ // Delete current image(if any) and rebuild.
216
244
  // Use spawn() and {stdio: 'inherit'} so we can see the logs in real time.
217
- if(stdout === '' || versionOpt || forceOpt) {
218
- if ((stdout !== '' && versionOpt) || forceOpt) {
245
+ if(!dockerfileExists || stdout === '' || versionOpt || forceOpt) {
246
+ if (stdout !== '') {
219
247
  exec('docker image rm matchstick', (error, stdout, stderr) => {
220
248
  print.info(chalk.bold(`Removing matchstick image\n${stdout}`))
221
249
  })
@@ -224,7 +252,7 @@ async function runDocker(datasource, opts) {
224
252
  // run a container from that image.
225
253
  spawn(
226
254
  'docker',
227
- ['build', '--no-cache', '-f', `${dockerDir}/Dockerfile`, '-t', 'matchstick', '.'],
255
+ ['build', '-f', dockerfilePath, '-t', 'matchstick', '.'],
228
256
  { stdio: 'inherit' }
229
257
  ).on('close', code => {
230
258
  if (code === 0) {
@@ -239,37 +267,32 @@ async function runDocker(datasource, opts) {
239
267
  })
240
268
  }
241
269
 
242
- // TODO: Move these in separate file (in a function maybe)
243
- function dockerfile(versionOpt, latestVersion) {
244
- return `
245
- FROM ubuntu:20.04
246
- ENV ARGS=""
247
-
248
- # Install necessary packages
249
- RUN apt update
250
- RUN apt install -y nodejs
251
- RUN apt install -y npm
252
- RUN apt install -y git
253
- RUN apt install -y postgresql
254
- RUN apt install -y curl
255
- RUN apt install -y cmake
256
- RUN npm install -g @graphprotocol/graph-cli
270
+ // Downloads Dockerfile template from the demo-subgraph repo
271
+ // Replaces the placeholders with their respective values
272
+ async function dockerfile(dockerfilePath, versionOpt, latestVersion) {
273
+ let spinner = print.spin("Generating Dockerfile...")
257
274
 
258
- # Download the latest linux binary
259
- RUN curl -OL https://github.com/LimeChain/matchstick/releases/download/${versionOpt || latestVersion}/binary-linux-20
260
-
261
- # Make it executable
262
- RUN chmod a+x binary-linux-20
275
+ try {
276
+ // Fetch the Dockerfile template content from the demo-subgraph repo
277
+ let content = await fetch('https://raw.githubusercontent.com/LimeChain/demo-subgraph/main/Dockerfile')
278
+ .then((response) => {
279
+ if (response.ok) {
280
+ return response.text()
281
+ } else {
282
+ throw new Error(`Status Code: ${response.status}, with error: ${response.statusText}`);
283
+ }
284
+ })
263
285
 
264
- # Create a matchstick dir where the host will be copied
265
- RUN mkdir matchstick
266
- WORKDIR matchstick
286
+ // Write the Dockerfile
287
+ await filesystem.write(dockerfilePath, content)
267
288
 
268
- # Copy host to /matchstick
269
- COPY ../ .
289
+ // Replaces the version placeholders
290
+ await patching.replace(dockerfilePath, '<MATCHSTICK_VERSION>', versionOpt || latestVersion)
270
291
 
271
- RUN graph codegen
272
- RUN graph build
292
+ } catch (error) {
293
+ spinner.fail(`A problem occurred while generating the Dockerfile. Please attend to the errors below:\n ${error.message}`)
294
+ process.exit(1)
295
+ }
273
296
 
274
- CMD ../binary-linux-20 \${ARGS}`
297
+ spinner.succeed('Successfully generated Dockerfile.')
275
298
  }