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

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

# 

# Copyright (C) 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/>. 

 

"""Common keywords for plugins that use common source options. 

 

A part that uses common source options can have these keyword entries: 

 

    - source: 

      (string) 

      A path to some source tree to build. It can be either remote or local, 

      and either a directory tree or a tarball. 

    - source-type: 

      (string) 

      In some cases the source is not enough to identify the version control 

      system or compression algorithim. This hints the system into what to 

      do, the valid values are: 

 

                   - bzr 

                   - mercurial 

                   - hg 

                   - git 

                   - tar 

 

    - source-branch: 

      (string) 

      A specific branch from the source tree. This will result in an error 

      if used with a bazaar source type. 

    - source-tag: 

      (string) 

      A specific tag from the source tree. 

    - source-subdir: 

      (string) 

      A source directory within a repository or tarfile to enter and build 

      from. 

""" 

 

 

import logging 

import os 

import os.path 

import requests 

import shutil 

import tarfile 

import re 

import subprocess 

import tempfile 

 

import snapcraft.common 

 

 

logging.getLogger('urllib3').setLevel(logging.CRITICAL) 

 

 

class IncompatibleOptionsError(Exception): 

 

    def __init__(self, message): 

        self.message = message 

 

 

class Base: 

 

    def __init__(self, source, source_dir, source_tag=None, 

                 source_branch=None): 

        self.source = source 

        self.source_dir = source_dir 

        self.source_tag = source_tag 

        self.source_branch = source_branch 

 

 

class Bazaar(Base): 

 

    def __init__(self, source, source_dir, source_tag=None, 

                 source_branch=None): 

        super().__init__(source, source_dir, source_tag, source_branch) 

        if source_branch: 

            raise IncompatibleOptionsError( 

                'can\'t specify a source-branch for a bzr source') 

 

    def pull(self): 

        tag_opts = [] 

        if self.source_tag: 

            tag_opts = ['-r', 'tag:' + self.source_tag] 

        if os.path.exists(os.path.join(self.source_dir, '.bzr')): 

            cmd = ['bzr', 'pull'] + tag_opts + \ 

                  [self.source, '-d', self.source_dir] 

        else: 

            os.rmdir(self.source_dir) 

            cmd = ['bzr', 'branch'] + tag_opts + \ 

                  [self.source, self.source_dir] 

 

        subprocess.check_call(cmd) 

 

 

class Git(Base): 

 

    def __init__(self, source, source_dir, source_tag=None, 

                 source_branch=None): 

        super().__init__(source, source_dir, source_tag, source_branch) 

        if source_tag and source_branch: 

            raise IncompatibleOptionsError( 

                'can\'t specify both source-tag and source-branch for ' 

                'a git source') 

 

    def pull(self): 

        if os.path.exists(os.path.join(self.source_dir, '.git')): 

            refspec = 'HEAD' 

            if self.source_branch: 

                refspec = 'refs/heads/' + self.source_branch 

            elif self.source_tag: 

                refspec = 'refs/tags/' + self.source_tag 

            cmd = ['git', '-C', self.source_dir, 'pull', self.source, refspec] 

        else: 

            branch_opts = [] 

            if self.source_tag or self.source_branch: 

                branch_opts = ['--branch', 

                               self.source_tag or self.source_branch] 

            cmd = ['git', 'clone'] + branch_opts + \ 

                  [self.source, self.source_dir] 

 

        subprocess.check_call(cmd) 

 

 

class Mercurial(Base): 

 

    def __init__(self, source, source_dir, source_tag=None, 

                 source_branch=None): 

        super().__init__(source, source_dir, source_tag, source_branch) 

        if source_tag and source_branch: 

            raise IncompatibleOptionsError( 

                'can\'t specify both source-tag and source-branch for a ' 

                'mercurial source') 

 

    def pull(self): 

        if os.path.exists(os.path.join(self.source_dir, '.hg')): 

            ref = [] 

            if self.source_tag: 

                ref = ['-r', self.source_tag] 

            elif self.source_branch: 

                ref = ['-b', self.source_branch] 

            cmd = ['hg', 'pull'] + ref + [self.source, ] 

        else: 

            ref = [] 

            if self.source_tag or self.source_branch: 

                ref = ['-u', self.source_tag or self.source_branch] 

            cmd = ['hg', 'clone'] + ref + [self.source, self.source_dir] 

 

        subprocess.check_call(cmd) 

 

 

class Tar(Base): 

 

    def __init__(self, source, source_dir, source_tag=None, 

                 source_branch=None): 

        super().__init__(source, source_dir, source_tag, source_branch) 

        if source_tag: 

            raise IncompatibleOptionsError( 

                'can\'t specify a source-tag for a tar source') 

        elif source_branch: 

            raise IncompatibleOptionsError( 

                'can\'t specify a source-branch for a tar source') 

 

    def pull(self): 

178        if snapcraft.common.isurl(self.source): 

            self._download() 

        self.provision(self.source_dir) 

 

    def _download(self): 

        req = requests.get(self.source, stream=True, allow_redirects=True) 

183        if req.status_code is not 200: 

            raise EnvironmentError('unexpected http status code when ' 

                                   'downloading {}'.format(req.status_code)) 

 

        file = os.path.join(self.source_dir, os.path.basename(self.source)) 

        with open(file, 'wb') as f: 

            for chunk in req.iter_content(1024): 

                f.write(chunk) 

 

    def provision(self, dst, clean_target=True): 

        # TODO add unit tests. 

        if snapcraft.common.isurl(self.source): 

            tarball = os.path.join( 

                self.source_dir, 

                os.path.basename(self.source)) 

        else: 

            tarball = os.path.abspath(self.source) 

 

        if clean_target: 

            tmp_tarball = tempfile.NamedTemporaryFile().name 

            shutil.move(tarball, tmp_tarball) 

            shutil.rmtree(dst) 

            os.makedirs(dst) 

            shutil.move(tmp_tarball, tarball) 

 

        self._extract(tarball, dst) 

 

    def _extract(self, tarball, dst): 

        with tarfile.open(tarball) as tar: 

            def filter_members(tar): 

                """Filters members and member names: 

                    - strips common prefix 

                    - bans dangerous names""" 

                members = tar.getmembers() 

                common = os.path.commonprefix([m.name for m in members]) 

 

                # commonprefix() works a character at a time and will 

                # consider "d/ab" and "d/abc" to have common prefix "d/ab"; 

                # check all members either start with common dir 

                for m in members: 

                    if not (m.name.startswith(common + '/') or 

                            m.isdir() and m.name == common): 

                        # commonprefix() didn't return a dir name; go up one 

                        # level 

                        common = os.path.dirname(common) 

                        break 

 

                for m in members: 

                    if m.name == common: 

                        continue 

                    if m.name.startswith(common + '/'): 

                        m.name = m.name[len(common + '/'):] 

                    # strip leading '/', './' or '../' as many times as needed 

                    m.name = re.sub(r'^(\.{0,2}/)*', r'', m.name) 

                    # We mask all files to be writable to be able to easily 

                    # extract on top. 

                    m.mode = m.mode | 0o200 

                    yield m 

 

            tar.extractall(members=filter_members(tar), path=dst) 

 

 

class Local(Base): 

 

    def pull(self): 

        path = os.path.abspath(self.source) 

249        if os.path.islink(self.source_dir): 

            os.remove(self.source_dir) 

        elif os.path.isdir(self.source_dir): 

            os.rmdir(self.source_dir) 

        else: 

            os.remove(self.source_dir) 

        os.symlink(path, self.source_dir) 

 

 

def get(sourcedir, builddir, options): 

    """Populate sourcedir and builddir from parameters defined in options. 

 

    :param str sourcedir: The source directory to use. 

    :param str builddir: The build directory to use. 

    :param options: source options. 

    """ 

    source_type = getattr(options, 'source_type', None) 

    source_tag = getattr(options, 'source_tag', None) 

    source_branch = getattr(options, 'source_branch', None) 

 

    handler_class = _get_source_handler(source_type, options.source) 

    handler = handler_class(options.source, sourcedir, source_tag, 

                            source_branch) 

    handler.pull() 

 

 

_source_handler = { 

    'bzr': Bazaar, 

    'git': Git, 

    'hg': Mercurial, 

    'mercurial': Mercurial, 

    'tar': Tar, 

} 

 

 

def _get_source_handler(source_type, source): 

    if not source_type: 

        source_type = _get_source_type_from_uri(source) 

 

    return _source_handler.get(source_type, Local) 

 

 

_tar_type_regex = re.compile(r'.*\.((tar\.(xz|gz|bz2))|tgz)$') 

 

 

def _get_source_type_from_uri(source): 

    source_type = '' 

296    if source.startswith('bzr:') or source.startswith('lp:'): 

        source_type = 'bzr' 

298    elif source.startswith('git:') or source.startswith('git@'): 

        source_type = 'git' 

    elif _tar_type_regex.match(source): 

        source_type = 'tar' 

    elif snapcraft.common.isurl(source): 

        raise ValueError('no handler to manage source') 

    elif not os.path.isdir(source): 

        raise ValueError('local source is not a directory') 

 

    return source_type