89a4920ba006b36753bc7b3ddb8db033b5930da0
[mass-build.git] / vcs.py
1 # mass-build - Easily Build Software Involving a Large Amount of Source Repositories
2 # Copyright (C) 2012-2013 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 non-digit 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                 currentVersion = repo.git.describe()
95                 # get sorted list of tag names with the same non-digit prefix and higher version number
96                 tags = map(str, repo.tags)
97                 tags = filter(lambda t: get_non_digit_prefix(t) == get_non_digit_prefix(currentVersion) and natural_sort_key(t) > natural_sort_key(currentVersion), tags)
98                 if not tags: return
99                 tags.sort(key = natural_sort_key)
100                 print "Versions newer than "+currentVersion+" available:"
101                 print tags
102
103 # Fetch updates via SVN
104 class SVN:
105         def __init__(self, folder, url):
106                 self.folder = os.path.abspath(folder)
107                 self.url = url
108
109         def update(self, mode = MODE_REBASE):
110                 if mode == MODE_FETCH: raise Exception("Just fetching is not supported with SVN")
111                 if os.path.exists(self.folder):
112                         os.chdir(self.folder) # go into repository
113                         if mode == MODE_RESET: subprocess.check_call(['svn', 'revert', '-R', '.'])
114                         subprocess.check_call(['svn', 'switch', self.url]) # and update to the URL we got
115                 else:
116                         os.makedirs(self.folder) # if even the parent folder does not exist, svn fails
117                         subprocess.check_call(['svn', 'co', self.url, self.folder]) # just download it
118         
119         def version(self):
120                 return None
121         
122         def checkVersions(self):
123                 print "Version checking not supporting with SVN"