make version check smarter: only compare to tags having the same non-digit prefix
[mass-build.git] / vcs.py
1 # mass-build - Easily Build Software Involving a Large Amount of Source Repositories
2 # Copyright (C) 2012 Ralf Jung <post@ralfj.de>
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 import os, git, subprocess, re
19
20 '''A VCS must have an "update" method with an optional "mode" parameter taking one of the three values below,
21    a "version" method returning a version name (or None),
22    and a "newVersions" method which checks for new versions and prints the result to standard output.'''
23 MODE_FETCH = 0
24 MODE_REBASE = 1
25 MODE_RESET = 2
26
27 def natural_sort_key(val):
28         return [ (int(c) if c.isdigit() else c) for c in re.split('([0-9]+)', val) ]
29
30 def get_non_digit_prefix(val):
31         return re.match('[^0-9]*', val).group(0)
32
33 # Fetch updates from git
34 class Git:
35         def __init__(self, folder, config):
36                 self.folder = os.path.abspath(folder)
37                 self.url = config['url']
38                 self.commit = config['version']
39
40         class _ProgressPrinter(git.remote.RemoteProgress):
41                 def update(self, op_code, cur_count, max_count=None, message=''):
42                         print self._cur_line+(" "*30)+"\r",
43
44         def update(self, mode = MODE_REBASE):
45                 isBranch = (self.commit.startswith('origin/'))
46                 if isBranch:
47                         branchname = self.commit[len('origin/'):]
48                 else:
49                         branchname = "tag"
50                 # get us a git repository, and the "origin" remote
51                 if os.path.exists(self.folder):
52                         # load existing repo
53                         repo = git.Repo(self.folder)
54                         origin = repo.remotes.origin
55                         origin.config_writer.set_value("url", self.url) # make sure we use the current URL
56                 else:
57                         # create a new one
58                         os.makedirs(self.folder)
59                         repo = git.Repo.init(self.folder)
60                         origin = repo.create_remote('origin', self.url)
61                 origin.fetch(progress=Git._ProgressPrinter()) # download new data
62                 print " "*80+"\r", # clean the line we are in
63                 if mode == MODE_FETCH:
64                         return
65                 # create/find correct branch
66                 if branchname in repo.heads:
67                         branch = repo.heads[branchname]
68                 else:
69                         branch = repo.create_head(branchname, self.commit)
70                         if isBranch: # track remote branch
71                                 branch.set_tracking_branch(origin.refs[branchname])
72                 # update it to the latest remote commit
73                 branch.checkout()
74                 if mode == MODE_RESET:
75                         repo.head.reset(self.commit, working_tree=True)
76                 else:
77                         repo.git.rebase(self.commit)
78                 # update submodules
79                 repo.git.submodule("update", "--init", "--recursive", "--rebase")
80                 # done
81                 print "...done",
82                 if repo.head.reference.commit != repo.commit(self.commit):
83                         print "(keeping local patches around)",
84                 print
85
86         def version(self):
87                 repo = git.Repo(self.folder)
88                 v = repo.git.describe()
89                 return v[len(get_non_digit_prefix(v)):] # remove the letter prefix from v (so that it starts with a number)
90
91         def checkVersions(self):
92                 self.update(mode =  MODE_FETCH)
93                 repo = git.Repo(self.folder)
94                 # get tag name for current commit, if any
95                 commit = repo.commit(self.commit)
96                 commitTag = filter(lambda t: t.commit == commit, repo.tags)
97                 if not commitTag:
98                         print "Version is not a tag"
99                         return
100                 currentVersion = str(commitTag[0])
101                 # get sorted list of tag names with the same letter prefix and higher version number
102                 tags = map(str, repo.tags)
103                 tags = filter(lambda t: get_non_digit_prefix(t) == get_non_digit_prefix(currentVersion) and natural_sort_key(t) > natural_sort_key(currentVersion), tags)
104                 if not tags: return
105                 tags.sort(key = natural_sort_key)
106                 print "Versions newer than "+self.commit+" available:"
107                 print tags
108
109 # Fetch updates via SVN
110 class SVN:
111         def __init__(self, folder, url):
112                 self.folder = os.path.abspath(folder)
113                 self.url = url
114
115         def update(self, mode = MODE_REBASE):
116                 if mode == MODE_FETCH: raise Exception("Just fetching is not supported with SVN")
117                 if os.path.exists(self.folder):
118                         os.chdir(self.folder) # go into repository
119                         if mode == MODE_RESET: subprocess.check_call(['svn', 'revert', '-R', '.'])
120                         subprocess.check_call(['svn', 'switch', self.url]) # and update to the URL we got
121                 else:
122                         os.makedirs(self.folder) # if even the parent folder does not exist, svn fails
123                         subprocess.check_call(['svn', 'co', self.url, self.folder]) # just download it
124         
125         def version(self):
126                 return None
127         
128         def checkVersions(self):
129                 print "Version checking not supporting with SVN"