CfczdZddlZddlZddlZddlZddlZ ddlmZmZm Z m Z m Z m Z m Z mZmZmZmZmZmZmZedZedZddlmZmZmZmZmZddlmZm Z  dd lm!Z!d Z"e#e"gZ$ejJe&Z'Gd d e(Z)Gd de)Z*Gdde)e+Z,dZ-Gdde.Z/dZ0Gdde.Z1Gdde.Z2dZ3dZ4dZ5dZ6GddejnddZ8d Z9Gd!d"e:Z;Gd#d$e;%Z<Gd&d'e<Z=Gd(d)e<Z>Gd*d+e<Z?y#e$rdZYwxYw#e$rYwxYw),a9Utilities for parsing and creating machine-readable debian/copyright files. The specification for the format (also known as DEP5) is available here: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Start from the Copyright docstring for usage information. Copyright Classes ----------------- N)AnyCallable FrozenSetIOIterableIteratorListOptionalPatternTextTupleUnion TYPE_CHECKINGcast)FilesParagraphLicenseParagraph)HeaderrrF)parse_deb822_fileDeb822ParagraphElementDeb822FileElement'Deb822NoDuplicateFieldsParagraphElementSyntaxOrParseError)RestrictedFieldRestrictedFieldError)Deb822ValueTypezBhttps://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ceZdZdZy)Errorz)Base class for exceptions in this module.N__name__ __module__ __qualname____doc__2/usr/lib/python3/dist-packages/debian/copyright.pyrrSs3r$rceZdZdZy)NotMachineReadableErrorzFRaised when the input is not a machine-readable debian/copyright file.Nrr#r$r%r'r'WsPr$r'ceZdZdZy)MachineReadableFormatErrorzRaised when the input is not valid. This is both a `copyright.Error` and a `ValueError` to ease handling of errors coming from this module. Nrr#r$r%r)r)[sr$r)cH|r t|tj|yN)r)loggerwarning)msgstricts r% _complainr0cs (-- NN3r$ceZdZdZd fd ZedZejdZdZdZ dZ dZ d Z d Z d Zdd ZxZS) CopyrightaRepresents a debian/copyright file. A Copyright object contains a Header paragraph and a list of additional Files or License paragraphs. It provides methods to iterate over those paragraphs, in addition to adding new ones. It also provides a mechanism for finding the Files paragraph (if any) that matches a particular filename. Typical usage:: with io.open('debian/copyright', 'rt', encoding='utf-8') as f: c = copyright.Copyright(f) header = c.header # Header exposes standard fields, e.g. print('Upstream name: ', header.upstream_name) lic = header.license if lic: print('Overall license: ', lic.synopsis) # You can also retrieve and set custom fields. header['My-Special-Field'] = 'Very special' # Find the license for a given file. paragraph = c.find_files_paragraph('debian/rules') if paragraph: print('License for debian/rules: ', paragraph.license) # Dump the result, including changes, to another file. with io.open('debian/copyright.new', 'wt', encoding='utf-8') as f: c.dump(f=f) It is possible to build up a Copyright from scratch, by modifying the header and using add_files_paragraph and add_license_paragraph. See the associated method docstrings. ctt| g|_|d} t ||| |_|j D]v}| t|}d|vr*t|||}|jj|?d|vr(t||}|jj|ktd|x|s td||_ytj |_t|_|j j|jj"|jj|jy#t $r}tt|d}~wwxYw)a Create a new copyright file in the current format. :param sequence: Sequence of lines, e.g. a list of strings or a file-like object. If not specified, a blank Copyright object is initialized. :param encoding: Encoding to use, in case input is raw byte strings. It is recommended to use unicode objects everywhere instead, e.g. by opening files in text mode. :param strict: Raise if format errors are detected in the data. Raises: :class:`NotMachineReadableError` if 'sequence' does not contain a machine-readable debian/copyright file. MachineReadableFormatError if 'sequence' is not a valid file. N)sequenceencoding#accept_files_with_duplicated_fieldsFiles)r/Licensez=Non-header paragraph has neither "Files" nor "License" fieldszno paragraphs in input)superr2__init___Copyright__paragraphsr_Copyright__filerr'strrrappendrr0_Copyright__headerrnew_empty_file_underlying_paragraph) selfr4r5r/headereppfpl __class__s r%r:zCopyright.__init__sL" i')  F 6/!)H@FJH [[ :>#AYF\'6&AB%%,,R0!^)!V4B%%,,R0128: :-.FGG"DM,::z+Copyright.all_paragraphs..s.LQq.Ls ) itertoolschainrCr;rJs r%all_paragraphszCopyright.all_paragraphss' }.L$:K:K.LMMr$c"|jS)zXIterate over all paragraphs see all_paragraphs() for more information )rVrJs r%__iter__zCopyright.__iter__s""$$r$c(d|jDS)z>Returns an iterator over the contained FilesParagraph objects.c3BK|]}t|ts|ywr+)rLrrQs r%rSz1Copyright.all_files_paragraphs..sNa 1n0MNr;rJs r%all_files_paragraphszCopyright.all_files_paragraphssO4,,NNr$c\d}|jD]}|j|s|}|S)zReturns the FilesParagraph for the given filename. In accordance with the spec, this method returns the last FilesParagraph that matches the filename. If no paragraphs matched, returns None. N)r]matches)rBfilenameresultrEs r%find_files_paragraphzCopyright.find_files_paragraphs9**, Ayy"  r$c.t|ts tdd}t|jD]\}}t|ts|}|jj |dz||j j |dz|jy)zAdds a FilesParagraph to this object. The paragraph is inserted directly after the last FilesParagraph (which might be before a standalone LicenseParagraph). z+paragraph must be a FilesParagraph instanceN)rLrrM enumerater;insertr<rA)rB paragraphlast_iirEs r%add_files_paragraphzCopyright.add_files_paragraphs)^4IJ Jd//0 DAq!^,    !Y7 6A:y'F'FGr$c(d|jDS)z=Returns an iterator over standalone LicenseParagraph objects.c3BK|]}t|ts|ywr+)rLrrQs r%rSz3Copyright.all_license_paragraphs.. sPa 1>N0OPr[r\rJs r%all_license_paragraphsz Copyright.all_license_paragraphssQ4,,PPr$ct|ts td|jj ||j j |j y)zoAdds a LicenceParagraph to this object. The paragraph is inserted after any other paragraphs. z-paragraph must be a LicenseParagraph instanceN)rLrrMr;r>r<rA)rBris r%add_license_paragraphzCopyright.add_license_paragraph sG )%56KL L   + 9::;r$cb|jj}||j|y|S)aaDumps the contents of the copyright file. If f is None, returns a unicode object. Otherwise, writes the contents to f, which must be a file-like object that is opened in text mode (i.e. that accepts unicode objects directly). It is thus up to the caller to arrange for the file to do any appropriate encoding. N)r<dumpwrite)rBfss r%rszCopyright.dumps. KK    = GGAJr$)Nzutf-8Tr+)rr r!r"r:propertyrCsetterrVrXr]rbrlrorqrs __classcell__rHs@r%r2r2jsg"H14f  ]] N%O H"Q <r$r2c$d|vr td|S)zNReturns s if it is a single line; otherwise raises MachineReadableFormatError. zmust be single line)r)rvs r% _single_liner~'s qy()>?? Hr$c0eZdZdZedZedZy) _LineBasedz@Namespace for conversion methods for line-based lists as tuples.cttdd|xsdjjDDS)z?Returns the lines in 's', with whitespace stripped, as a tuple.c3$K|]}|r| ywr+r#rRvs r%rSz&_LineBased.from_str..7s1sc3<K|]}|jywr+)strip)rRlines r%rSz&_LineBased.from_str..8sNtdjjlNs)tupler splitlinesr}s r%from_strz_LineBased.from_str3s7NR/@/K/K/MN r$ct|}|syd}t|dk(r ||dSdg}|D]}|jd||zdj|S)zReturns the sequence as a string with each element on its own line. If 'seq' has one element, the result will be on a single line. Otherwise, the first line will be blank. Nc^|j}|s tdd|vr td|S)Nvalues must not be emptyr|z values must not contain newlines)rr)r}s r%process_and_validatez/_LineBased.to_str..process_and_validateGs8 A01KLLqy0688Hr$rerr r|)listlenr>join)seqlrtmprvs r%to_strz_LineBased.to_str;so I  q6Q;'!- -d 6A JJs1!44 5 6yy~r$N)rr r!r" staticmethodrrr#r$r%rr/s-Jr$rcTeZdZdZej dZedZe dZ y)_SpaceSeparatedzENamespace for conversion methods for space-separated lists as tuples.z\scJtd|xsdjDS)z>Returns the values in s as a tuple (empty if only whitespace).c3&K|] }|s| ywr+r#rs r%rSz+_SpaceSeparated.from_str..ds71QQ7sr)rsplitr}s r%rz_SpaceSeparated.from_str`s 7b 1777r$ct|}|syg}|D]V}|jj|r td|j }|s td|j |Xdj |S)zAReturns the sequence as a space-separated string (None if empty).Nz"values must not contain whitespacerr)r _has_spacesearchr)rr>r)clsrrrrvs r%rz_SpaceSeparated.to_strfs~ I A~~$$Q'08:: A01KLL JJqM xx}r$N) rr r!r"recompilerrr classmethodrr#r$r%rrZs=OE"J88 r$rc:|yt|jS)zFormats multiline text for insertion in a Deb822ParagraphElement field. Each line except for the first one is prefixed with a single space. Lines that are blank or only whitespace are replaced with ' .' N)format_multiline_linesrr}s r%format_multiliner{s y !!,,. 11r$cg}t|D]2\}}|dk7r|jsd}d|z}|j|4dj|S)z?Same as format_multline, but taking input pre-split into lines.r.rr|)rgrr>r)lines out_linesrkrs r%rrs^IU#4 6::<:D  99Y r$c<|ydjt|S)agInverse of format_multiline. Technically it can't be a perfect inverse, since format_multline must replace all-whitespace lines with ' .'. Specifically, this function: - Does nothing to the first line - Removes first character (which must be ' ') from each proceeding line. - Replaces any line that is '.' with an empty line. Nr|)rparse_multiline_as_linesr}s r%parse_multiliners! y 99-a0 11r$c|j}t|D]9\}}|dk(r |jdr|dd}n td|dk(rd}|||<;|S)zpSame as parse_multiline, but returns a list of lines. (This is the inverse of format_multiline_lines.) rrreNz"continued line must begin with " "rr)rrg startswithr))rvrrkrs r%rrst LLNEU# 4 6  ??3 8D,46 6 3;Da  Lr$c:eZdZdZdfd ZedZdZxZS)r8z7Represents the contents of a License field. Immutable.cJtt| |t||xsdS)aCreates a new License object. :param synopsis: The short name of the license, or an expression giving alternatives. (The first line of a License field.) :param text: The full text of the license, if any (may be None). The lines should not be mangled for "deb822"-style wrapping - i.e. they should not have whitespace prefixes or single '.' for empty lines. r)synopsistext)r9r8__new__r~)rrrrHs r%rzLicense.__new__s0Wc* ,x0 +E Er$c |yt|}|s|dS||ddjtj|ddS)Nrrr|re)r)rrrTislice)rrvrs r%rzLicense.from_strsK 9(+r7N58$))I,<, ??r$c"eZdZdZfdZxZS)_ClassInitMetaaMetaclass for classes that can be initialized at creation time. Implement the method:: @classmethod def _class_init(cls, new_attrs): pass on a class, and apply this metaclass to it. The _class_init method will be called right after the class is created. The 'new_attrs' param is a dict containing the attributes added in the definition of the class. cRtt| ||||j|yr+)r9rr: _class_init)rnamebasesattrsrHs r%r:z_ClassInitMeta.__init__s$ nc+D%? r$)rr r!r"r:ryrzs@r%rr s r$rceZdZdZeZedZedZd fd Z e dZ dZ dZ dZd Zd Z d d ZxZS)_RestrictedWrappera^Base class to wrap a Deb822 object, restricting write access to some keys. The underlying data is hidden internally. Subclasses may keep a reference to the data before giving it to this class's constructor, if necessary, but RestrictedField should cover most use-cases. The dump method from Deb822 is directly proxied. Typical usage:: class Foo(object): def __init__(self, ...): # ... @staticmethod def from_str(self, s): # Parse s... return Foo(...) def to_str(self): # Return in string format. return ... class MyClass(deb822._RestrictedWrapper): def __init__(self): data = Deb822ParagraphElement.new_empty_paragraph() data['Bar'] = 'baz' super(MyClass, self).__init__(data) foo = deb822.RestrictedField( 'Foo', from_str=Foo.from_str, to_str=Foo.to_str) bar = deb822.RestrictedField('Bar', allow_none=False) d = MyClass() d['Bar'] # returns 'baz' d['Bar'] = 'quux' # raises RestrictedFieldError d.bar = 'quux' d.bar # returns 'quux' d['Bar'] # returns 'quux' d.foo = Foo(...) d['Foo'] # returns string representation of foo cg}|jD]Q\}}t|ts|j|jj |j ||St||_yr+) itemsrLrr>rlower)_RestrictedWrapper__init_restricted_field frozenset%_RestrictedWrapper__restricted_fields)r new_attrsrestricted_fields attr_namevals r%rz_RestrictedWrapper._class_initQse'oo/ 99;$22 2&!"# # KK r$c(d|jDS)Nc32K|]}t|ywr+)r=)rRks r%rSz._RestrictedWrapper.__iter__..s,1A,srrJs r%rXz_RestrictedWrapper.__iter__s, ,,r$c,t|jSr+)rrrJs r%__len__z_RestrictedWrapper.__len__s4;;r$cX||(|s&|jjtd|y|jj}|+td|j|j |y|rtd|j|y|jjS)zcCalls dump() on the underlying data object. See Deb822.dump for more information. Nz IO[bytes]zIO[str])rrsrrtencode)rBfdr5 text_modeas_strs r%rsz_RestrictedWrapper.dumps >    k2!67[[%%'F#["%++FMM(,CDY#))&1{{!!r$T)NNF)rr r!r"rrrrrr:rwrArrrrXrrsryrzs@r%rr"s}*X$+??LL. !- "r$r) metaclassceZdZdZej dZdfd ZedZ dZ dZ e de je jd Ze d d Ze d ejejd Ze d ZxZS)rzRepresents a Files paragraph of a debian/copyright file. This kind of paragraph is used to specify the copyright and license for a particular set of files in the package. rctt| |||rGd|vr tdd|vr t d|d|vr t d||j s t d|d|j f|_y) Nr7z"Files" field requiredr2z'Files paragraph missing Copyright fieldr8z%Files paragraph missing License fieldz%Files paragraph has empty Files fieldr)r9rr:r)r0files _default_re!_FilesParagraph__cached_files_pat)rBrrr/rHs r%r:zFilesParagraph.__init__sw nd,T3EF d"01IJJ$&CVL$A6J::A6J#%t'7'7"8r$ch|tjd}||_||_||_|S)zCreate a new FilesParagraph from its required parts. :param files: The list of file globs. :param copyright: The copyright for the files (free-form text). :param license: The Licence for the files. Fr)rnew_empty_paragraphr copyrightlicense)rrrrrEs r%createzFilesParagraph.creates5 &::IG,,W^^Gi(Gr$rceZdZdZd fd ZedZedejejdZ edZ edZ xZS) ra Represents a standalone license paragraph of a debian/copyright file. Minimally, this kind of paragraph requires a 'License' field and has no 'Files' field. It is used to give a short name to a license text, which can be referred to from the header or files paragraphs. cptt| |||rd|vr tdd|vr tdyy)Nr8z"License" field requiredr7z%input appears to be a Files paragraph)r9rr:r)rs r%r:zLicenseParagraph.__init__ sN .t5GH $01KLL$0;== r$ct|ts td|tjd}||_|S)z2Returns a LicenseParagraph with the given license.z"license must be a License instanceFr )rLr8rMrr r)rrris r%rzLicenseParagraph.creates? '7+@A A.BBDY^_ # r$r8Frrr7r)rr r!r"r:rrrr8rrrr_LicenseParagraph__filesryrzs@r%rrsY=G,,W^^Gi(Gg&Gr$rceZdZdZdfd ZdZdZededZ ede Z ed e je j Zed Zed ZedZedejej ZedZede je j Zede je j ZxZS)rzRepresents the header paragraph of a debian/copyright file. Property values are all immutable, such that in order to modify them you must explicitly set them (rather than modifying a returned reference). c|tj}t|d<d|vr tj d|d|d<|d=t t ||t}|j}|tk7rU|S|jds|dz }|jdrd|ddz}|tvrtj d ||_ | td |tvrtj d |yy) zInitializer. :param data: A Deb822ParagraphElement object for underlying data. If None, a new one will be created. NFormatzFormat-SpecificationzEuse of deprecated "Format-Specification" field; rewriting as "Format"/zhttp:zhttps:%szFixing Format URLz0input is not a machine-readable debian/copyrightzformat not known: %r)rr _CURRENT_FORMATr,r-r9rr:r=formatendswithr_KNOWN_FORMATSr')rBrfmtrHs r%r:zHeader.__init__5s <)==?D,DN !T ) NN4 5!"89DN+, fd$T*ekk / !co<<$s ~~g& 3qr7*n$23! ;)BD D n $ NN13 7 %r$c&|jtvS)z%Returns True iff the format is known.)r$r&rJs r% known_formatzHeader.known_format]s{{n,,r$c(|jtk(S)z2Returns True iff the format is the current format.)r$r#rJs r%current_formatzHeader.current_formatbs{{o--r$r F)rrz Upstream-Name)rzUpstream-Contact)rrSource Disclaimerrr8r2zFiles-ExcludedzFiles-Includedr+)rr r!r"r:r)r+rr~r$ upstream_namerrrupstream_contactsource disclaimerrr8rrfiles_excludedfiles_includedryrzs@r%rr.s &8P- . %9F$ .M'Z%8%8  "X &F .Ji(GG,,W^^EG ,I$:#6#6  "N%:#6#6  "Nr$r)@r" collectionsrTloggingrrtypingrrrrrrr r r r r rrrParagraphTypesAllParagraphTypes ImportErrordebian._deb822_reprorrrrr debian.deb822rrrr#rr& getLoggerrr, Exceptionrr'rr)r0objectr2r~rrrrrr namedtupler8rtyperrrrrr#r$r%rAs 6  ?@NLM  @ - I   8 $4I4QeQ zzz ((VfB 2   2 *P$k$$Y@PF+@\T0N">N"bN)'N)b'')''TU" U"qM  s#*D)D6)D32D36D>=D>