code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self.parser.casename:
self.mountpoint = tempfile.mkdtemp(prefix='image_mounter_', suffix='_' + self.parser.casename)
else:
self.mountpoint = tempfile.mkdtemp(prefix='image_mounter_')
if self.read_write:
self.rwpath = tempfile.mkstemp(prefix="imag... | def mount(self) | Mounts the base image on a temporary location using the mount method stored in :attr:`method`. If mounting
was successful, :attr:`mountpoint` is set to the temporary mountpoint.
If :attr:`read_write` is enabled, a temporary read-write cache is also created and stored in :attr:`rwpath`.
:return... | 3.423876 | 3.300155 | 1.037489 |
if self.disk_mounter == 'dummy':
return self.paths[0]
else:
if self.disk_mounter == 'avfs' and os.path.isdir(os.path.join(self.mountpoint, 'avfs')):
logger.debug("AVFS mounted as a directory, will look in directory for (random) file.")
# ... | def get_raw_path(self) | Returns the raw path to the mounted disk image, i.e. the raw :file:`.dd`, :file:`.raw` or :file:`ewf1`
file.
:rtype: str | 5.801458 | 5.158538 | 1.124632 |
# prevent adding the same volumes twice
if self.volumes.has_detected:
for v in self.volumes:
yield v
elif single:
for v in self.volumes.detect_volumes(method='single'):
yield v
else:
# if single == False or si... | def detect_volumes(self, single=None) | Generator that detects the volumes from the Disk, using one of two methods:
* Single volume: the entire Disk is a single volume
* Multiple volumes: the Disk is a volume system
:param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`.
... | 5.774888 | 5.28632 | 1.092421 |
self.mount()
self.volumes.preload_volume_data()
for v in self.init_volumes(single, only_mount=only_mount, skip_mount=skip_mount,
swallow_exceptions=swallow_exceptions):
yield v | def init(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True) | Calls several methods required to perform a full initialisation: :func:`mount`, and
:func:`mount_volumes` and yields all detected volumes.
:param bool|None single: indicates whether the disk should be mounted as a single disk, not as a single disk or
whether it should try both (defaults to ... | 3.92217 | 4.230772 | 0.927058 |
for volume in self.detect_volumes(single=single):
for vol in volume.init(only_mount=only_mount, skip_mount=skip_mount,
swallow_exceptions=swallow_exceptions):
yield vol | def init_volumes(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True) | Generator that detects and mounts all volumes in the disk.
:param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`.
If *single* is False, only :func:`init_multiple_volumes` is called. If *single* is None,
:func:`init_multiple_... | 3.104377 | 3.008183 | 1.031978 |
volumes = []
for v in self.volumes:
volumes.extend(v.get_volumes())
return volumes | def get_volumes(self) | Gets a list of all volumes in this disk, including volumes that are contained in other volumes. | 4.627476 | 4.17642 | 1.108001 |
for m in list(sorted(self.volumes, key=lambda v: v.mountpoint or "", reverse=True)):
try:
m.unmount(allow_lazy=allow_lazy)
except ImageMounterError:
logger.warning("Error unmounting volume {0}".format(m.mountpoint))
if self._paths.get('n... | def unmount(self, remove_rw=False, allow_lazy=False) | Removes all ties of this disk to the filesystem, so the image can be unmounted successfully.
:raises SubsystemError: when one of the underlying commands fails. Some are swallowed.
:raises CleanupError: when actual cleanup fails. Some are swallowed. | 3.04306 | 2.938385 | 1.035623 |
self.argparser = ShellArgumentParser(prog='')
subparsers = self.argparser.add_subparsers()
for name in self.get_names():
if name.startswith('parser_'):
parser = subparsers.add_parser(name[7:])
parser.set_defaults(func=getattr(self, 'arg_' + n... | def _make_argparser(self) | Makes a new argument parser. | 3.547855 | 3.463702 | 1.024296 |
result = cmd.Cmd.complete(self, text, state)
if self.argparser_completer:
self._make_argparser()
# argparser screws up with internal states, this is the best way to fix it for now
return result | def complete(self, text, state) | Overridden to reset the argument parser after every completion (argcomplete fails :() | 11.51729 | 8.716505 | 1.32132 |
if any((line.startswith(x) for x in self.argparse_names())):
try:
args = self.argparser.parse_args(shlex.split(line))
except Exception: # intentionally catches also other errors in argparser
pass
else:
args.func(args)... | def default(self, line) | Overriding default to get access to any argparse commands we have specified. | 5.17459 | 4.224021 | 1.225039 |
if self.argparser_completer and any((line.startswith(x) for x in self.argparse_names())):
self.argparser_completer.rl_complete(line, 0)
return [x[begidx:] for x in self.argparser_completer._rl_matches]
else:
return [] | def completedefault(self, text, line, begidx, endidx) | Accessing the argcompleter if available. | 5.41195 | 4.655491 | 1.162488 |
return sorted(cmd.Cmd.completenames(self, text, *ignored) + self.argparse_names(text)) | def completenames(self, text, *ignored) | Patched to also return argparse commands | 7.6627 | 4.902021 | 1.563171 |
if not arg or arg not in self.argparse_names():
cmd.Cmd.do_help(self, arg)
else:
try:
self.argparser.parse_args([arg, '--help'])
except Exception:
pass | def do_help(self, arg) | Patched to show help for arparse commands | 4.237355 | 3.769278 | 1.124182 |
if header == self.doc_header:
cmds.extend(self.argparse_names())
cmd.Cmd.print_topics(self, header, sorted(cmds), cmdlen, maxcol) | def print_topics(self, header, cmds, cmdlen, maxcol) | Patched to show all argparse commands as being documented | 8.286711 | 5.556773 | 1.491281 |
if not self.parser:
self.stdout.write("Welcome to imagemounter {version}".format(version=__version__))
self.stdout.write("\n")
self.parser = ImageParser()
for p in self.args.paths:
self.onecmd('disk "{}"'.format(p)) | def preloop(self) | if the parser is not already set, loads the parser. | 8.774527 | 6.981205 | 1.256879 |
try:
return cmd.Cmd.onecmd(self, line)
except Exception as e:
print("Critical error.", e) | def onecmd(self, line) | Do not crash the entire program when a single command fails. | 5.804163 | 5.061087 | 1.146821 |
if self.parser:
return [v.index for v in self.parser.get_volumes()] + [d.index for d in self.parser.disks]
else:
return None | def _get_all_indexes(self) | Returns all indexes available in the parser | 6.837224 | 5.173821 | 1.321504 |
volume_or_disk = self.parser.get_by_index(index)
volume, disk = (volume_or_disk, None) if not isinstance(volume_or_disk, Disk) else (None, volume_or_disk)
return volume, disk | def _get_by_index(self, index) | Returns a volume,disk tuple for the specified index | 3.847314 | 2.711652 | 1.418808 |
if self.saved:
self.save()
else:
self.parser.clean()
return True | def do_quit(self, arg) | Quits the program. | 10.44766 | 10.647324 | 0.981248 |
commands = []
for mountpoint in self.find_bindmounts():
commands.append('umount {0}'.format(mountpoint))
for mountpoint in self.find_mounts():
commands.append('umount {0}'.format(mountpoint))
commands.append('rm -Rf {0}'.format(mountpoint))
f... | def preview_unmount(self) | Returns a list of all commands that would be executed if the :func:`unmount` method would be called.
Note: any system changes between calling this method and calling :func:`unmount` aren't listed by this command. | 2.395839 | 2.337148 | 1.025112 |
self.unmount_bindmounts()
self.unmount_mounts()
self.unmount_volume_groups()
self.unmount_loopbacks()
self.unmount_base_images()
self.clean_dirs() | def unmount(self) | Calls all unmount methods in the correct order. | 5.322516 | 4.012751 | 1.326401 |
# find all mountponits
self.mountpoints = {}
# noinspection PyBroadException
try:
result = _util.check_output_(['mount'])
for line in result.splitlines():
m = re.match(r'(.+) on (.+) type (.+) \((.+)\)', line)
if m:
... | def _index_mountpoints(self) | Finds all mountpoints and stores them in :attr:`mountpoints` | 3.309305 | 3.002944 | 1.10202 |
self.loopbacks = {}
try:
result = _util.check_output_(['losetup', '-a'])
for line in result.splitlines():
m = re.match(r'(.+): (.+) \((.+)\).*', line)
if m:
self.loopbacks[m.group(1)] = m.group(3)
except Except... | def _index_loopbacks(self) | Finds all loopbacks and stores them in :attr:`loopbacks` | 3.712945 | 3.166213 | 1.172677 |
for mountpoint, (orig, fs, opts) in self.mountpoints.items():
if 'bind' in opts and re.match(self.re_pattern, mountpoint):
yield mountpoint | def find_bindmounts(self) | Finds all bind mountpoints that are inside mounts that match the :attr:`re_pattern` | 6.072991 | 3.918559 | 1.549802 |
for mountpoint, (orig, fs, opts) in self.mountpoints.items():
if 'bind' not in opts and (re.match(self.orig_re_pattern, orig) or
(self.be_greedy and re.match(self.re_pattern, mountpoint))):
yield mountpoint | def find_mounts(self) | Finds all mountpoints that are mounted to a directory matching :attr:`re_pattern` or originate from a
directory matching :attr:`orig_re_pattern`. | 6.160474 | 4.28007 | 1.43934 |
for mountpoint, _ in self.mountpoints.items():
if re.match(self.orig_re_pattern, mountpoint):
yield mountpoint | def find_base_images(self) | Finds all mountpoints that are mounted to a directory matching :attr:`orig_re_pattern`. | 6.941245 | 2.645754 | 2.623541 |
os.environ['LVM_SUPPRESS_FD_WARNINGS'] = '1'
# find volume groups
try:
result = _util.check_output_(['pvdisplay'])
pvname = vgname = None
for line in result.splitlines():
if '--- Physical volume ---' in line:
pvna... | def find_volume_groups(self) | Finds all volume groups that are mounted through a loopback originating from :attr:`orig_re_pattern`.
Generator yields tuples of vgname, pvname | 4.682392 | 3.82539 | 1.22403 |
for dev, source in self.loopbacks.items():
if re.match(self.orig_re_pattern, source):
yield dev | def find_loopbacks(self) | Finds all loopbacks originating from :attr:`orig_re_pattern`.
Generator yields device names | 10.05457 | 3.672692 | 2.737657 |
for mountpoint in self.find_bindmounts():
_util.clean_unmount(['umount'], mountpoint, rmdir=False) | def unmount_bindmounts(self) | Unmounts all bind mounts identified by :func:`find_bindmounts` | 15.563695 | 12.424787 | 1.252633 |
for vgname, pvname in self.find_volume_groups():
_util.check_output_(['lvchange', '-a', 'n', vgname])
_util.check_output_(['losetup', '-d', pvname]) | def unmount_volume_groups(self) | Unmounts all volume groups and related loopback devices as identified by :func:`find_volume_groups` | 7.210212 | 6.009315 | 1.199839 |
# re-index loopback devices
self._index_loopbacks()
for dev in self.find_loopbacks():
_util.check_output_(['losetup', '-d', dev]) | def unmount_loopbacks(self) | Unmounts all loopback devices as identified by :func:`find_loopbacks` | 9.783625 | 7.921793 | 1.235027 |
for folder in glob.glob(self.glob_pattern):
if re.match(self.re_pattern, folder):
yield folder
for folder in glob.glob(self.orig_glob_pattern):
if re.match(self.orig_re_pattern, folder):
yield folder | def find_clean_dirs(self) | Finds all (temporary) directories according to the glob and re patterns that should be cleaned. | 3.120698 | 2.46238 | 1.267351 |
if is_encase(path):
return glob.glob(path[:-2] + '??') or [path]
ext_match = re.match(r'^.*\.(\d{2,})$', path)
if ext_match is not None:
ext_size = len(ext_match.groups()[-1])
return glob.glob(path[:-ext_size] + '[0-9]' * ext_size) or [path]
else:
return [path] | def expand_path(path) | Expand the given path to either an Encase image or a dd image
i.e. if path is '/path/to/image.E01' then the result of this method will be
/path/to/image.E*'
and if path is '/path/to/image.001' then the result of this method will be
'/path/to/image.[0-9][0-9]?' | 3.801884 | 3.199363 | 1.188326 |
if self.disks and self.disks[0].index is None:
raise DiskIndexError("First disk has no index.")
if force_disk_indexes or self.disks:
index = len(self.disks) + 1
else:
index = None
disk = Disk(self, path, index=str(index) if index else None, *... | def add_disk(self, path, force_disk_indexes=True, **args) | Adds a disk specified by the path to the ImageParser.
:param path: The path to the disk volume
:param force_disk_indexes: If true, always uses disk indexes. If False, only uses disk indexes if this is the
second volume you add. If you plan on using this method, always... | 2.968215 | 3.022512 | 0.982036 |
for d in self.disks:
for v in d.init(single, swallow_exceptions=swallow_exceptions):
yield v | def init(self, single=None, swallow_exceptions=True) | Handles all important disk-mounting tasks, i.e. calls the :func:`Disk.init` function on all underlying
disks. It yields every volume that is encountered, including volumes that have not been mounted.
:param single: indicates whether the :class:`Disk` should be mounted as a single disk, not as a single ... | 4.715405 | 3.672955 | 1.283818 |
result = True
for disk in self.disks:
result = disk.mount() and result
return result | def mount_disks(self) | Mounts all disks in the parser, i.e. calling :func:`Disk.mount` on all underlying disks. You probably want to
use :func:`init` instead.
:return: whether all mounts have succeeded
:rtype: bool | 5.503546 | 4.81517 | 1.14296 |
result = False
for disk in self.disks:
result = disk.rw_active() or result
return result | def rw_active(self) | Indicates whether a read-write cache is active in any of the disks.
:rtype: bool | 6.054905 | 6.271598 | 0.965449 |
for disk in self.disks:
logger.info("Mounting volumes in {0}".format(disk))
for volume in disk.init_volumes(single, only_mount, skip_mount, swallow_exceptions=swallow_exceptions):
yield volume | def init_volumes(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True) | Detects volumes (as volume system or as single volume) in all disks and yields the volumes. This calls
:func:`Disk.init_volumes` on all disks and should be called after :func:`mount_disks`.
:rtype: generator | 3.247103 | 2.694889 | 1.204912 |
try:
return self[index]
except KeyError:
for v in self.get_volumes():
if v.index == str(index):
return v
raise KeyError(index) | def get_by_index(self, index) | Returns a Volume or Disk by its index. | 5.131561 | 3.750006 | 1.368414 |
volumes = []
for disk in self.disks:
volumes.extend(disk.get_volumes())
return volumes | def get_volumes(self) | Gets a list of all volumes of all disks, concatenating :func:`Disk.get_volumes` of all disks.
:rtype: list | 4.525379 | 3.848653 | 1.175834 |
# To ensure clean unmount after reconstruct, we sort across all volumes in all our disks to provide a proper
# order
volumes = list(sorted(self.get_volumes(), key=lambda v: v.mountpoint or "", reverse=True))
for v in volumes:
try:
v.unmount(allow_laz... | def clean(self, remove_rw=False, allow_lazy=False) | Cleans all volumes of all disks (:func:`Volume.unmount`) and all disks (:func:`Disk.unmount`). Volume errors
are ignored, but returns immediately on disk unmount error.
:param bool remove_rw: indicates whether a read-write cache should be removed
:param bool allow_lazy: indicates whether lazy u... | 6.002317 | 5.383475 | 1.114952 |
while True:
try:
self.clean(remove_rw=remove_rw, allow_lazy=allow_lazy)
except ImageMounterError:
if retries == 0:
raise
retries -= 1
time.sleep(sleep_interval)
else:
... | def force_clean(self, remove_rw=False, allow_lazy=False, retries=5, sleep_interval=0.5) | Attempts to call the clean method, but will retry automatically if an error is raised. When the attempts
run out, it will raise the last error.
Note that the method will only catch :class:`ImageMounterError` exceptions.
:param bool remove_rw: indicates whether a read-write cache should be remo... | 2.601292 | 2.056216 | 1.265087 |
volumes = list(sorted((v for v in self.get_volumes() if v.mountpoint and v.info.get('lastmountpoint')),
key=lambda v: v.numeric_index))
try:
root = list(filter(lambda x: x.info.get('lastmountpoint') == '/', volumes))[0]
except IndexError:
... | def reconstruct(self) | Reconstructs the filesystem of all volumes mounted by the parser by inspecting the last mount point and
bind mounting everything.
:raises: NoRootFoundError if no root could be found
:return: the root :class:`Volume` | 3.926831 | 3.266293 | 1.202229 |
from imagemounter.volume import Volume
v = Volume(disk=self.disk, parent=self.parent,
volume_detector=self.volume_detector,
**args) # vstype is not passed down, let it decide for itself.
self.volumes.append(v)
return v | def _make_subvolume(self, **args) | Creates a subvolume, adds it to this class and returns it. | 11.052683 | 10.279642 | 1.075201 |
if only_one and self.volumes:
return self.volumes[0]
if self.parent.index is None:
index = '0'
else:
index = '{0}.0'.format(self.parent.index)
volume = self._make_subvolume(index=index, **args)
return volume | def _make_single_subvolume(self, only_one=True, **args) | Creates a subvolume, adds it to this class, sets the volume index to 0 and returns it.
:param bool only_one: if this volume system already has at least one volume, it is returned instead. | 3.232161 | 3.08889 | 1.046383 |
if self.has_detected and not force:
logger.warning("Detection already ran.")
return
if vstype is None:
vstype = self.vstype
if method is None:
method = self.volume_detector
if method == 'auto':
method = VolumeSystem._... | def detect_volumes(self, vstype=None, method=None, force=False) | Iterator for detecting volumes within this volume system.
:param str vstype: The volume system type to use. If None, uses :attr:`vstype`
:param str method: The detection method to use. If None, uses :attr:`detection`
:param bool force: Specify if you wnat to force running the detection if has_D... | 3.770405 | 3.373407 | 1.117684 |
if dependencies.pytsk3.is_available:
return 'pytsk3'
elif dependencies.mmls.is_available:
return 'mmls'
elif dependencies.parted.is_available:
return 'parted'
else:
raise PrerequisiteFailedError("No valid detection method is insta... | def _determine_auto_detection_method() | Return the detection method to use when the detection method is 'auto | 5.390986 | 5.414923 | 0.995579 |
if not _util.command_exists('disktype'):
logger.warning("disktype not installed, could not detect volume type")
return None
disktype = _util.check_output_(['disktype', self.parent.get_raw_path()]).strip()
current_partition = None
for line in disktype.s... | def _load_disktype_data(self) | Calls the :command:`disktype` command and obtains the disk GUID from GPT volume systems. As we
are running the tool anyway, the label is also extracted from the tool if it is not yet set.
The disktype data is only loaded and not assigned to volumes yet. | 3.790559 | 3.405648 | 1.113021 |
if slot is None:
slot = volume.slot
if slot in self._disktype:
data = self._disktype[slot]
if not volume.info.get('guid') and 'guid' in data:
volume.info['guid'] = data['guid']
if not volume.info.get('label') and 'label' in data:
... | def _assign_disktype_data(self, volume, slot=None) | Assigns cached disktype data to a volume. | 2.432521 | 2.316483 | 1.050092 |
if volume_system.parent.index is not None:
return '{0}.{1}'.format(volume_system.parent.index, idx)
else:
return str(idx) | def _format_index(self, volume_system, idx) | Returns a formatted index given the disk index idx. | 3.489008 | 3.099797 | 1.12556 |
volume = volume_system._make_single_subvolume(offset=0)
is_directory = os.path.isdir(volume_system.parent.get_raw_path())
if is_directory:
filesize = _util.check_output_(['du', '-scDb', volume_system.parent.get_raw_path()]).strip()
if filesize:
v... | def detect(self, volume_system, vstype='detect') | Detects' a single volume. It should not be called other than from a :class:`Disk`. | 4.743931 | 4.489628 | 1.056642 |
try:
# noinspection PyUnresolvedReferences
import pytsk3
except ImportError:
logger.error("pytsk3 not installed, could not detect volumes")
raise ModuleNotFoundError("pytsk3")
baseimage = None
try:
# ewf raw image is ... | def _find_volumes(self, volume_system, vstype='detect') | Finds all volumes based on the pytsk3 library. | 4.27192 | 4.185639 | 1.020614 |
# Loop over all volumes in image.
for p in self._find_volumes(volume_system, vstype):
import pytsk3
volume = volume_system._make_subvolume(
index=self._format_index(volume_system, p.addr),
offset=p.start * volume_system.disk.block_size,
... | def detect(self, volume_system, vstype='detect') | Generator that mounts every partition of this image and yields the mountpoint. | 3.45285 | 3.369584 | 1.024711 |
# for some reason, parted does not properly return extended volume types in its machine
# output, so we need to execute it twice.
meta_volumes = []
# noinspection PyBroadException
try:
output = _util.check_output_(['parted', volume_system.parent.get_raw_path... | def detect(self, volume_system, vstype='detect') | Finds and mounts all volumes based on parted.
:param VolumeSystem volume_system: The volume system. | 3.893568 | 3.844548 | 1.01275 |
try:
cmd = ['mmls']
if volume_system.parent.offset:
cmd.extend(['-o', str(volume_system.parent.offset // volume_system.disk.block_size)])
if vstype in ('dos', 'mac', 'bsd', 'sun', 'gpt'):
cmd.extend(['-t', vstype])
cmd.app... | def detect(self, volume_system, vstype='detect') | Finds and mounts all volumes based on mmls. | 3.86207 | 3.780603 | 1.021549 |
path = volume_system.parent._paths['vss']
try:
volume_info = _util.check_output_(["vshadowinfo", "-o", str(volume_system.parent.offset),
volume_system.parent.get_raw_path()])
except Exception as e:
logger.exception... | def detect(self, volume_system, vstype='detect') | Detect volume shadow copy volumes in the specified path. | 4.679695 | 4.322089 | 1.082739 |
volume_group = volume_system.parent.info.get('volume_group')
result = _util.check_output_(["lvm", "lvdisplay", volume_group])
cur_v = None
for l in result.splitlines():
if "--- Logical volume ---" in l:
cur_v = volume_system._make_subvolume(
... | def detect(self, volume_system, vstype='detect') | Gather information about lvolumes, gathering their label, size and raw path | 3.840878 | 3.695256 | 1.039408 |
if fstype:
self.fstype = fstype
elif self.index in self.disk.parser.fstypes:
self.fstype = self.disk.parser.fstypes[self.index]
elif '*' in self.disk.parser.fstypes:
self.fstype = self.disk.parser.fstypes['*']
elif '?' in self.disk.parser.fsty... | def _get_fstype_from_parser(self, fstype=None) | Load fstype information from the parser instance. | 2.607216 | 2.5332 | 1.029218 |
desc = ''
if with_size and self.size:
desc += '{0} '.format(self.get_formatted_size())
s = self.info.get('statfstype') or self.info.get('fsdescription') or '-'
if with_index:
desc += '{1}:{0}'.format(s, self.index)
else:
desc += s
... | def get_description(self, with_size=True, with_index=True) | Obtains a generic description of the volume, containing the file system type, index, label and NTFS version.
If *with_size* is provided, the volume size is also included. | 3.339628 | 3.097229 | 1.078263 |
if self.size is not None:
if self.size < 1024:
return "{0} B".format(self.size)
elif self.size < 1024 ** 2:
return "{0} KiB".format(round(self.size / 1024, 2))
elif self.size < 1024 ** 3:
return "{0} MiB".format(round(... | def get_formatted_size(self) | Obtains the size of the volume in a human-readable format (i.e. in TiBs, GiBs or MiBs). | 1.382214 | 1.320823 | 1.04648 |
try:
result = _util.check_output_(['blkid', '-p', '-O', str(self.offset), self.get_raw_path()])
if not result:
return None
# noinspection PyTypeChecker
blkid_result = dict(re.findall(r'([A-Z]+)="(.+?)"', result))
self.info['b... | def _get_blkid_type(self) | Retrieves the FS type from the blkid command. | 3.947992 | 3.724161 | 1.060102 |
try:
with io.open(self.disk.get_fs_path(), "rb") as file:
file.seek(self.offset)
fheader = file.read(min(self.size, 4096) if self.size else 4096)
except IOError:
logger.exception("Failed reading first 4K bytes from volume.")
r... | def _get_magic_type(self) | Checks the volume for its magic bytes and returns the magic. | 5.210046 | 4.87388 | 1.068973 |
v = self
if not include_self:
# lv / vss_store are exceptions, as it covers the volume itself, not the child volume
if v._paths.get('lv'):
return v._paths['lv']
elif v._paths.get('vss_store'):
return v._paths['vss_store']
... | def get_raw_path(self, include_self=False) | Retrieves the base mount path of the volume. Typically equals to :func:`Disk.get_fs_path` but may also be the
path to a logical volume. This is used to determine the source path for a mount call.
The value returned is normally based on the parent's paths, e.g. if this volume is mounted to a more specif... | 3.393597 | 2.972541 | 1.141649 |
if self.info.get('label') == '/':
return 'root'
suffix = re.sub(r"[/ \(\)]+", "_", self.info.get('label')) if self.info.get('label') else ""
if suffix and suffix[0] == '_':
suffix = suffix[1:]
if len(suffix) > 2 and suffix[-1] == '_':
suffix... | def get_safe_label(self) | Returns a label that is safe to add to a path in the mountpoint for this volume. | 3.784231 | 3.339215 | 1.13327 |
self._make_mountpoint(var_name='carve', suffix="carve", in_paths=True)
# if no slot, we need to make a loopback that we can use to carve the volume
loopback_was_created_for_carving = False
if not self.slot:
if not self.loopback:
self._find_loopback(... | def carve(self, freespace=True) | Call this method to carve the free space of the volume for (deleted) files. Note that photorec has its
own interface that temporarily takes over the shell.
:param freespace: indicates whether the entire volume should be carved (False) or only the free space (True)
:type freespace: bool
... | 4.378223 | 3.78976 | 1.155277 |
self._make_mountpoint(var_name='vss', suffix="vss", in_paths=True)
try:
_util.check_call_(["vshadowmount", "-o", str(self.offset), self.get_raw_path(), self._paths['vss']])
except Exception as e:
logger.exception("Failed mounting the volume shadow copies.")
... | def detect_volume_shadow_copies(self) | Method to call vshadowmount and mount NTFS volume shadow copies.
:return: iterable with the :class:`Volume` objects of the VSS
:raises CommandNotFoundError: if the underlying command does not exist
:raises SubSystemError: if the underlying command fails
:raises NoMountpointAvailableErro... | 11.09962 | 8.600528 | 1.290574 |
om = only_mount is None or \
self.index in only_mount or \
self.info.get('lastmountpoint') in only_mount or \
self.info.get('label') in only_mount
sm = skip_mount is None or \
(self.index not in skip_mount and
self.info.get('lastmoun... | def _should_mount(self, only_mount=None, skip_mount=None) | Indicates whether this volume should be mounted. Internal method, used by imount.py | 2.772496 | 2.642601 | 1.049154 |
if swallow_exceptions:
self.exception = None
try:
if not self._should_mount(only_mount, skip_mount):
yield self
return
if not self.init_volume():
yield self
return
except ImageMounterE... | def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True) | Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded,... | 2.89233 | 2.933365 | 0.986011 |
logger.debug("Initializing volume {0}".format(self))
if not self._should_mount():
return False
if self.flag != 'alloc':
return False
if self.info.get('raid_status') == 'waiting':
logger.info("RAID array %s not ready for mounting", self)
... | def init_volume(self, fstype=None) | Initializes a single volume. You should use this method instead of :func:`mount` if you want some sane checks
before mounting. | 4.31311 | 4.30521 | 1.001835 |
parser = self.disk.parser
if parser.mountdir and not os.path.exists(parser.mountdir):
os.makedirs(parser.mountdir)
if parser.pretty:
md = parser.mountdir or tempfile.gettempdir()
case_name = casename or self.disk.parser.casename or \
... | def _make_mountpoint(self, casename=None, var_name='mountpoint', suffix='', in_paths=False) | Creates a directory that can be used as a mountpoint. The directory is stored in :attr:`mountpoint`,
or the varname as specified by the argument. If in_paths is True, the path is stored in the :attr:`_paths`
attribute instead.
:returns: the mountpoint path
:raises NoMountpointAvailableE... | 2.909034 | 2.830109 | 1.027888 |
if self.mountpoint:
os.rmdir(self.mountpoint)
self.mountpoint = "" | def _clear_mountpoint(self) | Clears a created mountpoint. Does not unmount it, merely deletes it. | 3.499061 | 3.043404 | 1.14972 |
# noinspection PyBroadException
try:
loopback = _util.check_output_(['losetup', '-f']).strip()
setattr(self, var_name, loopback)
except Exception:
logger.warning("No free loopback device found.", exc_info=True)
raise NoLoopbackAvailableEr... | def _find_loopback(self, use_loopback=True, var_name='loopback') | Finds a free loopback device that can be used. The loopback is stored in :attr:`loopback`. If *use_loopback*
is True, the loopback will also be used directly.
:returns: the loopback address
:raises NoLoopbackAvailableError: if no loopback could be found | 4.008101 | 3.59362 | 1.115338 |
fstype_fallback = None
if isinstance(self.fstype, filesystems.FallbackFileSystemType):
fstype_fallback = self.fstype.fallback
elif isinstance(self.fstype, filesystems.FileSystemType):
return self.fstype
result = collections.Counter()
for source... | def determine_fs_type(self) | Determines the FS type for this partition. This function is used internally to determine which mount system
to use, based on the file system description. Return values include *ext*, *ufs*, *ntfs*, *lvm* and *luks*.
Note: does not do anything if fstype is already set to something sensible. | 4.224788 | 4.096986 | 1.031194 |
if not self.parent.is_mounted:
raise NotMountedError(self.parent)
if fstype is None:
fstype = self.determine_fs_type()
self._load_fsstat_data()
# Prepare mount command
try:
fstype.mount(self)
self.was_mounted = True
... | def mount(self, fstype=None) | Based on the file system type as determined by :func:`determine_fs_type`, the proper mount command is executed
for this volume. The volume is mounted in a temporary path (or a pretty path if :attr:`pretty` is enabled) in
the mountpoint as specified by :attr:`mountpoint`.
If the file system type... | 4.530112 | 3.833626 | 1.181678 |
if not self.mountpoint:
raise NotMountedError(self)
try:
_util.check_call_(['mount', '--bind', self.mountpoint, mountpoint], stdout=subprocess.PIPE)
if 'bindmounts' in self._paths:
self._paths['bindmounts'].append(mountpoint)
else... | def bindmount(self, mountpoint) | Bind mounts the volume to another mountpoint. Only works if the volume is already mounted.
:raises NotMountedError: when the volume is not yet mounted
:raises SubsystemError: when the underlying command failed | 3.493511 | 3.029454 | 1.153182 |
if self.volumes:
volumes = []
for v in self.volumes:
volumes.extend(v.get_volumes())
volumes.append(self)
return volumes
else:
return [self] | def get_volumes(self) | Recursively gets a list of all subvolumes and the current volume. | 3.148147 | 2.60864 | 1.206815 |
def stats_thread():
try:
cmd = ['fsstat', self.get_raw_path(), '-o', str(self.offset // self.disk.block_size)]
# Setting the fstype explicitly makes fsstat much faster and more reliable
# In some versions, the auto-detect yaffs2 check takes ... | def _load_fsstat_data(self, timeout=3) | Using :command:`fsstat`, adds some additional information of the volume to the Volume. | 2.711638 | 2.685838 | 1.009606 |
if self.info.get('lastmountpoint'):
return self.info.get('lastmountpoint')
if not self.mountpoint:
return None
result = None
paths = os.listdir(self.mountpoint)
if 'grub' in paths:
result = '/boot'
elif 'usr' in paths and 'va... | def detect_mountpoint(self) | Attempts to detect the previous mountpoint if this was not done through :func:`load_fsstat_data`. This
detection does some heuristic method on the mounted volume. | 2.225791 | 2.14032 | 1.039934 |
for volume in self.volumes:
try:
volume.unmount(allow_lazy=allow_lazy)
except ImageMounterError:
pass
if self.is_mounted:
logger.info("Unmounting volume %s", self)
if self.loopback and self.info.get('volume_group'):
... | def unmount(self, allow_lazy=False) | Unounts the volume from the filesystem.
:raises SubsystemError: if one of the underlying processes fails
:raises CleanupError: if the cleanup fails | 2.771661 | 2.719945 | 1.019014 |
# TODO: require(*requirements, none_on_failure=False) is not supported by Python 2
none_on_failure = kwargs.get('none_on_failure', False)
def inner(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for req in requirements:
if none_on_failure:
... | def require(*requirements, **kwargs) | Decorator that can be used to require requirements.
:param requirements: List of requirements that should be verified
:param none_on_failure: If true, does not raise a PrerequisiteFailedError, but instead returns None | 2.99337 | 3.053273 | 0.980381 |
if self.is_available:
return "INSTALLED {0!s}"
elif self.why and self.package:
return "MISSING {0!s:<20}needed for {0.why}, part of the {0.package} package"
elif self.why:
return "MISSING {0!s:<20}needed for {0.why}"
elif self.package:
... | def status_message(self) | Detailed message about whether the dependency is installed.
:rtype: str | 3.660285 | 3.423104 | 1.069288 |
if source == "guid" and description in self.guids:
return {self: 100}
description = description.lower()
if description == self.type:
return {self: 100}
elif re.search(r"\b" + self.type + r"\b", description):
return {self: 80}
elif an... | def detect(self, source, description) | Detects the type of a volume based on the provided information. It returns the plausibility for all
file system types as a dict. Although it is only responsible for returning its own plausibility, it is possible
that one type of filesystem is more likely than another, e.g. when NTFS detects it is likely... | 3.164706 | 3.066262 | 1.032105 |
volume._make_mountpoint()
try:
self._call_mount(volume, volume.mountpoint, self._mount_type or self.type, self._mount_opts)
except Exception:
# undo the creation of the mountpoint
volume._clear_mountpoint()
raise | def mount(self, volume) | Mounts the given volume on the provided mountpoint. The default implementation simply calls mount.
:param Volume volume: The volume to be mounted
:param mountpoint: The file system path to mount the filesystem on.
:raises UnsupportedFilesystemError: when the volume system type can not be mounte... | 5.867062 | 6.185219 | 0.948562 |
# default arguments for calling mount
if opts and not opts.endswith(','):
opts += ","
opts += 'loop,offset=' + str(volume.offset) + ',sizelimit=' + str(volume.size)
# building the command
cmd = ['mount', volume.get_raw_path(), mountpoint, '-o', opts]
... | def _call_mount(self, volume, mountpoint, type=None, opts="") | Calls the mount command, specifying the mount type and mount options. | 4.805867 | 4.80627 | 0.999916 |
# we have to make a ram-device to store the image, we keep 20% overhead
size_in_kb = int((volume.size / 1024) * 1.2)
_util.check_call_(['modprobe', '-v', 'mtd'])
_util.check_call_(['modprobe', '-v', 'jffs2'])
_util.check_call_(['modprobe', '-v', 'mtdram', 'total_size={}'... | def mount(self, volume) | Perform specific operations to mount a JFFS2 image. This kind of image is sometimes used for things like
bios images. so external tools are required but given this method you don't have to memorize anything and it
works fast and easy.
Note that this module might not yet work while mounting mult... | 3.855253 | 3.865314 | 0.997397 |
# Open a loopback device
volume._find_loopback()
# Check if this is a LUKS device
# noinspection PyBroadException
try:
_util.check_call_(["cryptsetup", "isLuks", volume.loopback], stderr=subprocess.STDOUT)
# ret = 0 if isLuks
except Exce... | def mount(self, volume) | Command that is an alternative to the :func:`mount` command that opens a LUKS container. The opened volume is
added to the subvolume set of this volume. Requires the user to enter the key manually.
TODO: add support for :attr:`keys`
:return: the Volume contained in the LUKS container, or None ... | 3.846443 | 3.537161 | 1.087438 |
volume._paths['bde'] = tempfile.mkdtemp(prefix='image_mounter_bde_')
try:
if volume.key:
t, v = volume.key.split(':', 1)
key = ['-' + t, v]
else:
logger.warning("No key material provided for %s", volume)
k... | def mount(self, volume) | Mounts a BDE container. Uses key material provided by the :attr:`keys` attribute. The key material should be
provided in the same format as to :cmd:`bdemount`, used as follows:
k:full volume encryption and tweak key
p:passphrase
r:recovery password
s:file to startup key (.bek)
... | 6.21613 | 5.102345 | 1.218289 |
os.environ['LVM_SUPPRESS_FD_WARNINGS'] = '1'
# find free loopback device
volume._find_loopback()
time.sleep(0.2)
try:
# Scan for new lvm volumes
result = _util.check_output_(["lvm", "pvscan"])
for l in result.splitlines():
... | def mount(self, volume) | Performs mount actions on a LVM. Scans for active volume groups from the loopback device, activates it
and fills :attr:`volumes` with the logical volumes.
:raises NoLoopbackAvailableError: when no loopback was available
:raises IncorrectFilesystemError: when the volume is not a volume group | 6.882528 | 5.829298 | 1.180679 |
volume._find_loopback()
raid_status = None
try:
# use mdadm to mount the loopback to a md device
# incremental and run as soon as available
output = _util.check_output_(['mdadm', '-IR', volume.loopback], stderr=subprocess.STDOUT)
match ... | def mount(self, volume) | Add the volume to a RAID system. The RAID array is activated as soon as the array can be activated.
:raises NoLoopbackAvailableError: if no loopback device was found | 4.900849 | 4.868093 | 1.006729 |
def sub(m):
c = m.group()
if c in CHAR_ESCAPE:
return CHAR_ESCAPE[c]
if c.isspace():
if fold_newlines:
return r'\\'
return r'\\[{}\baselineskip]'.format(len(c))
return ESCAPE_RE.sub(sub, s) | def escape(s, fold_newlines=True) | Escapes a string to make it usable in LaTeX text mode. Will replace
special characters as well as newlines.
Some problematic characters like ``[`` and ``]`` are escaped into groups
(e.g. ``{[}``), because they tend to cause problems when mixed with ``\\``
newlines otherwise.
:param s: The string t... | 4.699237 | 3.554607 | 1.322013 |
if builder is None:
builders = PREFERRED_BUILDERS
elif builder not in BUILDERS:
raise RuntimeError('Invalid Builder specified')
else:
builders = (builder, )
for bld in builders:
bld_cls = BUILDERS[bld]
builder = bld_cls()
if not builder.is_available(... | def build_pdf(source, texinputs=[], builder=None) | Builds a LaTeX source to PDF.
Will automatically instantiate an available builder (or raise a
:class:`exceptions.RuntimeError` if none are available) and build the
supplied source with it.
Parameters are passed on to the builder's
:meth:`~latex.build.LatexBuilder.build_pdf` function.
:param b... | 3.515213 | 3.194221 | 1.100492 |
lines = log.splitlines()
errors = []
for n, line in enumerate(lines):
m = LATEX_ERR_RE.match(line)
if m:
err = m.groupdict().copy()
err['context'] = lines[n:n + context_size]
try:
err['line'] = int(err['line'])
except Type... | def parse_log(log, context_size=3) | Parses latex log output and tries to extract error messages.
Requires ``-file-line-error`` to be active.
:param log: The contents of the logfile as a string.
:param context_size: Number of lines to keep as context, including the
original error line.
:return: A dictionary conta... | 3.224306 | 3.036336 | 1.061907 |
ka = ENV_ARGS.copy()
ka.update(kwargs)
env = Environment(*args, **ka)
env.filters['e'] = LatexMarkup.escape
env.filters['escape'] = LatexMarkup.escape
env.filters['forceescape'] = LatexMarkup.escape # FIXME: this is a bug
return env | def make_env(*args, **kwargs) | Creates an :py:class:`~jinja2.Environment` with different defaults.
Per default, ``autoescape`` will be disabled and ``trim_blocks`` enabled.
All start/end/prefix strings will be changed for a more LaTeX-friendly
version (see the docs for details).
Any arguments will be passed on to the :py:class:`~ji... | 6.369131 | 4.525861 | 1.407275 |
params = {}
metadata = {}
for header_name in headers:
if header_name.lower() in header_mapping:
params[header_mapping[header_name.lower()]] = headers[header_name]
else:
metadata[header_name] = headers[header_name]
return metadata, params | def split_metadata_params(headers) | Given a dict of headers for s3, seperates those that are boto3
parameters and those that must be metadata | 2.257584 | 2.251557 | 1.002677 |
hasher = hashlib.sha1()
with open(filename, 'rb') as f:
buf = f.read(65536)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(65536)
return hasher.hexdigest() | def hash_file(filename) | Generate a hash for the contents of a file | 1.430043 | 1.46083 | 0.978925 |
app = current_app
# manage other special values, all have no meaning for static urls
values.pop('_external', False) # external has no meaning here
values.pop('_anchor', None) # anchor as well
values.pop('_method', None) # method too
url_style = get_setting('FLASKS3_URL_STYLE', app)
... | def _get_bucket_name(**values) | Generates the bucket name for url_for. | 3.531531 | 3.39083 | 1.041495 |
app = current_app
if app.config.get('TESTING', False) and not app.config.get('FLASKS3_OVERRIDE_TESTING', True):
return flask_url_for(endpoint, **values)
if 'FLASKS3_BUCKET_NAME' not in app.config:
raise ValueError("FLASKS3_BUCKET_NAME not found in app configuration.")
if endpoint =... | def url_for(endpoint, **values) | Generates a URL to the given endpoint.
If the endpoint is for a static resource then an Amazon S3 URL is
generated, otherwise the call is passed on to `flask.url_for`.
Because this function is set as a jinja environment variable when
`FlaskS3.init_app` is invoked, this function replaces
`flask.url... | 3.226475 | 3.448186 | 0.935702 |
u = six.u('%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or ''))
return u | def _bp_static_url(blueprint) | builds the absolute url path for a blueprint's static folder | 4.694875 | 4.985202 | 0.941762 |
dirs = [(six.text_type(app.static_folder), app.static_url_path)]
if hasattr(app, 'blueprints'):
blueprints = app.blueprints.values()
bp_details = lambda x: (x.static_folder, _bp_static_url(x))
dirs.extend([bp_details(x) for x in blueprints if x.static_folder])
valid_files = def... | def _gather_files(app, hidden, filepath_filter_regex=None) | Gets all files in static folders and returns in dict. | 3.279936 | 3.145839 | 1.042627 |
# first get the asset path relative to the static folder.
# static_asset is not simply a filename because it could be
# sub-directory then file etc.
if not static_asset.startswith(static_folder):
raise ValueError("%s static asset must be under %s static folder" %
(s... | def _static_folder_path(static_url, static_folder, static_asset) | Returns a path to a file based on the static folder, and not on the
filesystem holding the file.
Returns a path relative to static_url for static_asset | 4.935503 | 5.180254 | 0.952753 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.