7e6c1a301e40cafadcfd732d839528a9c08fb862
[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, 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 class GitCommand:
34         def __getattr__(self, name):
35                 def call(*args, suppress_stderr = False):
36                         cmd = ["git", name.replace('_', '-')] + list(args)
37                         with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE if suppress_stderr else None) as p:
38                                 (stdout, stderr) = p.communicate()
39                                 if p.returncode != 0:
40                                         raise Exception("Running %s returned non-zero exit code %d" % (str(cmd), p.returncode))
41                         stdout = stdout.decode('utf-8').strip('\n')
42                         return stdout
43                 return call
44 git = GitCommand()
45
46 # Fetch updates from git
47 class Git:
48         def __init__(self, folder, config):
49                 self.folder = os.path.abspath(folder)
50                 self.url = config['url']
51                 self.commit = config['version']
52
53         def update(self, mode = MODE_REBASE):
54                 isBranch = (self.commit.startswith('origin/'))
55                 if isBranch:
56                         branchname = self.commit[len('origin/'):]
57                 else:
58                         branchname = "tag"
59                 # get us a git repository, and the "origin" remote
60                 if os.path.exists(self.folder):
61                         # load existing repo
62                         os.chdir(self.folder)
63                         git.remote("set-url", "origin", self.url) # make sure we use the current URL
64                 else:
65                         # create a new one
66                         os.makedirs(self.folder)
67                         os.chdir(self.folder)
68                         git.init()
69                         git.remote("add", "origin", self.url)
70                 git.fetch("origin")
71                 if mode == MODE_FETCH:
72                         return
73                 # create/find correct branch
74                 if not git.branch("--list", branchname): # the branch does not yet exit
75                         git.branch(branchname, self.commit)
76                         if isBranch: # make sure we track the correct remote branch
77                                 git.branch("-u", self.commit, branchname)
78                 # update it to the latest remote commit
79                 git.checkout(branchname, suppress_stderr=True)
80                 if mode == MODE_RESET:
81                         git.reset("--hard", self.commit)
82                 else:
83                         git.rebase(self.commit)
84                 # update submodules
85                 git.submodule("update", "--init", "--recursive", "--rebase")
86                 # done
87                 print("...done", end=' ')
88                 if git.rev_parse("HEAD") != git.rev_parse(self.commit):
89                         print("(keeping local patches around)", end=' ')
90                 print()
91
92         def version(self):
93                 v = git.describe()
94                 return v[len(get_non_digit_prefix(v)):] # remove the non-digit prefix from v (so that it starts with a number)
95
96         def checkVersions(self):
97                 self.update(mode = MODE_FETCH)
98                 currentVersion = git.describe()
99                 # get sorted list of tag names with the same non-digit prefix and higher version number
100                 tags = git.tag().split('\n')
101                 tags = [t for t in tags if get_non_digit_prefix(t) == get_non_digit_prefix(currentVersion) and natural_sort_key(t) > natural_sort_key(currentVersion)]
102                 if not tags: return
103                 tags.sort(key = natural_sort_key)
104                 print("Versions newer than "+currentVersion+" available:")
105                 print(tags)
106
107 # Fetch updates via SVN
108 class SVN:
109         def __init__(self, folder, url):
110                 self.folder = os.path.abspath(folder)
111                 self.url = url
112
113         def update(self, mode = MODE_REBASE):
114                 if mode == MODE_FETCH: raise Exception("Just fetching is not supported with SVN")
115                 if os.path.exists(self.folder):
116                         os.chdir(self.folder) # go into repository
117                         if mode == MODE_RESET: subprocess.check_call(['svn', 'revert', '-R', '.'])
118                         subprocess.check_call(['svn', 'switch', self.url]) # and update to the URL we got
119                 else:
120                         os.makedirs(self.folder) # if even the parent folder does not exist, svn fails
121                         subprocess.check_call(['svn', 'co', self.url, self.folder]) # just download it
122         
123         def version(self):
124                 return None
125         
126         def checkVersions(self):
127                 print("Version checking not supporting with SVN")