def ParseMountedDevices(): # FIXME: Identify labels for different systems & drive types device_labels = ( u'/dev/sd', ) # Empty the device list mounted_devices = {} if os.path.isfile(u'/etc/mtab'): mtab = ReadFile(u'/etc/mtab', split=True, convert=list) # Only keep lines referring to devices directory for X in reversed(range(len(mtab))): if not mtab[X].startswith(u'/dev'): mtab.pop(X) mtab.sort() for LINE in mtab: LINE = LINE.split(u' ') device = LINE[0] mount_point = LINE[1] for LABEL in device_labels: if device.startswith(LABEL): mounted_devices[device] = mount_point else: Logger.Warn(__name__, u'/etc/mtab file does not exist. Mounted devices list will be empty') return mounted_devices
def SetLicense(self): ## Defines where the LICENSE.txt is located # # By default it is located in the folder 'doc' # under the applications root directory. The # install script or Makefile should change this # to reflect installed path. if INSTALLED: license_path = u'{}/share/doc/debreate/copyright'.format(PREFIX) else: license_path = u'{}/docs/LICENSE.txt'.format(PREFIX) if os.path.isfile(license_path): lic_text = ReadFile(license_path) else: lic_text = GT( u'ERROR: Could not locate license file:\n\t\'{}\' not found'. format(license_path)) lic_text += u'\n\nCopyright © {} {} <{}>'.format( GetYear(), AUTHOR_name, AUTHOR_email) lic_text += u'\n\nhttps://opensource.org/licenses/MIT' self.license.SetValue(lic_text) self.license.SetInsertionPoint(0)
def OnLoadLauncher(self, event=None): dia = GetFileOpenDialog(GetMainWindow(), GT(u'Open Launcher')) if ShowDialog(dia): path = dia.GetPath() data = ReadFile(path, split=True, convert=list) # Remove unneeded lines if data[0] == u'[Desktop Entry]': data = data[1:] self.Reset() # First line needs to be changed to '1' data.insert(0, u'1') self.Set(u'\n'.join(data))
def ReadConfig(k_name, conf=default_config): Logger.Debug(__name__, GT(u'Reading configuration file: {}'.format(conf)), newline=True) if not os.path.isfile(conf): #Logger.Warning(__name__, u'Configuration file does not exist: {}'.format(conf)) return ConfCode.FILE_NOT_FOUND # Use the string '__test__' for test when app is initialized if k_name == u'__test__': return ConfCode.SUCCESS # Only read pre-defined keys if k_name not in default_config_values: #Logger.Warning(__name__, u'Undefined key, not attempting to retrieve value: {}'.format(k_name)) return ConfCode.KEY_NOT_DEFINED conf_lines = ReadFile(conf) if conf_lines: conf_lines = conf_lines.split(u'\n') for L in conf_lines: if u'=' in L: key = L.split(u'=') value = key[1] key = key[0] if k_name == key: value = default_config_values[key][0](value) #Logger.Debug(__name__, u'Retrieved key-value: {}={}, value type: {}'.format(key, value, type(value))) return value if k_name in default_config_values: #Logger.Debug(__name__, u'Configuration does not contain key, retrieving default value: {}'.format(k_name)) return GetDefaultConfigValue(k_name) return ConfCode.KEY_NO_EXIST
def ImportFromFile(self, filename): if not os.path.isfile(filename): return dbrerrno.ENOENT copyright_data = ReadFile(filename, split=True) # Remove preceding empty lines remove_index = 0 for I in copyright_data: if not TextIsEmpty(I): break remove_index += 1 for I in reversed(range(remove_index)): copyright_data.remove(copyright_data[I]) copyright_data = u'\n'.join(copyright_data) self.dsp_copyright.SetValue(copyright_data) return 0
def ExportBuild(self, target, installedSize=0): self.Export(target, u'control') absolute_filename = ConcatPaths((target, u'control')) if not os.path.isfile(absolute_filename): return GT(u'Control file was not created') if installedSize: control_data = ReadFile(absolute_filename, split=True, convert=list) size_line = u'Installed-Size: {}'.format(installedSize) if len(control_data) > 3: control_data.insert(3, size_line) else: control_data.append(size_line) # Be sure not to strip trailing newline (dpkg is picky) WriteFile(absolute_filename, control_data, noStrip=u'\n') return GT(u'Control file created: {}').format(absolute_filename)
def GetCachedDistNames(unstable=True, obsolete=False, generic=False): global FILE_distnames if not os.path.isfile(FILE_distnames): if not UpdateDistNamesCache(unstable, obsolete, generic): return None text_temp = ReadFile(FILE_distnames) dist_names = {} if text_temp: try: dist_names[u'debian'] = RemoveEmptyLines( text_temp.split(u'[DEBIAN]')[1].split(u'[UBUNTU]')[0].split( u'\n')) except IndexError: pass try: dist_names[u'ubuntu'] = RemoveEmptyLines( text_temp.split(u'[UBUNTU]')[1].split(u'[LINUX MINT]') [0].split(u'\n')) except IndexError: pass try: dist_names[u'mint'] = RemoveEmptyLines( text_temp.split(u'[LINUX MINT]')[1].split(u'\n')) except IndexError: pass return (dist_names)
def ImportFromFile(self, filename): Logger.Debug(__name__, GT(u'Importing file: {}'.format(filename))) if not os.path.isfile(filename): ShowErrorDialog(GT(u'File does not exist: {}'.format(filename)), linewrap=600) return dbrerrno.ENOENT file_text = ReadFile(filename) page_depends = GetPage(pgid.DEPENDS) # Reset fields to default before opening self.Reset() page_depends.Reset() depends_data = self.Set(file_text) page_depends.Set(depends_data)
def GetOSDistNames(): global FILE_distnames dist_names = [] if os.path.isfile(FILE_distnames): cached_names = GetCachedDistNames() if cached_names: for OS in ( u'debian', u'ubuntu', u'mint', ): for NAME in cached_names[OS]: dist_names.append(NAME) # Only check system for dist names if could not be loaded from cache file if not dist_names: # Ubuntu & Linux Mint distributions global OS_codename, OS_upstream_codename for CN in ( OS_codename, OS_upstream_codename, ): if CN and CN not in dist_names: dist_names.append(CN) # Debian distributions FILE_debian = u'/etc/debian_version' if os.path.isfile(FILE_debian): debian_names = RemoveEmptyLines(ReadFile(FILE_debian, split=True))[:1] # Usable names should all be on first line if u'/' in debian_names[0]: debian_names = sorted(debian_names[0].split(u'/')) for NAME in reversed(debian_names): if NAME not in dist_names: # Put Debian names first dist_names.insert(0, NAME) return tuple(dist_names)
def GetPrefix(): global PATH_app, INSTALLED if not INSTALLED: return PATH_app lines = ReadFile(u'{}/INSTALLED'.format(PATH_app), split=True) for L in lines: if u'=' in L: key = L.split(u'=') value = key[1] key = key[0] if key.lower() == u'prefix': return value return PATH_app
def GetOSInfo(key, upstream=False): lsb_release = u'/etc/lsb-release' if upstream: lsb_release = u'/etc/upstream-release/lsb-release' if not os.path.isfile(lsb_release): return None release_data = ReadFile(lsb_release, split=True) value = None for L in release_data: if L.startswith(key): value = L.replace(u'{}='.format(key), u'').replace(u'"', u'') break return value
def ImportFromFile(self, filename): if not os.path.isfile(filename): return dbrerrno.ENOENT build_data = ReadFile(filename, split=True) options_definitions = {} for L in build_data: if u'=' in L: key = L.split(u'=') value = GetBoolean(key[-1]) key = key[0] options_definitions[key] = value for O in self.build_options: name = O.GetName() if name in options_definitions and isinstance( options_definitions[name], bool): O.SetValue(options_definitions[name]) return 0
def ImportFromFile(self, filename): Logger.Debug(__name__, GT(u'Importing script: {}').format(filename)) script_name = filename.split(u'-')[-1] script_object = None for DS, RB in self.script_objects: if script_name == DS.GetFilename(): script_object = DS break # Loading the actual text # FIXME: Should be done in class method if script_object != None: script_data = ReadFile(filename, split=True, convert=list) # FIXME: this should be global variable shebang = u'/bin/bash' remove_indexes = 0 if u'#!' == script_data[0][:2]: shebang = script_data[0][2:] script_data.remove(script_data[0]) # Remove empty lines from beginning of script for L in script_data: if not TextIsEmpty(L): break remove_indexes += 1 for I in reversed(range(remove_indexes)): script_data.remove(script_data[I]) script_data = u'\n'.join(script_data) script_object.SetShell(shebang, True) script_object.SetValue(script_data)
def ImportFromFile(self, filename): if not os.path.isfile(filename): return dbrerrno.ENOENT clog_data = ReadFile(filename, split=True) sections = {} def parse_section(key, lines): value = u'\n'.join(lines).split(u'\n[')[0] if u'=' in key: key = key.split(u'=') value = (key[-1], value) key = key[0] sections[key] = value # NOTE: This would need to be changed were more sections added to project file for L in clog_data: line_index = clog_data.index(L) if not TextIsEmpty(L) and u'[' in L and u']' in L: L = L.split(u'[')[-1].split(u']')[0] parse_section(L, clog_data[line_index + 1:]) for S in sections: Logger.Debug( __name__, GT(u'Changelog section: "{}", Value:\n{}').format( S, sections[S])) if isinstance(sections[S], (tuple, list)): value_index = 0 for I in sections[S]: Logger.Debug(__name__, GT(u'Value {}: {}').format(value_index, I)) value_index += 1 if S == u'TARGET': Logger.Debug(__name__, u'SECTION TARGET FOUND') if sections[S][0] == u'DEFAULT': Logger.Debug(__name__, u'Using default target') if not self.pnl_target.UsingDefault(): self.pnl_target.Reset() else: Logger.Debug( __name__, GT(u'Using custom target: {}').format(sections[S][0])) self.pnl_target.SetPath(sections[S][0]) continue if S == u'BODY': Logger.Debug(__name__, u'SECTION BODY FOUND') self.dsp_changes.SetValue(sections[S]) continue return 0
def ImportFromFile(self, filename): Logger.Debug(__name__, GT(u'Importing page info from {}').format(filename)) if not os.path.isfile(filename): return dbrerrno.ENOENT menu_data = ReadFile(filename, split=True, convert=list) if u'[Desktop Entry]' in menu_data[0]: menu_data.remove(menu_data[0]) menu_definitions = {} unused_raw_lines = [] for L in menu_data: if u'=' in L: key = L.split(u'=') value = key[-1] key = key[0] menu_definitions[key] = value continue # Any unrecognizable lines will be added to "Other" section unused_raw_lines.append(L) def set_value(option): key = option.GetName() value = None if key in menu_definitions: value = menu_definitions[key] if not TextIsEmpty(value): if option in self.opts_input: option.SetValue(value) return True elif option in self.opts_choice: if option.SetStringSelection(value): return True elif option in self.opts_list: lst_categories = GetField(self, listid.CAT) if key == lst_categories.GetName(): value = value.split(u';') if value: for X, val in enumerate(value): lst_categories.InsertStringItem(X, val) return True return False categories_used = [] for group in self.opts_input, self.opts_choice, self.opts_list: for O in group: if set_value(O): categories_used.append(O.GetName()) # List of keys that can be ignored if unused bypass_unused = (u'Version', ) categories_unused = [] for key in menu_definitions: if key not in categories_used and key not in bypass_unused: categories_unused.append(u'{}={}'.format( key, menu_definitions[key])) categories_unused += unused_raw_lines if len(categories_unused): categories_unused = u'\n'.join(categories_unused) #self.ti_other.SetValue(categories_unused) return 0
def OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting Lintian overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file): Logger.Error( __name__, u'Lintian tags file is missing: {}'.format(lintian_tags_file)) return False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags: Logger.Debug(__name__, u'Lintian tags set') # DEBUG: Start if DebugEnabled() and len(lint_tags) > 50: print(u' Reducing tag count to 200 ...') lint_tags = lint_tags[:50] Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags))) # DEBUG: End tag_count = len(lint_tags) def GetProgressMessage(message, count=tag_count): return u'{} ({} {})'.format(message, count, GT(u'tags')) progress = TimedProgressDialog( GetMainWindow(), GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning default tags'))) progress.Start() wx.Yield() # Create the dialog overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True) # FIXME: Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage( GetProgressMessage(GT(u'Setting selected overrides'))) for T in lint_tags: if T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage( GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides))) # Remaining tags should be custom entries # FIXME: if self.lint_overrides: for T in self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop() if overrides_dialog.ShowModal() == wx.ID_OK: # Remove old overrides self.lint_overrides = [] for L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian override: {}').format(L)) self.lint_overrides.append(L) return True else: Logger.Debug(__name__, u'Setting lintian tags failed') return False
def Read(self, split=False, convert=tuple, noStrip=None): return ReadFile(self.Path, split, convert, noStrip)
def OnBuild(self, event=None): stage = self.input_stage.GetValue() target = self.input_target.GetValue().rstrip(u'/') # Attempt to use DEBIAN/control file to set output filename. This is normally # done automatically by the dpkg command, but we need to set it manually to # check for overwriting a file. if os.path.isdir(target): control_file = ConcatPaths((stage, u'DEBIAN/control')) if os.path.isfile(control_file): control_lines = ReadFile(control_file, split=True) name = None version = None arch = None for LINE in control_lines: if LINE.startswith(u'Package:'): name = LINE.replace(u'Package: ', u'').strip() elif LINE.startswith(u'Version:'): version = LINE.replace(u'Version: ', u'').strip() elif LINE.startswith(u'Architecture:'): arch = LINE.replace(u'Architecture: ', u'').strip() if name and version and arch: target = ConcatPaths((target, u'{}.deb'.format(u'_'.join(( name, version, arch, ))))) # Automatically add .deb filename extension if not present elif not target.lower().endswith(u'.deb'): target = u'{}.deb'.format(target) if not os.path.isdir(stage): ShowErrorDialog(GT(u'Stage directory does not exist'), stage, self, True) return target_path = os.path.dirname(target) if not os.path.isdir(target_path): ShowErrorDialog(GT(u'Target directory does not exist'), target_path, self, True) return elif not os.access(target_path, os.W_OK): ShowErrorDialog(GT(u'No write access to target directory'), target_path, self, True) return # Update the text input if target altered if target != self.input_target.GetValue(): self.input_target.SetValue(target) # Check for pre-existing file if os.path.isfile(target): if not OverwriteDialog(self, target).Confirmed(): return self.SetTitle(u'{} ({})'.format(self.title, GT(u'in progress'))) # Don't allow dialog to be closed while build in progress self.Disable() self.timer.Start(100) # Start new thread for background process Thread(self.Build, stage, target).Start()
def ProjectOpen(self, project_file=None): Logger.Debug(__name__, u'Opening project: {}'.format(project_file)) # Need to show file open dialog because no project file was specified if not project_file: wc_z = GetDialogWildcards(ID_PROJ_Z) wc_l = GetDialogWildcards(ID_PROJ_L) wc_a = GetDialogWildcards(ID_PROJ_A) wc_t = GetDialogWildcards(ID_PROJ_T) wildcards = ( wc_a[0], wc_a[1], wc_z[0], wc_z[1], wc_t[0], wc_t[1], wc_l[0], wc_l[1], ) open_dialog = GetFileOpenDialog(self, GT(u'Open Debreate Project'), wildcards) if not ShowDialog(open_dialog): return dbrerrno.ECNCLD # Get the path and set the saved project project_file = open_dialog.GetPath() # Failsafe check that file exists if not os.path.isfile(project_file): err_l1 = GT(u'Cannot open project:') err_details = GT(u'File does not exist') ShowErrorDialog(u'{} {}'.format(err_l1, project_file), err_details) return dbrerrno.ENOENT # Check for unsaved changes & reset project to defaults if not self.ProjectClose(): return dbrerrno.ECNCLD mime_type = GetFileMimeType(project_file) Logger.Debug(__name__, GT(u'Project mime type: {}').format(mime_type)) opened = None if mime_type == u'text/plain': p_text = ReadFile(project_file) filename = os.path.split(project_file)[1] # Legacy projects should return None since we can't save in that format opened = self.ProjectOpenLegacy(p_text, filename) else: opened = self.ProjectOpenArchive(project_file, mime_type) Logger.Debug( __name__, GT(u'Project loaded before OnProjectOpen: {}').format( self.ProjectIsLoaded())) if opened == dbrerrno.SUCCESS: self.LoadedProject = project_file # Set project 'unmodified' for newly opened project self.ProjectSetDirty(False) Logger.Debug( __name__, GT(u'Project loaded after OnOpenPreject: {}').format( self.ProjectIsLoaded())) if DebugEnabled() and self.ProjectIsLoaded(): Logger.Debug(__name__, GT(u'Loaded project: {}').format(self.LoadedProject)) return opened
def ImportFromFile(self, filename): Logger.Debug(__name__, GT(u'Importing page info from {}').format(filename)) if not os.path.isfile(filename): return dbrerrno.ENOENT menu_data = ReadFile(filename, split=True, convert=list) if u'[Desktop Entry]' in menu_data[0]: menu_data.remove(menu_data[0]) menu_definitions = {} unused_raw_lines = [] for L in menu_data: if u'=' in L: key = L.split(u'=') value = key[-1] key = key[0] menu_definitions[key] = value continue # Any unrecognizable lines will be added to "Other" section unused_raw_lines.append(L) def set_value(option): key = option.GetName() value = None if key in menu_definitions: value = menu_definitions[key] if not TextIsEmpty(value): if option in self.opts_input: option.SetValue(value) return True elif option in self.opts_choice: if option.SetStringSelection(value): return True elif option in self.opts_list: lst_categories = GetField(self, listid.CAT) if key == lst_categories.GetName(): value = value.split(u';') if value: for X, val in enumerate(value): lst_categories.InsertStringItem(X, val) return True return False categories_used = [] for group in self.opts_input, self.opts_choice, self.opts_list: for O in group: if set_value(O): categories_used.append(O.GetName()) # List of keys that can be ignored if unused bypass_unused = ( u'Version', ) categories_unused = [] for key in menu_definitions: if key not in categories_used and key not in bypass_unused: categories_unused.append(u'{}={}'.format(key, menu_definitions[key])) categories_unused += unused_raw_lines if len(categories_unused): categories_unused = u'\n'.join(categories_unused) #self.ti_other.SetValue(categories_unused) return 0
def OnTemplateFull(self, event=None): selected_template = self.sel_templates.GetStringSelection() template_file = self.GetLicensePath(selected_template) if self.DestroyLicenseText(): if not template_file or not os.path.isfile(template_file): ShowErrorDialog(GT(u'Could not locate license file: {}').format(self.GetSelectedName())) return Logger.Debug(__name__, u'Copying license {}'.format(template_file)) license_text = ReadFile(template_file, noStrip=u' ') # Number defines how many empty lines to add after the copyright header # Boolean/Integer defines whether copyright header should be centered/offset add_header = { u'Artistic': (1, True), u'BSD': (0, False), } template_name = os.path.basename(template_file) if template_name in add_header: license_text = license_text.split(u'\n') empty_lines = add_header[template_name][0] for L in range(empty_lines): license_text.insert(0, wx.EmptyString) header = copyright_header.format(GetYear()) center_header = add_header[template_name][1] if center_header: Logger.Debug(__name__, u'Centering header...') offset = 0 # Don't use isinstance() here because boolean is an instance of integer if type(center_header) == int: offset = center_header else: # Use the longest line found in the text to center the header longest_line = GetLongestLine(license_text) Logger.Debug(__name__, u'Longest line: {}'.format(longest_line)) header_length = len(header) if header_length < longest_line: offset = (longest_line - header_length) / 2 if offset: Logger.Debug(__name__, u'Offset: {}'.format(offset)) header = u'{}{}'.format(u' ' * offset, header) # Special changes for BSD license if template_name == u'BSD': line_index = 0 for LI in license_text: if u'copyright (c)' in LI.lower(): license_text[line_index] = header break line_index += 1 else: license_text.insert(0, header) license_text = u'\n'.join(license_text) if not license_text: ShowErrorDialog(GT(u'License template is empty')) return self.dsp_copyright.SetValue(license_text) self.dsp_copyright.SetInsertionPoint(0) self.dsp_copyright.SetFocus()
def OnPreviewCache(self, event=None): self.preview.SetValue(ReadFile(FILE_distnames)) self.preview.ShowModal()
def WriteConfig(k_name, k_value, conf=default_config, sectLabel=None): conf_dir = os.path.dirname(conf) if not os.path.isdir(conf_dir): if os.path.exists(conf_dir): print(u'{}: {}: {}'.format(GT(u'Error'), GT(u'Cannot create config directory, file exists'), conf_dir)) return ConfCode.ERR_WRITE os.makedirs(conf_dir) # Only write pre-defined keys if k_name not in default_config_values: print(u'{}: {}: {}'.format(GT(u'Error'), GT(u'Configuration key not found'), k_name)) return ConfCode.KEY_NOT_DEFINED # Make sure we are writing the correct type k_value = default_config_values[k_name][0](k_value) if k_value == None: print(u'{}: {}: {}'.format(GT(u'Error'), GT(u'Wrong value type for configuration key'), k_name)) return ConfCode.WRONG_TYPE # tuple is the only type we need to format if isinstance(k_value, tuple): k_value = u'{},{}'.format(GS(k_value[0]), GS(k_value[1])) else: k_value = GS(k_value) conf_text = wx.EmptyString # Save current config to buffer if os.path.exists(conf): if not os.path.isfile(conf): print(u'{}: {}: {}'.format(GT(u'Error'), GT(u'Cannot open config for writing, directory exists'), conf)) return ConfCode.ERR_WRITE conf_text = ReadFile(conf) # FIXME: ReadFile returns None type if config file exists but is empty if conf_text == None: conf_text = u'' else: conf_text = u'[CONFIG-{}.{}]'.format(GS(config_version[0]), GS(config_version[1])) conf_lines = conf_text.split(u'\n') key_exists = False for L in conf_lines: l_index = conf_lines.index(L) if u'=' in L: key = L.split(u'=')[0] if k_name == key: key_exists = True conf_lines[l_index] = u'{}={}'.format(k_name, k_value) if not key_exists: conf_lines.append(u'{}={}'.format(k_name, k_value)) conf_text = u'\n'.join(conf_lines) if TextIsEmpty(conf_text): print(u'{}: {}'.format(GT(u'Warning'), GT(u'Not writing empty text to configuration'))) return ConfCode.ERR_WRITE # Actual writing to configuration WriteFile(conf, conf_text) if os.path.isfile(conf): return ConfCode.SUCCESS return ConfCode.ERR_WRITE
def OnDropFiles(self, event=None): if not self.IsEnabled() or not event: return False # Flash red if doesn't accept file drops if not self.IsDropTarget(): parent = self.GetParent() if isinstance(parent, TextAreaPanel): main_object = parent else: main_object = self bgcolor = main_object.GetBackgroundColour() main_object.SetBackgroundColour(wx.RED) wx.Yield() time.sleep(0.1) main_object.SetBackgroundColour(bgcolor) return False filename = event.GetFiles() if not filename: return False # Use only the first file if isinstance(filename, (tuple, list)): filename = filename[0] if not TextIsEmpty(self.GetValue()): msg_li1 = GT(u'This will delete all text') msg_li2 = GT(u'Continue?') # FIXME: Use custom dialogs (currently cannot import) message = wx.MessageDialog(GetMainWindow(), u'{}\n\n{}'.format(msg_li1, msg_li2), GT(u'Warning'), wx.OK | wx.CANCEL | wx.ICON_WARNING) confirmed = message.ShowModal() in (wx.OK, wx.ID_OK, wx.YES, wx.ID_YES) if not confirmed: return False try: input_text = ReadFile(filename) if input_text: self.SetValue(input_text) return True except UnicodeDecodeError: pass #ShowErrorDialog(GT(u'There was an error reading file: {}').format(filename)) wx.MessageDialog( GetMainWindow(), GT(u'There was an error reading file: {}').format(filename), GT(u'Error'), wx.OK | wx.ICON_ERROR).ShowModal() return False
def WriteConfig(k_name, k_value, conf=default_config, sectLabel=None): conf_dir = os.path.dirname(conf) if not os.path.isdir(conf_dir): if os.path.exists(conf_dir): print(u'{}: {}: {}'.format( GT(u'Error'), GT(u'Cannot create config directory, file exists'), conf_dir)) return ConfCode.ERR_WRITE os.makedirs(conf_dir) # Only write pre-defined keys if k_name not in default_config_values: print(u'{}: {}: {}'.format(GT(u'Error'), GT(u'Configuration key not found'), k_name)) return ConfCode.KEY_NOT_DEFINED # Make sure we are writing the correct type k_value = default_config_values[k_name][0](k_value) if k_value == None: print(u'{}: {}: {}'.format( GT(u'Error'), GT(u'Wrong value type for configuration key'), k_name)) return ConfCode.WRONG_TYPE # tuple is the only type we need to format if isinstance(k_value, tuple): k_value = u'{},{}'.format(GS(k_value[0]), GS(k_value[1])) else: k_value = GS(k_value) conf_text = wx.EmptyString # Save current config to buffer if os.path.exists(conf): if not os.path.isfile(conf): print(u'{}: {}: {}'.format( GT(u'Error'), GT(u'Cannot open config for writing, directory exists'), conf)) return ConfCode.ERR_WRITE conf_text = ReadFile(conf) # FIXME: ReadFile returns None type if config file exists but is empty if conf_text == None: conf_text = u'' else: conf_text = u'[CONFIG-{}.{}]'.format(GS(config_version[0]), GS(config_version[1])) conf_lines = conf_text.split(u'\n') key_exists = False for L in conf_lines: l_index = conf_lines.index(L) if u'=' in L: key = L.split(u'=')[0] if k_name == key: key_exists = True conf_lines[l_index] = u'{}={}'.format(k_name, k_value) if not key_exists: conf_lines.append(u'{}={}'.format(k_name, k_value)) conf_text = u'\n'.join(conf_lines) if TextIsEmpty(conf_text): print(u'{}: {}'.format(GT(u'Warning'), GT(u'Not writing empty text to configuration'))) return ConfCode.ERR_WRITE # Actual writing to configuration WriteFile(conf, conf_text) if os.path.isfile(conf): return ConfCode.SUCCESS return ConfCode.ERR_WRITE
def ImportFromFile(self, filename): Logger.Debug(__name__, GT(u'Importing page info from {}').format(filename)) if not os.path.isfile(filename): return dbrerrno.ENOENT files_data = ReadFile(filename, split=True) # Lines beginning with these characters will be ignored ignore_characters = ( u'', u' ', u'#', ) target = None targets_list = [] for L in files_data: if not TextIsEmpty(L) and L[0] not in ignore_characters: if u'[' in L and u']' in L: target = L.split(u'[')[-1].split(u']')[0] continue if target: executable = (len(L) > 1 and L[-2:] == u' *') if executable: L = L[:-2] targets_list.append((target, L, executable)) missing_files = [] for T in targets_list: # FIXME: Create method in FileList class to retrieve all missing files if not os.path.exists(T[1]): missing_files.append(T[1]) source_file = os.path.basename(T[1]) source_dir = os.path.dirname(T[1]) self.lst_files.AddFile(source_file, source_dir, T[0], executable=T[2]) if len(missing_files): main_window = GetMainWindow() err_line1 = GT( u'The following files/folders are missing from the filesystem.' ) err_line2 = GT(u'They will be highlighted on the Files page.') DetailedMessageDialog( main_window, title=GT(u'Warning'), icon=ICON_ERROR, text=u'\n'.join((err_line1, err_line2)), details=u'\n'.join(missing_files)).ShowModal() return 0
def SetChangelog(self): ## Defines where the changelog is located # # By default it is located in the folder 'doc' # under the applications root directory. The # install script or Makefile should change this # to reflect installed path. if INSTALLED: # FIXME: Read compressed .gz changelog CHANGELOG = u'{}/share/doc/debreate/changelog.gz'.format(PREFIX) else: CHANGELOG = u'{}/docs/changelog'.format(PREFIX) if os.path.isfile(CHANGELOG): changelog_mimetype = GetFileMimeType(CHANGELOG) Logger.Debug( __name__, GT(u'Changelog mimetype: {}').format(changelog_mimetype)) # Set log text in case of read error log_text = GT(u'Error reading changelog: {}\n\t').format(CHANGELOG) log_text = u'{}{}'.format( log_text, GT(u'Cannot decode, unrecognized mimetype: {}').format( changelog_mimetype)) if changelog_mimetype == u'application/gzip': temp_dir = CreateStage() shutil.copy(CHANGELOG, temp_dir) CMD_gzip = GetExecutable(u'gzip') if CMD_gzip: prev_dir = os.getcwd() os.chdir(temp_dir) gzip_output = commands.getstatusoutput(u'{} -fd {}'.format( CMD_gzip, os.path.basename(CHANGELOG))) Logger.Debug( __name__, GT(u'gzip decompress; Code: {}, Output: {}').format( gzip_output[0], gzip_output[1])) os.chdir(prev_dir) changelog_file = os.path.basename(CHANGELOG).split(u'.')[0] changelog_file = u'{}/{}'.format(temp_dir, changelog_file) if os.path.isfile(changelog_file): log_text = ReadFile(changelog_file) RemoveStage(temp_dir) elif changelog_mimetype == u'text/plain': log_text = ReadFile(CHANGELOG) else: ShowErrorDialog(log_text, parent=self) else: log_text = GT( u'ERROR: Could not locate changelog file:\n\t\'{}\' not found'. format(CHANGELOG)) self.changelog.SetValue(log_text) self.changelog.SetInsertionPoint(0)