Skip to content

Commit

Permalink
Merge pull request #57 from pop-os/typing-fixes
Browse files Browse the repository at this point in the history
Fixes for potential TypeErrors (and related type errors)
  • Loading branch information
isantop committed Oct 19, 2022
2 parents b65bfd5 + f31c457 commit 085414e
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 67 deletions.
2 changes: 1 addition & 1 deletion repolib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
}

if systemd_support:
journald_log = JournalHandler()
journald_log = JournalHandler() # type: ignore (this is handled by the wrapping if)
journald_log.setLevel(logging.INFO)
journald_log.setFormatter(stream_fmt)
log.addHandler(journald_log)
Expand Down
20 changes: 19 additions & 1 deletion repolib/command/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ def run(self) -> bool:
print('Fetching repository information...')

self.log.debug('Adding line %s', self.deb_line)

new_source: Source = Source()

for prefix in shortcut_prefixes:
self.log.debug('Trying prefix %s', prefix)
Expand All @@ -169,9 +171,25 @@ def run(self) -> bool:
except IndexError:
pass
return False

new_source.load_from_data([self.deb_line])
break

new_source.load_from_data([self.deb_line])

if not new_source:
self.log.error(
f'Could not parse line "{self.deb_line}". Double-check the '
'spelling.'
)
valid_shortcuts: str = ''
for shortcut in shortcut_prefixes:
if shortcut.startswith('deb'):
continue
valid_shortcuts += f'{shortcut}, '
valid_shortcuts = valid_shortcuts.strip(', ')
print(f'Supported repository shortcuts:\n {valid_shortcuts}')
return False

new_source.twin_source = True
new_source.sourcecode_enabled = self.source_code

Expand Down
5 changes: 2 additions & 3 deletions repolib/command/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Key(Command):
"""

@classmethod
def init_options(self, subparsers):
def init_options(cls, subparsers) -> None:
"""Sets up this command's options parser"""

sub = subparsers.add_parser(
Expand Down Expand Up @@ -127,7 +127,6 @@ def finalize_options(self, args):
self.keyserver = args.keyserver

self.actions:dict = {}
self.source = None
self.system_source = False

for act in [
Expand Down Expand Up @@ -248,7 +247,7 @@ def url(self, value:str) -> bool:
self.source.load_key()
return True

def ascii(self, value:str) -> None:
def ascii(self, value:str) -> bool:
"""Loads the key from provided ASCII-armored data"""
if not value:
return False
Expand Down
23 changes: 12 additions & 11 deletions repolib/command/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,18 @@ def list_legacy(self, indent) -> None:
sources_list_file = None

print('Legacy source.list sources:')
with open(sources_list_file, mode='r') as file:
for line in file:
if 'cdrom' in line:
line = ''

try:
source = Source()
source.load_from_data([line])
print(textwrap.indent(source.ui, indent))
except SourceError:
pass
if sources_list_file:
with open(sources_list_file, mode='r') as file:
for line in file:
if 'cdrom' in line:
line = ''

try:
source = Source()
source.load_from_data([line])
print(textwrap.indent(source.ui, indent))
except SourceError:
pass

def list_all(self):
"""List all sources presently configured in the system
Expand Down
15 changes: 6 additions & 9 deletions repolib/command/modify.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,6 @@ def run(self):
try:
self.source = util.sources[self.repo]
except KeyError:
self.source = None

if not self.source:
self.log.error(
'The source %s could not be found. Check the spelling',
self.repo
Expand Down Expand Up @@ -299,7 +296,7 @@ def source_endisable(self, value:str) -> bool:
self.source.sourcecode_enabled = True
return True

def add_uri(self, values:list) -> bool:
def add_uri(self, values:str) -> bool:
"""Adds URIs to the source, if not already present."""
if not values:
return False
Expand Down Expand Up @@ -330,7 +327,7 @@ def add_uri(self, values:list) -> bool:
return True
return False

def remove_uri(self, values:list) -> bool:
def remove_uri(self, values:str) -> bool:
"""Remove URIs from the soruce, if they are added."""
if not values:
return False
Expand Down Expand Up @@ -364,7 +361,7 @@ def remove_uri(self, values:list) -> bool:

return False

def add_suite(self, values:list) -> bool:
def add_suite(self, values:str) -> bool:
"""Adds a suite to the source"""
if not values:
return False
Expand All @@ -389,7 +386,7 @@ def add_suite(self, values:list) -> bool:
return True
return False

def remove_suite(self, values:list) -> bool:
def remove_suite(self, values:str) -> bool:
"""Remove a suite from the source"""
if not values:
return False
Expand Down Expand Up @@ -423,7 +420,7 @@ def remove_suite(self, values:list) -> bool:

return False

def add_component(self, values:list) -> bool:
def add_component(self, values:str) -> bool:
"""Adds components to the source"""
if not values:
return False
Expand Down Expand Up @@ -455,7 +452,7 @@ def add_component(self, values:list) -> bool:
return True
return False

def remove_component(self, values:list) -> bool:
def remove_component(self, values:str) -> bool:
"""Removes components from the source"""
if not values:
return False
Expand Down
17 changes: 9 additions & 8 deletions repolib/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def __init__(self, name:str='') -> None:
"""
self.log = logging.getLogger(__name__)
self.name:str = ''
self.path:Path = None
self.alt_path:Path = None
self.path:Path = Path()
self.alt_path:Path = Path()
self.format:util.SourceFormat = util.SourceFormat.DEFAULT
self.contents:list = []
self.sources:list = []
Expand Down Expand Up @@ -108,7 +108,7 @@ def remove_source(self, ident:str) -> None:
## Remove sources prefs files/pin-priority
prefs_path = source.prefs
try:
if prefs_path.exists():
if prefs_path.exists() and prefs_path.name:
prefs_path.unlink()

except AttributeError:
Expand Down Expand Up @@ -290,7 +290,7 @@ def load(self) -> None:
elif valid_legacy:
if self.format != util.SourceFormat.LEGACY:
raise SourceFileError(
f'File {self.ident} is an updated file, but '
f'File {self.path.name} is an updated file, but '
'contains legacy-format sources. This is not '
'allowed. Please fix the file manually.'
)
Expand Down Expand Up @@ -321,7 +321,7 @@ def load(self) -> None:
if util.validate_debline(line.strip()):
if self.format != util.SourceFormat.LEGACY:
raise SourceFileError(
f'File {self.ident} is an updated file, but '
f'File {self.path.name} is an updated file, but '
'contains legacy-format sources. This is not '
'allowed. Please fix the file manually.'
)
Expand Down Expand Up @@ -353,7 +353,7 @@ def load(self) -> None:
if line.startswith(key):
if self.format == util.SourceFormat.LEGACY:
raise SourceFileError(
f'File {self.ident} is a DEB822-format file, but '
f'File {self.path.name} is a DEB822-format file, but '
'contains legacy sources. This is not allowed. '
'Please fix the file manually.'
)
Expand Down Expand Up @@ -472,13 +472,14 @@ def save(self) -> None:

## Attribute properties
@property
def format(self) -> util.SourceFormat:
def format(self) -> util.SourceFormat: # type: ignore (We don't use str.format)
"""The format of the file on disk"""
return self._format

@format.setter
def format(self, format:util.SourceFormat) -> None:
def format(self, format:util.SourceFormat) -> None: # type: ignore (We don't use str.format)
"""The path needs to be updated when the format changes"""
alt_format:util.SourceFormat = util.SourceFormat.LEGACY
self._format = format
self.path = util.SOURCES_DIR / f'{self.name}.{self._format.value}'
for format_ in util.SourceFormat:
Expand Down
8 changes: 4 additions & 4 deletions repolib/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ class SourceKey:

def __init__(self, name:str = '') -> None:
self.log = logging.getLogger(__name__)
self.tmp_path = None
self.path = None
self.gpg = None
self.data = None
self.tmp_path = Path()
self.path = Path()
self.gpg = gnupg.GPG()
self.data = b''

if name:
self.reset_path(name=name)
Expand Down
16 changes: 8 additions & 8 deletions repolib/parsedeb.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,20 +213,20 @@ def __init__(self, debug:bool = False) -> None:
self.curr_line: str = ''
self.curr_line_valid: bool = False

def parse_options(self, options:str) -> dict:
def parse_options(self, opt:str) -> dict:
""" Parses a string of options into a dictionary that repolib can use.
Arguments:
options(str): The string with options returned from the line parser.
opt(str): The string with options returned from the line parser.
Returns:
`dict`: The dictionary of options with key:val pairs (may be {})
"""
options = options.strip()
options = options[1:-1].strip() # Remove enclosing brackets
options = options.split()
opt = opt.strip()
opt = opt[1:-1].strip() # Remove enclosing brackets
options = opt.split()

parsed_options:dict(str, str) = {}
parsed_options:dict = {}

for opt in options:
pre_key, values = opt.split('=')
Expand All @@ -236,7 +236,7 @@ def parse_options(self, options:str) -> dict:
key:str = util.options_inmap[pre_key]
except KeyError:
raise DebParseError(
f'Could not parse line {self.curr_line}: option {key} is '
f'Could not parse line {self.curr_line}: option {opt} is '
'not a valid debian repository option or is unsupported.'
)
parsed_options[key] = value
Expand Down Expand Up @@ -285,7 +285,7 @@ def parse_line(self, line:str) -> dict:

comments_index = line.find('#')
if comments_index > 0:
raw_comments:list = line[comments_index + 1:].strip()
raw_comments:str = line[comments_index + 1:].strip()
(
line_parsed['name'],
line_parsed['ident'],
Expand Down
6 changes: 3 additions & 3 deletions repolib/shortcuts/popdev.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def validator(shortcut:str) -> bool:

return False

def __init__(self, *args, line=None, fetch_data=True, **kwargs):
def __init__(self, *args, line='', fetch_data=True, **kwargs):
if line:
if not line.startswith('ppa:'):
raise SourceError(f'The PPA shortcut {line} is malformed')
Expand All @@ -91,7 +91,7 @@ def __init__(self, *args, line=None, fetch_data=True, **kwargs):
self.branch_name:str = ''
self.branch_url:str = ''
if line:
self.load_from_shortcut(self.line)
self.load_from_shortcut(line)

def tasks_save(self, *args, **kwargs) -> None:
super().tasks_save(*args, **kwargs)
Expand Down Expand Up @@ -121,7 +121,7 @@ def load_from_data(self, data: list) -> None:
self.log.debug('Loading line %s', data[0])
self.load_from_shortcut(shortcut=data[0])

def load_from_shortcut(self, shortcut:str='', meta:bool=True, key:bool=True) -> None:
def load_from_shortcut(self, shortcut:str='', meta:bool=True, get_key:bool=True) -> None:
"""Translates the shortcut line into a full repo.
Arguments:
Expand Down
30 changes: 17 additions & 13 deletions repolib/shortcuts/ppa.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@
from launchpadlib.launchpad import Launchpad
from lazr.restfulclient.errors import BadRequest, NotFound, Unauthorized
except ImportError:
Launchpad = None
raise SourceError(
'Missing optional dependency "launchpadlib". Try `sudo apt install '
'python3-launchpadlib` to install it.'
)

BASE_FORMAT = util.SourceFormat.LEGACY
BASE_URL = 'http://ppa.launchpad.net'
Expand Down Expand Up @@ -74,7 +77,7 @@ def validator(shortcut:str) -> bool:
return True
return False

def __init__(self, *args, line=None, fetch_data=True, **kwargs):
def __init__(self, *args, line='', fetch_data=True, **kwargs):
if line:
if not line.startswith('ppa:'):
raise SourceError(f'The PPA shortcut {line} is malformed')
Expand All @@ -93,6 +96,7 @@ def get_description(self) -> str:
output += self.displayname
output += '\n\n'
output += self.description
return output

def load_from_data(self, data: list) -> None:
self.load_from_shortcut(shortcut=data[0])
Expand Down Expand Up @@ -145,13 +149,13 @@ def load_from_shortcut(self, shortcut:str='', meta:bool=True, key:bool=True) ->
self.name = self.ppa.displayname

if self.ppa and key:
key = SourceKey(name=self.ident)
if str(key.path) not in util.keys:
key.load_key_data(fingerprint=self.ppa.fingerprint)
util.keys[str(key.path)] = key
self.key = key
repo_key = SourceKey(name=self.ident)
if str(repo_key.path) not in util.keys:
repo_key.load_key_data(fingerprint=self.ppa.fingerprint)
util.keys[str(repo_key.path)] = repo_key
self.key:SourceKey = repo_key
else:
self.key = util.keys[key.path]
self.key = util.keys[repo_key.path]
self.signed_by = str(self.key.path)

self.enabled = True
Expand Down Expand Up @@ -215,7 +219,7 @@ def lpteam(self):
""" The Launchpad object for the PPA's owner."""
if not self._lpteam:
try:
self._lpteam = self.lap.people(self.teamname)
self._lpteam = self.lap.people(self.teamname) # type: ignore (This won't actually be unbound because of the property)
except NotFound as err:
msg = f'User/Team "{self.teamname}" not found'
raise SourceError(msg) from err
Expand All @@ -239,14 +243,14 @@ def lpppa(self):
return self._lpppa

@property
def description(self):
def description(self) -> str:
"""str: The description of the PPA."""
return self.lpppa.description
return self.lpppa.description or ''

@property
def displayname(self):
def displayname(self) -> str:
""" str: the fancy name of the PPA."""
return self.lpppa.displayname
return self.lpppa.displayname or ''

@property
def fingerprint(self):
Expand Down

0 comments on commit 085414e

Please sign in to comment.