idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
19,100
def shorten ( string , maxlen ) : if 1 < maxlen < len ( string ) : string = string [ : maxlen - 1 ] + u'…' return string [ : maxlen ]
shortens string if longer than maxlen appending ellipsis
19,101
def call_cmd ( cmdlist , stdin = None ) : termenc = urwid . util . detected_encoding if isinstance ( stdin , str ) : stdin = stdin . encode ( termenc ) try : logging . debug ( "Calling %s" % cmdlist ) proc = subprocess . Popen ( cmdlist , stdout = subprocess . PIPE , stderr = subprocess . PIPE , stdin = subprocess . PIPE if stdin is not None else None ) except OSError as e : out = b'' err = e . strerror ret = e . errno else : out , err = proc . communicate ( stdin ) ret = proc . returncode out = string_decode ( out , termenc ) err = string_decode ( err , termenc ) return out , err , ret
get a shell commands output error message and return value and immediately return .
19,102
async def call_cmd_async ( cmdlist , stdin = None , env = None ) : termenc = urwid . util . detected_encoding cmdlist = [ s . encode ( termenc ) for s in cmdlist ] environment = os . environ . copy ( ) if env is not None : environment . update ( env ) logging . debug ( 'ENV = %s' , environment ) logging . debug ( 'CMD = %s' , cmdlist ) try : proc = await asyncio . create_subprocess_exec ( * cmdlist , env = environment , stdout = asyncio . subprocess . PIPE , stderr = asyncio . subprocess . PIPE , stdin = asyncio . subprocess . PIPE if stdin else None ) except OSError as e : return ( '' , str ( e ) , 1 ) out , err = await proc . communicate ( stdin . encode ( termenc ) if stdin else None ) return ( out . decode ( termenc ) , err . decode ( termenc ) , proc . returncode )
Given a command call that command asynchronously and return the output .
19,103
def guess_mimetype ( blob ) : mimetype = 'application/octet-stream' if hasattr ( magic , 'open' ) : m = magic . open ( magic . MAGIC_MIME_TYPE ) m . load ( ) magictype = m . buffer ( blob ) elif hasattr ( magic , 'from_buffer' ) : magictype = magic . from_buffer ( blob , mime = True ) or magictype else : raise Exception ( 'Unknown magic API' ) if re . match ( r'\w+\/\w+' , magictype ) : mimetype = magictype return mimetype
uses file magic to determine the mime - type of the given data blob .
19,104
def guess_encoding ( blob ) : if hasattr ( magic , 'open' ) : m = magic . open ( magic . MAGIC_MIME_ENCODING ) m . load ( ) return m . buffer ( blob ) elif hasattr ( magic , 'from_buffer' ) : m = magic . Magic ( mime_encoding = True ) return m . from_buffer ( blob ) else : raise Exception ( 'Unknown magic API' )
uses file magic to determine the encoding of the given data blob .
19,105
def libmagic_version_at_least ( version ) : if hasattr ( magic , 'open' ) : magic_wrapper = magic . _libraries [ 'magic' ] elif hasattr ( magic , 'from_buffer' ) : magic_wrapper = magic . libmagic else : raise Exception ( 'Unknown magic API' ) if not hasattr ( magic_wrapper , 'magic_version' ) : return False return magic_wrapper . magic_version >= version
checks if the libmagic library installed is more recent than a given version .
19,106
def mimewrap ( path , filename = None , ctype = None ) : with open ( path , 'rb' ) as f : content = f . read ( ) if not ctype : ctype = guess_mimetype ( content ) if ( ctype == 'application/msword' and not libmagic_version_at_least ( 513 ) ) : mimetype , _ = mimetypes . guess_type ( path ) if mimetype : ctype = mimetype maintype , subtype = ctype . split ( '/' , 1 ) if maintype == 'text' : part = MIMEText ( content . decode ( guess_encoding ( content ) , 'replace' ) , _subtype = subtype , _charset = 'utf-8' ) elif maintype == 'image' : part = MIMEImage ( content , _subtype = subtype ) elif maintype == 'audio' : part = MIMEAudio ( content , _subtype = subtype ) else : part = MIMEBase ( maintype , subtype ) part . set_payload ( content ) email . encoders . encode_base64 ( part ) if not filename : filename = os . path . basename ( path ) part . add_header ( 'Content-Disposition' , 'attachment' , filename = filename ) return part
Take the contents of the given path and wrap them into an email MIME part according to the content type . The content type is auto detected from the actual file contents and the file name if it is not given .
19,107
def parse_mailcap_nametemplate ( tmplate = '%s' ) : nt_list = tmplate . split ( '%s' ) template_prefix = '' template_suffix = '' if len ( nt_list ) == 2 : template_suffix = nt_list [ 1 ] template_prefix = nt_list [ 0 ] else : template_suffix = tmplate return ( template_prefix , template_suffix )
this returns a prefix and suffix to be used in the tempfile module for a given mailcap nametemplate string
19,108
def parse_mailto ( mailto_str ) : if mailto_str . startswith ( 'mailto:' ) : import urllib . parse to_str , parms_str = mailto_str [ 7 : ] . partition ( '?' ) [ : : 2 ] headers = { } body = u'' to = urllib . parse . unquote ( to_str ) if to : headers [ 'To' ] = [ to ] for s in parms_str . split ( '&' ) : key , value = s . partition ( '=' ) [ : : 2 ] key = key . capitalize ( ) if key == 'Body' : body = urllib . parse . unquote ( value ) elif value : headers [ key ] = [ urllib . parse . unquote ( value ) ] return ( headers , body ) else : return ( None , None )
Interpret mailto - string
19,109
def lookup ( self , query = '' ) : res = [ ] query = re . compile ( '.*%s.*' % re . escape ( query ) , self . reflags ) for name , email in self . get_contacts ( ) : if query . match ( name ) or query . match ( email ) : res . append ( ( name , email ) ) return res
looks up all contacts where name or address match query
19,110
def set_focus ( self , pos ) : "Set the focus in the underlying body widget." logging . debug ( 'setting focus to %s ' , pos ) self . body . set_focus ( pos )
Set the focus in the underlying body widget .
19,111
def focus_parent ( self ) : mid = self . get_selected_mid ( ) newpos = self . _tree . parent_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) self . body . set_focus ( newpos )
move focus to parent of currently focussed message
19,112
def focus_first_reply ( self ) : mid = self . get_selected_mid ( ) newpos = self . _tree . first_child_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) self . body . set_focus ( newpos )
move focus to first reply to currently focussed message
19,113
def focus_last_reply ( self ) : mid = self . get_selected_mid ( ) newpos = self . _tree . last_child_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) self . body . set_focus ( newpos )
move focus to last reply to currently focussed message
19,114
def focus_next_sibling ( self ) : mid = self . get_selected_mid ( ) newpos = self . _tree . next_sibling_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) self . body . set_focus ( newpos )
focus next sibling of currently focussed message in thread tree
19,115
def focus_prev_sibling ( self ) : mid = self . get_selected_mid ( ) localroot = self . _sanitize_position ( ( mid , ) ) if localroot == self . get_focus ( ) [ 1 ] : newpos = self . _tree . prev_sibling_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) else : newpos = localroot if newpos is not None : self . body . set_focus ( newpos )
focus previous sibling of currently focussed message in thread tree
19,116
def focus_next ( self ) : mid = self . get_selected_mid ( ) newpos = self . _tree . next_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) self . body . set_focus ( newpos )
focus next message in depth first order
19,117
def focus_prev ( self ) : mid = self . get_selected_mid ( ) localroot = self . _sanitize_position ( ( mid , ) ) if localroot == self . get_focus ( ) [ 1 ] : newpos = self . _tree . prev_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) else : newpos = localroot if newpos is not None : self . body . set_focus ( newpos )
focus previous message in depth first order
19,118
def focus_property ( self , prop , direction ) : newpos = self . get_selected_mid ( ) newpos = direction ( newpos ) while newpos is not None : MT = self . _tree [ newpos ] if prop ( MT ) : newpos = self . _sanitize_position ( ( newpos , ) ) self . body . set_focus ( newpos ) break newpos = direction ( newpos )
does a walk in the given direction and focuses the first message tree that matches the given property
19,119
def focus_next_matching ( self , querystring ) : self . focus_property ( lambda x : x . _message . matches ( querystring ) , self . _tree . next_position )
focus next matching message in depth first order
19,120
def focus_prev_matching ( self , querystring ) : self . focus_property ( lambda x : x . _message . matches ( querystring ) , self . _tree . prev_position )
focus previous matching message in depth first order
19,121
def focus_next_unfolded ( self ) : self . focus_property ( lambda x : not x . is_collapsed ( x . root ) , self . _tree . next_position )
focus next unfolded message in depth first order
19,122
def focus_prev_unfolded ( self ) : self . focus_property ( lambda x : not x . is_collapsed ( x . root ) , self . _tree . prev_position )
focus previous unfolded message in depth first order
19,123
def expand ( self , msgpos ) : MT = self . _tree [ msgpos ] MT . expand ( MT . root )
expand message at given position
19,124
def collapse ( self , msgpos ) : MT = self . _tree [ msgpos ] MT . collapse ( MT . root ) self . focus_selected_message ( )
collapse message at given position
19,125
def collapse_all ( self ) : for MT in self . messagetrees ( ) : MT . collapse ( MT . root ) self . focus_selected_message ( )
collapse all messages in thread
19,126
def unfold_matching ( self , querystring , focus_first = True ) : first = None for MT in self . messagetrees ( ) : msg = MT . _message if msg . matches ( querystring ) : MT . expand ( MT . root ) if first is None : first = ( self . _tree . position_of_messagetree ( MT ) , MT . root ) self . body . set_focus ( first ) else : MT . collapse ( MT . root ) self . body . refresh ( )
expand all messages that match a given querystring .
19,127
def __cmp ( self , other , comparitor ) : if not isinstance ( other , TagWidget ) : return NotImplemented self_len = len ( self . translated ) oth_len = len ( other . translated ) if ( self_len == 1 ) is not ( oth_len == 1 ) : return comparitor ( self_len , oth_len ) return comparitor ( self . translated . lower ( ) , other . translated . lower ( ) )
Shared comparison method .
19,128
def add_signature_headers ( mail , sigs , error_msg ) : sig_from = '' sig_known = True uid_trusted = False assert error_msg is None or isinstance ( error_msg , str ) if not sigs : error_msg = error_msg or u'no signature found' elif not error_msg : try : key = crypto . get_key ( sigs [ 0 ] . fpr ) for uid in key . uids : if crypto . check_uid_validity ( key , uid . email ) : sig_from = uid . uid uid_trusted = True break else : sig_from = key . uids [ 0 ] . uid except GPGProblem : sig_from = sigs [ 0 ] . fpr sig_known = False if error_msg : msg = 'Invalid: {}' . format ( error_msg ) elif uid_trusted : msg = 'Valid: {}' . format ( sig_from ) else : msg = 'Untrusted: {}' . format ( sig_from ) mail . add_header ( X_SIGNATURE_VALID_HEADER , 'False' if ( error_msg or not sig_known ) else 'True' ) mail . add_header ( X_SIGNATURE_MESSAGE_HEADER , msg )
Add pseudo headers to the mail indicating whether the signature verification was successful .
19,129
def get_params ( mail , failobj = None , header = 'content-type' , unquote = True ) : failobj = failobj or [ ] return { k . lower ( ) : v for k , v in mail . get_params ( failobj , header , unquote ) }
Get Content - Type parameters as dict .
19,130
def _handle_signatures ( original , message , params ) : malformed = None if len ( message . get_payload ( ) ) != 2 : malformed = u'expected exactly two messages, got {0}' . format ( len ( message . get_payload ( ) ) ) else : ct = message . get_payload ( 1 ) . get_content_type ( ) if ct != _APP_PGP_SIG : malformed = u'expected Content-Type: {0}, got: {1}' . format ( _APP_PGP_SIG , ct ) if not params . get ( 'micalg' , 'nothing' ) . startswith ( 'pgp-' ) : malformed = u'expected micalg=pgp-..., got: {0}' . format ( params . get ( 'micalg' , 'nothing' ) ) sigs = [ ] if not malformed : try : sigs = crypto . verify_detached ( message . get_payload ( 0 ) . as_bytes ( policy = email . policy . SMTP ) , message . get_payload ( 1 ) . get_payload ( decode = True ) ) except GPGProblem as e : malformed = str ( e ) add_signature_headers ( original , sigs , malformed )
Shared code for handling message signatures .
19,131
def _handle_encrypted ( original , message , session_keys = None ) : malformed = False ct = message . get_payload ( 0 ) . get_content_type ( ) if ct != _APP_PGP_ENC : malformed = u'expected Content-Type: {0}, got: {1}' . format ( _APP_PGP_ENC , ct ) want = 'application/octet-stream' ct = message . get_payload ( 1 ) . get_content_type ( ) if ct != want : malformed = u'expected Content-Type: {0}, got: {1}' . format ( want , ct ) if not malformed : payload = message . get_payload ( 1 ) . get_payload ( ) . encode ( 'ascii' ) try : sigs , d = crypto . decrypt_verify ( payload , session_keys ) except GPGProblem as e : malformed = str ( e ) else : n = decrypted_message_from_bytes ( d , session_keys ) original . attach ( n ) original . defects . extend ( n . defects ) if not sigs : if X_SIGNATURE_VALID_HEADER in n : for k in ( X_SIGNATURE_VALID_HEADER , X_SIGNATURE_MESSAGE_HEADER ) : original [ k ] = n [ k ] else : add_signature_headers ( original , sigs , '' ) if malformed : msg = u'Malformed OpenPGP message: {0}' . format ( malformed ) content = email . message_from_string ( msg , policy = email . policy . SMTP ) content . set_charset ( 'utf-8' ) original . attach ( content )
Handle encrypted messages helper .
19,132
def decrypted_message_from_message ( m , session_keys = None ) : del m [ X_SIGNATURE_VALID_HEADER ] del m [ X_SIGNATURE_MESSAGE_HEADER ] if m . is_multipart ( ) : p = get_params ( m ) if ( m . get_content_subtype ( ) == 'signed' and p . get ( 'protocol' ) == _APP_PGP_SIG ) : _handle_signatures ( m , m , p ) elif ( m . get_content_subtype ( ) == 'encrypted' and p . get ( 'protocol' ) == _APP_PGP_ENC and 'Version: 1' in m . get_payload ( 0 ) . get_payload ( ) ) : _handle_encrypted ( m , m , session_keys ) elif m . get_content_subtype ( ) == 'mixed' : sub = m . get_payload ( 0 ) if sub . is_multipart ( ) : p = get_params ( sub ) if ( sub . get_content_subtype ( ) == 'signed' and p . get ( 'protocol' ) == _APP_PGP_SIG ) : _handle_signatures ( m , sub , p ) elif ( sub . get_content_subtype ( ) == 'encrypted' and p . get ( 'protocol' ) == _APP_PGP_ENC ) : _handle_encrypted ( m , sub , session_keys ) return m
Detect and decrypt OpenPGP encrypted data in an email object . If this succeeds any mime messages found in the recovered plaintext message are added to the returned message object .
19,133
def decrypted_message_from_bytes ( bytestring , session_keys = None ) : return decrypted_message_from_message ( email . message_from_bytes ( bytestring , policy = email . policy . SMTP ) , session_keys )
Create a Message from bytes .
19,134
def render_part ( part , field_key = 'copiousoutput' ) : ctype = part . get_content_type ( ) raw_payload = remove_cte ( part ) rendered_payload = None _ , entry = settings . mailcap_find_match ( ctype , key = field_key ) if entry is not None : tempfile_name = None stdin = None handler_raw_commandstring = entry [ 'view' ] if '%s' in handler_raw_commandstring : nametemplate = entry . get ( 'nametemplate' , '%s' ) prefix , suffix = parse_mailcap_nametemplate ( nametemplate ) with tempfile . NamedTemporaryFile ( delete = False , prefix = prefix , suffix = suffix ) as tmpfile : tmpfile . write ( raw_payload ) tempfile_name = tmpfile . name else : stdin = raw_payload parms = tuple ( '=' . join ( p ) for p in part . get_params ( ) ) cmd = mailcap . subst ( entry [ 'view' ] , ctype , filename = tempfile_name , plist = parms ) logging . debug ( 'command: %s' , cmd ) logging . debug ( 'parms: %s' , str ( parms ) ) cmdlist = split_commandstring ( cmd ) stdout , _ , _ = helper . call_cmd ( cmdlist , stdin = stdin ) if stdout : rendered_payload = stdout if tempfile_name : os . unlink ( tempfile_name ) return rendered_payload
renders a non - multipart email part into displayable plaintext by piping its payload through an external script . The handler itself is determined by the mailcap entry for this part s ctype .
19,135
def remove_cte ( part , as_string = False ) : enc = part . get_content_charset ( ) or 'ascii' cte = str ( part . get ( 'content-transfer-encoding' , '7bit' ) ) . lower ( ) . strip ( ) payload = part . get_payload ( ) sp = '' bp = b'' logging . debug ( 'Content-Transfer-Encoding: "{}"' . format ( cte ) ) if cte not in [ 'quoted-printable' , 'base64' , '7bit' , '8bit' , 'binary' ] : logging . info ( 'Unknown Content-Transfer-Encoding: "{}"' . format ( cte ) ) if '7bit' in cte or 'binary' in cte : logging . debug ( 'assuming Content-Transfer-Encoding: 7bit' ) sp = payload if as_string : return sp bp = payload . encode ( 'utf-8' ) return bp elif '8bit' in cte : logging . debug ( 'assuming Content-Transfer-Encoding: 8bit' ) bp = payload . encode ( 'raw-unicode-escape' ) elif 'quoted-printable' in cte : logging . debug ( 'assuming Content-Transfer-Encoding: quoted-printable' ) bp = quopri . decodestring ( payload . encode ( 'ascii' ) ) elif 'base64' in cte : logging . debug ( 'assuming Content-Transfer-Encoding: base64' ) bp = base64 . b64decode ( payload ) else : logging . debug ( 'failed to interpret Content-Transfer-Encoding: ' '"{}"' . format ( cte ) ) if as_string : try : sp = bp . decode ( enc ) except LookupError : sp = helper . try_decode ( bp ) except UnicodeDecodeError as emsg : logging . debug ( 'Decoding failure: {}' . format ( emsg ) ) sp = helper . try_decode ( bp ) return sp return bp
Interpret MIME - part according to it s Content - Transfer - Encodings .
19,136
def extract_body ( mail , types = None , field_key = 'copiousoutput' ) : preferred = 'text/plain' if settings . get ( 'prefer_plaintext' ) else 'text/html' has_preferred = False if types is None : has_preferred = list ( typed_subpart_iterator ( mail , * preferred . split ( '/' ) ) ) body_parts = [ ] for part in mail . walk ( ) : if part . is_multipart ( ) : continue ctype = part . get_content_type ( ) if types is not None : if ctype not in types : continue cd = part . get ( 'Content-Disposition' , '' ) if cd . startswith ( 'attachment' ) : continue if has_preferred and ctype != preferred : continue if ctype == 'text/plain' : body_parts . append ( string_sanitize ( remove_cte ( part , as_string = True ) ) ) else : rendered_payload = render_part ( part ) if rendered_payload : body_parts . append ( string_sanitize ( rendered_payload ) ) elif cd : part . replace_header ( 'Content-Disposition' , 'attachment; ' + cd ) else : part . add_header ( 'Content-Disposition' , 'attachment;' ) return u'\n\n' . join ( body_parts )
Returns a string view of a Message .
19,137
def decode_header ( header , normalize = False ) : regex = r'"(=\?.+?\?.+?\?[^ ?]+\?=)"' value = re . sub ( regex , r'\1' , header ) logging . debug ( "unquoted header: |%s|" , value ) valuelist = email . header . decode_header ( value ) decoded_list = [ ] for v , enc in valuelist : v = string_decode ( v , enc ) decoded_list . append ( string_sanitize ( v ) ) value = '' . join ( decoded_list ) if normalize : value = re . sub ( r'\n\s+' , r' ' , value ) return value
decode a header value to a unicode string
19,138
def get_threads ( self , querystring , sort = 'newest_first' , exclude_tags = None ) : assert sort in self . _sort_orders q = self . query ( querystring ) q . set_sort ( self . _sort_orders [ sort ] ) if exclude_tags : for tag in exclude_tags : q . exclude_tag ( tag ) return self . async_ ( q . search_threads , ( lambda a : a . get_thread_id ( ) ) )
asynchronously look up thread ids matching querystring .
19,139
def add_message ( self , path , tags = None , afterwards = None ) : tags = tags or [ ] if self . ro : raise DatabaseROError ( ) if not is_subdir_of ( path , self . path ) : msg = 'message path %s ' % path msg += ' is not below notmuchs ' msg += 'root path (%s)' % self . path raise DatabaseError ( msg ) else : self . writequeue . append ( ( 'add' , afterwards , path , tags ) )
Adds a file to the notmuch index .
19,140
def remove_message ( self , message , afterwards = None ) : if self . ro : raise DatabaseROError ( ) path = message . get_filename ( ) self . writequeue . append ( ( 'remove' , afterwards , path ) )
Remove a message from the notmuch index
19,141
def save_named_query ( self , alias , querystring , afterwards = None ) : if self . ro : raise DatabaseROError ( ) self . writequeue . append ( ( 'setconfig' , afterwards , 'query.' + alias , querystring ) )
add an alias for a query string .
19,142
def remove_named_query ( self , alias , afterwards = None ) : if self . ro : raise DatabaseROError ( ) self . writequeue . append ( ( 'setconfig' , afterwards , 'query.' + alias , '' ) )
remove a named query from the notmuch database .
19,143
def RFC3156_micalg_from_algo ( hash_algo ) : algo = gpg . core . hash_algo_name ( hash_algo ) if algo is None : raise GPGProblem ( 'Unknown hash algorithm {}' . format ( algo ) , code = GPGCode . INVALID_HASH_ALGORITHM ) return 'pgp-' + algo . lower ( )
Converts a GPGME hash algorithm name to one conforming to RFC3156 .
19,144
def list_keys ( hint = None , private = False ) : ctx = gpg . core . Context ( ) return ctx . keylist ( hint , private )
Returns a generator of all keys containing the fingerprint or all keys if hint is None .
19,145
def detached_signature_for ( plaintext_str , keys ) : ctx = gpg . core . Context ( armor = True ) ctx . signers = keys ( sigblob , sign_result ) = ctx . sign ( plaintext_str , mode = gpg . constants . SIG_MODE_DETACH ) return sign_result . signatures , sigblob
Signs the given plaintext string and returns the detached signature .
19,146
def encrypt ( plaintext_str , keys ) : assert keys , 'Must provide at least one key to encrypt with' ctx = gpg . core . Context ( armor = True ) out = ctx . encrypt ( plaintext_str , recipients = keys , sign = False , always_trust = True ) [ 0 ] return out
Encrypt data and return the encrypted form .
19,147
def bad_signatures_to_str ( error ) : return ", " . join ( "{}: {}" . format ( s . fpr , "Bad signature for key(s)" ) for s in error . result . signatures if s . status != NO_ERROR )
Convert a bad signature exception to a text message . This is a workaround for gpg not handling non - ascii data correctly .
19,148
def verify_detached ( message , signature ) : ctx = gpg . core . Context ( ) try : verify_results = ctx . verify ( message , signature ) [ 1 ] return verify_results . signatures except gpg . errors . BadSignatures as e : raise GPGProblem ( bad_signatures_to_str ( e ) , code = GPGCode . BAD_SIGNATURE ) except gpg . errors . GPGMEError as e : raise GPGProblem ( str ( e ) , code = e . getcode ( ) )
Verifies whether the message is authentic by checking the signature .
19,149
def validate_key ( key , sign = False , encrypt = False ) : if key . revoked : raise GPGProblem ( 'The key "{}" is revoked.' . format ( key . uids [ 0 ] . uid ) , code = GPGCode . KEY_REVOKED ) elif key . expired : raise GPGProblem ( 'The key "{}" is expired.' . format ( key . uids [ 0 ] . uid ) , code = GPGCode . KEY_EXPIRED ) elif key . invalid : raise GPGProblem ( 'The key "{}" is invalid.' . format ( key . uids [ 0 ] . uid ) , code = GPGCode . KEY_INVALID ) if encrypt and not key . can_encrypt : raise GPGProblem ( 'The key "{}" cannot be used to encrypt' . format ( key . uids [ 0 ] . uid ) , code = GPGCode . KEY_CANNOT_ENCRYPT ) if sign and not key . can_sign : raise GPGProblem ( 'The key "{}" cannot be used to sign' . format ( key . uids [ 0 ] . uid ) , code = GPGCode . KEY_CANNOT_SIGN )
Assert that a key is valide and optionally that it can be used for signing or encrypting . Raise GPGProblem otherwise .
19,150
def attr_triple ( value ) : keys = [ 'dfg' , 'dbg' , '1fg' , '1bg' , '16fg' , '16bg' , '256fg' , '256bg' ] acc = { } if not isinstance ( value , ( list , tuple ) ) : value = value , if len ( value ) > 6 : raise VdtValueTooLongError ( value ) attrstrings = ( value + ( 6 - len ( value ) ) * [ None ] ) [ : 6 ] attrstrings = ( 2 * [ 'default' ] ) + attrstrings for i , value in enumerate ( attrstrings ) : if value : acc [ keys [ i ] ] = value else : acc [ keys [ i ] ] = acc [ keys [ i - 2 ] ] try : mono = AttrSpec ( acc [ '1fg' ] , acc [ '1bg' ] , 1 ) normal = AttrSpec ( acc [ '16fg' ] , acc [ '16bg' ] , 16 ) high = AttrSpec ( acc [ '256fg' ] , acc [ '256bg' ] , 256 ) except AttrSpecError as e : raise ValidateError ( str ( e ) ) return mono , normal , high
Check that interprets the value as urwid . AttrSpec triple for the colour modes 1 16 and 256 . It assumes a <6 tuple of attribute strings for mono foreground mono background 16c fg 16c bg 256 fg and 256 bg respectively . If any of these are missing we downgrade to the next lower available pair defaulting to default .
19,151
def gpg_key ( value ) : try : return crypto . get_key ( value ) except GPGProblem as e : raise ValidateError ( str ( e ) )
test if value points to a known gpg key and return that key as a gpg key object .
19,152
def resolve_att ( a , fallback ) : if a is None : return fallback if a . background in [ 'default' , '' ] : bg = fallback . background else : bg = a . background if a . foreground in [ 'default' , '' ] : fg = fallback . foreground else : fg = a . foreground return AttrSpec ( fg , bg )
replace and default by fallback values
19,153
def relevant_part ( self , original , pos , sep = ' ' ) : start = original . rfind ( sep , 0 , pos ) + 1 end = original . find ( sep , pos - 1 ) if end == - 1 : end = len ( original ) return original [ start : end ] , start , end , pos - start
calculates the subword in a sep - splitted list of substrings of original that pos is ia . n
19,154
def relevant_part ( self , original , pos ) : start = original . rfind ( self . _separator , 0 , pos ) if start == - 1 : start = 0 else : start = start + len ( self . _separator ) end = original . find ( self . _separator , pos - 1 ) if end == - 1 : end = len ( original ) return original [ start : end ] , start , end , pos - start
calculates the subword of original that pos is in
19,155
def get_context ( line , pos ) : commands = split_commandline ( line ) + [ '' ] i = 0 start = 0 end = len ( commands [ i ] ) while pos > end : i += 1 start = end + 1 end += 1 + len ( commands [ i ] ) return start , end
computes start and end position of substring of line that is the command string under given position
19,156
def _path_factory ( check ) : @ functools . wraps ( check ) def validator ( paths ) : if isinstance ( paths , str ) : check ( paths ) elif isinstance ( paths , collections . Sequence ) : for path in paths : check ( path ) else : raise Exception ( 'expected either basestr or sequenc of basstr' ) return validator
Create a function that checks paths .
19,157
def optional_file_like ( path ) : if ( os . path . exists ( path ) and not ( os . path . isfile ( path ) or stat . S_ISFIFO ( os . stat ( path ) . st_mode ) or stat . S_ISCHR ( os . stat ( path ) . st_mode ) ) ) : raise ValidationFailed ( '{} is not a valid file, character device, or fifo.' . format ( path ) )
Validator that ensures that if a file exists it regular a fifo or a character device . The file is not required to exist .
19,158
def get_filename ( self ) : fname = self . part . get_filename ( ) if fname : extracted_name = decode_header ( fname ) if extracted_name : return os . path . basename ( extracted_name ) return None
return name of attached file . If the content - disposition header contains no file name this returns None
19,159
def get_content_type ( self ) : ctype = self . part . get_content_type ( ) if ctype in [ 'octet/stream' , 'application/octet-stream' , 'application/octetstream' ] : ctype = guess_mimetype ( self . get_data ( ) ) return ctype
mime type of the attachment part
19,160
def get_mime_representation ( self ) : part = deepcopy ( self . part ) part . set_param ( 'maxlinelen' , '78' , header = 'Content-Disposition' ) return part
returns mime part that constitutes this attachment
19,161
def get_attribute ( self , colourmode , mode , name , part = None ) : thmble = self . _config [ mode ] [ name ] if part is not None : thmble = thmble [ part ] thmble = thmble or DUMMYDEFAULT return thmble [ self . _colours . index ( colourmode ) ]
returns requested attribute
19,162
def get_threadline_theming ( self , thread , colourmode ) : def pickcolour ( triple ) : return triple [ self . _colours . index ( colourmode ) ] def matches ( sec , thread ) : if sec . get ( 'tagged_with' ) is not None : if not set ( sec [ 'tagged_with' ] ) . issubset ( thread . get_tags ( ) ) : return False if sec . get ( 'query' ) is not None : if not thread . matches ( sec [ 'query' ] ) : return False return True default = self . _config [ 'search' ] [ 'threadline' ] match = default candidates = self . _config [ 'search' ] . sections for candidatename in candidates : candidate = self . _config [ 'search' ] [ candidatename ] if ( candidatename . startswith ( 'threadline' ) and ( not candidatename == 'threadline' ) and matches ( candidate , thread ) ) : match = candidate break res = { } res [ 'normal' ] = pickcolour ( match . get ( 'normal' ) or default [ 'normal' ] ) res [ 'focus' ] = pickcolour ( match . get ( 'focus' ) or default [ 'focus' ] ) res [ 'parts' ] = match . get ( 'parts' ) or default [ 'parts' ] for part in res [ 'parts' ] : defaultsec = default . get ( part ) partsec = match . get ( part ) or { } def fill ( key , fallback = None ) : pvalue = partsec . get ( key ) or defaultsec . get ( key ) return pvalue or fallback res [ part ] = { } res [ part ] [ 'width' ] = fill ( 'width' , ( 'fit' , 0 , 0 ) ) res [ part ] [ 'alignment' ] = fill ( 'alignment' , 'right' ) res [ part ] [ 'normal' ] = pickcolour ( fill ( 'normal' ) ) res [ part ] [ 'focus' ] = pickcolour ( fill ( 'focus' ) ) return res
look up how to display a Threadline wiidget in search mode for a given thread .
19,163
async def apply_commandline ( self , cmdline ) : cmdline = cmdline . lstrip ( ) def apply_this_command ( cmdstring ) : logging . debug ( '%s command string: "%s"' , self . mode , str ( cmdstring ) ) cmd = commandfactory ( cmdstring , self . mode ) if cmd . repeatable : self . last_commandline = cmdline return self . apply_command ( cmd ) try : for c in split_commandline ( cmdline ) : await apply_this_command ( c ) except Exception as e : self . _error_handler ( e )
interprets a command line string
19,164
def paused ( self ) : self . mainloop . stop ( ) try : yield finally : self . mainloop . start ( ) self . mainloop . screen_size = None self . mainloop . draw_screen ( )
context manager that pauses the UI to allow running external commands .
19,165
def get_deep_focus ( self , startfrom = None ) : if not startfrom : startfrom = self . current_buffer if 'get_focus' in dir ( startfrom ) : focus = startfrom . get_focus ( ) if isinstance ( focus , tuple ) : focus = focus [ 0 ] if isinstance ( focus , urwid . Widget ) : return self . get_deep_focus ( startfrom = focus ) return startfrom
return the bottom most focussed widget of the widget tree
19,166
def clear_notify ( self , messages ) : newpile = self . _notificationbar . widget_list for l in messages : if l in newpile : newpile . remove ( l ) if newpile : self . _notificationbar = urwid . Pile ( newpile ) else : self . _notificationbar = None self . update ( )
Clears notification popups . Call this to ged rid of messages that don t time out .
19,167
def choice ( self , message , choices = None , select = None , cancel = None , msg_position = 'above' , choices_to_return = None ) : choices = choices or { 'y' : 'yes' , 'n' : 'no' } assert select is None or select in choices . values ( ) assert cancel is None or cancel in choices . values ( ) assert msg_position in [ 'left' , 'above' ] fut = asyncio . get_event_loop ( ) . create_future ( ) oldroot = self . mainloop . widget def select_or_cancel ( text ) : self . mainloop . widget = oldroot self . _passall = False fut . set_result ( text ) msgpart = urwid . Text ( message ) choicespart = ChoiceWidget ( choices , choices_to_return = choices_to_return , callback = select_or_cancel , select = select , cancel = cancel ) if msg_position == 'left' : both = urwid . Columns ( [ ( 'fixed' , len ( message ) , msgpart ) , ( 'weight' , 1 , choicespart ) , ] , dividechars = 1 ) else : both = urwid . Pile ( [ msgpart , choicespart ] ) att = settings . get_theming_attribute ( 'global' , 'prompt' ) both = urwid . AttrMap ( both , att , att ) overlay = urwid . Overlay ( both , oldroot , ( 'fixed left' , 0 ) , ( 'fixed right' , 0 ) , ( 'fixed bottom' , 1 ) , None ) self . mainloop . widget = overlay self . _passall = True return fut
prompt user to make a choice .
19,168
async def apply_command ( self , cmd ) : if cmd : if cmd . prehook : await cmd . prehook ( ui = self , dbm = self . dbman , cmd = cmd ) try : if asyncio . iscoroutinefunction ( cmd . apply ) : await cmd . apply ( self ) else : cmd . apply ( self ) except Exception as e : self . _error_handler ( e ) else : if cmd . posthook : logging . info ( 'calling post-hook' ) await cmd . posthook ( ui = self , dbm = self . dbman , cmd = cmd )
applies a command
19,169
def handle_signal ( self , signum , frame ) : if signum == signal . SIGINT : logging . info ( 'shut down cleanly' ) asyncio . ensure_future ( self . apply_command ( globals . ExitCommand ( ) ) ) elif signum == signal . SIGUSR1 : if isinstance ( self . current_buffer , SearchBuffer ) : self . current_buffer . rebuild ( ) self . update ( )
handles UNIX signals
19,170
def cleanup ( self ) : size = settings . get ( 'history_size' ) self . _save_history_to_file ( self . commandprompthistory , self . _cmd_hist_file , size = size ) self . _save_history_to_file ( self . senderhistory , self . _sender_hist_file , size = size ) self . _save_history_to_file ( self . recipienthistory , self . _recipients_hist_file , size = size )
Do the final clean up before shutting down .
19,171
def _load_history_from_file ( path , size = - 1 ) : if size == 0 : return [ ] if os . path . exists ( path ) : with codecs . open ( path , 'r' , encoding = 'utf-8' ) as histfile : lines = [ line . rstrip ( '\n' ) for line in histfile ] if size > 0 : lines = lines [ - size : ] return lines else : return [ ]
Load a history list from a file and split it into lines .
19,172
def parser ( ) : parser = argparse . ArgumentParser ( add_help = False ) parser . add_argument ( '-r' , '--read-only' , action = 'store_true' , help = 'open notmuch database in read-only mode' ) parser . add_argument ( '-c' , '--config' , metavar = 'FILENAME' , action = cargparse . ValidatedStoreAction , validator = cargparse . require_file , help = 'configuration file' ) parser . add_argument ( '-n' , '--notmuch-config' , metavar = 'FILENAME' , default = os . environ . get ( 'NOTMUCH_CONFIG' , os . path . expanduser ( '~/.notmuch-config' ) ) , action = cargparse . ValidatedStoreAction , validator = cargparse . require_file , help = 'notmuch configuration file' ) parser . add_argument ( '-C' , '--colour-mode' , metavar = 'COLOURS' , choices = ( 1 , 16 , 256 ) , type = int , help = 'number of colours to use' ) parser . add_argument ( '-p' , '--mailindex-path' , metavar = 'PATH' , action = cargparse . ValidatedStoreAction , validator = cargparse . require_dir , help = 'path to notmuch index' ) parser . add_argument ( '-d' , '--debug-level' , metavar = 'LEVEL' , default = 'info' , choices = ( 'debug' , 'info' , 'warning' , 'error' ) , help = 'debug level [default: %(default)s]' ) parser . add_argument ( '-l' , '--logfile' , metavar = 'FILENAME' , default = '/dev/null' , action = cargparse . ValidatedStoreAction , validator = cargparse . optional_file_like , help = 'log file [default: %(default)s]' ) parser . add_argument ( '-h' , '--help' , action = 'help' , help = 'display this help and exit' ) parser . add_argument ( '-v' , '--version' , action = 'version' , version = alot . __version__ , help = 'output version information and exit' ) parser . add_argument ( 'command' , nargs = argparse . REMAINDER , help = 'possible subcommands are {}' . format ( ', ' . join ( _SUBCOMMANDS ) ) ) options = parser . parse_args ( ) if options . command : parser = argparse . ArgumentParser ( ) subparsers = parser . add_subparsers ( dest = 'subcommand' ) for subcommand in _SUBCOMMANDS : subparsers . add_parser ( subcommand , parents = [ COMMANDS [ 'global' ] [ subcommand ] [ 1 ] ] ) command = parser . parse_args ( options . command ) else : command = None return options , command
Parse command line arguments validate them and return them .
19,173
def main ( ) : options , command = parser ( ) root_logger = logging . getLogger ( ) for log_handler in root_logger . handlers : root_logger . removeHandler ( log_handler ) root_logger = None numeric_loglevel = getattr ( logging , options . debug_level . upper ( ) , None ) logformat = '%(levelname)s:%(module)s:%(message)s' logging . basicConfig ( level = numeric_loglevel , filename = options . logfile , filemode = 'w' , format = logformat ) cpath = options . config if options . config is None : xdg_dir = get_xdg_env ( 'XDG_CONFIG_HOME' , os . path . expanduser ( '~/.config' ) ) alotconfig = os . path . join ( xdg_dir , 'alot' , 'config' ) if os . path . exists ( alotconfig ) : cpath = alotconfig try : settings . read_config ( cpath ) settings . read_notmuch_config ( options . notmuch_config ) except ( ConfigError , OSError , IOError ) as e : print ( 'Error when parsing a config file. ' 'See log for potential details.' ) sys . exit ( e ) if options . colour_mode : settings . set ( 'colourmode' , options . colour_mode ) indexpath = settings . get_notmuch_setting ( 'database' , 'path' ) indexpath = options . mailindex_path or indexpath dbman = DBManager ( path = indexpath , ro = options . read_only ) if command is None : try : cmdstring = settings . get ( 'initial_command' ) except CommandParseError as err : sys . exit ( err ) elif command . subcommand in _SUBCOMMANDS : cmdstring = ' ' . join ( options . command ) UI ( dbman , cmdstring ) exit_hook = settings . get_hook ( 'exit' ) if exit_hook is not None : exit_hook ( )
The main entry point to alot . It parses the command line and prepares for the user interface main loop to run .
19,174
async def update_keys ( ui , envelope , block_error = False , signed_only = False ) : encrypt_keys = [ ] for header in ( 'To' , 'Cc' ) : if header not in envelope . headers : continue for recipient in envelope . headers [ header ] [ 0 ] . split ( ',' ) : if not recipient : continue match = re . search ( "<(.*@.*)>" , recipient ) if match : recipient = match . group ( 1 ) encrypt_keys . append ( recipient ) logging . debug ( "encryption keys: " + str ( encrypt_keys ) ) keys = await _get_keys ( ui , encrypt_keys , block_error = block_error , signed_only = signed_only ) if keys : envelope . encrypt_keys = keys envelope . encrypt = True if 'From' in envelope . headers : try : if envelope . account is None : envelope . account = settings . account_matching_address ( envelope [ 'From' ] ) acc = envelope . account if acc . encrypt_to_self : if acc . gpg_key : logging . debug ( 'encrypt to self: %s' , acc . gpg_key . fpr ) envelope . encrypt_keys [ acc . gpg_key . fpr ] = acc . gpg_key else : logging . debug ( 'encrypt to self: no gpg_key in account' ) except NoMatchingAccount : logging . debug ( 'encrypt to self: no account found' ) else : envelope . encrypt = False
Find and set the encryption keys in an envolope .
19,175
async def _get_keys ( ui , encrypt_keyids , block_error = False , signed_only = False ) : keys = { } for keyid in encrypt_keyids : try : key = crypto . get_key ( keyid , validate = True , encrypt = True , signed_only = signed_only ) except GPGProblem as e : if e . code == GPGCode . AMBIGUOUS_NAME : tmp_choices = [ '{} ({})' . format ( k . uids [ 0 ] . uid , k . fpr ) for k in crypto . list_keys ( hint = keyid ) ] choices = { str ( i ) : t for i , t in enumerate ( tmp_choices , 1 ) } keys_to_return = { str ( i ) : t for i , t in enumerate ( [ k for k in crypto . list_keys ( hint = keyid ) ] , 1 ) } choosen_key = await ui . choice ( "ambiguous keyid! Which " + "key do you want to use?" , choices = choices , choices_to_return = keys_to_return ) if choosen_key : keys [ choosen_key . fpr ] = choosen_key continue else : ui . notify ( str ( e ) , priority = 'error' , block = block_error ) continue keys [ key . fpr ] = key return keys
Get several keys from the GPG keyring . The keys are selected by keyid and are checked if they can be used for encryption .
19,176
def from_string ( cls , address , case_sensitive = False ) : assert isinstance ( address , str ) , 'address must be str' username , domainname = address . split ( '@' ) return cls ( username , domainname , case_sensitive = case_sensitive )
Alternate constructor for building from a string .
19,177
def __cmp ( self , other , comparitor ) : if isinstance ( other , str ) : try : ouser , odomain = other . split ( '@' ) except ValueError : ouser , odomain = '' , '' else : ouser = other . username odomain = other . domainname if not self . case_sensitive : ouser = ouser . lower ( ) username = self . username . lower ( ) else : username = self . username return ( comparitor ( username , ouser ) and comparitor ( self . domainname . lower ( ) , odomain . lower ( ) ) )
Shared helper for rich comparison operators .
19,178
def matches_address ( self , address ) : if self . address == address : return True for alias in self . aliases : if alias == address : return True if self . _alias_regexp and self . _alias_regexp . match ( address ) : return True return False
returns whether this account knows about an email address
19,179
def store_mail ( mbx , mail ) : if not isinstance ( mbx , mailbox . Mailbox ) : logging . debug ( 'Not a mailbox' ) return False mbx . lock ( ) if isinstance ( mbx , mailbox . Maildir ) : logging . debug ( 'Maildir' ) msg = mailbox . MaildirMessage ( mail ) msg . set_flags ( 'S' ) else : logging . debug ( 'no Maildir' ) msg = mailbox . Message ( mail ) try : message_id = mbx . add ( msg ) mbx . flush ( ) mbx . unlock ( ) logging . debug ( 'got mailbox msg id : %s' , message_id ) except Exception as e : raise StoreMailError ( e ) path = None if isinstance ( mbx , mailbox . Maildir ) : plist = glob . glob1 ( os . path . join ( mbx . _path , 'new' ) , message_id + '*' ) if plist : path = os . path . join ( mbx . _path , 'new' , plist [ 0 ] ) logging . debug ( 'path of saved msg: %s' , path ) return path
stores given mail in mailbox . If mailbox is maildir set the S - flag and return path to newly added mail . Oherwise this will return None .
19,180
def refresh ( self , thread = None ) : if not thread : thread = self . _dbman . _get_notmuch_thread ( self . _id ) self . _total_messages = thread . get_total_messages ( ) self . _notmuch_authors_string = thread . get_authors ( ) subject_type = settings . get ( 'thread_subject' ) if subject_type == 'notmuch' : subject = thread . get_subject ( ) elif subject_type == 'oldest' : try : first_msg = list ( thread . get_toplevel_messages ( ) ) [ 0 ] subject = first_msg . get_header ( 'subject' ) except IndexError : subject = '' self . _subject = subject self . _authors = None ts = thread . get_oldest_date ( ) try : self . _oldest_date = datetime . fromtimestamp ( ts ) except ValueError : self . _oldest_date = None try : timestamp = thread . get_newest_date ( ) self . _newest_date = datetime . fromtimestamp ( timestamp ) except ValueError : self . _newest_date = None self . _tags = { t for t in thread . get_tags ( ) } self . _messages = { } self . _toplevel_messages = [ ]
refresh thread metadata from the index
19,181
def get_tags ( self , intersection = False ) : tags = set ( list ( self . _tags ) ) if intersection : for m in self . get_messages ( ) . keys ( ) : tags = tags . intersection ( set ( m . get_tags ( ) ) ) return tags
returns tagsstrings attached to this thread
19,182
def add_tags ( self , tags , afterwards = None , remove_rest = False ) : def myafterwards ( ) : if remove_rest : self . _tags = set ( tags ) else : self . _tags = self . _tags . union ( tags ) if callable ( afterwards ) : afterwards ( ) self . _dbman . tag ( 'thread:' + self . _id , tags , afterwards = myafterwards , remove_rest = remove_rest )
add tags to all messages in this thread
19,183
def get_authors_string ( self , own_accts = None , replace_own = None ) : if replace_own is None : replace_own = settings . get ( 'thread_authors_replace_me' ) if replace_own : if own_accts is None : own_accts = settings . get_accounts ( ) authorslist = [ ] for aname , aaddress in self . get_authors ( ) : for account in own_accts : if account . matches_address ( aaddress ) : aname = settings . get ( 'thread_authors_me' ) break if not aname : aname = aaddress if aname not in authorslist : authorslist . append ( aname ) return ', ' . join ( authorslist ) else : return self . _notmuch_authors_string
returns a string of comma - separated authors Depending on settings it will substitute me for author name if address is user s own .
19,184
def get_messages ( self ) : if not self . _messages : query = self . _dbman . query ( 'thread:' + self . _id ) thread = next ( query . search_threads ( ) ) def accumulate ( acc , msg ) : M = Message ( self . _dbman , msg , thread = self ) acc [ M ] = [ ] r = msg . get_replies ( ) if r is not None : for m in r : acc [ M ] . append ( accumulate ( acc , m ) ) return M self . _messages = { } for m in thread . get_toplevel_messages ( ) : self . _toplevel_messages . append ( accumulate ( self . _messages , m ) ) return self . _messages
returns all messages in this thread as dict mapping all contained messages to their direct responses .
19,185
def get_replies_to ( self , msg ) : mid = msg . get_message_id ( ) msg_hash = self . get_messages ( ) for m in msg_hash . keys ( ) : if m . get_message_id ( ) == mid : return msg_hash [ m ] return None
returns all replies to the given message contained in this thread .
19,186
def matches ( self , query ) : thread_query = 'thread:{tid} AND {subquery}' . format ( tid = self . _id , subquery = query ) num_matches = self . _dbman . count_messages ( thread_query ) return num_matches > 0
Check if this thread matches the given notmuch query .
19,187
def lookup_command ( cmdname , mode ) : if cmdname in COMMANDS [ mode ] : return COMMANDS [ mode ] [ cmdname ] elif cmdname in COMMANDS [ 'global' ] : return COMMANDS [ 'global' ] [ cmdname ] else : return None , None , None
returns commandclass argparser and forced parameters used to construct a command for cmdname when called in mode .
19,188
def get_selected_tag ( self ) : cols , _ = self . taglist . get_focus ( ) tagwidget = cols . original_widget . get_focus ( ) return tagwidget . tag
returns selected tagstring
19,189
def parse_chart ( chart , convert ) : out = [ ] for match in re . finditer ( ATTR_RE , chart ) : if match . group ( 'whitespace' ) : out . append ( match . group ( 'whitespace' ) ) entry = match . group ( 'entry' ) entry = entry . replace ( "_" , " " ) while entry : attrtext = convert ( entry [ : SHORT_ATTR ] ) if attrtext : elen = SHORT_ATTR entry = entry [ SHORT_ATTR : ] . strip ( ) else : attrtext = convert ( entry . strip ( ) ) assert attrtext , "Invalid palette entry: %r" % entry elen = len ( entry ) entry = "" attr , text = attrtext out . append ( ( attr , text . ljust ( elen ) ) ) return out
Convert string chart into text markup with the correct attributes .
19,190
def foreground_chart ( chart , background , colors ) : def convert_foreground ( entry ) : try : attr = urwid . AttrSpec ( entry , background , colors ) except urwid . AttrSpecError : return None return attr , entry return parse_chart ( chart , convert_foreground )
Create text markup for a foreground colour chart
19,191
def background_chart ( chart , foreground , colors ) : def convert_background ( entry ) : try : attr = urwid . AttrSpec ( foreground , entry , colors ) except urwid . AttrSpecError : return None if colors > 16 and attr . background_basic and attr . background_number >= 8 : entry = 'h%d' % attr . background_number attr = urwid . AttrSpec ( foreground , entry , colors ) return attr , entry return parse_chart ( chart , convert_background )
Create text markup for a background colour chart
19,192
def prepare_string ( partname , thread , maxw ) : prep = { 'mailcount' : ( prepare_mailcount_string , None ) , 'date' : ( prepare_date_string , None ) , 'authors' : ( prepare_authors_string , shorten_author_string ) , 'subject' : ( prepare_subject_string , None ) , 'content' : ( prepare_content_string , None ) , } s = ' ' if thread : content , shortener = prep [ partname ] s = content ( thread ) s = s . replace ( '\n' , ' ' ) s = s . replace ( '\r' , '' ) if maxw : if len ( s ) > maxw and shortener : s = shortener ( s , maxw ) else : s = s [ : maxw ] return s
extract a content string for part partname from thread of maximal length maxw .
19,193
def reload ( self ) : self . read_notmuch_config ( self . _notmuchconfig . filename ) self . read_config ( self . _config . filename )
Reload notmuch and alot config files
19,194
def _expand_config_values ( section , key ) : def expand_environment_and_home ( value ) : xdg_vars = { 'XDG_CONFIG_HOME' : '~/.config' , 'XDG_CACHE_HOME' : '~/.cache' } for xdg_name , fallback in xdg_vars . items ( ) : if xdg_name in value : xdg_value = get_xdg_env ( xdg_name , fallback ) value = value . replace ( '$%s' % xdg_name , xdg_value ) . replace ( '${%s}' % xdg_name , xdg_value ) return os . path . expanduser ( os . path . expandvars ( value ) ) value = section [ key ] if isinstance ( value , str ) : section [ key ] = expand_environment_and_home ( value ) elif isinstance ( value , ( list , tuple ) ) : new = list ( ) for item in value : if isinstance ( item , str ) : new . append ( expand_environment_and_home ( item ) ) else : new . append ( item ) section [ key ] = new
Walker function for ConfigObj . walk
19,195
def _parse_accounts ( config ) : accounts = [ ] if 'accounts' in config : for acc in config [ 'accounts' ] . sections : accsec = config [ 'accounts' ] [ acc ] args = dict ( config [ 'accounts' ] [ acc ] . items ( ) ) abook = accsec [ 'abook' ] logging . debug ( 'abook defined: %s' , abook ) if abook [ 'type' ] == 'shellcommand' : cmd = abook [ 'command' ] regexp = abook [ 'regexp' ] if cmd is not None and regexp is not None : ef = abook [ 'shellcommand_external_filtering' ] args [ 'abook' ] = ExternalAddressbook ( cmd , regexp , external_filtering = ef ) else : msg = 'underspecified abook of type \'shellcommand\':' msg += '\ncommand: %s\nregexp:%s' % ( cmd , regexp ) raise ConfigError ( msg ) elif abook [ 'type' ] == 'abook' : contacts_path = abook [ 'abook_contacts_file' ] args [ 'abook' ] = AbookAddressBook ( contacts_path , ignorecase = abook [ 'ignorecase' ] ) else : del args [ 'abook' ] cmd = args [ 'sendmail_command' ] del args [ 'sendmail_command' ] newacc = SendmailAccount ( cmd , ** args ) accounts . append ( newacc ) return accounts
read accounts information from config
19,196
def get ( self , key , fallback = None ) : value = None if key in self . _config : value = self . _config [ key ] if isinstance ( value , Section ) : value = None if value is None : value = fallback return value
look up global config values from alot s config
19,197
def get_notmuch_setting ( self , section , key , fallback = None ) : value = None if section in self . _notmuchconfig : if key in self . _notmuchconfig [ section ] : value = self . _notmuchconfig [ section ] [ key ] if value is None : value = fallback return value
look up config values from notmuch s config
19,198
def get_theming_attribute ( self , mode , name , part = None ) : colours = int ( self . _config . get ( 'colourmode' ) ) return self . _theme . get_attribute ( colours , mode , name , part )
looks up theming attribute
19,199
def get_tagstring_representation ( self , tag , onebelow_normal = None , onebelow_focus = None ) : colourmode = int ( self . _config . get ( 'colourmode' ) ) theme = self . _theme cfg = self . _config colours = [ 1 , 16 , 256 ] def colourpick ( triple ) : if triple is None : return None return triple [ colours . index ( colourmode ) ] default_normal = theme . get_attribute ( colourmode , 'global' , 'tag' ) default_focus = theme . get_attribute ( colourmode , 'global' , 'tag_focus' ) fallback_normal = resolve_att ( onebelow_normal , default_normal ) fallback_focus = resolve_att ( onebelow_focus , default_focus ) for sec in cfg [ 'tags' ] . sections : if re . match ( '^{}$' . format ( sec ) , tag ) : normal = resolve_att ( colourpick ( cfg [ 'tags' ] [ sec ] [ 'normal' ] ) , fallback_normal ) focus = resolve_att ( colourpick ( cfg [ 'tags' ] [ sec ] [ 'focus' ] ) , fallback_focus ) translated = cfg [ 'tags' ] [ sec ] [ 'translated' ] translated = string_decode ( translated , 'UTF-8' ) if translated is None : translated = tag translation = cfg [ 'tags' ] [ sec ] [ 'translation' ] if translation : translated = re . sub ( translation [ 0 ] , translation [ 1 ] , tag ) break else : normal = fallback_normal focus = fallback_focus translated = tag return { 'normal' : normal , 'focussed' : focus , 'translated' : translated }
looks up user s preferred way to represent a given tagstring .