appendClassContent method

bool appendClassContent(
  1. String className,
  2. String value
)

Append the content of dart class

var newClassContent = '''abstract class Routes {
 Routes._();

}
abstract class _Paths {
 _Paths._();
}'''.appendClassContent('Routes', 'static const HOME = _Paths.HOME;' );
print(newClassContent);

abstract class Routes { Routes._(); static const HOME = _Paths.HOME; } abstract class _Paths { Paths.(); }

Implementation

bool appendClassContent(String className, String value) {
  var content = dartCode;
  var matches = RegExp(
    r'class\s+' + RegExp.escape(className) + r'\s*{(.*?)}',
    dotAll: true,
    multiLine: true,
  ).allMatches(content);
  if (matches.isEmpty) {
    throw CliException('The class $className is not found in the file $path');
  } else if (matches.length > 1) {
    throw CliException(
      'The class $className is found more than once in the file $path',
    );
  }
  var match = matches.first;

  // 检查是否已包含该 value
  final classBody = match.group(1) ?? '';
  if (classBody.contains(value)) {
    return false; // 已包含,不添加
  }

  content = content.insert(match.end - 1, value);
  writeFile(
    path,
    content,
    overwrite: true,
    logger: false,
    useRelativeImport: true,
  );
  return true;
}