logo

live-bootstrap

Mirror of <https://github.com/fosslinux/live-bootstrap>

utils.py (2373B)


  1. #!/usr/bin/env python3
  2. """
  3. This file contains a few self-contained helper functions
  4. """
  5. # SPDX-License-Identifier: GPL-3.0-or-later
  6. # SPDX-FileCopyrightText: 2021 Andrius Štikonas <andrius@stikonas.eu>
  7. # SPDX-FileCopyrightText: 2021-23 fosslinux <fosslinux@aussies.space>
  8. import os
  9. import shutil
  10. import subprocess
  11. import sys
  12. def run(*args, **kwargs):
  13. """A small wrapper around subprocess.run"""
  14. arguments = [str(arg) for arg in args if arg is not None]
  15. if kwargs.pop('verbose', False):
  16. print(arguments)
  17. try:
  18. return subprocess.run(arguments, check=True, **kwargs)
  19. except subprocess.CalledProcessError:
  20. print("Bootstrapping failed")
  21. sys.exit(1)
  22. def run_as_root(*args, **kwargs):
  23. """A helper for run that invokes sudo when unprivileged"""
  24. if os.geteuid() != 0:
  25. return run("sudo", *args, **kwargs)
  26. return run(*args, **kwargs)
  27. # pylint: disable=too-many-arguments,too-many-positional-arguments
  28. def create_disk(image, disk_type, fs_type, size, bootable=False, mkfs_args=None):
  29. """Create a disk image, with a filesystem on it"""
  30. if mkfs_args is None:
  31. mkfs_args = []
  32. run('truncate', '-s', size, image)
  33. # Create the partition
  34. if disk_type != "none":
  35. # 1 GiB if bootable, 1 MiB otherwise
  36. offset = str(1024 * 1024 * (1024 if bootable else 1))
  37. run('parted', '--script', image, 'mklabel', disk_type, 'mkpart',
  38. 'primary', fs_type, offset + 'B', '100%')
  39. run('mkfs.' + fs_type, image, '-E', 'offset=' + offset, *mkfs_args)
  40. def mount(source, target, fs_type, options='', **kwargs):
  41. """Mount filesystem"""
  42. run_as_root('mount', source, target, '-t', fs_type, '-o', options, **kwargs)
  43. def umount(target, **kwargs):
  44. """Unmount filesystem"""
  45. run_as_root('umount', '--recursive', target, **kwargs)
  46. def copytree(src, dst, ignore=shutil.ignore_patterns('*.git*')):
  47. """Copy directory tree into another directory"""
  48. if not os.path.exists(dst):
  49. os.makedirs(dst)
  50. lst = os.listdir(src)
  51. if ignore:
  52. excl = ignore(src, lst)
  53. lst = [x for x in lst if x not in excl]
  54. for item in lst:
  55. source = os.path.join(src, item)
  56. dest = os.path.join(dst, item)
  57. if os.path.isdir(source):
  58. copytree(source, dest, ignore)
  59. else:
  60. shutil.copy2(source, dest)