Use subprocess.check_call
[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, get_stderr = False):
36                         cmd = ["git", name.replace('_', '-')] + list(args)
37                         output = subprocess.check_call(cmd, stderr=subprocess.STDOUT if get_stderr else None)
38                         return output.decode('utf-8').strip('\n')
39                 return call
40 git = GitCommand()
41
42 # Fetch updates from git
43 class Git:
44         def __init__(self, folder, config):
45                 self.folder = os.path.abspath(folder)
46                 self.url = config['url']
47                 self.commit = config['version']
48
49         def update(self, mode = MODE_REBASE):
50                 isBranch = (self.commit.startswith('origin/'))
51                 if isBranch:
52                         branchname = self.commit[len('origin/'):]
53                 else:
54                         branchname = "tag"
55                 # get us a git repository, and the "origin" remote
56                 if os.path.exists(self.folder):
57                         # load existing repo
58                         os.chdir(self.folder)
59                         git.remote("set-url", "origin", self.url) # make sure we use the current URL
60                 else:
61                         # create a new one
62                         os.makedirs(self.folder)
63                         os.chdir(self.folder)
64                         git.init()
65                         git.remote("add", "origin", self.url)
66                 git.fetch("origin")
67                 if mode == MODE_FETCH:
68                         return
69                 # create/find correct branch
70                 if not git.branch("--list", branchname): # the branch does not yet exit
71                         git.branch(branchname, self.commit)
72                         if isBranch: # make sure we track the correct remote branch
73                                 git.branch("-u", self.commit, branchname)
74                 # update it to the latest remote commit
75                 git.checkout(branchname, get_stderr=True)
76                 if mode == MODE_RESET:
77                         git.reset("--hard", self.commit)
78                 else:
79                         git.rebase(self.commit)
80                 # update submodules
81                 git.submodule("update", "--init", "--recursive", "--rebase")
82                 # done
83                 print("...done", end=' ')
84                 if git.rev_parse("HEAD") != git.rev_parse(self.commit):
85                         print("(keeping local patches around)", end=' ')
86                 print()
87
88         def version(self):
89                 v = git.describe()
90                 return v[len(get_non_digit_prefix(v)):] # remove the non-digit prefix from v (so that it starts with a number)
91
92         def checkVersions(self):
93                 self.update(mode = MODE_FETCH)
94                 currentVersion = git.describe()
95                 # get sorted list of tag names with the same non-digit prefix and higher version number
96                 tags = git.tag().split('\n')
97                 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)]
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")