def set_pkg_verif_code(self, doc, code):
        """Sets the package verification code, if not already set.
        code - A string.
        Raises CardinalityError if already defined.
        Raises OrderError if no package previously defined.
        Raises Value error if doesn't match verifcode form
        """
        self.assert_package_exists()
        if not self.package_verif_set:
            self.package_verif_set = True
            match = self.VERIF_CODE_REGEX.match(code)
            if match:
                doc.package.verif_code = match.group(self.VERIF_CODE_CODE_GRP)
                if match.group(self.VERIF_CODE_EXC_FILES_GRP) is not None:
                    doc.package.verif_exc_files = match.group(self.VERIF_CODE_EXC_FILES_GRP).split(',')
                return True
            else:
                raise SPDXValueError('Package::VerificationCode')
        else:
            raise CardinalityError('Package::VerificationCode')

def set_pkg_verif_code ( self , doc , code ) : self . assert_package_exists ( ) if not self . package_verif_set : self . package_verif_set = True match = self . VERIF_CODE_REGEX . match ( code ) if match : doc . package . verif_code = match . group ( self . VERIF_CODE_CODE_GRP ) if match . group ( self . VERIF_CODE_EXC_FILES_GRP ) is not None : doc . package . verif_exc_files = match . group ( self . VERIF_CODE_EXC_FILES_GRP ) . split ( ',' ) return True else : raise SPDXValueError ( 'Package::VerificationCode' ) else : raise CardinalityError ( 'Package::VerificationCode' )

Sets the package verification code if not already set . code - A string . Raises CardinalityError if already defined . Raises OrderError if no package previously defined . Raises Value error if doesn t match verifcode form


def set_pkg_source_info(self, doc, text):
        """Sets the package's source information, if not already set.
        text - Free form text.
        Raises CardinalityError if already defined.
        Raises OrderError if no package previously defined.
        SPDXValueError if text is not free form text.
        """
        self.assert_package_exists()
        if not self.package_source_info_set:
            self.package_source_info_set = True
            if validations.validate_pkg_src_info(text):
                doc.package.source_info = str_from_text(text)
                return True
            else:
                raise SPDXValueError('Pacckage::SourceInfo')
        else:
            raise CardinalityError('Package::SourceInfo')

def set_pkg_source_info ( self , doc , text ) : self . assert_package_exists ( ) if not self . package_source_info_set : self . package_source_info_set = True if validations . validate_pkg_src_info ( text ) : doc . package . source_info = str_from_text ( text ) return True else : raise SPDXValueError ( 'Pacckage::SourceInfo' ) else : raise CardinalityError ( 'Package::SourceInfo' )

Sets the package s source information if not already set . text - Free form text . Raises CardinalityError if already defined . Raises OrderError if no package previously defined . SPDXValueError if text is not free form text .


def set_pkg_licenses_concluded(self, doc, licenses):
        """Sets the package's concluded licenses.
        licenses - License info.
        Raises CardinalityError if already defined.
        Raises OrderError if no package previously defined.
        Raises SPDXValueError if data malformed.
        """
        self.assert_package_exists()
        if not self.package_conc_lics_set:
            self.package_conc_lics_set = True
            if validations.validate_lics_conc(licenses):
                doc.package.conc_lics = licenses
                return True
            else:
                raise SPDXValueError('Package::ConcludedLicenses')
        else:
            raise CardinalityError('Package::ConcludedLicenses')

def set_pkg_licenses_concluded ( self , doc , licenses ) : self . assert_package_exists ( ) if not self . package_conc_lics_set : self . package_conc_lics_set = True if validations . validate_lics_conc ( licenses ) : doc . package . conc_lics = licenses return True else : raise SPDXValueError ( 'Package::ConcludedLicenses' ) else : raise CardinalityError ( 'Package::ConcludedLicenses' )

Sets the package s concluded licenses . licenses - License info . Raises CardinalityError if already defined . Raises OrderError if no package previously defined . Raises SPDXValueError if data malformed .


def set_pkg_license_from_file(self, doc, lic):
        """Adds a license from a file to the package.
        Raises SPDXValueError if data malformed.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if validations.validate_lics_from_file(lic):
            doc.package.licenses_from_files.append(lic)
            return True
        else:
            raise SPDXValueError('Package::LicensesFromFile')

def set_pkg_license_from_file ( self , doc , lic ) : self . assert_package_exists ( ) if validations . validate_lics_from_file ( lic ) : doc . package . licenses_from_files . append ( lic ) return True else : raise SPDXValueError ( 'Package::LicensesFromFile' )

Adds a license from a file to the package . Raises SPDXValueError if data malformed . Raises OrderError if no package previously defined .


def set_pkg_license_declared(self, doc, lic):
        """Sets the package's declared license.
        Raises SPDXValueError if data malformed.
        Raises OrderError if no package previously defined.
        Raises CardinalityError if already set.
        """
        self.assert_package_exists()
        if not self.package_license_declared_set:
            self.package_license_declared_set = True
            if validations.validate_lics_conc(lic):
                doc.package.license_declared = lic
                return True
            else:
                raise SPDXValueError('Package::LicenseDeclared')
        else:
            raise CardinalityError('Package::LicenseDeclared')

def set_pkg_license_declared ( self , doc , lic ) : self . assert_package_exists ( ) if not self . package_license_declared_set : self . package_license_declared_set = True if validations . validate_lics_conc ( lic ) : doc . package . license_declared = lic return True else : raise SPDXValueError ( 'Package::LicenseDeclared' ) else : raise CardinalityError ( 'Package::LicenseDeclared' )

Sets the package s declared license . Raises SPDXValueError if data malformed . Raises OrderError if no package previously defined . Raises CardinalityError if already set .


def set_pkg_license_comment(self, doc, text):
        """Sets the package's license comment.
        Raises OrderError if no package previously defined.
        Raises CardinalityError if already set.
        Raises SPDXValueError if text is not free form text.
        """
        self.assert_package_exists()
        if not self.package_license_comment_set:
            self.package_license_comment_set = True
            if validations.validate_pkg_lics_comment(text):
                doc.package.license_comment = str_from_text(text)
                return True
            else:
                raise SPDXValueError('Package::LicenseComment')
        else:
            raise CardinalityError('Package::LicenseComment')

def set_pkg_license_comment ( self , doc , text ) : self . assert_package_exists ( ) if not self . package_license_comment_set : self . package_license_comment_set = True if validations . validate_pkg_lics_comment ( text ) : doc . package . license_comment = str_from_text ( text ) return True else : raise SPDXValueError ( 'Package::LicenseComment' ) else : raise CardinalityError ( 'Package::LicenseComment' )

Sets the package s license comment . Raises OrderError if no package previously defined . Raises CardinalityError if already set . Raises SPDXValueError if text is not free form text .


def set_pkg_summary(self, doc, text):
        """Set's the package summary.
        Raises SPDXValueError if text is not free form text.
        Raises CardinalityError if summary already set.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if not self.package_summary_set:
            self.package_summary_set = True
            if validations.validate_pkg_summary(text):
                doc.package.summary = str_from_text(text)
            else:
                raise SPDXValueError('Package::Summary')
        else:
            raise CardinalityError('Package::Summary')

def set_pkg_summary ( self , doc , text ) : self . assert_package_exists ( ) if not self . package_summary_set : self . package_summary_set = True if validations . validate_pkg_summary ( text ) : doc . package . summary = str_from_text ( text ) else : raise SPDXValueError ( 'Package::Summary' ) else : raise CardinalityError ( 'Package::Summary' )

Set s the package summary . Raises SPDXValueError if text is not free form text . Raises CardinalityError if summary already set . Raises OrderError if no package previously defined .


def set_pkg_desc(self, doc, text):
        """Set's the package's description.
        Raises SPDXValueError if text is not free form text.
        Raises CardinalityError if description already set.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if not self.package_desc_set:
            self.package_desc_set = True
            if validations.validate_pkg_desc(text):
                doc.package.description = str_from_text(text)
            else:
                raise SPDXValueError('Package::Description')
        else:
            raise CardinalityError('Package::Description')

def set_pkg_desc ( self , doc , text ) : self . assert_package_exists ( ) if not self . package_desc_set : self . package_desc_set = True if validations . validate_pkg_desc ( text ) : doc . package . description = str_from_text ( text ) else : raise SPDXValueError ( 'Package::Description' ) else : raise CardinalityError ( 'Package::Description' )

Set s the package s description . Raises SPDXValueError if text is not free form text . Raises CardinalityError if description already set . Raises OrderError if no package previously defined .


def set_file_name(self, doc, name):
        """Raises OrderError if no package defined.
        """
        if self.has_package(doc):
            doc.package.files.append(file.File(name))
            # A file name marks the start of a new file instance.
            # The builder must be reset
            # FIXME: this state does not make sense
            self.reset_file_stat()
            return True
        else:
            raise OrderError('File::Name')

Raises OrderError if no package defined .


def set_file_spdx_id(self, doc, spdx_id):
        """
        Sets the file SPDX Identifier.
        Raises OrderError if no package or no file defined.
        Raises SPDXValueError if malformed value.
        Raises CardinalityError if more than one spdx_id set.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_spdx_id_set:
                self.file_spdx_id_set = True
                if validations.validate_file_spdx_id(spdx_id):
                    self.file(doc).spdx_id = spdx_id
                    return True
                else:
                    raise SPDXValueError('File::SPDXID')
            else:
                raise CardinalityError('File::SPDXID')
        else:
            raise OrderError('File::SPDXID')

def set_file_spdx_id ( self , doc , spdx_id ) : if self . has_package ( doc ) and self . has_file ( doc ) : if not self . file_spdx_id_set : self . file_spdx_id_set = True if validations . validate_file_spdx_id ( spdx_id ) : self . file ( doc ) . spdx_id = spdx_id return True else : raise SPDXValueError ( 'File::SPDXID' ) else : raise CardinalityError ( 'File::SPDXID' ) else : raise OrderError ( 'File::SPDXID' )

Sets the file SPDX Identifier . Raises OrderError if no package or no file defined . Raises SPDXValueError if malformed value . Raises CardinalityError if more than one spdx_id set .


def set_file_comment(self, doc, text):
        """
        Raises OrderError if no package or no file defined.
        Raises CardinalityError if more than one comment set.
        Raises SPDXValueError if text is not free form text.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_comment_set:
                self.file_comment_set = True
                if validations.validate_file_comment(text):
                    self.file(doc).comment = str_from_text(text)
                    return True
                else:
                    raise SPDXValueError('File::Comment')
            else:
                raise CardinalityError('File::Comment')
        else:
            raise OrderError('File::Comment')

def set_file_comment ( self , doc , text ) : if self . has_package ( doc ) and self . has_file ( doc ) : if not self . file_comment_set : self . file_comment_set = True if validations . validate_file_comment ( text ) : self . file ( doc ) . comment = str_from_text ( text ) return True else : raise SPDXValueError ( 'File::Comment' ) else : raise CardinalityError ( 'File::Comment' ) else : raise OrderError ( 'File::Comment' )

Raises OrderError if no package or no file defined . Raises CardinalityError if more than one comment set . Raises SPDXValueError if text is not free form text .


def set_file_type(self, doc, type_value):
        """
        Raises OrderError if no package or file defined.
        Raises CardinalityError if more than one type set.
        Raises SPDXValueError if type is unknown.
        """
        type_dict = {
            'SOURCE': file.FileType.SOURCE,
            'BINARY': file.FileType.BINARY,
            'ARCHIVE': file.FileType.ARCHIVE,
            'OTHER': file.FileType.OTHER
        }
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_type_set:
                self.file_type_set = True
                if type_value in type_dict.keys():
                    self.file(doc).type = type_dict[type_value]
                    return True
                else:
                    raise SPDXValueError('File::Type')
            else:
                raise CardinalityError('File::Type')
        else:
            raise OrderError('File::Type')

def set_file_type ( self , doc , type_value ) : type_dict = { 'SOURCE' : file . FileType . SOURCE , 'BINARY' : file . FileType . BINARY , 'ARCHIVE' : file . FileType . ARCHIVE , 'OTHER' : file . FileType . OTHER } if self . has_package ( doc ) and self . has_file ( doc ) : if not self . file_type_set : self . file_type_set = True if type_value in type_dict . keys ( ) : self . file ( doc ) . type = type_dict [ type_value ] return True else : raise SPDXValueError ( 'File::Type' ) else : raise CardinalityError ( 'File::Type' ) else : raise OrderError ( 'File::Type' )

Raises OrderError if no package or file defined . Raises CardinalityError if more than one type set . Raises SPDXValueError if type is unknown .


def set_file_chksum(self, doc, chksum):
        """
        Raises OrderError if no package or file defined.
        Raises CardinalityError if more than one chksum set.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_chksum_set:
                self.file_chksum_set = True
                self.file(doc).chk_sum = checksum_from_sha1(chksum)
                return True
            else:
                raise CardinalityError('File::CheckSum')
        else:
            raise OrderError('File::CheckSum')

def set_file_chksum ( self , doc , chksum ) : if self . has_package ( doc ) and self . has_file ( doc ) : if not self . file_chksum_set : self . file_chksum_set = True self . file ( doc ) . chk_sum = checksum_from_sha1 ( chksum ) return True else : raise CardinalityError ( 'File::CheckSum' ) else : raise OrderError ( 'File::CheckSum' )

Raises OrderError if no package or file defined . Raises CardinalityError if more than one chksum set .


def set_concluded_license(self, doc, lic):
        """
        Raises OrderError if no package or file defined.
        Raises CardinalityError if already set.
        Raises SPDXValueError if malformed.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_conc_lics_set:
                self.file_conc_lics_set = True
                if validations.validate_lics_conc(lic):
                    self.file(doc).conc_lics = lic
                    return True
                else:
                    raise SPDXValueError('File::ConcludedLicense')
            else:
                raise CardinalityError('File::ConcludedLicense')
        else:
            raise OrderError('File::ConcludedLicense')

def set_concluded_license ( self , doc , lic ) : if self . has_package ( doc ) and self . has_file ( doc ) : if not self . file_conc_lics_set : self . file_conc_lics_set = True if validations . validate_lics_conc ( lic ) : self . file ( doc ) . conc_lics = lic return True else : raise SPDXValueError ( 'File::ConcludedLicense' ) else : raise CardinalityError ( 'File::ConcludedLicense' ) else : raise OrderError ( 'File::ConcludedLicense' )

Raises OrderError if no package or file defined . Raises CardinalityError if already set . Raises SPDXValueError if malformed .


def set_file_license_in_file(self, doc, lic):
        """
        Raises OrderError if no package or file defined.
        Raises SPDXValueError if malformed value.
        """
        if self.has_package(doc) and self.has_file(doc):
            if validations.validate_file_lics_in_file(lic):
                self.file(doc).add_lics(lic)
                return True
            else:
                raise SPDXValueError('File::LicenseInFile')
        else:
            raise OrderError('File::LicenseInFile')

def set_file_license_in_file ( self , doc , lic ) : if self . has_package ( doc ) and self . has_file ( doc ) : if validations . validate_file_lics_in_file ( lic ) : self . file ( doc ) . add_lics ( lic ) return True else : raise SPDXValueError ( 'File::LicenseInFile' ) else : raise OrderError ( 'File::LicenseInFile' )

Raises OrderError if no package or file defined . Raises SPDXValueError if malformed value .


def set_file_license_comment(self, doc, text):
        """
        Raises OrderError if no package or file defined.
        Raises SPDXValueError if text is not free form text.
        Raises CardinalityError if more than one per file.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_license_comment_set:
                self.file_license_comment_set = True
                if validations.validate_file_lics_comment(text):
                    self.file(doc).license_comment = str_from_text(text)
                else:
                    raise SPDXValueError('File::LicenseComment')
            else:
                raise CardinalityError('File::LicenseComment')
        else:
            raise OrderError('File::LicenseComment')

def set_file_license_comment ( self , doc , text ) : if self . has_package ( doc ) and self . has_file ( doc ) : if not self . file_license_comment_set : self . file_license_comment_set = True if validations . validate_file_lics_comment ( text ) : self . file ( doc ) . license_comment = str_from_text ( text ) else : raise SPDXValueError ( 'File::LicenseComment' ) else : raise CardinalityError ( 'File::LicenseComment' ) else : raise OrderError ( 'File::LicenseComment' )

Raises OrderError if no package or file defined . Raises SPDXValueError if text is not free form text . Raises CardinalityError if more than one per file .


def set_file_copyright(self, doc, text):
        """Raises OrderError if no package or file defined.
        Raises SPDXValueError if not free form text or NONE or NO_ASSERT.
        Raises CardinalityError if more than one.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_copytext_set:
                self.file_copytext_set = True
                if validations.validate_file_cpyright(text):
                    if isinstance(text, string_types):
                        self.file(doc).copyright = str_from_text(text)
                    else:
                        self.file(doc).copyright = text  # None or NoAssert
                    return True
                else:
                    raise SPDXValueError('File::CopyRight')
            else:
                raise CardinalityError('File::CopyRight')
        else:
            raise OrderError('File::CopyRight')

def
set_file_copyright
(
self
,
doc
,
text
)
:
if
self
.
has_package
(
doc
)
and
self
.
has_file
(
doc
)
:
if
not
self
.
file_copytext_set
:
self
.
file_copytext_set
=
True
if
validations
.
validate_file_cpyright
(
text
)
:
if
isinstance
(
text
,
string_types
)
:
self
.
file
(
doc
)
.
copyright
=
str_from_text
(
text
)
else
:
self
.
file
(
doc
)
.
copyright
=
text
# None or NoAssert
return
True
else
:
raise
SPDXValueError
(
'File::CopyRight'
)
else
:
raise
CardinalityError
(
'File::CopyRight'
)
else
:
raise
OrderError
(
'File::CopyRight'
)

Raises OrderError if no package or file defined . Raises SPDXValueError if not free form text or NONE or NO_ASSERT . Raises CardinalityError if more than one .


def set_file_notice(self, doc, text):
        """Raises OrderError if no package or file defined.
        Raises SPDXValueError if not free form text.
        Raises CardinalityError if more than one.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_notice_set:
                self.file_notice_set = True
                if validations.validate_file_notice(text):
                    self.file(doc).notice = str_from_text(text)
                else:
                    raise SPDXValueError('File::Notice')
            else:
                raise CardinalityError('File::Notice')
        else:
            raise OrderError('File::Notice')

def set_file_notice ( self , doc , text ) : if self . has_package ( doc ) and self . has_file ( doc ) : if not self . file_notice_set : self . file_notice_set = True if validations . validate_file_notice ( text ) : self . file ( doc ) . notice = str_from_text ( text ) else : raise SPDXValueError ( 'File::Notice' ) else : raise CardinalityError ( 'File::Notice' ) else : raise OrderError ( 'File::Notice' )

Raises OrderError if no package or file defined . Raises SPDXValueError if not free form text . Raises CardinalityError if more than one .


def set_file_atrificat_of_project(self, doc, symbol, value):
        """Sets a file name, uri or home artificat.
        Raises OrderError if no package or file defined.
        """
        if self.has_package(doc) and self.has_file(doc):
            self.file(doc).add_artifact(symbol, value)
        else:
            raise OrderError('File::Artificat')

def set_file_atrificat_of_project ( self , doc , symbol , value ) : if self . has_package ( doc ) and self . has_file ( doc ) : self . file ( doc ) . add_artifact ( symbol , value ) else : raise OrderError ( 'File::Artificat' )

Sets a file name uri or home artificat . Raises OrderError if no package or file defined .


def reset_file_stat(self):
        """Resets the builder's state to enable building new files."""
        # FIXME: this state does not make sense
        self.file_spdx_id_set = False
        self.file_comment_set = False
        self.file_type_set = False
        self.file_chksum_set = False
        self.file_conc_lics_set = False
        self.file_license_comment_set = False
        self.file_notice_set = False
        self.file_copytext_set = False

def
reset_file_stat
(
self
)
:
# FIXME: this state does not make sense
self
.
file_spdx_id_set
=
False
self
.
file_comment_set
=
False
self
.
file_type_set
=
False
self
.
file_chksum_set
=
False
self
.
file_conc_lics_set
=
False
self
.
file_license_comment_set
=
False
self
.
file_notice_set
=
False
self
.
file_copytext_set
=
False

Resets the builder s state to enable building new files .


def set_lic_id(self, doc, lic_id):
        """Adds a new extracted license to the document.
        Raises SPDXValueError if data format is incorrect.
        """
        # FIXME: this state does not make sense
        self.reset_extr_lics()
        if validations.validate_extracted_lic_id(lic_id):
            doc.add_extr_lic(document.ExtractedLicense(lic_id))
            return True
        else:
            raise SPDXValueError('ExtractedLicense::id')

def
set_lic_id
(
self
,
doc
,
lic_id
)
:
# FIXME: this state does not make sense
self
.
reset_extr_lics
(
)
if
validations
.
validate_extracted_lic_id
(
lic_id
)
:
doc
.
add_extr_lic
(
document
.
ExtractedLicense
(
lic_id
)
)
return
True
else
:
raise
SPDXValueError
(
'ExtractedLicense::id'
)

Adds a new extracted license to the document . Raises SPDXValueError if data format is incorrect .


def set_lic_text(self, doc, text):
        """Sets license extracted text.
        Raises SPDXValueError if text is not free form text.
        Raises OrderError if no license ID defined.
        """
        if self.has_extr_lic(doc):
            if not self.extr_text_set:
                self.extr_text_set = True
                if validations.validate_is_free_form_text(text):
                    self.extr_lic(doc).text = str_from_text(text)
                    return True
                else:
                    raise SPDXValueError('ExtractedLicense::text')
            else:
                raise CardinalityError('ExtractedLicense::text')
        else:
            raise OrderError('ExtractedLicense::text')

def set_lic_text ( self , doc , text ) : if self . has_extr_lic ( doc ) : if not self . extr_text_set : self . extr_text_set = True if validations . validate_is_free_form_text ( text ) : self . extr_lic ( doc ) . text = str_from_text ( text ) return True else : raise SPDXValueError ( 'ExtractedLicense::text' ) else : raise CardinalityError ( 'ExtractedLicense::text' ) else : raise OrderError ( 'ExtractedLicense::text' )

Sets license extracted text . Raises SPDXValueError if text is not free form text . Raises OrderError if no license ID defined .


def set_lic_name(self, doc, name):
        """Sets license name.
        Raises SPDXValueError if name is not str or utils.NoAssert
        Raises OrderError if no license id defined.
        """
        if self.has_extr_lic(doc):
            if not self.extr_lic_name_set:
                self.extr_lic_name_set = True
                if validations.validate_extr_lic_name(name):
                    self.extr_lic(doc).full_name = name
                    return True
                else:
                    raise SPDXValueError('ExtractedLicense::Name')
            else:
                raise CardinalityError('ExtractedLicense::Name')
        else:
            raise OrderError('ExtractedLicense::Name')

def set_lic_name ( self , doc , name ) : if self . has_extr_lic ( doc ) : if not self . extr_lic_name_set : self . extr_lic_name_set = True if validations . validate_extr_lic_name ( name ) : self . extr_lic ( doc ) . full_name = name return True else : raise SPDXValueError ( 'ExtractedLicense::Name' ) else : raise CardinalityError ( 'ExtractedLicense::Name' ) else : raise OrderError ( 'ExtractedLicense::Name' )

Sets license name . Raises SPDXValueError if name is not str or utils . NoAssert Raises OrderError if no license id defined .


def set_lic_comment(self, doc, comment):
        """Sets license comment.
        Raises SPDXValueError if comment is not free form text.
        Raises OrderError if no license ID defined.
        """
        if self.has_extr_lic(doc):
            if not self.extr_lic_comment_set:
                self.extr_lic_comment_set = True
                if validations.validate_is_free_form_text(comment):
                    self.extr_lic(doc).comment = str_from_text(comment)
                    return True
                else:
                    raise SPDXValueError('ExtractedLicense::comment')
            else:
                raise CardinalityError('ExtractedLicense::comment')
        else:
            raise OrderError('ExtractedLicense::comment')

def set_lic_comment ( self , doc , comment ) : if self . has_extr_lic ( doc ) : if not self . extr_lic_comment_set : self . extr_lic_comment_set = True if validations . validate_is_free_form_text ( comment ) : self . extr_lic ( doc ) . comment = str_from_text ( comment ) return True else : raise SPDXValueError ( 'ExtractedLicense::comment' ) else : raise CardinalityError ( 'ExtractedLicense::comment' ) else : raise OrderError ( 'ExtractedLicense::comment' )

Sets license comment . Raises SPDXValueError if comment is not free form text . Raises OrderError if no license ID defined .


def add_lic_xref(self, doc, ref):
        """Adds a license cross reference.
        Raises OrderError if no License ID defined.
        """
        if self.has_extr_lic(doc):
            self.extr_lic(doc).add_xref(ref)
            return True
        else:
            raise OrderError('ExtractedLicense::CrossRef')

def add_lic_xref ( self , doc , ref ) : if self . has_extr_lic ( doc ) : self . extr_lic ( doc ) . add_xref ( ref ) return True else : raise OrderError ( 'ExtractedLicense::CrossRef' )

Adds a license cross reference . Raises OrderError if no License ID defined .


def reset(self):
        """Resets builder's state for building new documents.
        Must be called between usage with different documents.
        """
        # FIXME: this state does not make sense
        self.reset_creation_info()
        self.reset_document()
        self.reset_package()
        self.reset_file_stat()
        self.reset_reviews()
        self.reset_annotations()
        self.reset_extr_lics()

def
reset
(
self
)
:
# FIXME: this state does not make sense
self
.
reset_creation_info
(
)
self
.
reset_document
(
)
self
.
reset_package
(
)
self
.
reset_file_stat
(
)
self
.
reset_reviews
(
)
self
.
reset_annotations
(
)
self
.
reset_extr_lics
(
)

Resets builder s state for building new documents . Must be called between usage with different documents .


def datetime_iso_format(date):
    """
    Return an ISO-8601 representation of a datetime object.
    """
    return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z".format(
        date.year, date.month, date.day, date.hour,
        date.minute, date.second)

Return an ISO - 8601 representation of a datetime object .


def datetime_from_iso_format(string):
    """
    Return a datetime object from an iso 8601 representation.
    Return None if string is non conforming.
    """
    match = DATE_ISO_REGEX.match(string)
    if match:
        date = datetime.datetime(year=int(match.group(DATE_ISO_YEAR_GRP)),
                                 month=int(match.group(DATE_ISO_MONTH_GRP)),
                                 day=int(match.group(DATE_ISO_DAY_GRP)),
                                 hour=int(match.group(DATE_ISO_HOUR_GRP)),
                                 second=int(match.group(DATE_ISO_SEC_GRP)),
                                 minute=int(match.group(DATE_ISO_MIN_GRP)))
        return date
    else:
        return None

def datetime_from_iso_format ( string ) : match = DATE_ISO_REGEX . match ( string ) if match : date = datetime . datetime ( year = int ( match . group ( DATE_ISO_YEAR_GRP ) ) , month = int ( match . group ( DATE_ISO_MONTH_GRP ) ) , day = int ( match . group ( DATE_ISO_DAY_GRP ) ) , hour = int ( match . group ( DATE_ISO_HOUR_GRP ) ) , second = int ( match . group ( DATE_ISO_SEC_GRP ) ) , minute = int ( match . group ( DATE_ISO_MIN_GRP ) ) ) return date else : return None

Return a datetime object from an iso 8601 representation . Return None if string is non conforming .


def build(self, **kwargs):
        """Must be called before parse."""
        self.yacc = yacc.yacc(module=self, **kwargs)

def build ( self , * * kwargs ) : self . yacc = yacc . yacc ( module = self , * * kwargs )


def parse(self, data):
        """Parses a license list and returns a License or None if it failed."""
        try:
            return self.yacc.parse(data, lexer=self.lex)
        except:
            return None

def parse ( self , data ) : try : return self . yacc . parse ( data , lexer = self . lex ) except : return None

Parses a license list and returns a License or None if it failed .


def write_document(document, out, validate=True):
    """
    Write an SPDX RDF document.
    - document - spdx.document instance.
    - out - file like object that will be written to.
    Optionally `validate` the document before writing and raise
    InvalidDocumentError if document.validate returns False.
    """

    if validate:
        messages = []
        messages = document.validate(messages)
        if messages:
            raise InvalidDocumentError(messages)

    writer = Writer(document, out)
    writer.write()

def write_document ( document , out , validate = True ) : if validate : messages = [ ] messages = document . validate ( messages ) if messages : raise InvalidDocumentError ( messages ) writer = Writer ( document , out ) writer . write ( )

Write an SPDX RDF document . - document - spdx . document instance . - out - file like object that will be written to . Optionally validate the document before writing and raise InvalidDocumentError if document . validate returns False .


def create_checksum_node(self, chksum):
        """
        Return a node representing spdx.checksum.
        """
        chksum_node = BNode()
        type_triple = (chksum_node, RDF.type, self.spdx_namespace.Checksum)
        self.graph.add(type_triple)
        algorithm_triple = (chksum_node, self.spdx_namespace.algorithm, Literal(chksum.identifier))
        self.graph.add(algorithm_triple)
        value_triple = (chksum_node, self.spdx_namespace.checksumValue, Literal(chksum.value))
        self.graph.add(value_triple)
        return chksum_node

def create_checksum_node ( self , chksum ) : chksum_node = BNode ( ) type_triple = ( chksum_node , RDF . type , self . spdx_namespace . Checksum ) self . graph . add ( type_triple ) algorithm_triple = ( chksum_node , self . spdx_namespace . algorithm , Literal ( chksum . identifier ) ) self . graph . add ( algorithm_triple ) value_triple = ( chksum_node , self . spdx_namespace . checksumValue , Literal ( chksum . value ) ) self . graph . add ( value_triple ) return chksum_node

Return a node representing spdx . checksum .


def to_special_value(self, value):
        """
        Return proper spdx term or Literal
        """
        if isinstance(value, utils.NoAssert):
            return self.spdx_namespace.noassertion
        elif isinstance(value, utils.SPDXNone):
            return self.spdx_namespace.none
        else:
            return Literal(value)

def to_special_value ( self , value ) : if isinstance ( value , utils . NoAssert ) : return self . spdx_namespace . noassertion elif isinstance ( value , utils . SPDXNone ) : return self . spdx_namespace . none else : return Literal ( value )


def licenses_from_tree(self, tree):
        """
        Traverse conjunctions and disjunctions like trees and return a
        set of all licenses in it as nodes.
        """
        # FIXME: this is unordered!
        licenses = set()
        self.licenses_from_tree_helper(tree, licenses)
        return licenses

def
licenses_from_tree
(
self
,
tree
)
:
# FIXME: this is unordered!
licenses
=
set
(
)
self
.
licenses_from_tree_helper
(
tree
,
licenses
)
return
licenses

Traverse conjunctions and disjunctions like trees and return a set of all licenses in it as nodes .


def create_conjunction_node(self, conjunction):
        """
        Return a node representing a conjunction of licenses.
        """
        node = BNode()
        type_triple = (node, RDF.type, self.spdx_namespace.ConjunctiveLicenseSet)
        self.graph.add(type_triple)
        licenses = self.licenses_from_tree(conjunction)
        for lic in licenses:
            member_triple = (node, self.spdx_namespace.member, lic)
            self.graph.add(member_triple)
        return node

def create_conjunction_node ( self , conjunction ) : node = BNode ( ) type_triple = ( node , RDF . type , self . spdx_namespace . ConjunctiveLicenseSet ) self . graph . add ( type_triple ) licenses = self . licenses_from_tree ( conjunction ) for lic in licenses : member_triple = ( node , self . spdx_namespace . member , lic ) self . graph . add ( member_triple ) return node

Return a node representing a conjunction of licenses .


def create_disjunction_node(self, disjunction):
        """
        Return a node representing a disjunction of licenses.
        """
        node = BNode()
        type_triple = (node, RDF.type, self.spdx_namespace.DisjunctiveLicenseSet)
        self.graph.add(type_triple)
        licenses = self.licenses_from_tree(disjunction)
        for lic in licenses:
            member_triple = (node, self.spdx_namespace.member, lic)
            self.graph.add(member_triple)
        return node

def create_disjunction_node ( self , disjunction ) : node = BNode ( ) type_triple = ( node , RDF . type , self . spdx_namespace . DisjunctiveLicenseSet ) self . graph . add ( type_triple ) licenses = self . licenses_from_tree ( disjunction ) for lic in licenses : member_triple = ( node , self . spdx_namespace . member , lic ) self . graph . add ( member_triple ) return node

Return a node representing a disjunction of licenses .


def create_extracted_license(self, lic):
        """
        Handle extracted license.
        Return the license node.
        """
        licenses = list(self.graph.triples((None, self.spdx_namespace.licenseId, lic.identifier)))
        if len(licenses) != 0:
            return licenses[0][0]  # return subject in first triple
        else:
            license_node = BNode()
            type_triple = (license_node, RDF.type, self.spdx_namespace.ExtractedLicensingInfo)
            self.graph.add(type_triple)
            ident_triple = (license_node, self.spdx_namespace.licenseId, Literal(lic.identifier))
            self.graph.add(ident_triple)
            text_triple = (license_node, self.spdx_namespace.extractedText, Literal(lic.text))
            self.graph.add(text_triple)
            if lic.full_name is not None:
                name_triple = (license_node, self.spdx_namespace.licenseName, self.to_special_value(lic.full_name))
                self.graph.add(name_triple)
            for ref in lic.cross_ref:
                triple = (license_node, RDFS.seeAlso, URIRef(ref))
                self.graph.add(triple)
            if lic.comment is not None:
                comment_triple = (license_node, RDFS.comment, Literal(lic.comment))
                self.graph.add(comment_triple)
            return license_node

def
create_extracted_license
(
self
,
lic
)
:
licenses
=
list
(
self
.
graph
.
triples
(
(
,
self
.
spdx_namespace
.
licenseId
,
lic
.
identifier
)
)
)
if
len
(
licenses
)
!=
0
:
return
licenses
[
0
]
[
0
]
# return subject in first triple
else
:
license_node
=
BNode
(
)
type_triple
=
(
license_node
,
RDF
.
type
,
self
.
spdx_namespace
.
ExtractedLicensingInfo
)
self
.
graph
.
add
(
type_triple
)
ident_triple
=
(
license_node
,
self
.
spdx_namespace
.
licenseId
,
Literal
(
lic
.
identifier
)
)
self
.
graph
.
add
(
ident_triple
)
text_triple
=
(
license_node
,
self
.
spdx_namespace
.
extractedText
,
Literal
(
lic
.
text
)
)
self
.
graph
.
add
(
text_triple
)
if
lic
.
full_name
is
not
:
name_triple
=
(
license_node
,
self
.
spdx_namespace
.
licenseName
,
self
.
to_special_value
(
lic
.
full_name
)
)
self
.
graph
.
add
(
name_triple
)
for
ref
in
lic
.
cross_ref
:
triple
=
(
license_node
,
RDFS
.
seeAlso
,
URIRef
(
ref
)
)
self
.
graph
.
add
(
triple
)
if
lic
.
comment
is
not
:
comment_triple
=
(
license_node
,
RDFS
.
comment
,
Literal
(
lic
.
comment
)
)
self
.
graph
.
add
(
comment_triple
)
return
license_node

Handle extracted license . Return the license node .


def create_file_node(self, doc_file):
        """
        Create a node for spdx.file.
        """
        file_node = URIRef('http://www.spdx.org/files#{id}'.format(
            id=str(doc_file.spdx_id)))
        type_triple = (file_node, RDF.type, self.spdx_namespace.File)
        self.graph.add(type_triple)

        name_triple = (file_node, self.spdx_namespace.fileName, Literal(doc_file.name))
        self.graph.add(name_triple)

        if doc_file.has_optional_field('comment'):
            comment_triple = (file_node, RDFS.comment, Literal(doc_file.comment))
            self.graph.add(comment_triple)

        if doc_file.has_optional_field('type'):
            ftype = self.spdx_namespace[self.FILE_TYPES[doc_file.type]]
            ftype_triple = (file_node, self.spdx_namespace.fileType, ftype)
            self.graph.add(ftype_triple)

        self.graph.add((file_node, self.spdx_namespace.checksum, self.create_checksum_node(doc_file.chk_sum)))

        conc_lic_node = self.license_or_special(doc_file.conc_lics)
        conc_lic_triple = (file_node, self.spdx_namespace.licenseConcluded, conc_lic_node)
        self.graph.add(conc_lic_triple)

        license_info_nodes = map(self.license_or_special, doc_file.licenses_in_file)
        for lic in license_info_nodes:
            triple = (file_node, self.spdx_namespace.licenseInfoInFile, lic)
            self.graph.add(triple)

        if doc_file.has_optional_field('license_comment'):
            comment_triple = (file_node, self.spdx_namespace.licenseComments, Literal(doc_file.license_comment))
            self.graph.add(comment_triple)

        cr_text_node = self.to_special_value(doc_file.copyright)
        cr_text_triple = (file_node, self.spdx_namespace.copyrightText, cr_text_node)
        self.graph.add(cr_text_triple)

        if doc_file.has_optional_field('notice'):
            notice_triple = (file_node, self.spdx_namespace.noticeText, doc_file.notice)
            self.graph.add(notice_triple)

        contrib_nodes = map(lambda c: Literal(c), doc_file.contributors)
        contrib_triples = [(file_node, self.spdx_namespace.fileContributor, node) for node in contrib_nodes]
        for triple in contrib_triples:
            self.graph.add(triple)

        return file_node

def create_file_node ( self , doc_file ) : file_node = URIRef ( 'http://www.spdx.org/files#{id}' . format ( id = str ( doc_file . spdx_id ) ) ) type_triple = ( file_node , RDF . type , self . spdx_namespace . File ) self . graph . add ( type_triple ) name_triple = ( file_node , self . spdx_namespace . fileName , Literal ( doc_file . name ) ) self . graph . add ( name_triple ) if doc_file . has_optional_field ( 'comment' ) : comment_triple = ( file_node , RDFS . comment , Literal ( doc_file . comment ) ) self . graph . add ( comment_triple ) if doc_file . has_optional_field ( 'type' ) : ftype = self . spdx_namespace [ self . FILE_TYPES [ doc_file . type ] ] ftype_triple = ( file_node , self . spdx_namespace . fileType , ftype ) self . graph . add ( ftype_triple ) self . graph . add ( ( file_node , self . spdx_namespace . checksum , self . create_checksum_node ( doc_file . chk_sum ) ) ) conc_lic_node = self . license_or_special ( doc_file . conc_lics ) conc_lic_triple = ( file_node , self . spdx_namespace . licenseConcluded , conc_lic_node ) self . graph . add ( conc_lic_triple ) license_info_nodes = map ( self . license_or_special , doc_file . licenses_in_file ) for lic in license_info_nodes : triple = ( file_node , self . spdx_namespace . licenseInfoInFile , lic ) self . graph . add ( triple ) if doc_file . has_optional_field ( 'license_comment' ) : comment_triple = ( file_node , self . spdx_namespace . licenseComments , Literal ( doc_file . license_comment ) ) self . graph . add ( comment_triple ) cr_text_node = self . to_special_value ( doc_file . copyright ) cr_text_triple = ( file_node , self . spdx_namespace . copyrightText , cr_text_node ) self . graph . add ( cr_text_triple ) if doc_file . has_optional_field ( 'notice' ) : notice_triple = ( file_node , self . spdx_namespace . noticeText , doc_file . notice ) self . graph . add ( notice_triple ) contrib_nodes = map ( lambda c : Literal ( c ) , doc_file . contributors ) contrib_triples = [ ( file_node , self . spdx_namespace . fileContributor , node ) for node in contrib_nodes ] for triple in contrib_triples : self . graph . add ( triple ) return file_node


def add_file_dependencies_helper(self, doc_file):
        """
        Handle dependencies for a single file.
        - doc_file - instance of spdx.file.File.
        """
        subj_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(doc_file.name))))
        if len(subj_triples) != 1:
            raise InvalidDocumentError('Could not find dependency subject {0}'.format(doc_file.name))
        subject_node = subj_triples[0][0]
        for dependency in doc_file.dependencies:
            dep_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(dependency))))
            if len(dep_triples) == 1:
                dep_node = dep_triples[0][0]
                dep_triple = (subject_node, self.spdx_namespace.fileDependency, dep_node)
                self.graph.add(dep_triple)
            else:
                print('Warning could not resolve file dependency {0} -> {1}'.format(doc_file.name, dependency))

Handle dependencies for a single file . - doc_file - instance of spdx . file . File .


def create_review_node(self, review):
        """
        Return a review node.
        """
        review_node = BNode()
        type_triple = (review_node, RDF.type, self.spdx_namespace.Review)
        self.graph.add(type_triple)

        reviewer_node = Literal(review.reviewer.to_value())
        self.graph.add((review_node, self.spdx_namespace.reviewer, reviewer_node))
        reviewed_date_node = Literal(review.review_date_iso_format)
        reviewed_triple = (review_node, self.spdx_namespace.reviewDate, reviewed_date_node)
        self.graph.add(reviewed_triple)
        if review.has_comment:
            comment_node = Literal(review.comment)
            comment_triple = (review_node, RDFS.comment, comment_node)
            self.graph.add(comment_triple)

        return review_node

def create_review_node ( self , review ) : review_node = BNode ( ) type_triple = ( review_node , RDF . type , self . spdx_namespace . Review ) self . graph . add ( type_triple ) reviewer_node = Literal ( review . reviewer . to_value ( ) ) self . graph . add ( ( review_node , self . spdx_namespace . reviewer , reviewer_node ) ) reviewed_date_node = Literal ( review . review_date_iso_format ) reviewed_triple = ( review_node , self . spdx_namespace . reviewDate , reviewed_date_node ) self . graph . add ( reviewed_triple ) if review . has_comment : comment_node = Literal ( review . comment ) comment_triple = ( review_node , RDFS . comment , comment_node ) self . graph . add ( comment_triple ) return review_node


def create_annotation_node(self, annotation):
        """
        Return an annotation node.
        """
        annotation_node = URIRef(str(annotation.spdx_id))
        type_triple = (annotation_node, RDF.type, self.spdx_namespace.Annotation)
        self.graph.add(type_triple)

        annotator_node = Literal(annotation.annotator.to_value())
        self.graph.add((annotation_node, self.spdx_namespace.annotator, annotator_node))
        annotation_date_node = Literal(annotation.annotation_date_iso_format)
        annotation_triple = (annotation_node, self.spdx_namespace.annotationDate, annotation_date_node)
        self.graph.add(annotation_triple)
        if annotation.has_comment:
            comment_node = Literal(annotation.comment)
            comment_triple = (annotation_node, RDFS.comment, comment_node)
            self.graph.add(comment_triple)
        annotation_type_node = Literal(annotation.annotation_type)
        annotation_type_triple = (annotation_node, self.spdx_namespace.annotationType, annotation_type_node)
        self.graph.add(annotation_type_triple)

        return annotation_node

def create_annotation_node ( self , annotation ) : annotation_node = URIRef ( str ( annotation . spdx_id ) ) type_triple = ( annotation_node , RDF . type , self . spdx_namespace . Annotation ) self . graph . add ( type_triple ) annotator_node = Literal ( annotation . annotator . to_value ( ) ) self . graph . add ( ( annotation_node , self . spdx_namespace . annotator , annotator_node ) ) annotation_date_node = Literal ( annotation . annotation_date_iso_format ) annotation_triple = ( annotation_node , self . spdx_namespace . annotationDate , annotation_date_node ) self . graph . add ( annotation_triple ) if annotation . has_comment : comment_node = Literal ( annotation . comment ) comment_triple = ( annotation_node , RDFS . comment , comment_node ) self . graph . add ( comment_triple ) annotation_type_node = Literal ( annotation . annotation_type ) annotation_type_triple = ( annotation_node , self . spdx_namespace . annotationType , annotation_type_node ) self . graph . add ( annotation_type_triple ) return annotation_node


def package_verif_node(self, package):
        """
        Return a node representing package verification code.
        """
        verif_node = BNode()
        type_triple = (verif_node, RDF.type, self.spdx_namespace.PackageVerificationCode)
        self.graph.add(type_triple)
        value_triple = (verif_node, self.spdx_namespace.packageVerificationCodeValue, Literal(package.verif_code))
        self.graph.add(value_triple)
        excl_file_nodes = map(
            lambda excl: Literal(excl), package.verif_exc_files)
        excl_predicate = self.spdx_namespace.packageVerificationCodeExcludedFile
        excl_file_triples = [(verif_node, excl_predicate, xcl_file) for xcl_file in excl_file_nodes]
        for trp in excl_file_triples:
            self.graph.add(trp)
        return verif_node

def package_verif_node ( self , package ) : verif_node = BNode ( ) type_triple = ( verif_node , RDF . type , self . spdx_namespace . PackageVerificationCode ) self . graph . add ( type_triple ) value_triple = ( verif_node , self . spdx_namespace . packageVerificationCodeValue , Literal ( package . verif_code ) ) self . graph . add ( value_triple ) excl_file_nodes = map ( lambda excl : Literal ( excl ) , package . verif_exc_files ) excl_predicate = self . spdx_namespace . packageVerificationCodeExcludedFile excl_file_triples = [ ( verif_node , excl_predicate , xcl_file ) for xcl_file in excl_file_nodes ] for trp in excl_file_triples : self . graph . add ( trp ) return verif_node

Return a node representing package verification code .


def handle_pkg_optional_fields(self, package, package_node):
        """
        Write package optional fields.
        """
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.versionInfo, 'version')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.packageFileName, 'file_name')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.supplier, 'supplier')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.originator, 'originator')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.sourceInfo, 'source_info')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.licenseComments, 'license_comment')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.summary, 'summary')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.description, 'description')

        if package.has_optional_field('check_sum'):
            checksum_node = self.create_checksum_node(package.check_sum)
            self.graph.add((package_node, self.spdx_namespace.checksum, checksum_node))

        if package.has_optional_field('homepage'):
            homepage_node = URIRef(self.to_special_value(package.homepage))
            homepage_triple = (package_node, self.doap_namespace.homepage, homepage_node)
            self.graph.add(homepage_triple)

def handle_pkg_optional_fields ( self , package , package_node ) : self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . versionInfo , 'version' ) self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . packageFileName , 'file_name' ) self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . supplier , 'supplier' ) self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . originator , 'originator' ) self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . sourceInfo , 'source_info' ) self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . licenseComments , 'license_comment' ) self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . summary , 'summary' ) self . handle_package_literal_optional ( package , package_node , self . spdx_namespace . description , 'description' ) if package . has_optional_field ( 'check_sum' ) : checksum_node = self . create_checksum_node ( package . check_sum ) self . graph . add ( ( package_node , self . spdx_namespace . checksum , checksum_node ) ) if package . has_optional_field ( 'homepage' ) : homepage_node = URIRef ( self . to_special_value ( package . homepage ) ) homepage_triple = ( package_node , self . doap_namespace . homepage , homepage_node ) self . graph . add ( homepage_triple )


def create_package_node(self, package):
        """
        Return a Node representing the package.
        Files must have been added to the graph before this method is called.
        """
        package_node = BNode()
        type_triple = (package_node, RDF.type, self.spdx_namespace.Package)
        self.graph.add(type_triple)
        # Handle optional fields:
        self.handle_pkg_optional_fields(package, package_node)
        # package name
        name_triple = (package_node, self.spdx_namespace.name, Literal(package.name))
        self.graph.add(name_triple)
        # Package download location
        down_loc_node = (package_node, self.spdx_namespace.downloadLocation, self.to_special_value(package.download_location))
        self.graph.add(down_loc_node)
        # Handle package verification
        verif_node = self.package_verif_node(package)
        verif_triple = (package_node, self.spdx_namespace.packageVerificationCode, verif_node)
        self.graph.add(verif_triple)
        # Handle concluded license
        conc_lic_node = self.license_or_special(package.conc_lics)
        conc_lic_triple = (package_node, self.spdx_namespace.licenseConcluded, conc_lic_node)
        self.graph.add(conc_lic_triple)
        # Handle declared license
        decl_lic_node = self.license_or_special(package.license_declared)
        decl_lic_triple = (package_node, self.spdx_namespace.licenseDeclared, decl_lic_node)
        self.graph.add(decl_lic_triple)
        # Package licenses from files
        licenses_from_files_nodes = map(lambda el: self.license_or_special(el), package.licenses_from_files)
        lic_from_files_predicate = self.spdx_namespace.licenseInfoFromFiles
        lic_from_files_triples = [(package_node, lic_from_files_predicate, node) for node in licenses_from_files_nodes]
        for triple in lic_from_files_triples:
            self.graph.add(triple)
        # Copyright Text
        cr_text_node = self.to_special_value(package.cr_text)
        cr_text_triple = (package_node, self.spdx_namespace.copyrightText, cr_text_node)
        self.graph.add(cr_text_triple)
        # Handle files
        self.handle_package_has_file(package, package_node)
        return package_node

def
create_package_node
(
self
,
package
)
:
package_node
=
BNode
(
)
type_triple
=
(
package_node
,
RDF
.
type
,
self
.
spdx_namespace
.
Package
)
self
.
graph
.
add
(
type_triple
)
# Handle optional fields:
self
.
handle_pkg_optional_fields
(
package
,
package_node
)
# package name
name_triple
=
(
package_node
,
self
.
spdx_namespace
.
name
,
Literal
(
package
.
name
)
)
self
.
graph
.
add
(
name_triple
)
# Package download location
down_loc_node
=
(
package_node
,
self
.
spdx_namespace
.
downloadLocation
,
self
.
to_special_value
(
package
.
download_location
)
)
self
.
graph
.
add
(
down_loc_node
)
# Handle package verification
verif_node
=
self
.
package_verif_node
(
package
)
verif_triple
=
(
package_node
,
self
.
spdx_namespace
.
packageVerificationCode
,
verif_node
)
self
.
graph
.
add
(
verif_triple
)
# Handle concluded license
conc_lic_node
=
self
.
license_or_special
(
package
.
conc_lics
)
conc_lic_triple
=
(
package_node
,
self
.
spdx_namespace
.
licenseConcluded
,
conc_lic_node
)
self
.
graph
.
add
(
conc_lic_triple
)
# Handle declared license
decl_lic_node
=
self
.
license_or_special
(
package
.
license_declared
)
decl_lic_triple
=
(
package_node
,
self
.
spdx_namespace
.
licenseDeclared
,
decl_lic_node
)
self
.
graph
.
add
(
decl_lic_triple
)
# Package licenses from files
licenses_from_files_nodes
=
map
(
lambda
el
:
self
.
license_or_special
(
el
)
,
package
.
licenses_from_files
)
lic_from_files_predicate
=
self
.
spdx_namespace
.
licenseInfoFromFiles
lic_from_files_triples
=
[
(
package_node
,
lic_from_files_predicate
,
node
)
for
node
in
licenses_from_files_nodes
]
for
triple
in
lic_from_files_triples
:
self
.
graph
.
add
(
triple
)
# Copyright Text
cr_text_node
=
self
.
to_special_value
(
package
.
cr_text
)
cr_text_triple
=
(
package_node
,
self
.
spdx_namespace
.
copyrightText
,
cr_text_node
)
self
.
graph
.
add
(
cr_text_triple
)
# Handle files
self
.
handle_package_has_file
(
package
,
package_node
)
return
package_node

Return a Node representing the package . Files must have been added to the graph before this method is called .


def handle_package_has_file_helper(self, pkg_file):
        """
        Return node representing pkg_file
        pkg_file should be instance of spdx.file.
        """
        nodes = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(pkg_file.name))))
        if len(nodes) == 1:
            return nodes[0][0]
        else:
            raise InvalidDocumentError('handle_package_has_file_helper could not' +
                                       ' find file node for file: {0}'.format(pkg_file.name))

Return node representing pkg_file pkg_file should be instance of spdx . file .


def handle_package_has_file(self, package, package_node):
        """
        Add hasFile triples to graph.
        Must be called after files have been added.
        """
        file_nodes = map(self.handle_package_has_file_helper, package.files)
        triples = [(package_node, self.spdx_namespace.hasFile, node) for node in file_nodes]
        for triple in triples:
            self.graph.add(triple)

def handle_package_has_file ( self , package , package_node ) : file_nodes = map ( self . handle_package_has_file_helper , package . files ) triples = [ ( package_node , self . spdx_namespace . hasFile , node ) for node in file_nodes ] for triple in triples : self . graph . add ( triple )

Add hasFile triples to graph . Must be called after files have been added .


def create_doc(self):
        """
        Add and return the root document node to graph.
        """
        doc_node = URIRef('http://www.spdx.org/tools#SPDXRef-DOCUMENT')
        # Doc type
        self.graph.add((doc_node, RDF.type, self.spdx_namespace.SpdxDocument))
        # Version
        vers_literal = Literal(str(self.document.version))
        self.graph.add((doc_node, self.spdx_namespace.specVersion, vers_literal))
        # Data license
        data_lics = URIRef(self.document.data_license.url)
        self.graph.add((doc_node, self.spdx_namespace.dataLicense, data_lics))
        doc_name = URIRef(self.document.name)
        self.graph.add((doc_node, self.spdx_namespace.name, doc_name))
        return doc_node

Add and return the root document node to graph .


def validate(self, messages):
        """Returns True if the fields are valid according to the SPDX standard.
        Appends user friendly messages to the messages parameter.
        """
        messages = self.validate_creators(messages)
        messages = self.validate_created(messages)

        return messages

def validate ( self , messages ) : messages = self . validate_creators ( messages ) messages = self . validate_created ( messages ) return messages

Returns True if the fields are valid according to the SPDX standard . Appends user friendly messages to the messages parameter .


def value_error(self, key, bad_value):
        """Reports a value error using ERROR_MESSAGES dict.
        key - key to use for ERROR_MESSAGES.
        bad_value - is passed to format which is called on what key maps to
        in ERROR_MESSAGES.
        """
        msg = ERROR_MESSAGES[key].format(bad_value)
        self.logger.log(msg)
        self.error = True

def value_error ( self , key , bad_value ) : msg = ERROR_MESSAGES [ key ] . format ( bad_value ) self . logger . log ( msg ) self . error = True

Reports a value error using ERROR_MESSAGES dict . key - key to use for ERROR_MESSAGES . bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES .


def to_special_value(self, value):
        """Checks if value is a special SPDX value such as
        NONE, NOASSERTION or UNKNOWN if so returns proper model.
        else returns value"""
        if value == self.spdx_namespace.none:
            return utils.SPDXNone()
        elif value == self.spdx_namespace.noassertion:
            return utils.NoAssert()
        elif value == self.spdx_namespace.unknown:
            return utils.UnKnown()
        else:
            return value

def to_special_value ( self , value ) : if value == self . spdx_namespace . none : return utils . SPDXNone ( ) elif value == self . spdx_namespace . noassertion : return utils . NoAssert ( ) elif value == self . spdx_namespace . unknown : return utils . UnKnown ( ) else : return value

Checks if value is a special SPDX value such as NONE NOASSERTION or UNKNOWN if so returns proper model . else returns value


def handle_lics(self, lics):
        """
        Return a License from a `lics` license resource.
        """
        # Handle extracted licensing info type.
        if (lics, RDF.type, self.spdx_namespace['ExtractedLicensingInfo']) in self.graph:
            return self.parse_only_extr_license(lics)

        # Assume resource, hence the path separator
        ident_start = lics.rfind('/') + 1
        if ident_start == 0:
            # special values such as spdx:noassertion
            special = self.to_special_value(lics)
            if special == lics:
                if self.LICS_REF_REGEX.match(lics):
                    # Is a license ref i.e LicenseRef-1
                    return document.License.from_identifier(lics)
                else:
                    # Not a known license form
                    raise SPDXValueError('License')
            else:
                # is a special value
                return special
        else:
            # license url
            return document.License.from_identifier(lics[ident_start:])

Return a License from a lics license resource .


def get_extr_license_ident(self, extr_lic):
        """
        Return an a license identifier from an ExtractedLicense or None.
        """
        identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None)))

        if not identifier_tripples:
            self.error = True
            msg = 'Extracted license must have licenseId property.'
            self.logger.log(msg)
            return

        if len(identifier_tripples) > 1:
            self.more_than_one_error('extracted license identifier_tripples')
            return

        identifier_tripple = identifier_tripples[0]
        _s, _p, identifier = identifier_tripple
        return identifier

Return an a license identifier from an ExtractedLicense or None .


def get_extr_license_text(self, extr_lic):
        """
        Return extracted text  from an ExtractedLicense or None.
        """
        text_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['extractedText'], None)))
        if not text_tripples:
            self.error = True
            msg = 'Extracted license must have extractedText property'
            self.logger.log(msg)
            return

        if len(text_tripples) > 1:
            self.more_than_one_error('extracted license text')
            return

        text_tripple = text_tripples[0]
        _s, _p, text = text_tripple
        return text

Return extracted text from an ExtractedLicense or None .


def get_extr_lic_name(self, extr_lic):
        """
        Return the license name from an ExtractedLicense or None
        """
        extr_name_list = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseName'], None)))
        if len(extr_name_list) > 1:
            self.more_than_one_error('extracted license name')
            return
        elif len(extr_name_list) == 0:
            return
        return self.to_special_value(extr_name_list[0][2])

def
get_extr_lic_name
(
self
,
extr_lic
)
:
extr_name_list
=
list
(
self
.
graph
.
triples
(
(
extr_lic
,
self
.
spdx_namespace
[
'licenseName'
]
,
)
)
)
if
len
(
extr_name_list
)
>
1
:
self
.
more_than_one_error
(
'extracted license name'
)
return
elif
len
(
extr_name_list
)
==
0
:
return
return
self
.
to_special_value
(
extr_name_list
[
0
]
[
2
]
)


def get_extr_lics_xref(self, extr_lic):
        """
        Return a list of cross references.
        """
        xrefs = list(self.graph.triples((extr_lic, RDFS.seeAlso, None)))
        return map(lambda xref_triple: xref_triple[2], xrefs)

def get_extr_lics_xref ( self , extr_lic ) : xrefs = list ( self . graph . triples ( ( extr_lic , RDFS . seeAlso , None ) ) ) return map ( lambda xref_triple : xref_triple [ 2 ] , xrefs )


def get_extr_lics_comment(self, extr_lics):
        """
        Return license comment or None.
        """
        comment_list = list(self.graph.triples(
            (extr_lics, RDFS.comment, None)))
        if len(comment_list) > 1 :
            self.more_than_one_error('extracted license comment')
            return
        elif len(comment_list) == 1:
            return comment_list[0][2]
        else:
            return

def
get_extr_lics_comment
(
self
,
extr_lics
)
:
comment_list
=
list
(
self
.
graph
.
triples
(
(
extr_lics
,
RDFS
.
comment
,
)
)
)
if
len
(
comment_list
)
>
1
:
self
.
more_than_one_error
(
'extracted license comment'
)
return
elif
len
(
comment_list
)
==
1
:
return
comment_list
[
0
]
[
2
]
else
:
return


def parse_only_extr_license(self, extr_lic):
        """
        Return an ExtractedLicense object to represent a license object.
        But does not add it to the SPDXDocument model.
        Return None if failed.
        """
        # Grab all possible values
        ident = self.get_extr_license_ident(extr_lic)
        text = self.get_extr_license_text(extr_lic)
        comment = self.get_extr_lics_comment(extr_lic)
        xrefs = self.get_extr_lics_xref(extr_lic)
        name = self.get_extr_lic_name(extr_lic)

        if not ident:
            # Must have identifier
            return

        # Set fields
        # FIXME: the constructor of the license should alwas accept a name
        lic = document.ExtractedLicense(ident)
        if text is not None:
            lic.text = text
        if name is not None:
            lic.full_name = name
        if comment is not None:
            lic.comment = comment
        lic.cross_ref = map(lambda x: six.text_type(x), xrefs)
        return lic

Return an ExtractedLicense object to represent a license object . But does not add it to the SPDXDocument model . Return None if failed .


def handle_extracted_license(self, extr_lic):
        """
        Build and return an ExtractedLicense or None.
        Note that this function adds the license to the document.
        """
        lic = self.parse_only_extr_license(extr_lic)
        if lic is not None:
            self.doc.add_extr_lic(lic)
        return lic

def handle_extracted_license ( self , extr_lic ) : lic = self . parse_only_extr_license ( extr_lic ) if lic is not None : self . doc . add_extr_lic ( lic ) return lic

Build and return an ExtractedLicense or None . Note that this function adds the license to the document .


def parse_package(self, p_term):
        """Parses package fields."""
        # Check there is a pacakge name
        if not (p_term, self.spdx_namespace['name'], None) in self.graph:
            self.error = True
            self.logger.log('Package must have a name.')
            # Create dummy package so that we may continue parsing the rest of
            # the package fields.
            self.builder.create_package(self.doc, 'dummy_package')
        else:
            for _s, _p, o in self.graph.triples((p_term, self.spdx_namespace['name'], None)):
                try:
                    self.builder.create_package(self.doc, six.text_type(o))
                except CardinalityError:
                    self.more_than_one_error('Package name')
                    break

        self.p_pkg_vinfo(p_term, self.spdx_namespace['versionInfo'])
        self.p_pkg_fname(p_term, self.spdx_namespace['packageFileName'])
        self.p_pkg_suppl(p_term, self.spdx_namespace['supplier'])
        self.p_pkg_originator(p_term, self.spdx_namespace['originator'])
        self.p_pkg_down_loc(p_term, self.spdx_namespace['downloadLocation'])
        self.p_pkg_homepg(p_term, self.doap_namespace['homepage'])
        self.p_pkg_chk_sum(p_term, self.spdx_namespace['checksum'])
        self.p_pkg_src_info(p_term, self.spdx_namespace['sourceInfo'])
        self.p_pkg_verif_code(p_term, self.spdx_namespace['packageVerificationCode'])
        self.p_pkg_lic_conc(p_term, self.spdx_namespace['licenseConcluded'])
        self.p_pkg_lic_decl(p_term, self.spdx_namespace['licenseDeclared'])
        self.p_pkg_lics_info_from_files(p_term, self.spdx_namespace['licenseInfoFromFiles'])
        self.p_pkg_comments_on_lics(p_term, self.spdx_namespace['licenseComments'])
        self.p_pkg_cr_text(p_term, self.spdx_namespace['copyrightText'])
        self.p_pkg_summary(p_term, self.spdx_namespace['summary'])
        self.p_pkg_descr(p_term, self.spdx_namespace['description'])


def handle_pkg_lic(self, p_term, predicate, builder_func):
        """Handles package lics concluded or declared."""
        try:
            for _, _, licenses in self.graph.triples((p_term, predicate, None)):
                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_conjunctive_list(licenses)
                    builder_func(self.doc, lics)

                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_disjunctive_list(licenses)
                    builder_func(self.doc, lics)

                else:
                    try:
                        lics = self.handle_lics(licenses)
                        builder_func(self.doc, lics)
                    except SPDXValueError:
                        self.value_error('PKG_SINGLE_LICS', licenses)
        except CardinalityError:
            self.more_than_one_error('package {0}'.format(predicate))

def
handle_pkg_lic
(
self
,
p_term
,
predicate
,
builder_func
)
:
try
:
for
_
,
_
,
licenses
in
self
.
graph
.
triples
(
(
p_term
,
predicate
,
)
)
:
if
(
licenses
,
RDF
.
type
,
self
.
spdx_namespace
[
'ConjunctiveLicenseSet'
]
)
in
self
.
graph
:
lics
=
self
.
handle_conjunctive_list
(
licenses
)
builder_func
(
self
.
doc
,
lics
)
elif
(
licenses
,
RDF
.
type
,
self
.
spdx_namespace
[
'DisjunctiveLicenseSet'
]
)
in
self
.
graph
:
lics
=
self
.
handle_disjunctive_list
(
licenses
)
builder_func
(
self
.
doc
,
lics
)
else
:
try
:
lics
=
self
.
handle_lics
(
licenses
)
builder_func
(
self
.
doc
,
lics
)
except
SPDXValueError
:
self
.
value_error
(
'PKG_SINGLE_LICS'
,
licenses
)
except
CardinalityError
:
self
.
more_than_one_error
(
'package {0}'
.
format
(
predicate
)
)

Handles package lics concluded or declared .


def get_file_name(self, f_term):
        """Returns first found fileName property or None if not found."""
        for _, _, name in self.graph.triples((f_term, self.spdx_namespace['fileName'], None)):
            return name
        return

def get_file_name ( self , f_term ) : for _ , _ , name in self . graph . triples ( ( f_term , self . spdx_namespace [ 'fileName' ] , None ) ) : return name return

Returns first found fileName property or None if not found .


def p_file_depends(self, f_term, predicate):
        """Sets file dependencies."""
        for _, _, other_file in self.graph.triples((f_term, predicate, None)):
            name = self.get_file_name(other_file)
            if name is not None:
                self.builder.add_file_dep(six.text_type(name))
            else:
                self.error = True
                msg = 'File depends on file with no name'
                self.logger.log(msg)

def
p_file_depends
(
self
,
f_term
,
predicate
)
:
for
_
,
_
,
other_file
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
name
=
self
.
get_file_name
(
other_file
)
if
name
is
not
:
self
.
builder
.
add_file_dep
(
six
.
text_type
(
name
)
)
else
:
self
.
error
=
True
msg
=
'File depends on file with no name'
self
.
logger
.
log
(
msg
)


def p_file_contributor(self, f_term, predicate):
        """
        Parse all file contributors and adds them to the model.
        """
        for _, _, contributor in self.graph.triples((f_term, predicate, None)):
            self.builder.add_file_contribution(self.doc, six.text_type(contributor))

def p_file_contributor ( self , f_term , predicate ) : for _ , _ , contributor in self . graph . triples ( ( f_term , predicate , None ) ) : self . builder . add_file_contribution ( self . doc , six . text_type ( contributor ) )

Parse all file contributors and adds them to the model .


def p_file_notice(self, f_term, predicate):
        """Sets file notice text."""
        try:
            for _, _, notice in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_notice(self.doc, six.text_type(notice))
        except CardinalityError:
            self.more_than_one_error('file notice')

def
p_file_notice
(
self
,
f_term
,
predicate
)
:
try
:
for
_
,
_
,
notice
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
self
.
builder
.
set_file_notice
(
self
.
doc
,
six
.
text_type
(
notice
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'file notice'
)


def p_file_comment(self, f_term, predicate):
        """Sets file comment text."""
        try:
            for _, _, comment in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_comment(self.doc, six.text_type(comment))
        except CardinalityError:
            self.more_than_one_error('file comment')

def
p_file_comment
(
self
,
f_term
,
predicate
)
:
try
:
for
_
,
_
,
comment
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
self
.
builder
.
set_file_comment
(
self
.
doc
,
six
.
text_type
(
comment
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'file comment'
)


def p_file_cr_text(self, f_term, predicate):
        """Sets file copyright text."""
        try:
            for _, _, cr_text in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_copyright(self.doc, six.text_type(cr_text))
        except CardinalityError:
            self.more_than_one_error('file copyright text')

def
p_file_cr_text
(
self
,
f_term
,
predicate
)
:
try
:
for
_
,
_
,
cr_text
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
self
.
builder
.
set_file_copyright
(
self
.
doc
,
six
.
text_type
(
cr_text
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'file copyright text'
)


def p_file_comments_on_lics(self, f_term, predicate):
        """Sets file license comment."""
        try:
            for _, _, comment in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_license_comment(self.doc, six.text_type(comment))
        except CardinalityError:
            self.more_than_one_error('file comments on license')

def
p_file_comments_on_lics
(
self
,
f_term
,
predicate
)
:
try
:
for
_
,
_
,
comment
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
self
.
builder
.
set_file_license_comment
(
self
.
doc
,
six
.
text_type
(
comment
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'file comments on license'
)


def p_file_lic_info(self, f_term, predicate):
        """Sets file license information."""
        for _, _, info in self.graph.triples((f_term, predicate, None)):
            lic = self.handle_lics(info)
            if lic is not None:
                self.builder.set_file_license_in_file(self.doc, lic)

def p_file_lic_info ( self , f_term , predicate ) : for _ , _ , info in self . graph . triples ( ( f_term , predicate , None ) ) : lic = self . handle_lics ( info ) if lic is not None : self . builder . set_file_license_in_file ( self . doc , lic )


def p_file_type(self, f_term, predicate):
        """Sets file type."""
        try:
            for _, _, ftype in self.graph.triples((f_term, predicate, None)):
                try:
                    if ftype.endswith('binary'):
                        ftype = 'BINARY'
                    elif ftype.endswith('source'):
                        ftype = 'SOURCE'
                    elif ftype.endswith('other'):
                        ftype = 'OTHER'
                    elif ftype.endswith('archive'):
                        ftype = 'ARCHIVE'
                    self.builder.set_file_type(self.doc, ftype)
                except SPDXValueError:
                    self.value_error('FILE_TYPE', ftype)
        except CardinalityError:
            self.more_than_one_error('file type')

def
p_file_type
(
self
,
f_term
,
predicate
)
:
try
:
for
_
,
_
,
ftype
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
try
:
if
ftype
.
endswith
(
'binary'
)
:
ftype
=
'BINARY'
elif
ftype
.
endswith
(
'source'
)
:
ftype
=
'SOURCE'
elif
ftype
.
endswith
(
'other'
)
:
ftype
=
'OTHER'
elif
ftype
.
endswith
(
'archive'
)
:
ftype
=
'ARCHIVE'
self
.
builder
.
set_file_type
(
self
.
doc
,
ftype
)
except
SPDXValueError
:
self
.
value_error
(
'FILE_TYPE'
,
ftype
)
except
CardinalityError
:
self
.
more_than_one_error
(
'file type'
)


def p_file_chk_sum(self, f_term, predicate):
        """Sets file checksum. Assumes SHA1 algorithm without checking."""
        try:
            for _s, _p, checksum in self.graph.triples((f_term, predicate, None)):
                for _, _, value in self.graph.triples((checksum, self.spdx_namespace['checksumValue'], None)):
                    self.builder.set_file_chksum(self.doc, six.text_type(value))
        except CardinalityError:
            self.more_than_one_error('File checksum')

def
p_file_chk_sum
(
self
,
f_term
,
predicate
)
:
try
:
for
_s
,
_p
,
checksum
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
for
_
,
_
,
value
in
self
.
graph
.
triples
(
(
checksum
,
self
.
spdx_namespace
[
'checksumValue'
]
,
)
)
:
self
.
builder
.
set_file_chksum
(
self
.
doc
,
six
.
text_type
(
value
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'File checksum'
)

Sets file checksum . Assumes SHA1 algorithm without checking .


def p_file_lic_conc(self, f_term, predicate):
        """Sets file licenses concluded."""
        try:
            for _, _, licenses in self.graph.triples((f_term, predicate, None)):
                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_conjunctive_list(licenses)
                    self.builder.set_concluded_license(self.doc, lics)

                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_disjunctive_list(licenses)
                    self.builder.set_concluded_license(self.doc, lics)

                else:
                    try:
                        lics = self.handle_lics(licenses)
                        self.builder.set_concluded_license(self.doc, lics)
                    except SPDXValueError:
                        self.value_error('FILE_SINGLE_LICS', licenses)
        except CardinalityError:
            self.more_than_one_error('file {0}'.format(predicate))

def
p_file_lic_conc
(
self
,
f_term
,
predicate
)
:
try
:
for
_
,
_
,
licenses
in
self
.
graph
.
triples
(
(
f_term
,
predicate
,
)
)
:
if
(
licenses
,
RDF
.
type
,
self
.
spdx_namespace
[
'ConjunctiveLicenseSet'
]
)
in
self
.
graph
:
lics
=
self
.
handle_conjunctive_list
(
licenses
)
self
.
builder
.
set_concluded_license
(
self
.
doc
,
lics
)
elif
(
licenses
,
RDF
.
type
,
self
.
spdx_namespace
[
'DisjunctiveLicenseSet'
]
)
in
self
.
graph
:
lics
=
self
.
handle_disjunctive_list
(
licenses
)
self
.
builder
.
set_concluded_license
(
self
.
doc
,
lics
)
else
:
try
:
lics
=
self
.
handle_lics
(
licenses
)
self
.
builder
.
set_concluded_license
(
self
.
doc
,
lics
)
except
SPDXValueError
:
self
.
value_error
(
'FILE_SINGLE_LICS'
,
licenses
)
except
CardinalityError
:
self
.
more_than_one_error
(
'file {0}'
.
format
(
predicate
)
)


def get_review_date(self, r_term):
        """Returns review date or None if not found.
        Reports error on failure.
        Note does not check value format.
        """
        reviewed_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewDate'], None)))
        if len(reviewed_list) != 1:
            self.error = True
            msg = 'Review must have exactlyone review date'
            self.logger.log(msg)
            return
        return six.text_type(reviewed_list[0][2])

Returns review date or None if not found . Reports error on failure . Note does not check value format .


def get_reviewer(self, r_term):
        """Returns reviewer as creator object or None if failed.
        Reports errors on failure.
        """
        reviewer_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewer'], None)))
        if len(reviewer_list) != 1:
            self.error = True
            msg = 'Review must have exactly one reviewer'
            self.logger.log(msg)
            return
        try:
            return self.builder.create_entity(self.doc, six.text_type(reviewer_list[0][2]))
        except SPDXValueError:
            self.value_error('REVIEWER_VALUE', reviewer_list[0][2])

def
get_reviewer
(
self
,
r_term
)
:
reviewer_list
=
list
(
self
.
graph
.
triples
(
(
r_term
,
self
.
spdx_namespace
[
'reviewer'
]
,
)
)
)
if
len
(
reviewer_list
)
!=
1
:
self
.
error
=
True
msg
=
'Review must have exactly one reviewer'
self
.
logger
.
log
(
msg
)
return
try
:
return
self
.
builder
.
create_entity
(
self
.
doc
,
six
.
text_type
(
reviewer_list
[
0
]
[
2
]
)
)
except
SPDXValueError
:
self
.
value_error
(
'REVIEWER_VALUE'
,
reviewer_list
[
0
]
[
2
]
)

Returns reviewer as creator object or None if failed . Reports errors on failure .


def get_annotation_type(self, r_term):
        """Returns annotation type or None if found none or more than one.
        Reports errors on failure."""
        for _, _, typ in self.graph.triples((
                r_term, self.spdx_namespace['annotationType'], None)):
            if typ is not None:
                return typ
            else:
                self.error = True
                msg = 'Annotation must have exactly one annotation type.'
                self.logger.log(msg)
                return

Returns annotation type or None if found none or more than one . Reports errors on failure .


def get_annotation_comment(self, r_term):
        """Returns annotation comment or None if found none or more than one.
        Reports errors.
        """
        comment_list = list(self.graph.triples((r_term, RDFS.comment, None)))
        if len(comment_list) > 1:
            self.error = True
            msg = 'Annotation can have at most one comment.'
            self.logger.log(msg)
            return
        else:
            return six.text_type(comment_list[0][2])

Returns annotation comment or None if found none or more than one . Reports errors .


def get_annotation_date(self, r_term):
        """Returns annotation date or None if not found.
        Reports error on failure.
        Note does not check value format.
        """
        annotation_date_list = list(self.graph.triples((r_term, self.spdx_namespace['annotationDate'], None)))
        if len(annotation_date_list) != 1:
            self.error = True
            msg = 'Annotation must have exactly one annotation date.'
            self.logger.log(msg)
            return
        return six.text_type(annotation_date_list[0][2])

Returns annotation date or None if not found . Reports error on failure . Note does not check value format .


def parse(self, fil):
        """Parses a file and returns a document object.
        File, a file like object.
        """
        self.error = False
        self.graph = Graph()
        self.graph.parse(file=fil, format='xml')
        self.doc = document.Document()

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['SpdxDocument'])):
            self.parse_doc_fields(s)

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['ExternalDocumentRef'])):
            self.parse_ext_doc_ref(s)

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['CreationInfo'])):
            self.parse_creation_info(s)

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['Package'])):
            self.parse_package(s)

        for s, _p, o in self.graph.triples((None, self.spdx_namespace['referencesFile'], None)):
            self.parse_file(o)

        for s, _p, o in self.graph.triples((None, self.spdx_namespace['reviewed'], None)):
            self.parse_review(o)

        for s, _p, o in self.graph.triples((None, self.spdx_namespace['annotation'], None)):
            self.parse_annotation(o)

        validation_messages = []
        # Report extra errors if self.error is False otherwise there will be
        # redundent messages
        validation_messages = self.doc.validate(validation_messages)
        if not self.error:
            if validation_messages:
                for msg in validation_messages:
                    self.logger.log(msg)
                self.error = True
        return self.doc, self.error

Parses a file and returns a document object . File a file like object .


def parse_creation_info(self, ci_term):
        """
        Parse creators, created and comment.
        """
        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None)):
            try:
                ent = self.builder.create_entity(self.doc, six.text_type(o))
                self.builder.add_creator(self.doc, ent)
            except SPDXValueError:
                self.value_error('CREATOR_VALUE', o)

        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['created'], None)):
            try:
                self.builder.set_created_date(self.doc, six.text_type(o))
            except SPDXValueError:
                self.value_error('CREATED_VALUE', o)
            except CardinalityError:
                self.more_than_one_error('created')
                break

        for _s, _p, o in self.graph.triples((ci_term, RDFS.comment, None)):
            try:
                self.builder.set_creation_comment(self.doc, six.text_type(o))
            except CardinalityError:
                self.more_than_one_error('CreationInfo comment')
                break
        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['licenseListVersion'], None)):
            try:
                self.builder.set_lics_list_ver(self.doc, six.text_type(o))
            except CardinalityError:
                self.more_than_one_error('licenseListVersion')
                break
            except SPDXValueError:
                self.value_error('LL_VALUE', o)

def
parse_creation_info
(
self
,
ci_term
)
:
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
ci_term
,
self
.
spdx_namespace
[
'creator'
]
,
)
)
:
try
:
ent
=
self
.
builder
.
create_entity
(
self
.
doc
,
six
.
text_type
(
o
)
)
self
.
builder
.
add_creator
(
self
.
doc
,
ent
)
except
SPDXValueError
:
self
.
value_error
(
'CREATOR_VALUE'
,
o
)
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
ci_term
,
self
.
spdx_namespace
[
'created'
]
,
)
)
:
try
:
self
.
builder
.
set_created_date
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
SPDXValueError
:
self
.
value_error
(
'CREATED_VALUE'
,
o
)
except
CardinalityError
:
self
.
more_than_one_error
(
'created'
)
break
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
ci_term
,
RDFS
.
comment
,
)
)
:
try
:
self
.
builder
.
set_creation_comment
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'CreationInfo comment'
)
break
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
ci_term
,
self
.
spdx_namespace
[
'licenseListVersion'
]
,
)
)
:
try
:
self
.
builder
.
set_lics_list_ver
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'licenseListVersion'
)
break
except
SPDXValueError
:
self
.
value_error
(
'LL_VALUE'
,
o
)


def parse_doc_fields(self, doc_term):
        """Parses the version, data license, name, SPDX Identifier, namespace,
        and comment."""
        try:
            self.builder.set_doc_spdx_id(self.doc, doc_term)
        except SPDXValueError:
            self.value_error('DOC_SPDX_ID_VALUE', doc_term)
        try:
            if doc_term.count('#', 0, len(doc_term)) <= 1:
                doc_namespace = doc_term.split('#')[0]
                self.builder.set_doc_namespace(self.doc, doc_namespace)
            else:
                self.value_error('DOC_NAMESPACE_VALUE', doc_term)
        except SPDXValueError:
            self.value_error('DOC_NAMESPACE_VALUE', doc_term)
        for _s, _p, o in self.graph.triples((doc_term, self.spdx_namespace['specVersion'], None)):
            try:
                self.builder.set_doc_version(self.doc, six.text_type(o))
            except SPDXValueError:
                self.value_error('DOC_VERS_VALUE', o)
            except CardinalityError:
                self.more_than_one_error('specVersion')
                break
        for _s, _p, o in self.graph.triples((doc_term, self.spdx_namespace['dataLicense'], None)):
            try:
                self.builder.set_doc_data_lic(self.doc, six.text_type(o))
            except SPDXValueError:
                self.value_error('DOC_D_LICS', o)
            except CardinalityError:
                self.more_than_one_error('dataLicense')
                break
        for _s, _p, o in self.graph.triples(
                (doc_term, self.spdx_namespace['name'], None)):
            try:
                self.builder.set_doc_name(self.doc, six.text_type(o))
            except CardinalityError:
                self.more_than_one_error('name')
                break
        for _s, _p, o in self.graph.triples((doc_term, RDFS.comment, None)):
            try:
                self.builder.set_doc_comment(self.doc, six.text_type(o))
            except CardinalityError:
                self.more_than_one_error('Document comment')
                break

def
parse_doc_fields
(
self
,
doc_term
)
:
try
:
self
.
builder
.
set_doc_spdx_id
(
self
.
doc
,
doc_term
)
except
SPDXValueError
:
self
.
value_error
(
'DOC_SPDX_ID_VALUE'
,
doc_term
)
try
:
if
doc_term
.
count
(
'#'
,
0
,
len
(
doc_term
)
)
<=
1
:
doc_namespace
=
doc_term
.
split
(
'#'
)
[
0
]
self
.
builder
.
set_doc_namespace
(
self
.
doc
,
doc_namespace
)
else
:
self
.
value_error
(
'DOC_NAMESPACE_VALUE'
,
doc_term
)
except
SPDXValueError
:
self
.
value_error
(
'DOC_NAMESPACE_VALUE'
,
doc_term
)
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
doc_term
,
self
.
spdx_namespace
[
'specVersion'
]
,
)
)
:
try
:
self
.
builder
.
set_doc_version
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
SPDXValueError
:
self
.
value_error
(
'DOC_VERS_VALUE'
,
o
)
except
CardinalityError
:
self
.
more_than_one_error
(
'specVersion'
)
break
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
doc_term
,
self
.
spdx_namespace
[
'dataLicense'
]
,
)
)
:
try
:
self
.
builder
.
set_doc_data_lic
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
SPDXValueError
:
self
.
value_error
(
'DOC_D_LICS'
,
o
)
except
CardinalityError
:
self
.
more_than_one_error
(
'dataLicense'
)
break
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
doc_term
,
self
.
spdx_namespace
[
'name'
]
,
)
)
:
try
:
self
.
builder
.
set_doc_name
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'name'
)
break
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
doc_term
,
RDFS
.
comment
,
)
)
:
try
:
self
.
builder
.
set_doc_comment
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
CardinalityError
:
self
.
more_than_one_error
(
'Document comment'
)
break

Parses the version data license name SPDX Identifier namespace and comment .


def parse_ext_doc_ref(self, ext_doc_ref_term):
        """
        Parses the External Document ID, SPDX Document URI and Checksum.
        """
        for _s, _p, o in self.graph.triples(
                (ext_doc_ref_term,
                 self.spdx_namespace['externalDocumentId'],
                 None)):
            try:
                self.builder.set_ext_doc_id(self.doc, six.text_type(o))
            except SPDXValueError:
                self.value_error('EXT_DOC_REF_VALUE', 'External Document ID')
                break

        for _s, _p, o in self.graph.triples(
                (ext_doc_ref_term,
                 self.spdx_namespace['spdxDocument'],
                 None)):
            try:
                self.builder.set_spdx_doc_uri(self.doc, six.text_type(o))
            except SPDXValueError:
                self.value_error('EXT_DOC_REF_VALUE', 'SPDX Document URI')
                break

        for _s, _p, checksum in self.graph.triples(
                (ext_doc_ref_term, self.spdx_namespace['checksum'], None)):
            for _, _, value in self.graph.triples(
                    (checksum, self.spdx_namespace['checksumValue'], None)):
                try:
                    self.builder.set_chksum(self.doc, six.text_type(value))
                except SPDXValueError:
                    self.value_error('EXT_DOC_REF_VALUE', 'Checksum')
                    break

def
parse_ext_doc_ref
(
self
,
ext_doc_ref_term
)
:
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
ext_doc_ref_term
,
self
.
spdx_namespace
[
'externalDocumentId'
]
,
)
)
:
try
:
self
.
builder
.
set_ext_doc_id
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
SPDXValueError
:
self
.
value_error
(
'EXT_DOC_REF_VALUE'
,
'External Document ID'
)
break
for
_s
,
_p
,
o
in
self
.
graph
.
triples
(
(
ext_doc_ref_term
,
self
.
spdx_namespace
[
'spdxDocument'
]
,
)
)
:
try
:
self
.
builder
.
set_spdx_doc_uri
(
self
.
doc
,
six
.
text_type
(
o
)
)
except
SPDXValueError
:
self
.
value_error
(
'EXT_DOC_REF_VALUE'
,
'SPDX Document URI'
)
break
for
_s
,
_p
,
checksum
in
self
.
graph
.
triples
(
(
ext_doc_ref_term
,
self
.
spdx_namespace
[
'checksum'
]
,
)
)
:
for
_
,
_
,
value
in
self
.
graph
.
triples
(
(
checksum
,
self
.
spdx_namespace
[
'checksumValue'
]
,
)
)
:
try
:
self
.
builder
.
set_chksum
(
self
.
doc
,
six
.
text_type
(
value
)
)
except
SPDXValueError
:
self
.
value_error
(
'EXT_DOC_REF_VALUE'
,
'Checksum'
)
break

Parses the External Document ID SPDX Document URI and Checksum .


def validate(self, messages):
        """
        Validate the package fields.
        Append user friendly error messages to the `messages` list.
        """
        messages = self.validate_checksum(messages)
        messages = self.validate_optional_str_fields(messages)
        messages = self.validate_mandatory_str_fields(messages)
        messages = self.validate_files(messages)
        messages = self.validate_mandatory_fields(messages)
        messages = self.validate_optional_fields(messages)

        return messages

def validate ( self , messages ) : messages = self . validate_checksum ( messages ) messages = self . validate_optional_str_fields ( messages ) messages = self . validate_mandatory_str_fields ( messages ) messages = self . validate_files ( messages ) messages = self . validate_mandatory_fields ( messages ) messages = self . validate_optional_fields ( messages ) return messages

Validate the package fields . Append user friendly error messages to the messages list .


def validate_str_fields(self, fields, optional, messages):
        """Helper for validate_mandatory_str_field and
        validate_optional_str_fields"""
        for field_str in fields:
            field = getattr(self, field_str)
            if field is not None:
                # FIXME: this does not make sense???
                attr = getattr(field, '__str__', None)
                if not callable(attr):
                    messages = messages + [
                        '{0} must provide __str__ method.'.format(field)
                    ]
                    # Continue checking.
            elif not optional:
                messages = messages + [
                    'Package {0} can not be None.'.format(field_str)
                ]

        return messages

def
validate_str_fields
(
self
,
fields
,
optional
,
messages
)
:
for
field_str
in
fields
:
field
=
getattr
(
self
,
field_str
)
if
field
is
not
:
# FIXME: this does not make sense???
attr
=
getattr
(
field
,
'__str__'
,
)
if
not
callable
(
attr
)
:
messages
=
messages
+
[
'{0} must provide __str__ method.'
.
format
(
field
)
]
# Continue checking.
elif
not
optional
:
messages
=
messages
+
[
'Package {0} can not be None.'
.
format
(
field_str
)
]
return
messages


def set_doc_comment(self, doc, comment):
        """Sets document comment, Raises CardinalityError if
        comment already set.
        """
        if not self.doc_comment_set:
            self.doc_comment_set = True
            doc.comment = comment
        else:
            raise CardinalityError('Document::Comment')

def set_doc_comment ( self , doc , comment ) : if not self . doc_comment_set : self . doc_comment_set = True doc . comment = comment else : raise CardinalityError ( 'Document::Comment' )

Sets document comment Raises CardinalityError if comment already set .


def set_chksum(self, doc, chk_sum):
        """
        Sets the external document reference's check sum, if not already set.
        chk_sum - The checksum value in the form of a string.
        """
        if chk_sum:
            doc.ext_document_references[-1].check_sum = checksum.Algorithm(
                'SHA1', chk_sum)
        else:
            raise SPDXValueError('ExternalDocumentRef::Checksum')

def set_chksum ( self , doc , chk_sum ) : if chk_sum : doc . ext_document_references [ - 1 ] . check_sum = checksum . Algorithm ( 'SHA1' , chk_sum ) else : raise SPDXValueError ( 'ExternalDocumentRef::Checksum' )

Sets the external document reference s check sum if not already set . chk_sum - The checksum value in the form of a string .