Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- 

# 

# Copyright © 2015 Canonical Ltd 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License version 3 as 

# published by the Free Software Foundation. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with this program.  If not, see <http://www.gnu.org/licenses/>. 

 

"""The catkin plugin is useful for building ROS parts. 

 

This plugin uses the common plugin keywords as well as those for "sources". 

For more information check the 'plugins' topic for the former and the 

'sources' topic for the latter. 

 

Additionally, this plugin uses the following plugin-specific keywords: 

 

    - catkin-packages: 

      (list of strings) 

      List of catkin packages to build. 

""" 

 

import lxml.etree 

import os 

import tempfile 

import logging 

import shutil 

 

import snapcraft 

from snapcraft import repo 

 

logger = logging.getLogger(__name__) 

 

 

class CatkinPlugin(snapcraft.BasePlugin): 

 

    _PLUGIN_STAGE_SOURCES = ''' 

deb http://packages.ros.org/ros/ubuntu/ trusty main 

deb http://${prefix}.ubuntu.com/${suffix}/ trusty main universe 

deb http://${prefix}.ubuntu.com/${suffix}/ trusty-updates main universe 

deb http://${prefix}.ubuntu.com/${suffix}/ trusty-security main universe 

deb http://${security}.ubuntu.com/${suffix} trusty-security main universe 

''' 

 

    @classmethod 

    def schema(cls): 

        schema = super().schema() 

        schema['properties']['rosversion'] = { 

            'type': 'string', 

            'default': 'indigo' 

        } 

        schema['properties']['catkin-packages'] = { 

            'type': 'array', 

            'minitems': 1, 

            'uniqueItems': True, 

            'items': { 

                'type': 'string' 

            }, 

            'default': [], 

        } 

 

        schema['required'].append('catkin-packages') 

 

        return schema 

 

    def __init__(self, name, options): 

        super().__init__(name, options) 

        self.packages = set(options.catkin_packages) 

        self.dependencies = ['ros-core'] 

        self.package_deps_found = False 

        self.package_local_deps = {} 

        self._deb_packages = [] 

 

    def pull(self): 

        super().pull() 

        self._setup_deb_packages() 

 

    def env(self, root): 

        return [ 

            'PYTHONPATH={0}'.format( 

                os.path.join( 

                    self.installdir, 

                    'usr', 

                    'lib', 

                    self.python_version, 

                    'dist-packages')), 

            'DESTDIR={0}'.format(self.installdir), 

            # ROS needs it but doesn't set it :-/ 

            'CPPFLAGS="-std=c++11 $CPPFLAGS -I{0} -I{1}"'.format( 

                os.path.join(root, 'usr', 'include', 'c++', self.gcc_version), 

                os.path.join(root, 

                             'usr', 

                             'include', 

                             snapcraft.common.get_arch_triplet(), 

                             'c++', 

                             self.gcc_version)), 

            'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:{0}/opt/ros/{1}/lib'.format( 

                root, 

                self.options.rosversion), 

            'ROS_MASTER_URI=http://localhost:11311', 

            '_CATKIN_SETUP_DIR={}'.format(os.path.join( 

                root, 'opt', 'ros', self.options.rosversion)), 

            'echo FOO=BAR\nif `test -e {0}` ; then\n. {0} ;\nfi\n'.format( 

                os.path.join( 

                    root, 'opt', 'ros', self.options.rosversion, 'setup.sh')) 

        ] 

 

    @property 

    def python_version(self): 

        return self.run_output(['pyversions', '-i']) 

 

    @property 

    def gcc_version(self): 

        return self.run_output(['gcc', '-dumpversion']) 

 

    @property 

    def rosdir(self): 

        return os.path.join(self.installdir, 

                            'opt', 'ros', self.options.rosversion) 

 

    def _deps_from_packagesxml(self, f, pkg): 

        tree = lxml.etree.parse(f) 

 

        for deptype in ('buildtool_depend', 'build_depend', 'run_depend'): 

            for xmldep in tree.xpath('/package/' + deptype): 

                dep = xmldep.text 

 

                self.dependencies.append(dep) 

 

                # Make sure we're not providing the dep ourselves 

                if dep in self.packages: 

                    self.package_local_deps[pkg].add(dep) 

                    continue 

 

                # If we're already getting this through a deb package, 

                # we don't need it 

                if (dep in self._deb_packages or 

                        dep.replace('_', '-') in self._deb_packages): 

                    continue 

 

                # Get the ROS package for it 

                self._deb_packages.append( 

                    'ros-'+self.options.rosversion+'-'+dep.replace('_', '-')) 

 

                if dep == 'roscpp': 

                    self._deb_packages.append('g++') 

 

    def _find_package_deps(self): 

157        if self.package_deps_found: 

            return 

 

        source_subdir = getattr(self.options, 'source_subdir', None) 

161        if source_subdir: 

            sourcedir = os.path.join(self.sourcedir, source_subdir) 

        else: 

            sourcedir = self.sourcedir 

 

        # catkin expects packages to be in 'src' but most repos 

        # keep there catkin-packages in plain sight without a 

        # 'src' directory as the top level. 

169        if os.path.exists(os.path.join(sourcedir, 'src')): 

            basedir = os.path.join(sourcedir, 'src') 

        else: 

            basedir = sourcedir 

 

        # Look for a package definition and pull deps if there are any 

189        for pkg in self.packages: 

178            if pkg not in self.package_local_deps: 

                self.package_local_deps[pkg] = set() 

 

            filename = os.path.join(basedir, pkg, 'package.xml') 

            try: 

                with open(filename, 'r') as f: 

                    self._deps_from_packagesxml(f, pkg) 

            except IOError as e: 

                if e.errno is os.errno.ENOENT: 

                    raise FileNotFoundError( 

                        'unable to find "package.xml" for "{}"'.format(pkg)) 

                else: 

                    raise e 

 

        self.package_deps_found = True 

 

    def _setup_deb_packages(self): 

        self._find_package_deps() 

 

        ubuntudir = os.path.join(self.partdir, 'ubuntu') 

        os.makedirs(ubuntudir, exist_ok=True) 

        if self._deb_packages: 

            ubuntu = repo.Ubuntu(ubuntudir, sources=self.PLUGIN_STAGE_SOURCES) 

            ubuntu.get(self._deb_packages) 

            ubuntu.unpack(self.installdir) 

 

    def _rosrun(self, commandlist, cwd=None): 

        with tempfile.NamedTemporaryFile(mode='w') as f: 

            f.write('set -ex\n') 

            f.write('exec {}\n'.format(' '.join(commandlist))) 

            f.flush() 

 

            self.run(['/bin/bash', f.name], cwd=cwd) 

 

    def _provision_builddir(self): 

212        if os.path.exists(self.builddir): 

            shutil.rmtree(self.builddir) 

        dst = os.path.join(self.builddir, 'src') 

 

        source_subdir = getattr(self.options, 'source_subdir', None) 

        if source_subdir: 

            sourcedir = os.path.join(self.sourcedir, source_subdir) 

        else: 

            sourcedir = self.sourcedir 

 

        shutil.copytree( 

            sourcedir, dst, symlinks=True, 

            ignore=lambda d, s: snapcraft.common.SNAPCRAFT_FILES 

            if d is self.sourcedir else []) 

 

    def build(self): 

        if os.path.exists(os.path.join(self.sourcedir, 'src')): 

            super().build() 

        else: 

            self._provision_builddir() 

 

        # Fixup ROS Cmake files that have hardcoded paths in them 

        self.run([ 

            'find', self.rosdir, '-name', '*.cmake', 

            '-exec', 'sed', '-i', '-e', 

            r's|\(\W\)/usr/lib/|\1{0}/usr/lib/|g'.format(self.installdir), 

            '{}', ';' 

        ]) 

 

        self._find_package_deps() 

        self._build_packages_deps() 

 

        # the hacks 

        findcmd = ['find', self.installdir, '-name', '*.cmake', '-delete'] 

        self.run(findcmd) 

 

        self.run( 

            ['rm', '-f', 

             'opt/ros/' + self.options.rosversion + '/.catkin', 

             'opt/ros/' + self.options.rosversion + '/.rosinstall', 

             'opt/ros/' + self.options.rosversion + '/setup.sh', 

             'opt/ros/' + self.options.rosversion + '/_setup_util.py'], 

            cwd=self.installdir) 

 

        os.remove(os.path.join(self.installdir, 'usr/bin/xml2-config')) 

 

    def _build_packages_deps(self): 

        # Ugly dependency resolution, just loop through until we can 

        # find something to build. When we do, build it. Loop until we 

        # either can't build anything or we built everything. 

        built = set() 

        built_pkg = True 

 

        while len(built) < len(self.packages) and built_pkg: 

            built_pkg = False 

            for pkg in self.packages - built: 

                if len(self.package_local_deps[pkg] - built) > 0: 

                    continue 

                self._handle_package(pkg) 

 

                built.add(pkg) 

                built_pkg = True 

 

        if not built_pkg: 

            raise RuntimeError('some packages failed to build') 

 

    def _handle_package(self, pkg): 

        catkincmd = ['catkin_make_isolated'] 

 

        catkincmd.append('--pkg') 

        catkincmd.append(pkg) 

 

        # Define the location 

        catkincmd.extend(['--directory', self.builddir]) 

 

        # Start the CMake Commands 

        catkincmd.append('--cmake-args') 

 

        # CMake directories 

        catkincmd.append('-DCATKIN_DEVEL_PREFIX={}'.format(self.rosdir)) 

        catkincmd.append('-DCMAKE_INSTALL_PREFIX={}'.format(self.installdir)) 

 

        # Dep CMake files 

        for dep in self.dependencies: 

            catkincmd.append('-D{0}_DIR={1}'.format( 

                dep.replace('-', '_'), 

                os.path.join(self.rosdir, 'share', dep, 'cmake'))) 

 

        # Compiler fun 

        catkincmd.extend([ 

            '-DCMAKE_C_FLAGS="$CFLAGS"', 

            '-DCMAKE_CXX_FLAGS="$CPPFLAGS"', 

            '-DCMAKE_LD_FLAGS="$LDFLAGS"', 

            '-DCMAKE_C_COMPILER={}'.format( 

                os.path.join(self.installdir, 'usr', 'bin', 'gcc')), 

            '-DCMAKE_CXX_COMPILER={}'.format( 

                os.path.join(self.installdir, 'usr', 'bin', 'g++')) 

        ]) 

 

        self._rosrun(catkincmd)