Python typing.Text() Examples

The following are 30 code examples of typing.Text(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: files.py    From glazier with Apache License 2.0 8 votes vote down vote up
def Dump(path: Text, data: Any, mode: Text = 'w'):
  """Write a config file containing some data.

  Args:
    path: The filesystem path to the destination file.
    data: Data to be written to the file as yaml.
    mode: Mode to use for writing the file (default: w)
  """
  file_util.CreateDirectories(path)
  tmp_f = path + '.tmp'
  # Write to a .tmp file to avoid corrupting the original if aborted mid-way.
  try:
    with open(tmp_f, mode) as handle:
      handle.write(yaml.dump(data))
  except IOError as e:
    raise Error('Could not save data to yaml file %s: %s' % (path, str(e)))
  # Replace the original with the tmp.
  try:
    file_util.Move(tmp_f, path)
  except file_util.Error as e:
    raise Error('Could not replace config file. (%s)' % str(e)) 
Example #2
Source File: identifier.py    From glazier with Apache License 2.0 6 votes vote down vote up
def check_id() -> Text:
  """Call set_id if image identifier is not set and in WinPE.

  Check build_info (dumped via buildinfodump) in host if image_id does
  not exist.

  Returns:
    Image identifier as a string if already set.
  """
  image_id = None
  try:
    image_id = registry.get_value('image_id')
  except registry.Error as e:
    logging.error(str(e))

  if image_id:
    return image_id
  if winpe.check_winpe():
    return _set_id()

  return _check_file() 
Example #3
Source File: file_util.py    From glazier with Apache License 2.0 6 votes vote down vote up
def CreateDirectories(path: Text):
  """Create directory if the path to a file doesn't exist.

  Args:
    path: The full file path to where a file will be placed.

  Raises:
    Error: Failure creating the requested directory.
  """
  dirname = os.path.dirname(path)
  if not os.path.isdir(dirname):
    logging.debug('Creating directory %s ', dirname)
    try:
      os.makedirs(dirname)
    except (shutil.Error, OSError):
      raise Error('Unable to make directory: %s' % dirname) 
Example #4
Source File: beyondcorp.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _GetHash(self, file_path: Text) -> bytes:
    """Calculates the hash of the boot wim.

    Args:
      file_path: path to the file to be hashed

    Returns:
      hash of boot wim in hex
    """
    block_size = 33554432  # define bytes to read at a time when hashing (32mb)
    hasher = hashlib.sha256()

    with open(file_path, 'rb') as f:
      fb = f.read(block_size)
      while fb:
        hasher.update(fb)
        fb = f.read(block_size)
    return base64.b64encode(hasher.digest()) 
Example #5
Source File: title.py    From glazier with Apache License 2.0 6 votes vote down vote up
def set_title(string: Optional[Text] = None) -> Text:
  """Set the console title.

  Args:
    string: Optional string to add to the console title.

  Returns:
    Title as a string.
  """
  title = _build_title(string)
  try:
    os.system('title {}'.format(title))
    logging.debug('Set console title: %s', title)
    return title
  except OSError as e:
    raise Error('Failed to set console title: {}'.format(str(e))) 
Example #6
Source File: identity.py    From glazier with Apache License 2.0 6 votes vote down vote up
def set_hostname(hostname: Optional[Text] = None) -> Text:
  """Sets the hostname in the registry.

   Gets hostname from socket.hostname if no hostname is passed.

  Args:
    hostname: Value to set as the hostname in registry.

  Returns:
    hostname: The determined hostname.

  Raise:
    Error: Failed to set hostname in registry.
  """
  if not hostname:
    hostname = socket.gethostname()

  hostname = hostname.strip()

  try:
    registry.set_value('Name', hostname)
  except registry.Error as e:
    raise Error(str(e))

  return hostname 
Example #7
Source File: title.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _base_title() -> Optional[Text]:
  """Concatenate base values for the title based on build information.

  Returns:
    The base text for the title as a string.
  """
  build_info = buildinfo.BuildInfo()
  getid = build_info.ImageID()
  base = []

  if winpe.check_winpe():
    base.append('WinPE')
  if constants.FLAGS.config_root_path:
    base.append(constants.FLAGS.config_root_path.strip('/'))
  if getid:
    base.append(getid)

  # Convert list to a string, using map() to account for nonetypes
  return ' - '.join(map(str, base)) 
Example #8
Source File: file_util.py    From glazier with Apache License 2.0 6 votes vote down vote up
def Move(src: Text, dst: Text):
  """Move a file from src to dst.

  Python's os.rename doesn't support overwrite on Windows.

  Args:
    src: The full file path to the source.
    dst: The full file path to the destination.

  Raises:
    Error: Failure moving the file.
  """
  try:
    Remove(dst)
    os.rename(src, dst)
  except OSError as e:
    raise Error('Failure moving file from %s to %s. (%s)' % (src, dst, str(e))) 
Example #9
Source File: log_copy.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _EventLogUpload(self, source_log: Text):
    """Upload the log file contents to the local EventLog."""
    event_handler = logging.handlers.NTEventLogHandler('GlazierBuildLog')
    logger = logging.Logger('eventlogger')
    logger.addHandler(event_handler)
    logger.setLevel(logging.DEBUG)

    try:
      with open(source_log, 'r') as f:
        content = f.readlines()
        for line in content:
          logger.info(line)
    except IOError:
      raise LogCopyError(
          'Unable to open log file. It will not be imported into '
          'the Windows Event Log.') 
Example #10
Source File: log_copy.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _ShareUpload(self, source_log: Text, share: Text):
    """Copy the log file to a network file share.

    Args:
      source_log: Path to the source log file to be copied.
      share: The destination share to copy the file to.

    Raises:
      LogCopyError: Failure to mount share and copy log.
    """
    creds = LogCopyCredentials()
    username = creds.GetUsername()
    password = creds.GetPassword()

    mapper = drive_map.DriveMap()
    result = mapper.MapDrive('l:', share, username, password)
    if result:
      destination = self._GetLogFileName()
      try:
        shutil.copy(source_log, destination)
      except shutil.Error:
        raise LogCopyError('Log copy failed.')
      mapper.UnmapDrive('l:')
    else:
      raise LogCopyError('Drive mapping failed.') 
Example #11
Source File: identity.py    From glazier with Apache License 2.0 6 votes vote down vote up
def set_username(username: Optional[Text] = None,
                 prompt: Optional[Text] = None) -> Text:
  """Sets the username in the registry.

  Optionally prompts if there is no username supplied as a parameter.

  Args:
    username: Value to set as the username in registry.
    prompt: Custom string to append to username prompt.

  Returns:
    username: The determined username.

  Raises:
    Error: Failed to set username in registry.
  """
  if not username:
    username = interact.GetUsername(prompt)
  try:
    registry.set_value('Username', username)
  except registry.Error as e:
    raise Error(str(e))

  return username 
Example #12
Source File: interact.py    From glazier with Apache License 2.0 6 votes vote down vote up
def GetUsername(purpose: Optional[Text] = None) -> Text:
  """Prompt the user for their username.

  Args:
    purpose: Additional string to include when prompting for username.

  Returns:
    The username string entered by the user.
  """
  username = None

  prompt_string = 'Please enter your username: '
  if purpose:
    prompt_string = 'Please enter your username for {}: '.format(purpose)

  while not username:
    username = Prompt(prompt_string, validator='^[a-zA-Z0-9]+$')

  return username 
Example #13
Source File: files.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _YamlReader(path: Text) -> Text:
  """Read a configuration file and return the contents.

  Can be overloaded to read configs from different sources.

  Args:
    path: The config file name (eg build.yaml).

  Returns:
    The parsed content of the yaml file.
  """
  try:
    with open(path, 'r') as yaml_file:
      yaml_config = yaml.safe_load(yaml_file)
  except IOError as e:
    raise Error('Could not read yaml file %s: %s' % (path, str(e)))
  return yaml_config 
Example #14
Source File: files.py    From glazier with Apache License 2.0 6 votes vote down vote up
def Read(path: Text):
  """Read a config file at path and return any data it contains.

  Will attempt to download files from remote repositories prior to reading.

  Args:
    path: The path (either local or remote) to read from.

  Returns:
    The parsed YAML content from the file.

  Raises:
    Error: Failure retrieving a remote file or parsing file content.
  """
  if re.match('^http(s)?://', path):
    downloader = download.Download()
    try:
      path = downloader.DownloadFileTemp(path)
    except download.DownloadError as e:
      raise Error('Could not download yaml file %s: %s' % (path, str(e)))
  return _YamlReader(path) 
Example #15
Source File: download.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _ConvertBytes(self, num_bytes: int) -> Text:
    """Converts number of bytes to a human readable format.

    Args:
      num_bytes: The number to convert to a more human readable format (int).

    Returns:
      size: The number of bytes in human readable format (string).
    """
    num_bytes = float(num_bytes)
    if num_bytes >= 1099511627776:
      terabytes = num_bytes / 1099511627776
      size = '%.2fTB' % terabytes
    elif num_bytes >= 1073741824:
      gigabytes = num_bytes / 1073741824
      size = '%.2fGB' % gigabytes
    elif num_bytes >= 1048576:
      megabytes = num_bytes / 1048576
      size = '%.2fMB' % megabytes
    elif num_bytes >= 1024:
      kilobytes = num_bytes / 1024
      size = '%.2fKB' % kilobytes
    else:
      size = '%.2fB' % num_bytes
    return size 
Example #16
Source File: download.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _SetUrl(self, url: Text):
    """Simple helper function to determine signed URL.

    Args:
      url: the url we want to download from.

    Returns:
      A string with the applicable URLs

    Raises:
      DownloadError: Failed to obtain SignedURL.
    """
    if not FLAGS.use_signed_url:
      return url
    config_server = '%s%s' % (FLAGS.config_server, '/')
    try:
      return self._beyondcorp.GetSignedUrl(
          url[url.startswith(config_server) and len(config_server):])
    except beyondcorp.BCError as e:
      raise DownloadError(e) 
Example #17
Source File: files.py    From glazier with Apache License 2.0 6 votes vote down vote up
def Remove(path: Text, backup: bool = True):
  """Remove a config file.

  Args:
    path: The filesystem path to the file.
    backup: Whether to make a backup of the file being removed.

  Raises:
    Error: Failure performing the filesystem operation.
  """
  if backup:
    try:
      file_util.Move(path, path + '.bak')
    except file_util.Error as e:
      raise Error('Failed to create backup file (%s)' % str(e))
  else:
    try:
      file_util.Remove(path)
    except file_util.Error as e:
      raise Error('Failed to remove file (%s)' % str(e)) 
Example #18
Source File: buildinfo.py    From glazier with Apache License 2.0 6 votes vote down vote up
def ActiveConfigPath(self,
                       append: Optional[Text] = None,
                       pop: bool = False,
                       set_to: Optional[List[Text]] = None) -> List[Text]:
    """Tracks the active configuration path beneath the config root.

    Use append/pop for directory traversal.

    Args:
      append: Append a string to the active config path.
      pop: Pop the rightmost string from the active config path.
      set_to: Set the config path to an entirely new path.

    Returns:
      The active config path after any modifications.
    """
    if append:
      self._active_conf_path.append(append)
    elif set_to:
      self._active_conf_path = set_to
    elif pop and self._active_conf_path:
      self._active_conf_path.pop()
    return self._active_conf_path 
Example #19
Source File: device_model.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _ModelSupportPrompt(self, message: Text, this_model: Text) -> bool:
    """Prompts the user whether to halt an unsupported build.

    Args:
      message: A message to be displayed to the user.
      this_model: The hardware model that failed validation.

    Returns:
      true if the user wishes to proceed anyway, else false.
    """
    warning = message % this_model
    print(warning)
    answer = input('Do you still want to proceed (y/n)? ')
    answer_re = r'^[Yy](es)?$'
    if re.match(answer_re, answer):
      return True
    return False 
Example #20
Source File: powershell.py    From glazier with Apache License 2.0 6 votes vote down vote up
def RunLocal(self, path: Text, args: List[Text],
               ok_result: Optional[List[int]] = None) -> int:
    """Run a powershell script on the local filesystem.

    Args:
      path: a local filesystem path string
      args: a list of additional powershell arguments
      ok_result: a list of acceptable exit codes; default is 0

    Returns:
      Process returncode if successfully exited.

    Raises:
      PowerShellError: Invalid path supplied for execution.
    """
    if not os.path.exists(path):
      raise PowerShellError('Cannot find path to script. [%s]' % path)
    assert isinstance(args, list), 'args must be passed as a list'
    if ok_result:
      assert isinstance(ok_result,
                        list), 'result codes must be passed as a list'
    return self._LaunchPs('-File', [path] + args, ok_result) 
Example #21
Source File: powershell.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _GetResPath(self, path: Text) -> Text:
    """Translate an installer resource path into a local path.

    Args:
      path: the resource path string

    Raises:
      PowerShellError: unable to locate the requested resource

    Returns:
      The local filesystem path as a string.
    """
    r = resources.Resources()
    try:
      path = r.GetResourceFileName(path)
    except resources.FileNotFound as e:
      raise PowerShellError(e)
    return os.path.normpath(path) 
Example #22
Source File: powershell.py    From glazier with Apache License 2.0 6 votes vote down vote up
def RunCommand(self,
                 command: List[Text],
                 ok_result: Optional[List[int]] = None) -> int:
    """Run a powershell script on the local filesystem.

    Args:
      command: a list containing the command and all accompanying arguments
      ok_result: a list of acceptable exit codes; default is 0

    Returns:
      Process returncode if successfully exited.
    """
    assert isinstance(command, list), 'command must be passed as a list'
    if ok_result:
      assert isinstance(ok_result,
                        list), 'result codes must be passed as a list'
    return self._LaunchPs('-Command', command, ok_result) 
Example #23
Source File: buildinfo.py    From glazier with Apache License 2.0 6 votes vote down vote up
def EncryptionLevel(self) -> Text:
    """Determines what encryption level is required for this machine.

    Returns:
      The required encryption type as a string (none, tpm)
    """
    if self.IsVirtual():
      logging.info(
          'Virtual machine type %s does not require full disk '
          'encryption.', self.ComputerModel())
      return 'none'

    logging.info('Machine %s requires full disk encryption.',
                 self.ComputerModel())

    if self.TpmPresent():
      logging.info('TPM detected - using TPM encryption.')
      return 'tpm'

    logging.info('No TPM was detected in this machine.')
    return 'tpm' 
Example #24
Source File: powershell.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _LaunchPs(self, op: Text,
                args: List[Text],
                ok_result: Optional[List[int]] = None) -> int:
    """Launch the powershell executable to run a script.

    Args:
      op: -Command or -File
      args: any additional commandline args as a list
      ok_result: a list of acceptable exit codes; default is 0

    Returns:
      Process returncode if successfully exited.

    Raises:
      PowerShellError: failure to execute powershell command cleanly
    """
    if op not in ['-Command', '-File']:
      raise PowerShellError('Unsupported PowerShell parameter: %s' % op)

    try:
      return execute.execute_binary(_Powershell(),
                                    ['-NoProfile', '-NoLogo', op] + args,
                                    ok_result, self.shell, self.log)
    except execute.Error as e:
      raise PowerShellError(str(e)) 
Example #25
Source File: buildinfo.py    From glazier with Apache License 2.0 6 votes vote down vote up
def OsCode(self) -> Text:
    """Return the OS code associated with this build.

    Returns:
      the os code as a string

    Raises:
      Error: Reference to an unknown operating system.
    """
    os = self.ComputerOs()
    release_info = self._ReleaseInfo()
    if 'os_codes' in release_info:
      os_codes = release_info['os_codes']
      if os in os_codes:
        return os_codes[os]['code']
    raise Error('Unknown OS [%s]' % os) 
Example #26
Source File: buildinfo.py    From glazier with Apache License 2.0 6 votes vote down vote up
def Branch(self) -> Text:
    """Determine the current build branch.

    Returns:
      The build branch as a string.

    Raises:
      Error: Reference to an unknown operating system.
    """
    versions = self.KnownBranches()
    comp_os = self.ComputerOs()
    if not comp_os:
      raise Error('Unable to determine host OS.')
    if comp_os in versions:
      return versions[comp_os]
    raise Error('Unable to find a release that supports %s.' % comp_os) 
Example #27
Source File: download.py    From glazier with Apache License 2.0 6 votes vote down vote up
def Transform(string: Text, build_info) -> Text:
  r"""Transforms abbreviated file names to absolute file paths.

  Short name support:
    #: A reference to the active release branch location.
    @: A reference to the binary storage root.
    \#: Escaped # character - replaced by # in string
    \@: Escaped @ character - replaced by @ in string

  Args:
    string: The configuration string to be transformed.
    build_info: the current build information

  Returns:
    The adjusted file name string to be used in the manifest.
  """
  string = re.sub(r'(?<!\\)#', PathCompile(build_info) + '/', string)
  string = re.sub(r'\\#', '#', string)
  string = re.sub(r'(?<!\\)@', str(build_info.BinaryPath()), string)
  string = re.sub(r'\\@', '@', string)
  return string 
Example #28
Source File: stage.py    From glazier with Apache License 2.0 5 votes vote down vote up
def _load_time(stage_id: int, key: Text) -> Optional[datetime.datetime]:
  """Load a time string and convert it into a native datetime value."""
  val = None
  try:
    v = registry.get_value(key, 'HLKM', _stage_root(stage_id))
    if v:
      val = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
  except (registry.Error, ValueError) as e:
    logging.error(str(e))
    return None
  return val 
Example #29
Source File: stage.py    From glazier with Apache License 2.0 5 votes vote down vote up
def _stage_root(stage_id: int) -> Text:
  return r'%s\%d' % (STAGES_ROOT, stage_id) 
Example #30
Source File: files.py    From glazier with Apache License 2.0 5 votes vote down vote up
def _Run(self, command: Text, success_codes: List[int],
           reboot_codes: List[int], restart_retry: bool, shell: bool):
    logging.debug('Interpreting command: %s', command)
    try:
      command_cache = cache.Cache().CacheFromLine(command, self._build_info)
    except cache.CacheError as e:
      raise ActionError(e)

    try:
      command_list = shlex.split(command_cache, posix=False)
      result = execute.execute_binary(
          command_list[0],
          command_list[1:],
          success_codes + reboot_codes,
          shell=shell)
    except (execute.Error, ValueError) as e:
      raise ActionError(e)
    except KeyboardInterrupt:
      raise ActionError('KeyboardInterrupt detected, exiting.')

    if result in reboot_codes:
      raise RestartEvent(
          'Restart triggered by exit code: %d' % result,
          5,
          retry_on_restart=restart_retry)
    elif result not in success_codes:
      raise ActionError('Command returned invalid exit code: %d' % result)