88db907bd01ebb41fdfab6eadca4aa66d684cfec
[mass-build.git] / mass_build.py
1 #!/usr/bin/python3
2 # mass-build - Easily Build Software Involving a Large Amount of Source Repositories
3 # Copyright (C) 2012-2013 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, importlib.machinery
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("-w", "--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 old_val = sys.dont_write_bytecode
83 sys.dont_write_bytecode = True
84 config = importlib.machinery.SourceFileLoader('config', args.config).load_module().__dict__
85 sys.dont_write_bytecode = old_val
86
87 # initialise variables holding the configuration
88 allProjects = OrderedDict() # all projects
89 allFolders = {} # all folders
90 workProjects = [] # projects we work on
91
92 # copy all items which don't exist below, except for those in the exclude list
93 def inherit(subConfig, superConfig, exclude = ('name', 'projects')):
94         for name in superConfig.keys():
95                 if (not name in subConfig) and (not name in exclude):
96                         subConfig[name] = superConfig[name]
97
98 # populate list of projects, return list of projects in that folder
99 def loadProjects(config, folder=''):
100         folderProjects = []
101         for projectConfig in config['projects']:
102                 assert 'name' in projectConfig # everything must have a name
103                 inherit(projectConfig, config)
104                 if 'projects' in projectConfig: # a subpath
105                         folderProjects += loadProjects(projectConfig, os.path.join(folder, projectConfig['name']))
106                 else: # a proper project
107                         if projectConfig['name'] in allProjects:
108                                 raise Exception("Duplicate project name "+projectConfig['name'])
109                         project = Project(folder, projectConfig)
110                         allProjects[projectConfig['name']] = project
111                         folderProjects.append(project)
112         # store projects of this folder
113         if folder in allFolders:
114                 raise Exception("Duplicate folder name "+folder)
115         allFolders[folder] = folderProjects
116         return folderProjects
117
118 # load available projects
119 loadProjects(config)
120 # get base set og projects to process
121 if args.projects:
122         for name in args.projects:
123                 if name in allProjects:
124                         workProjects.append(allProjects[name])
125                 elif name in allFolders:
126                         workProjects += allFolders[name]
127                 else:
128                         raise Exception("Project or folder %s does not exist" % name)
129 else:
130         workProjects = list(allProjects.values()) # all the projects
131 # apply the "resume from"
132 if args.resume_from is not None:
133         # find project index
134         startIndex = 0
135         while startIndex < len(workProjects):
136                 if workProjects[startIndex].name == args.resume_from:
137                         break # we found it
138                 else:
139                         startIndex += 1
140         if startIndex >= len(workProjects): # project not found
141                 raise Exception("%s not found in list of projects to work on" % args.resume_from)
142         # start here
143         workProjects = workProjects[startIndex:]
144
145 # and do it!
146 for project in workProjects:
147         try:
148                 if args.version_check:
149                         print("Checking project",project.sourceFolder())
150                         project.vcs.checkVersions()
151                 else:
152                         if args.update:
153                                 print("Updating project",project.sourceFolder())
154                                 project.vcs.update(mode = vcs.MODE_RESET if args.reset_source else vcs.MODE_REBASE)
155                         print("Building project",project.sourceFolder())
156                         project.buildSystem.build(reconfigure=args.reconfigure, waitAfterConfig=args.wait_after_config)
157                 print()
158         except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
159                 print(file=sys.stderr)
160                 print(file=sys.stderr)
161                 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
162                         print("Interruped by user while processing %s" % (project.name), file=sys.stderr)
163                 else:
164                         print("Error while processing %s: %s" % (project.name, str(e)), file=sys.stderr)
165                 print(file=sys.stderr)
166                 sys.exit(1)
167 print("All operations successfully completed")