From a9c5b67455662c2338041ee05dcf781696b271e8 Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 11:17:06 -0700 Subject: [PATCH 01/31] feat: add huey for async task processing https://huey.readthedocs.io/ the huey consumer runs as a runit daemon in the server service the default dev mode behavior of immediate=False (tasks run synchronously) is currently disabled for testing purposes --- django/Dockerfile | 7 ++++--- django/core/huey.py | 13 +++++++++++++ django/core/settings/defaults.py | 17 +++++++++++++++-- django/core/settings/staging.py | 5 +++++ django/deploy/huey.sh | 2 ++ django/library/tasks.py | 11 +++++++++++ django/requirements.txt | 2 ++ 7 files changed, 52 insertions(+), 5 deletions(-) create mode 100644 django/core/huey.py create mode 100755 django/deploy/huey.sh create mode 100644 django/library/tasks.py diff --git a/django/Dockerfile b/django/Dockerfile index c78ac5ec5..ba2a1b372 100644 --- a/django/Dockerfile +++ b/django/Dockerfile @@ -43,9 +43,9 @@ RUN --mount=type=cache,target=/var/lib/apt,sharing=locked \ && update-alternatives --install /usr/bin/python python /usr/bin/python3 1000 \ && python -m venv ${VIRTUAL_ENV} \ && apt-get upgrade -q -y -o Dpkg::Options::="--force-confold" \ - && mkdir -p /etc/service/django \ - && touch /etc/service/django/run /etc/postgresql-backup-pre \ - && chmod a+x /etc/service/django/run /etc/postgresql-backup-pre \ + && mkdir -p /etc/service/django /etc/service/huey \ + && touch /etc/service/django/run /etc/service/huey/run /etc/postgresql-backup-pre \ + && chmod a+x /etc/service/django/run /etc/service/huey/run /etc/postgresql-backup-pre \ && apt-get autoremove -y && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* WORKDIR /code @@ -61,5 +61,6 @@ COPY ./deploy/cron.weekly/* /etc/cron.weekly/ COPY ./deploy/db/autopostgresqlbackup.conf /etc/default/autopostgresqlbackup COPY ./deploy/db/postgresql-backup-pre /etc/ COPY ${RUN_SCRIPT} /etc/service/django/run +COPY ./deploy/huey.sh /etc/service/huey/run COPY . /code CMD ["/sbin/my_init"] diff --git a/django/core/huey.py b/django/core/huey.py new file mode 100644 index 000000000..a6c4d8769 --- /dev/null +++ b/django/core/huey.py @@ -0,0 +1,13 @@ +from django_redis import get_redis_connection +from huey import RedisHuey + + +class DjangoRedisHuey(RedisHuey): + """Huey subclass that uses the existing connection pool + from the django-redis cache backend + """ + + def __init__(self, *args, **kwargs): + connection = get_redis_connection("default") + kwargs["connection_pool"] = connection.connection_pool + super().__init__(*args, **kwargs) diff --git a/django/core/settings/defaults.py b/django/core/settings/defaults.py index d509b3994..8302bcaa4 100644 --- a/django/core/settings/defaults.py +++ b/django/core/settings/defaults.py @@ -118,6 +118,7 @@ def is_test(self): "django_extensions", "django_vite", "guardian", + "huey.contrib.djhuey", "rest_framework", "rest_framework_swagger", "robots", @@ -396,6 +397,11 @@ def is_test(self): "handlers": ["console", "comsesfile"], "propagate": False, }, + "huey": { + "level": "INFO", + "handlers": ["console", "comsesfile"], + "propagate": False, + }, }, } @@ -479,10 +485,19 @@ def is_test(self): "LOCATION": "unix:///shared/redis/redis.sock", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", + "CONNECTION_POOL_KWARGS": {"max_connections": 20}, }, } } +HUEY = { + "name": "comses", + "huey_class": "core.huey.DjangoRedisHuey", + "immediate": False, # always run tasks in the background (for now), if removed it will default to DEBUG + # FIXME: this should generally be True in development, the huey consumer WILL NOT + # automatically reload when the code changes when False +} + # SSO, user registration, and django-allauth configuration, see # https://django-allauth.readthedocs.io/en/latest/configuration.html # ACCOUNT_ADAPTER = 'core.adapter.AccountAdapter' @@ -501,9 +516,7 @@ def is_test(self): ACCOUNT_CHANGE_EMAIL = True ORCID_CLIENT_ID = os.getenv("ORCID_CLIENT_ID", "") - ORCID_CLIENT_SECRET = read_secret("orcid_client_secret") - GITHUB_CLIENT_ID = os.getenv("GITHUB_CLIENT_ID", "") GITHUB_CLIENT_SECRET = read_secret("github_client_secret") diff --git a/django/core/settings/staging.py b/django/core/settings/staging.py index 9821e5557..74332965c 100644 --- a/django/core/settings/staging.py +++ b/django/core/settings/staging.py @@ -181,5 +181,10 @@ "handlers": ["comsesfile"], "propagate": False, }, + "huey": { + "level": "WARNING", + "handlers": ["comsesfile"], + "propagate": False, + }, }, } diff --git a/django/deploy/huey.sh b/django/deploy/huey.sh new file mode 100755 index 000000000..ee3d365a2 --- /dev/null +++ b/django/deploy/huey.sh @@ -0,0 +1,2 @@ +#!/bin/bash +exec /code/manage.py run_huey diff --git a/django/library/tasks.py b/django/library/tasks.py new file mode 100644 index 000000000..6de220501 --- /dev/null +++ b/django/library/tasks.py @@ -0,0 +1,11 @@ +from huey.contrib.djhuey import db_task + + +import logging + +logger = logging.getLogger(__name__) + + +@db_task(retries=3, retry_delay=30) +def example_task(): + pass diff --git a/django/requirements.txt b/django/requirements.txt index 5511d1272..3791b3dde 100644 --- a/django/requirements.txt +++ b/django/requirements.txt @@ -28,6 +28,7 @@ Django==4.2.17 elasticsearch-dsl>=7.0.0,<8.0.0 elasticsearch>=7.0.0,<8.0.0 html2text>=2016.9.19 +huey==2.5.1 jinja2==3.1.5 jsonschema==4.23.0 jwt==1.3.1 # needed for allauth @@ -37,6 +38,7 @@ numpy==1.26.4 pandas==2.2.2 psycopg2-binary==2.9.10 pytz==2024.1 +pyyaml>=6.0.1 # used for institution -> affiliation data migration rapidfuzz==3.9.3 rarfile==4.2 From f5233a639a780d230f7c1fc2ceb2055bf9a79764 Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 11:19:28 -0700 Subject: [PATCH 02/31] build: dynamically add vue apps to vite config adding these manually was an easily forgotten step that wouldn't be noticed in dev but would fail to build in prod --- frontend/vite.config.ts | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index d04f60146..5a5b55477 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,11 +1,26 @@ import { defineConfig } from "vite"; import vue from "@vitejs/plugin-vue"; +import fs from "fs"; const { resolve } = require("path"); const resolvePath = (relativePath: string) => { return resolve(__dirname, relativePath); }; +const getAppEntries = () => { + const appsDir = resolvePath("./src/apps"); + const entries: { [key: string]: string } = {}; + + fs.readdirSync(appsDir).forEach(file => { + if (file.endsWith(".ts")) { + const name = file.replace(".ts", ""); + entries[name] = resolvePath(`./src/apps/${file}`); + } + }); + + return entries; +}; + export default defineConfig({ plugins: [vue()], root: resolvePath("./src"), @@ -34,26 +49,7 @@ export default defineConfig({ manifest: true, rollupOptions: { external: [/holder\.js.*/], - input: { - main: resolvePath("./src/apps/main.ts"), - codebase_list: resolvePath("./src/apps/codebase_list.ts"), - codebase_edit: resolvePath("./src/apps/codebase_edit.ts"), - event_calendar: resolvePath("./src/apps/event_calendar.ts"), - event_list: resolvePath("./src/apps/event_list.ts"), - event_edit: resolvePath("./src/apps/event_edit.ts"), - image_gallery: resolvePath("./src/apps/image_gallery.ts"), - job_list: resolvePath("./src/apps/job_list.ts"), - job_edit: resolvePath("./src/apps/job_edit.ts"), - metrics: resolvePath("./src/apps/metrics.ts"), - profile_list: resolvePath("./src/apps/profile_list.ts"), - profile_edit: resolvePath("./src/apps/profile_edit.ts"), - release_editor: resolvePath("./src/apps/release_editor.ts"), - release_download: resolvePath("./src/apps/release_download.ts"), - release_regenerate_share_uuid: resolvePath("./src/apps/release_regenerate_share_uuid.ts"), - review_editor: resolvePath("./src/apps/review_editor.ts"), - review_reminders: resolvePath("./src/apps/review_reminders.ts"), - reviewer_list: resolvePath("./src/apps/reviewer_list.ts"), - }, + input: getAppEntries(), }, }, /* From 4dc1e7f5c455b8131c8253aa81729bf2a5bb9ee7 Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 12:01:39 -0700 Subject: [PATCH 03/31] feat: add codemeta_snapshot field and license text codemeta_snapshot will be used to keep a codemeta data structure updated along with changes to metadata, which makes it easier to watch for changes and speeds up access license text is created from a template for each release and included in the fs package as LICENSE file ref comses/planning#234 --- django/library/fs.py | 22 +++++-- .../0032_license_text_codemeta_snapshot.py | 61 +++++++++++++++++++ django/library/models.py | 29 ++++++++- 3 files changed, 105 insertions(+), 7 deletions(-) create mode 100644 django/library/migrations/0032_license_text_codemeta_snapshot.py diff --git a/django/library/fs.py b/django/library/fs.py index f3352e581..0e032532b 100644 --- a/django/library/fs.py +++ b/django/library/fs.py @@ -360,11 +360,11 @@ def __init__( system_file_presence_message_level=MessageLevels.error, mimetype_mismatch_message_level=MessageLevels.error, ): + self.release = codebase_release self.uuid = str(codebase_release.codebase.uuid) self.identifier = codebase_release.codebase.identifier self.version_number = codebase_release.version_number self.release_id = codebase_release.id - self.codemeta = codebase_release.codemeta self.bagit_info = codebase_release.bagit_info self.mimetype_mismatch_message_level = mimetype_mismatch_message_level @@ -409,6 +409,10 @@ def sip_dir(self): def codemeta_path(self): return self.sip_contents_dir.joinpath("codemeta.json") + @property + def license_path(self): + return self.sip_contents_dir.joinpath("LICENSE") + @property def sip_contents_dir(self): return self.sip_dir.joinpath("data") @@ -511,8 +515,6 @@ def initialize( def create_or_update_codemeta(self, force=False): """ Returns True if a codemeta.json file was created, False otherwise - :param metadata: an optional dictionary with codemeta properties - :return: """ path = self.codemeta_path if force or not path.exists(): @@ -521,20 +523,30 @@ def create_or_update_codemeta(self, force=False): return True return False - def get_codemeta_json(self): - return self.codemeta.to_json() + def create_or_update_license(self, force=False): + """ + Returns True if a LICENSE file was created, False otherwise + """ + path = self.license_path + if self.release.license and (force or not path.exists()): + with path.open(mode="w", encoding="utf-8") as license_out: + license_out.write(self.release.license_text) + return True + return False def build_published_archive(self, force=False): """ FIXME: some of this should be moved to an async processing task. """ self.create_or_update_codemeta(force=force) + self.create_or_update_license(force=force) bag = self.get_or_create_sip_bag(self.bagit_info) self.validate_bagit(bag) self.build_archive(force=force) def build_review_archive(self): self.create_or_update_codemeta(force=True) + self.create_or_update_license(force=True) shutil.make_archive( str(self.review_archivepath.with_suffix("")), format="zip", diff --git a/django/library/migrations/0032_license_text_codemeta_snapshot.py b/django/library/migrations/0032_license_text_codemeta_snapshot.py new file mode 100644 index 000000000..f6e0a067a --- /dev/null +++ b/django/library/migrations/0032_license_text_codemeta_snapshot.py @@ -0,0 +1,61 @@ +# Generated by Django 4.2.14 on 2024-08-01 18:22 + +from django.db import migrations, models + + +def add_default_text(apps, schema_editor): + License = apps.get_model("library", "License") + license_text = { + "CC-BY-4.0": 'Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation ("Creative Commons") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an "as-is" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n Considerations for licensors: Our public licenses are\n intended for use by those authorized to give the public\n permission to use material in ways otherwise restricted by\n copyright and certain other rights. Our licenses are\n irrevocable. Licensors should read and understand the terms\n and conditions of the license they choose before applying it.\n Licensors should also secure all rights necessary before\n applying our licenses so that the public can reuse the\n material as expected. Licensors should clearly mark any\n material not subject to the license. This includes other CC-\n licensed material, or material used under an exception or\n limitation to copyright. More considerations for licensors:\n wiki.creativecommons.org/Considerations_for_licensors\n\n Considerations for the public: By using one of our public\n licenses, a licensor grants the public permission to use the\n licensed material under specified terms and conditions. If\n the licensor\'s permission is not necessary for any reason--for\n example, because of any applicable exception or limitation to\n copyright--then that use is not regulated by the license. Our\n licenses grant only permissions under copyright and certain\n other rights that a licensor has authority to grant. Use of\n the licensed material may still be restricted for other\n reasons, including because others have copyright or other\n rights in the material. A licensor may make special requests,\n such as asking that all changes be marked or described.\n Although not required by our licenses, you are encouraged to\n respect those requests where reasonable. More considerations\n for the public:\n wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License ("Public License"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n a. Adapted Material means material subject to Copyright and Similar\n Rights that is derived from or based upon the Licensed Material\n and in which the Licensed Material is translated, altered,\n arranged, transformed, or otherwise modified in a manner requiring\n permission under the Copyright and Similar Rights held by the\n Licensor. For purposes of this Public License, where the Licensed\n Material is a musical work, performance, or sound recording,\n Adapted Material is always produced where the Licensed Material is\n synched in timed relation with a moving image.\n\n b. Adapter\'s License means the license You apply to Your Copyright\n and Similar Rights in Your contributions to Adapted Material in\n accordance with the terms and conditions of this Public License.\n\n c. Copyright and Similar Rights means copyright and/or similar rights\n closely related to copyright including, without limitation,\n performance, broadcast, sound recording, and Sui Generis Database\n Rights, without regard to how the rights are labeled or\n categorized. For purposes of this Public License, the rights\n specified in Section 2(b)(1)-(2) are not Copyright and Similar\n Rights.\n\n d. Effective Technological Measures means those measures that, in the\n absence of proper authority, may not be circumvented under laws\n fulfilling obligations under Article 11 of the WIPO Copyright\n Treaty adopted on December 20, 1996, and/or similar international\n agreements.\n\n e. Exceptions and Limitations means fair use, fair dealing, and/or\n any other exception or limitation to Copyright and Similar Rights\n that applies to Your use of the Licensed Material.\n\n f. Licensed Material means the artistic or literary work, database,\n or other material to which the Licensor applied this Public\n License.\n\n g. Licensed Rights means the rights granted to You subject to the\n terms and conditions of this Public License, which are limited to\n all Copyright and Similar Rights that apply to Your use of the\n Licensed Material and that the Licensor has authority to license.\n\n h. Licensor means the individual(s) or entity(ies) granting rights\n under this Public License.\n\n i. Share means to provide material to the public by any means or\n process that requires permission under the Licensed Rights, such\n as reproduction, public display, public performance, distribution,\n dissemination, communication, or importation, and to make material\n available to the public including in ways that members of the\n public may access the material from a place and at a time\n individually chosen by them.\n\n j. Sui Generis Database Rights means rights other than copyright\n resulting from Directive 96/9/EC of the European Parliament and of\n the Council of 11 March 1996 on the legal protection of databases,\n as amended and/or succeeded, as well as other essentially\n equivalent rights anywhere in the world.\n\n k. You means the individual or entity exercising the Licensed Rights\n under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n a. License grant.\n\n 1. Subject to the terms and conditions of this Public License,\n the Licensor hereby grants You a worldwide, royalty-free,\n non-sublicensable, non-exclusive, irrevocable license to\n exercise the Licensed Rights in the Licensed Material to:\n\n a. reproduce and Share the Licensed Material, in whole or\n in part; and\n\n b. produce, reproduce, and Share Adapted Material.\n\n 2. Exceptions and Limitations. For the avoidance of doubt, where\n Exceptions and Limitations apply to Your use, this Public\n License does not apply, and You do not need to comply with\n its terms and conditions.\n\n 3. Term. The term of this Public License is specified in Section\n 6(a).\n\n 4. Media and formats; technical modifications allowed. The\n Licensor authorizes You to exercise the Licensed Rights in\n all media and formats whether now known or hereafter created,\n and to make technical modifications necessary to do so. The\n Licensor waives and/or agrees not to assert any right or\n authority to forbid You from making technical modifications\n necessary to exercise the Licensed Rights, including\n technical modifications necessary to circumvent Effective\n Technological Measures. For purposes of this Public License,\n simply making modifications authorized by this Section 2(a)\n (4) never produces Adapted Material.\n\n 5. Downstream recipients.\n\n a. Offer from the Licensor -- Licensed Material. Every\n recipient of the Licensed Material automatically\n receives an offer from the Licensor to exercise the\n Licensed Rights under the terms and conditions of this\n Public License.\n\n b. No downstream restrictions. You may not offer or impose\n any additional or different terms or conditions on, or\n apply any Effective Technological Measures to, the\n Licensed Material if doing so restricts exercise of the\n Licensed Rights by any recipient of the Licensed\n Material.\n\n 6. No endorsement. Nothing in this Public License constitutes or\n may be construed as permission to assert or imply that You\n are, or that Your use of the Licensed Material is, connected\n with, or sponsored, endorsed, or granted official status by,\n the Licensor or others designated to receive attribution as\n provided in Section 3(a)(1)(A)(i).\n\n b. Other rights.\n\n 1. Moral rights, such as the right of integrity, are not\n licensed under this Public License, nor are publicity,\n privacy, and/or other similar personality rights; however, to\n the extent possible, the Licensor waives and/or agrees not to\n assert any such rights held by the Licensor to the limited\n extent necessary to allow You to exercise the Licensed\n Rights, but not otherwise.\n\n 2. Patent and trademark rights are not licensed under this\n Public License.\n\n 3. To the extent possible, the Licensor waives any right to\n collect royalties from You for the exercise of the Licensed\n Rights, whether directly or through a collecting society\n under any voluntary or waivable statutory or compulsory\n licensing scheme. In all other cases the Licensor expressly\n reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n a. Attribution.\n\n 1. If You Share the Licensed Material (including in modified\n form), You must:\n\n a. retain the following if it is supplied by the Licensor\n with the Licensed Material:\n\n i. identification of the creator(s) of the Licensed\n Material and any others designated to receive\n attribution, in any reasonable manner requested by\n the Licensor (including by pseudonym if\n designated);\n\n ii. a copyright notice;\n\n iii. a notice that refers to this Public License;\n\n iv. a notice that refers to the disclaimer of\n warranties;\n\n v. a URI or hyperlink to the Licensed Material to the\n extent reasonably practicable;\n\n b. indicate if You modified the Licensed Material and\n retain an indication of any previous modifications; and\n\n c. indicate the Licensed Material is licensed under this\n Public License, and include the text of, or the URI or\n hyperlink to, this Public License.\n\n 2. You may satisfy the conditions in Section 3(a)(1) in any\n reasonable manner based on the medium, means, and context in\n which You Share the Licensed Material. For example, it may be\n reasonable to satisfy the conditions by providing a URI or\n hyperlink to a resource that includes the required\n information.\n\n 3. If requested by the Licensor, You must remove any of the\n information required by Section 3(a)(1)(A) to the extent\n reasonably practicable.\n\n 4. If You Share Adapted Material You produce, the Adapter\'s\n License You apply must not prevent recipients of the Adapted\n Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n to extract, reuse, reproduce, and Share all or a substantial\n portion of the contents of the database;\n\n b. if You include all or a substantial portion of the database\n contents in a database in which You have Sui Generis Database\n Rights, then the database in which You have Sui Generis Database\n Rights (but not its individual contents) is Adapted Material; and\n\n c. You must comply with the conditions in Section 3(a) if You Share\n all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n c. The disclaimer of warranties and limitation of liability provided\n above shall be interpreted in a manner that, to the extent\n possible, most closely approximates an absolute disclaimer and\n waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n a. This Public License applies for the term of the Copyright and\n Similar Rights licensed here. However, if You fail to comply with\n this Public License, then Your rights under this Public License\n terminate automatically.\n\n b. Where Your right to use the Licensed Material has terminated under\n Section 6(a), it reinstates:\n\n 1. automatically as of the date the violation is cured, provided\n it is cured within 30 days of Your discovery of the\n violation; or\n\n 2. upon express reinstatement by the Licensor.\n\n For the avoidance of doubt, this Section 6(b) does not affect any\n right the Licensor may have to seek remedies for Your violations\n of this Public License.\n\n c. For the avoidance of doubt, the Licensor may also offer the\n Licensed Material under separate terms or conditions or stop\n distributing the Licensed Material at any time; however, doing so\n will not terminate this Public License.\n\n d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n a. The Licensor shall not be bound by any additional or different\n terms or conditions communicated by You unless expressly agreed.\n\n b. Any arrangements, understandings, or agreements regarding the\n Licensed Material not stated herein are separate from and\n independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n a. For the avoidance of doubt, this Public License does not, and\n shall not be interpreted to, reduce, limit, restrict, or impose\n conditions on any use of the Licensed Material that could lawfully\n be made without permission under this Public License.\n\n b. To the extent possible, if any provision of this Public License is\n deemed unenforceable, it shall be automatically reformed to the\n minimum extent necessary to make it enforceable. If the provision\n cannot be reformed, it shall be severed from this Public License\n without affecting the enforceability of the remaining terms and\n conditions.\n\n c. No term or condition of this Public License will be waived and no\n failure to comply consented to unless expressly agreed to by the\n Licensor.\n\n d. Nothing in this Public License constitutes or may be interpreted\n as a limitation upon, or waiver of, any privileges and immunities\n that apply to the Licensor or You, including from the legal\n processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public licenses.\nNotwithstanding, Creative Commons may elect to apply one of its public\nlicenses to material it publishes and in those instances will be\nconsidered the “Licensor.” The text of the Creative Commons public\nlicenses is dedicated to the public domain under the CC0 Public Domain\nDedication. Except for the limited purpose of indicating that material\nis shared under a Creative Commons public license or as otherwise\npermitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark "Creative Commons" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the public\nlicenses.\n\nCreative Commons may be contacted at creativecommons.org.\n', + "CC-BY-SA-4.0": 'Attribution-ShareAlike 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation ("Creative Commons") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an "as-is" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n Considerations for licensors: Our public licenses are\n intended for use by those authorized to give the public\n permission to use material in ways otherwise restricted by\n copyright and certain other rights. Our licenses are\n irrevocable. Licensors should read and understand the terms\n and conditions of the license they choose before applying it.\n Licensors should also secure all rights necessary before\n applying our licenses so that the public can reuse the\n material as expected. Licensors should clearly mark any\n material not subject to the license. This includes other CC-\n licensed material, or material used under an exception or\n limitation to copyright. More considerations for licensors:\n wiki.creativecommons.org/Considerations_for_licensors\n\n Considerations for the public: By using one of our public\n licenses, a licensor grants the public permission to use the\n licensed material under specified terms and conditions. If\n the licensor\'s permission is not necessary for any reason--for\n example, because of any applicable exception or limitation to\n copyright--then that use is not regulated by the license. Our\n licenses grant only permissions under copyright and certain\n other rights that a licensor has authority to grant. Use of\n the licensed material may still be restricted for other\n reasons, including because others have copyright or other\n rights in the material. A licensor may make special requests,\n such as asking that all changes be marked or described.\n Although not required by our licenses, you are encouraged to\n respect those requests where reasonable. More considerations\n for the public:\n wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution-ShareAlike 4.0 International Public\nLicense\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution-ShareAlike 4.0 International Public License ("Public\nLicense"). To the extent this Public License may be interpreted as a\ncontract, You are granted the Licensed Rights in consideration of Your\nacceptance of these terms and conditions, and the Licensor grants You\nsuch rights in consideration of benefits the Licensor receives from\nmaking the Licensed Material available under these terms and\nconditions.\n\n\nSection 1 -- Definitions.\n\n a. Adapted Material means material subject to Copyright and Similar\n Rights that is derived from or based upon the Licensed Material\n and in which the Licensed Material is translated, altered,\n arranged, transformed, or otherwise modified in a manner requiring\n permission under the Copyright and Similar Rights held by the\n Licensor. For purposes of this Public License, where the Licensed\n Material is a musical work, performance, or sound recording,\n Adapted Material is always produced where the Licensed Material is\n synched in timed relation with a moving image.\n\n b. Adapter\'s License means the license You apply to Your Copyright\n and Similar Rights in Your contributions to Adapted Material in\n accordance with the terms and conditions of this Public License.\n\n c. BY-SA Compatible License means a license listed at\n creativecommons.org/compatiblelicenses, approved by Creative\n Commons as essentially the equivalent of this Public License.\n\n d. Copyright and Similar Rights means copyright and/or similar rights\n closely related to copyright including, without limitation,\n performance, broadcast, sound recording, and Sui Generis Database\n Rights, without regard to how the rights are labeled or\n categorized. For purposes of this Public License, the rights\n specified in Section 2(b)(1)-(2) are not Copyright and Similar\n Rights.\n\n e. Effective Technological Measures means those measures that, in the\n absence of proper authority, may not be circumvented under laws\n fulfilling obligations under Article 11 of the WIPO Copyright\n Treaty adopted on December 20, 1996, and/or similar international\n agreements.\n\n f. Exceptions and Limitations means fair use, fair dealing, and/or\n any other exception or limitation to Copyright and Similar Rights\n that applies to Your use of the Licensed Material.\n\n g. License Elements means the license attributes listed in the name\n of a Creative Commons Public License. The License Elements of this\n Public License are Attribution and ShareAlike.\n\n h. Licensed Material means the artistic or literary work, database,\n or other material to which the Licensor applied this Public\n License.\n\n i. Licensed Rights means the rights granted to You subject to the\n terms and conditions of this Public License, which are limited to\n all Copyright and Similar Rights that apply to Your use of the\n Licensed Material and that the Licensor has authority to license.\n\n j. Licensor means the individual(s) or entity(ies) granting rights\n under this Public License.\n\n k. Share means to provide material to the public by any means or\n process that requires permission under the Licensed Rights, such\n as reproduction, public display, public performance, distribution,\n dissemination, communication, or importation, and to make material\n available to the public including in ways that members of the\n public may access the material from a place and at a time\n individually chosen by them.\n\n l. Sui Generis Database Rights means rights other than copyright\n resulting from Directive 96/9/EC of the European Parliament and of\n the Council of 11 March 1996 on the legal protection of databases,\n as amended and/or succeeded, as well as other essentially\n equivalent rights anywhere in the world.\n\n m. You means the individual or entity exercising the Licensed Rights\n under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n a. License grant.\n\n 1. Subject to the terms and conditions of this Public License,\n the Licensor hereby grants You a worldwide, royalty-free,\n non-sublicensable, non-exclusive, irrevocable license to\n exercise the Licensed Rights in the Licensed Material to:\n\n a. reproduce and Share the Licensed Material, in whole or\n in part; and\n\n b. produce, reproduce, and Share Adapted Material.\n\n 2. Exceptions and Limitations. For the avoidance of doubt, where\n Exceptions and Limitations apply to Your use, this Public\n License does not apply, and You do not need to comply with\n its terms and conditions.\n\n 3. Term. The term of this Public License is specified in Section\n 6(a).\n\n 4. Media and formats; technical modifications allowed. The\n Licensor authorizes You to exercise the Licensed Rights in\n all media and formats whether now known or hereafter created,\n and to make technical modifications necessary to do so. The\n Licensor waives and/or agrees not to assert any right or\n authority to forbid You from making technical modifications\n necessary to exercise the Licensed Rights, including\n technical modifications necessary to circumvent Effective\n Technological Measures. For purposes of this Public License,\n simply making modifications authorized by this Section 2(a)\n (4) never produces Adapted Material.\n\n 5. Downstream recipients.\n\n a. Offer from the Licensor -- Licensed Material. Every\n recipient of the Licensed Material automatically\n receives an offer from the Licensor to exercise the\n Licensed Rights under the terms and conditions of this\n Public License.\n\n b. Additional offer from the Licensor -- Adapted Material.\n Every recipient of Adapted Material from You\n automatically receives an offer from the Licensor to\n exercise the Licensed Rights in the Adapted Material\n under the conditions of the Adapter\'s License You apply.\n\n c. No downstream restrictions. You may not offer or impose\n any additional or different terms or conditions on, or\n apply any Effective Technological Measures to, the\n Licensed Material if doing so restricts exercise of the\n Licensed Rights by any recipient of the Licensed\n Material.\n\n 6. No endorsement. Nothing in this Public License constitutes or\n may be construed as permission to assert or imply that You\n are, or that Your use of the Licensed Material is, connected\n with, or sponsored, endorsed, or granted official status by,\n the Licensor or others designated to receive attribution as\n provided in Section 3(a)(1)(A)(i).\n\n b. Other rights.\n\n 1. Moral rights, such as the right of integrity, are not\n licensed under this Public License, nor are publicity,\n privacy, and/or other similar personality rights; however, to\n the extent possible, the Licensor waives and/or agrees not to\n assert any such rights held by the Licensor to the limited\n extent necessary to allow You to exercise the Licensed\n Rights, but not otherwise.\n\n 2. Patent and trademark rights are not licensed under this\n Public License.\n\n 3. To the extent possible, the Licensor waives any right to\n collect royalties from You for the exercise of the Licensed\n Rights, whether directly or through a collecting society\n under any voluntary or waivable statutory or compulsory\n licensing scheme. In all other cases the Licensor expressly\n reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n a. Attribution.\n\n 1. If You Share the Licensed Material (including in modified\n form), You must:\n\n a. retain the following if it is supplied by the Licensor\n with the Licensed Material:\n\n i. identification of the creator(s) of the Licensed\n Material and any others designated to receive\n attribution, in any reasonable manner requested by\n the Licensor (including by pseudonym if\n designated);\n\n ii. a copyright notice;\n\n iii. a notice that refers to this Public License;\n\n iv. a notice that refers to the disclaimer of\n warranties;\n\n v. a URI or hyperlink to the Licensed Material to the\n extent reasonably practicable;\n\n b. indicate if You modified the Licensed Material and\n retain an indication of any previous modifications; and\n\n c. indicate the Licensed Material is licensed under this\n Public License, and include the text of, or the URI or\n hyperlink to, this Public License.\n\n 2. You may satisfy the conditions in Section 3(a)(1) in any\n reasonable manner based on the medium, means, and context in\n which You Share the Licensed Material. For example, it may be\n reasonable to satisfy the conditions by providing a URI or\n hyperlink to a resource that includes the required\n information.\n\n 3. If requested by the Licensor, You must remove any of the\n information required by Section 3(a)(1)(A) to the extent\n reasonably practicable.\n\n b. ShareAlike.\n\n In addition to the conditions in Section 3(a), if You Share\n Adapted Material You produce, the following conditions also apply.\n\n 1. The Adapter\'s License You apply must be a Creative Commons\n license with the same License Elements, this version or\n later, or a BY-SA Compatible License.\n\n 2. You must include the text of, or the URI or hyperlink to, the\n Adapter\'s License You apply. You may satisfy this condition\n in any reasonable manner based on the medium, means, and\n context in which You Share Adapted Material.\n\n 3. You may not offer or impose any additional or different terms\n or conditions on, or apply any Effective Technological\n Measures to, Adapted Material that restrict exercise of the\n rights granted under the Adapter\'s License You apply.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n to extract, reuse, reproduce, and Share all or a substantial\n portion of the contents of the database;\n\n b. if You include all or a substantial portion of the database\n contents in a database in which You have Sui Generis Database\n Rights, then the database in which You have Sui Generis Database\n Rights (but not its individual contents) is Adapted Material,\n including for purposes of Section 3(b); and\n\n c. You must comply with the conditions in Section 3(a) if You Share\n all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n c. The disclaimer of warranties and limitation of liability provided\n above shall be interpreted in a manner that, to the extent\n possible, most closely approximates an absolute disclaimer and\n waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n a. This Public License applies for the term of the Copyright and\n Similar Rights licensed here. However, if You fail to comply with\n this Public License, then Your rights under this Public License\n terminate automatically.\n\n b. Where Your right to use the Licensed Material has terminated under\n Section 6(a), it reinstates:\n\n 1. automatically as of the date the violation is cured, provided\n it is cured within 30 days of Your discovery of the\n violation; or\n\n 2. upon express reinstatement by the Licensor.\n\n For the avoidance of doubt, this Section 6(b) does not affect any\n right the Licensor may have to seek remedies for Your violations\n of this Public License.\n\n c. For the avoidance of doubt, the Licensor may also offer the\n Licensed Material under separate terms or conditions or stop\n distributing the Licensed Material at any time; however, doing so\n will not terminate this Public License.\n\n d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n a. The Licensor shall not be bound by any additional or different\n terms or conditions communicated by You unless expressly agreed.\n\n b. Any arrangements, understandings, or agreements regarding the\n Licensed Material not stated herein are separate from and\n independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n a. For the avoidance of doubt, this Public License does not, and\n shall not be interpreted to, reduce, limit, restrict, or impose\n conditions on any use of the Licensed Material that could lawfully\n be made without permission under this Public License.\n\n b. To the extent possible, if any provision of this Public License is\n deemed unenforceable, it shall be automatically reformed to the\n minimum extent necessary to make it enforceable. If the provision\n cannot be reformed, it shall be severed from this Public License\n without affecting the enforceability of the remaining terms and\n conditions.\n\n c. No term or condition of this Public License will be waived and no\n failure to comply consented to unless expressly agreed to by the\n Licensor.\n\n d. Nothing in this Public License constitutes or may be interpreted\n as a limitation upon, or waiver of, any privileges and immunities\n that apply to the Licensor or You, including from the legal\n processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public licenses.\nNotwithstanding, Creative Commons may elect to apply one of its public\nlicenses to material it publishes and in those instances will be\nconsidered the “Licensor.” The text of the Creative Commons public\nlicenses is dedicated to the public domain under the CC0 Public Domain\nDedication. Except for the limited purpose of indicating that material\nis shared under a Creative Commons public license or as otherwise\npermitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark "Creative Commons" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the public\nlicenses.\n\nCreative Commons may be contacted at creativecommons.org.\n', + "GPL-2.0": ' GNU GENERAL PUBLIC LICENSE\n Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The licenses for most software are designed to take away your\nfreedom to share and change it. By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users. This\nGeneral Public License applies to most of the Free Software\nFoundation\'s software and to any other program whose authors commit to\nusing it. (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.) You can apply it to\nyour programs, too.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have. You must make sure that they, too, receive or can get the\nsource code. And you must show them these terms so they know their\nrights.\n\n We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n Also, for each author\'s protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware. If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors\' reputations.\n\n Finally, any free program is threatened constantly by software\npatents. We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary. To prevent this, we have made it clear that any\npatent must be licensed for everyone\'s free use or not licensed at all.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n GNU GENERAL PUBLIC LICENSE\n TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n 0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License. The "Program", below,\nrefers to any such program or work, and a "work based on the Program"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage. (Hereinafter, translation is included without limitation in\nthe term "modification".) Each licensee is addressed as "you".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope. The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n 1. You may copy and distribute verbatim copies of the Program\'s\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n 2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n a) You must cause the modified files to carry prominent notices\n stating that you changed the files and the date of any change.\n\n b) You must cause any work that you distribute or publish, that in\n whole or in part contains or is derived from the Program or any\n part thereof, to be licensed as a whole at no charge to all third\n parties under the terms of this License.\n\n c) If the modified program normally reads commands interactively\n when run, you must cause it, when started running for such\n interactive use in the most ordinary way, to print or display an\n announcement including an appropriate copyright notice and a\n notice that there is no warranty (or else, saying that you provide\n a warranty) and that users may redistribute the program under\n these conditions, and telling the user how to view a copy of this\n License. (Exception: if the Program itself is interactive but\n does not normally print such an announcement, your work based on\n the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole. If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works. But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n 3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n a) Accompany it with the complete corresponding machine-readable\n source code, which must be distributed under the terms of Sections\n 1 and 2 above on a medium customarily used for software interchange; or,\n\n b) Accompany it with a written offer, valid for at least three\n years, to give any third party, for a charge no more than your\n cost of physically performing source distribution, a complete\n machine-readable copy of the corresponding source code, to be\n distributed under the terms of Sections 1 and 2 above on a medium\n customarily used for software interchange; or,\n\n c) Accompany it with the information you received as to the offer\n to distribute corresponding source code. (This alternative is\n allowed only for noncommercial distribution and only if you\n received the program in object code or executable form with such\n an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it. For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable. However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n 4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License. Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n 5. You are not required to accept this License, since you have not\nsigned it. However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works. These actions are\nprohibited by law if you do not accept this License. Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n 6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions. You may not impose any further\nrestrictions on the recipients\' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n 7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all. For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices. Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n 8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded. In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n 9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time. Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number. If the Program\nspecifies a version number of this License which applies to it and "any\nlater version", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation. If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n 10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission. For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this. Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n NO WARRANTY\n\n 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n END OF TERMS AND CONDITIONS\n\n How to Apply These Terms to Your New Programs\n\n If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n To do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe "copyright" line and a pointer to where the full notice is found.\n\n \n Copyright (C) \n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n Gnomovision version 69, Copyright (C) year name of author\n Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.\n This is free software, and you are welcome to redistribute it\n under certain conditions; type `show c\' for details.\n\nThe hypothetical commands `show w\' and `show c\' should show the appropriate\nparts of the General Public License. Of course, the commands you use may\nbe called something other than `show w\' and `show c\'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a "copyright disclaimer" for the program, if\nnecessary. Here is a sample; alter the names:\n\n Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n `Gnomovision\' (which makes passes at compilers) written by James Hacker.\n\n , 1 April 1989\n Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs. If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary. If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n', + "GPL-3.0": ' GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users. We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors. You can apply it to\nyour programs, too.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\n Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n For the developers\' and authors\' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users\' and\nauthors\' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so. This is fundamentally incompatible with the aim of\nprotecting users\' freedom to change the software. The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts. If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary. To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n "This License" refers to version 3 of the GNU General Public License.\n\n "Copyright" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n "The Program" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as "you". "Licensees" and\n"recipients" may be individuals or organizations.\n\n To "modify" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a "modified version" of the\nearlier work or a work "based on" the earlier work.\n\n A "covered work" means either the unmodified Program or a work based\non the Program.\n\n To "propagate" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To "convey" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n An interactive user interface displays "Appropriate Legal Notices"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n 1. Source Code.\n\n The "source code" for a work means the preferred form of the work\nfor making modifications to it. "Object code" means any non-source\nform of a work.\n\n A "Standard Interface" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n The "System Libraries" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n"Major Component", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n The "Corresponding Source" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work\'s\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n The Corresponding Source for a work in source code form is that\nsame work.\n\n 2. Basic Permissions.\n\n All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n Conveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n 3. Protecting Users\' Legal Rights From Anti-Circumvention Law.\n\n No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work\'s\nusers, your or third parties\' legal rights to forbid circumvention of\ntechnological measures.\n\n 4. Conveying Verbatim Copies.\n\n You may convey verbatim copies of the Program\'s source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n 5. Conveying Modified Source Versions.\n\n You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n a) The work must carry prominent notices stating that you modified\n it, and giving a relevant date.\n\n b) The work must carry prominent notices stating that it is\n released under this License and any conditions added under section\n 7. This requirement modifies the requirement in section 4 to\n "keep intact all notices".\n\n c) You must license the entire work, as a whole, under this\n License to anyone who comes into possession of a copy. This\n License will therefore apply, along with any applicable section 7\n additional terms, to the whole of the work, and all its parts,\n regardless of how they are packaged. This License gives no\n permission to license the work in any other way, but it does not\n invalidate such permission if you have separately received it.\n\n d) If the work has interactive user interfaces, each must display\n Appropriate Legal Notices; however, if the Program has interactive\n interfaces that do not display Appropriate Legal Notices, your\n work need not make them do so.\n\n A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n"aggregate" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation\'s users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n 6. Conveying Non-Source Forms.\n\n You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n a) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by the\n Corresponding Source fixed on a durable physical medium\n customarily used for software interchange.\n\n b) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by a\n written offer, valid for at least three years and valid for as\n long as you offer spare parts or customer support for that product\n model, to give anyone who possesses the object code either (1) a\n copy of the Corresponding Source for all the software in the\n product that is covered by this License, on a durable physical\n medium customarily used for software interchange, for a price no\n more than your reasonable cost of physically performing this\n conveying of source, or (2) access to copy the\n Corresponding Source from a network server at no charge.\n\n c) Convey individual copies of the object code with a copy of the\n written offer to provide the Corresponding Source. This\n alternative is allowed only occasionally and noncommercially, and\n only if you received the object code with such an offer, in accord\n with subsection 6b.\n\n d) Convey the object code by offering access from a designated\n place (gratis or for a charge), and offer equivalent access to the\n Corresponding Source in the same way through the same place at no\n further charge. You need not require recipients to copy the\n Corresponding Source along with the object code. If the place to\n copy the object code is a network server, the Corresponding Source\n may be on a different server (operated by you or a third party)\n that supports equivalent copying facilities, provided you maintain\n clear directions next to the object code saying where to find the\n Corresponding Source. Regardless of what server hosts the\n Corresponding Source, you remain obligated to ensure that it is\n available for as long as needed to satisfy these requirements.\n\n e) Convey the object code using peer-to-peer transmission, provided\n you inform other peers where the object code and Corresponding\n Source of the work are being offered to the general public at no\n charge under subsection 6d.\n\n A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n A "User Product" is either (1) a "consumer product", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, "normally used" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n "Installation Information" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n 7. Additional Terms.\n\n "Additional permissions" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n a) Disclaiming warranty or limiting liability differently from the\n terms of sections 15 and 16 of this License; or\n\n b) Requiring preservation of specified reasonable legal notices or\n author attributions in that material or in the Appropriate Legal\n Notices displayed by works containing it; or\n\n c) Prohibiting misrepresentation of the origin of that material, or\n requiring that modified versions of such material be marked in\n reasonable ways as different from the original version; or\n\n d) Limiting the use for publicity purposes of names of licensors or\n authors of the material; or\n\n e) Declining to grant rights under trademark law for use of some\n trade names, trademarks, or service marks; or\n\n f) Requiring indemnification of licensors and authors of that\n material by anyone who conveys the material (or modified versions of\n it) with contractual assumptions of liability to the recipient, for\n any liability that these contractual assumptions directly impose on\n those licensors and authors.\n\n All other non-permissive additional terms are considered "further\nrestrictions" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n 8. Termination.\n\n You may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n 9. Acceptance Not Required for Having Copies.\n\n You are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n 10. Automatic Licensing of Downstream Recipients.\n\n Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\n An "entity transaction" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party\'s predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n 11. Patents.\n\n A "contributor" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor\'s "contributor version".\n\n A contributor\'s "essential patent claims" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, "control" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor\'s essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n In the following three paragraphs, a "patent license" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To "grant" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. "Knowingly relying" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient\'s use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n A patent license is "discriminatory" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n 12. No Surrender of Others\' Freedom.\n\n If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n 13. Use with the GNU Affero General Public License.\n\n Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n 14. Revised Versions of this License.\n\n The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time. Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n Each version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License "or any later version" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy\'s\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n Later license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n 15. Disclaimer of Warranty.\n\n THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n 16. Limitation of Liability.\n\n IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n 17. Interpretation of Sections 15 and 16.\n\n If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n END OF TERMS AND CONDITIONS\n\n How to Apply These Terms to Your New Programs\n\n If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n To do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe "copyright" line and a pointer to where the full notice is found.\n\n \n Copyright (C) \n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n\nAlso add information on how to contact you by electronic and paper mail.\n\n If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n Copyright (C) \n This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.\n This is free software, and you are welcome to redistribute it\n under certain conditions; type `show c\' for details.\n\nThe hypothetical commands `show w\' and `show c\' should show the appropriate\nparts of the General Public License. Of course, your program\'s commands\nmight be different; for a GUI interface, you would use an "about box".\n\n You should also get your employer (if you work as a programmer) or school,\nif any, to sign a "copyright disclaimer" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n.\n\n The GNU General Public License does not permit incorporating your program\ninto proprietary programs. If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library. If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License. But first, please read\n.\n', + "CC-BY-NC-4.0": "Creative Commons Attribution-NonCommercial 4.0 International\n\n Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.\n\nConsiderations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.\n\nConsiderations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.\n\nCreative Commons Attribution-NonCommercial 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License (\"Public License\"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.\n\nSection 1 – Definitions.\n\n a.\tAdapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.\n\n b.\tAdapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.\n\n c.\tCopyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.\n\n d.\tEffective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.\n\n e.\tExceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.\n\n f.\tLicensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.\n\n g.\tLicensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.\n\n h.\tLicensor means the individual(s) or entity(ies) granting rights under this Public License.\n\n i.\tNonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.\n\n j.\tShare means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.\n\n k.\tSui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.\n\n l.\tYou means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.\n\nSection 2 – Scope.\n\n a.\tLicense grant.\n\n 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:\n\n A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and\n\n B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.\n\n 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.\n\n 3. Term. The term of this Public License is specified in Section 6(a).\n\n 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.\n\n 5. Downstream recipients.\n\n A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.\n\n B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.\n\n 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).\n\n b.\tOther rights.\n\n 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.\n\n 2. Patent and trademark rights are not licensed under this Public License.\n\n 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.\n\nSection 3 – License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the following conditions.\n\n a.\tAttribution.\n\n 1. If You Share the Licensed Material (including in modified form), You must:\n\n A. retain the following if it is supplied by the Licensor with the Licensed Material:\n\n i.\tidentification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);\n\n ii.\ta copyright notice;\n\n iii. a notice that refers to this Public License;\n\n iv.\ta notice that refers to the disclaimer of warranties;\n\n v.\ta URI or hyperlink to the Licensed Material to the extent reasonably practicable;\n\n B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and\n\n C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.\n\n 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.\n\n 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.\n\n 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.\n\nSection 4 – Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:\n\n a.\tfor the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;\n\n b.\tif You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and\n\n c.\tYou must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.\nFor the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.\n\nSection 5 – Disclaimer of Warranties and Limitation of Liability.\n\n a.\tUnless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.\n\n b.\tTo the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.\n\n c.\tThe disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.\n\nSection 6 – Term and Termination.\n\n a.\tThis Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.\n\n b.\tWhere Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:\n\n 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or\n\n 2. upon express reinstatement by the Licensor.\n\n For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.\n\n c.\tFor the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.\n\n d.\tSections 1, 5, 6, 7, and 8 survive termination of this Public License.\n\nSection 7 – Other Terms and Conditions.\n\n a.\tThe Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.\n\n b.\tAny arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.\n\nSection 8 – Interpretation.\n\n a.\tFor the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.\n\n b.\tTo the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.\n\n c.\tNo term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.\n\n d.\tNothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.\n\nCreative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n", + "CC-BY-NC-SA-4.0": "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International\n\n Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.\n\nConsiderations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.\n\nConsiderations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.\n\nCreative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License (\"Public License\"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.\n\nSection 1 – Definitions.\n\n a.\tAdapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.\n\n b.\tAdapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.\n\n c.\tBY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.\n\n d.\tCopyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.\n\n e.\tEffective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.\n\n f.\tExceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.\n\n g.\tLicense Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.\n\n h.\tLicensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.\n\n i.\tLicensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.\n\n j.\tLicensor means the individual(s) or entity(ies) granting rights under this Public License.\n\n k.\tNonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.\n\n l.\tShare means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.\n\n m.\tSui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.\n\n n.\tYou means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.\n\nSection 2 – Scope.\n\n a.\tLicense grant.\n\n 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:\n\n A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and\n\n B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.\n\n 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.\n\n 3. Term. The term of this Public License is specified in Section 6(a).\n\n 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.\n\n 5. Downstream recipients.\n\n A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.\n\n B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.\n\n C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.\n\n 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).\n\n b.\tOther rights.\n\n 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.\n\n 2. Patent and trademark rights are not licensed under this Public License.\n\n 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.\n\nSection 3 – License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the following conditions.\n\n a.\tAttribution.\n\n 1. If You Share the Licensed Material (including in modified form), You must:\n\n A. retain the following if it is supplied by the Licensor with the Licensed Material:\n\n i.\tidentification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);\n\n ii.\ta copyright notice;\n\n iii. a notice that refers to this Public License;\n\n iv.\ta notice that refers to the disclaimer of warranties;\n\n v.\ta URI or hyperlink to the Licensed Material to the extent reasonably practicable;\n\n B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and\n\n C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.\n\n 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.\n\n 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.\n\n b.\tShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.\n\n 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.\n\n 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.\n\n 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.\n\nSection 4 – Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:\n\n a.\tfor the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;\n\n b.\tif You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and\n\n c.\tYou must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.\nFor the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.\n\nSection 5 – Disclaimer of Warranties and Limitation of Liability.\n\n a.\tUnless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.\n\n b.\tTo the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.\n\n c.\tThe disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.\n\nSection 6 – Term and Termination.\n\n a.\tThis Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.\n\n b.\tWhere Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:\n\n 1.\tautomatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or\n\n 2.\tupon express reinstatement by the Licensor.\n\n For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.\n\n c.\tFor the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.\n\n d.\tSections 1, 5, 6, 7, and 8 survive termination of this Public License.\n\nSection 7 – Other Terms and Conditions.\n\n a.\tThe Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.\n\n b.\tAny arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.\n\nSection 8 – Interpretation.\n\n a.\tFor the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.\n\n b.\tTo the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.\n\n c.\tNo term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.\n\n d.\tNothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.\n\nCreative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n", + "CC-BY-NC-ND-4.0": 'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International\n\n Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.\n\nConsiderations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.\n\nConsiderations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.\n\nCreative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.\n\nSection 1 – Definitions.\n\n a.\tAdapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.\n\n b.\tCopyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.\n\n c.\tEffective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.\n\n d.\tExceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.\n\n e.\tLicensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.\n\n f.\tLicensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.\n\n g.\tLicensor means the individual(s) or entity(ies) granting rights under this Public License.\n\n h.\tNonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.\n\n i.\tShare means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.\n\n j.\tSui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.\n\n k.\tYou means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.\n\nSection 2 – Scope.\n\n a.\tLicense grant.\n\n 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:\n\n A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and\n\n B. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.\n\n 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.\n\n 3. Term. The term of this Public License is specified in Section 6(a).\n\n 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.\n\n 5. Downstream recipients.\n A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.\n\n B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.\n\n 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).\n\n b.\tOther rights.\n\n 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.\n\n 2. Patent and trademark rights are not licensed under this Public License.\n\n 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.\n\nSection 3 – License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the following conditions.\n\n a.\tAttribution.\n\n 1. If You Share the Licensed Material, You must:\n\n A. retain the following if it is supplied by the Licensor with the Licensed Material:\n\n i.\tidentification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);\n\n ii.\ta copyright notice;\n\n iii. a notice that refers to this Public License;\n\n iv.\ta notice that refers to the disclaimer of warranties;\n\n v.\ta URI or hyperlink to the Licensed Material to the extent reasonably practicable;\n\n B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and\n\n C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.\n\n For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.\n\n 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.\n\n 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.\n\nSection 4 – Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:\n\n a.\tfor the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only and provided You do not Share Adapted Material;\n\n b.\tif You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and\n\n c.\tYou must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.\nFor the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.\n\nSection 5 – Disclaimer of Warranties and Limitation of Liability.\n\n a.\tUnless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.\n\n b.\tTo the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.\n\n c.\tThe disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.\n\nSection 6 – Term and Termination.\n\n a.\tThis Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.\n\n b.\tWhere Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:\n\n 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or\n\n 2. upon express reinstatement by the Licensor.\n\n For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.\n\n c.\tFor the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.\n\n d.\tSections 1, 5, 6, 7, and 8 survive termination of this Public License.\n\nSection 7 – Other Terms and Conditions.\n\n a.\tThe Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.\n\n b.\tAny arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.\n\nSection 8 – Interpretation.\n\n a.\tFor the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.\n\n b.\tTo the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.\n\n c.\tNo term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.\n\n d.\tNothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.\n\nCreative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n', + "Apache-2.0": ' Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n "License" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n "Licensor" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n "Legal Entity" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n "control" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n "You" (or "Your") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n "Source" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n "Object" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n "Work" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n "Derivative Works" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n "Contribution" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, "submitted"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as "Not a Contribution."\n\n "Contributor" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a "NOTICE" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an "AS IS" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n APPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets "[]"\n replaced with your own identifying information. (Don\'t include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same "printed page" as the copyright notice for easier\n identification within third-party archives.\n\n Copyright [yyyy] [name of copyright owner]\n\n Licensed under the Apache License, Version 2.0 (the "License");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an "AS IS" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n', + "MIT": 'MIT License\r\n\r\nCopyright (c) ${copyright_year} ${copyright_name}\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the "Software"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.', + "MPL-2.0": 'Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. "Contributor"\n means each individual or legal entity that creates, contributes to\n the creation of, or owns Covered Software.\n\n1.2. "Contributor Version"\n means the combination of the Contributions of others (if any) used\n by a Contributor and that particular Contributor\'s Contribution.\n\n1.3. "Contribution"\n means Covered Software of a particular Contributor.\n\n1.4. "Covered Software"\n means Source Code Form to which the initial Contributor has attached\n the notice in Exhibit A, the Executable Form of such Source Code\n Form, and Modifications of such Source Code Form, in each case\n including portions thereof.\n\n1.5. "Incompatible With Secondary Licenses"\n means\n\n (a) that the initial Contributor has attached the notice described\n in Exhibit B to the Covered Software; or\n\n (b) that the Covered Software was made available under the terms of\n version 1.1 or earlier of the License, but not also under the\n terms of a Secondary License.\n\n1.6. "Executable Form"\n means any form of the work other than Source Code Form.\n\n1.7. "Larger Work"\n means a work that combines Covered Software with other material, in\n a separate file or files, that is not Covered Software.\n\n1.8. "License"\n means this document.\n\n1.9. "Licensable"\n means having the right to grant, to the maximum extent possible,\n whether at the time of the initial grant or subsequently, any and\n all of the rights conveyed by this License.\n\n1.10. "Modifications"\n means any of the following:\n\n (a) any file in Source Code Form that results from an addition to,\n deletion from, or modification of the contents of Covered\n Software; or\n\n (b) any new file in Source Code Form that contains any Covered\n Software.\n\n1.11. "Patent Claims" of a Contributor\n means any patent claim(s), including without limitation, method,\n process, and apparatus claims, in any patent Licensable by such\n Contributor that would be infringed, but for the grant of the\n License, by the making, using, selling, offering for sale, having\n made, import, or transfer of either its Contributions or its\n Contributor Version.\n\n1.12. "Secondary License"\n means either the GNU General Public License, Version 2.0, the GNU\n Lesser General Public License, Version 2.1, the GNU Affero General\n Public License, Version 3.0, or any later versions of those\n licenses.\n\n1.13. "Source Code Form"\n means the form of the work preferred for making modifications.\n\n1.14. "You" (or "Your")\n means an individual or a legal entity exercising rights under this\n License. For legal entities, "You" includes any entity that\n controls, is controlled by, or is under common control with You. For\n purposes of this definition, "control" means (a) the power, direct\n or indirect, to cause the direction or management of such entity,\n whether by contract or otherwise, or (b) ownership of more than\n fifty percent (50%) of the outstanding shares or beneficial\n ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or\n as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n for sale, have made, import, and otherwise transfer either its\n Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n or\n\n(b) for infringements caused by: (i) Your and any other third party\'s\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients\' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n Form, as described in Section 3.1, and You must inform recipients of\n the Executable Form how they can obtain a copy of such Source Code\n Form by reasonable means in a timely manner, at a charge no more\n than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n License, or sublicense it under different terms, provided that the\n license for the Executable Form does not attempt to limit or alter\n the recipients\' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n* *\n* 6. Disclaimer of Warranty *\n* ------------------------- *\n* *\n* Covered Software is provided under this License on an "as is" *\n* basis, without warranty of any kind, either expressed, implied, or *\n* statutory, including, without limitation, warranties that the *\n* Covered Software is free of defects, merchantable, fit for a *\n* particular purpose or non-infringing. The entire risk as to the *\n* quality and performance of the Covered Software is with You. *\n* Should any Covered Software prove defective in any respect, You *\n* (not any Contributor) assume the cost of any necessary servicing, *\n* repair, or correction. This disclaimer of warranty constitutes an *\n* essential part of this License. No use of any Covered Software is *\n* authorized under this License except under this disclaimer. *\n* *\n************************************************************************\n\n************************************************************************\n* *\n* 7. Limitation of Liability *\n* -------------------------- *\n* *\n* Under no circumstances and under no legal theory, whether tort *\n* (including negligence), contract, or otherwise, shall any *\n* Contributor, or anyone who distributes Covered Software as *\n* permitted above, be liable to You for any direct, indirect, *\n* special, incidental, or consequential damages of any character *\n* including, without limitation, damages for lost profits, loss of *\n* goodwill, work stoppage, computer failure or malfunction, or any *\n* and all other commercial damages or losses, even if such party *\n* shall have been informed of the possibility of such damages. This *\n* limitation of liability shall not apply to liability for death or *\n* personal injury resulting from such party\'s negligence to the *\n* extent applicable law prohibits such limitation. Some *\n* jurisdictions do not allow the exclusion or limitation of *\n* incidental or consequential damages, so this exclusion and *\n* limitation may not apply to You. *\n* *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party\'s ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - "Incompatible With Secondary Licenses" Notice\n---------------------------------------------------------\n\n This Source Code Form is "Incompatible With Secondary Licenses", as\n defined by the Mozilla Public License, v. 2.0.\n', + "LGPL-3.0": ' GNU LESSER GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n\n This version of the GNU Lesser General Public License incorporates\nthe terms and conditions of version 3 of the GNU General Public\nLicense, supplemented by the additional permissions listed below.\n\n 0. Additional Definitions.\n\n As used herein, "this License" refers to version 3 of the GNU Lesser\nGeneral Public License, and the "GNU GPL" refers to version 3 of the GNU\nGeneral Public License.\n\n "The Library" refers to a covered work governed by this License,\nother than an Application or a Combined Work as defined below.\n\n An "Application" is any work that makes use of an interface provided\nby the Library, but which is not otherwise based on the Library.\nDefining a subclass of a class defined by the Library is deemed a mode\nof using an interface provided by the Library.\n\n A "Combined Work" is a work produced by combining or linking an\nApplication with the Library. The particular version of the Library\nwith which the Combined Work was made is also called the "Linked\nVersion".\n\n The "Minimal Corresponding Source" for a Combined Work means the\nCorresponding Source for the Combined Work, excluding any source code\nfor portions of the Combined Work that, considered in isolation, are\nbased on the Application, and not on the Linked Version.\n\n The "Corresponding Application Code" for a Combined Work means the\nobject code and/or source code for the Application, including any data\nand utility programs needed for reproducing the Combined Work from the\nApplication, but excluding the System Libraries of the Combined Work.\n\n 1. Exception to Section 3 of the GNU GPL.\n\n You may convey a covered work under sections 3 and 4 of this License\nwithout being bound by section 3 of the GNU GPL.\n\n 2. Conveying Modified Versions.\n\n If you modify a copy of the Library, and, in your modifications, a\nfacility refers to a function or data to be supplied by an Application\nthat uses the facility (other than as an argument passed when the\nfacility is invoked), then you may convey a copy of the modified\nversion:\n\n a) under this License, provided that you make a good faith effort to\n ensure that, in the event an Application does not supply the\n function or data, the facility still operates, and performs\n whatever part of its purpose remains meaningful, or\n\n b) under the GNU GPL, with none of the additional permissions of\n this License applicable to that copy.\n\n 3. Object Code Incorporating Material from Library Header Files.\n\n The object code form of an Application may incorporate material from\na header file that is part of the Library. You may convey such object\ncode under terms of your choice, provided that, if the incorporated\nmaterial is not limited to numerical parameters, data structure\nlayouts and accessors, or small macros, inline functions and templates\n(ten or fewer lines in length), you do both of the following:\n\n a) Give prominent notice with each copy of the object code that the\n Library is used in it and that the Library and its use are\n covered by this License.\n\n b) Accompany the object code with a copy of the GNU GPL and this license\n document.\n\n 4. Combined Works.\n\n You may convey a Combined Work under terms of your choice that,\ntaken together, effectively do not restrict modification of the\nportions of the Library contained in the Combined Work and reverse\nengineering for debugging such modifications, if you also do each of\nthe following:\n\n a) Give prominent notice with each copy of the Combined Work that\n the Library is used in it and that the Library and its use are\n covered by this License.\n\n b) Accompany the Combined Work with a copy of the GNU GPL and this license\n document.\n\n c) For a Combined Work that displays copyright notices during\n execution, include the copyright notice for the Library among\n these notices, as well as a reference directing the user to the\n copies of the GNU GPL and this license document.\n\n d) Do one of the following:\n\n 0) Convey the Minimal Corresponding Source under the terms of this\n License, and the Corresponding Application Code in a form\n suitable for, and under terms that permit, the user to\n recombine or relink the Application with a modified version of\n the Linked Version to produce a modified Combined Work, in the\n manner specified by section 6 of the GNU GPL for conveying\n Corresponding Source.\n\n 1) Use a suitable shared library mechanism for linking with the\n Library. A suitable mechanism is one that (a) uses at run time\n a copy of the Library already present on the user\'s computer\n system, and (b) will operate properly with a modified version\n of the Library that is interface-compatible with the Linked\n Version.\n\n e) Provide Installation Information, but only if you would otherwise\n be required to provide such information under section 6 of the\n GNU GPL, and only to the extent that such information is\n necessary to install and execute a modified version of the\n Combined Work produced by recombining or relinking the\n Application with a modified version of the Linked Version. (If\n you use option 4d0, the Installation Information must accompany\n the Minimal Corresponding Source and Corresponding Application\n Code. If you use option 4d1, you must provide the Installation\n Information in the manner specified by section 6 of the GNU GPL\n for conveying Corresponding Source.)\n\n 5. Combined Libraries.\n\n You may place library facilities that are a work based on the\nLibrary side by side in a single library together with other library\nfacilities that are not Applications and are not covered by this\nLicense, and convey such a combined library under terms of your\nchoice, if you do both of the following:\n\n a) Accompany the combined library with a copy of the same work based\n on the Library, uncombined with any other library facilities,\n conveyed under the terms of this License.\n\n b) Give prominent notice with the combined library that part of it\n is a work based on the Library, and explaining where to find the\n accompanying uncombined form of the same work.\n\n 6. Revised Versions of the GNU Lesser General Public License.\n\n The Free Software Foundation may publish revised and/or new versions\nof the GNU Lesser General Public License from time to time. Such new\nversions will be similar in spirit to the present version, but may\ndiffer in detail to address new problems or concerns.\n\n Each version is given a distinguishing version number. If the\nLibrary as you received it specifies that a certain numbered version\nof the GNU Lesser General Public License "or any later version"\napplies to it, you have the option of following the terms and\nconditions either of that published version or of any later version\npublished by the Free Software Foundation. If the Library as you\nreceived it does not specify a version number of the GNU Lesser\nGeneral Public License, you may choose any version of the GNU Lesser\nGeneral Public License ever published by the Free Software Foundation.\n\n If the Library as you received it specifies that a proxy can decide\nwhether future versions of the GNU Lesser General Public License shall\napply, that proxy\'s public statement of acceptance of any version is\npermanent authorization for you to choose that version for the\nLibrary.\n', + "AFL-3.0": 'Academic Free License ("AFL") v. 3.0\n\nThis Academic Free License (the "License") applies to any original work of\nauthorship (the "Original Work") whose owner (the "Licensor") has placed the\nfollowing licensing notice adjacent to the copyright notice for the Original\nWork:\n\n Licensed under the Academic Free License version 3.0\n\n1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free,\nnon-exclusive, sublicensable license, for the duration of the copyright, to do\nthe following:\n\n a) to reproduce the Original Work in copies, either alone or as part of a\n collective work;\n\n b) to translate, adapt, alter, transform, modify, or arrange the Original\n Work, thereby creating derivative works ("Derivative Works") based upon the\n Original Work;\n\n c) to distribute or communicate copies of the Original Work and Derivative\n Works to the public, under any license of your choice that does not\n contradict the terms and conditions, including Licensor\'s reserved rights\n and remedies, in this Academic Free License;\n\n d) to perform the Original Work publicly; and\n\n e) to display the Original Work publicly.\n\n2) Grant of Patent License. Licensor grants You a worldwide, royalty-free,\nnon-exclusive, sublicensable license, under patent claims owned or controlled\nby the Licensor that are embodied in the Original Work as furnished by the\nLicensor, for the duration of the patents, to make, use, sell, offer for sale,\nhave made, and import the Original Work and Derivative Works.\n\n3) Grant of Source Code License. The term "Source Code" means the preferred\nform of the Original Work for making modifications to it and all available\ndocumentation describing how to modify the Original Work. Licensor agrees to\nprovide a machine-readable copy of the Source Code of the Original Work along\nwith each copy of the Original Work that Licensor distributes. Licensor\nreserves the right to satisfy this obligation by placing a machine-readable\ncopy of the Source Code in an information repository reasonably calculated to\npermit inexpensive and convenient access by You for as long as Licensor\ncontinues to distribute the Original Work.\n\n4) Exclusions From License Grant. Neither the names of Licensor, nor the names\nof any contributors to the Original Work, nor any of their trademarks or\nservice marks, may be used to endorse or promote products derived from this\nOriginal Work without express prior permission of the Licensor. Except as\nexpressly stated herein, nothing in this License grants any license to\nLicensor\'s trademarks, copyrights, patents, trade secrets or any other\nintellectual property. No patent license is granted to make, use, sell, offer\nfor sale, have made, or import embodiments of any patent claims other than the\nlicensed claims defined in Section 2. No license is granted to the trademarks\nof Licensor even if such marks are included in the Original Work. Nothing in\nthis License shall be interpreted to prohibit Licensor from licensing under\nterms different from this License any Original Work that Licensor otherwise\nwould have a right to license.\n\n5) External Deployment. The term "External Deployment" means the use,\ndistribution, or communication of the Original Work or Derivative Works in any\nway such that the Original Work or Derivative Works may be used by anyone\nother than You, whether those works are distributed or communicated to those\npersons or made available as an application intended for use over a network.\nAs an express condition for the grants of license hereunder, You must treat\nany External Deployment by You of the Original Work or a Derivative Work as a\ndistribution under section 1(c).\n\n6) Attribution Rights. You must retain, in the Source Code of any Derivative\nWorks that You create, all copyright, patent, or trademark notices from the\nSource Code of the Original Work, as well as any notices of licensing and any\ndescriptive text identified therein as an "Attribution Notice." You must cause\nthe Source Code for any Derivative Works that You create to carry a prominent\nAttribution Notice reasonably calculated to inform recipients that You have\nmodified the Original Work.\n\n7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that\nthe copyright in and to the Original Work and the patent rights granted herein\nby Licensor are owned by the Licensor or are sublicensed to You under the\nterms of this License with the permission of the contributor(s) of those\ncopyrights and patent rights. Except as expressly stated in the immediately\npreceding sentence, the Original Work is provided under this License on an "AS\nIS" BASIS and WITHOUT WARRANTY, either express or implied, including, without\nlimitation, the warranties of non-infringement, merchantability or fitness for\na particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK\nIS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this\nLicense. No license to the Original Work is granted by this License except\nunder this disclaimer.\n\n8) Limitation of Liability. Under no circumstances and under no legal theory,\nwhether in tort (including negligence), contract, or otherwise, shall the\nLicensor be liable to anyone for any indirect, special, incidental, or\nconsequential damages of any character arising as a result of this License or\nthe use of the Original Work including, without limitation, damages for loss\nof goodwill, work stoppage, computer failure or malfunction, or any and all\nother commercial damages or losses. This limitation of liability shall not\napply to the extent applicable law prohibits such limitation.\n\n9) Acceptance and Termination. If, at any time, You expressly assented to this\nLicense, that assent indicates your clear and irrevocable acceptance of this\nLicense and all of its terms and conditions. If You distribute or communicate\ncopies of the Original Work or a Derivative Work, You must make a reasonable\neffort under the circumstances to obtain the express assent of recipients to\nthe terms of this License. This License conditions your rights to undertake\nthe activities listed in Section 1, including your right to create Derivative\nWorks based upon the Original Work, and doing so without honoring these terms\nand conditions is prohibited by copyright law and international treaty.\nNothing in this License is intended to affect copyright exceptions and\nlimitations (including "fair use" or "fair dealing"). This License shall\nterminate immediately and You may no longer exercise any of the rights granted\nto You by this License upon your failure to honor the conditions in Section\n1(c).\n\n10) Termination for Patent Action. This License shall terminate automatically\nand You may no longer exercise any of the rights granted to You by this\nLicense as of the date You commence an action, including a cross-claim or\ncounterclaim, against Licensor or any licensee alleging that the Original Work\ninfringes a patent. This termination provision shall not apply for an action\nalleging patent infringement by combinations of the Original Work with other\nsoftware or hardware.\n\n11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this\nLicense may be brought only in the courts of a jurisdiction wherein the\nLicensor resides or in which Licensor conducts its primary business, and under\nthe laws of that jurisdiction excluding its conflict-of-law provisions. The\napplication of the United Nations Convention on Contracts for the\nInternational Sale of Goods is expressly excluded. Any use of the Original\nWork outside the scope of this License or after its termination shall be\nsubject to the requirements and penalties of copyright or patent law in the\nappropriate jurisdiction. This section shall survive the termination of this\nLicense.\n\n12) Attorneys\' Fees. In any action to enforce the terms of this License or\nseeking damages relating thereto, the prevailing party shall be entitled to\nrecover its costs and expenses, including, without limitation, reasonable\nattorneys\' fees and costs incurred in connection with such action, including\nany appeal of such action. This section shall survive the termination of this\nLicense.\n\n13) Miscellaneous. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent necessary\nto make it enforceable.\n\n14) Definition of "You" in This License. "You" throughout this License,\nwhether in upper or lower case, means an individual or a legal entity\nexercising rights under, and complying with all of the terms of, this License.\nFor legal entities, "You" includes any entity that controls, is controlled by,\nor is under common control with you. For purposes of this definition,\n"control" means (i) the power, direct or indirect, to cause the direction or\nmanagement of such entity, whether by contract or otherwise, or (ii) ownership\nof fifty percent (50%) or more of the outstanding shares, or (iii) beneficial\nownership of such entity.\n\n15) Right to Use. You may use the Original Work in all ways not otherwise\nrestricted or conditioned by this License or by law, and Licensor promises not\nto interfere with or be responsible for such uses by You.\n\n16) Modification of This License. This License is Copyright © 2005 Lawrence\nRosen. Permission is granted to copy, distribute, or communicate this License\nwithout modification. Nothing in this License permits You to modify this\nLicense as applied to the Original Work or to Derivative Works. However, You\nmay modify the text of this License and copy, distribute or communicate your\nmodified version (the "Modified License") and apply it to other original works\nof authorship subject to the following conditions: (i) You may not indicate in\nany way that your Modified License is the "Academic Free License" or "AFL" and\nyou may not use those names in the name of your Modified License; (ii) You\nmust replace the notice specified in the first paragraph above with the notice\n"Licensed under " or with a notice of your own\nthat is not confusingly similar to the notice in this License; and (iii) You\nmay not claim that your original works are open source software unless your\nModified License has been approved by Open Source Initiative (OSI) and You\ncomply with its license review and certification process.\n', + "CC-BY-ND-4.0": 'Creative Commons Attribution-NoDerivatives 4.0 International\n\n Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.\n\nConsiderations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.\n\nConsiderations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.\n\nCreative Commons Attribution-NoDerivatives 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.\n\nSection 1 – Definitions.\n\n a.\tAdapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.\n\n b.\tCopyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.\n\n c.\tEffective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.\n\n d.\tExceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.\n\n e.\tLicensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.\n\n f.\tLicensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.\n\n g.\tLicensor means the individual(s) or entity(ies) granting rights under this Public License.\n\n h.\tShare means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.\n\n i.\tSui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.\n\n j.\tYou means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.\n\nSection 2 – Scope.\n\n a.\tLicense grant.\n\n 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:\n\n A. reproduce and Share the Licensed Material, in whole or in part; and\n\n B. produce and reproduce, but not Share, Adapted Material.\n\n 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.\n\n 3. Term. The term of this Public License is specified in Section 6(a).\n\n 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.\n\n 5. Downstream recipients.\n\n A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.\n\n B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.\n\n 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).\n\n b.\tOther rights.\n\n 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.\n\n 2. Patent and trademark rights are not licensed under this Public License.\n\n 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.\n\nSection 3 – License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the following conditions.\n\n a.\tAttribution.\n\n 1. If You Share the Licensed Material, You must:\n\n A. retain the following if it is supplied by the Licensor with the Licensed Material:\n\n i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);\n\n ii.\ta copyright notice;\n\n iii. a notice that refers to this Public License;\n\n iv.\ta notice that refers to the disclaimer of warranties;\n\n v.\ta URI or hyperlink to the Licensed Material to the extent reasonably practicable;\n\n B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and\n\n C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.\n\n 2. For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.\n\n 3. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.\n\n 4. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.\n\nSection 4 – Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:\n\n a.\tfor the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database, provided You do not Share Adapted Material;\n\n b.\tif You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and\n\n c.\tYou must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.\nFor the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.\n\nSection 5 – Disclaimer of Warranties and Limitation of Liability.\n\n a.\tUnless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.\n\n b.\tTo the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.\n\n c.\tThe disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.\n\nSection 6 – Term and Termination.\n\n a.\tThis Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.\n\n b.\tWhere Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:\n\n 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or\n\n 2. upon express reinstatement by the Licensor.\n\n c.\tFor the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.\n\n d.\tFor the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.\n\n e.\tSections 1, 5, 6, 7, and 8 survive termination of this Public License.\n\nSection 7 – Other Terms and Conditions.\n\n a.\tThe Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.\n\n b.\tAny arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.\n\nSection 8 – Interpretation.\n\n a.\tFor the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.\n\n b.\tTo the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.\n\n c.\tNo term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.\n\n d.\tNothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.\n\nCreative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n', + "BSD-2-Clause": 'Copyright (c) ${copyright_year} ${copyright_name}\r\n\r\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r\n\r\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r\n\r\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.', + "BSD-3-Clause": 'Copyright (c) ${copyright_year} ${copyright_name}. \r\n\r\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r\n\r\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r\n\r\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r\n\r\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.', + } + + for l in License.objects.all(): + if l.name in license_text: + l.text = license_text[l.name] + l.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ("library", "0031_dataciteregistrationlog_and_more"), + ] + + operations = [ + migrations.AddField( + model_name="license", + name="text", + field=models.TextField(blank=True, help_text="Full license text"), + ), + migrations.RunPython(add_default_text, reverse_code=migrations.RunPython.noop), + migrations.AddField( + model_name="codebase", + name="codemeta_snapshot", + field=models.JSONField( + default=dict, + help_text="JSON metadata conforming to the codemeta schema. Cached as of the last update", + ), + ), + migrations.AddField( + model_name="codebaserelease", + name="codemeta_snapshot", + field=models.JSONField( + default=dict, + help_text="JSON metadata conforming to the codemeta schema. Cached as of the last update", + ), + ), + ] diff --git a/django/library/models.py b/django/library/models.py index 04ee7e0e6..a4ab5bb98 100644 --- a/django/library/models.py +++ b/django/library/models.py @@ -3,13 +3,15 @@ import logging import os import pathlib +from string import Template +import uuid import semver import uuid - +from collections import OrderedDict +from datetime import timedelta from abc import ABC from collections import OrderedDict, defaultdict from datetime import date, timedelta -from typing import List from django.conf import settings from django.contrib.postgres.fields import ArrayField @@ -122,6 +124,16 @@ class License(models.Model): max_length=200, help_text=_("SPDX license code from https://spdx.org/licenses/") ) url = models.URLField(blank=True) + text = models.TextField(blank=True, help_text=_("Full license text")) + + def get_formatted_text(self, authors: str): + template = Template(self.text) + return template.substitute( + { + "copyright_year": timezone.now().year, + "copyright_name": authors, + } + ) def __str__(self): return f"{self.name} ({self.url})" @@ -584,6 +596,13 @@ class Codebase(index.Indexed, ModeratedContent, ClusterableModel): settings.AUTH_USER_MODEL, related_name="codebases", on_delete=models.PROTECT ) + codemeta_snapshot = models.JSONField( + default=dict, + help_text=_( + "JSON metadata conforming to the codemeta schema. Cached as of the last update" + ), + ) + objects = CodebaseQuerySet.as_manager() search_fields = [ @@ -1247,6 +1266,12 @@ class Status(models.TextChoices): null=True, storage=FileSystemStorage(location=settings.LIBRARY_ROOT), ) + codemeta_snapshot = models.JSONField( + default=dict, + help_text=_( + "JSON metadata conforming to the codemeta schema. Cached as of the last update" + ), + ) # M2M relationships for publications, disabled until citation migrates to django 2.0 # https://github.com/comses/citation/issues/20 """ From 7885432b702776e06ab9be50eb2b3e9526cae2f6 Mon Sep 17 00:00:00 2001 From: sgfost Date: Wed, 8 Jan 2025 19:51:44 -0700 Subject: [PATCH 04/31] refactor: standardize definition of 'author' contributors and replace redis caching of codebase all_contributor lists with querysets (did save a few queries but doesn't seem to have any meaningful performance impact) codebases were considering any citable release contributor as an author and releases considered anyone with a role of "author" to be an author. Now we use a union of the two -- not sure if this is the best way but regardless, its easier to change since it all stems from authors() and nonauthors() on the ReleaseContributorQuerySet codebase and release both now have 'nonauthor contributor' accessors, which is useful because this is what things like codemeta/datacite/etc. consider 'contributors' --- .../library/codebases/releases/retrieve.jinja | 2 +- django/library/models.py | 189 ++++++++---------- django/library/serializers.py | 6 - django/library/tests/test_codemeta.py | 10 +- 4 files changed, 95 insertions(+), 112 deletions(-) diff --git a/django/library/jinja2/library/codebases/releases/retrieve.jinja b/django/library/jinja2/library/codebases/releases/retrieve.jinja index f1c1610dd..c9ddd5169 100644 --- a/django/library/jinja2/library/codebases/releases/retrieve.jinja +++ b/django/library/jinja2/library/codebases/releases/retrieve.jinja @@ -22,7 +22,7 @@ https://scholar.google.com/intl/en/scholar/inclusion.html#indexing #} - {% for c in codebase.all_contributors -%} + {% for c in codebase.all_citable_contributors -%} {% if c.email -%} diff --git a/django/library/models.py b/django/library/models.py index a4ab5bb98..8945970c0 100644 --- a/django/library/models.py +++ b/django/library/models.py @@ -724,85 +724,45 @@ def base_library_dir(self): def base_git_dir(self): return pathlib.Path(settings.REPOSITORY_ROOT, str(self.uuid)) - @property - def codebase_contributors_redis_key(self): - return f"codebase:contributors:{self.identifier}" - - @property - def codebase_authors_redis_key(self): - return f"codebase:authors:{self.identifier}" - @property def publication_year(self): return ( self.last_published_on.year if self.last_published_on else date.today().year ) - def clear_contributors_cache(self): - cache.delete(self.codebase_contributors_redis_key) - cache.delete(self.codebase_authors_redis_key) - - def compute_contributors(self, force=False): - """ - caches and returns a two values: codebase_contributors and codebase_authors - codebase_contributors are all contributors to the release - codebase_authors are the contributors to the release that should be included in the citation - - both return types should be ordered, distinct lists of ReleaseContributor objects - """ - contributors_redis_key = self.codebase_contributors_redis_key - codebase_contributors = cache.get(contributors_redis_key) if not force else None - codebase_authors = ( - cache.get(self.codebase_authors_redis_key) if not force else None - ) - - codebase_authors_dict = OrderedDict() - - if codebase_contributors is None: - codebase_contributors_dict = OrderedDict() - for release_contributor in ReleaseContributor.objects.for_codebase(self): - contributor = release_contributor.contributor - codebase_contributors_dict[contributor] = release_contributor - # only include citable authors in returned codebase_authors - if release_contributor.include_in_citation: - codebase_authors_dict[contributor] = release_contributor - # PEP 448 syntax to unpack dict keys into list literal - # https://www.python.org/dev/peps/pep-0448/ - codebase_contributors = [*codebase_contributors_dict.values()] - codebase_authors = [*codebase_authors_dict.values()] - cache.set(contributors_redis_key, codebase_contributors) - cache.set(self.codebase_authors_redis_key, codebase_authors) - return codebase_contributors, codebase_authors - - @property + @cached_property def all_contributors(self): - """Get all the contributors associated with this codebase. A contributor is associated - with a codebase if any release associated with that codebase is also associated with the - same contributor. - - Caching contributors on _all_contributors makes it possible to ask for - codebase_contributors in bulk""" - if not hasattr(self, "_all_contributors"): - all_contributors, all_authors = self.compute_contributors(force=True) - self._all_contributors = all_contributors - self._all_authors = all_authors - return self._all_contributors + return Contributor.objects.filter( + id__in=ReleaseContributor.objects.for_codebase(self).values( + "contributor_id" + ) + ) - @property - def all_authors(self): - if not hasattr(self, "_all_authors"): - all_contributors, all_authors = self.compute_contributors(force=True) - self._all_contributors = all_contributors - self._all_authors = all_authors - return self._all_authors + @cached_property + def all_author_contributors(self): + return Contributor.objects.filter( + id__in=ReleaseContributor.objects.authors() + .for_codebase(self) + .values("contributor_id") + ) - @property - def author_list(self): - return [c.get_full_name() for c in self.all_authors if c.has_name] + @cached_property + def all_nonauthor_contributors(self): + return self.all_contributors.exclude( + id__in=self.all_author_contributors.values("id") + ) + + @cached_property + def all_citable_contributors(self): + return Contributor.objects.filter( + id__in=ReleaseContributor.objects.citable() + .for_codebase(self) + .values("contributor_id") + ) @property - def contributor_list(self): - return [c.get_full_name() for c in self.all_contributors if c.has_name] + def citable_names(self): + return [c.get_full_name() for c in self.all_citable_contributors if c.has_name] def get_all_contributors_search_fields(self): return " ".join( @@ -1536,15 +1496,33 @@ def permanent_url(self): return Codebase.format_doi_url(self.doi) return self.comses_permanent_url + @property + def release_contributors(self): + return ReleaseContributor.objects.for_release(self) + + @property + def author_release_contributors(self): + return ReleaseContributor.objects.authors().for_release(self) + + @property + def coauthor_release_contributors(self): + return self.author_release_contributors.exclude( + contributor__user=self.submitter + ) + + @property + def nonauthor_release_contributors(self): + return ReleaseContributor.objects.nonauthors().for_release(self) + @cached_property def citation_authors(self): authors = self.submitter.member_profile.name - author_list = self.codebase.author_list - if author_list: - authors = ", ".join(author_list) + citable_names = self.codebase.citable_names + if citable_names: + authors = ", ".join(citable_names) else: logger.warning( - "No authors found for release, using default submitter name: %s", + "No authors found for release when building citation text, using default submitter name: %s", self.submitter, ) return authors @@ -1592,12 +1570,12 @@ def archive_filename(self): return f"{slugify(self.codebase.title)}_v{self.version_number}.zip" @property - def contributor_list(self): - """Returns all contributors for just this CodebaseRelease""" + def contributor_names(self): + """Returns the names for all contributors for just this CodebaseRelease""" return [ - c.contributor.get_full_name() - for c in self.index_ordered_release_contributors - if c.contributor.has_name + rc.contributor.get_full_name() + for rc in self.release_contributors + if rc.contributor.has_name ] @property @@ -1611,7 +1589,7 @@ def bagit_info(self): return { "Contact-Name": self.submitter.get_full_name(), "Contact-Email": self.submitter.email, - "Author": self.contributor_list, + "Author": self.contributor_names, "Version-Number": self.version_number, "Codebase-DOI": str(self.codebase.doi), "DOI": str(self.doi), @@ -1805,6 +1783,8 @@ class Meta: class ReleaseContributorQuerySet(models.QuerySet): def for_codebase(self, codebase, ordered=True): + """all release contributors (with contributors) for any published release + of a codebase""" qs = self.select_related("contributor").filter( release__codebase=codebase, release__status=CodebaseRelease.Status.PUBLISHED ) @@ -1812,6 +1792,25 @@ def for_codebase(self, codebase, ordered=True): return qs.order_by("release__date_created", "index") return qs + def for_release(self, release, ordered=True): + """release contributors (with contributors) for a release""" + qs = self.select_related("contributor").filter(release=release) + if ordered: + return qs.order_by("index") + return qs + + def authors(self): + """all release contributors with a role of 'Author' or include_in_citation=True""" + return self.filter(Q(include_in_citation=True) | Q(roles__contains="{author}")) + + def nonauthors(self): + """all release contributors without a role of 'Author' or include_in_citation=True""" + return self.exclude(Q(include_in_citation=True) | Q(roles__contains="{author}")) + + def citable(self): + """release contributors that should be included in a citation""" + return self.filter(include_in_citation=True) + def copy_to(self, release: CodebaseRelease): release_contributors = list(self) for release_contributor in release_contributors: @@ -1819,23 +1818,6 @@ def copy_to(self, release: CodebaseRelease): release_contributor.release = release return self.bulk_create(release_contributors) - def authors(self, release): - return ( - self.select_related("contributor") - .filter( - release=release, include_in_citation=True, roles__contains="{author}" - ) - .order_by("index") - ) - - def nonauthors(self, release): - return ( - self.select_related("contributor") - .filter(release=release, include_in_citation=True) - .exclude(roles__contains="{author}") - .order_by("index") - ) - class ReleaseContributor(models.Model): release = models.ForeignKey( @@ -2677,11 +2659,13 @@ def descriptions(self): @cached_property def release_contributor_nonauthors(self): - return ReleaseContributor.objects.nonauthors(self.codebase_release) + return ReleaseContributor.objects.nonauthors().for_release( + self.codebase_release + ) @cached_property def release_contributor_authors(self): - return ReleaseContributor.objects.authors(self.codebase_release) + return ReleaseContributor.objects.authors().for_release(self.codebase_release) class CodeMetaSchema: @@ -2906,11 +2890,10 @@ def convert_keywords(cls, common_metadata: CommonMetadata): return [{"subject": keyword} for keyword in unique_keywords] @classmethod - def convert_release_contributor(cls, release_contributor: ReleaseContributor): + def convert_contributor(cls, contributor: Contributor): """ Converts a ReleaseContributor to a DataCite creator dictionary """ - contributor = release_contributor.contributor creator = {} # check for ORCID name identifier first: https://datacite-metadata-schema.readthedocs.io/en/4.5/properties/creator/#nameidentifier if contributor.is_person: @@ -2961,13 +2944,13 @@ def convert_affiliation(cls, affiliation: dict): return datacite_affiliation @classmethod - def to_citable_authors(cls, release_contributors): + def to_citable_authors(cls, contributors: Contributor): """ Maps a set of ReleaseContributors to a list of dictionaries representing DataCite creators https://datacite-metadata-schema.readthedocs.io/en/4.5/properties/creator/ """ - return [cls.convert_release_contributor(rc) for rc in release_contributors] + return [cls.convert_contributor(c) for c in contributors] @classmethod def to_publication_year(cls, common_metadata: CommonMetadata): @@ -3060,7 +3043,7 @@ def convert(cls, common_metadata: CommonMetadata): """ metadata = { "creators": cls.to_citable_authors( - common_metadata.release_contributor_authors + [rc.contributor for rc in common_metadata.release_contributor_authors] ), "descriptions": common_metadata.descriptions, "publicationYear": str(cls.to_publication_year(common_metadata)), @@ -3151,7 +3134,7 @@ def convert(cls, codebase: Codebase): # FIXME: establish CommonMetadata for Codebases as well and change signature to operate on CommonMetadata # add references_text and associated_publication_text fields when better structured metadata for those fields are available metadata = { - "creators": cls.to_citable_authors(codebase.all_authors), + "creators": cls.to_citable_authors(codebase.all_author_contributors), "titles": [{"title": codebase.title}], "descriptions": [ { diff --git a/django/library/serializers.py b/django/library/serializers.py index 0707e1517..7471a5f1c 100644 --- a/django/library/serializers.py +++ b/django/library/serializers.py @@ -300,19 +300,13 @@ def create_unsaved(context, validated_data): instance = ReleaseContributor(**validated_data) return instance - def update_codebase_contributor_cache(self, release_contributor): - # invalidate contributors cache for the given codebase - release_contributor.release.codebase.clear_contributors_cache() - def create(self, validated_data): release_contributor = self.create_unsaved(self.context, validated_data) release_contributor.save() - self.update_codebase_contributor_cache(release_contributor) return release_contributor def update(self, instance, validated_data): release_contributor = super().update(instance, validated_data) - self.update_codebase_contributor_cache(release_contributor) return release_contributor class Meta: diff --git a/django/library/tests/test_codemeta.py b/django/library/tests/test_codemeta.py index 65421f7a1..9ea5ffeb9 100644 --- a/django/library/tests/test_codemeta.py +++ b/django/library/tests/test_codemeta.py @@ -411,10 +411,16 @@ def length_agrees(self): total number of added unique authors and non-author contributors should match """ real_author_contributors_count = ( - ReleaseContributor.objects.authors(self.codebase_release).all().count() + ReleaseContributor.objects.authors() + .for_release(self.codebase_release) + .all() + .count() ) real_nonauthor_contributors_count = ( - ReleaseContributor.objects.nonauthors(self.codebase_release).all().count() + ReleaseContributor.objects.nonauthors() + .for_release(self.codebase_release) + .all() + .count() ) assert ( From 7622cefdded1fef2cc56387766003e1c3d37919d Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 12:52:03 -0700 Subject: [PATCH 05/31] refactor: use codemeticulous and on save hook for metadata generation move metadata conversion to a metadata module which provides converters for different formats. codemeta is used as the primary format which the others (datacite, cff) can be derived from the primary codemeta accessor is the codemeta_snapshot json field, which is rebuilt each time a codebase/release is saved * add `update_codebase_metadata` command to update the codemeta snapshot for all objects, then update packages on the fs * add CITATION.cff file to fs package --- django/Dockerfile | 7 + django/core/serializers.py | 4 +- django/library/fs.py | 52 ++- .../library/codebases/releases/retrieve.jinja | 4 +- .../commands/update_codebase_metadata.py | 68 ++++ .../management/commands/update_codemeta.py | 22 -- django/library/metadata.py | 251 ++++++++++++++ django/library/models.py | 323 +++++++----------- django/library/serializers.py | 10 +- django/library/tasks.py | 10 +- django/library/tests/base.py | 2 +- django/library/tests/test_views.py | 2 +- django/library/views.py | 2 + 13 files changed, 506 insertions(+), 251 deletions(-) create mode 100644 django/library/management/commands/update_codebase_metadata.py delete mode 100644 django/library/management/commands/update_codemeta.py create mode 100644 django/library/metadata.py diff --git a/django/Dockerfile b/django/Dockerfile index ba2a1b372..0330b57d5 100644 --- a/django/Dockerfile +++ b/django/Dockerfile @@ -63,4 +63,11 @@ COPY ./deploy/db/postgresql-backup-pre /etc/ COPY ${RUN_SCRIPT} /etc/service/django/run COPY ./deploy/huey.sh /etc/service/huey/run COPY . /code + +# FIXME: replace with install from pypi +# upgrading pip because of some bug with the debian patched version +RUN python3 -m pip install --upgrade pip +RUN pip3 install git+https://github.com/sgfost/codemeticulous.git +RUN pip3 install -r /tmp/requirements.txt + CMD ["/sbin/my_init"] diff --git a/django/core/serializers.py b/django/core/serializers.py index 3c663131a..434523866 100644 --- a/django/core/serializers.py +++ b/django/core/serializers.py @@ -69,10 +69,8 @@ def create(model_cls, validated_data, context): def update(serializer_update, instance, validated_data): tags = TagSerializer(many=True, data=validated_data.pop("tags")) - instance = serializer_update(instance, validated_data) set_tags(instance, tags) - instance.save() - return instance + return serializer_update(instance, validated_data) class EditableSerializerMixin(serializers.Serializer): diff --git a/django/library/fs.py b/django/library/fs.py index 0e032532b..bbd13f6b5 100644 --- a/django/library/fs.py +++ b/django/library/fs.py @@ -1,4 +1,3 @@ -import json import logging import mimetypes import os @@ -405,10 +404,22 @@ def originals_dir(self): def sip_dir(self): return self.rootdir.joinpath("sip") + @property + def codemeta_contents(self) -> str: + return self.release.codemeta_json_str + @property def codemeta_path(self): return self.sip_contents_dir.joinpath("codemeta.json") + @property + def cff_contents(self) -> str: + return self.release.cff_yaml_str + + @property + def cff_path(self): + return self.sip_contents_dir.joinpath("CITATION.cff") + @property def license_path(self): return self.sip_contents_dir.joinpath("LICENSE") @@ -519,7 +530,25 @@ def create_or_update_codemeta(self, force=False): path = self.codemeta_path if force or not path.exists(): with path.open(mode="w", encoding="utf-8") as codemeta_out: - json.dump(self.codemeta.to_dict(), codemeta_out) + codemeta_out.write(self.codemeta_contents) + return True + return False + + def create_or_update_citation_cff(self, force=False): + """ + Returns True if a CITATION.cff file was created, False otherwise + """ + path = self.cff_path + try: + cff_contents = self.cff_contents + except Exception as e: + logger.exception( + f"error generating CITATION.cff for release {self.release}: {e}" + ) + return False + if force or not path.exists(): + with path.open(mode="w", encoding="utf-8") as cff_out: + cff_out.write(cff_contents) return True return False @@ -539,6 +568,7 @@ def build_published_archive(self, force=False): FIXME: some of this should be moved to an async processing task. """ self.create_or_update_codemeta(force=force) + self.create_or_update_citation_cff(force=force) self.create_or_update_license(force=force) bag = self.get_or_create_sip_bag(self.bagit_info) self.validate_bagit(bag) @@ -546,6 +576,7 @@ def build_published_archive(self, force=False): def build_review_archive(self): self.create_or_update_codemeta(force=True) + self.create_or_update_citation_cff(force=True) self.create_or_update_license(force=True) shutil.make_archive( str(self.review_archivepath.with_suffix("")), @@ -745,10 +776,21 @@ def build_archive(self, force=False): if not self.archivepath.exists() or force: self.build_archive_at_dest(dest=str(self.archivepath)) - def rebuild(self): - msgs = self.build_sip() + def rebuild(self, metadata_only=False) -> MessageGroup: + """rebuild the submission package and archive if it already exists + + if metadata_only is True, only the metadata files are rebuilt, not the entire package + """ + if not metadata_only: + msgs = self.build_sip() + else: + msgs = self._create_msg_group() self.create_or_update_codemeta(force=True) - self.build_archive(force=True) + self.create_or_update_citation_cff(force=True) + self.create_or_update_license(force=True) + # only rebuild the archive package if it already exists + if self.aip_dir.exists(): + self.build_archive(force=True) return msgs diff --git a/django/library/jinja2/library/codebases/releases/retrieve.jinja b/django/library/jinja2/library/codebases/releases/retrieve.jinja index c9ddd5169..7340faa89 100644 --- a/django/library/jinja2/library/codebases/releases/retrieve.jinja +++ b/django/library/jinja2/library/codebases/releases/retrieve.jinja @@ -14,7 +14,7 @@ {%- block head -%} {% if release.live %} @@ -504,7 +504,7 @@ - {% for related_release in codebase.ordered_releases(has_change_perm) %} + {% for related_release in codebase.ordered_releases_list(has_change_perm, asc=False) %} {{ related_release.version_number }} diff --git a/django/library/management/commands/update_codebase_metadata.py b/django/library/management/commands/update_codebase_metadata.py new file mode 100644 index 000000000..6010aff59 --- /dev/null +++ b/django/library/management/commands/update_codebase_metadata.py @@ -0,0 +1,68 @@ +import json +import logging + +from django.core.management.base import BaseCommand + +from library.models import Codebase, CodebaseRelease + + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + """ + Update stored codemeta representation of metadata for all codebases and releases. + Rebuilds the archive package on the filesystem + + This is intended to be run as a one-off command to update codemeta for all records + after a change to how codemeta is stored, generated, and used. + """ + + def handle(self, *args, **options): + self.stdout.write("Updating codemeta for all Codebase objects...") + self.update_codemeta(Codebase) + self.stdout.write("Updating codemeta for all CodebaseRelease objects...") + self.update_codemeta(CodebaseRelease) + self.stdout.write("Rebuilding fs packages for all releases...") + self.update_release_packages() + self.stdout.write("Done") + + def update_codemeta(self, model): + objects = model.objects.all() + total = objects.count() + errors = [] + for obj in objects: + try: + fresh_codemeta = json.loads(obj.codemeta.json()) + model.objects.filter(pk=obj.pk).update(codemeta_snapshot=fresh_codemeta) + except Exception as e: + errors.append((obj, e)) + if errors: + for obj, e in errors: + logger.error(f"Error updating codemeta for {obj}: {e}") + self.stdout.write( + f"Updated codemeta for {total - len(errors)}/{total} {model.__name__} objects" + ) + self.stdout.write(f"with {len(errors)} errors") + else: + self.stdout.write(f"Updated codemeta for {total} {model.__name__} objects") + + def update_release_packages(self): + releases = CodebaseRelease.objects.all() + total = releases.count() + errors = [] + for release in releases: + try: + fs_api = release.get_fs_api() + fs_api.rebuild(metadata_only=True) + except Exception as e: + errors.append((release, e)) + if errors: + for release, e in errors: + logger.error(f"Error updating metadata for {release}: {e}") + self.stdout.write( + f"Updated metadata for {total - len(errors)}/{total} release packages" + ) + self.stdout.write(f"with {len(errors)} errors") + else: + self.stdout.write(f"Updated metadata for {total} release packages") diff --git a/django/library/management/commands/update_codemeta.py b/django/library/management/commands/update_codemeta.py deleted file mode 100644 index dd866e487..000000000 --- a/django/library/management/commands/update_codemeta.py +++ /dev/null @@ -1,22 +0,0 @@ -""" -Initializes CoMSES virtual conference Page Models and other canned data. -""" - -import logging - -from django.core.management.base import BaseCommand - -from library.models import CodebaseRelease - - -logger = logging.getLogger(__name__) - - -class Command(BaseCommand): - """ - Updates all codemeta files for all Codebases and updates archive - """ - - def handle(self, *args, **options): - for release in CodebaseRelease.objects.all(): - release.get_fs_api().create_or_update_codemeta(force=True) diff --git a/django/library/metadata.py b/django/library/metadata.py new file mode 100644 index 000000000..1e78a51b2 --- /dev/null +++ b/django/library/metadata.py @@ -0,0 +1,251 @@ +from datetime import date +from typing import Literal +from codemeticulous.codemeta.models import ( + CodeMeta, + Person, + Organization, + Role, + CreativeWork, +) +from codemeticulous.cff.models import CitationFileFormat +from codemeticulous.datacite.models import DataCite +from codemeticulous import convert + +from django.conf import settings + +import logging + +logger = logging.getLogger(__name__) + + +class CodeMetaConverter: + """Create codemeta objects that represent the metadata for a codebase or release.""" + + COMSES_ORGANIZATION = { + "@id": "https://ror.org/015bsfc29", + "@type": "Organization", + "name": "CoMSES Net", + "url": "https://www.comses.net", + } + + COMSES_MODEL_LIBRARY_CREATIVE_WORK = { + "@type": "WebApplication", + "applicationCategory": "Computational Modeling Software Repository", + "operatingSystem": "Any", + "name": "CoMSES Model Library", + "url": "https://www.comses.net/codebases", + } + + @classmethod + def convert_affiliation(cls, affiliation: dict) -> Organization: + return Organization( + id_=affiliation.get("ror_id") or None, + name=affiliation.get("name"), + url=affiliation.get("url"), + identifier=affiliation.get("ror_id") or None, + ) + + @classmethod + def convert_release_contributors( + cls, + release_contributors, + actor_type: Literal["author", "contributor"], + ) -> list[Person | Organization | Role]: + codemeta_actors = [] + codemeta_roles = [] + for num, rc in enumerate(release_contributors): + contributor = rc.contributor + # https://www.w3.org/TR/json-ld11/#identifying-blank-nodes + contributor_id = contributor.orcid_url or f"_:{actor_type}_{num + 1}" + if contributor.is_organization: + codemeta_actors.append( + Organization( + id_=contributor_id, + name=contributor.name, + ) + ) + elif contributor.is_person: + affiliation = ( + cls.convert_affiliation(contributor.primary_affiliation) + if contributor.primary_affiliation + else None + ) + codemeta_actors.append( + Person( + id_=contributor_id, + givenName=contributor.get_given_name() or None, + familyName=contributor.get_family_name() or None, + affiliation=affiliation, + email=contributor.email or None, + ) + ) + + for role in rc.roles: + if role != "author": + codemeta_roles.append( + Role( + id_=contributor_id, + roleName=role, + ) + ) + + return codemeta_actors + codemeta_roles + + @classmethod + def to_textual_creative_work(cls, text: str) -> CreativeWork: + return { + "@type": "CreativeWork", + "text": text, + } + + @classmethod + def _convert_release(cls, release) -> CodeMeta: + codebase = release.codebase + return CodeMeta( + type_="SoftwareSourceCode", + id_=release.permanent_url, + identifier=( + [release.doi, release.permanent_url] + if release.doi + else release.permanent_url + ), + name=codebase.title, + # FIXME: is this semantically correct? + # isPartOf=COMSES_MODEL_LIBRARY_CREATIVE_WORK, + codeRepository=codebase.repository_url or None, + programmingLanguage=[ + # FIXME: this can include "version" when langs are refactored + {"@type": "ComputerLanguage", "name": pl.name} + for pl in release.programming_languages.all().order_by("name") + ], + runtimePlatform=[ + tag.name for tag in release.platform_tags.all().order_by("name") + ] + or None, + # FIXME: anything to use this for? it can be either the target os or target + # framework (e.g. Mesa, NetLogo) but these are both already covered + # targetProduct=release.os, + applicationCategory="Computational Model", + # applicationSubCategory="Agent-Based Model", <-- would be nice + downloadUrl=f"{settings.BASE_URL}{release.get_download_url()}", + operatingSystem=release.os, + releaseNotes=release.release_notes.raw, + supportingData=release.output_data_url or None, + author=cls.convert_release_contributors( + release.author_release_contributors, "author" + ) + or None, + citation=[ + cls.to_textual_creative_work(text) + for text in [ + codebase.references_text, + codebase.replication_text, + ] + if text + ] + or None, + contributor=cls.convert_release_contributors( + release.nonauthor_release_contributors, "contributor" + ) + or None, + copyrightYear=( + release.last_published_on.year if release.last_published_on else None + ), + dateCreated=codebase.date_created.date(), + dateModified=( + release.last_modified.date() if release.last_modified else None + ), + datePublished=( + release.last_published_on.date() if release.last_published_on else None + ), + # tags are sorted so that comparisons are deterministic + keywords=[tag.name for tag in codebase.tags.all().order_by("name")] or None, + license=release.license.url if release.license else None, + publisher=cls.COMSES_ORGANIZATION, + version=release.version_number, + description=codebase.description.raw, + url=release.permanent_url, + embargoEndDate=release.embargo_end_date, + referencePublication=codebase.associated_publication_text or None, + ) + + @classmethod + def _convert_release_minimal(cls, release) -> CodeMeta: + codebase = release.codebase + return CodeMeta( + type_="SoftwareSourceCode", + name=codebase.title, + ) + + @classmethod + def convert_release(cls, release) -> CodeMeta: + try: + return cls._convert_release(release) + except Exception as e: + # in case something goes horribly wrong, log the error and return a valid but + # minimal codemeta object + logger.exception("Error when generating codemeta: %s", e) + return cls._convert_release_minimal(release) + + @classmethod + def convert_codebase(cls, codebase) -> CodeMeta: + # TODO: finish this, should extract common stuff from create_release + return CodeMeta( + type_="SoftwareSourceCode", + id_=codebase.permanent_url, + name=codebase.title, + publisher=cls.COMSES_ORGANIZATION, + ) + + +class CitationFileFormatConverter: + """Create citation file format objects that represent the metadata for a codebase or release.""" + + @classmethod + def convert_release( + cls, release, codemeta: CodeMeta | dict = None + ) -> CitationFileFormat: + if not codemeta: + codemeta = CodeMetaConverter.convert_release(release) + elif isinstance(codemeta, dict): + try: + codemeta = CodeMeta(**codemeta) + except: + codemeta = None + return convert("codemeta", "cff", codemeta) + + +class DataCiteConverter: + """Create datacite metadata objects that represent the metadata for a codebase or release.""" + + @classmethod + def convert_release(cls, release, codemeta: CodeMeta | dict = None) -> DataCite: + if not codemeta: + codemeta = CodeMetaConverter.convert_release(release) + elif isinstance(codemeta, dict): + try: + codemeta = CodeMeta(**codemeta) + except: + codemeta = None + # datacite always needs a publication date + if not codemeta.datePublished: + codemeta.datePublished = date.today() + # any additional fields that cannot be derived from codemeta + addl_datacite_fields = {} + return convert("codemeta", "datacite", codemeta, **addl_datacite_fields) + + @classmethod + def convert_codebase(cls, codebase, codemeta: CodeMeta | dict = None) -> DataCite: + if not codemeta: + codemeta = CodeMetaConverter.convert_codebase(codebase) + elif isinstance(codemeta, dict): + try: + codemeta = CodeMeta(**codemeta) + except: + codemeta = None + # datacite always needs a publication date + if not codemeta.datePublished: + codemeta.datePublished = date.today() + # any additional fields that cannot be derived from codemeta + addl_datacite_fields = {} + return convert("codemeta", "datacite", codemeta, **addl_datacite_fields) diff --git a/django/library/models.py b/django/library/models.py index 8945970c0..85e9dfff3 100644 --- a/django/library/models.py +++ b/django/library/models.py @@ -1,5 +1,6 @@ import hashlib import json +import yaml import logging import os import pathlib @@ -9,6 +10,7 @@ import uuid from collections import OrderedDict from datetime import timedelta +from packaging.version import Version from abc import ABC from collections import OrderedDict, defaultdict from datetime import date, timedelta @@ -51,6 +53,7 @@ from core.queryset import get_viewable_objects_for_user from core.utils import send_markdown_email from core.view_helpers import get_search_queryset +from .metadata import CodeMetaConverter, DataCiteConverter, CitationFileFormatConverter from .fs import ( CodebaseReleaseFsApi, StagingDirectories, @@ -278,9 +281,6 @@ def get_profile_url(self): def get_markdown_link(self): return f"[{self.get_full_name()}]({self.member_profile_url})" - def to_codemeta(self): - return CodeMetaSchema.convert_contributor(self) - def get_aggregated_search_fields(self): return " ".join( {self.given_name, self.family_name, self.email} | self._get_user_fields() @@ -303,6 +303,15 @@ def get_full_name(self, family_name_first=False): # organizations only use given_name return self.given_name + def get_given_name(self): + return self.given_name or (self.user.first_name if self.user else "") + + def get_family_name(self): + return self.family_name or (self.user.last_name if self.user else "") + + def get_email(self): + return self.email or (self.user.email if self.user else "") + def _get_person_full_name(self, family_name_first=False): if not self.has_name: logger.warning("No usable name found for contributor %s", self.id) @@ -634,10 +643,22 @@ class Codebase(index.Indexed, ModeratedContent, ClusterableModel): HAS_PUBLISHED_KEY = True + @property + def codemeta(self): + """a freshly generated CodeMeta object representing this codebase""" + return CodeMetaConverter.convert_codebase(self) + @cached_property def datacite(self): return DataCiteSchema.from_codebase(self) + # FIXME: replace the above datacite metadata generation with this + # @property + # def datacite(self): + # return DataCiteConverter.convert_codebase( + # self, codemeta=self.codemeta_snapshot or None + # ) + @property def is_replication(self): return bool(self.replication_text.strip()) @@ -790,13 +811,20 @@ def download_count(self): release__codebase__id=self.id ).count() - def ordered_releases(self, has_change_perm=False, **kwargs): - releases = self.releases.order_by("-version_number").filter(**kwargs) - return ( - releases - if has_change_perm - else releases.filter(status=CodebaseRelease.Status.PUBLISHED) - ) + def ordered_releases_list(self, has_change_perm=False, asc=True, **kwargs): + """ + list public releases (or all release if has_change_perm is True) in ascending (default) or descending order + """ + if has_change_perm: + releases = self.releases.filter(**kwargs) + else: + releases = self.public_releases(**kwargs) + releases_list = list(releases) + releases_list.sort(key=lambda r: Version(r.version_number), reverse=not asc) + return releases_list + + def public_releases(self, **kwargs): + return self.releases.filter(status=CodebaseRelease.Status.PUBLISHED, **kwargs) @classmethod def get_list_url(cls): @@ -1000,6 +1028,17 @@ def create_release( self.save() return release + def save(self, rebuild_metadata=True, **kwargs): + if rebuild_metadata: + logger.debug("Building codemeta for codebase: %s", self) + self.codemeta_snapshot = json.loads(self.codemeta.json()) + super().save(**kwargs) + # saving releases will trigger metadata rebuilding and updating + # the fs and git mirror if one exists + if rebuild_metadata: + for release in self.releases.all(): + release.save(rebuild_metadata=True) + @classmethod def get_indexed_objects(cls): return cls.objects.public() @@ -1601,11 +1640,6 @@ def common_metadata(self): """Returns a CommonMetadata object used to build specific metadata objects: for example CodeMeta or DataCite""" return CommonMetadata(self) - @cached_property - def codemeta(self): - """Returns a CodeMetaMetadata object that can be dumped to json""" - return CodeMetaSchema.build(self) - @cached_property def datacite(self): if not self.live: @@ -1614,6 +1648,44 @@ def datacite(self): ) return DataCiteSchema.from_release(self) + # FIXME: replace the above datacite metadata generation with this + # @property + # def datacite_temp(self): + # return DataCiteConverter.convert_release( + # self, codemeta=self.codemeta_snapshot or None + # ) + + @property + def codemeta(self): + """a freshly generated CodeMeta object representing this release""" + return CodeMetaConverter.convert_release(self) + + @property + def cff(self): + """an object representing this release in the Citation File Format""" + return CitationFileFormatConverter.convert_release( + self, codemeta=self.codemeta_snapshot or None + ) + + @property + def codemeta_json_str(self): + """json-formatted string of the codemeta metadata""" + return json.dumps(self.codemeta_snapshot, indent=2) + + @property + def cff_yaml_str(self): + """yaml-formatted string of the cff metadata""" + return yaml.dump(json.loads(self.cff.json()), default_flow_style=False) + + @cached_property + def license_text(self) -> str: + """return the license text with the copyright notice filled in""" + return ( + self.license.get_formatted_text(self.citation_authors) + if self.license + else "" + ) + @property def is_draft(self): return self.status == self.Status.DRAFT @@ -1652,10 +1724,6 @@ def get_status_color(self): } return COLOR_MAP.get(self.status) - @property - def codemeta_json(self): - return self.codemeta.to_json() - def create_or_update_codemeta(self, force=True): return self.get_fs_api().create_or_update_codemeta(force=force) @@ -1690,28 +1758,29 @@ def add_contributor(self, contributor: Contributor, role=Role.AUTHOR, index=None return existing_release_contributor @transaction.atomic - def publish(self, defer_fs=False): + def publish(self): self.validate_publishable() - self._publish(defer_fs) + self._publish() - def _publish(self, defer_fs=False): + def _publish(self): if not self.live: now = timezone.now() self.first_published_at = now self.last_published_on = now self.status = self.Status.PUBLISHED - if defer_fs: - logger.debug("FIXME: set up async publish archive task") - else: - self.get_fs_api().build_published_archive(force=True) - self.save() + self.get_fs_api().build_published_archive(force=True) codebase = self.codebase codebase.latest_version = self codebase.live = True codebase.last_published_on = now if codebase.first_published_at is None: codebase.first_published_at = now - codebase.save() + codebase.save(rebuild_metadata=False) + # normally, rebuilding metadata is asynchronous and automatic but + # here we need to build it synchronously after setting everything + self.codemeta_snapshot = json.loads(self.codemeta.json()) + self.save(rebuild_metadata=False) + self.get_fs_api().rebuild(metadata_only=True) @transaction.atomic def unpublish(self): @@ -1770,6 +1839,24 @@ def set_version_number(self, version_number): ) self.version_number = version_number + def cache_codemeta(self): + self.codemeta_snapshot = json.loads(self.codemeta.json()) + self.save(rebuild_metadata=False) + + def save(self, rebuild_metadata=True, **kwargs): + if not rebuild_metadata: + super().save(**kwargs) + else: + logger.debug("Building codemeta for release: %s", self) + old_codemeta = self.codemeta_snapshot + self.codemeta_snapshot = json.loads(self.codemeta.json()) + super().save(**kwargs) + + if old_codemeta != self.codemeta_snapshot: + from .tasks import update_fs_release_metadata + + update_fs_release_metadata(self.id) + @classmethod def get_indexed_objects(cls): return cls.objects.public() @@ -2668,184 +2755,6 @@ def release_contributor_authors(self): return ReleaseContributor.objects.authors().for_release(self.codebase_release) -class CodeMetaSchema: - COMSES_ORGANIZATION = { - "@id": "https://ror.org/015bsfc29", - "@type": "Organization", - **CommonMetadata.COMSES_ORGANIZATION, - } - - INITIAL_METADATA = { - "@context": "https://w3id.org/codemeta/v3.0", - "@type": "SoftwareSourceCode", - "isPartOf": { - "@type": "WebApplication", - "applicationCategory": "Computational Modeling Software Repository", - "operatingSystem": "Any", - "name": "CoMSES Model Library", - "url": "https://www.comses.net/codebases", - }, - "publisher": COMSES_ORGANIZATION, - "provider": COMSES_ORGANIZATION, - "description": "Default CoMSES Description", - "keywords": [], - "author": [], - "license": "https://opensource.org/license/mit", - } - - def __init__(self, metadata: dict): - if not metadata: - raise ValueError( - "Initialize with a base dictionary with codemeta terms mapped to JSON-serializable values" - ) - self.metadata = metadata - - @classmethod - def build(cls, codebase_release: CodebaseRelease): - if not codebase_release.live: - logger.warning( - "generating codemeta for an unpublished release: %s", codebase_release - ) - return CodeMetaSchema(cls.INITIAL_METADATA) - return CodeMetaSchema(cls.convert(codebase_release)) - - @classmethod - def convert(cls, codebase_release: CodebaseRelease): - """ - Converts the given CodebaseRelease into a Python dictionary. - """ - common_metadata = codebase_release.common_metadata - metadata = { - **cls.INITIAL_METADATA, - # base metadata from CommonMetadata - "@id": common_metadata.identifier, - "identifier": common_metadata.identifier, - "name": common_metadata.name, - "copyrightYear": common_metadata.copyright_year, - "dateCreated": common_metadata.date_created.isoformat(), - "dateModified": common_metadata.date_modified.isoformat(), - "datePublished": common_metadata.last_published.isoformat(), - "description": common_metadata.description, - "keywords": common_metadata.keywords, - "releaseNotes": common_metadata.release_notes, - "license": common_metadata.license_url, - "runtimePlatform": common_metadata.runtime_platform, - "url": common_metadata.permanent_url, - # requires additional CodeMeta specific processing - "author": cls.convert_authors(common_metadata), - "citation": cls.convert_citations(common_metadata), - "programmingLanguage": cls.convert_programming_languages(common_metadata), - "targetProduct": cls.convert_target_product(common_metadata), - } - if hasattr(common_metadata, "code_repository"): - metadata.update(codeRepository=common_metadata.code_repository) - if hasattr(common_metadata, "release_notes"): - metadata.update(releaseNotes=common_metadata.release_notes) - return metadata - - @classmethod - def convert_programming_languages(cls, common_metadata: CommonMetadata): - return [ - {"@type": "ComputerLanguage", "name": pl.name} - for pl in common_metadata.programming_languages - ] - - @classmethod - def convert_citations(cls, common_metadata: CommonMetadata): - return [ - cls.to_creative_work(citation_text) - for citation_text in common_metadata.citations - ] - - @classmethod - def to_creative_work(cls, text): - return {"@type": "CreativeWork", "text": text} - - @classmethod - def convert_authors(cls, common_metadata: CommonMetadata): - return [ - cls.convert_contributor(author.contributor) - for author in common_metadata.release_contributor_authors - ] - - @classmethod - def convert_affiliation(cls, affiliation: dict): - codemeta_affiliation = {} - if affiliation: - codemeta_affiliation = { - # FIXME: may switch to https://schema.org/ResearchOrganization at some point - "@type": "Organization", - "name": affiliation.get("name"), - "url": affiliation.get("url"), - } - if affiliation.get("ror_id"): - codemeta_affiliation.update( - { - "@id": affiliation.get("ror_id"), - "identifier": affiliation.get("ror_id"), - "sameAs": affiliation.get("ror_id"), - } - ) - return codemeta_affiliation - - @classmethod - def convert_contributor(cls, contributor: Contributor): - codemeta = { - "@type": "Person", - # FIXME: Contributor should proxy to User / MemberProfile fields if User is available and given_name and family_name are not set - "givenName": contributor.given_name, - "familyName": contributor.family_name, - } - if contributor.orcid_url: - codemeta["@id"] = contributor.orcid_url - if contributor.affiliations: - codemeta["affiliation"] = cls.convert_affiliation( - contributor.primary_affiliation - ) - if contributor.email: - codemeta["email"] = contributor.email - return codemeta - - @classmethod - def convert_target_product(cls, common_metadata: CommonMetadata): - target_product = { - "@type": "SoftwareApplication", - "name": common_metadata.release_title, - "operatingSystem": common_metadata.os, - "applicationCategory": "Computational Model", - } - if common_metadata.live: - target_product.update( - # FIXME: consider adding a convenience method to generate absolute urls - downloadUrl=f"{settings.BASE_URL}{common_metadata.download_url}", - releaseNotes=getattr(common_metadata, "release_notes", None), - softwareVersion=common_metadata.version, - identifier=common_metadata.identifier, - sameAs=common_metadata.comses_permanent_url, - ) - image_url = common_metadata.get_featured_rendition_url - if image_url: - # FIXME: consider adding a convenience method to generate absolute urls - target_product.update(screenshot=f"{settings.BASE_URL}{image_url}") - return target_product - - def to_json(self, **kwargs): - """ - Convert the metadata of the object to a JSON string. - - Args: - **kwargs: Additional keyword arguments to be passed to the json.dumps() function. - - Returns: - str: A JSON string representation of the metadata. - - """ - return json.dumps(self.metadata, **kwargs) - - def to_dict(self): - return self.metadata.copy() - - class DataCiteSchema(ABC): SCHEMA_VERSION = "http://datacite.org/schema/kernel-4" @@ -3160,7 +3069,7 @@ def convert(cls, codebase: Codebase): metadata["relatedIdentifiers"] = [] # assumes that all peer reviewed releases have been issued a DOI before issuing a DOI for the parent Codebase - for release in codebase.ordered_releases(): + for release in codebase.ordered_releases_list(): if release.doi: metadata["relatedIdentifiers"].append( { diff --git a/django/library/serializers.py b/django/library/serializers.py index 7471a5f1c..8a1edafbd 100644 --- a/django/library/serializers.py +++ b/django/library/serializers.py @@ -642,18 +642,14 @@ def update(self, instance, validated_data): many=True, data=validated_data.pop("platform_tags") ) - raw_license = validated_data.pop("license") - existing_license = License.objects.get(name=raw_license["name"]) - set_tags(instance, programming_languages, "programming_languages") set_tags(instance, platform_tags, "platform_tags") - instance = super().update(instance, validated_data) - + raw_license = validated_data.pop("license") + existing_license = License.objects.get(name=raw_license["name"]) instance.license = existing_license - instance.save() - return instance + return super().update(instance, validated_data) def save_release_contributors( self, diff --git a/django/library/tasks.py b/django/library/tasks.py index 6de220501..239d79460 100644 --- a/django/library/tasks.py +++ b/django/library/tasks.py @@ -1,11 +1,15 @@ from huey.contrib.djhuey import db_task +from .models import Codebase, CodebaseRelease import logging logger = logging.getLogger(__name__) -@db_task(retries=3, retry_delay=30) -def example_task(): - pass +@db_task(retries=1, retry_delay=30) +def update_fs_release_metadata(release_id: int): + release = CodebaseRelease.objects.get(id=release_id) + codebase = release.codebase + fs_api = release.get_fs_api() + fs_api.rebuild(metadata_only=True) diff --git a/django/library/tests/base.py b/django/library/tests/base.py index 644f85c01..f4f3abcc3 100644 --- a/django/library/tests/base.py +++ b/django/library/tests/base.py @@ -55,7 +55,7 @@ def create_published_release(self, codebase=None, **kwargs): **kwargs, defaults=self.get_default_data() ) release = ReleaseSetup.setUpPublishableDraftRelease(codebase) - release.publish(defer_fs=True) + release.publish() return release diff --git a/django/library/tests/test_views.py b/django/library/tests/test_views.py index 6e4c390e3..3d8040ffc 100644 --- a/django/library/tests/test_views.py +++ b/django/library/tests/test_views.py @@ -562,7 +562,7 @@ def test_publish_codebaserelease(self): self.assertRaises(ValidationError, lambda: self.codebase_release.publish()) self.codebase_release.programming_languages.add("Java") - + self.codebase_release.save() self.codebase_release.publish() download_response = self.client.get( diff --git a/django/library/views.py b/django/library/views.py index 94f6ca201..804d89b2e 100644 --- a/django/library/views.py +++ b/django/library/views.py @@ -822,6 +822,8 @@ def contributors(self, request, **kwargs): ) crs.is_valid(raise_exception=True) crs.save() + # trigger a re-generation of release codemeta by saving + codebase_release.save() return Response(status=status.HTTP_204_NO_CONTENT) @action(detail=True, methods=["post"]) From f0bda6a8e025dd58f49cf0eef2f57988e8158221 Mon Sep 17 00:00:00 2001 From: sgfost Date: Fri, 10 Jan 2025 11:48:34 -0700 Subject: [PATCH 06/31] refactor: datacite generation from codemeta usage of the old datacite metadata generation still needs to be replaced --- django/library/metadata.py | 327 +++++++++++++++++++++++++------------ django/library/models.py | 29 ++-- django/library/views.py | 3 +- 3 files changed, 241 insertions(+), 118 deletions(-) diff --git a/django/library/metadata.py b/django/library/metadata.py index 1e78a51b2..8b74dd243 100644 --- a/django/library/metadata.py +++ b/django/library/metadata.py @@ -5,7 +5,6 @@ Person, Organization, Role, - CreativeWork, ) from codemeticulous.cff.models import CitationFileFormat from codemeticulous.datacite.models import DataCite @@ -46,73 +45,142 @@ def convert_affiliation(cls, affiliation: dict) -> Organization: ) @classmethod - def convert_release_contributors( + def _convert_actor( + cls, contributor, actor_type: Literal["author", "contributor"], index: int + ) -> Person | Organization: + # https://www.w3.org/TR/json-ld11/#identifying-blank-nodes + actor_id = contributor.orcid_url or f"_:{actor_type}_{index + 1}" + if contributor.is_organization: + return Organization( + id_=actor_id, + name=contributor.name, + ) + elif contributor.is_person: + affiliation = ( + cls.convert_affiliation(contributor.primary_affiliation) + if contributor.primary_affiliation + else None + ) + return Person( + id_=actor_id, + givenName=contributor.get_given_name() or None, + familyName=contributor.get_family_name() or None, + affiliation=affiliation, + email=contributor.email or None, + ) + else: + raise ValueError(f"Invalid actor type '{actor_type}'") + + @classmethod + def _convert_roles(cls, actor_id: str, roles: list[str]) -> list[Role]: + return [ + Role( + id_=actor_id, + roleName=role, + ) + for role in roles + if role != "author" + ] + + @classmethod + def convert_contributors( cls, - release_contributors, + contributors, actor_type: Literal["author", "contributor"], ) -> list[Person | Organization | Role]: + """converts a list of Contributor or ReleaseContributor objects to a list of codemeta actors. + If ReleaseContributors are given, the roles are also converted to codemeta/schema.org roles + """ codemeta_actors = [] codemeta_roles = [] - for num, rc in enumerate(release_contributors): - contributor = rc.contributor - # https://www.w3.org/TR/json-ld11/#identifying-blank-nodes - contributor_id = contributor.orcid_url or f"_:{actor_type}_{num + 1}" - if contributor.is_organization: - codemeta_actors.append( - Organization( - id_=contributor_id, - name=contributor.name, - ) - ) - elif contributor.is_person: - affiliation = ( - cls.convert_affiliation(contributor.primary_affiliation) - if contributor.primary_affiliation - else None - ) - codemeta_actors.append( - Person( - id_=contributor_id, - givenName=contributor.get_given_name() or None, - familyName=contributor.get_family_name() or None, - affiliation=affiliation, - email=contributor.email or None, - ) + for index, contributor_or_rc in enumerate(contributors): + contributor = ( + contributor_or_rc.contributor + if hasattr(contributor_or_rc, "contributor") + else contributor_or_rc + ) + actor = cls._convert_actor(contributor, actor_type, index) + codemeta_actors.append(actor) + if hasattr(contributor_or_rc, "roles"): + codemeta_roles.extend( + cls._convert_roles(actor.id_, contributor_or_rc.roles) ) - - for role in rc.roles: - if role != "author": - codemeta_roles.append( - Role( - id_=contributor_id, - roleName=role, - ) - ) - return codemeta_actors + codemeta_roles @classmethod - def to_textual_creative_work(cls, text: str) -> CreativeWork: + def to_textual_creative_work(cls, text: str) -> dict: return { "@type": "CreativeWork", "text": text, } + @classmethod + def license_to_creative_work(cls, license) -> dict: + return { + "@type": "CreativeWork", + "name": license.name, + "url": license.url, + } + + @classmethod + def _common_codebase_fields(cls, codebase) -> dict: + return dict( + type_="SoftwareSourceCode", + name=codebase.title, + codeRepository=codebase.repository_url or None, + applicationCategory="Computational Model", + citation=[ + cls.to_textual_creative_work(text) + for text in [ + codebase.references_text, + codebase.replication_text, + ] + if text + ] + or None, + # tags are sorted so that comparisons are deterministic + keywords=[tag.name for tag in codebase.tags.all().order_by("name")] or None, + publisher=cls.COMSES_ORGANIZATION, + description=codebase.description.raw, + referencePublication=codebase.associated_publication_text or None, + ) + + @classmethod + def _convert_codebase(cls, codebase) -> CodeMeta: + return CodeMeta( + **cls._common_codebase_fields(codebase), + id_=codebase.permanent_url, + identifier=( + [codebase.doi, codebase.permanent_url] + if codebase.doi + else codebase.permanent_url + ), + author=cls.convert_contributors(codebase.all_author_contributors, "author") + or None, + contributor=cls.convert_contributors( + codebase.all_nonauthor_contributors, "contributor" + ) + or None, + dateCreated=codebase.date_created.date(), + datePublished=( + codebase.last_published_on.date() + if codebase.last_published_on + else None + ), + url=codebase.permanent_url, + ) + @classmethod def _convert_release(cls, release) -> CodeMeta: codebase = release.codebase return CodeMeta( - type_="SoftwareSourceCode", + **cls._common_codebase_fields(codebase), id_=release.permanent_url, identifier=( [release.doi, release.permanent_url] if release.doi else release.permanent_url ), - name=codebase.title, - # FIXME: is this semantically correct? - # isPartOf=COMSES_MODEL_LIBRARY_CREATIVE_WORK, - codeRepository=codebase.repository_url or None, programmingLanguage=[ # FIXME: this can include "version" when langs are refactored {"@type": "ComputerLanguage", "name": pl.name} @@ -125,53 +193,40 @@ def _convert_release(cls, release) -> CodeMeta: # FIXME: anything to use this for? it can be either the target os or target # framework (e.g. Mesa, NetLogo) but these are both already covered # targetProduct=release.os, - applicationCategory="Computational Model", - # applicationSubCategory="Agent-Based Model", <-- would be nice downloadUrl=f"{settings.BASE_URL}{release.get_download_url()}", operatingSystem=release.os, releaseNotes=release.release_notes.raw, supportingData=release.output_data_url or None, - author=cls.convert_release_contributors( + author=cls.convert_contributors( release.author_release_contributors, "author" ) or None, - citation=[ - cls.to_textual_creative_work(text) - for text in [ - codebase.references_text, - codebase.replication_text, - ] - if text - ] - or None, - contributor=cls.convert_release_contributors( + contributor=cls.convert_contributors( release.nonauthor_release_contributors, "contributor" ) or None, copyrightYear=( release.last_published_on.year if release.last_published_on else None ), - dateCreated=codebase.date_created.date(), + dateCreated=release.date_created.date(), dateModified=( release.last_modified.date() if release.last_modified else None ), datePublished=( release.last_published_on.date() if release.last_published_on else None ), - # tags are sorted so that comparisons are deterministic - keywords=[tag.name for tag in codebase.tags.all().order_by("name")] or None, - license=release.license.url if release.license else None, - publisher=cls.COMSES_ORGANIZATION, + license=( + cls.license_to_creative_work(release.license) + if release.license + else None + ), version=release.version_number, - description=codebase.description.raw, url=release.permanent_url, embargoEndDate=release.embargo_end_date, - referencePublication=codebase.associated_publication_text or None, ) @classmethod - def _convert_release_minimal(cls, release) -> CodeMeta: - codebase = release.codebase + def _convert_codebase_minimal(cls, codebase) -> CodeMeta: return CodeMeta( type_="SoftwareSourceCode", name=codebase.title, @@ -184,18 +239,20 @@ def convert_release(cls, release) -> CodeMeta: except Exception as e: # in case something goes horribly wrong, log the error and return a valid but # minimal codemeta object - logger.exception("Error when generating codemeta: %s", e) - return cls._convert_release_minimal(release) + logger.exception( + f"Error when generating codemeta for release {release}: {e}" + ) + return cls._convert_codebase_minimal(release.codebase) @classmethod def convert_codebase(cls, codebase) -> CodeMeta: - # TODO: finish this, should extract common stuff from create_release - return CodeMeta( - type_="SoftwareSourceCode", - id_=codebase.permanent_url, - name=codebase.title, - publisher=cls.COMSES_ORGANIZATION, - ) + try: + return cls._convert_codebase(codebase) + except Exception as e: + logger.exception( + f"Error when generating codemeta for codebase {codebase}: {e}" + ) + return cls._convert_codebase_minimal(codebase) class CitationFileFormatConverter: @@ -205,47 +262,113 @@ class CitationFileFormatConverter: def convert_release( cls, release, codemeta: CodeMeta | dict = None ) -> CitationFileFormat: - if not codemeta: - codemeta = CodeMetaConverter.convert_release(release) - elif isinstance(codemeta, dict): - try: - codemeta = CodeMeta(**codemeta) - except: - codemeta = None + codemeta = coerce_codemeta(codemeta, release=release) return convert("codemeta", "cff", codemeta) class DataCiteConverter: """Create datacite metadata objects that represent the metadata for a codebase or release.""" + @classmethod + def get_formats(cls): + return ["text/plain"] + + @classmethod + def to_related_identifier( + cls, related_identifier: str, relation_type: str, related_identifier_type="DOI" + ): + return { + "relatedIdentifier": related_identifier, + "relatedIdentifierType": related_identifier_type, + "relationType": relation_type, + } + + @classmethod + def get_release_related_identifiers(cls, release): + related_identifiers = [] + if release.codebase.doi: + related_identifiers.append( + cls.to_related_identifier(release.codebase.doi, "IsVersionOf") + ) + previous_release = release.get_previous_release() + next_release = release.get_next_release() + # set relationship to previous_release + if previous_release and previous_release.doi: + related_identifiers.append( + cls.to_related_identifier(previous_release.doi, "IsNewVersionOf") + ) + + # set relationship to next_release + if next_release and next_release.doi: + related_identifiers.append( + cls.to_related_identifier(next_release.doi, "IsPreviousVersionOf") + ) + return related_identifiers or None + + @classmethod + def get_codebase_related_identifiers(cls, codebase): + # other identifiers to consider? (too many, prioritize which ones) + # IsReviewedBy, IsRequiredBy, IsDocumentedBy, IsReferencedBy, IsVariantOf, IsDerivedFrom, Obsoletes, IsObsoletedBy, IsCitedBy, IsSupplementTo, IsSupplementedBy + return [ + cls.to_related_identifier(release.doi, "HasVersion") + for release in codebase.ordered_releases_list() + if release.doi + ] or None + + @classmethod + def get_codebase_descriptions(cls, codebase): + return [ + { + "description": codebase.description.raw, + "descriptionType": "Abstract", + }, + { + "description": "The DOI pointing to this resource is a `concept version` representing all versions of this computational model and will always redirect to the latest version of this computational model. See https://zenodo.org/help/versioning for more details on the rationale behind a concept version DOI that rolls up all versions of a given computational model or any other digital research object.", + "descriptionType": "Other", + }, + ] + @classmethod def convert_release(cls, release, codemeta: CodeMeta | dict = None) -> DataCite: - if not codemeta: - codemeta = CodeMetaConverter.convert_release(release) - elif isinstance(codemeta, dict): - try: - codemeta = CodeMeta(**codemeta) - except: - codemeta = None + codemeta = coerce_codemeta(codemeta, release=release) # datacite always needs a publication date if not codemeta.datePublished: codemeta.datePublished = date.today() - # any additional fields that cannot be derived from codemeta - addl_datacite_fields = {} - return convert("codemeta", "datacite", codemeta, **addl_datacite_fields) + return convert( + "codemeta", + "datacite", + codemeta, + formats=cls.get_formats(), + relatedIdentifiers=cls.get_release_related_identifiers(release), + ) @classmethod def convert_codebase(cls, codebase, codemeta: CodeMeta | dict = None) -> DataCite: - if not codemeta: - codemeta = CodeMetaConverter.convert_codebase(codebase) - elif isinstance(codemeta, dict): - try: - codemeta = CodeMeta(**codemeta) - except: - codemeta = None + codemeta = coerce_codemeta(codemeta, codebase=codebase) # datacite always needs a publication date if not codemeta.datePublished: codemeta.datePublished = date.today() - # any additional fields that cannot be derived from codemeta - addl_datacite_fields = {} - return convert("codemeta", "datacite", codemeta, **addl_datacite_fields) + return convert( + "codemeta", + "datacite", + codemeta, + # any additional fields that cannot be derived from codemeta + descriptions=cls.get_codebase_descriptions(codebase), + relatedIdentifiers=cls.get_codebase_related_identifiers(codebase), + ) + + +def coerce_codemeta(codemeta: dict | CodeMeta, codebase=None, release=None) -> CodeMeta: + """make sure that codemeta is a CodeMeta object. If we didn't receive anything, + try to re-generate it""" + if not codemeta: + if codebase: + codemeta = CodeMetaConverter.convert_codebase(codebase) + elif release: + codemeta = CodeMetaConverter.convert_release(release) + elif isinstance(codemeta, dict): + try: + codemeta = CodeMeta(**codemeta) + except: + codemeta = None + return codemeta diff --git a/django/library/models.py b/django/library/models.py index 85e9dfff3..e2c1e7c73 100644 --- a/django/library/models.py +++ b/django/library/models.py @@ -653,11 +653,11 @@ def datacite(self): return DataCiteSchema.from_codebase(self) # FIXME: replace the above datacite metadata generation with this - # @property - # def datacite(self): - # return DataCiteConverter.convert_codebase( - # self, codemeta=self.codemeta_snapshot or None - # ) + @property + def datacite_temp(self): + return DataCiteConverter.convert_codebase( + self, codemeta=self.codemeta_snapshot or None + ) @property def is_replication(self): @@ -1635,11 +1635,6 @@ def bagit_info(self): # FIXME: check codemeta for additional metadata } - @cached_property - def common_metadata(self): - """Returns a CommonMetadata object used to build specific metadata objects: for example CodeMeta or DataCite""" - return CommonMetadata(self) - @cached_property def datacite(self): if not self.live: @@ -1649,11 +1644,15 @@ def datacite(self): return DataCiteSchema.from_release(self) # FIXME: replace the above datacite metadata generation with this - # @property - # def datacite_temp(self): - # return DataCiteConverter.convert_release( - # self, codemeta=self.codemeta_snapshot or None - # ) + @property + def datacite_temp(self): + if not self.live: + logger.warning( + "Attempting to generate datacite for an unpublished release: %s", self + ) + return DataCiteConverter.convert_release( + self, codemeta=self.codemeta_snapshot or None + ) @property def codemeta(self): diff --git a/django/library/views.py b/django/library/views.py index 804d89b2e..57949783e 100644 --- a/django/library/views.py +++ b/django/library/views.py @@ -822,7 +822,8 @@ def contributors(self, request, **kwargs): ) crs.is_valid(raise_exception=True) crs.save() - # trigger a re-generation of release codemeta by saving + # re-generate codemeta + codebase_release.codebase.save(rebuild_metadata=False) codebase_release.save() return Response(status=status.HTTP_204_NO_CONTENT) From 1f4dd6404a92e4b3bb8322aa45acd69905b564cf Mon Sep 17 00:00:00 2001 From: sgfost Date: Fri, 10 Jan 2025 13:59:36 -0700 Subject: [PATCH 07/31] refactor: replace json.loads(obj.json()) idiom --- .../management/commands/update_codebase_metadata.py | 2 +- django/library/models.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/django/library/management/commands/update_codebase_metadata.py b/django/library/management/commands/update_codebase_metadata.py index 6010aff59..cc3eecc86 100644 --- a/django/library/management/commands/update_codebase_metadata.py +++ b/django/library/management/commands/update_codebase_metadata.py @@ -33,7 +33,7 @@ def update_codemeta(self, model): errors = [] for obj in objects: try: - fresh_codemeta = json.loads(obj.codemeta.json()) + fresh_codemeta = obj.codemeta.dict(serialize=True) model.objects.filter(pk=obj.pk).update(codemeta_snapshot=fresh_codemeta) except Exception as e: errors.append((obj, e)) diff --git a/django/library/models.py b/django/library/models.py index e2c1e7c73..f29bd019f 100644 --- a/django/library/models.py +++ b/django/library/models.py @@ -1031,7 +1031,7 @@ def create_release( def save(self, rebuild_metadata=True, **kwargs): if rebuild_metadata: logger.debug("Building codemeta for codebase: %s", self) - self.codemeta_snapshot = json.loads(self.codemeta.json()) + self.codemeta_snapshot = self.codemeta.dict(serialize=True) super().save(**kwargs) # saving releases will trigger metadata rebuilding and updating # the fs and git mirror if one exists @@ -1674,7 +1674,7 @@ def codemeta_json_str(self): @property def cff_yaml_str(self): """yaml-formatted string of the cff metadata""" - return yaml.dump(json.loads(self.cff.json()), default_flow_style=False) + return yaml.dump(self.cff.dict(serialize=True), default_flow_style=False) @cached_property def license_text(self) -> str: @@ -1777,7 +1777,7 @@ def _publish(self): codebase.save(rebuild_metadata=False) # normally, rebuilding metadata is asynchronous and automatic but # here we need to build it synchronously after setting everything - self.codemeta_snapshot = json.loads(self.codemeta.json()) + self.codemeta_snapshot = self.codemeta.dict(serialize=True) self.save(rebuild_metadata=False) self.get_fs_api().rebuild(metadata_only=True) @@ -1839,7 +1839,7 @@ def set_version_number(self, version_number): self.version_number = version_number def cache_codemeta(self): - self.codemeta_snapshot = json.loads(self.codemeta.json()) + self.codemeta_snapshot = self.codemeta.dict(serialize=True) self.save(rebuild_metadata=False) def save(self, rebuild_metadata=True, **kwargs): @@ -1848,7 +1848,7 @@ def save(self, rebuild_metadata=True, **kwargs): else: logger.debug("Building codemeta for release: %s", self) old_codemeta = self.codemeta_snapshot - self.codemeta_snapshot = json.loads(self.codemeta.json()) + self.codemeta_snapshot = self.codemeta.dict(serialize=True) super().save(**kwargs) if old_codemeta != self.codemeta_snapshot: From 9cbc597fd303f6aaf52541dbab46f00395de15e5 Mon Sep 17 00:00:00 2001 From: sgfost Date: Mon, 13 Jan 2025 15:14:50 -0700 Subject: [PATCH 08/31] fix: properly transform output data url to codemeta * visually indicate that the release metadata form is saving, since this takes a little bit longer now --- django/library/metadata.py | 13 ++++++++++++- .../components/releaseEditor/MetadataFormPage.vue | 12 +++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/django/library/metadata.py b/django/library/metadata.py index 8b74dd243..8d3c786e8 100644 --- a/django/library/metadata.py +++ b/django/library/metadata.py @@ -122,6 +122,13 @@ def license_to_creative_work(cls, license) -> dict: "url": license.url, } + @classmethod + def url_to_datafeed(cls, url: str) -> dict: + return { + "@type": "DataFeed", + "url": url, + } + @classmethod def _common_codebase_fields(cls, codebase) -> dict: return dict( @@ -196,7 +203,11 @@ def _convert_release(cls, release) -> CodeMeta: downloadUrl=f"{settings.BASE_URL}{release.get_download_url()}", operatingSystem=release.os, releaseNotes=release.release_notes.raw, - supportingData=release.output_data_url or None, + supportingData=( + cls.url_to_datafeed(release.output_data_url) + if release.output_data_url + else None + ), author=cls.convert_contributors( release.author_release_contributors, "author" ) diff --git a/frontend/src/components/releaseEditor/MetadataFormPage.vue b/frontend/src/components/releaseEditor/MetadataFormPage.vue index 770462320..ac83e218a 100644 --- a/frontend/src/components/releaseEditor/MetadataFormPage.vue +++ b/frontend/src/components/releaseEditor/MetadataFormPage.vue @@ -87,8 +87,14 @@ - @@ -152,7 +158,7 @@ type ReleaseMetadataFields = yup.InferType; const isLoading = ref(true); -const { serverErrors, update } = useReleaseEditorAPI(); +const { serverErrors, update, isLoading: isSubmitLoading } = useReleaseEditorAPI(); const { errors, handleSubmit, values, setValues } = useForm({ schema, From b6d93cdd12dc0355f0145f4a0057d5a6ae090bb0 Mon Sep 17 00:00:00 2001 From: sgfost Date: Wed, 15 Jan 2025 17:31:40 -0700 Subject: [PATCH 09/31] test: disable test_codemeta, add test_metadata and resolve some edge case bugs with metadata generation. test_codemeta was primarily checking to make sure that codemeta was conforming to the expected schema, and this is implicit now we may still want some test module that uses hypothesis, but it would be even more useful to do this at a higher level e.g. create a bunch of codebase+releases and see if anything goes wrong downstream --- django/core/settings/e2e.py | 2 +- django/core/settings/test.py | 2 +- django/library/metadata.py | 10 +- django/library/models.py | 37 +- django/library/tests/test_codemeta.py | 1076 ++++++++++++------------- django/library/tests/test_metadata.py | 93 +++ 6 files changed, 659 insertions(+), 561 deletions(-) create mode 100644 django/library/tests/test_metadata.py diff --git a/django/core/settings/e2e.py b/django/core/settings/e2e.py index a7bc69622..7c9e72a67 100644 --- a/django/core/settings/e2e.py +++ b/django/core/settings/e2e.py @@ -7,7 +7,7 @@ SHARE_DIR = path.realpath("/shared/e2e") LIBRARY_ROOT = path.join(SHARE_DIR, "library") LIBRARY_PREVIOUS_ROOT = path.join(SHARE_DIR, ".latest") -REPOSITORY_ROOT = path.join(BASE_DIR, "repository") +REPOSITORY_ROOT = path.join(SHARE_DIR, "repository") BACKUP_ROOT = path.join(SHARE_DIR, "backups") BORG_ROOT = path.join(BACKUP_ROOT, "repo") EXTRACT_ROOT = path.join(SHARE_DIR, "extract") diff --git a/django/core/settings/test.py b/django/core/settings/test.py index be685f1fd..f699cc030 100644 --- a/django/core/settings/test.py +++ b/django/core/settings/test.py @@ -18,7 +18,7 @@ SHARE_DIR = path.realpath("library/tests/tmp") LIBRARY_ROOT = path.join(SHARE_DIR, "library") LIBRARY_PREVIOUS_ROOT = path.join(SHARE_DIR, ".latest") -REPOSITORY_ROOT = path.join(BASE_DIR, "repository") +REPOSITORY_ROOT = path.join(SHARE_DIR, "repository") BACKUP_ROOT = path.join(SHARE_DIR, "backups") BORG_ROOT = path.join(BACKUP_ROOT, "repo") EXTRACT_ROOT = path.join(SHARE_DIR, "extract") diff --git a/django/library/metadata.py b/django/library/metadata.py index 8d3c786e8..212cc3161 100644 --- a/django/library/metadata.py +++ b/django/library/metadata.py @@ -116,11 +116,13 @@ def to_textual_creative_work(cls, text: str) -> dict: @classmethod def license_to_creative_work(cls, license) -> dict: - return { + creative_work_license = { "@type": "CreativeWork", "name": license.name, - "url": license.url, } + if license.url: + creative_work_license["url"] = license.url + return creative_work_license @classmethod def url_to_datafeed(cls, url: str) -> dict: @@ -168,7 +170,7 @@ def _convert_codebase(cls, codebase) -> CodeMeta: codebase.all_nonauthor_contributors, "contributor" ) or None, - dateCreated=codebase.date_created.date(), + dateCreated=codebase.date_created.date() if codebase.date_created else None, datePublished=( codebase.last_published_on.date() if codebase.last_published_on @@ -219,7 +221,7 @@ def _convert_release(cls, release) -> CodeMeta: copyrightYear=( release.last_published_on.year if release.last_published_on else None ), - dateCreated=release.date_created.date(), + dateCreated=release.date_created.date() if release.date_created else None, dateModified=( release.last_modified.date() if release.last_modified else None ), diff --git a/django/library/models.py b/django/library/models.py index f29bd019f..0e8252c63 100644 --- a/django/library/models.py +++ b/django/library/models.py @@ -751,7 +751,7 @@ def publication_year(self): self.last_published_on.year if self.last_published_on else date.today().year ) - @cached_property + @property def all_contributors(self): return Contributor.objects.filter( id__in=ReleaseContributor.objects.for_codebase(self).values( @@ -759,7 +759,7 @@ def all_contributors(self): ) ) - @cached_property + @property def all_author_contributors(self): return Contributor.objects.filter( id__in=ReleaseContributor.objects.authors() @@ -767,13 +767,13 @@ def all_author_contributors(self): .values("contributor_id") ) - @cached_property + @property def all_nonauthor_contributors(self): return self.all_contributors.exclude( id__in=self.all_author_contributors.values("id") ) - @cached_property + @property def all_citable_contributors(self): return Contributor.objects.filter( id__in=ReleaseContributor.objects.citable() @@ -1028,14 +1028,16 @@ def create_release( self.save() return release - def save(self, rebuild_metadata=True, **kwargs): + def save(self, rebuild_metadata=True, rebuild_release_metadata=True, **kwargs): + """save the codebase and optionally rebuild metadata by updating codemeta_snapshot. + If rebuild_release_metadata is True, all releases will be saved to trigger metadata updates""" if rebuild_metadata: logger.debug("Building codemeta for codebase: %s", self) self.codemeta_snapshot = self.codemeta.dict(serialize=True) super().save(**kwargs) # saving releases will trigger metadata rebuilding and updating # the fs and git mirror if one exists - if rebuild_metadata: + if rebuild_metadata and rebuild_release_metadata: for release in self.releases.all(): release.save(rebuild_metadata=True) @@ -1774,12 +1776,11 @@ def _publish(self): codebase.last_published_on = now if codebase.first_published_at is None: codebase.first_published_at = now - codebase.save(rebuild_metadata=False) # normally, rebuilding metadata is asynchronous and automatic but # here we need to build it synchronously after setting everything - self.codemeta_snapshot = self.codemeta.dict(serialize=True) - self.save(rebuild_metadata=False) - self.get_fs_api().rebuild(metadata_only=True) + self.save(defer_fs=False) + # and then rebuild the codebase metadata + codebase.save(rebuild_metadata=True, rebuild_release_metadata=False) @transaction.atomic def unpublish(self): @@ -1838,11 +1839,10 @@ def set_version_number(self, version_number): ) self.version_number = version_number - def cache_codemeta(self): - self.codemeta_snapshot = self.codemeta.dict(serialize=True) - self.save(rebuild_metadata=False) - - def save(self, rebuild_metadata=True, **kwargs): + def save(self, rebuild_metadata=True, defer_fs=True, **kwargs): + """save the release and optionally rebuild metadata by updating codemeta_snapshot + and rebuilding the filesystem metadata. If defer_fs is True (default), the filesystem rebuild + will be deferred to an async task""" if not rebuild_metadata: super().save(**kwargs) else: @@ -1852,9 +1852,12 @@ def save(self, rebuild_metadata=True, **kwargs): super().save(**kwargs) if old_codemeta != self.codemeta_snapshot: - from .tasks import update_fs_release_metadata + if defer_fs: + from .tasks import update_fs_release_metadata - update_fs_release_metadata(self.id) + update_fs_release_metadata(self.id) + else: + self.get_fs_api().rebuild(metadata_only=True) @classmethod def get_indexed_objects(cls): diff --git a/django/library/tests/test_codemeta.py b/django/library/tests/test_codemeta.py index 9ea5ffeb9..8167147a1 100644 --- a/django/library/tests/test_codemeta.py +++ b/django/library/tests/test_codemeta.py @@ -1,538 +1,538 @@ -import json -import jsonschema -import logging -import random -import string - -from django.contrib.auth.models import User -from hypothesis import ( - note, - settings, - strategies as st, - Verbosity, -) -from hypothesis.extra.django import TestCase -from hypothesis.stateful import ( - RuleBasedStateMachine, - initialize, - invariant, - rule, - Bundle, -) - -from core.tests.base import UserFactory -from library.models import ( - CodeMetaSchema, - CommonMetadata, - Contributor, - ReleaseContributor, - Role, -) -from .base import CodebaseFactory - -logger = logging.getLogger(__name__) -logger.setLevel(logging.ERROR) - - -MAX_PROPERTY_TEST_RUNS = 10 -MAX_STATEFUL_TEST_RUNS = 5 -MAX_STATEFUL_TEST_RULES_COUNT = 15 - -HYPOTHESIS_VERBOSITY = Verbosity.normal - -# We primarily use -# https://schema.org/SoftwareSourceCode -# and CodeMeta v3 https://w3id.org/codemeta/v3.0 -# -CODEMETA_SCHEMA = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "CodeMeta 3.0 JSON-LD Schema", - "description": "Schema for CodeMeta version 3.0 in JSON-LD format.", - "type": "object", - "required": [ - "@context", - "@id", - "@type", - "author", - "identifier", - "license", - "name", - "programmingLanguage", - "url", - ], - "properties": { - "@context": {"type": "string", "enum": ["https://w3id.org/codemeta/v3.0"]}, - "@type": {"type": "string", "enum": ["SoftwareSourceCode"]}, - "name": {"type": "string", "description": "The name of the software."}, - "author": { - "type": "array", - "description": "An array of authors for the software.", - "items": { - "type": "object", - "properties": { - "@type": {"type": "string", "enum": ["Person", "Organization"]}, - "givenName": {"type": "string"}, - "familyName": {"type": "string"}, - "email": {"type": "string"}, - "affiliation": { - "type": "object", - "properties": { - "@type": {"type": "string", "enum": ["Organization"]}, - "name": { - "type": "string", - "description": "The name of the affiliated organization.", - }, - }, - }, - }, - "required": ["@type", "givenName", "familyName"], - "minItems": 1, - }, - }, - "version": {"type": "string", "description": "The version of the software."}, - "description": { - "type": "string", - "description": "A short description of the software.", - }, - "license": { - "type": "string", - "description": "A URL to the software’s license.", - }, - "codeRepository": { - "type": "string", - "description": "A URL to the source code repository.", - }, - "issueTracker": { - "type": "string", - "description": "A URL to the issue tracker for the software.", - }, - "programmingLanguage": { - "type": "array", - "description": "The programming language(s) of the software.", - "items": { - "type": "object", - "properties": { - "@type": {"type": "string"}, - "name": {"type": "string"}, - "url": {"type": "string", "format": "uri"}, - }, - "required": ["@type", "name"], - }, - }, - "keywords": { - "type": "array", - "description": "Keywords or tags for the software.", - "items": {"type": "string"}, - }, - "softwareRequirements": { - "type": "array", - "description": "Software or hardware requirements for the software.", - "items": {"type": "string"}, - }, - "softwareSuggestions": { - "type": "array", - "description": "Recommended software to accompany this software.", - "items": {"type": "string"}, - }, - "citation": { - "type": "array", - "description": "Associated citation(s) for the software.", - "items": { - "type": "object", - "properties": { - "@type": {"type": "string"}, - "text": {"type": "string"}, - }, - "required": ["@type", "text"], - }, - }, - "identifier": {"type": "string", "format": "uri"}, - "dateCreated": { - "type": "string", - "format": "date", - "description": "The date when the software was created.", - }, - "dateModified": { - "type": "string", - "format": "date", - "description": "The date when the software was last modified.", - }, - "datePublished": { - "type": "string", - "format": "date", - "description": "The date when the software was published.", - }, - "maintainer": { - "type": "array", - "description": "An array of maintainers for the software.", - "items": { - "type": "object", - "properties": { - "@type": {"type": "string", "enum": ["Person", "Organization"]}, - "name": { - "type": "string", - "description": "The name of the maintainer.", - }, - }, - "required": ["@type", "name"], - }, - }, - "publisher": { - "type": "object", - "properties": { - "@id": {"type": "string", "format": "uri"}, - "@type": {"type": "string", "const": "Organization"}, - "name": {"type": "string"}, - "url": {"type": "string", "format": "uri"}, - }, - "required": ["@id", "@type", "name", "url"], - }, - "provider": { - "type": "object", - "properties": { - "@id": {"type": "string", "format": "uri"}, - "@type": {"type": "string", "const": "Organization"}, - "name": {"type": "string"}, - "url": {"type": "string", "format": "uri"}, - }, - "required": ["@id", "@type", "name", "url"], - }, - "targetProduct": { - "type": "object", - "properties": { - "@type": {"type": "string", "const": "SoftwareApplication"}, - "name": {"type": "string"}, - "operatingSystem": {"type": "string"}, - "applicationCategory": {"type": "string"}, - "downloadUrl": {"type": "string", "format": "uri"}, - "identifier": {"type": "string", "format": "uri"}, - "softwareRequirements": {"type": "string"}, - "softwareVersion": {"type": "string"}, - "memoryRequirements": {"type": "string"}, - "processorRequirements": {"type": "string"}, - "releaseNotes": {"type": "string"}, - "screenshot": {"type": "string", "format": "uri"}, - }, - "required": ["@type", "name"], - }, - }, -} - - -""" -Define a mapping for specific User attributes and their corresponding strategies - -ALLOW ONLY string.printable: -'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' -""" - -USER_MAPPING = { - "username": st.text(min_size=1, max_size=50, alphabet=string.printable), - "first_name": st.text(min_size=1, max_size=50, alphabet=string.printable), - "last_name": st.text(min_size=1, max_size=50, alphabet=string.printable), - "email": st.emails(), -} - -""" -This class is used to test whether a random combination of methods that affect CodeMeta will produce a valid codemeta.json -""" - - -@settings( - max_examples=MAX_STATEFUL_TEST_RUNS, - stateful_step_count=MAX_STATEFUL_TEST_RULES_COUNT, - verbosity=HYPOTHESIS_VERBOSITY, - deadline=None, - # suppress_health_check=[HealthCheck.data_too_large], -) -class CodeMetaValidationTest(RuleBasedStateMachine): - added_release_contributors = Bundle("added_release_contributors") - - def __init__(self): - self.release_contributors_count = 0 - self.release_nonauthor_contributors_count = 0 - self.release_author_contributors_count = 0 - - self.keywords_count = 0 - self.programming_languages_count = 1 - - self.user_factory = None - self.users = None - self.popped_users = None - - self.submitter = None - self.codebase = None - self.codebase_release = None - - super().__init__() - - @initialize(data=st.data()) - def setup(self, data): - """ - Runs before each test case. Some duplicated initialization here and __init__? - """ - self.release_contributors_count = 0 - self.release_nonauthor_contributors_count = 0 - self.release_author_contributors_count = 0 - - self.keywords_count = 0 - self.programming_languages_count = 1 - - """ - Generate a pool of unique users dicts - """ - unique_user_dict_pool = data.draw( - st.lists( - st.fixed_dictionaries(USER_MAPPING), - min_size=MAX_STATEFUL_TEST_RULES_COUNT, - max_size=MAX_STATEFUL_TEST_RULES_COUNT, - unique_by=(lambda x: x["username"]), - ) - ) - - """ - Create users - """ - self.user_factory = UserFactory() - self.popped_users = set() - - self.users = { - self.user_factory.get_or_create( - username=user_dict["username"], - email=user_dict["email"], - first_name=user_dict["first_name"], - last_name=user_dict["last_name"], - ) - for user_dict in unique_user_dict_pool - } - """ - Create Submitter - """ - self.submitter = self.users.pop() - - # submitter is regarded as default contributor with role=Role.AUTHOR - self.release_contributors_count += 1 - self.release_author_contributors_count += 1 - - """ - Create Codebase and CodebaseRelease - """ - codebase_factory = CodebaseFactory(submitter=self.submitter) - self.codebase_release = codebase_factory.create_published_release() - self.codebase = self.codebase_release.codebase - - @rule( - role=st.sampled_from(list(Role)), - ) - def add_unique_contributor(self, role): - # this should return a unique user - u = self.users.pop() - self.popped_users.add(u) - - contributor, created = Contributor.from_user(u) - - note(f"adding unique contributor: {contributor.name}") - - # Function under test: CodebaseRelease.add_contributor() - self.codebase_release.add_contributor(contributor, role) - self.codebase_release.save() - - # since we are always adding a unique user, the contributors count will always increase by one - self.release_contributors_count += 1 - - if role == Role.AUTHOR: - self.release_author_contributors_count += 1 - else: - self.release_nonauthor_contributors_count += 1 - - @rule( - role=st.sampled_from(list(Role)), - ) - def add_existing_contributor(self, role): - # pick an existing contributor on the release - contributor = random.choice( - Contributor.objects.filter(codebaserelease=self.codebase_release) - ) - existing_contributor_roles = ( - ReleaseContributor.objects.filter(contributor=contributor).get().roles - ) - - # Function under test: CodebaseRelease.add_contributor() - self.codebase_release.add_contributor(contributor, role) - self.codebase_release.save() - - # if an existing contributor is added again, but with AUTHOR role -> it will be considered "author" and not "nonauthor" - if Role.AUTHOR not in existing_contributor_roles and role == Role.AUTHOR: - self.release_author_contributors_count += 1 - self.release_nonauthor_contributors_count -= 1 - - @rule( - programming_language=st.text( - min_size=10, max_size=20, alphabet=string.printable - ) - ) - def add_programming_language(self, programming_language): - existing_pls = self.codebase_release.programming_languages.all() - # .lower() is used to make the test pass. - # TODO: check behaviour when adding programming_languages - lowercase_pl = programming_language.lower() - if lowercase_pl not in [pl.name for pl in existing_pls]: - self.codebase_release.programming_languages.add(lowercase_pl) - self.programming_languages_count += 1 - - @rule(keyword=st.text(min_size=1, max_size=25, alphabet=string.printable)) - def add_keyword(self, keyword): - existing_tags = self.codebase_release.codebase.tags.all() - - # adding tags is case INSENSITIVE, need to make sure that the counter is increase - # keyword should not be null or "", hence `min_size=1`! - keyword = keyword.upper() - if keyword not in [tag.name for tag in existing_tags]: - self.codebase_release.codebase.tags.add(keyword) - self.keywords_count += 1 - - @invariant() - def length_agrees(self): - """ - authors and contributors - """ - - # total number of added unique contributors should match - expected_contributors_count = self.release_contributors_count - real_contributors_count = ( - self.codebase_release.codebase_contributors.all().count() - ) - note( - f"expected contributors: {expected_contributors_count}, actual contributors: {real_contributors_count}", - ) - assert expected_contributors_count == real_contributors_count - - """ - total number of added unique authors and non-author contributors should match - """ - real_author_contributors_count = ( - ReleaseContributor.objects.authors() - .for_release(self.codebase_release) - .all() - .count() - ) - real_nonauthor_contributors_count = ( - ReleaseContributor.objects.nonauthors() - .for_release(self.codebase_release) - .all() - .count() - ) - - assert ( - expected_contributors_count - == self.release_author_contributors_count - + self.release_nonauthor_contributors_count - ) - - assert ( - expected_contributors_count - == real_author_contributors_count + real_nonauthor_contributors_count - ) - - expected_codemeta_authors_count = len( - CodeMetaSchema.convert_authors(CommonMetadata(self.codebase_release)) - ) - assert expected_codemeta_authors_count == self.release_author_contributors_count - - """ - keywords - """ - expected_keywords_count = self.keywords_count - real_keywords_count = self.codebase_release.codebase.tags.all().count() - - assert expected_keywords_count == real_keywords_count - - """ - programming_languages - """ - expected_programming_languages_count = self.programming_languages_count - real_programming_languages_count = ( - self.codebase_release.programming_languages.all().count() - ) - - assert expected_programming_languages_count == real_programming_languages_count - - """ - citations - """ - # check citations if citation has been set - # Replicate citation building mechanism from CodeMeta - # citations should include references_text, replication_text, associated_publication_text, and CodebaseRelease.citation_text - expected_citations = { - self.codebase.references_text, - self.codebase.replication_text, - self.codebase.associated_publication_text, - self.codebase_release.citation_text, - } - - fresh_codemeta = CodeMetaSchema.build(self.codebase_release) - # Extract text from CodeMeta.metadata - codemeta_citations = { - creative_work["text"] - for creative_work in fresh_codemeta.metadata["citation"] - } - assert expected_citations == codemeta_citations - - note("length_agrees() done.") - - @invariant() - def validate_against_schema(self): - """ - release.codemeta.to_json() should ALWAYS validate against CODEMETA_SCHEMA - """ - fresh_codemeta = CodeMetaSchema.build(self.codebase_release) - try: - jsonschema.validate( - json.loads(fresh_codemeta.to_json()), - schema=CODEMETA_SCHEMA, - ) - assert True, "codemeta.json is valid." - except Exception as e: - logger.error("codemeta json was invalid ", e) - assert False, f"CodeMeta validation error: {e}" - - def teardown(self): - """ - Clean up all created objects. This runs at the end of each test case - """ - note("teardown()") - # TODO: why is this check necessary? Why does hypothesis run multiple @initialize and teardown at start? - if self.codebase_release is not None: - try: - # Delete CodebaseRelease - self.codebase_release.delete() - # CodebaseRelease.objects.filter(id=self.codebase_release.id).delete() - # Delete Codebase - # Codebase.objects.filter(id=self.codebase.id).delete() - self.codebase.delete() - # Delete Submitter - self.submitter.delete() - # User.objects.filter(id=self.submitter.id).delete() - # Delete generated users which were added as contributors - User.objects.filter( - id__in=[ - user.id for user in (list(self.popped_users) + list(self.users)) - ] - ).delete() - # Delete the rest of user objects - # User.objects.filter(id__in=[user.id for user in self.users]).delete() - except Exception as err: - logger.error(f"Exception during teardown: {err}") - - note("teardown() done.") - - -""" -This class is used to run CodeMetaValidationTest -""" - - -class StatefulCodeMetaValidationTest(CodeMetaValidationTest.TestCase, TestCase): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) +# import json +# import jsonschema +# import logging +# import random +# import string + +# from django.contrib.auth.models import User +# from hypothesis import ( +# note, +# settings, +# strategies as st, +# Verbosity, +# ) +# from hypothesis.extra.django import TestCase +# from hypothesis.stateful import ( +# RuleBasedStateMachine, +# initialize, +# invariant, +# rule, +# Bundle, +# ) + +# from core.tests.base import UserFactory +# from library.models import ( +# CodeMetaSchema, +# CommonMetadata, +# Contributor, +# ReleaseContributor, +# Role, +# ) +# from .base import CodebaseFactory + +# logger = logging.getLogger(__name__) +# logger.setLevel(logging.ERROR) + + +# MAX_PROPERTY_TEST_RUNS = 10 +# MAX_STATEFUL_TEST_RUNS = 5 +# MAX_STATEFUL_TEST_RULES_COUNT = 15 + +# HYPOTHESIS_VERBOSITY = Verbosity.normal + +# # We primarily use +# # https://schema.org/SoftwareSourceCode +# # and CodeMeta v3 https://w3id.org/codemeta/v3.0 +# # +# CODEMETA_SCHEMA = { +# "$schema": "https://json-schema.org/draft/2020-12/schema", +# "title": "CodeMeta 3.0 JSON-LD Schema", +# "description": "Schema for CodeMeta version 3.0 in JSON-LD format.", +# "type": "object", +# "required": [ +# "@context", +# "@id", +# "@type", +# "author", +# "identifier", +# "license", +# "name", +# "programmingLanguage", +# "url", +# ], +# "properties": { +# "@context": {"type": "string", "enum": ["https://w3id.org/codemeta/v3.0"]}, +# "@type": {"type": "string", "enum": ["SoftwareSourceCode"]}, +# "name": {"type": "string", "description": "The name of the software."}, +# "author": { +# "type": "array", +# "description": "An array of authors for the software.", +# "items": { +# "type": "object", +# "properties": { +# "@type": {"type": "string", "enum": ["Person", "Organization"]}, +# "givenName": {"type": "string"}, +# "familyName": {"type": "string"}, +# "email": {"type": "string"}, +# "affiliation": { +# "type": "object", +# "properties": { +# "@type": {"type": "string", "enum": ["Organization"]}, +# "name": { +# "type": "string", +# "description": "The name of the affiliated organization.", +# }, +# }, +# }, +# }, +# "required": ["@type", "givenName", "familyName"], +# "minItems": 1, +# }, +# }, +# "version": {"type": "string", "description": "The version of the software."}, +# "description": { +# "type": "string", +# "description": "A short description of the software.", +# }, +# "license": { +# "type": "string", +# "description": "A URL to the software’s license.", +# }, +# "codeRepository": { +# "type": "string", +# "description": "A URL to the source code repository.", +# }, +# "issueTracker": { +# "type": "string", +# "description": "A URL to the issue tracker for the software.", +# }, +# "programmingLanguage": { +# "type": "array", +# "description": "The programming language(s) of the software.", +# "items": { +# "type": "object", +# "properties": { +# "@type": {"type": "string"}, +# "name": {"type": "string"}, +# "url": {"type": "string", "format": "uri"}, +# }, +# "required": ["@type", "name"], +# }, +# }, +# "keywords": { +# "type": "array", +# "description": "Keywords or tags for the software.", +# "items": {"type": "string"}, +# }, +# "softwareRequirements": { +# "type": "array", +# "description": "Software or hardware requirements for the software.", +# "items": {"type": "string"}, +# }, +# "softwareSuggestions": { +# "type": "array", +# "description": "Recommended software to accompany this software.", +# "items": {"type": "string"}, +# }, +# "citation": { +# "type": "array", +# "description": "Associated citation(s) for the software.", +# "items": { +# "type": "object", +# "properties": { +# "@type": {"type": "string"}, +# "text": {"type": "string"}, +# }, +# "required": ["@type", "text"], +# }, +# }, +# "identifier": {"type": "string", "format": "uri"}, +# "dateCreated": { +# "type": "string", +# "format": "date", +# "description": "The date when the software was created.", +# }, +# "dateModified": { +# "type": "string", +# "format": "date", +# "description": "The date when the software was last modified.", +# }, +# "datePublished": { +# "type": "string", +# "format": "date", +# "description": "The date when the software was published.", +# }, +# "maintainer": { +# "type": "array", +# "description": "An array of maintainers for the software.", +# "items": { +# "type": "object", +# "properties": { +# "@type": {"type": "string", "enum": ["Person", "Organization"]}, +# "name": { +# "type": "string", +# "description": "The name of the maintainer.", +# }, +# }, +# "required": ["@type", "name"], +# }, +# }, +# "publisher": { +# "type": "object", +# "properties": { +# "@id": {"type": "string", "format": "uri"}, +# "@type": {"type": "string", "const": "Organization"}, +# "name": {"type": "string"}, +# "url": {"type": "string", "format": "uri"}, +# }, +# "required": ["@id", "@type", "name", "url"], +# }, +# "provider": { +# "type": "object", +# "properties": { +# "@id": {"type": "string", "format": "uri"}, +# "@type": {"type": "string", "const": "Organization"}, +# "name": {"type": "string"}, +# "url": {"type": "string", "format": "uri"}, +# }, +# "required": ["@id", "@type", "name", "url"], +# }, +# "targetProduct": { +# "type": "object", +# "properties": { +# "@type": {"type": "string", "const": "SoftwareApplication"}, +# "name": {"type": "string"}, +# "operatingSystem": {"type": "string"}, +# "applicationCategory": {"type": "string"}, +# "downloadUrl": {"type": "string", "format": "uri"}, +# "identifier": {"type": "string", "format": "uri"}, +# "softwareRequirements": {"type": "string"}, +# "softwareVersion": {"type": "string"}, +# "memoryRequirements": {"type": "string"}, +# "processorRequirements": {"type": "string"}, +# "releaseNotes": {"type": "string"}, +# "screenshot": {"type": "string", "format": "uri"}, +# }, +# "required": ["@type", "name"], +# }, +# }, +# } + + +# """ +# Define a mapping for specific User attributes and their corresponding strategies + +# ALLOW ONLY string.printable: +# '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' +# """ + +# USER_MAPPING = { +# "username": st.text(min_size=1, max_size=50, alphabet=string.printable), +# "first_name": st.text(min_size=1, max_size=50, alphabet=string.printable), +# "last_name": st.text(min_size=1, max_size=50, alphabet=string.printable), +# "email": st.emails(), +# } + +# """ +# This class is used to test whether a random combination of methods that affect CodeMeta will produce a valid codemeta.json +# """ + + +# @settings( +# max_examples=MAX_STATEFUL_TEST_RUNS, +# stateful_step_count=MAX_STATEFUL_TEST_RULES_COUNT, +# verbosity=HYPOTHESIS_VERBOSITY, +# deadline=None, +# # suppress_health_check=[HealthCheck.data_too_large], +# ) +# class CodeMetaValidationTest(RuleBasedStateMachine): +# added_release_contributors = Bundle("added_release_contributors") + +# def __init__(self): +# self.release_contributors_count = 0 +# self.release_nonauthor_contributors_count = 0 +# self.release_author_contributors_count = 0 + +# self.keywords_count = 0 +# self.programming_languages_count = 1 + +# self.user_factory = None +# self.users = None +# self.popped_users = None + +# self.submitter = None +# self.codebase = None +# self.codebase_release = None + +# super().__init__() + +# @initialize(data=st.data()) +# def setup(self, data): +# """ +# Runs before each test case. Some duplicated initialization here and __init__? +# """ +# self.release_contributors_count = 0 +# self.release_nonauthor_contributors_count = 0 +# self.release_author_contributors_count = 0 + +# self.keywords_count = 0 +# self.programming_languages_count = 1 + +# """ +# Generate a pool of unique users dicts +# """ +# unique_user_dict_pool = data.draw( +# st.lists( +# st.fixed_dictionaries(USER_MAPPING), +# min_size=MAX_STATEFUL_TEST_RULES_COUNT, +# max_size=MAX_STATEFUL_TEST_RULES_COUNT, +# unique_by=(lambda x: x["username"]), +# ) +# ) + +# """ +# Create users +# """ +# self.user_factory = UserFactory() +# self.popped_users = set() + +# self.users = { +# self.user_factory.get_or_create( +# username=user_dict["username"], +# email=user_dict["email"], +# first_name=user_dict["first_name"], +# last_name=user_dict["last_name"], +# ) +# for user_dict in unique_user_dict_pool +# } +# """ +# Create Submitter +# """ +# self.submitter = self.users.pop() + +# # submitter is regarded as default contributor with role=Role.AUTHOR +# self.release_contributors_count += 1 +# self.release_author_contributors_count += 1 + +# """ +# Create Codebase and CodebaseRelease +# """ +# codebase_factory = CodebaseFactory(submitter=self.submitter) +# self.codebase_release = codebase_factory.create_published_release() +# self.codebase = self.codebase_release.codebase + +# @rule( +# role=st.sampled_from(list(Role)), +# ) +# def add_unique_contributor(self, role): +# # this should return a unique user +# u = self.users.pop() +# self.popped_users.add(u) + +# contributor, created = Contributor.from_user(u) + +# note(f"adding unique contributor: {contributor.name}") + +# # Function under test: CodebaseRelease.add_contributor() +# self.codebase_release.add_contributor(contributor, role) +# self.codebase_release.save() + +# # since we are always adding a unique user, the contributors count will always increase by one +# self.release_contributors_count += 1 + +# if role == Role.AUTHOR: +# self.release_author_contributors_count += 1 +# else: +# self.release_nonauthor_contributors_count += 1 + +# @rule( +# role=st.sampled_from(list(Role)), +# ) +# def add_existing_contributor(self, role): +# # pick an existing contributor on the release +# contributor = random.choice( +# Contributor.objects.filter(codebaserelease=self.codebase_release) +# ) +# existing_contributor_roles = ( +# ReleaseContributor.objects.filter(contributor=contributor).get().roles +# ) + +# # Function under test: CodebaseRelease.add_contributor() +# self.codebase_release.add_contributor(contributor, role) +# self.codebase_release.save() + +# # if an existing contributor is added again, but with AUTHOR role -> it will be considered "author" and not "nonauthor" +# if Role.AUTHOR not in existing_contributor_roles and role == Role.AUTHOR: +# self.release_author_contributors_count += 1 +# self.release_nonauthor_contributors_count -= 1 + +# @rule( +# programming_language=st.text( +# min_size=10, max_size=20, alphabet=string.printable +# ) +# ) +# def add_programming_language(self, programming_language): +# existing_pls = self.codebase_release.programming_languages.all() +# # .lower() is used to make the test pass. +# # TODO: check behaviour when adding programming_languages +# lowercase_pl = programming_language.lower() +# if lowercase_pl not in [pl.name for pl in existing_pls]: +# self.codebase_release.programming_languages.add(lowercase_pl) +# self.programming_languages_count += 1 + +# @rule(keyword=st.text(min_size=1, max_size=25, alphabet=string.printable)) +# def add_keyword(self, keyword): +# existing_tags = self.codebase_release.codebase.tags.all() + +# # adding tags is case INSENSITIVE, need to make sure that the counter is increase +# # keyword should not be null or "", hence `min_size=1`! +# keyword = keyword.upper() +# if keyword not in [tag.name for tag in existing_tags]: +# self.codebase_release.codebase.tags.add(keyword) +# self.keywords_count += 1 + +# @invariant() +# def length_agrees(self): +# """ +# authors and contributors +# """ + +# # total number of added unique contributors should match +# expected_contributors_count = self.release_contributors_count +# real_contributors_count = ( +# self.codebase_release.codebase_contributors.all().count() +# ) +# note( +# f"expected contributors: {expected_contributors_count}, actual contributors: {real_contributors_count}", +# ) +# assert expected_contributors_count == real_contributors_count + +# """ +# total number of added unique authors and non-author contributors should match +# """ +# real_author_contributors_count = ( +# ReleaseContributor.objects.authors() +# .for_release(self.codebase_release) +# .all() +# .count() +# ) +# real_nonauthor_contributors_count = ( +# ReleaseContributor.objects.nonauthors() +# .for_release(self.codebase_release) +# .all() +# .count() +# ) + +# assert ( +# expected_contributors_count +# == self.release_author_contributors_count +# + self.release_nonauthor_contributors_count +# ) + +# assert ( +# expected_contributors_count +# == real_author_contributors_count + real_nonauthor_contributors_count +# ) + +# expected_codemeta_authors_count = len( +# CodeMetaSchema.convert_authors(CommonMetadata(self.codebase_release)) +# ) +# assert expected_codemeta_authors_count == self.release_author_contributors_count + +# """ +# keywords +# """ +# expected_keywords_count = self.keywords_count +# real_keywords_count = self.codebase_release.codebase.tags.all().count() + +# assert expected_keywords_count == real_keywords_count + +# """ +# programming_languages +# """ +# expected_programming_languages_count = self.programming_languages_count +# real_programming_languages_count = ( +# self.codebase_release.programming_languages.all().count() +# ) + +# assert expected_programming_languages_count == real_programming_languages_count + +# """ +# citations +# """ +# # check citations if citation has been set +# # Replicate citation building mechanism from CodeMeta +# # citations should include references_text, replication_text, associated_publication_text, and CodebaseRelease.citation_text +# expected_citations = { +# self.codebase.references_text, +# self.codebase.replication_text, +# self.codebase.associated_publication_text, +# self.codebase_release.citation_text, +# } + +# fresh_codemeta = CodeMetaSchema.build(self.codebase_release) +# # Extract text from CodeMeta.metadata +# codemeta_citations = { +# creative_work["text"] +# for creative_work in fresh_codemeta.metadata["citation"] +# } +# assert expected_citations == codemeta_citations + +# note("length_agrees() done.") + +# @invariant() +# def validate_against_schema(self): +# """ +# release.codemeta.to_json() should ALWAYS validate against CODEMETA_SCHEMA +# """ +# fresh_codemeta = CodeMetaSchema.build(self.codebase_release) +# try: +# jsonschema.validate( +# json.loads(fresh_codemeta.to_json()), +# schema=CODEMETA_SCHEMA, +# ) +# assert True, "codemeta.json is valid." +# except Exception as e: +# logger.error("codemeta json was invalid ", e) +# assert False, f"CodeMeta validation error: {e}" + +# def teardown(self): +# """ +# Clean up all created objects. This runs at the end of each test case +# """ +# note("teardown()") +# # TODO: why is this check necessary? Why does hypothesis run multiple @initialize and teardown at start? +# if self.codebase_release is not None: +# try: +# # Delete CodebaseRelease +# self.codebase_release.delete() +# # CodebaseRelease.objects.filter(id=self.codebase_release.id).delete() +# # Delete Codebase +# # Codebase.objects.filter(id=self.codebase.id).delete() +# self.codebase.delete() +# # Delete Submitter +# self.submitter.delete() +# # User.objects.filter(id=self.submitter.id).delete() +# # Delete generated users which were added as contributors +# User.objects.filter( +# id__in=[ +# user.id for user in (list(self.popped_users) + list(self.users)) +# ] +# ).delete() +# # Delete the rest of user objects +# # User.objects.filter(id__in=[user.id for user in self.users]).delete() +# except Exception as err: +# logger.error(f"Exception during teardown: {err}") + +# note("teardown() done.") + + +# """ +# This class is used to run CodeMetaValidationTest +# """ + + +# class StatefulCodeMetaValidationTest(CodeMetaValidationTest.TestCase, TestCase): + +# def __init__(self, *args, **kwargs): +# super().__init__(*args, **kwargs) diff --git a/django/library/tests/test_metadata.py b/django/library/tests/test_metadata.py new file mode 100644 index 000000000..dadf08e05 --- /dev/null +++ b/django/library/tests/test_metadata.py @@ -0,0 +1,93 @@ +import logging + +from core.tests.base import BaseModelTestCase, UserFactory +from .base import ( + CodebaseFactory, + ReleaseSetup, +) +from library.metadata import CodeMeta + +logger = logging.getLogger(__name__) + + +class CodebaseMetadataTestCase(BaseModelTestCase): + + def setUp(self): + self.user_factory = UserFactory() + self.submitter = self.user_factory.create( + first_name="Rob", last_name="Submitter" + ) + codebase_factory = CodebaseFactory(submitter=self.submitter) + self.codebase = codebase_factory.create() + self.release1 = ReleaseSetup.setUpPublishableDraftRelease(self.codebase) + self.release1.publish() + + def test_codebase_codemeta_updates_on_save(self): + old_codemeta_snapshot = self.codebase.codemeta_snapshot + self.codebase.description = "Updated codebase description" + self.codebase.save() + self.assertNotEqual(old_codemeta_snapshot, self.codebase.codemeta_snapshot) + + def test_codebase_codemeta_snapshot_is_valid(self): + CodeMeta(**self.codebase.codemeta_snapshot) + + def test_codebase_codemeta_snapshot_has_expected_fields(self): + snapshot = self.codebase.codemeta_snapshot + + self.assertIn("name", snapshot) + self.assertIn("@type", snapshot) + self.assertIn("@id", snapshot) + self.assertIn("author", snapshot) + self.assertIn("description", snapshot) + + def test_codebase_datacite_generation(self): + old_datacite_metadata = self.codebase.datacite_temp.dict(serialize=True) + self.codebase.description = "new description" + self.codebase.save() + new_datacite_metadata = self.codebase.datacite_temp.dict(serialize=True) + self.assertNotEqual(old_datacite_metadata, new_datacite_metadata) + + def test_release_codemeta_updates_on_save(self): + old_codemeta_snapshot = self.release1.codemeta_snapshot + self.release1.release_notes = "Updated release notes" + self.release1.save() + self.assertNotEqual(old_codemeta_snapshot, self.release1.codemeta_snapshot) + + def test_release_codemeta_snapshot_is_valid(self): + CodeMeta(**self.release1.codemeta_snapshot) + + def test_release_codemeta_snapshot_has_expected_fields(self): + snapshot = self.release1.codemeta_snapshot + + self.assertIn("name", snapshot) + self.assertIn("@type", snapshot) + self.assertIn("@id", snapshot) + self.assertIn("author", snapshot) + self.assertIn("description", snapshot) + + def test_release_datacite_generation(self): + old_datacite_metadata = self.release1.datacite_temp.dict(serialize=True) + self.release1.release_notes = "new release notes" + self.release1.save() + new_datacite_metadata = self.release1.datacite_temp.dict(serialize=True) + self.assertNotEqual(old_datacite_metadata, new_datacite_metadata) + + def test_release_metadata_files_in_package(self): + # LICENSE, CITATION.cff, codemeta.json + fs_api = self.release1.get_fs_api() + sip_contents = fs_api.list_sip_contents() + files_found = [] + + def recurse_contents(contents): + for item in contents: + if item["label"].lower() in [ + "license", + "citation.cff", + "codemeta.json", + ]: + files_found.append(item["label"]) + if "contents" in item: + recurse_contents(item["contents"]) + + recurse_contents(sip_contents["contents"]) + self.assertEqual(len(files_found), 3) From 4a571d5bee7d19e38d4caf27e722778768e04a34 Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 14:18:07 -0700 Subject: [PATCH 10/31] feat: add model for tracking git mirror of a codebase --- ...3_codebasegitmirror_codebase_git_mirror.py | 69 ++++++++++++++++ django/library/models.py | 82 ++++++++++++++++++- 2 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 django/library/migrations/0033_codebasegitmirror_codebase_git_mirror.py diff --git a/django/library/migrations/0033_codebasegitmirror_codebase_git_mirror.py b/django/library/migrations/0033_codebasegitmirror_codebase_git_mirror.py new file mode 100644 index 000000000..3d8510af1 --- /dev/null +++ b/django/library/migrations/0033_codebasegitmirror_codebase_git_mirror.py @@ -0,0 +1,69 @@ +# Generated by Django 4.2.17 on 2025-01-09 20:57 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ("library", "0032_license_text_codemeta_snapshot"), + ] + + operations = [ + migrations.CreateModel( + name="CodebaseGitMirror", + fields=[ + ( + "id", + models.AutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("date_created", models.DateTimeField(auto_now_add=True)), + ("last_modified", models.DateTimeField(auto_now=True)), + ("repository_name", models.CharField(max_length=100, unique=True)), + ( + "remote_url", + models.URLField( + blank=True, help_text="URL of mirrored remote repository" + ), + ), + ("last_local_update", models.DateTimeField(blank=True, null=True)), + ("last_remote_update", models.DateTimeField(blank=True, null=True)), + ( + "user_access_token", + models.CharField(blank=True, max_length=200, null=True), + ), + ( + "organization_login", + models.CharField(blank=True, max_length=100, null=True), + ), + ( + "local_releases", + models.ManyToManyField( + related_name="+", to="library.codebaserelease" + ), + ), + ( + "remote_releases", + models.ManyToManyField( + related_name="+", to="library.codebaserelease" + ), + ), + ], + ), + migrations.AddField( + model_name="codebase", + name="git_mirror", + field=models.OneToOneField( + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="codebase", + to="library.codebasegitmirror", + ), + ), + ] diff --git a/django/library/models.py b/django/library/models.py index 0e8252c63..3edf9f15b 100644 --- a/django/library/models.py +++ b/django/library/models.py @@ -8,11 +8,10 @@ import uuid import semver import uuid -from collections import OrderedDict from datetime import timedelta from packaging.version import Version from abc import ABC -from collections import OrderedDict, defaultdict +from collections import defaultdict from datetime import date, timedelta from django.conf import settings @@ -532,6 +531,64 @@ def updated_after(self, start_date, end_date=None, **kwargs): return new_codebases, updated_codebases, releases +class CodebaseGitMirror(models.Model): + """ + Keeps track of a git repository and its GitHub remote that were created + from a Codebase using the mirror (read-only archiving) workflow + """ + + # is_active = models.BooleanField(default=True) + date_created = models.DateTimeField(auto_now_add=True) + last_modified = models.DateTimeField(auto_now=True) + repository_name = models.CharField(max_length=100, unique=True) + remote_url = models.URLField( + blank=True, + help_text=_("URL of mirrored remote repository"), + ) + # keep track of timestamp and releases that have been mirrored locally + last_local_update = models.DateTimeField(null=True, blank=True) + local_releases = models.ManyToManyField("CodebaseRelease", related_name="+") + # keep track of timestamp and releases that have been synced to the remote + last_remote_update = models.DateTimeField(null=True, blank=True) + remote_releases = models.ManyToManyField("CodebaseRelease", related_name="+") + user_access_token = models.CharField(max_length=200, null=True, blank=True) + organization_login = models.CharField(max_length=100, null=True, blank=True) + + @property + def latest_local_release(self): + return max(self.local_releases.all(), key=lambda r: Version(r.version_number)) + + @property + def latest_remote_release(self): + return max(self.remote_releases.all(), key=lambda r: Version(r.version_number)) + + @property + def unmirrored_local_releases(self): + return self.codebase.public_releases().exclude( + id__in=self.local_releases.values_list("id", flat=True) + ) + + @property + def unmirrored_remote_releases(self): + return self.local_releases.exclude( + id__in=self.remote_releases.values_list("id", flat=True) + ) + + def update_local_releases(self, new_releases: models.QuerySet | list): + if self.local_releases.exists(): + self.local_releases.add(*new_releases) + else: + self.local_releases.set(new_releases) + self.last_local_update = timezone.now() + self.save() + + def update_remote_releases(self): + releases = self.local_releases.all() + self.remote_releases.set(releases) + self.last_remote_update = timezone.now() + self.save() + + @add_to_comses_permission_whitelist class Codebase(index.Indexed, ModeratedContent, ClusterableModel): """ @@ -567,6 +624,13 @@ class Codebase(index.Indexed, ModeratedContent, ClusterableModel): on_delete=models.SET_NULL, ) + git_mirror = models.OneToOneField( + "CodebaseGitMirror", + null=True, + related_name="codebase", + on_delete=models.SET_NULL, + ) + repository_url = models.URLField( blank=True, help_text=_( @@ -745,6 +809,16 @@ def base_library_dir(self): def base_git_dir(self): return pathlib.Path(settings.REPOSITORY_ROOT, str(self.uuid)) + def create_git_mirror(self, repository_name, **kwargs): + if not self.git_mirror: + git_mirror = CodebaseGitMirror.objects.create( + repository_name=repository_name, + **kwargs, + ) + self.git_mirror = git_mirror + self.save() + return self.git_mirror + @property def publication_year(self): return ( @@ -1762,6 +1836,10 @@ def add_contributor(self, contributor: Contributor, role=Role.AUTHOR, index=None def publish(self): self.validate_publishable() self._publish() + if self.codebase.git_mirror: + from .tasks import update_mirrored_codebase + + transaction.on_commit(lambda: update_mirrored_codebase(self.codebase.id)) def _publish(self): if not self.live: From 5fc74845fa80572e7166a921d6539f428d1ef6c8 Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 14:26:45 -0700 Subject: [PATCH 11/31] feat: add codebase git repository fs api this API is responsible for managing a local git repository mirror for a comses codebase. PUBLIC release archives are commits/tags in the history. Release branches are created for each release and only added to if there is an update to metadata `build()` and `append_releases()` are the two main API methods which construct (or rebuild) a git repo and add new releases to the repo, respectively `update_release_branch()` will add a new commit containing changes to a release branch (and update main if they point to the same thing). This will mainly be used for updating metadata --- django/core/models.py | 8 + django/core/tests/base.py | 8 + django/curator/tests/test_dump_restore.py | 4 +- django/library/fs.py | 342 +++++++++++++++++- django/library/tests/base.py | 22 +- .../tests/{ => samples}/archives/.gitignore | 0 .../tests/{ => samples}/archives/invalid.zip | 0 .../archives/nestedcode/.DS_store} | 0 .../archives/nestedcode/.svn/svn_files_here | 0 .../archives/nestedcode/README.md | 0 .../archives/nestedcode/src/ex.py | 0 .../animals-model/1.0.0/code/model.py | 1 + .../animals-model/1.0.0/data/input.csv | 2 + .../animals-model/1.0.0/docs/README.txt | 3 + .../animals-model/1.0.0/results/analysis.txt | 1 + .../animals-model/2.0.0/code/animals/cow.py | 3 + .../animals-model/2.0.0/code/animals/horse.py | 3 + .../animals-model/2.0.0/code/animals/sheep.py | 3 + .../animals-model/2.0.0/code/model.py | 1 + .../animals-model/2.0.0/data/input.csv | 2 + .../animals-model/2.0.0/docs/README.md | 5 + django/library/tests/test_fs.py | 174 ++++++++- django/requirements.txt | 2 + 23 files changed, 567 insertions(+), 17 deletions(-) rename django/library/tests/{ => samples}/archives/.gitignore (100%) rename django/library/tests/{ => samples}/archives/invalid.zip (100%) rename django/library/tests/{archives/nestedcode/.DS_Store => samples/archives/nestedcode/.DS_store} (100%) rename django/library/tests/{ => samples}/archives/nestedcode/.svn/svn_files_here (100%) rename django/library/tests/{ => samples}/archives/nestedcode/README.md (100%) rename django/library/tests/{ => samples}/archives/nestedcode/src/ex.py (100%) create mode 100644 django/library/tests/samples/releases/animals-model/1.0.0/code/model.py create mode 100644 django/library/tests/samples/releases/animals-model/1.0.0/data/input.csv create mode 100644 django/library/tests/samples/releases/animals-model/1.0.0/docs/README.txt create mode 100644 django/library/tests/samples/releases/animals-model/1.0.0/results/analysis.txt create mode 100644 django/library/tests/samples/releases/animals-model/2.0.0/code/animals/cow.py create mode 100644 django/library/tests/samples/releases/animals-model/2.0.0/code/animals/horse.py create mode 100644 django/library/tests/samples/releases/animals-model/2.0.0/code/animals/sheep.py create mode 100644 django/library/tests/samples/releases/animals-model/2.0.0/code/model.py create mode 100644 django/library/tests/samples/releases/animals-model/2.0.0/data/input.csv create mode 100644 django/library/tests/samples/releases/animals-model/2.0.0/docs/README.md diff --git a/django/core/models.py b/django/core/models.py index 0d158d0d7..881e52df0 100644 --- a/django/core/models.py +++ b/django/core/models.py @@ -464,6 +464,14 @@ def github_url(self): """ return self.get_social_account_profile_url("github") + @property + def github_username(self): + github_account = self.get_social_account("github") + if github_account: + return github_account.extra_data.get("login") + else: + return None + def get_social_account_profile_url(self, provider_name): social_acct = self.get_social_account(provider_name) if social_acct: diff --git a/django/core/tests/base.py b/django/core/tests/base.py index b8e5b495c..e8f06ee64 100644 --- a/django/core/tests/base.py +++ b/django/core/tests/base.py @@ -173,5 +173,13 @@ def initialize_test_shared_folders(): ) +def clear_test_shared_folder(dir=settings.REPOSITORY_ROOT): + for fs in os.scandir(dir): + if fs.is_dir(): + shutil.rmtree(os.path.join(dir, fs.name), ignore_errors=True) + elif fs.is_file(): + os.remove(os.path.join(dir, fs.name)) + + def destroy_test_shared_folders(): shutil.rmtree(settings.SHARE_DIR, ignore_errors=True) diff --git a/django/curator/tests/test_dump_restore.py b/django/curator/tests/test_dump_restore.py index 0d232ebb9..b7b71a39b 100644 --- a/django/curator/tests/test_dump_restore.py +++ b/django/curator/tests/test_dump_restore.py @@ -19,7 +19,7 @@ from core.tests.base import EventFactory, JobFactory from library.fs import import_archive from library.models import Codebase -from library.tests.base import CodebaseFactory +from library.tests.base import CodebaseFactory, TEST_SAMPLES_DIR logger = logging.getLogger(__name__) @@ -51,7 +51,7 @@ def setUp(self): fs_api = self.release.get_fs_api() import_archive( codebase_release=self.release, - nested_code_folder_name="library/tests/archives/nestedcode", + nested_code_folder_name=TEST_SAMPLES_DIR / "archives" / "nestedcode", fs_api=fs_api, ) diff --git a/django/library/fs.py b/django/library/fs.py index bbd13f6b5..9eee5a731 100644 --- a/django/library/fs.py +++ b/django/library/fs.py @@ -1,3 +1,5 @@ +import json +import yaml import logging import mimetypes import os @@ -5,11 +7,15 @@ import shutil import tarfile import zipfile +import filecmp +from contextlib import contextmanager +from packaging.version import Version from enum import Enum from functools import total_ordering from pathlib import Path from tempfile import TemporaryDirectory -from typing import Optional +from typing import Callable, Optional +from git import Actor, GitCommandError, InvalidGitRepositoryError, Repo import bagit import rarfile @@ -17,6 +23,7 @@ from django.core.files.storage import FileSystemStorage from django.core.files.uploadedfile import File from django.urls import reverse +from django.utils import timezone from rest_framework.exceptions import ValidationError from core import fs @@ -794,6 +801,339 @@ def rebuild(self, metadata_only=False) -> MessageGroup: return msgs +class CodebaseGitRepositoryApi: + """ + Manage a (local) git repository mirror of a codebase + """ + + FILE_SIZE_LIMIT = settings.GITHUB_INDIVIDUAL_FILE_SIZE_LIMIT + MEGABYTE = 1024 * 1024 + FILE_SIZE_LIMIT_MB = FILE_SIZE_LIMIT / MEGABYTE + DEFAULT_BRANCH_NAME = "main" + RELEASE_BRANCH_PREFIX = "release/" + + def __init__(self, codebase): + self.codebase = codebase + self.mirror = codebase.git_mirror + if not self.mirror: + raise ValueError("Codebase must have a git_mirror") + self.repo_dir = Path(self.codebase.base_git_dir, str(self.repo_name)).absolute() + + @property + def repo_name(self): + return self.mirror.repository_name + + @property + def committer(self): + return Actor("CoMSES Net", settings.EDITOR_EMAIL) + + @property + def author(self): + profile = self.codebase.submitter.member_profile + author_email = ( + f"{profile.github_username}@users.noreply.github.com" + if profile.github_username + else profile.email + ) + return Actor(profile.name, author_email) + + def get_release_branch_name(self, release): + return f"{self.RELEASE_BRANCH_PREFIX}{release.version_number}" + + @classmethod + def check_file_sizes(cls, codebase): + releases = codebase.ordered_releases_list() + for release in releases: + release_fs_api = release.get_fs_api() + sip_storage = release_fs_api.get_sip_storage() + for file in sip_storage.list(absolute=True): + if file.stat().st_size > cls.FILE_SIZE_LIMIT: + file_size_mb = file.stat().st_size / cls.MEGABYTE + raise ValidationError( + f"File {file} is too large ({file_size_mb}MB), individual files must be under {cls.FILE_SIZE_LIMIT_MB}MB" + ) + + @contextmanager + def use_temporary_repo(self, from_existing=False): + """ + context manager that allows for 'atomic' operations on the git repository + by creating a temporary copy and copying it back after the block is executed + """ + original_repo_dir = self.repo_dir + with TemporaryDirectory() as tmpdir: + self.repo_dir = Path(tmpdir) + if from_existing: + shutil.copytree(original_repo_dir, self.repo_dir, dirs_exist_ok=True) + self.initialize(should_exist=True) + yield + if original_repo_dir.exists(): + shutil.rmtree(original_repo_dir) + shutil.copytree(self.repo_dir, original_repo_dir, dirs_exist_ok=True) + self.repo_dir = original_repo_dir + + def initialize(self, should_exist=False): + """ + initialize the git repository or connect to an existing one + + :param should_exist: if True, raise an error if the repository does not exist + """ + if not self.repo_dir.exists(): + if should_exist: + raise RuntimeError(f"Repository {self.repo_dir} does not exist") + self.repo_dir.mkdir(parents=True) + try: + self.repo = Repo(self.repo_dir) + except InvalidGitRepositoryError: + if should_exist: + raise RuntimeError(f"Repository {self.repo_dir} does not exist") + self.repo = Repo.init( + self.repo_dir, initial_branch=self.DEFAULT_BRANCH_NAME + ) + except Exception as e: + logger.exception(e) + raise RuntimeError(f"Failed to initialize git repository") + + def checkout_main(self): + self.repo.git.checkout(self.DEFAULT_BRANCH_NAME) + + def clear_existing_files(self): + """ + clear any existing files in the working tree (tracked or untracked) besides .git + """ + for item in self.repo_dir.iterdir(): + if item.name != ".git": + if item.is_dir(): + shutil.rmtree(item) + else: + item.unlink() + self.repo.index.remove( + [str(item.relative_to(self.repo_dir))], + working_tree=True, + r=True, + ) + + def add_release_files(self, release): + """ + copy over submission package files for a release to the working tree of the git repo + starting from a clean directory by removing all files except .git/ + """ + release_fs_api: CodebaseReleaseFsApi = release.get_fs_api() + sip_storage = release_fs_api.get_sip_storage() + self.clear_existing_files() + # copy over files from the sip storage and add to the index + # FIXME: consider moving this copy all operation to the CodebaseReleaseStorage class + for file in sip_storage.list(absolute=True): + rel_path = file.relative_to(sip_storage.location) + dest_path = self.repo_dir / rel_path + dest_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(file, dest_path) + self.repo.index.add([str(rel_path)]) + + def add_readme(self, release): + """ + add a readme file to the repository root. If one already exists somewhere, move it. + Otherwise, generate one from a template + """ + release_fs_api: CodebaseReleaseFsApi = release.get_fs_api() + sip_storage = release_fs_api.get_sip_storage() + readme_pattern = re.compile( + r"(?i)^readme(?:\.(?:markdown|mdown|mkdn|md|textile|rdoc|org|creole|mediawiki|wiki|rst|asciidoc|adoc|asc|pod|txt))?$" + ) + for file in sip_storage.list(absolute=True): + # check for an existing readme and duplicate it to the repo root + # for github to recognize. Otherwise, we'll generate one later + if readme_pattern.match(file.name): + shutil.copy(file, self.repo_dir / file.name) + self.repo.index.add([file.name]) + return + readme_content = f"# {self.codebase.title}\n\n{self.codebase.description.raw}\n" + self._add_single_file("README.md", readme_content) + + def _add_single_file(self, filename, content: str, overwrite=False): + dest_path = self.repo_dir / filename + if not dest_path.exists() or overwrite: + with dest_path.open("w") as f: + f.write(content) + self.repo.index.add([filename]) + + def commit_release(self, release, tag=True): + """ + commit the the release and tag it, should only be called after adding all necessary files + """ + # make sure the commit goes to main, then create the release branch later + # unless this is the first commit + if self.DEFAULT_BRANCH_NAME in self.repo.heads: + self.checkout_main() + commit_msg = ( + f"Release {release.version_number}\n\n{release.release_notes.raw}\n" + ) + for rc in release.coauthor_release_contributors: + contributor = rc.contributor + email = "" + # try to use the co-author's github account email, otherwise just leave it blank + if contributor.user and contributor.user.member_profile.github_username: + email = f"{contributor.user.member_profile.github_username}@users.noreply.github.com" + commit_msg += f"\nCo-authored-by: {contributor.name} <{email}>" + commit = self.repo.index.commit( + message=commit_msg, + committer=self.committer, + author=self.author, + author_date=release.last_published_on, + ) + if tag: + self.repo.create_tag(f"{release.version_number}") + return commit + + def create_release_branch(self, release, commit): + """ + create a new branch for the release + """ + release_branch_name = self.get_release_branch_name(release) + self.repo.create_head(release_branch_name, commit) + return release_branch_name + + def update_release_branch(self, release) -> Repo | None: + """ + update a release branch with new metadata, merging back into main (fast-forward) + if it is the latest release + + this ONLY updates metadata files and does not add + changes to the code, docs, etc. as it is assumed that any synced releases are published + and frozen + + returns None if no changes were made, otherwise returns the updated repo + """ + with self.use_temporary_repo(from_existing=True): + self.initialize(should_exist=True) + release_branch_name = self.get_release_branch_name(release) + # determine whether this is the latest release (i.e. points to the + # same thing as main) and should merge back into main + release_branch = self.repo.heads[release_branch_name] + main_branch = self.repo.heads[self.DEFAULT_BRANCH_NAME] + merge_into_main = (main_branch.commit == release_branch.commit) and ( + main_branch.commit == self.repo.head.commit + ) + + self.repo.git.checkout(release_branch_name) + self.add_release_files(release) + self.add_readme(release) + + # check for changes before committing + if not self.repo.is_dirty(): + return None + + commit_msg = f"Update metadata for release {release.version_number}" + self.repo.index.commit( + message=commit_msg, + committer=self.committer, + author=self.author, + author_date=timezone.now(), + ) + if merge_into_main: + self.checkout_main() + try: + self.repo.git.merge("--ff-only", release_branch_name) + except Exception as e: + logger.error( + f"Unexpected divergence when trying to merge {release_branch_name} into {self.DEFAULT_BRANCH_NAME}: {e}" + ) + self.checkout_main() + + return Repo(self.repo_dir) + + def append_releases(self, releases=None) -> Repo: + """ + add new releases to the git repository. + releases must be newer/higher than the latest mirrored release so that they can be added on top + + this should only be used if no releases have been removed or otherwise modified since these require + rewriting history and this method strictly appends new releases + + :param releases: list of releases to append, if None, all unmirrored releases will be appended + """ + self.check_file_sizes(self.codebase) + if not releases: + releases = self.mirror.unmirrored_local_releases + if not releases: + # nothing to do, return the existing repo + return Repo(self.repo_dir) + with self.use_temporary_repo(from_existing=True): + # make sure the releases are higher than the latest mirrored release + if not all( + Version(release.version_number) + > Version(self.mirror.latest_local_release.version_number) + for release in releases + ): + raise ValueError( + "Releases must be higher than the latest mirrored release to append" + ) + # make sure the releases are ordered by version number + releases = sorted(releases, key=lambda r: Version(r.version_number)) + # append releases to the git repo by adding files, committing, and creating a branch + for release in releases: + self.add_release_files(release) + self.add_readme(release) + commit = self.commit_release(release) + self.create_release_branch(release, commit) + self.checkout_main() + # record newly mirrored releases and update timestamp + self.mirror.update_local_releases(releases) + return Repo(self.repo_dir) + + def build(self) -> Repo: + """ + builds or rebuilds the git repository from codebase releases + + this will create an entirely new repository and should only be used if we are creating the + mirror for the first time or need to rebuild the entire history + """ + self.check_file_sizes(self.codebase) + releases = self.codebase.ordered_releases_list() + if not releases: + raise ValidationError("Must have at least one public release to build from") + with self.use_temporary_repo(): + self.initialize() + for release in releases: + self.add_release_files(release) + self.add_readme(release) + commit = self.commit_release(release) + self.create_release_branch(release, commit) + self.checkout_main() + # record mirrored releases and update timestamp + self.mirror.update_local_releases(releases) + return Repo(self.repo_dir) + + def update_or_build(self) -> Repo: + if self.repo_dir.exists() and self.repo_dir.joinpath(".git").exists(): + return self.append_releases() + else: + return self.build() + + def dirs_equal(self, dir1: Path, dir2: Path, ignore=[".git"]): + """ + check if two directories are equal by recursively comparing their contents + excluding the files in the ignore list (default is just .git) + + this will likely go unused in favor of a more efficient method for checking if a + release mirror (commit) is up to date + """ + dir1 = Path(dir1) + dir2 = Path(dir2) + comparison = filecmp.dircmp(dir1, dir2, ignore=ignore) + if ( + comparison.left_only + or comparison.right_only + or comparison.diff_files + or comparison.funny_files + ): + return False + else: + for subdir in comparison.common_dirs: + if not self.dirs_equal(dir1 / subdir, dir2 / subdir): + return False + return True + + class ArchiveExtractor: def __init__(self, sip_storage: CodebaseReleaseSipStorage): self.sip_storage = sip_storage diff --git a/django/library/tests/base.py b/django/library/tests/base.py index f4f3abcc3..9155a5e1f 100644 --- a/django/library/tests/base.py +++ b/django/library/tests/base.py @@ -1,5 +1,6 @@ import io import logging +from pathlib import Path import random from uuid import UUID @@ -17,6 +18,8 @@ ) from library.serializers import CodebaseSerializer +TEST_SAMPLES_DIR = Path("library/tests/samples") + logger = logging.getLogger(__name__) @@ -161,7 +164,7 @@ def setUpReviewData(cls): class ReleaseSetup: @classmethod - def setUpPublishableDraftRelease(cls, codebase): + def setUpPublishableDraftRelease(cls, codebase, with_files=True): draft_release = codebase.create_release( status=CodebaseRelease.Status.DRAFT, initialize=True, @@ -173,15 +176,14 @@ def setUpPublishableDraftRelease(cls, codebase): release_contributor_factory = ReleaseContributorFactory(draft_release) contributor = contributor_factory.create() release_contributor_factory.create(contributor) - - code_file = io.BytesIO(b"print('hello world')") - code_file.name = "some_code_file.py" - docs_file = io.BytesIO(b"# Documentation") - docs_file.name = "some_doc_file.md" - fs_api = draft_release.get_fs_api() - fs_api.add(content=code_file, category=FileCategoryDirectories.code) - fs_api.add(content=docs_file, category=FileCategoryDirectories.docs) + if with_files: + code_file = io.BytesIO(b"print('hello world')") + code_file.name = "some_code_file.py" + docs_file = io.BytesIO(b"# Documentation") + docs_file.name = "some_doc_file.md" + fs_api = draft_release.get_fs_api() + fs_api.add(content=code_file, category=FileCategoryDirectories.code) + fs_api.add(content=docs_file, category=FileCategoryDirectories.docs) draft_release.save() - return draft_release diff --git a/django/library/tests/archives/.gitignore b/django/library/tests/samples/archives/.gitignore similarity index 100% rename from django/library/tests/archives/.gitignore rename to django/library/tests/samples/archives/.gitignore diff --git a/django/library/tests/archives/invalid.zip b/django/library/tests/samples/archives/invalid.zip similarity index 100% rename from django/library/tests/archives/invalid.zip rename to django/library/tests/samples/archives/invalid.zip diff --git a/django/library/tests/archives/nestedcode/.DS_Store b/django/library/tests/samples/archives/nestedcode/.DS_store similarity index 100% rename from django/library/tests/archives/nestedcode/.DS_Store rename to django/library/tests/samples/archives/nestedcode/.DS_store diff --git a/django/library/tests/archives/nestedcode/.svn/svn_files_here b/django/library/tests/samples/archives/nestedcode/.svn/svn_files_here similarity index 100% rename from django/library/tests/archives/nestedcode/.svn/svn_files_here rename to django/library/tests/samples/archives/nestedcode/.svn/svn_files_here diff --git a/django/library/tests/archives/nestedcode/README.md b/django/library/tests/samples/archives/nestedcode/README.md similarity index 100% rename from django/library/tests/archives/nestedcode/README.md rename to django/library/tests/samples/archives/nestedcode/README.md diff --git a/django/library/tests/archives/nestedcode/src/ex.py b/django/library/tests/samples/archives/nestedcode/src/ex.py similarity index 100% rename from django/library/tests/archives/nestedcode/src/ex.py rename to django/library/tests/samples/archives/nestedcode/src/ex.py diff --git a/django/library/tests/samples/releases/animals-model/1.0.0/code/model.py b/django/library/tests/samples/releases/animals-model/1.0.0/code/model.py new file mode 100644 index 000000000..8cde7829c --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/1.0.0/code/model.py @@ -0,0 +1 @@ +print("hello world") diff --git a/django/library/tests/samples/releases/animals-model/1.0.0/data/input.csv b/django/library/tests/samples/releases/animals-model/1.0.0/data/input.csv new file mode 100644 index 000000000..29aa17e68 --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/1.0.0/data/input.csv @@ -0,0 +1,2 @@ +horses,sheep +10,15 diff --git a/django/library/tests/samples/releases/animals-model/1.0.0/docs/README.txt b/django/library/tests/samples/releases/animals-model/1.0.0/docs/README.txt new file mode 100644 index 000000000..c9be3ff53 --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/1.0.0/docs/README.txt @@ -0,0 +1,3 @@ +instructions: + +python model.py diff --git a/django/library/tests/samples/releases/animals-model/1.0.0/results/analysis.txt b/django/library/tests/samples/releases/animals-model/1.0.0/results/analysis.txt new file mode 100644 index 000000000..29fee6381 --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/1.0.0/results/analysis.txt @@ -0,0 +1 @@ +result tells us there are more sheep diff --git a/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/cow.py b/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/cow.py new file mode 100644 index 000000000..f4963717d --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/cow.py @@ -0,0 +1,3 @@ +class Cow: + def __init__(self, name): + self.name = name diff --git a/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/horse.py b/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/horse.py new file mode 100644 index 000000000..84790eaf9 --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/horse.py @@ -0,0 +1,3 @@ +class Horse: + def __init__(self, name): + self.name = name diff --git a/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/sheep.py b/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/sheep.py new file mode 100644 index 000000000..3c575356d --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/2.0.0/code/animals/sheep.py @@ -0,0 +1,3 @@ +class Sheep: + def __init__(self, name): + self.name = name diff --git a/django/library/tests/samples/releases/animals-model/2.0.0/code/model.py b/django/library/tests/samples/releases/animals-model/2.0.0/code/model.py new file mode 100644 index 000000000..8cde7829c --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/2.0.0/code/model.py @@ -0,0 +1 @@ +print("hello world") diff --git a/django/library/tests/samples/releases/animals-model/2.0.0/data/input.csv b/django/library/tests/samples/releases/animals-model/2.0.0/data/input.csv new file mode 100644 index 000000000..603cf0ed3 --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/2.0.0/data/input.csv @@ -0,0 +1,2 @@ +horses,sheep,cows +10,15,5 diff --git a/django/library/tests/samples/releases/animals-model/2.0.0/docs/README.md b/django/library/tests/samples/releases/animals-model/2.0.0/docs/README.md new file mode 100644 index 000000000..64258c3b0 --- /dev/null +++ b/django/library/tests/samples/releases/animals-model/2.0.0/docs/README.md @@ -0,0 +1,5 @@ +# instructions: + +``` +python model.py +``` \ No newline at end of file diff --git a/django/library/tests/test_fs.py b/django/library/tests/test_fs.py index 5bcd21f9a..d7923db8e 100644 --- a/django/library/tests/test_fs.py +++ b/django/library/tests/test_fs.py @@ -1,19 +1,24 @@ from pathlib import Path - +import os +from git import Repo from django.test import TestCase +from django.conf import settings from core.tests.base import ( UserFactory, destroy_test_shared_folders, initialize_test_shared_folders, + clear_test_shared_folder, ) from library.fs import ( FileCategoryDirectories, StagingDirectories, MessageLevels, import_archive, + CodebaseGitRepositoryApi, ) -from library.tests.base import CodebaseFactory +from library.tests.base import CodebaseFactory, TEST_SAMPLES_DIR +from library.models import License import logging @@ -26,7 +31,7 @@ def setUpModule(): class ArchiveExtractorTestCase(TestCase): - nested_code_folder = Path("library/tests/archives/nestedcode") + nested_code_folder = TEST_SAMPLES_DIR / "archives" / "nestedcode" def setUp(self): self.user_factory = UserFactory() @@ -70,7 +75,7 @@ def test_zipfile_saving(self): ) def test_invalid_zipfile_saving(self): - archive_name = "library/tests/archives/invalid.zip" + archive_name = str(TEST_SAMPLES_DIR / "archives" / "invalid.zip") fs_api = self.codebase_release.get_fs_api() with open(archive_name, "rb") as f: msgs = fs_api.add( @@ -86,5 +91,166 @@ def tearDownClass(cls): cls.nested_code_folder.with_suffix(".zip").unlink(missing_ok=True) +class GitRepoApiTestCase(TestCase): + model_dir = TEST_SAMPLES_DIR / "releases" / "animals-model" + release_1_dir = model_dir / "1.0.0" + release_2_dir = model_dir / "2.0.0" + + def setUp(self): + self.user_factory = UserFactory() + self.submitter = self.user_factory.create() + self.codebase_factory = CodebaseFactory(submitter=self.submitter) + self.codebase = self.codebase_factory.create() + self.release_1 = self.codebase.create_release() + self.git_mirror = self.codebase.create_git_mirror("animals-model") + + def tearDown(self): + clear_test_shared_folder(settings.REPOSITORY_ROOT) + + def test_repo_build(self): + update_release_from_sample( + self.release_1, self.release_1_dir, version_number="1.0.0" + ) + self.release_1.publish() + public_release_count = self.codebase.public_releases().count() + self.assertEqual(public_release_count, 1) + api = CodebaseGitRepositoryApi(self.codebase) + api.build() + # check that the mirror model is updated and the repo is built + self.assertIsNotNone(self.git_mirror.last_local_update) + self.assertEqual(self.git_mirror.local_releases.count(), 1) + self.assertTrue(os.path.exists(api.repo_dir)) + # check git stuff + repo = Repo(api.repo_dir) + self.assertFalse(repo.is_dirty()) + self.assertEqual(sum(1 for _ in repo.iter_commits()), public_release_count) + self.assertEqual(len(repo.tags), public_release_count) + # check contents + self.assertTrue(os.path.exists(api.repo_dir / "codemeta.json")) + self.assertTrue(os.path.exists(api.repo_dir / "CITATION.cff")) + self.assertTrue(os.path.exists(api.repo_dir / "LICENSE")) + fs_api = self.release_1.get_fs_api() + fs_api.list(StagingDirectories.sip, FileCategoryDirectories.code) + for category in ["code", "data", "docs"]: + self.assertTrue( + api.dirs_equal( + fs_api.sip_contents_dir / category, + api.repo_dir / category, + ) + ) + + def test_repo_append_releases(self): + update_release_from_sample( + self.release_1, self.release_1_dir, version_number="1.0.0" + ) + self.release_1.publish() + api = CodebaseGitRepositoryApi(self.codebase) + api.build() + self.release_2 = self.codebase.create_release() + update_release_from_sample( + self.release_2, self.release_2_dir, version_number="2.0.0" + ) + self.release_2.publish() + api.append_releases() + + self.assertEqual(self.git_mirror.local_releases.count(), 2) + # check git stuff + repo = Repo(api.repo_dir) + self.assertFalse(repo.is_dirty()) + public_release_count = self.codebase.public_releases().count() + self.assertEqual(sum(1 for _ in repo.iter_commits()), public_release_count) + self.assertEqual(len(repo.tags), public_release_count) + # check contents + self.assertTrue(os.path.exists(api.repo_dir / "codemeta.json")) + self.assertTrue(os.path.exists(api.repo_dir / "CITATION.cff")) + self.assertTrue(os.path.exists(api.repo_dir / "LICENSE")) + fs_api = self.release_2.get_fs_api() + fs_api.list(StagingDirectories.sip, FileCategoryDirectories.code) + for category in ["code", "data", "docs"]: + self.assertTrue( + api.dirs_equal( + fs_api.sip_contents_dir / category, + api.repo_dir / category, + ) + ) + + def test_will_not_append_lower_version(self): + # publish 2.0.0 first and build + update_release_from_sample( + self.release_1, self.release_1_dir, version_number="1.0.0" + ) + self.release_2 = self.codebase.create_release() + update_release_from_sample( + self.release_2, self.release_2_dir, version_number="2.0.0" + ) + self.release_2.publish() + api = CodebaseGitRepositoryApi(self.codebase) + api.build() + # now publish release 1.0.0 + self.release_1.publish() + self.assertRaises(ValueError, api.append_releases) + + def test_repo_rebuild(self): + update_release_from_sample( + self.release_1, self.release_1_dir, version_number="1.0.0" + ) + self.release_1.publish() + api = CodebaseGitRepositoryApi(self.codebase) + api.build() + self.release_2 = self.codebase.create_release() + update_release_from_sample( + self.release_2, self.release_2_dir, version_number="2.0.0" + ) + self.release_2.publish() + api.build() + + self.assertEqual(self.git_mirror.local_releases.count(), 2) + # check git stuff + repo = Repo(api.repo_dir) + self.assertFalse(repo.is_dirty()) + public_release_count = self.codebase.public_releases().count() + self.assertEqual(sum(1 for _ in repo.iter_commits()), public_release_count) + self.assertEqual(len(repo.tags), public_release_count) + # check contents + self.assertTrue(os.path.exists(api.repo_dir / "codemeta.json")) + self.assertTrue(os.path.exists(api.repo_dir / "CITATION.cff")) + self.assertTrue(os.path.exists(api.repo_dir / "LICENSE")) + fs_api = self.release_2.get_fs_api() + fs_api.list(StagingDirectories.sip, FileCategoryDirectories.code) + for category in ["code", "data", "docs"]: + self.assertTrue( + api.dirs_equal( + fs_api.sip_contents_dir / category, + api.repo_dir / category, + ) + ) + + def tearDownModule(): destroy_test_shared_folders() + + +# helpers ================================================ + + +def upload_category(fs_api, release_dir: Path, category: str): + category_path = release_dir / category + for filepath in category_path.rglob("*"): + if filepath.is_file(): + with filepath.open("rb") as f: + relpath = filepath.relative_to(category_path) + file_name = str(relpath) + fs_api.add(FileCategoryDirectories[category], content=f, name=file_name) + + +def update_release_from_sample(release, sample_dir, version_number): + release.os = "Linux" + release.programming_languages.add("Python") + release.license = License.objects.create(name="MIT") + release.release_notes = "Initial release" + release.version_number = version_number + release.save() + fs_api = release.get_fs_api() + for category in ["code", "data", "docs"]: + upload_category(fs_api, sample_dir, category) + return release diff --git a/django/requirements.txt b/django/requirements.txt index 3791b3dde..332530ab8 100644 --- a/django/requirements.txt +++ b/django/requirements.txt @@ -27,6 +27,7 @@ djangorestframework-camel-case==1.4.2 Django==4.2.17 elasticsearch-dsl>=7.0.0,<8.0.0 elasticsearch>=7.0.0,<8.0.0 +gitpython==3.1.43 html2text>=2016.9.19 huey==2.5.1 jinja2==3.1.5 @@ -37,6 +38,7 @@ nltk>=3.8.1,<4.0.0 numpy==1.26.4 pandas==2.2.2 psycopg2-binary==2.9.10 +PyGithub==2.5.0 pytz==2024.1 pyyaml>=6.0.1 # used for institution -> affiliation data migration From c109dd5ccc1d4a5ce4a9c3070fe4e03a42a527f4 Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 14:33:50 -0700 Subject: [PATCH 12/31] feat: add github integration api and mirroring tasks the GithubApi provides access to auth and repository actions adds 3 huey (async) tasks for creating a mirror, updating a mirror, and updating metadata for a single release of a mirror --- Makefile | 2 +- base.yml | 6 + deploy/conf/.env.template | 6 + django/core/settings/defaults.py | 17 ++ django/library/github_integration.py | 253 +++++++++++++++++++++++++++ django/library/tasks.py | 91 ++++++++++ 6 files changed, 374 insertions(+), 1 deletion(-) create mode 100644 django/library/github_integration.py diff --git a/Makefile b/Makefile index 7e5a24a1d..c76465fb4 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ SECRETS_DIR=${BUILD_DIR}/secrets DB_PASSWORD_PATH=${SECRETS_DIR}/db_password PGPASS_PATH=${SECRETS_DIR}/.pgpass SECRET_KEY_PATH=${SECRETS_DIR}/django_secret_key -EXT_SECRETS=hcaptcha_secret github_client_secret orcid_client_secret discourse_api_key discourse_sso_secret mail_api_key datacite_api_password +EXT_SECRETS=hcaptcha_secret github_client_secret orcid_client_secret discourse_api_key discourse_sso_secret mail_api_key datacite_api_password github_integration_app_private_key github_integration_app_client_secret GENERATED_SECRETS=$(DB_PASSWORD_PATH) $(PGPASS_PATH) $(SECRET_KEY_PATH) ENVREPLACE := deploy/scripts/envreplace diff --git a/base.yml b/base.yml index 374bbc4ce..ac7ac9fc3 100644 --- a/base.yml +++ b/base.yml @@ -67,6 +67,8 @@ services: - django_secret_key - github_client_secret - orcid_client_secret + - github_integration_app_private_key + - github_integration_app_client_secret - hcaptcha_secret - mail_api_key volumes: @@ -98,6 +100,10 @@ secrets: file: ./build/secrets/django_secret_key github_client_secret: file: ./build/secrets/github_client_secret + github_integration_app_private_key: + file: ./build/secrets/github_integration_app_private_key + github_integration_app_client_secret: + file: ./build/secrets/github_integration_app_client_secret hcaptcha_secret: file: ./build/secrets/hcaptcha_secret mail_api_key: diff --git a/deploy/conf/.env.template b/deploy/conf/.env.template index ce64ac44e..b477f1054 100644 --- a/deploy/conf/.env.template +++ b/deploy/conf/.env.template @@ -42,6 +42,12 @@ ORCID_CLIENT_ID= DATACITE_API_USERNAME= DATACITE_DRY_RUN="true" # allowed values: "true" or "false" +# github integration app +GITHUB_INTEGRATION_APP_ID= +GITHUB_INTEGRATION_APP_INSTALLATION_ID= +GITHUB_INTEGRATION_APP_CLIENT_ID= +GITHUB_MODEL_LIBRARY_ORG_NAME= + # test TEST_USER_ID=10000000 TEST_USERNAME=__test_user__ diff --git a/django/core/settings/defaults.py b/django/core/settings/defaults.py index 8302bcaa4..7c654a822 100644 --- a/django/core/settings/defaults.py +++ b/django/core/settings/defaults.py @@ -520,6 +520,23 @@ def is_test(self): GITHUB_CLIENT_ID = os.getenv("GITHUB_CLIENT_ID", "") GITHUB_CLIENT_SECRET = read_secret("github_client_secret") +GITHUB_INTEGRATION_APP_ID = int(os.getenv("GITHUB_INTEGRATION_APP_ID") or 0) +GITHUB_INTEGRATION_APP_PRIVATE_KEY = read_secret("github_integration_app_private_key") +GITHUB_INTEGRATION_APP_INSTALLATION_ID = int( + os.getenv("GITHUB_INTEGRATION_APP_INSTALLATION_ID") or 0 +) +# client id and secret are only used for getting user access tokens to be able to push +# to the user's repositories. We are not re-using the regular oauth app in order to +# keep minimal permissions +GITHUB_INTEGRATION_APP_CLIENT_ID = os.getenv("GITHUB_INTEGRATION_APP_ID", "") +GITHUB_INTEGRATION_APP_CLIENT_SECRET = read_secret( + "github_integration_app_client_secret" +) +GITHUB_MODEL_LIBRARY_ORG_NAME = os.getenv("GITHUB_MODEL_LIBRARY_ORG_NAME", "") +GITHUB_INDIVIDUAL_FILE_SIZE_LIMIT = os.getenv( + "GITHUB_INDIVIDUAL_FILE_SIZE_LIMIT", 100 * 1024 * 1024 +) + TEST_BASIC_AUTH_PASSWORD = os.getenv("TEST_BASIC_AUTH_PASSWORD", "test password") TEST_USER_ID = os.getenv("TEST_USER_ID", 1000000) TEST_USERNAME = os.getenv("TEST_USERNAME", "__test_user__") diff --git a/django/library/github_integration.py b/django/library/github_integration.py new file mode 100644 index 000000000..722d8a6b6 --- /dev/null +++ b/django/library/github_integration.py @@ -0,0 +1,253 @@ +import re +from github import GithubIntegration, Auth, Github +from github.GithubException import UnknownObjectException +from github.Repository import Repository as GithubRepo +from git import Repo as GitRepo +from django.conf import settings +from django.core.cache import cache +from django.utils import timezone + +from .models import Codebase + +INSTALLATION_ACCESS_TOKEN_REDIS_KEY = "github_installation_access_token" + + +class GithubRepoNameValidator: + @classmethod + def validate( + cls, + repo_name: str, + username: str | None = None, + user_access_token: str | None = None, + ): + cls._validate_format(repo_name) + if username and user_access_token: + cls._check_user_repo_name_unused(repo_name, username, user_access_token) + elif username: + raise ValueError("User access token required for user repository") + else: + cls._check_org_repo_name_unused(repo_name) + + @staticmethod + def _validate_format(repo_name: str): + if not re.fullmatch(r"[A-Za-z0-9_.-]+", repo_name): + raise ValueError( + "The repository name can only contain ASCII letters, digits, and the characters ., -, and _" + ) + if not (1 <= len(repo_name) <= 100): + raise ValueError("Repository name is too long (maximum is 100 characters)") + if repo_name.endswith(".git"): + raise ValueError("Repository name cannot end with '.git'") + if "github" in repo_name: + raise ValueError("Repository name cannot contain 'github'") + + @staticmethod + def _check_user_repo_name_unused( + repo_name: str, username: str, user_access_token: str + ): + if username in repo_name: + raise ValueError( + f"Repository name cannot contain your username: '{username}'" + ) + github = Github(user_access_token) + try: + github.get_user(username).get_repo(repo_name) + raise ValueError( + f"Repository name already exists at https://github.com/{username}/{repo_name}" + ) + except UnknownObjectException: + return True + + @staticmethod + def _check_org_repo_name_unused(repo_name: str): + if settings.GITHUB_MODEL_LIBRARY_ORG_NAME in repo_name: + raise ValueError( + f"Repository name cannot contain the organization name: '{settings.GITHUB_MODEL_LIBRARY_ORG_NAME}'" + ) + github = Github(GithubApi.get_installation_access_token()) + try: + github.get_organization(settings.GITHUB_MODEL_LIBRARY_ORG_NAME).get_repo( + repo_name + ) + raise ValueError( + f"Repository name already exists at https://github.com/{settings.GITHUB_MODEL_LIBRARY_ORG_NAME}/{repo_name}" + ) + except UnknownObjectException: + return True + + +class GithubApi: + """Functionality for interacting with a remote Github repository + and Github API + """ + + def __init__( + self, + codebase: Codebase, + local_repo: GitRepo, + repo_name: str, + is_user_repo=False, + organization_login: str | None = None, + user_access_token: str | None = None, + private_repo=False, + ): + if is_user_repo: + raise NotImplementedError("User repositories not yet supported") + self.private_repo = private_repo + self.codebase = codebase + self.local_repo = local_repo + self.repo_name = repo_name + self.is_user_repo = is_user_repo + if is_user_repo and not organization_login: + raise ValueError("User access token required for user repository") + if not is_user_repo and not organization_login: + raise ValueError("Organization login required for org repository") + self.organization_login = organization_login + self.user_access_token = user_access_token + self._github_repo = None + + @property + def github_repo(self) -> GithubRepo: + if not self._github_repo: + try: + self._github_repo = self._get_existing_repo() + except: + raise ValueError("Github repository not created yet") + return self._github_repo + + @property + def installation_access_token(self): + return self.get_installation_access_token() + + @classmethod + def get_installation_access_token(cls): + cached_token = cache.get(INSTALLATION_ACCESS_TOKEN_REDIS_KEY) + if cached_token: + return cached_token + return cls.refresh_installation_access_token() + + @staticmethod + def refresh_installation_access_token(): + """retrieve a new installation access token for the Github app + and cache it for future use + """ + auth = Auth.AppAuth( + settings.GITHUB_INTEGRATION_APP_ID, + settings.GITHUB_INTEGRATION_APP_PRIVATE_KEY, + ) + integration = GithubIntegration(auth=auth) + installation_auth = integration.get_access_token( + settings.GITHUB_INTEGRATION_APP_INSTALLATION_ID + ) + token = installation_auth.token + seconds_until_expiration = ( + installation_auth.expires_at - timezone.now() + ).total_seconds() + # cache the token for 1 minute less than the expiration time + cache.set( + INSTALLATION_ACCESS_TOKEN_REDIS_KEY, + token, + seconds_until_expiration - 60, + ) + return token + + @staticmethod + def get_user_access_token(code: str): + # just need to link to the app install and it will go to callback with ?code=... + """return an access token for the Github user + + this token is used to authenticate requests to the Github API + to act on behalf of the user on resources they own + """ + github = Github() + app = github.get_oauth_application( + settings.GITHUB_INTEGRATION_APP_CLIENT_ID, + settings.GITHUB_INTEGRATION_APP_CLIENT_SECRET, + ) + return app.get_access_token(code).token + + def get_or_create_repo(self) -> GithubRepo: + """get or create the Github repository for a user or organization""" + try: + return self.github_repo + except: + if self.is_user_repo: + self._github_repo = self._create_user_repo() + else: + self._github_repo = self._create_org_repo() + return self._github_repo + + def push(self, local_repo: GitRepo): + """push the local git repository to the Github repository""" + if self.is_user_repo: + raise NotImplementedError("User repositories not yet supported") + else: + token = self.installation_access_token + push_url = f"https://x-access-token:{token}@github.com/{self.github_repo.full_name}.git" + self._push_to_url(local_repo, push_url) + + def create_releases(self, local_repo: GitRepo): + """create Github releases for each tag in the local repository that + does not already have a corresponding release in the remote repository""" + for tag in local_repo.tags: + try: + existing_release = self.github_repo.get_release(tag.name) + except: + existing_release = None + if not existing_release: + self.github_repo.create_git_release( + tag.name, + name=tag.name, + message=tag.commit.message, + draft=False, + prerelease=False, + ) + + def _get_existing_repo(self): + """attempt to get an existing repository for the authenticated user or organization""" + if self.is_user_repo: + github = Github(self.user_access_token) + name = github.get_user().login + return github.get_repo(f"{name}/{self.repo_name}") + else: + github = Github(self.installation_access_token) + return github.get_repo(f"{self.organization_login}/{self.repo_name}") + + def _create_user_repo(self): + """create a new repository in the user's account + + this function requires the `repo` scope for the user access token + """ + token = self.user_access_token + if not token: + raise ValueError("User access token required for creating user repository") + github = Github(token) + repo = github.get_user().create_repo( + name=self.repo_name, + description=self.codebase.description, + private=self.private_repo, + ) + return repo + + def _create_org_repo(self): + """create a new repository in the CoMSES model library organization + + this function requires the `repo` scope for the installation access token + """ + token = self.installation_access_token + github = Github(token) + org = github.get_organization(settings.GITHUB_MODEL_LIBRARY_ORG_NAME) + repo = org.create_repo( + name=self.repo_name, + description=f"Mirror of {self.codebase.permanent_url}", + private=self.private_repo, + ) + return repo + + def _push_to_url(self, local_repo: GitRepo, push_url: str): + if "origin" not in local_repo.remotes: + local_repo.create_remote("origin", push_url) + else: + local_repo.remotes["origin"].set_url(push_url) + local_repo.git.push("--all") + local_repo.git.push("--tags") diff --git a/django/library/tasks.py b/django/library/tasks.py index 239d79460..ab2101a68 100644 --- a/django/library/tasks.py +++ b/django/library/tasks.py @@ -1,15 +1,106 @@ from huey.contrib.djhuey import db_task +from django.conf import settings from .models import Codebase, CodebaseRelease +from .github_integration import GithubApi +from .fs import CodebaseGitRepositoryApi import logging logger = logging.getLogger(__name__) +@db_task(retries=3, retry_delay=30) +def mirror_codebase(codebase_id: int, private_repo=False): + """asynchronous task that mirrors a codebase to a remote Github repository""" + codebase = Codebase.objects.get(id=codebase_id) + mirror = codebase.git_mirror + if not mirror: + raise ValueError("Codebase does not have a git mirror") + mirror.organization_login = settings.GITHUB_MODEL_LIBRARY_ORG_NAME + mirror.save() + + git_fs_api = CodebaseGitRepositoryApi(codebase) + local_repo = git_fs_api.update_or_build() + + gh_api = GithubApi( + codebase=codebase, + local_repo=local_repo, + repo_name=mirror.repository_name, + is_user_repo=False, + organization_login=mirror.organization_login, + user_access_token=mirror.user_access_token, + private_repo=private_repo, + ) + repo = gh_api.get_or_create_repo() + mirror.remote_url = repo.html_url + gh_api.push(local_repo) + gh_api.create_releases(local_repo) + mirror.update_remote_releases() + + +@db_task(retries=3, retry_delay=30) +def update_mirrored_codebase(codebase_id: int): + """asynchronous task that updates a mirrored codebase by pushing new releases to Github""" + codebase = Codebase.objects.get(id=codebase_id) + mirror = codebase.git_mirror + if not mirror: + raise ValueError("Codebase does not have a git mirror") + if not mirror.remote_url: + raise ValueError("Codebase git mirror does not have a remote url") + + git_fs_api = CodebaseGitRepositoryApi(codebase) + local_repo = git_fs_api.append_releases() + gh_api = GithubApi( + codebase=codebase, + local_repo=local_repo, + repo_name=mirror.repository_name, + is_user_repo=bool(mirror.user_access_token), + organization_login=mirror.organization_login, + user_access_token=mirror.user_access_token, + ) + gh_api.push(local_repo) + gh_api.create_releases(local_repo) + mirror.update_remote_releases() + + +@db_task(retries=3, retry_delay=30) +def update_mirrored_release_metadata(release_id: int): + """asynchronous task that updates a SINGLE RELEASE BRANCH with any metadata changes + that may have occurred. + + This should be called when release metadata has been changed + """ + release = CodebaseRelease.objects.get(id=release_id) + codebase = release.codebase + mirror = codebase.git_mirror + if not mirror: + raise ValueError("Codebase does not have a git mirror") + if not mirror.remote_url: + raise ValueError("Codebase git mirror does not have a remote url") + + git_fs_api = CodebaseGitRepositoryApi(codebase) + local_repo = git_fs_api.update_release_branch(release) + if local_repo: + gh_api = GithubApi( + codebase=codebase, + local_repo=local_repo, + repo_name=mirror.repository_name, + is_user_repo=bool(mirror.user_access_token), + organization_login=mirror.organization_login, + user_access_token=mirror.user_access_token, + ) + gh_api.push(local_repo) + mirror.update_remote_releases() + + @db_task(retries=1, retry_delay=30) def update_fs_release_metadata(release_id: int): release = CodebaseRelease.objects.get(id=release_id) codebase = release.codebase fs_api = release.get_fs_api() fs_api.rebuild(metadata_only=True) + # if the release is published and the codebase has a git mirror, + # update the metadata in the git repository + if release.is_published and codebase.git_mirror and codebase.git_mirror.remote_url: + update_mirrored_release_metadata(release_id) From c1b51d4271c4f6fd9cc368c2c3cb5a4ca0df3fb4 Mon Sep 17 00:00:00 2001 From: sgfost Date: Thu, 9 Jan 2025 14:39:27 -0700 Subject: [PATCH 13/31] feat: github integration ui and mirroring feature * /github page to describe the integration features * sidebar element on release detail page will show information about integration status for that codebase, and allow users with edit permissions to create a new mirror --- .../library/codebases/releases/retrieve.jinja | 56 +++++ .../library/github-integration-overview.jinja | 234 ++++++++++++++++++ django/library/metadata.py | 7 +- django/library/urls.py | 10 + django/library/views.py | 45 +++- frontend/src/apps/github_mirror.ts | 8 + frontend/src/components/GithubMirrorModal.vue | 93 +++++++ .../src/components/form/HoneypotField.vue | 2 +- frontend/src/composables/api/codebase.ts | 5 + frontend/src/scss/_global.scss | 32 +++ 10 files changed, 489 insertions(+), 3 deletions(-) create mode 100644 django/library/jinja2/library/github-integration-overview.jinja create mode 100644 frontend/src/apps/github_mirror.ts create mode 100644 frontend/src/components/GithubMirrorModal.vue diff --git a/django/library/jinja2/library/codebases/releases/retrieve.jinja b/django/library/jinja2/library/codebases/releases/retrieve.jinja index 7340faa89..3ba1017cf 100644 --- a/django/library/jinja2/library/codebases/releases/retrieve.jinja +++ b/django/library/jinja2/library/codebases/releases/retrieve.jinja @@ -289,6 +289,61 @@ {% endif %} {% endwith %} +{% if codebase.git_mirror or has_change_perm %} + +{% endif %} +