Last active
December 3, 2022 00:24
-
-
Save jtmuller5/626c0c308f4d1c47f6ec649de8415e2d to your computer and use it in GitHub Desktop.
Dart function to increment the version and build numbers of flutter apps. Built by Joe Muller and chat GPT.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:developer'; | |
import 'dart:io'; | |
import 'package:yaml/yaml.dart'; | |
import 'package:yaml_writer/yaml_writer.dart'; | |
/// Run by calling dart increment_version.dart major/minor/patch | |
void main(List<String> args) { | |
// Use the provided argument to determine the version type to increment, | |
// or default to minor if no argument is provided | |
var versionType = args.isEmpty ? 'minor' : args[0]; | |
var yamlWriter = YAMLWriter(addQuotes: false); | |
// Read the pubspec.yaml file | |
var pubspec = File('pubspec.yaml').readAsStringSync(); | |
// Parse the pubspec.yaml file into a Map | |
var pubspecMap = loadYaml(pubspec); | |
var data = {}; | |
data.addAll(pubspecMap); | |
// Extract the current version number | |
var currentVersion = pubspecMap['version']; | |
var versionCode = currentVersion.split('+')[0]; | |
var buildNumber = currentVersion.split('+')[1]; | |
var newVersion = versionCode.split('.'); | |
if (versionType == 'major') { | |
newVersion[0] = (int.parse(versionCode[0]) + 1).toString(); | |
newVersion[1] = '0'; | |
newVersion[2] = '0'; | |
} else if (versionType == 'minor') { | |
newVersion[1] = (int.parse(newVersion[1]) + 1).toString(); | |
newVersion[2] = '0'; | |
} else if (versionType == 'patch') { | |
newVersion[2] = (int.parse(newVersion[2]) + 1).toString(); | |
} else { | |
log('Invalid version type "$versionType". Please specify either "major", "minor", or "patch".'); | |
return; | |
} | |
// Update the pubspec.yaml file with the new version number | |
data['version'] = '${newVersion.join('.')}+${(int.parse(buildNumber) + 1)}'; | |
// Use the write method of the YAMLWriter object to convert the Map to a YAML string | |
var yamlString = yamlWriter.write(data); | |
File('pubspec.yaml').writeAsStringSync(yamlString); | |
} | |
String getBuildNumber(String version) { | |
var versionParts = version.split('.'); | |
if (versionParts.length > 3) { | |
var buildNumber = versionParts[3]; | |
if (buildNumber.startsWith('+')) { | |
return buildNumber.substring(1); | |
} | |
} | |
return ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment