Skip to content

Commit

Permalink
Build: Display last commit hash in "*-dev" version strings
Browse files Browse the repository at this point in the history
BIT use the last commit hash in its version string if it is a "*-dev" version.

Additionally some refactoring:
 - "Config.VERSION" moved into new file "version.py" as "__version__"
 - "diagnostics.py::get_git_repository_info()" moved to "tools.py".
 - Removed "tools.py::gitRevisionAndHash()"

Some more
 - File "VERSION" no longer part of "make install" target

Close #1637
  • Loading branch information
buhtz authored Feb 13, 2024
1 parent 2349c31 commit cf02bee
Show file tree
Hide file tree
Showing 14 changed files with 148 additions and 166 deletions.
2 changes: 2 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ Back In Time

Version 1.4.4-dev (development of upcoming release)
* Feature: Support rsync '--one-file-system' in Expert Options (#1598)
* Feature: "*-dev" version strings contain last commit hash (#1637)
* Build: Git commit hash is presevered while "make install" (#1637)
* Build: Fix bash-completion symlink creation while installing & adding --diagnostics (#1615)
* Build: Activate PyLint error E602 (undefined-variable)
* Build: TravisCI use PyQt (except arch "ppc64le")
Expand Down
10 changes: 3 additions & 7 deletions common/backintime.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from diagnostics import collect_diagnostics
from exceptions import MountException
from applicationinstance import ApplicationInstance
from version import __version__

RETURN_OK = 0
RETURN_ERR = 1
Expand Down Expand Up @@ -203,7 +204,7 @@ def createParsers(app_name = 'backintime'):
parsers['main'] = parser
parser.add_argument('--version', '-v',
action = 'version',
version = '%(prog)s ' + str(config.Config.VERSION),
version = '%(prog)s ' + __version__,
help = "show %(prog)s's version number.")
parser.add_argument('--license',
action = printLicense,
Expand Down Expand Up @@ -600,14 +601,9 @@ def printHeader():
"""
Print application name, version and legal notes.
"""
version = config.Config.VERSION
# Git info is now only shown via --diagnostics
# ref, hashid = tools.gitRevisionAndHash()
# if ref:
# version += " git branch '{}' hash '{}'".format(ref, hashid)
print('')
print('Back In Time')
print('Version: ' + version)
print('Version: ' + __version__)
print('')
print('Back In Time comes with ABSOLUTELY NO WARRANTY.')
print('This is free software, and you are welcome to redistribute it')
Expand Down
4 changes: 2 additions & 2 deletions common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@
InvalidChar, \
InvalidCmd, \
LimitExceeded
import version


class Config(configfile.ConfigFileWithProfiles):
APP_NAME = 'Back In Time'
VERSION = '1.4.4-dev'
COPYRIGHT = 'Copyright (C) 2008-2024 Oprea Dan, Bart de Koning, ' \
'Richard Bailey, Germar Reitze, Christian Buhtz, Michael Büker, Jürgen Altfeld et al.'

Expand Down Expand Up @@ -209,7 +209,7 @@ def __init__(self, config_path=None, data_path=None):
"doesn't support upgrading config from version " \
"< 1.0 anymore. Please use BackInTime version " \
"<= 1.1.12 to upgrade the config to a more recent "\
"version.".format(self.VERSION))
"version.".format(version.__version__))
#TODO: add popup warning
sys.exit(2)

Expand Down
3 changes: 1 addition & 2 deletions common/configure
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ printf "\trm -f .coverage\n" >> ${MAKEFILE}
printf "\trm -rf htmlcov\n" >> ${MAKEFILE}
printf "\n" >> ${MAKEFILE}

#create install and uninstall target
# Create install and uninstall target
printf "install:\tinstall_translations\n" >> ${MAKEFILE}
addComment "python"
addUninstallDir "/share/backintime/common/__pycache__"
Expand All @@ -196,7 +196,6 @@ addInstallFile "../AUTHORS" "/share/doc/backintime-common"
addInstallFile "../LICENSE" "/share/doc/backintime-common"
addInstallFile "../README.md" "/share/doc/backintime-common"
addInstallFile "../TRANSLATIONS" "/share/doc/backintime-common"
addInstallFile "../VERSION" "/share/doc/backintime-common"
addInstallFile "../CHANGES" "/share/doc/backintime-common"
addNewline

Expand Down
52 changes: 4 additions & 48 deletions common/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
import subprocess
import json
import re
import config # config.Config.VERSION Refactor after src-layout migration
import config
import tools
import version


def collect_diagnostics():
Expand All @@ -40,7 +41,7 @@ def collect_diagnostics():

result['backintime'] = {
'name': config.Config.APP_NAME,
'version': config.Config.VERSION,
'version': version.__version__,
'latest-config-version': config.Config.CONFIG_VERSION,
'local-config-file': cfg._LOCAL_CONFIG_PATH,
'local-config-file-found': Path(cfg._LOCAL_CONFIG_PATH).exists(),
Expand All @@ -55,7 +56,7 @@ def collect_diagnostics():

# Git repo
bit_root_path = Path(tools.backintimePath(""))
git_info = get_git_repository_info(bit_root_path)
git_info = tools.get_git_repository_info(bit_root_path)

if git_info:

Expand Down Expand Up @@ -295,51 +296,6 @@ def _get_extern_versions(cmd,
return result.strip() # as string


def get_git_repository_info(path=None):
"""Return the current branch and last commit hash.
Credits: https://stackoverflow.com/a/51224861/4865723
Args:
path (Path): Path with '.git' folder in (default is
current working directory).
Returns:
(dict): Dict with keys "branch" and "hash" if it is a git repo,
otherwise an `None`.
"""

if not path:
path = Path.cwd()

git_folder = path / '.git'

if not git_folder.exists():
return None

result = {}

# branch name
with (git_folder / 'HEAD').open('r') as handle:
val = handle.read()

if val.startswith('ref: '):
result['branch'] = '/'.join(val.split('/')[2:]).strip()

else:
result['branch'] = '(detached HEAD)'
result['hash'] = val

return result

# commit hash
with (git_folder / 'refs' / 'heads' / result['branch']) \
.open('r') as handle:
result['hash'] = handle.read().strip()

return result


def _get_os_release():
"""Try to get the name and version of the operating system used.
Expand Down
3 changes: 2 additions & 1 deletion common/sshtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from mount import MountControl
from exceptions import MountException, NoPubKeyLogin, KnownHost
import bcolors
import version


class SSH(MountControl):
Expand Down Expand Up @@ -692,7 +693,7 @@ def checkPingHost(self):

logger.debug('Check ping host', self)
versionString = 'SSH-2.0-backintime_{}\r\n'.format(
self.config.VERSION).encode()
version.__version__).encode()

count = 0

Expand Down
3 changes: 2 additions & 1 deletion common/test/test_backintime.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import json

import config
import version

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

Expand Down Expand Up @@ -248,4 +249,4 @@ def test_diagnostics_arg(self):
self.assertEqual(diagnostics["backintime"]["name"],
config.Config.APP_NAME)
self.assertEqual(diagnostics["backintime"]["version"],
config.Config.VERSION)
version.__version__)
38 changes: 0 additions & 38 deletions common/test/test_diagnostics.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import sys
import pathlib
import unittest
import pyfakefs.fake_filesystem_unittest as pyfakefs_ut

# This workaround will become obsolet when migrating to src-layout
sys.path.append(str(pathlib.Path(__file__).parent))
Expand Down Expand Up @@ -89,40 +88,3 @@ def test_replace_user_path(self):
)


class Diagnostics_FakeFS(pyfakefs_ut.TestCase):
"""Tests using a fake filesystem.
"""

def setUp(self):
self.setUpPyfakefs(allow_root_user=False)

def test_git_repo_info(self):

# not a git repo
self.assertEqual(diagnostics.get_git_repository_info(), None)

# simulate a git repo
path = pathlib.Path('.git')
path.mkdir()

# Branch folders and hash containing file
foobar = path / 'refs' / 'heads' / 'fix' / 'foobar'
foobar.parent.mkdir(parents=True)

with foobar.open('w') as handle:
handle.write('01234')

# HEAD file
head = path / 'HEAD'

with head.open('w') as handle:
handle.write('ref: refs/heads/fix/foobar')

# Test
self.assertEqual(
diagnostics.get_git_repository_info(),
{
'hash': '01234',
'branch': 'fix/foobar'
}
)
55 changes: 41 additions & 14 deletions common/test/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from datetime import datetime
from test import generic
from time import sleep
from pyfakefs.fake_filesystem_unittest import patchfs
import pyfakefs.fake_filesystem_unittest as pyfakefs_ut

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import tools
Expand Down Expand Up @@ -129,18 +129,6 @@ def test_addSourceToPathEnviron(self):
tools.addSourceToPathEnviron()
self.assertIn(source, os.environ['PATH'])

def test_gitRevisionAndHash(self):
ref, hashid = tools.gitRevisionAndHash()
if isinstance(ref, str):
self.assertGreater(len(ref), 0)
else:
self.assertIsNone(ref)

if isinstance(hashid, str):
self.assertEqual(len(hashid), 7)
else:
self.assertIsNone(hashid)

def test_readFile(self):
"""
Test the function readFile
Expand Down Expand Up @@ -470,7 +458,7 @@ def test_uuidFromPath(self):
self.assertRegex(uuid.lower(), r'^[a-f0-9\-]+$')
self.assertEqual(len(uuid.replace('-', '')), 32)

@patchfs
@pyfakefs_ut.patchfs
def test_uuid_via_filesystem(self, fake_fs):
"""Extract UUID from /dev filesystem.
Expand Down Expand Up @@ -1033,3 +1021,42 @@ def test_callback(self):
def test_pausable(self):
proc = tools.Execute('true')
self.assertFalse(proc.pausable)


class Tools_FakeFS(pyfakefs_ut.TestCase):
"""Tests using a fake filesystem.
"""

def setUp(self):
self.setUpPyfakefs(allow_root_user=False)

def test_git_repo_info(self):

# not a git repo
self.assertEqual(tools.get_git_repository_info(), None)

# simulate a git repo
path = pathlib.Path('.git')
path.mkdir()

# Branch folders and hash containing file
foobar = path / 'refs' / 'heads' / 'fix' / 'foobar'
foobar.parent.mkdir(parents=True)

with foobar.open('w') as handle:
handle.write('01234')

# HEAD file
head = path / 'HEAD'

with head.open('w') as handle:
handle.write('ref: refs/heads/fix/foobar')

# Test
self.assertEqual(
tools.get_git_repository_info(),
{
'hash': '01234',
'branch': 'fix/foobar'
}
)
Loading

0 comments on commit cf02bee

Please sign in to comment.