def found_suites_from_sources(): sources = sourceslist.SourcesList() found = list(set(get_suites(sources))) huayra_suites = [ 'brisa', 'mate-brisa', 'pampero', 'mate-pampero', 'sud', 'zonda', 'torbellino' ] huayras = [] for suite in huayra_suites: found, huayras = proc_found(found, huayras, suite) found, huayras = proc_found(found, huayras, suite + '-updates') found, huayras = proc_found(found, huayras, suite + '-proposed') deb_suites = [ 'squeeze', 'oldoldstable', 'wheezy', 'oldstable', 'jessie', 'stable', 'stretch', 'testing', 'sid', 'unstable', 'experimental', 'rc-buggy' ] debians = [] for suite in deb_suites: found, debians = proc_found(found, debians, suite) found, debians = proc_found(found, debians, suite + '-updates') found, debians = proc_found(found, debians, suite + '/updates') found, debians = proc_found(found, debians, suite + '-proposed-updates') found, debians = proc_found(found, debians, suite + '-backports') huayra = ",".join(str(i) for i in huayras) debian = ",".join(str(i) for i in debians) resto = ",".join(str(i) for i in found) return huayra, debian, resto
def check_enabled(codename): expected_entry = "deb https://private-ppa.launchpad.net/ubuntu-advantage/fips/ubuntu " + codename + " main" sources = sourceslist.SourcesList() for source in sources.list: if source.str() == expected_entry: return True return False
def list_repos(): ''' Lists all repos in the sources.list (and sources.lists.d) files CLI Example: .. code-block:: bash salt '*' pkg.list_repos salt '*' pkg.list_repos disabled=True ''' if not apt_support: msg = 'Error: aptsources.sourceslist python module not found' log.error(msg) return msg repos = {} sources = sourceslist.SourcesList() for source in sources.list: if source.invalid: continue repo = {} repo['file'] = source.file repo['comps'] = getattr(source, 'comps', []) repo['disabled'] = source.disabled repo['dist'] = source.dist repo['type'] = source.type repo['uri'] = source.uri.rstrip('/') repo['line'] = _strip_uri(source.line.strip()) repo['architectures'] = getattr(source, 'architectures', []) repos.setdefault(source.uri, []).append(repo) return repos
def __init__(self, parent=None): super(SourceEdit, self).__init__(parent) self.resize(600, 500) self.font = QtGui.QFont() self.font.setBold(True) self.font2 = QtGui.QFont() self.font2.setBold(False) self.searchEditText = QtGui.QLineEdit() self.searchEditText.setPlaceholderText("Search for repositories") palette = QtGui.QPalette() palette.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red) self.label = QtGui.QLabel() self.btnRemove = QtGui.QPushButton() self.btDisable = QtGui.QPushButton() self.btnEnable = QtGui.QPushButton() self.btnClose = QtGui.QPushButton() self.btnClose.setText("Close") self.btnRemove.setText("Remove entries") self.btDisable.setText("Disable entries") self.btnEnable.setText("Enable entries") self.label.setPalette(palette) self.btnRemove.clicked.connect(self.removeSelectedSources) self.btDisable.clicked.connect(self.disableSelectedSources) self.btnEnable.clicked.connect(self.enableSelectedSources) self.msg = QtGui.QMessageBox() self.msg.setIcon(QtGui.QMessageBox.Information) self.msg.setWindowTitle("Success") self.msg.setText("Your changes have been successfully applied") self.btnClose.clicked.connect(self.close) self.s = sourceslist.SourcesList() self.sourceslists = [] self.items = []
def main() -> int: opts = options.get() ret = EXIT_SUCCESS if opts.verb != "find" and (not opts.simulate and os.geteuid() > 0): print("Error: The given action requires root privileges.", file=sys.stderr) return EXIT_FAILURE if (opts.verb == "apply-template" and (opts.template is None or opts.distribution is None)): print( "Error: `apply-template` requires non-empty --template and --distribution paramters.", file=sys.stderr) return EXIT_FAILURE try: deletion_queue = [] src = sourceslist.SourcesList() ret = FUNCTION_TABLE[opts.verb](src, opts, deletion_queue) if not opts.simulate and opts.verb != "find": for path in deletion_queue: if os.access(path, os.F_OK | os.W_OK): os.remove(path) src.save() except BaseException as e: print("ERROR, will not save any change(s):", e, file=sys.stderr) return EXIT_FAILURE return ret
def list_repos(): ''' Lists all repos in the sources.list (and sources.lists.d) files CLI Example:: salt '*' pkg.list_repos salt '*' pkg.list_repos disabled=True ''' if not apt_support: return 'Error: aptsources.sourceslist python module not found' repos = {} sources = sourceslist.SourcesList() for source in sources.list: if source.invalid: continue repo = {} repo['file'] = source.file repo['comps'] = getattr(source, 'comps', []) repo['disabled'] = source.disabled repo['dist'] = source.dist repo['type'] = source.type repo['uri'] = source.uri repo['line'] = source.line repo['architectures'] = getattr(source, 'architectures', []) repos.setdefault(source.uri, []).append(repo) return repos
def apt_sources_list(self): """represents the full sources.list + sources.list.d file. :return: list of apt sources :rtype: list """ from aptsources import sourceslist return sourceslist.SourcesList()
def __init__(self, parent=None): super(EasyPPAInstall, self).__init__(parent) self.setWindowTitle("Easy PPA Install") self.searchEditText = QtGui.QLineEdit() self.searchEditText.setPlaceholderText("Search for applications") self.searchEditText.setMaximumWidth(200) self.searchbutton = QtGui.QPushButton() self.error_msg = QtGui.QMessageBox() self.error_msg.setIcon(QtGui.QMessageBox.Critical) self.error_msg.setWindowTitle("Error") self.closebutton = QtGui.QPushButton() self.closebutton = QtGui.QPushButton() self.closebutton.setText('Close') self.closebutton.setMaximumWidth(150) self.closebutton.clicked.connect(self.close) self.searchbutton.setText("Search") self.searchbutton.setMaximumWidth(100) self.progressbar = QtGui.QProgressBar() self.lbl1 = QtGui.QLabel() self.buttonRefresh = QtGui.QPushButton() self.buttonRefresh.setText("Refresh sources") self.isWrittenTo = False self.table = QtGui.QTableWidget() self.configureTable(self.table) self.searchbutton.clicked.connect( lambda: self.searchForPPA(self.table)) self.buttonRefresh.clicked.connect(self.updateSources) self.table.verticalHeader().hide() self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.addWidget(self.searchEditText) self.horizontalLayout.addWidget(self.searchbutton) self.horizontalLayout.setAlignment(QtCore.Qt.AlignRight) self.horizontalLayout2 = QtGui.QHBoxLayout() self.horizontalLayout2.setAlignment(QtCore.Qt.AlignRight) self.horizontalLayout2.addWidget(self.progressbar) self.horizontalLayout2.addWidget(self.buttonRefresh) self.horizontalLayout2.addWidget(self.closebutton) self.verticalLayout = QtGui.QVBoxLayout(self) self.verticalLayout.addLayout(self.horizontalLayout) self.verticalLayout.addWidget(self.table) self.verticalLayout.addWidget(self.lbl1) self.verticalLayout.addLayout(self.horizontalLayout2) self.os_info = lsb_release.get_distro_information() self.sources = sourceslist.SourcesList() self.aprogress = UIAcquireProgress(True) self.thread1 = QtCore.QThread() self.aprogress.moveToThread(self.thread1) self.thread1.started.connect( lambda: self.aprogress.play(0.0, False, "")) self.aprogress.finished.connect(self.thread1.quit) self.connect(self.aprogress, QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"), self.updateProgressBar2) self.ppa = [] self.table_data = []
def apt_sources_list(self): """represents the full sources.list + sources.list.d file. :return: list of apt sources :rtype: list """ from aptsources import sourceslist sources = sourceslist.SourcesList().list return [str(source) for source in sources if not source.line.startswith("#") and source.line != "\n"]
def is_backports_current(): """Return whether backports are enabled for the current release.""" if not is_backports_enabled(): return False _, dist = get_current_release() dist += '-backports' sources = sourceslist.SourcesList() for source in sources: if source.dist == dist: return True return False
def get_repo_mirror_from_apt(self): """ This tries to determine the apt mirror/archive to use (when processing repos) if the host machine is Debian or Ubuntu. :return: False if the try fails or otherwise the mirrors. """ try: sources = sourceslist.SourcesList() release = debdistro.get_distro() release.get_sources(sources) mirrors = release.get_server_list() for mirror in mirrors: if mirror[2]: return mirror[1] except: return False
def get_repo_mirror_from_apt(self): """ This tries to determine the apt mirror/archive to use (when processing repos) if the host machine is Debian or Ubuntu. """ try: sources = sourceslist.SourcesList() release = distro.get_distro() release.get_sources(sources) mirrors = release.get_server_list() for mirror in mirrors: if mirror[2] == True: mirror = mirror[1] break except: return False return mirror
def update_sources_list(): sources = sourceslist.SourcesList() sw_source = [] for source in sources.list: if source.uri.startswith('spacewalk://'): source.set_enabled(False) sw_source.append(source) if up2dateAuth.getSystemId(): channels = get_channels() if len(channels): for source in sw_source: sources.remove(source) sources.add(type='deb', uri='spacewalk://' + get_server(), dist='channels:', orig_comps=channels, file=get_conf_file()) sources.save()
def add_sources(self, soruce_val): root = ET.parse(soruce_val).getroot() for repo in root.iter('repository'): # e stands for element if repo.get('install') == 'True': source = SL.SourcesList() SE = SL.SourceEntry sl = SE.mysplit(repo, repo.text) # sl = split line # source.backup() if 'arch' in sl[1]: pass # source.add(sl[0], sl[2], sl[3], sl[4], sl[1]) else: pass # source.add(sl[0], sl[1], sl[2], sl[3]) for ppa in root.iter('ppa'): if ppa.get('install') == 'True': SPsp = SP.SoftwareProperties() # key = SP.ppa.AddPPASigningKey() SPsp.add_source_from_line(ppa.text) source.save() # Remove this comment for release version
def apt_sources_list(self): from aptsources import sourceslist return sourceslist.SourcesList()
def del_repo(repo, **kwargs): ''' Delete a repo from the sources.list / sources.list.d If the .list file is in the sources.list.d directory and the file that the repo exists in does not contain any other repo configuration, the file itself will be deleted. The repo passed in must be a fully formed repository definition string. CLI Examples: .. code-block:: bash salt '*' pkg.del_repo "myrepo definition" ''' if not apt_support: return 'Error: aptsources.sourceslist python module not found' is_ppa = False if repo.startswith('ppa:') and __grains__['os'] == 'Ubuntu': # This is a PPA definition meaning special handling is needed # to derive the name. is_ppa = True dist = __grains__['lsb_distrib_codename'] if not ppa_format_support: _warn_software_properties(repo) owner_name, ppa_name = repo[4:].split('/') if 'ppa_auth' in kwargs: auth_info = '{0}@'.format(kwargs['ppa_auth']) repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name, ppa_name) else: repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist) else: repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0] sources = sourceslist.SourcesList() repos = filter(lambda s: not s.invalid, sources.list) if repos: deleted_from = dict() try: repo_type, repo_uri, repo_dist, repo_comps = _split_repo_str(repo) except SyntaxError: error_str = 'Error: repo {0!r} not a well formatted definition' return error_str.format(repo) for source in repos: if (source.type == repo_type and source.uri == repo_uri and source.dist == repo_dist): s_comps = set(source.comps) r_comps = set(repo_comps) if s_comps.intersection(r_comps): deleted_from[source.file] = 0 source.comps = list(s_comps.difference(r_comps)) if not source.comps: try: sources.remove(source) except ValueError: pass # PPAs are special and can add deb-src where expand_ppa_line doesn't # always reflect this. Lets just cleanup here for good measure if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and source.uri == repo_uri and source.dist == repo_dist): s_comps = set(source.comps) r_comps = set(repo_comps) if s_comps.intersection(r_comps): deleted_from[source.file] = 0 source.comps = list(s_comps.difference(r_comps)) if not source.comps: try: sources.remove(source) except ValueError: pass sources.save() if deleted_from: ret = '' for source in sources: if source.file in deleted_from: deleted_from[source.file] += 1 for repo_file, c in deleted_from.iteritems(): msg = 'Repo {0!r} has been removed from {1}.\n' if c == 0 and 'sources.list.d/' in repo_file: if os.path.isfile(repo_file): msg = ('File {1} containing repo {0!r} has been ' 'removed.\n') try: os.remove(repo_file) except OSError: pass ret += msg.format(repo, repo_file) # explicit refresh after a repo is deleted refresh_db() return ret return "Repo {0} doesn't exist in the sources.list(s)".format(repo)
def mod_repo(repo, saltenv='base', **kwargs): ''' Modify one or more values for a repo. If the repo does not exist, it will be created, so long as the definition is well formed. For Ubuntu the "ppa:<project>/repo" format is acceptable. "ppa:" format can only be used to create a new repository. The following options are available to modify a repo definition:: comps (a comma separated list of components for the repo, e.g. "main") file (a file name to be used) keyserver (keyserver to get gpg key from) keyid (key id to load with the keyserver argument) key_url (URL to a gpg key to add to the apt gpg keyring) consolidate (if true, will attempt to de-dup and consolidate sources) * Note: Due to the way keys are stored for apt, there is a known issue where the key wont be updated unless another change is made at the same time. Keys should be properly added on initial configuration. CLI Examples: .. code-block:: bash salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe ''' if not apt_support: raise ImportError('Error: aptsources.sourceslist module not found') # to ensure no one sets some key values that _shouldn't_ be changed on the # object itself, this is just a white-list of "ok" to set properties if repo.startswith('ppa:'): if __grains__['os'] == 'Ubuntu': # secure PPAs cannot be supported as of the time of this code # implementation via apt-add-repository. The code path for # secure PPAs should be the same as urllib method if ppa_format_support and 'ppa_auth' not in kwargs: try: get_repo(repo) return {repo: ''} except Exception: if float(__grains__['osrelease']) < 12.04: cmd = 'apt-add-repository {0}'.format(repo) else: cmd = 'apt-add-repository -y {0}'.format(repo) out = __salt__['cmd.run_stdout'](cmd, **kwargs) # explicit refresh when a repo is modified. refresh_db() return {repo: out} else: if not ppa_format_support: _warn_software_properties(repo) else: log.info('Falling back to urllib method for private PPA') # fall back to urllib style try: owner_name, ppa_name = repo[4:].split('/', 1) except ValueError: raise CommandExecutionError( 'Unable to get PPA info from argument. ' 'Expected format "<PPA_OWNER>/<PPA_NAME>" ' '(e.g. saltstack/salt) not found. Received ' '{0!r} instead.'.format(repo[4:])) dist = __grains__['lsb_distrib_codename'] # ppa has a lot of implicit arguments. Make them explicit. # These will defer to any user-defined variants kwargs['dist'] = dist ppa_auth = '' if file not in kwargs: filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list' kwargs['file'] = filename.format(owner_name, ppa_name, dist) try: launchpad_ppa_info = _get_ppa_info_from_launchpad( owner_name, ppa_name) if 'ppa_auth' not in kwargs: kwargs['keyid'] = launchpad_ppa_info[ 'signing_key_fingerprint'] else: if 'keyid' not in kwargs: error_str = 'Private PPAs require a ' \ 'keyid to be specified: {0}/{1}' raise CommandExecutionError( error_str.format(owner_name, ppa_name)) except urllib2.HTTPError as exc: raise CommandExecutionError( 'Launchpad does not know about {0}/{1}: {2}'.format( owner_name, ppa_name, exc)) except IndexError as e: raise CommandExecutionError( 'Launchpad knows about {0}/{1} but did not ' 'return a fingerprint. Please set keyid ' 'manually: {2}'.format(owner_name, ppa_name, e)) if 'keyserver' not in kwargs: kwargs['keyserver'] = 'keyserver.ubuntu.com' if 'ppa_auth' in kwargs: if not launchpad_ppa_info['private']: raise CommandExecutionError( 'PPA is not private but auth credentials ' 'passed: {0}'.format(repo)) # assign the new repo format to the "repo" variable # so we can fall through to the "normal" mechanism # here. if 'ppa_auth' in kwargs: ppa_auth = '{0}@'.format(kwargs['ppa_auth']) repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name, ppa_name, dist) else: repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist) else: raise CommandExecutionError( 'cannot parse "ppa:" style repo definitions: {0}'.format(repo)) sources = sourceslist.SourcesList() if kwargs.get('consolidate', False): # attempt to de-dup and consolidate all sources # down to entries in sources.list # this option makes it easier to keep the sources # list in a "sane" state. # # this should remove duplicates, consolidate comps # for a given source down to one line # and eliminate "invalid" and comment lines # # the second side effect is removal of files # that are not the main sources.list file sources = _consolidate_repo_sources(sources) repos = filter(lambda s: not s.invalid, sources) mod_source = None try: repo_type, repo_uri, repo_dist, repo_comps = _split_repo_str(repo) except SyntaxError: raise SyntaxError( 'Error: repo {0!r} not a well formatted definition'.format(repo)) full_comp_list = set(repo_comps) if 'keyid' in kwargs: keyid = kwargs.pop('keyid', None) ks = kwargs.pop('keyserver', None) if not keyid or not ks: error_str = 'both keyserver and keyid options required.' raise NameError(error_str) cmd = 'apt-key export {0}'.format(keyid) output = __salt__['cmd.run_stdout'](cmd, **kwargs) imported = output.startswith('-----BEGIN PGP') if ks: if not imported: cmd = ('apt-key adv --keyserver {0} --logger-fd 1 ' '--recv-keys {1}') ret = __salt__['cmd.run_all'](cmd.format(ks, keyid), **kwargs) if ret['retcode'] != 0: raise CommandExecutionError( 'Error: key retrieval failed: {0}'.format( ret['stdout'])) elif 'key_url' in kwargs: key_url = kwargs['key_url'] fn_ = __salt__['cp.cache_file'](key_url, saltenv) cmd = 'apt-key add {0}'.format(fn_) out = __salt__['cmd.run_stdout'](cmd, **kwargs) if not out.upper().startswith('OK'): raise CommandExecutionError( 'Error: key retrieval failed: {0}'.format(cmd.format(key_url))) if 'comps' in kwargs: kwargs['comps'] = kwargs['comps'].split(',') full_comp_list.union(set(kwargs['comps'])) else: kwargs['comps'] = list(full_comp_list) if 'architectures' in kwargs: kwargs['architectures'] = kwargs['architectures'].split(',') if 'disabled' in kwargs: kw_disabled = kwargs['disabled'] if kw_disabled is True or str(kw_disabled).lower() == 'true': kwargs['disabled'] = True else: kwargs['disabled'] = False kw_type = kwargs.get('type') kw_dist = kwargs.get('dist') for source in repos: # This series of checks will identify the starting source line # and the resulting source line. The idea here is to ensure # we are not retuning bogus data because the source line # has already been modified on a previous run. if ((source.type == repo_type and source.uri == repo_uri and source.dist == repo_dist) or (source.dist == kw_dist and source.type == kw_type and source.type == kw_type)): for comp in full_comp_list: if comp in getattr(source, 'comps', []): mod_source = source if not source.comps: mod_source = source if mod_source: break if not mod_source: mod_source = sourceslist.SourceEntry(repo) sources.list.append(mod_source) # if all comps aren't part of the disable # match, it is important we keep the comps # not destined to be disabled/enabled in # the original state if ('disabled' in kwargs and mod_source.disabled != kwargs['disabled']): s_comps = set(mod_source.comps) r_comps = set(repo_comps) if s_comps.symmetric_difference(r_comps): new_source = sourceslist.SourceEntry(source.line) new_source.file = source.file new_source.comps = list(r_comps.difference(s_comps)) source.comps = list(s_comps.difference(r_comps)) sources.insert(sources.index(source), new_source) sources.save() for key in kwargs: if key in _MODIFY_OK and hasattr(mod_source, key): setattr(mod_source, key, kwargs[key]) sources.save() # on changes, explicitly refresh refresh_db() return { repo: { 'architectures': getattr(mod_source, 'architectures', []), 'comps': mod_source.comps, 'disabled': mod_source.disabled, 'file': mod_source.file, 'type': mod_source.type, 'uri': mod_source.uri, 'line': mod_source.line } }
#! /usr/bin/python3 import aptsources.sourceslist as sl import lsb_release codename = lsb_release.get_distro_information()['CODENAME'] sources = sl.SourcesList() for source in sources.list: if source.comment.lower().find("disabled on upgrade") >= 0: source.dist = codename source.set_enabled(True) print(source) sources.save()
def mod_repo(repo, refresh=False, **kwargs): ''' Modify one or more values for a repo. If the repo does not exist, it will be created, so long as the definition is well formed. For Ubuntu the "ppa:<project>/repo" format is acceptable. "ppa:" format can only be used to create a new repository. The following options are available to modify a repo definition:: comps (a comma separated list of components for the repo, e.g. "main") file (a file name to be used) refresh (refresh the apt sources db when the mod is done) keyserver (keyserver to get gpg key from) keyid (key id to load with the keyserver argument) key_url (URl to a gpg key to add to the apt gpg keyring) consolidate (if true, will attempt to de-dup and consolidate sources) CLI Examples:: salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe ''' if not apt_support: raise ImportError('Error: aptsources.sourceslist module not found') # to ensure no one sets some key values that _shouldn't_ be changed on the # object itself, this is just a white-list of "ok" to set properties _MODIFY_OK = set( ['uri', 'comps', 'architectures', 'disabled', 'file', 'dist']) if repo.startswith('ppa:') and __grains__['os'] == 'Ubuntu': if not ppa_format_support: error_str = 'cannot parse "ppa:" style repo definitions: {0}' raise Exception(error_str.format(repo)) cmd = 'apt-add-repository -y {0}'.format(repo) out = __salt__['cmd.run_stdout'](cmd) if refresh is True or str(refresh).lower() == 'true': refresh_db() return {repo: out} else: sources = sourceslist.SourcesList() if kwargs.get('consolidate', False): # attempt to de-dup and consolidate all sources # down to entries in sources.list # this option makes it easier to keep the sources # list in a "sane" state. # # this should remove duplicates, consolidate comps # for a given source down to one line # and eliminate "invalid" and comment lines # # the second side effect is removal of files # that are not the main sources.list file sources = _consolidate_repo_sources(sources) repos = filter(lambda s: not s.invalid, sources) if repos: mod_source = None try: repo_type, repo_uri, repo_dist, repo_comps = _split_repo_str( repo) except SyntaxError: error_str = 'Error: repo "{0}" not a well formatted definition' raise SyntaxError(error_str.format(repo)) full_comp_list = set(repo_comps) if 'keyid' in kwargs: keyid = kwargs.pop('keyid', None) ks = kwargs.pop('keyserver', None) if not keyid or not ks: error_str = 'both keyserver and keyid options required.' raise NameError(error_str) cmd = 'apt-key export {0}'.format(keyid) output = __salt__['cmd.run_stdout'](cmd) imported = output.startswith('-----BEGIN PGP') if ks: cmd = 'apt-key export {0}'.format(keyid) output = __salt__['cmd.run_stdout'](cmd) if not imported: cmd = ('apt-key adv --keyserver {0} --logger-fd 1 ' '--recv-keys {1}') out = __salt__['cmd.run_stdout'](cmd.format(ks, keyid)) if not out.find('imported') or out.find('not changed'): error_str = 'Error: key retrieval failed: {0}' raise Exception( error_str.format(cmd.format(ks, keyid))) elif 'key_url' in kwargs: key_url = kwargs.pop('key_url', None) cmd = 'wget -q -O- {0} | apt-key add -'.format(key_url) out = __salt__['cmd.run_stdout'](cmd) if not out.upper().startswith('OK'): error_str = 'Error: key retrieval failed: {0}' raise Exception(error_str.format(cmd.format(key_url))) if 'comps' in kwargs: kwargs['comps'] = kwargs['comps'].split(',') full_comp_list.union(set(kwargs['comps'])) else: kwargs['comps'] = list(full_comp_list) if 'architectures' in kwargs: kwargs['architectures'] = kwargs['architectures'].split(',') if 'disabled' in kwargs: kw_disabled = kwargs['disabled'] if kw_disabled is True or str(kw_disabled).lower() == 'true': kwargs['disabled'] = True else: kwargs['disabled'] = False kw_type = kwargs.get('type') kw_dist = kwargs.get('dist') for source in repos: # This series of checks will identify the starting source line # and the resulting source line. The idea here is to ensure # we are not retuning bogus data because the source line # has already been modified on a previous run. if ((source.type == repo_type and source.uri == repo_uri and source.dist == repo_dist) or (source.dist == kw_dist and source.type == kw_type and source.type == kw_type)): for comp in full_comp_list: if comp in getattr(source, 'comps', []): mod_source = source if not source.comps: mod_source = source if mod_source: break if not mod_source: mod_source = sourceslist.SourceEntry(repo) sources.list.append(mod_source) # if all comps aren't part of the disable # match, it is important we keep the comps # not destined to be disabled/enabled in # the original state if ('disabled' in kwargs and mod_source.disabled != kwargs['disabled']): s_comps = set(mod_source.comps) r_comps = set(repo_comps) if s_comps.symmetric_difference(r_comps): new_source = sourceslist.SourceEntry(source.line) new_source.file = source.file new_source.comps = list(r_comps.difference(s_comps)) source.comps = list(s_comps.difference(r_comps)) sources.insert(sources.index(source), new_source) sources.save() for key in kwargs: if key in _MODIFY_OK and hasattr(mod_source, key): if type(getattr(mod_source, key)) == type(kwargs[key]): setattr(mod_source, key, kwargs[key]) sources.save() if refresh is True or str(refresh).lower() == 'true': refresh_db() return { repo: { 'architectures': getattr(mod_source, 'architectures', []), 'comps': mod_source.comps, 'disabled': mod_source.disabled, 'file': mod_source.file, 'type': mod_source.type, 'uri': mod_source.uri, 'line': mod_source.line, } }
def listSources(self): from aptsources import sourceslist return sourceslist.SourcesList()
def del_repo(repo, refresh=False): ''' Delete a repo from the sources.list / sources.list.d If the .list file is in the sources.list.d directory and the file that the repo exists in does not contain any other repo configuration, the file itself will be deleted. The repo passed in must be a fully formed repository definition string. CLI Examples:: salt '*' pkg.del_repo "myrepo definition" salt '*' pkg.del_repo "myrepo definition" refresh=True ''' if not apt_support: return 'Error: aptsources.sourceslist python module not found' is_ppa = False if repo.startswith('ppa:') and __grains__['os'] == 'Ubuntu': # This is a PPA definition meaning special handling is needed # to derive the name. is_ppa = True if not ppa_format_support: error_str = 'Error: cannot parse "ppa:" style repo definition: {0}' return error_str.format(repo) repo = softwareproperties.ppa.expand_ppa_line( repo, __grains__['lsb_codename'])[0] sources = sourceslist.SourcesList() repos = filter(lambda s: not s.invalid, sources.list) if repos: deleted_from = dict() try: repo_type, repo_uri, repo_dist, repo_comps = _split_repo_str(repo) except SyntaxError: error_str = 'Error: repo "{0}" not a well formatted definition' return error_str.format(repo) for source in repos: if (source.type == repo_type and source.uri == repo_uri and source.dist == repo_dist): s_comps = set(source.comps) r_comps = set(repo_comps) if s_comps.intersection(r_comps): deleted_from[source.file] = 0 source.comps = list(s_comps.difference(r_comps)) if not source.comps: try: sources.remove(source) except ValueError: pass # PPAs are special and can add deb-src where expand_ppa_line doesn't # always reflect this. Lets just cleanup here for good measure if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and source.uri == repo_uri and source.dist == repo_dist): s_comps = set(source.comps) r_comps = set(repo_comps) if s_comps.intersection(r_comps): deleted_from[source.file] = 0 source.comps = list(s_comps.difference(r_comps)) if not source.comps: try: sources.remove(source) except ValueError: pass sources.save() if deleted_from: ret = '' for source in sources: if source.file in deleted_from: deleted_from[source.file] += 1 for repo_file, c in deleted_from.iteritems(): msg = 'Repo "{0}" has been removed from {1}.\n' if c == 0 and 'sources.list.d/' in repo_file: if os.path.isfile(repo_file): msg = ('File {1} containing repo "{0}" has been ' 'removed.\n') try: os.remove(repo_file) except OSError: pass ret += msg.format(repo, repo_file) if refresh or str(refresh).lower() == 'true': refresh_db() return ret return "Repo {0} doesn't exist in the sources.list(s)".format(repo)
def captureState(self): """Determines the state of the items managed by this plugin and stores it into the plugin's own internal structures""" self.versions = [] for line in open("/etc/lsb-release"): if "DISTRIB_CODENAME" in line: line = line.strip("\n") throwaway, distro = line.split("=") NumRepos = 0 if os.path.isfile(self.USERHOME + "/.mythbuntu/repos.db"): self.versions = [] for line in open(self.USERHOME + "/.mythbuntu/repos.db"): if distro in line: line = line.strip("\n") release, version = line.split("\t") if not version in self.versions: self.versions.append(version) NumRepos += 1 elif "MYTHTV_RELEASE" in line: line = line.strip("\n") VerName, self.CurVer = line.split("\t") elif "TRUNKPASS" in line: line = line.strip("\n") discard, self.TRUNKPASS = line.split("\t") elif "URL" in line: line = line.strip("\n") discard, self.DOWNLOADURL = line.split("\t") self.download_repo_db_label.hide() self.mythtv_updates_alignment.show() self.mythtv_updates_ckbox_alignment.show() self.mythtv_updates_label.show() self.mythtv_updates_checkbox.show() self.repobox.show() self.hseparator5.show() self.hseparator6.show() self.footer_alignment.show() if NumRepos == 0: self.versions.append('0') self.CurVer = '0' self.download_repo_db_label.show() self.mythtv_updates_alignment.hide() self.mythtv_updates_ckbox_alignment.hide() self.mythtv_updates_label.hide() self.mythtv_updates_checkbox.hide() self.repobox.hide() self.hseparator5.hide() self.hseparator6.hide() self.footer_alignment.hide() self.trunk_block.hide() self.DOWNLOADURL = 'https://raw.githubusercontent.com/mythcp/mythbuntu-control-panel/master/repos.db' self.changes = {} self.repobox.get_model().clear() for item in self.versions: self.builder.get_object('repobox').append_text(item) if os.path.exists(self.CONFIGFILE): self.config.read(self.CONFIGFILE) try: self.changes['MythTVUpdatesActivated'] = self.config.getboolean( "cfg", "ActivateMythTVUpdates") except: self.changes['MythTVUpdatesActivated'] = False try: self.changes['MythTVUpdatesRepo'] = self.config.get( "cfg", "MythTVRepo") except: self.changes['MythTVUpdatesRepo'] = self.versions[0] #MCP Updates PPA current state sources = sl.SourcesList() self.MCPUpdatesActivated = False # False unless determined true below for entry in sources: if 'ppa.launchpad.net/mythcp/mcp' in entry.str( ) and entry.str()[0] != "#": self.MCPUpdatesActivated = True break