def _logger_add_file_handler(logger, log_paths):
  """
  If the first log path in `log_paths` cannot be used (e.g. due to denied write
  permission), try out subsequent paths.
  
  Do not log if directories cannot be created or any of the log files cannot be
  created.
  """
  
  can_log = True
  for log_path in log_paths:
    try:
      pgpath.make_dirs(os.path.dirname(log_path))
    except OSError:
      can_log = False
      break
    
    try:
      logger.addHandler(logging.FileHandler(log_path))
    except (OSError, IOError):
      if log_path == log_paths[-1]:
        can_log = False
    else:
      break
  
  return can_log
def _logger_add_file_handler(logger, log_paths):
    """
  If the first log path in `log_paths` cannot be used (e.g. due to denied write
  permission), try out subsequent paths.
  
  Do not log if directories cannot be created or any of the log files cannot be
  created.
  """

    can_log = True
    for log_path in log_paths:
        try:
            pgpath.make_dirs(os.path.dirname(log_path))
        except OSError:
            can_log = False
            break

        try:
            logger.addHandler(logging.FileHandler(log_path))
        except (OSError, IOError):
            if log_path == log_paths[-1]:
                can_log = False
        else:
            break

    return can_log
    def _export(self, image, layer, output_filename):
        run_mode = self._get_run_mode()
        pgpath.make_dirs(os.path.dirname(output_filename))

        self._export_once(run_mode, image, layer, output_filename)

        if self._current_layer_export_status == self._FORCE_INTERACTIVE:
            self._export_once(gimpenums.RUN_INTERACTIVE, image, layer, output_filename)
Пример #4
0
    def _export(self, image, layer, output_filename):
        run_mode = self._get_run_mode()
        pgpath.make_dirs(os.path.dirname(output_filename))

        self._export_once(run_mode, image, layer, output_filename)

        if self._current_layer_export_status == self._FORCE_INTERACTIVE:
            self._export_once(gimpenums.RUN_INTERACTIVE, image, layer,
                              output_filename)
    def _export_layers(self):
        with self._layer_data.filter['layer_types'].remove_rule_temp(
                LayerFilterRules.is_empty_group, raise_if_not_found=False):
            self.progress_updater.num_total_tasks = len(self._layer_data)

        pgpath.make_dirs(self._output_directory)

        for layer_elem in self._layer_data:
            if self.should_stop:
                raise ExportLayersCancelError("export stopped by user")

            if layer_elem.item_type in (layer_elem.ITEM,
                                        layer_elem.NONEMPTY_GROUP):
                layer = layer_elem.item
                layer_copy = self._process_layer(layer)
                # Remove the " copy" suffix from the layer name, which is preserved in
                # formats supporting layers (XCF, PSD, ...).
                layer_copy.name = layer.name

                layer_elem.validate_name()
                self._strip_file_extension(layer_elem)

                self._set_file_extension_and_update_file_export_func(
                    layer_elem)
                self._layer_data.uniquify_name(
                    layer_elem, self._include_item_path,
                    self._get_uniquifier_position(layer_elem.name))
                self._export_layer(layer_elem, self._image_copy, layer_copy)

                if self._current_layer_export_status == self._USE_DEFAULT_FILE_EXTENSION:
                    self._set_file_extension_and_update_file_export_func(
                        layer_elem)
                    self._layer_data.uniquify_name(
                        layer_elem, self._include_item_path,
                        self._get_uniquifier_position(layer_elem.name))
                    self._export_layer(layer_elem, self._image_copy,
                                       layer_copy)

                self.progress_updater.update_tasks(1)
                if not self._is_current_layer_skipped:
                    # Append the original layer, not the copy, since the copy is going to
                    # be destroyed.
                    self._exported_layers.append(layer)
                    self._file_extension_properties[
                        self._current_file_extension].processed_count += 1
                pdb.gimp_image_remove_layer(self._image_copy, layer_copy)
            elif layer_elem.item_type == layer_elem.EMPTY_GROUP:
                layer_elem.validate_name()
                self._layer_data.uniquify_name(layer_elem,
                                               self._include_item_path)
                empty_directory = layer_elem.get_filepath(
                    self._output_directory, self._include_item_path)
                pgpath.make_dirs(empty_directory)
            else:
                raise ValueError(
                    "invalid/unsupported item type '{0}' of _ItemDataElement '{1}'"
                    .format(layer_elem.item_type, layer_elem.name))
Пример #6
0
    def _export_layers(self):
        with self._layer_data.filter.get_subfilter(
                'layer_types').remove_rule_temp(
                    LayerFilterRules.is_empty_group, raise_if_not_found=False):
            self.progress_updater.num_total_tasks = len(self._layer_data)

        pgpath.make_dirs(self._output_directory)

        for layer_elem in self._layer_data:
            if self.should_stop:
                raise ExportLayersCancelError("export stopped by user")

            if layer_elem.item_type in (layer_elem.ITEM,
                                        layer_elem.NONEMPTY_GROUP):
                layer = layer_elem.item
                layer_copy = self._process_layer(layer)

                layer_elem.validate_name()
                self._strip_file_extension(layer_elem)
                self._set_file_extension_and_update_file_export_func(
                    layer_elem)
                self._layer_data.uniquify_name(
                    layer_elem,
                    self._include_item_path,
                    place_before_file_extension=True)

                self._export_layer(layer_elem, self._image_copy, layer_copy)
                if self._current_layer_export_status == self._USE_DEFAULT_FILE_EXTENSION:
                    self._set_file_extension_and_update_file_export_func(
                        layer_elem)
                    self._layer_data.uniquify_name(
                        layer_elem,
                        self._include_item_path,
                        place_before_file_extension=True)
                    self._export_layer(layer_elem, self._image_copy,
                                       layer_copy)

                self.progress_updater.update_tasks(1)
                if not self._is_current_layer_skipped:
                    # Append the original layer, not the copy, since the copy is going to
                    # be destroyed.
                    self._exported_layers.append(layer)
                    self._layer_file_extension_properties[
                        self._current_file_extension].processed_count += 1
                pdb.gimp_image_remove_layer(self._image_copy, layer_copy)
            else:
                layer_elem.validate_name()
                self._layer_data.uniquify_name(
                    layer_elem,
                    self._include_item_path,
                    place_before_file_extension=False)
                empty_directory = layer_elem.get_filepath(
                    self._output_directory, self._include_item_path)
                pgpath.make_dirs(empty_directory)
    def _export_layers(self):
        with self._layer_data.filter["layer_types"].remove_rule_temp(
            LayerFilterRules.is_empty_group, raise_if_not_found=False
        ):
            self.progress_updater.num_total_tasks = len(self._layer_data)

        pgpath.make_dirs(self._output_directory)

        for layer_elem in self._layer_data:
            if self.should_stop:
                raise ExportLayersCancelError("export stopped by user")

            if layer_elem.item_type in (layer_elem.ITEM, layer_elem.NONEMPTY_GROUP):
                layer = layer_elem.item
                layer_copy = self._process_layer(layer)
                # Remove the " copy" suffix from the layer name, which is preserved in
                # formats supporting layers (XCF, PSD, ...).
                layer_copy.name = layer.name

                layer_elem.validate_name()
                self._strip_file_extension(layer_elem)

                self._set_file_extension_and_update_file_export_func(layer_elem)
                self._layer_data.uniquify_name(
                    layer_elem, self._include_item_path, self._get_uniquifier_position(layer_elem.name)
                )
                self._export_layer(layer_elem, self._image_copy, layer_copy)

                if self._current_layer_export_status == self._USE_DEFAULT_FILE_EXTENSION:
                    self._set_file_extension_and_update_file_export_func(layer_elem)
                    self._layer_data.uniquify_name(
                        layer_elem, self._include_item_path, self._get_uniquifier_position(layer_elem.name)
                    )
                    self._export_layer(layer_elem, self._image_copy, layer_copy)

                self.progress_updater.update_tasks(1)
                if not self._is_current_layer_skipped:
                    # Append the original layer, not the copy, since the copy is going to
                    # be destroyed.
                    self._exported_layers.append(layer)
                    self._file_extension_properties[self._current_file_extension].processed_count += 1
                pdb.gimp_image_remove_layer(self._image_copy, layer_copy)
            elif layer_elem.item_type == layer_elem.EMPTY_GROUP:
                layer_elem.validate_name()
                self._layer_data.uniquify_name(layer_elem, self._include_item_path)
                empty_directory = layer_elem.get_filepath(self._output_directory, self._include_item_path)
                pgpath.make_dirs(empty_directory)
            else:
                raise ValueError(
                    "invalid/unsupported item type '{0}' of _ItemDataElement '{1}'".format(
                        layer_elem.item_type, layer_elem.name
                    )
                )
Пример #8
0
 def _make_dirs(self, path):
   try:
     pgpath.make_dirs(path)
   except OSError as e:
     try:
       message = e.args[1]
       if e.filename is not None:
         message += ": \"{0}\"".format(e.filename)
     except (IndexError, AttributeError):
       message = str(e)
     
     raise InvalidOutputDirectoryError(message, self._current_layer_elem, self._default_file_extension)
def make_package(input_directory, output_file, version):
  
  def _set_permissions(path, perms):
    """
    Set file permissions on all files and subdirectories in a given path.
    """
    
    if os.name == "nt":
      _print_program_message("Warning: Cannot set Unix-style permissions on Windows", sys.stderr)
      return
    
    for root, dirs, files in os.walk(path):
      for dir_ in dirs:
        os.chmod(os.path.join(root, dir_), perms)
      for file_ in files:
        os.chmod(os.path.join(root, file_), perms)
  
  def _generate_pot_file(source_dir, version):
    if os.name == "nt":
      _print_program_message("Warning: Cannot generate .pot file on Windows", sys.stderr)
      return
    
    for file_ in os.listdir(source_dir):
      if os.path.isfile(os.path.join(source_dir, file_)):
        if file_.endswith(".pot"):
          os.remove(os.path.join(source_dir, file_))
     
    orig_cwd = os.getcwdu()
    os.chdir(source_dir)
    subprocess.call(["./generate_pot.sh", version])
    os.chdir(orig_cwd)
  
  _generate_pot_file(constants.LOCALE_PATH, version)
  
  files = _get_filtered_files(input_directory, INCLUDE_LIST_FILENAME)
  files_relative_paths = [file_[len(input_directory) + 1:] for file_ in files]
  
  for i, rel_file_path in enumerate(files_relative_paths):
    filename = os.path.basename(rel_file_path)
    if filename in FILENAMES_TO_RENAME:
      files_relative_paths[i] = os.path.join(os.path.dirname(rel_file_path), FILENAMES_TO_RENAME[filename])
  
  temp_dir = tempfile.mkdtemp()
  temp_files = [os.path.join(temp_dir, file_rel_path) for file_rel_path in files_relative_paths]
  
  for src_file, temp_file in zip(files, temp_files):
    dirname = os.path.dirname(temp_file)
    if not os.path.exists(dirname):
      pgpath.make_dirs(dirname)
    shutil.copy2(src_file, temp_file)
  
  _set_permissions(temp_dir, 0o755)
  
  for temp_file in temp_files:
    filename = os.path.basename(temp_file)
    if filename in FILES_TO_PROCESS:
      process_file(temp_file, *FILES_TO_PROCESS[filename])
  
  with zipfile.ZipFile(output_file, "w", zipfile.ZIP_STORED) as zip_file:
    for temp_file, file_ in zip(temp_files, files_relative_paths):
      zip_file.write(temp_file, file_)
  
  shutil.rmtree(temp_dir)
Пример #10
0
def make_package(input_directory, output_file, version):
  
  def _set_permissions(path, perms):
    """
    Set file permissions on all files and subdirectories in a given path.
    """
    
    if os.name == "nt":
      _print_program_message("Warning: Cannot set Unix-style permissions on Windows", sys.stderr)
      return
    
    for root, dirs, files in os.walk(path):
      for dir_ in dirs:
        os.chmod(os.path.join(root, dir_), perms)
      for file_ in files:
        os.chmod(os.path.join(root, file_), perms)
  
  def _generate_pot_file(source_dir, version):
    if os.name == "nt":
      _print_program_message("Warning: Cannot generate .pot file on Windows", sys.stderr)
      return
    
    for file_ in os.listdir(source_dir):
      if os.path.isfile(os.path.join(source_dir, file_)):
        if file_.endswith(".pot"):
          os.remove(os.path.join(source_dir, file_))
     
    orig_cwd = os.getcwdu()
    os.chdir(source_dir)
    subprocess.call(["./generate_pot.sh", version])
    os.chdir(orig_cwd)
  
  _generate_pot_file(pygimplib.config.LOCALE_PATH, version)
  
  files = _get_filtered_files(input_directory, INCLUDE_LIST_FILENAME)
  files_relative_paths = [file_[len(input_directory) + 1:] for file_ in files]
  
  for i, rel_file_path in enumerate(files_relative_paths):
    filename = os.path.basename(rel_file_path)
    if filename in FILENAMES_TO_RENAME:
      files_relative_paths[i] = os.path.join(os.path.dirname(rel_file_path), FILENAMES_TO_RENAME[filename])
  
  temp_dir = tempfile.mkdtemp()
  temp_files = [os.path.join(temp_dir, file_rel_path) for file_rel_path in files_relative_paths]
  
  for src_file, temp_file in zip(files, temp_files):
    dirname = os.path.dirname(temp_file)
    if not os.path.exists(dirname):
      pgpath.make_dirs(dirname)
    shutil.copy2(src_file, temp_file)
  
  _set_permissions(temp_dir, 0o755)
  
  for temp_file in temp_files:
    filename = os.path.basename(temp_file)
    if filename in FILES_TO_PROCESS:
      process_file(temp_file, *FILES_TO_PROCESS[filename])
  
  with zipfile.ZipFile(output_file, "w", zipfile.ZIP_STORED) as zip_file:
    for temp_file, file_ in zip(temp_files, files_relative_paths):
      zip_file.write(temp_file, file_)
  
  shutil.rmtree(temp_dir)