addDevDependencyToPubspec static method
void
addDevDependencyToPubspec({})
Add a dev dependency to pubspec.yaml under the dev_dependencies map.
If the dev dependency already exists its version is updated in place.
Creates the dev_dependencies section if it does not exist.
@param pubspecPath Absolute or relative path to pubspec.yaml.
@param name Package name as published on pub.dev.
@param version Version constraint, e.g. ^1.0.0.
Implementation
static void addDevDependencyToPubspec({
required String pubspecPath,
required String name,
required String version,
}) {
final content = FileHelper.readFile(pubspecPath);
final editor = YamlEditor(content);
// 1. Ensure `dev_dependencies` exists. `parseAt` throws when the key path
// is missing, so catch and create a fresh map in either no-value or
// no-key case.
try {
if (editor.parseAt(['dev_dependencies']).value == null) {
editor.update(['dev_dependencies'], {});
}
} catch (_) {
editor.update(['dev_dependencies'], {});
}
// 2. Upsert the dev dependency.
editor.update(['dev_dependencies', name], version);
FileHelper.writeFile(pubspecPath, editor.toString());
}