096d9a5834377a090fd5fb5c34fac5dada8b5654
[mass-build.git] / mass_build.py
1 #!/usr/bin/python
2 import vcs, build_system, imp
3 import argparse, os, sys, subprocess
4 from collections import OrderedDict
5
6 # an entire Project
7 class Project:
8         def __init__(self, folder, config):
9                 self.folder = folder
10                 self.name = config['name']
11                 # VCS
12                 vcsName = config['vcs']
13                 if vcsName == 'git':
14                         self.vcs = vcs.Git(self.sourceFolder(), config['url'], config['version'])
15                 elif vcsName == 'svn':
16                         self.vcs = vcs.SVN(self.sourceFolder(), config['url'])
17                 else:
18                         raise Exception("Unknown VCS type "+vcsName)
19                 # build system
20                 if config.get('buildDeb', False):
21                         self.buildSystem = build_system.AutoDebuild(self.sourceFolder(), self.buildFolder(), config, self.vcs)
22                 else:
23                         buildSystemName = config['buildSystem']
24                         if buildSystemName == 'cmake':
25                                 self.buildSystem = build_system.CMake(self.sourceFolder(), self.buildFolder(), config)
26                         else:
27                                 raise Exception("Unknown build system type "+buildSystemName)
28         
29         def sourceFolder(self):
30                 return os.path.join(self.folder, self.name)
31         
32         def buildFolder(self):
33                 return os.path.join(config['buildDir'], self.sourceFolder())
34
35 # read command-line arguments
36 parser = argparse.ArgumentParser(description='Update and build a bunch of stuff')
37 parser.add_argument("-c, --config",
38                     dest="config", default="mass-build.conf",
39                     help="mass-build config file")
40 parser.add_argument("--reconfigure",
41                     action="store_true", dest="reconfigure",
42                     help="Force configuration to be run")
43 parser.add_argument("--reset-source",
44                     action="store_true", dest="reset_source",
45                     help="Reset sourcecode to the given version (removes local changes!)")
46 parser.add_argument("--no-update",
47                     action="store_false", dest="update",
48                     help="Do not update projects before compilation")
49 parser.add_argument("--resume-from", metavar='PROJECT',
50                     dest="resume_from",
51                     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)")
52 parser.add_argument("projects",  metavar='PROJECT', nargs='*',
53                     help="Manually specify projects or folders to be built (project names take precedence)")
54 args = parser.parse_args()
55 # sanitize
56 if args.reset_source and not args.update:
57         raise Exception("When no update is performed, no reset to the given version can be done either")
58
59 # load config
60 config = imp.load_source('config', args.config).__dict__
61 os.remove(args.config+'c') # remove compiled python file
62 allProjects = OrderedDict() # all projects
63 allFolders = {} # all folders
64 workProjects = [] # projects we work on
65
66 # copy all items which don't exist below, except for those in the exclude list
67 def inherit(subConfig, superConfig, exclude = ('name', 'projects')):
68         for name in superConfig.keys():
69                 if (not name in subConfig) and (not name in exclude):
70                         subConfig[name] = superConfig[name]
71
72 # populate list of projects, return list of projects in that folder
73 def loadProjects(config, folder=''):
74         folderProjects = []
75         for projectConfig in config['projects']:
76                 assert 'name' in projectConfig # everything must have a name
77                 inherit(projectConfig, config)
78                 if 'projects' in projectConfig: # a subpath
79                         folderProjects += loadProjects(projectConfig, os.path.join(folder, projectConfig['name']))
80                 else: # a proper project
81                         if projectConfig['name'] in allProjects:
82                                 raise Exception("Duplicate project name "+projectConfig['name'])
83                         project = Project(folder, projectConfig)
84                         allProjects[projectConfig['name']] = project
85                         folderProjects.append(project)
86         # store projects of this folder
87         if folder in allFolders:
88                 raise Exception("Duplicate folder name "+folder)
89         allFolders[folder] = folderProjects
90         return folderProjects
91
92 # load available projects
93 loadProjects(config)
94 # get base set og projects to process
95 if args.projects:
96         for name in args.projects:
97                 if name in allProjects:
98                         workProjects.append(allProjects[name])
99                 elif name in allFolders:
100                         workProjects += allFolders[name]
101                 else:
102                         raise Exception("Project or folder %s does not exist" % name)
103 else:
104         workProjects = allProjects.values() # all the projects
105 # apply the "resume from"
106 if args.resume_from is not None:
107         # find project index
108         startIndex = 0
109         while startIndex < len(workProjects):
110                 if workProjects[startIndex].name == args.resume_from:
111                         break # we found it
112                 else:
113                         startIndex += 1
114         if startIndex >= len(workProjects): # project not found
115                 raise Exception("%s not found in list of projects to work on" % args.resume_from)
116         # start here
117         workProjects = workProjects[startIndex:]
118
119 # and do it!
120 for project in workProjects:
121         try:
122                 if args.update:
123                         print "Updating project",project.sourceFolder()
124                         project.vcs.update(forceVersion=args.reset_source)
125                 print "Building project",project.sourceFolder()
126                 project.buildSystem.build(reconfigure=args.reconfigure)
127                 print
128         except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
129                 print >> sys.stderr
130                 print >> sys.stderr
131                 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
132                         print >> sys.stderr, "Interruped by user while processing %s" % (project.name)
133                 else:
134                         print >> sys.stderr, "Error while processing %s: %s" % (project.name, str(e))
135                 print >> sys.stderr
136                 sys.exit(1)