Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Created November 7, 2021 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodydavis/02f77c69a9d75a620ac104633945c514 to your computer and use it in GitHub Desktop.
Save rodydavis/02f77c69a9d75a620ac104633945c514 to your computer and use it in GitHub Desktop.
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