Coverage for distro_tracker/core/utils/packages.py: 64%

287 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2026-11-25 22:25 +0000

1# Copyright 2013-2018 The Distro Tracker Developers 

2# See the COPYRIGHT file at the top-level directory of this distribution and 

3# at https://deb.li/DTAuthors 

4# 

5# This file is part of Distro Tracker. It is subject to the license terms 

6# in the LICENSE file found in the top-level directory of this 

7# distribution and at https://deb.li/DTLicense. No part of Distro Tracker, 

8# including this file, may be copied, modified, propagated, or distributed 

9# except according to the terms contained in the LICENSE file. 

10"""Utilities for processing Debian package information.""" 

11import os 

12import re 

13import shutil 

14import subprocess 

15import tarfile 

16 

17import apt 

18 

19import apt_pkg 

20 

21from debian import deb822 

22 

23from django.conf import settings 

24from django.core.validators import URLValidator 

25from django.core.exceptions import ValidationError 

26from django.urls import reverse 

27from django.utils.encoding import force_bytes 

28 

29from distro_tracker.core.utils.email_messages import \ 

30 names_and_addresses_from_string as parse_addresses 

31 

32 

33def package_hashdir(package_name): 

34 """ 

35 Returns the name of the hash directory used to avoid having too 

36 many entries in a single directory. It's usually the first letter 

37 of the package except for lib* packages where it's the first 4 

38 letters. 

39 

40 :param package_name: The package name. 

41 :type package_name: str 

42 

43 :returns: Name of the hash directory. 

44 :rtype: str 

45 """ 

46 if package_name is None: 

47 return None 

48 if package_name.startswith('lib'): 

49 return package_name[0:4] 

50 else: 

51 return package_name[0:1] 

52 

53 

54def package_url(package_name): 

55 """ 

56 Returns the URL of the page dedicated to this package name. 

57 

58 :param package_name: The package name. 

59 :type package_name: str or PackageName model 

60 

61 :returns: Name of the hash directory. 

62 :rtype: str 

63 """ 

64 if package_name is None: 

65 return None 

66 return reverse('dtracker-package-page', 

67 kwargs={'package_name': str(package_name)}) 

68 

69 

70# Debian Policy 5.6.26: <url> [ " -b " <branch> ] [ " [" <path> "]" ] 

71VCS_GIT_RE = re.compile( 

72 r'\s*(?P<url>\S+)' 

73 r'(?:\s+-b\s*(?P<branch>\S+))?' 

74 r'(?:\s+\[(?P<path>[^\]]+)\])?' 

75 r'\s*$' 

76) 

77 

78 

79def extract_vcs_information(stanza): 

80 """ 

81 Extracts the VCS information from a package's Sources entry. 

82 

83 :param stanza: The ``Sources`` entry from which to extract the VCS info. 

84 Maps ``Sources`` key names to values. 

85 :type stanza: dict 

86 

87 :returns: VCS information regarding the package. Contains the following 

88 keys: type[, browser, url, branch, path] 

89 :rtype: dict 

90 """ 

91 vcs = {} 

92 for key, value in stanza.items(): 

93 key = key.lower() 

94 if key == 'vcs-browser': 

95 vcs['browser'] = value 

96 elif key.startswith('vcs-'): 

97 vcs['type'] = key[4:] 

98 vcs['url'] = value 

99 if vcs['type'] == 'git': 

100 match = VCS_GIT_RE.match(value) 

101 if match: 

102 vcs['url'] = match.group('url') 

103 for part in ('branch', 'path'): 

104 if match.group(part): 

105 vcs[part] = match.group(part) 

106 return vcs 

107 

108 

109def extract_dsc_file_name(stanza): 

110 """ 

111 Extracts the name of the .dsc file from a package's Sources entry. 

112 

113 :param stanza: The ``Sources`` entry from which to extract the VCS info. 

114 Maps ``Sources`` key names to values. 

115 :type stanza: dict 

116 

117 """ 

118 for field in ('checksums-sha256', 'checksums-sha1', 'files'): 

119 for entry in stanza.get(field, []): 

120 if entry.get('name', '').endswith('.dsc'): 120 ↛ 119line 120 didn't jump to line 119, because the condition on line 120 was never false

121 return entry['name'] 

122 

123 return None 

124 

125 

126def extract_information_from_sources_entry(stanza): 

127 """ 

128 Extracts information from a ``Sources`` file entry and returns it in the 

129 form of a dictionary. 

130 

131 :param stanza: The raw entry's key-value pairs. 

132 :type stanza: Case-insensitive dict 

133 """ 

134 binaries = [ 

135 binary.strip() 

136 for binary in stanza['binary'].split(',') 

137 ] 

138 entry = { 

139 'version': stanza['version'], 

140 'homepage': stanza.get('homepage', ''), 

141 'priority': stanza.get('priority', ''), 

142 'section': stanza.get('section', ''), 

143 'architectures': stanza['architecture'].split(), 

144 'binary_packages': binaries, 

145 'maintainer': parse_addresses(stanza['maintainer'])[0], 

146 'uploaders': parse_addresses(stanza.get('uploaders', '')), 

147 'standards_version': stanza.get('standards-version', ''), 

148 'vcs': extract_vcs_information(stanza), 

149 'dsc_file_name': extract_dsc_file_name(stanza), 

150 'directory': stanza.get('directory', ''), 

151 } 

152 

153 # Validate incoming data a little bit 

154 try: 

155 URLValidator()(entry['homepage']) 

156 except ValidationError: 

157 entry['homepage'] = '' 

158 

159 return entry 

160 

161 

162def extract_information_from_packages_entry(stanza): 

163 """ 

164 Extracts information from a ``Packages`` file entry and returns it in the 

165 form of a dictionary. 

166 

167 :param stanza: The raw entry's key-value pairs. 

168 :type stanza: Case-insensitive dict 

169 """ 

170 entry = { 

171 'version': stanza['version'], 

172 'short_description': stanza.get('description', '')[:300], 

173 } 

174 

175 return entry 

176 

177 

178class SourcePackageRetrieveError(Exception): 

179 pass 

180 

181 

182class AptCache(object): 

183 """ 

184 A class for handling cached package information. 

185 """ 

186 DEFAULT_MAX_SIZE = 1 * 1024 ** 3 # 1 GiB 

187 QUILT_FORMAT = '3.0 (quilt)' 

188 

189 class AcquireProgress(apt.progress.base.AcquireProgress): 

190 """ 

191 Instances of this class can be passed to :meth:`apt.cache.Cache.update` 

192 calls. 

193 It provides a way to track which files were changed and which were not 

194 by an update operation. 

195 """ 

196 def __init__(self, *args, **kwargs): 

197 super(AptCache.AcquireProgress, self).__init__(*args, **kwargs) 

198 self.fetched = [] 

199 self.hit = [] 

200 

201 def done(self, item): 

202 self.fetched.append(os.path.split(item.owner.destfile)[1]) 

203 

204 def ims_hit(self, item): 

205 self.hit.append(os.path.split(item.owner.destfile)[1]) 

206 

207 def pulse(self, owner): 

208 return True 

209 

210 def __init__(self): 

211 # The root cache directory is a subdirectory in the 

212 # DISTRO_TRACKER_CACHE_DIRECTORY 

213 self.cache_root_dir = os.path.join( 

214 settings.DISTRO_TRACKER_CACHE_DIRECTORY, 

215 'apt-cache' 

216 ) 

217 self.sources_list_path = os.path.join( 

218 self.cache_root_dir, 'etc', 'sources.list') 

219 self.conf_file_path = os.path.join(self.cache_root_dir, 

220 'etc', 'apt.conf') 

221 os.environ['APT_CONFIG'] = self.conf_file_path 

222 

223 self.sources = [] 

224 self.packages = [] 

225 self.cache_max_size = getattr( 

226 settings, 'DISTRO_TRACKER_APT_CACHE_MAX_SIZE', 

227 self.DEFAULT_MAX_SIZE) 

228 #: The directory where source package files are cached 

229 self.source_cache_directory = os.path.join(self.cache_root_dir, 

230 'packages') 

231 self._cache_size = None # Evaluate the cache size lazily 

232 

233 self.configure_cache() 

234 

235 @property 

236 def cache_size(self): 

237 if self._cache_size is None: 

238 self._cache_size = \ 

239 self.get_directory_size(self.source_cache_directory) 

240 return self._cache_size 

241 

242 def get_directory_size(self, directory_path): 

243 """ 

244 Returns the total space taken by the given directory in bytes. 

245 

246 :param directory_path: The path to the directory 

247 :type directory_path: string 

248 

249 :rtype: int 

250 """ 

251 # Convert the directory path to bytes to make sure all os calls deal 

252 # with bytes, not unicode objects. 

253 # This way any file names with invalid utf-8 names, are correctly 

254 # handled, without causing an error. 

255 directory_path = force_bytes(directory_path) 

256 total_size = 0 

257 for dirpath, dirnames, filenames in os.walk(directory_path): 

258 for file_name in filenames: 

259 file_path = os.path.join(dirpath, file_name) 

260 stat = os.lstat(file_path) 

261 total_size += stat.st_size 

262 

263 return total_size 

264 

265 def clear_cache(self): 

266 """ 

267 Removes all cache information. This causes the next update to retrieve 

268 fresh repository files. 

269 """ 

270 self._remove_dir(self.cache_root_dir) 

271 self.configure_cache() 

272 

273 def update_sources_list(self): 

274 """ 

275 Updates the ``sources.list`` file used to list repositories for which 

276 package information should be cached. 

277 """ 

278 from distro_tracker.core.models import Repository 

279 

280 directory = os.path.dirname(self.sources_list_path) 

281 if not os.path.exists(directory): 

282 os.makedirs(directory) 

283 

284 with open(self.sources_list_path, 'w') as sources_list: 

285 for repository in Repository.objects.all(): 

286 sources_list.write(repository.sources_list_entry + '\n') 

287 

288 def update_apt_conf(self): 

289 """ 

290 Updates the ``apt.conf`` file which gives general settings for the 

291 :class:`apt.cache.Cache`. 

292 

293 In particular, this updates the list of all architectures which should 

294 be considered in package updates based on architectures that the 

295 repositories support. 

296 """ 

297 from distro_tracker.core.models import Architecture 

298 

299 with open(self.conf_file_path, 'w') as conf_file: 

300 conf_file.write('APT::Architectures { ') 

301 for arch in Architecture.objects.all(): 

302 conf_file.write(f'"{arch}";') 

303 conf_file.write('};\n') 

304 conf_file.write('Acquire::CompressionTypes::Order:: "xz";\n') 

305 path = self.cache_root_dir 

306 conf_file.write(f'Dir "{path}/";\n') 

307 conf_file.write('Dir::State "state/";\n') 

308 conf_file.write('Dir::State::status "dpkg-status";\n') 

309 conf_file.write('Dir::Etc "etc/";\n') 

310 path = self.sources_list_path 

311 conf_file.write(f'Dir::Etc::sourcelist "{path}";\n') 

312 path = settings.DISTRO_TRACKER_TRUSTED_GPG_PARTS_DIR 

313 conf_file.write(f'Dir::Etc::TrustedParts "{path}";\n') 

314 

315 # Create the corresponding .d directory that APT tries to access 

316 # next to its main configuration file 

317 os.makedirs(f'{self.conf_file_path}.d', exist_ok=True) 

318 

319 def configure_cache(self): 

320 """ 

321 Configures the cache based on the most current repository information. 

322 """ 

323 self.update_sources_list() 

324 self.update_apt_conf() 

325 # Clean up the configuration we might have read during "import apt" 

326 for root_key in apt_pkg.config.list(): 

327 apt_pkg.config.clear(root_key) 

328 # Load the proper configuration 

329 apt_pkg.init() 

330 # Ensure we have the required directories 

331 for apt_dir in [apt_pkg.config.find_dir('Dir::State::lists'), 

332 apt_pkg.config.find_dir('Dir::Etc::parts'), 

333 apt_pkg.config.find_dir('Dir::Etc::sourceparts'), 

334 apt_pkg.config.find_dir('Dir::Etc::preferencesparts'), 

335 apt_pkg.config.find_dir('Dir::Cache::archives')]: 

336 if not os.path.exists(apt_dir): 

337 os.makedirs(apt_dir) 

338 

339 def _index_file_full_path(self, file_name): 

340 """ 

341 Returns the absolute path for the given cached index file. 

342 

343 :param file_name: The name of the cached index file. 

344 :type file_name: string 

345 

346 :rtype: string 

347 """ 

348 return os.path.join( 

349 apt_pkg.config.find_dir('Dir::State::lists'), 

350 file_name 

351 ) 

352 

353 def _match_index_file_to_repository(self, sources_file): 

354 """ 

355 Returns a two-tuple ``(class:`Repository <distro_tracker.core. 

356 models.Repository>`, component)``. The class:`Repository 

357 <distro_tracker.core.models.Repository>` instance which matches the 

358 given cached ``Sources`` file and the ``component`` of the ``Source``. 

359 

360 :rtype: (:class:`Repository <distro_tracker.core.models.Repository>`, 

361 string) 

362 """ 

363 from distro_tracker.core.models import Repository 

364 

365 sources_list = apt_pkg.SourceList() 

366 sources_list.read_main_list() 

367 component_url = None 

368 component = None 

369 for entry in sources_list.list: 

370 for index_file in entry.index_files: 

371 if os.path.basename(sources_file) in index_file.describe: 

372 base_url, component, _ = index_file.describe.split(None, 2) 

373 base_url = base_url.rstrip('/') 

374 component_url = base_url + '/' + component 

375 break 

376 

377 components = component.split('/') 

378 if len(components) >= 2: 

379 component = components[1].strip() 

380 

381 for repository in Repository.objects.all(): 

382 if component_url in repository.component_urls: 

383 return repository, component 

384 

385 def _get_all_cached_files(self): 

386 """ 

387 Returns a list of all cached files. 

388 """ 

389 lists_directory = apt_pkg.config.find_dir('Dir::State::lists') 

390 try: 

391 return [ 

392 os.path.join(lists_directory, file_name) 

393 for file_name in os.listdir(lists_directory) 

394 if os.path.isfile(os.path.join(lists_directory, file_name)) 

395 ] 

396 except OSError: 

397 # The directory structure does not exist => nothing is cached 

398 return [] 

399 

400 def get_cached_files(self, filter_function=None): 

401 """ 

402 Returns cached files, optionally filtered by the given 

403 ``filter_function`` 

404 

405 :param filter_function: Takes a file name as the only parameter and 

406 returns a :class:`bool` indicating whether it should be included 

407 in the result. 

408 :type filter_function: callable 

409 

410 :returns: A list of cached file names 

411 :rtype: list 

412 """ 

413 if filter_function is None: 413 ↛ 415line 413 didn't jump to line 415, because the condition on line 413 was never true

414 # Include all files if the filter function is not provided 

415 def filter_function(x): 

416 return True 

417 

418 return [ 

419 file_name 

420 for file_name in self._get_all_cached_files() 

421 if filter_function(file_name) 

422 ] 

423 

424 def get_sources_files_for_repository(self, repository): 

425 """ 

426 Returns all ``Sources`` files which are cached for the given 

427 repository. 

428 

429 For instance, ``Sources`` files for different suites are cached 

430 separately. 

431 

432 :param repository: The repository for which to return all cached 

433 ``Sources`` files 

434 :type repository: :class:`Repository 

435 <distro_tracker.core.models.Repository>` 

436 

437 :rtype: ``iterable`` of strings 

438 """ 

439 return self.get_cached_files( 

440 lambda file_name: ( 

441 file_name.endswith('Sources') and 

442 self._match_index_file_to_repository( 

443 file_name)[0] == repository)) 

444 

445 def get_packages_files_for_repository(self, repository): 

446 """ 

447 Returns all ``Packages`` files which are cached for the given 

448 repository. 

449 

450 For instance, ``Packages`` files for different suites are cached 

451 separately. 

452 

453 :param repository: The repository for which to return all cached 

454 ``Packages`` files 

455 :type repository: :class:`Repository 

456 <distro_tracker.core.models.Repository>` 

457 

458 :rtype: ``iterable`` of strings 

459 """ 

460 return self.get_cached_files( 

461 lambda file_name: ( 

462 file_name.endswith('Packages') and 

463 self._match_index_file_to_repository( 

464 file_name)[0] == repository)) 

465 

466 def update_repositories(self, force_download=False): 

467 """ 

468 Initiates a cache update. 

469 

470 :param force_download: If set to ``True`` causes the cache to be 

471 cleared before starting the update, thus making sure all index 

472 files are downloaded again. 

473 

474 :returns: A two-tuple ``(updated_sources, updated_packages)``. Each of 

475 the tuple's members is a list of 

476 (:class:`Repository <distro_tracker.core.models.Repository>`, 

477 ``component``, ``file_name``) tuple representing the repository 

478 which was updated, component, and the file which contains the fresh 

479 information. The file is either a ``Sources`` or a ``Packages`` 

480 file respectively. 

481 """ 

482 if force_download: 

483 self.clear_cache() 

484 

485 self.configure_cache() 

486 

487 cache = apt.Cache(rootdir=self.cache_root_dir) 

488 progress = AptCache.AcquireProgress() 

489 cache.update(progress) 

490 

491 updated_sources = [] 

492 updated_packages = [] 

493 for fetched_file in progress.fetched: 

494 if fetched_file.endswith('Sources'): 

495 dest = updated_sources 

496 elif fetched_file.endswith('Packages'): 

497 dest = updated_packages 

498 else: 

499 continue 

500 repository, component = self._match_index_file_to_repository( 

501 fetched_file) 

502 dest.append(( 

503 repository, component, self._index_file_full_path(fetched_file) 

504 )) 

505 

506 return updated_sources, updated_packages 

507 

508 def _get_format(self, record): 

509 """ 

510 Returns the Format field value of the given source package record. 

511 """ 

512 record = deb822.Deb822(record) 

513 return record['format'] 

514 

515 def _extract_quilt_package_debian_tar(self, debian_tar_path, outdir): 

516 """ 

517 Extracts the given tarball to the given output directory. 

518 """ 

519 with tarfile.open(debian_tar_path) as archive_file: 

520 

521 def is_within_directory(directory, target): 

522 abs_directory = os.path.abspath(directory) 

523 abs_target = os.path.abspath(target) 

524 

525 prefix = os.path.commonprefix([abs_directory, abs_target]) 

526 

527 return prefix == abs_directory 

528 

529 def safe_extract(tar, path="."): 

530 for member in tar.getmembers(): 

531 member_path = os.path.join(path, member.name) 

532 if not is_within_directory(path, member_path): 

533 raise Exception("Attempted Path Traversal in Tar File") 

534 

535 tar.extractall(path) 

536 

537 safe_extract(archive_file, outdir) 

538 

539 def get_package_source_cache_directory(self, package_name): 

540 """ 

541 Returns the path to the directory where a particular source package is 

542 cached. 

543 

544 :param package_name: The name of the source package 

545 :type package_name: string 

546 

547 :rtype: string 

548 """ 

549 package_hash = ( 

550 package_name[0] 

551 if not package_name.startswith('lib') else 

552 package_name[:4] 

553 ) 

554 return os.path.join( 

555 self.source_cache_directory, 

556 package_hash, 

557 package_name) 

558 

559 def get_source_version_cache_directory(self, package_name, version): 

560 """ 

561 Returns the path to the directory where a particular source package 

562 version files are extracted. 

563 

564 :param package_name: The name of the source package 

565 :type package_name: string 

566 

567 :param version: The version of the source package 

568 :type version: string 

569 

570 :rtype: string 

571 """ 

572 package_dir = self.get_package_source_cache_directory(package_name) 

573 return os.path.join(package_dir, package_name + '-' + version) 

574 

575 def _remove_dir(self, directory_path): 

576 """ 

577 Removes the given directory, including any subdirectories and files. 

578 The method makes sure to correctly handle the situation where the 

579 directory contains files with names which are invalid utf-8. 

580 """ 

581 # Convert the directory path to bytes to make sure all os calls deal 

582 # with bytes, not unicode objects. 

583 # This way any file names with invalid utf-8 names, are correctly 

584 # handled, without causing an error. 

585 directory_path = force_bytes(directory_path) 

586 if os.path.exists(directory_path): 

587 shutil.rmtree(directory_path) 

588 

589 def clear_cached_sources(self): 

590 """ 

591 Clears all cached package source files. 

592 """ 

593 self._remove_dir(self.source_cache_directory) 

594 self._cache_size = self.get_directory_size(self.source_cache_directory) 

595 

596 def _get_apt_source_records(self, source_name, version): 

597 """ 

598 Returns a :class:`apt_pkg.SourceRecords` instance where the given 

599 source package is the current working record. 

600 """ 

601 apt.Cache(rootdir=self.cache_root_dir) # must be pre-created 

602 source_records = apt_pkg.SourceRecords() 

603 source_records.restart() 

604 # Find the cached record matching this source package and version 

605 found = False 

606 while source_records.lookup(source_name): 

607 if source_records.version == version: 

608 found = True 

609 break 

610 

611 if not found: 

612 # Package version does not exist in the cache 

613 raise SourcePackageRetrieveError( 

614 "Could not retrieve package {pkg} version {ver}:" 

615 " No such version found in the cache".format( 

616 pkg=source_name, ver=version)) 

617 

618 return source_records 

619 

620 def _extract_dpkg_source(self, retrieved_files, outdir): 

621 """ 

622 Uses dpkg-source to extract the source package. 

623 """ 

624 dsc_file_path = next( 

625 file_path 

626 for file_path in retrieved_files 

627 if file_path.endswith('.dsc')) 

628 dsc_file_path = os.path.abspath(dsc_file_path) 

629 outdir = os.path.abspath(outdir) 

630 subprocess.check_output(["dpkg-source", "-x", dsc_file_path, outdir], 

631 stderr=subprocess.STDOUT) 

632 

633 def _apt_acquire_package(self, 

634 source_records, 

635 dest_dir_path, 

636 debian_directory_only): 

637 """ 

638 Using :class:`apt_pkg.Acquire`, retrieves the source files for the 

639 source package described by the current source_records record. 

640 

641 :param source_records: The record describing the source package whose 

642 files should be retrieved. 

643 :type source_records: :class:`apt_pkg.Acquire` 

644 

645 :param dest_dir_path: The path to the directory where the downloaded 

646 files should be saved. 

647 :type dest_dir_path: string 

648 

649 :param debian_directory_only: A flag indicating whether only the debian 

650 directory should be downloaded. 

651 

652 :returns: A list of absolute paths of all retrieved source files. 

653 :rtype: list of strings 

654 """ 

655 package_format = self._get_format(source_records.record) 

656 # A reference to each AcquireFile instance must be kept 

657 files = [] 

658 acquire = apt_pkg.Acquire(apt.progress.base.AcquireProgress()) 

659 for srcfile in source_records.files: 

660 base = os.path.basename(srcfile.path) 

661 dest_file_path = os.path.join(dest_dir_path, base) 

662 if debian_directory_only and package_format == self.QUILT_FORMAT: 

663 if srcfile.type != 'diff': 

664 # Only retrieve the .debian.tar.* file for quilt packages 

665 # when only the debian directory is wanted 

666 continue 

667 files.append(apt_pkg.AcquireFile( 

668 acquire, 

669 source_records.index.archive_uri(srcfile.path), 

670 srcfile.hashes, 

671 srcfile.size, 

672 base, 

673 destfile=dest_file_path 

674 )) 

675 

676 acquire.run() 

677 

678 # Check if all items are correctly retrieved and build the list of file 

679 # paths. 

680 retrieved_paths = [] 

681 for item in acquire.items: 

682 if item.status != item.STAT_DONE: 

683 raise SourcePackageRetrieveError( 

684 'Could not retrieve file {file}: {error}'.format( 

685 file=item.destfile, 

686 error=item.error_text.decode('utf-8'))) 

687 retrieved_paths.append(item.destfile) 

688 

689 return retrieved_paths 

690 

691 def retrieve_source(self, source_name, version, 

692 debian_directory_only=False): 

693 """ 

694 Retrieve the source package files for the given source package version. 

695 

696 :param source_name: The name of the source package 

697 :type source_name: string 

698 :param version: The version of the source package 

699 :type version: string 

700 :param debian_directory_only: Flag indicating if the method should try 

701 to retrieve only the debian directory of the source package. This 

702 is usually only possible when the package format is 3.0 (quilt). 

703 :type debian_directory_only: Boolean 

704 

705 :returns: The path to the directory containing the extracted source 

706 package files. 

707 :rtype: string 

708 """ 

709 if self.cache_size > self.cache_max_size: 

710 # If the maximum allowed cache size has been exceeded, 

711 # clear the cache 

712 self.clear_cached_sources() 

713 

714 source_records = self._get_apt_source_records(source_name, version) 

715 

716 dest_dir_path = self.get_package_source_cache_directory(source_name) 

717 if not os.path.exists(dest_dir_path): 717 ↛ 720line 717 didn't jump to line 720, because the condition on line 717 was never false

718 os.makedirs(dest_dir_path) 

719 # Remember the size of the directory in the beginning 

720 old_size = self.get_directory_size(dest_dir_path) 

721 

722 # Download the source files 

723 retrieved_files = self._apt_acquire_package( 

724 source_records, dest_dir_path, debian_directory_only) 

725 

726 # Extract the retrieved source files 

727 outdir = self.get_source_version_cache_directory(source_name, version) 

728 # dpkg-source expects this directory not to exist 

729 self._remove_dir(outdir) 

730 

731 package_format = self._get_format(source_records.record) 

732 if debian_directory_only and package_format == self.QUILT_FORMAT: 732 ↛ 734line 732 didn't jump to line 734, because the condition on line 732 was never true

733 # dpkg-source cannot extract an incomplete package 

734 self._extract_quilt_package_debian_tar(retrieved_files[0], outdir) 

735 else: 

736 # Let dpkg-source handle the extraction in all other cases 

737 self._extract_dpkg_source(retrieved_files, outdir) 

738 

739 # Update the current cache size based on the changes made by getting 

740 # this source package. 

741 new_size = self.get_directory_size(dest_dir_path) 

742 size_delta = new_size - old_size 

743 self._cache_size += size_delta 

744 

745 return outdir 

746 

747 

748def html_package_list(packages): 

749 """Return a HTML-formatted list of packages.""" 

750 packages_html = [] 

751 for package in packages: 

752 if "/" in package: 

753 (source_package_name, remain) = package.split("/", 1) 

754 remain = "/%s" % (remain,) 

755 else: 

756 (source_package_name, remain) = (package, "") 

757 html = '<a href="{}">{}</a>{}'.format( 

758 package_url(source_package_name), source_package_name, remain) 

759 packages_html.append(html) 

760 

761 return ', '.join(packages_html)