#!/usr/bin/env python
# encoding: utf-8

import os

from lxml import etree

from website import settings
from website.app import setup_django
setup_django()
from osf.models.citation import CitationStyle


def main():

    # drop all styles
    CitationStyle.remove()

    total = 0

    for style_file in get_style_files(settings.CITATION_STYLES_PATH):
        with open(style_file, 'r') as f:
            try:
                root = etree.parse(f).getroot()
            except etree.XMLSyntaxError:
                continue
            total += 1
            namespace = root.nsmap.get(None)
            selector = '{{{ns}}}info/{{{ns}}}'.format(ns=namespace)

            # Required
            fields = {
                '_id': os.path.splitext(os.path.basename(style_file))[0],
                'title': root.find(selector + 'title').text,
                'has_bibliography': True if root.find(
                    '{{{ns}}}{tag}'.format(ns=namespace, tag='bibliography')) is not None else False
            }

            # Optional
            try:
                fields['short_title'] = root.find(selector + "title-short").text
            except AttributeError:
                pass

            try:
                fields['summary'] = root.find(selector + 'summary').text
            except AttributeError:
                pass

            style = CitationStyle(**fields)
            style.save()

    return total


def get_style_files(path):
    files = (os.path.join(path, x) for x in os.listdir(path))
    return (f for f in files if os.path.isfile(f))


if __name__ == '__main__':
    total = main()
    print("Parsed {} styles".format(total))

@@ -34,16 +34,1061 @@
  utf-8%0A%0A
+%22%22%22%0AThis script is modified in this PR (https://github.com/CenterForOpenScience/osf.io/pull/7595)%0Ato set the corresponding %60has_bibliography%60 flag to %60False%60 for all citation formats whose CSL file do not%0Ainclude a bibliography section. As a result, all such citation formats would not show up in OSF%0Acitation widgets for users to choose.%0A%0ANOTE:%0AAs of August 25th, 2017, there are however THREE EXCEPTIONS:%0A%22Bluebook Law Review%22, %22Bluebook Law Review(2)%22 and %22Bluebook Inline%22 shares a%0Aspecial CSL file ('website/static/bluebook.cls'), in which a bibliography section is defined,%0Afor rendering bibliographies even though their official CSL files (located in assets folder)%0Ado not contain a bibliography section.%0AThe side effect is that, upon parsing all the CSL files in the assets folder, these three citation%0Aformats are marked as %60has_bibliography=False%60, preventing them from user selection on the front end.%0ATherefore, intervention is needed to manually %22turn on%22 their 'has_bibliography' flag for them to show%0Aon the citation widget.%0A%22%22%22%0A%0A
 import o
@@ -1195,16 +1195,16 @@
 jango()%0A
+
 from osf
@@ -1242,17 +1242,16 @@
 nStyle%0A%0A
-%0A
 def main

add some docs