Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple pre commit git hook for updating a dart/flutter program version number and generating a constant for the application at runtime.
#!/bin/sh
npm run version-sync
git add pubspec.yaml
git add lib/src/version.dart
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
function getPubspecVersion(path, key) {
const file = fs.readFileSync(path, 'utf8');
const data = yaml.load(file);
return data[key];
}
function setPubspecVersion(path, key, version) {
const file = fs.readFileSync(path, 'utf8');
const data = yaml.load(file);
data[key] = version;
const yamlString = yaml.dump(data);
fs.writeFileSync(path, yamlString);
}
function updateGeneratedVersion(path, version) {
const contents = [`// Generated code. Do not modify.`, `const packageVersion = '${version}';`];
fs.writeFileSync(path, contents.join('\n'));
}
const version = getPubspecVersion(path.join(__dirname, '../pubspec.yaml'), 'version');
console.log(`Version: ${version}`);
const parts = version.split('+');
const versionName = parts[0];
const versionBuild = parseInt(parts[1]) || 0;
const newVersion = `${versionName}+${versionBuild + 1}`;
updateGeneratedVersion(path.join(__dirname, '../lib/src/version.dart'), newVersion);
setPubspecVersion(path.join(__dirname, '../pubspec.yaml'), 'version', newVersion);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment