extractConstructorParams function

JSONString extractConstructorParams(
  1. String codePath, [
  2. String? constructorName
])

Extracts the source code of the parameter list from a constructor in the given Dart file.

If constructorName is provided, it will look for a constructor with that name. Otherwise, it will return the parameters of the first constructor found. An empty string for constructorName targets the unnamed constructor.

Implementation

JSONString extractConstructorParams(String codePath, [String? constructorName]) {
  final file = File(codePath);
  if (!file.existsSync()) {
    return '';
  }

  final content = file.readAsStringSync();
  final result = parseString(
    content: content,
    featureSet: FeatureSet.latestLanguageVersion(),
    throwIfDiagnostics: false,
  );

  if (constructorName == null || constructorName.isEmpty) {
    printWarning(
        "constructorName arg (--name) is not passed, get first constructor name from extractContructorListFromClass...");
    final firstContructorName = extractConstructorListFromClass(codePath).first;
    if (firstContructorName.isNotEmpty) {
      constructorName = firstContructorName
          .split(".")
          .last;
    }
    printSuccess("Got $firstContructorName ...done");
  } else if (constructorName.contains(".")) {
    constructorName = constructorName
        .split(".")
        .last;
  }

  final unit = result.unit;
  final visitor = _ConstructorVisitor(constructorName: constructorName);
  unit.accept(visitor);

  final value = visitor.constructorParameters ?? '';
  final className = getClassName(codePath);

  return toJSONStringResult(
      {
      "className": className,
      "constructorName": constructorName,
      "constructorParams": value
      }
  );
}