semver#lt TypeScript Examples

The following examples show how to use semver#lt. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: definitions.ts    From solc-typed-ast with Apache License 2.0 6 votes vote down vote up
/**
 * Given an ASTNode `node` and a compiler version `version` determine if `node` is a
 * scope node. Note that `Block` is only a scope in 0.4.x
 */
function isScope(node: ASTNode, version: string): node is ScopeNode {
    if (lt(version, "0.5.0") && node instanceof Block) {
        return true;
    }

    return (
        node instanceof SourceUnit ||
        node instanceof ContractDefinition ||
        node instanceof FunctionDefinition ||
        node instanceof ModifierDefinition ||
        node instanceof VariableDeclarationStatement ||
        node instanceof TryCatchClause
    );
}
Example #2
Source File: utils.ts    From solc-typed-ast with Apache License 2.0 6 votes vote down vote up
/**
 * Given a set of compiled units and their corresponding compiler version, determine the
 * correct ABIEncoder version for these units. If mulitple incompatible explicit pragmas are found,
 * throw an error.
 */
export function getABIEncoderVersion(
    units: SourceUnit[],
    compilerVersion: string
): ABIEncoderVersion {
    const explicitEncoderVersions = new Set<ABIEncoderVersion>();

    for (const unit of units) {
        for (const nd of unit.getChildrenByType(PragmaDirective)) {
            if (
                nd.vIdentifier === "experimental" &&
                nd.literals.length === 2 &&
                ABIEncoderVersions.has(nd.literals[1])
            ) {
                explicitEncoderVersions.add(nd.literals[1] as ABIEncoderVersion);
            }

            if (nd.vIdentifier === "abicoder") {
                let version: ABIEncoderVersion;
                const rawVer = nd.literals[1];

                if (rawVer === "v1") {
                    version = ABIEncoderVersion.V1;
                } else if (rawVer === "v2") {
                    version = ABIEncoderVersion.V2;
                } else {
                    throw new Error(`Unknown abicoder pragma version ${rawVer}`);
                }

                explicitEncoderVersions.add(version);
            }
        }
    }

    assert(
        explicitEncoderVersions.size < 2,
        `Multiple encoder versions found: ${[...explicitEncoderVersions].join(", ")}`
    );

    if (explicitEncoderVersions.size === 1) {
        return [...explicitEncoderVersions][0];
    }

    return lt(compilerVersion, "0.8.0") ? ABIEncoderVersion.V1 : ABIEncoderVersion.V2;
}
Example #3
Source File: configErrors.ts    From cli with Apache License 2.0 6 votes vote down vote up
private computeMessageForString(version: string) {
    const coercedSemver = coerce(version);
    if (coercedSemver === null) {
      return `Version found in config '${version}' is not parsable to a valid semantic version.`;
    }
    if (gt(coercedSemver, CurrentSchemaVersion)) {
      return `Version found in config '${version}' is greater than the one accepted by this version of the CLI.`;
    }
    if (lt(coercedSemver, CurrentSchemaVersion)) {
      return `Version found in config '${version}' is less than the one accepted by this version of the CLI.`;
    }
    return dedent`
    Unknown config version error:
      - configVersion: ${version}
      - compatibleVersion: ${CurrentSchemaVersion}
    Please report this issue to Coveo.`;
  }
Example #4
Source File: checkUpdate.ts    From THUInfo with MIT License 5 votes vote down vote up
checkUpdate = (force: boolean = false) => {
	console.log("Current version: " + VersionNumber.appVersion);
	getUpdateInfo()
		.then((r) => r.filter((it) => gt(it.versionName, VersionNumber.appVersion)))
		.then((r) => {
			if (
				r.length &&
				(force ||
					lt(currState().config.doNotRemindSemver ?? "0.0.0", r[0].versionName))
			) {
				Alert.alert(
					getStr("newVersionAvailable"),
					r[0].versionName + "\n" + r[0].description,
					[
						{
							text: getStr("doNotRemind"),
							onPress: () =>
								store.dispatch(
									configSet("doNotRemindSemver", r[0].versionName),
								),
						},
						{text: getStr("nextTimeMust")},
						{
							text: getStr("download"),
							onPress: async () => {
								try {
									const {status} = await fetch(
										TUNA_BASE_URL + r[0].versionName,
									);
									await Linking.openURL(
										Platform.OS === "ios" || status === 404
											? r[0].url
											: TUNA_LATEST_URL,
									);
								} catch (e) {
									NetworkRetry();
								}
							},
						},
					],
					{cancelable: true},
				);
			}
			if (force && r.length === 0) {
				Snackbar.show({
					text: getStr("alreadyLatest"),
					duration: Snackbar.LENGTH_SHORT,
				});
			}
		});
}
Example #5
Source File: configErrors.spec.ts    From cli with Apache License 2.0 5 votes vote down vote up
mockedLt = jest.mocked(lt)
Example #6
Source File: MigrationPlan.ts    From elasticsearch-index-migrate with MIT License 5 votes vote down vote up
export function generateState(
    context: MigrationPlanContext,
    resolvedMigration?: ResolvedMigration,
    appliedMigration?: AppliedMigration
): MigrationStateInfo | undefined {
    if (!appliedMigration) {
        if (resolvedMigration?.version) {
            if (
                valid(resolvedMigration?.version) &&
                valid(context.baseline) &&
                lt(resolvedMigration?.version, context.baseline)
            ) {
                return MigrationStateInfo.get(MigrationStates.BELOW_BASELINE);
            }
            if (
                valid(resolvedMigration?.version) &&
                valid(context.lastApplied) &&
                lt(resolvedMigration?.version, context.lastApplied)
            ) {
                return MigrationStateInfo.get(MigrationStates.IGNORED);
            }
        }
        return MigrationStateInfo.get(MigrationStates.PENDING);
    }

    if (
        valid(appliedMigration?.version) &&
        valid(context.baseline) &&
        appliedMigration?.version === context.baseline &&
        appliedMigration?.success
    ) {
        return MigrationStateInfo.get(MigrationStates.BASELINE);
    }

    if (!resolvedMigration) {
        const version = generateVersion(resolvedMigration, appliedMigration) ?? '';
        if (
            !appliedMigration.version ||
            (valid(context.lastResolved) && valid(version) && lt(version, context.lastResolved))
        ) {
            if (appliedMigration?.success) {
                return MigrationStateInfo.get(MigrationStates.MISSING_SUCCESS);
            }
            return MigrationStateInfo.get(MigrationStates.MISSING_FAILED);
        } else {
            if (appliedMigration.success) {
                return MigrationStateInfo.get(MigrationStates.FUTURE_SUCCESS);
            }
            return MigrationStateInfo.get(MigrationStates.FUTURE_FAILED);
        }
    }

    if (!appliedMigration?.success) {
        return MigrationStateInfo.get(MigrationStates.FAILED);
    }

    return MigrationStateInfo.get(MigrationStates.SUCCESS);
}
Example #7
Source File: updater.ts    From Aragorn with MIT License 5 votes vote down vote up
protected async checkUpdateFromGithub(manul: boolean, useSystemNotification: boolean) {
    try {
      const { useBetaVersion, proxy } = this.setting.get();
      const agent = proxy ? new HttpsProxyAgent(proxy) : null;
      const res = await axios.get<{ prerelease: boolean; draft: boolean; tag_name: string; html_url: string }[]>(
        GithubReleaseApi,
        { httpsAgent: agent }
      );
      if (res.status === 200) {
        const data = res.data;
        const latest = data.find(item => item.prerelease === false && item.draft === false);
        const latestBeta = data.find(item => item.prerelease === true && item.draft === false);
        let updateInfo: ({ tag_name: string; html_url: string } & typeof latest) | null = null;
        if (useBetaVersion) {
          if (latest && lt(appVersion, latest.tag_name)) {
            updateInfo = latest;
          } else if (latestBeta && lt(appVersion, latestBeta.tag_name)) {
            updateInfo = latestBeta;
          }
        } else {
          if (latest && lt(appVersion, latest.tag_name)) {
            updateInfo = latest;
          }
        }
        if (updateInfo) {
          this.sendMessage(
            {
              message: `有新版本可供更新`,
              description: `${updateInfo.tag_name}`,
              url: updateInfo.html_url
            },
            useSystemNotification
          );
        } else {
          manul &&
            this.sendMessage(
              {
                message: '当前已是最新版本'
              },
              useSystemNotification
            );
        }
      } else {
        manul &&
          this.sendMessage(
            {
              message: `网络请求失败,请稍后重试`
            },
            useSystemNotification
          );
      }
    } catch (err) {
      console.error(`check update error: ${err.message}`);
      manul &&
        this.sendMessage(
          {
            message: `检查更新失败`,
            description: err.message
          },
          useSystemNotification
        );
    }
  }
Example #8
Source File: signatures.spec.ts    From solc-typed-ast with Apache License 2.0 4 votes vote down vote up
describe("Check canonical signatures are generated correctly", () => {
    for (const [sample, compilerVersion, encoderVer] of samples) {
        for (const kind of PossibleCompilerKinds) {
            it(`[${kind}] ${sample}`, async () => {
                const result = await compileSol(
                    sample,
                    "auto",
                    undefined,
                    undefined,
                    undefined,
                    kind as CompilerKind
                );

                expect(result.compilerVersion).toEqual(compilerVersion);

                const errors = detectCompileErrors(result.data);

                expect(errors).toHaveLength(0);

                const data = result.data;

                const reader = new ASTReader();
                const sourceUnits = reader.read(data, ASTKind.Any);
                const unit = sourceUnits[0];

                const runTestsHelper = (
                    contractName: string,
                    functionHashes: any,
                    abiData: any
                ) => {
                    for (const expectedSignature in functionHashes) {
                        const defName = expectedSignature.slice(0, expectedSignature.indexOf("("));
                        const def = resolveOne(defName, contractName, unit, compilerVersion);

                        if (def === undefined) {
                            continue;
                        }

                        let signature: string;

                        if (def instanceof VariableDeclaration) {
                            signature = def.getterCanonicalSignature(encoderVer);
                        } else if (def instanceof FunctionDefinition) {
                            signature = def.canonicalSignature(encoderVer);
                        } else {
                            throw new Error(`NYI: ${def.print()}`);
                        }

                        expect(signature).toEqual(expectedSignature);
                    }

                    /// 0.4.x doesn't report internal types in the ABI so we skip the ABI checks.
                    if (lt(compilerVersion, "0.5.0")) {
                        return;
                    }

                    for (const abiEntry of abiData) {
                        /// @todo fix the test so we can remove these
                        if (
                            abiEntry.type === "constructor" ||
                            abiEntry.type === "fallback" ||
                            abiEntry.type === "receive"
                        ) {
                            continue;
                        }

                        const def = resolveOne(abiEntry.name, contractName, unit, compilerVersion);

                        if (def === undefined) {
                            continue;
                        }

                        let funT: FunctionType;

                        if (def instanceof VariableDeclaration) {
                            funT = def.getterFunType();
                        } else if (def instanceof FunctionDefinition) {
                            funT = new FunctionType(
                                def.name,
                                def.vParameters.vParameters.map((param) =>
                                    variableDeclarationToTypeNode(param)
                                ),
                                def.vReturnParameters.vParameters.map((param) =>
                                    variableDeclarationToTypeNode(param)
                                ),
                                def.visibility,
                                def.stateMutability
                            );
                        } else if (def instanceof EventDefinition) {
                            funT = new FunctionType(
                                def.name,
                                def.vParameters.vParameters.map((param) =>
                                    variableDeclarationToTypeNode(param)
                                ),
                                [],
                                FunctionVisibility.Default,
                                FunctionStateMutability.View
                            );
                        } else if (def instanceof ErrorDefinition) {
                            funT = new FunctionType(
                                def.name,
                                def.vParameters.vParameters.map((param) =>
                                    variableDeclarationToTypeNode(param)
                                ),
                                [],
                                FunctionVisibility.Default,
                                FunctionStateMutability.View
                            );
                        } else {
                            throw new Error(`NYI: ${def.print()}`);
                        }

                        expect(funT.parameters.length).toEqual(abiEntry.inputs.length);

                        for (let i = 0; i < funT.parameters.length; i++) {
                            expect(generalizeType(funT.parameters[i])[0].pp()).toEqual(
                                abiEntry.inputs[i].internalType
                            );
                        }

                        if (abiEntry.type === "function") {
                            expect(funT.returns.length).toEqual(abiEntry.outputs.length);

                            for (let i = 0; i < funT.returns.length; i++) {
                                expect(generalizeType(funT.returns[i])[0].pp()).toEqual(
                                    abiEntry.outputs[i].internalType
                                );
                            }
                        }
                    }
                };

                for (const fileName in data.contracts) {
                    if ("functionHashes" in data.contracts[fileName]) {
                        /**
                         * Legacy compiler data structure
                         */
                        const contractName = fileName.slice(fileName.lastIndexOf(":") + 1);
                        const contractData = data.contracts[fileName];
                        const functionHashes = contractData.functionHashes;
                        const abiData = JSON.parse(contractData.interface);

                        runTestsHelper(contractName, functionHashes, abiData);
                    } else {
                        /**
                         * Modern compiler data structure
                         */
                        for (const contractName in data.contracts[fileName]) {
                            const contractData = data.contracts[fileName][contractName];
                            const functionHashes = contractData.evm.methodIdentifiers;
                            const abiData = contractData.abi;

                            runTestsHelper(contractName, functionHashes, abiData);
                        }
                    }
                }
            });
        }
    }
});