8f975460a7285d5f2d17f37a2f68fdf4773fb77e
[mass-build.git] / mass_build.py
1 #!/usr/bin/python
2 # mass-build - Easily Build Software Involving a Large Amount of Source Repositories
3 # Copyright (C) 2012 Ralf Jung <post@ralfj.de>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
19 import vcs, build_system, imp
20 import argparse, os, sys, subprocess
21 from collections import OrderedDict
22
23 # an entire Project
24 class Project:
25         def __init__(self, folder, config):
26                 self.folder = folder
27                 self.name = config['name']
28                 # VCS
29                 vcsName = config['vcs']
30                 if vcsName == 'git':
31                         self.vcs = vcs.Git(self.sourceFolder(), config)
32                 elif vcsName == 'svn':
33                         self.vcs = vcs.SVN(self.sourceFolder(), config['url'])
34                 else:
35                         raise Exception("Unknown VCS type "+vcsName)
36                 # build system
37                 if config.get('buildDeb', False):
38                         self.buildSystem = build_system.AutoDebuild(self.sourceFolder(), self.buildFolder(), config, self.vcs)
39                 else:
40                         buildSystemName = config['buildSystem']
41                         if buildSystemName == 'cmake':
42                                 self.buildSystem = build_system.CMake(self.sourceFolder(), self.buildFolder(), config)
43                         else:
44                                 raise Exception("Unknown build system type "+buildSystemName)
45         
46         def sourceFolder(self):
47                 return os.path.join(self.folder, self.name)
48         
49         def buildFolder(self):
50                 return os.path.join(config['buildDir'], self.sourceFolder())
51
52 # read command-line arguments
53 parser = argparse.ArgumentParser(description='Update and build a bunch of stuff')
54 parser.add_argument("-c, --config",
55                     dest="config", default="mass-build.conf",
56                     help="mass-build config file")
57 parser.add_argument("--reconfigure",
58                     action="store_true", dest="reconfigure",
59                     help="Force configuration to be run")
60 parser.add_argument("--wait-after-config",
61                     action="store_true", dest="wait_after_config",
62                     help="Wait for user confirmation after configuration is finished")
63 parser.add_argument("--reset-source",
64                     action="store_true", dest="reset_source",
65                     help="Reset sourcecode to the given version (removes local changes!)")
66 parser.add_argument("--no-update",
67                     action="store_false", dest="update",
68                     help="Do not update projects before compilation")
69 parser.add_argument("--resume-from", metavar='PROJECT',
70                     dest="resume_from",
71                     help="From the projects specified, continue building with this one (i.e., remove all projects before this one from the list - this never adds new projects)")
72 parser.add_argument("--check-versions",
73                     action="store_true", dest="version_check",
74                     help="Check the repositories for newer tags, if possible (does not perform any building steps)")
75 parser.add_argument("projects",  metavar='PROJECT', nargs='*',
76                     help="Manually specify projects or folders to be built (project names take precedence)")
77 args = parser.parse_args()
78 if args.reset_source and not args.update:
79         raise Exception("Can not reset sources without doing an update")
80
81 # load config
82 config = imp.load_source('config', args.config).__dict__
83 os.remove(args.config+'c') # remove compiled python file
84 allProjects = OrderedDict() # all projects
85 allFolders = {} # all folders
86 workProjects = [] # projects we work on
87
88 # copy all items which don't exist below, except for those in the exclude list
89 def inherit(subConfig, superConfig, exclude = ('name', 'projects')):
90         for name in superConfig.keys():
91                 if (not name in subConfig) and (not name in exclude):
92                         subConfig[name] = superConfig[name]
93
94 # populate list of projects, return list of projects in that folder
95 def loadProjects(config, folder=''):
96         folderProjects = []
97         for projectConfig in config['projects']:
98                 assert 'name' in projectConfig # everything must have a name
99                 inherit(projectConfig, config)
100                 if 'projects' in projectConfig: # a subpath
101                         folderProjects += loadProjects(projectConfig, os.path.join(folder, projectConfig['name']))
102                 else: # a proper project
103                         if projectConfig['name'] in allProjects:
104                                 raise Exception("Duplicate project name "+projectConfig['name'])
105                         project = Project(folder, projectConfig)
106                         allProjects[projectConfig['name']] = project
107                         folderProjects.append(project)
108         # store projects of this folder
109         if folder in allFolders:
110                 raise Exception("Duplicate folder name "+folder)
111         allFolders[folder] = folderProjects
112         return folderProjects
113
114 # load available projects
115 loadProjects(config)
116 # get base set og projects to process
117 if args.projects:
118         for name in args.projects:
119                 if name in allProjects:
120                         workProjects.append(allProjects[name])
121                 elif name in allFolders:
122                         workProjects += allFolders[name]
123                 else:
124                         raise Exception("Project or folder %s does not exist" % name)
125 else:
126         workProjects = allProjects.values() # all the projects
127 # apply the "resume from"
128 if args.resume_from is not None:
129         # find project index
130         startIndex = 0
131         while startIndex < len(workProjects):
132                 if workProjects[startIndex].name == args.resume_from:
133                         break # we found it
134                 else:
135                         startIndex += 1
136         if startIndex >= len(workProjects): # project not found
137                 raise Exception("%s not found in list of projects to work on" % args.resume_from)
138         # start here
139         workProjects = workProjects[startIndex:]
140
141 # and do it!
142 for project in workProjects:
143         try:
144                 if args.version_check:
145                         print "Checking project",project.sourceFolder()
146                         project.vcs.checkVersions()
147                 else:
148                         if args.update:
149                                 print "Updating project",project.sourceFolder()
150                                 project.vcs.update(mode = vcs.MODE_RESET if args.reset_source else vcs.MODE_REBASE)
151                         print "Building project",project.sourceFolder()
152                         project.buildSystem.build(reconfigure=args.reconfigure, waitAfterConfig=args.wait_after_config)
153                 print
154         except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
155                 print >> sys.stderr
156                 print >> sys.stderr
157                 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
158                         print >> sys.stderr, "Interruped by user while processing %s" % (project.name)
159                 else:
160                         print >> sys.stderr, "Error while processing %s: %s" % (project.name, str(e))
161                 print >> sys.stderr
162                 sys.exit(1)
163 print "All operations successfully completed"