From b19a86b54f8d0fc7af56d89e79481b115801aefa Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 10 Oct 2022 16:22:59 +0000 Subject: [PATCH 01/94] [pre-commit.ci] pre-commit autoupdate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/psf/black: 22.6.0 → 22.10.0](https://github.com/psf/black/compare/22.6.0...22.10.0) --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5401b28..1061012 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,6 +9,6 @@ repos: - id: check-yaml - id: check-added-large-files - repo: https://github.com/psf/black - rev: 22.6.0 + rev: 22.10.0 hooks: - id: black From 4fcc568b92fc959171e0688389ce1aff8395b3ef Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 Feb 2023 16:24:03 +0000 Subject: [PATCH 02/94] [pre-commit.ci] pre-commit autoupdate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/pre-commit/pre-commit-hooks: v4.3.0 → v4.4.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.3.0...v4.4.0) - [github.com/psf/black: 22.10.0 → 23.1.0](https://github.com/psf/black/compare/22.10.0...23.1.0) --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1061012..6c0ed16 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,13 +2,13 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.3.0 + rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-added-large-files - repo: https://github.com/psf/black - rev: 22.10.0 + rev: 23.1.0 hooks: - id: black From 059f4b4cdad977c51b6374310e0086ff3b398fd6 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 Feb 2023 16:26:06 +0000 Subject: [PATCH 03/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/models/activity.py | 1 - reproschema/models/base.py | 3 --- reproschema/models/item.py | 2 -- reproschema/models/protocol.py | 1 - 4 files changed, 7 deletions(-) diff --git a/reproschema/models/activity.py b/reproschema/models/activity.py index 25d27d2..0ad79e2 100644 --- a/reproschema/models/activity.py +++ b/reproschema/models/activity.py @@ -32,7 +32,6 @@ def set_defaults(self, name): self.set_ui_shuffle(False) def update_activity(self, item_info): - # TODO # - remove the hard coding on visibility and valueRequired diff --git a/reproschema/models/base.py b/reproschema/models/base.py index a2d59db..f3ecf93 100644 --- a/reproschema/models/base.py +++ b/reproschema/models/base.py @@ -10,7 +10,6 @@ class to deal with reproschema schemas schema_type = None def __init__(self, version): - URL = "https://raw.githubusercontent.com/ReproNim/reproschema/" VERSION = version or "1.0.0-rc2" @@ -47,12 +46,10 @@ def __set_defaults(self, name): self.set_description(name.replace("_", " ")) def sort_schema(self, schema_order): - reordered_dict = {k: self.schema[k] for k in schema_order} self.schema = reordered_dict def sort_ui(self, ui_order): - reordered_dict = {k: self.schema["ui"][k] for k in ui_order} self.schema["ui"] = reordered_dict diff --git a/reproschema/models/item.py b/reproschema/models/item.py index 595d67d..fc08c70 100644 --- a/reproschema/models/item.py +++ b/reproschema/models/item.py @@ -58,7 +58,6 @@ def set_input_type_as_slider(self): # self.set_response_options({"valueType": "xsd:string"}) def set_input_type_as_language(self): - URL = "https://raw.githubusercontent.com/ReproNim/reproschema/" self.set_input_type("selectLanguage") @@ -123,7 +122,6 @@ def set_input_type_as_multitext(self, max_length=300): # StaticReadOnly: Static/Static.vue def set_basic_response_type(self, response_type): - # default (also valid for "char" input type) self.set_input_type_as_char() diff --git a/reproschema/models/protocol.py b/reproschema/models/protocol.py index 284f2c8..10fa951 100644 --- a/reproschema/models/protocol.py +++ b/reproschema/models/protocol.py @@ -44,7 +44,6 @@ def set_defaults(self, name): self.set_ui_shuffle(False) def append_activity(self, activity): - # TODO # - remove the hard coding on visibility and valueRequired From ef2798240ac8912bfaa240c2368e4fead6523175 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 25 Dec 2023 18:50:10 +0000 Subject: [PATCH 04/94] convert js to python --- reproschema/redcap2reproschema.py | 385 ++++++++++++++++++++++++++++++ 1 file changed, 385 insertions(+) create mode 100644 reproschema/redcap2reproschema.py diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py new file mode 100644 index 0000000..1d2966c --- /dev/null +++ b/reproschema/redcap2reproschema.py @@ -0,0 +1,385 @@ +# User inputs: these are specific to your protocol, fill out before using the script + +# 1. your protocol id: use underscore for spaces, avoid special characters. +# The display name is the one that will show up in the app, this will be parsed as a string. +protocol_name = "sc_dd" + +# 2. your protocol display name: this will show up in the app and be parsed as a string +protocol_display_name = "Your protocol display name" + +# 3. create your raw GitHub repo URL +user_name = 'sanuann' +repo_name = 'reproschema' +branch_name = 'master' + +your_repo_url = f"https://raw.githubusercontent.com/{user_name}/{repo_name}/{branch_name}" + +# 4. add a description to your protocol +protocol_description = "Description for your protocol" + +# 5. where are you hosting your images? For example: openmoji +image_path = 'https://raw.githubusercontent.com/hfg-gmuend/openmoji/master/color/618x618/' + +import sys +import os +import csv +import json +import re +from collections import defaultdict +from bs4 import BeautifulSoup + +def create_form_context_schema(form, row_list): + item_obj = defaultdict(dict) + item_obj["@version"] = 1.1 + item_obj[form] = f"{your_repo_url}/activities/{form}/items/" + + for field in row_list: + field_name = field["Variable / Field Name"] + item_obj[field_name] = {"@id": f"{form}:{field_name}", "@type": "@id"} + + form_context = {"@context": item_obj} + fc = json.dumps(form_context, indent=4) + + try: + with open(f"activities/{form}/{form}_context", "w") as file: + file.write(fc) + print(f"Context created for form {form}") + except Exception as e: + print(e) + +def create_protocol_context(activity_list, your_repo_url, protocol_name): + # Create protocol context file + activity_obj = { + "@version": 1.1, + "activity_path": f"{your_repo_url}/activities/" + } + + for activity in activity_list: + # Define item_x urls to be inserted in context for the corresponding form + activity_obj[activity] = { + "@id": f"activity_path:{activity}/{activity}_schema", + "@type": "@id" + } + + protocol_context = { + "@context": activity_obj + } + + pc = json.dumps(protocol_context, indent=4) + + protocol_dir = f'protocols/{protocol_name}' + os.makedirs(protocol_dir, exist_ok=True) + + with open(f'{protocol_dir}/{protocol_name}_context', 'w') as file: + file.write(pc) + + print(f'Protocol context created for {protocol_name}') + + +def process_visibility(data): + condition = data.get('Branching Logic (Show field only if...)') + + if condition: + # Normalize the condition field to resemble a JavaScript-like condition + condition = re.sub(r"\(([0-9]*)\)", r"___\1", condition) + condition = re.sub(r"([^>|<])=", r"\1 ==", condition) + condition = condition.replace(" and ", " && ") + condition = condition.replace(" or ", " || ") + condition = re.sub(r"\[([^\]]*)\]", r" \1 ", condition) + + visibility_obj = { + "variableName": data['Variable / Field Name'], + "isAbout": f"items/{data['Variable / Field Name']}", + "isVis": condition if condition else True + } + return visibility_obj + +def parse_field_type_and_value(data, input_type_map): + field_type = data.get('Field Type', '') + + input_type = input_type_map.get(field_type, field_type) + + value_type_map = { + 'number': 'xsd:int', + 'date_': 'xsd:date', + 'datetime_': 'datetime', + 'time_': 'xsd:date', + 'email': 'email', + 'phone': 'phone' + } + validation_type = data.get('Text Validation Type OR Show Slider Number', '') + + value_type = value_type_map.get(validation_type, 'xsd:string') + + return input_type, value_type + +def process_choices(choices_str, image_path): + choices = [] + for choice in choices_str.split('|'): + parts = choice.split(', ') + choice_obj = {'schema:value': int(parts[0]), 'schema:name': parts[1]} + if len(parts) == 3: + choice_obj['schema:image'] = f"{image_path}{parts[2]}.png" + choices.append(choice_obj) + return choices + +def normalize_condition(condition_str): + condition_str = re.sub(r"\[([^\]]*)\]", r"\1", condition_str) + condition_str = re.sub(r"\(([0-9]*)\)", r"___\1", condition_str) + condition_str = condition_str.replace(" and ", " && ") + condition_str = condition_str.replace(" or ", " || ") + return condition_str + +def write_to_file(form, field_name, rowData): + try: + file_path = os.path.join('activities', form, 'items', f'{field_name}') + with open(file_path, 'w') as file: + json.dump(rowData, file, indent=4) + print(f"Item schema for {form} written successfully.") + except Exception as e: + print(f"Error in writing item schema for {form}: {e}") + +def parse_html(input_string, default_language='en'): + result = {} + soup = BeautifulSoup(input_string, 'html.parser') + + lang_elements = soup.find_all(True, {'lang': True}) + if lang_elements: + for element in lang_elements: + lang = element.get('lang', default_language) + text = element.get_text(strip=True) + if text: + result[lang] = text + if not result: + result[default_language] = soup.get_text(strip=True) + else: + result[default_language] = input_string + + return result + +def process_row(schema_context_url, form, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list): + rowData = { + '@context': schema_context_url, + '@type': 'reproschema:Field', + } + + field_type = field.get('Field Type', '') + schema_map['Choices, Calculations, OR Slider Labels'] = 'scoringLogic' if field_type == 'calc' else 'choices' + + input_type, value_type = parse_field_type_and_value(field, input_type_map) + rowData['ui'] = {'inputType': input_type} + if value_type: + rowData['responseOptions'] = {'valueType': value_type} + + for key, value in field.items(): + if schema_map.get(key) == 'allow' and value: + rowData.setdefault('ui', {}).update({schema_map[key]: value.split(', ')}) + + elif key in ui_list and value: + rowData.setdefault('ui', {}).update({schema_map[key]: input_type_map.get(value, value)}) + + elif key in response_list and value: + if key == 'multipleChoice': + value = value == '1' + rowData.setdefault('responseOptions', {}).update({schema_map[key]: value}) + + elif schema_map.get(key) == 'choices' and value: + rowData.setdefault('responseOptions', {}).update({'choices': process_choices(value, image_path)}) + + elif schema_map.get(key) == 'scoringLogic' and value: + condition = normalize_condition(value) + rowData.setdefault('ui', {}).update({'hidden': True}) + rowData.setdefault('scoringLogic', []).append({"variableName": field['Variable / Field Name'], "jsExpression": condition}) + + elif schema_map.get(key) == 'visibility' and value: + condition = normalize_condition(value) + rowData.setdefault('visibility', []).append({"variableName": field['Variable / Field Name'], "isVis": condition}) + + elif key in ['question', 'schema:description', 'preamble'] and value: + rowData.update({schema_map[key]: parse_html(value)}) + + elif key == 'Identifier?' and value: + identifier_val = value.lower() == 'y' + rowData.update({schema_map[key]: [{"legalStandard": "unknown", "isIdentifier": identifier_val}]}) + + elif key in additional_notes_list and value: + notes_obj = {"source": "redcap", "column": key, "value": value} + rowData.setdefault('additionalNotesObj', []).append(notes_obj) + + write_to_file(form, field['Variable / Field Name'], rowData) + +def create_form_schema(schema_context_url, form, activity_display_name, activity_description, order, bl_list, matrix_list, scores_list): + # Construct the JSON-LD structure + json_ld = { + "@context": schema_context_url, + "@type": "reproschema:Activity", + "@id": f"{form}_schema", + "prefLabel": activity_display_name, + "description": activity_description, + "schemaVersion": "1.0.0-rc4", + "version": "0.0.1", + "ui": { + "order": order.get(form, []), + "addProperties": bl_list, + "shuffle": False + } + } + + if matrix_list: + json_ld['matrixInfo'] = matrix_list + if scores_list: + json_ld['scoringLogic'] = scores_list + + try: + path = f'activities/{form}' + os.makedirs(path, exist_ok=True) # Ensure the directory exists + filename = f'{form}_schema' + with open(os.path.join(path, filename), 'w') as file: + json.dump(json_ld, file, indent=4) + print(f"{form} Instrument schema created") + except Exception as err: + print(f"Error in writing {form} form schema:", err) + +def process_activities(activity_name, protocol_visibility_obj, protocol_variable_map, protocol_order): + # Set default visibility condition + protocol_visibility_obj[activity_name] = True + + # Add activity to variableMap and Order + protocol_variable_map.append({ + "variableName": activity_name, + "isAbout": f"items/{activity_name}" + }) + protocol_order.append(activity_name) + +def create_protocol_schema(schema_context_url, protocol_name, protocol_display_name, protocol_description, protocol_variable_map, protocol_order, protocol_visibility_obj): + # Construct the protocol schema + protocol_schema = { + "@context": schema_context_url, + "@type": "reproschema:ActivitySet", + "@id": f"{protocol_name}_schema", + "skos:prefLabel": protocol_display_name, + "skos:altLabel": f"{protocol_name}_schema", + "schema:description": protocol_description, + "schema:schemaVersion": "1.0.0-rc4", + "schema:version": "0.0.1", + "variableMap": protocol_variable_map, + "ui": { + "order": protocol_order, + "shuffle": False, + "visibility": protocol_visibility_obj + } + } + + # Write the protocol schema to a file + try: + os.makedirs(f'protocols/{protocol_name}', exist_ok=True) # Ensure the directory exists + with open(f'protocols/{protocol_name}/{protocol_name}_schema', 'w') as file: + json.dump(protocol_schema, file, indent=4) + print("Protocol schema created") + except Exception as err: + print("Error in writing protocol schema:", err) + +def parse_language_iso_codes(input_string): + soup = BeautifulSoup(input_string, 'lxml') + return [element.get('lang') for element in soup.find_all(True, {'lang': True})] + +def main(csv_path, schema_context_url): + # Initialize variables + schema_map = { + "Variable / Field Name": "@id", + "Item Display Name": "prefLabel", + "Field Annotation": "description", + "Section Header": "preamble", + "Field Label": "question", + "Field Type": "inputType", + "Allow": "allow", + "Required Field?": "requiredValue", + "Text Validation Min": "minValue", + "Text Validation Max": "maxValue", + "Choices, Calculations, OR Slider Labels": "choices", + "Branching Logic (Show field only if...)": "visibility", + "Custom Alignment": "customAlignment", + "Identifier?": "identifiable", + "multipleChoice": "multipleChoice", + "responseType": "@type" + } + + input_type_map = { + "calc": "number", + "checkbox": "radio", + "descriptive": "static", + "dropdown": "select", + "notes": "text" + } + + ui_list = ['inputType', 'shuffle', 'allow', 'customAlignment'] + response_list = ['valueType', 'minValue', 'maxValue', 'requiredValue', 'multipleChoice'] + additional_notes_list = ['Field Note', 'Question Number (surveys only)'] + datas = {} + order = {} + bl_list = [] + sl_list = [] + visibility_obj = {} + scores_obj = {} + scores_list = [] + visibility_list = [] + languages = [] + variable_map = [] + matrix_list = [] + protocol_variable_map = [] + protocol_visibility_obj = {} + protocol_order = [] + + # Read and process the CSV file + with open(csv_path, mode='r', encoding='utf-8') as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + form_name = row['Form Name'] + datas.setdefault(form_name, []).append(row) + os.makedirs(f'activities/{form_name}/items', exist_ok=True) + os.makedirs(f'protocols/{protocol_name}', exist_ok=True) + + scores_list = [] + order[form_name] = [] + bl_list = [] + visibility_list = [] + variable_map = [] + matrix_list = [] + activity_display_name = row['Form Name'] + activity_description = row['Form Note'] + + for field in datas[form_name]: + if not languages: + languages = parse_language_iso_codes(field['Field Label']) + + field_name = field['Variable / Field Name'] + visibility_obj = process_visibility(field) + bl_list.append(visibility_obj) + variable_map.append({"variableName": field_name, "isAbout": f"items/{field_name}"}) + + if field.get('Matrix Group Name') or field.get('Matrix Ranking?'): + matrix_list.append({"variableName": field_name, "matrixGroupName": field['Matrix Group Name'], "matrixRanking": field['Matrix Ranking?']}) + + order[form_name].append(f"items/{field_name}") + process_row(schema_context_url, form_name, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list) + + create_form_schema(form_name, activity_display_name, activity_description, order[form_name], bl_list, matrix_list, scores_list) + + # Create protocol context and schema + activity_list = list(datas.keys()) + for activity_name in activity_list: + process_activities(activity_name, protocol_visibility_obj, protocol_variable_map, protocol_order) + + create_protocol_schema(schema_context_url, protocol_name, protocol_display_name, protocol_description, protocol_variable_map, protocol_order, protocol_visibility_obj) + +if __name__ == "__main__": + # Make sure we got a filename on the command line + if len(sys.argv) < 3: + print(f'Usage: {sys.argv[0]} your_data_dic.csv') + sys.exit(1) + + # Read the CSV file + csv_path = sys.argv[2] + schema_context_url = 'https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic' + + main(csv_path, schema_context_url) From 142089eeb4661f08ae11df4bc4055f5c5f2aea9f Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 25 Dec 2023 19:40:37 +0000 Subject: [PATCH 05/94] add redcap2rs yaml template --- templates/redcap2rs.yaml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 templates/redcap2rs.yaml diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml new file mode 100644 index 0000000..1faf87c --- /dev/null +++ b/templates/redcap2rs.yaml @@ -0,0 +1,19 @@ +# User inputs: these are specific to your protocol, fill out before using the script + +# 1. your protocol id: use underscore for spaces, avoid special characters. +# The display name is the one that will show up in the app, this will be parsed as a string. +protocol_name = "your_protocol_name" # e.g. "My_Protocol" + +# 2. your protocol display name: this will show up in the app and be parsed as a string +protocol_display_name = "Your protocol display name" + +# 3. create your raw GitHub repo URL +user_name = 'your_github_username' +repo_name = 'your_repo_name' +branch_name = 'main' + +repo_url = f"https://github.com/{user_name}/{repo_name}" # no need to change +raw_repo_url = f"https://raw.githubusercontent.com/{user_name}/{repo_name}/{branch_name}" # no need to change + +# 4. add a description to your protocol +protocol_description = "Description for your protocol" # e.g. "This is a protocol for ..." \ No newline at end of file From abd9c480db188e1b16bbfb3d3b19598331690170 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 25 Dec 2023 20:46:40 +0000 Subject: [PATCH 06/94] update yaml template --- templates/redcap2rs.yaml | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml index 1faf87c..4033ad4 100644 --- a/templates/redcap2rs.yaml +++ b/templates/redcap2rs.yaml @@ -1,19 +1,21 @@ -# User inputs: these are specific to your protocol, fill out before using the script +# Reproschema Protocol Configuration -# 1. your protocol id: use underscore for spaces, avoid special characters. -# The display name is the one that will show up in the app, this will be parsed as a string. -protocol_name = "your_protocol_name" # e.g. "My_Protocol" +# Protocol Name: +# Use underscores for spaces and avoid special characters. +# This is the unique identifier for your protocol. +protocol_name: "your_protocol_name" # Example: "My_Protocol" -# 2. your protocol display name: this will show up in the app and be parsed as a string -protocol_display_name = "Your protocol display name" +# Protocol Display Name: +# This name will be displayed in the application. +protocol_display_name: "Your protocol display name" -# 3. create your raw GitHub repo URL -user_name = 'your_github_username' -repo_name = 'your_repo_name' -branch_name = 'main' +# GitHub Repository Information: +# Create a GitHub repository named 'reproschema' to store your reproschema protocols. +# Replace 'your_github_username' with your actual GitHub username. +user_name: "your_github_username" +repo_name: "reproschema" # Recommended name; can be different if preferred. +repo_url: "https://github.com/your_github_username/reproschema" -repo_url = f"https://github.com/{user_name}/{repo_name}" # no need to change -raw_repo_url = f"https://raw.githubusercontent.com/{user_name}/{repo_name}/{branch_name}" # no need to change - -# 4. add a description to your protocol -protocol_description = "Description for your protocol" # e.g. "This is a protocol for ..." \ No newline at end of file +# Protocol Description: +# Provide a brief description of your protocol. +protocol_description: "Description for your protocol" # Example: "This protocol is for ..." \ No newline at end of file From 675a4b2ceac608b6d7ad1e4d5a37113c3002627b Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 25 Dec 2023 20:53:55 +0000 Subject: [PATCH 07/94] update instruction to use redcap2reproschema.py --- README.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/README.md b/README.md index bc6d120..bd26e1a 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,47 @@ Commands: validate ``` +## redcap2reproschema.py Usage + +### Prerequisites +Before using the conversion script, ensure you have the following: + +1. **GitHub Repository**: + - [Create a GitHub repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository) named `reproschema` to store all your reproschema protocols. + - This repository should be set up before converting any data using the script. + +2. **YAML Configuration File**: + - Fill out the `templates/redcap2rs.yaml` file with your protocol details. + +### YAML File Configuration +In the `templates/redcap2rs.yaml` file, provide the following information: + +- **protocol_name**: This is a unique identifier for your protocol. Use underscores for spaces and avoid special characters. +- **protocol_display_name**: The name that will appear in the application. +- **user_name**: Your GitHub username. +- **repo_name**: The repository name where your protocols are stored. It's recommended to use `reproschema`. +- **protocol_description**: A brief description of your protocol. + +Example: +```yaml +protocol_name: "My_Protocol" +protocol_display_name: "Assessment Protocol" +user_name: "john_doe" +repo_name: "reproschema" +protocol_description: "This protocol is for assessing cognitive skills." +``` + +### Using the Script + +After configuring the YAML file: + +1. Run the Python script with the paths to your CSV file and the YAML file as arguments. +2. Command Format: `python script_name.py path/to/your_redcap_data_dic.csv path/to/your_redcap2rs.yaml` + +### Notes +1. The script requires an active internet connection to access the GitHub repository. +2. Make sure you use `git add`, `git commit`, `git push` properly afterwards to maintain a good version control for your converted data. + ## Developer installation Install repo in developer mode: From 1f8746df197d067381de58069b31c8b3c294d1ee Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 25 Dec 2023 20:54:25 +0000 Subject: [PATCH 08/94] add additional python package --- setup.cfg | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup.cfg b/setup.cfg index ef22d32..36fda82 100644 --- a/setup.cfg +++ b/setup.cfg @@ -31,6 +31,8 @@ install_requires = PyLD requests requests_cache + beautifulsoup4 + lxml test_requires = pytest >= 4.4.0 From 550db3564908d3122e1b3b12d4cee11d4c367280 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 25 Dec 2023 20:54:51 +0000 Subject: [PATCH 09/94] convert redcap2rs too from js to python --- reproschema/redcap2reproschema.py | 356 +++++++++++++++--------------- 1 file changed, 178 insertions(+), 178 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 1d2966c..b53a836 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -1,96 +1,42 @@ -# User inputs: these are specific to your protocol, fill out before using the script - -# 1. your protocol id: use underscore for spaces, avoid special characters. -# The display name is the one that will show up in the app, this will be parsed as a string. -protocol_name = "sc_dd" - -# 2. your protocol display name: this will show up in the app and be parsed as a string -protocol_display_name = "Your protocol display name" - -# 3. create your raw GitHub repo URL -user_name = 'sanuann' -repo_name = 'reproschema' -branch_name = 'master' - -your_repo_url = f"https://raw.githubusercontent.com/{user_name}/{repo_name}/{branch_name}" - -# 4. add a description to your protocol -protocol_description = "Description for your protocol" - -# 5. where are you hosting your images? For example: openmoji -image_path = 'https://raw.githubusercontent.com/hfg-gmuend/openmoji/master/color/618x618/' - import sys import os +import argparse +import subprocess import csv import json import re +import yaml from collections import defaultdict from bs4 import BeautifulSoup -def create_form_context_schema(form, row_list): - item_obj = defaultdict(dict) - item_obj["@version"] = 1.1 - item_obj[form] = f"{your_repo_url}/activities/{form}/items/" - - for field in row_list: - field_name = field["Variable / Field Name"] - item_obj[field_name] = {"@id": f"{form}:{field_name}", "@type": "@id"} - - form_context = {"@context": item_obj} - fc = json.dumps(form_context, indent=4) - - try: - with open(f"activities/{form}/{form}_context", "w") as file: - file.write(fc) - print(f"Context created for form {form}") - except Exception as e: - print(e) - -def create_protocol_context(activity_list, your_repo_url, protocol_name): - # Create protocol context file - activity_obj = { - "@version": 1.1, - "activity_path": f"{your_repo_url}/activities/" - } - - for activity in activity_list: - # Define item_x urls to be inserted in context for the corresponding form - activity_obj[activity] = { - "@id": f"activity_path:{activity}/{activity}_schema", - "@type": "@id" - } - - protocol_context = { - "@context": activity_obj - } - - pc = json.dumps(protocol_context, indent=4) - - protocol_dir = f'protocols/{protocol_name}' - os.makedirs(protocol_dir, exist_ok=True) - - with open(f'{protocol_dir}/{protocol_name}_context', 'w') as file: - file.write(pc) - - print(f'Protocol context created for {protocol_name}') +def parse_arguments(): + parser = argparse.ArgumentParser(description='Process REDCap data dictionary and reproschema protocol.') + parser.add_argument('csv_file', help='Path to the REDCap data dictionary CSV file.') + parser.add_argument('yaml_file', help='Path to the reproschema protocol YAML file.') + return parser.parse_args() +def normalize_condition(condition_str): + re_parentheses = re.compile(r"\(([0-9]*)\)") + re_non_gt_lt_equal = re.compile(r"([^>|<])=") + re_brackets = re.compile(r"\[([^\]]*)\]") + + condition_str = re_parentheses.sub(r"___\1", condition_str) + condition_str = re_non_gt_lt_equal.sub(r"\1 ==", condition_str) + condition_str = condition_str.replace(" and ", " && ").replace(" or ", " || ") + condition_str = re_brackets.sub(r" \1 ", condition_str) + return condition_str def process_visibility(data): condition = data.get('Branching Logic (Show field only if...)') - if condition: - # Normalize the condition field to resemble a JavaScript-like condition - condition = re.sub(r"\(([0-9]*)\)", r"___\1", condition) - condition = re.sub(r"([^>|<])=", r"\1 ==", condition) - condition = condition.replace(" and ", " && ") - condition = condition.replace(" or ", " || ") - condition = re.sub(r"\[([^\]]*)\]", r" \1 ", condition) + condition = normalize_condition(condition) + else: + condition = True visibility_obj = { "variableName": data['Variable / Field Name'], "isAbout": f"items/{data['Variable / Field Name']}", - "isVis": condition if condition else True + "isVis": condition } return visibility_obj @@ -113,31 +59,26 @@ def parse_field_type_and_value(data, input_type_map): return input_type, value_type -def process_choices(choices_str, image_path): +def process_choices(choices_str): choices = [] for choice in choices_str.split('|'): parts = choice.split(', ') choice_obj = {'schema:value': int(parts[0]), 'schema:name': parts[1]} if len(parts) == 3: - choice_obj['schema:image'] = f"{image_path}{parts[2]}.png" + # TODO: handle image url + choice_obj['schema:image'] = f"{parts[2]}.png" choices.append(choice_obj) return choices -def normalize_condition(condition_str): - condition_str = re.sub(r"\[([^\]]*)\]", r"\1", condition_str) - condition_str = re.sub(r"\(([0-9]*)\)", r"___\1", condition_str) - condition_str = condition_str.replace(" and ", " && ") - condition_str = condition_str.replace(" or ", " || ") - return condition_str - -def write_to_file(form, field_name, rowData): +def write_to_file(form_name, field_name, rowData): + file_path = os.path.join('activities', form_name, 'items', f'{field_name}') + os.makedirs(os.path.dirname(file_path), exist_ok=True) try: - file_path = os.path.join('activities', form, 'items', f'{field_name}') with open(file_path, 'w') as file: json.dump(rowData, file, indent=4) - print(f"Item schema for {form} written successfully.") + print(f"Item schema for {form_name} written successfully.") except Exception as e: - print(f"Error in writing item schema for {form}: {e}") + print(f"Error in writing item schema for {form_name}: {e}") def parse_html(input_string, default_language='en'): result = {} @@ -157,7 +98,7 @@ def parse_html(input_string, default_language='en'): return result -def process_row(schema_context_url, form, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list): +def process_row(schema_context_url, form_name, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list): rowData = { '@context': schema_context_url, '@type': 'reproschema:Field', @@ -184,7 +125,7 @@ def process_row(schema_context_url, form, field, schema_map, input_type_map, ui_ rowData.setdefault('responseOptions', {}).update({schema_map[key]: value}) elif schema_map.get(key) == 'choices' and value: - rowData.setdefault('responseOptions', {}).update({'choices': process_choices(value, image_path)}) + rowData.setdefault('responseOptions', {}).update({'choices': process_choices(value)}) elif schema_map.get(key) == 'scoringLogic' and value: condition = normalize_condition(value) @@ -206,20 +147,20 @@ def process_row(schema_context_url, form, field, schema_map, input_type_map, ui_ notes_obj = {"source": "redcap", "column": key, "value": value} rowData.setdefault('additionalNotesObj', []).append(notes_obj) - write_to_file(form, field['Variable / Field Name'], rowData) + write_to_file(form_name, field['Variable / Field Name'], rowData) -def create_form_schema(schema_context_url, form, activity_display_name, activity_description, order, bl_list, matrix_list, scores_list): +def create_form_schema(schema_context_url, form_name, activity_display_name, activity_description, order, bl_list, matrix_list, scores_list): # Construct the JSON-LD structure json_ld = { "@context": schema_context_url, "@type": "reproschema:Activity", - "@id": f"{form}_schema", + "@id": f"{form_name}_schema", "prefLabel": activity_display_name, "description": activity_description, "schemaVersion": "1.0.0-rc4", "version": "0.0.1", "ui": { - "order": order.get(form, []), + "order": order.get(form_name, []), "addProperties": bl_list, "shuffle": False } @@ -230,15 +171,18 @@ def create_form_schema(schema_context_url, form, activity_display_name, activity if scores_list: json_ld['scoringLogic'] = scores_list + path = os.path.join('activities', form_name) + filename = f'{form_name}_schema' + file_path = os.path.join(path, filename) try: - path = f'activities/{form}' - os.makedirs(path, exist_ok=True) # Ensure the directory exists - filename = f'{form}_schema' - with open(os.path.join(path, filename), 'w') as file: + os.makedirs(path, exist_ok=True) + with open(file_path, 'w') as file: json.dump(json_ld, file, indent=4) - print(f"{form} Instrument schema created") - except Exception as err: - print(f"Error in writing {form} form schema:", err) + print(f"{form_name} Instrument schema created") + except OSError as e: + print(f"Error creating directory {path}: {e}") + except IOError as e: + print(f"Error writing to file {file_path}: {e}") def process_activities(activity_name, protocol_visibility_obj, protocol_variable_map, protocol_order): # Set default visibility condition @@ -270,36 +214,68 @@ def create_protocol_schema(schema_context_url, protocol_name, protocol_display_n } } - # Write the protocol schema to a file + protocol_dir = f'{protocol_name}' + schema_file = f'{protocol_name}_schema' + file_path = os.path.join(protocol_dir, schema_file) + try: - os.makedirs(f'protocols/{protocol_name}', exist_ok=True) # Ensure the directory exists - with open(f'protocols/{protocol_name}/{protocol_name}_schema', 'w') as file: + os.makedirs(protocol_dir, exist_ok=True) + with open(file_path, 'w') as file: json.dump(protocol_schema, file, indent=4) print("Protocol schema created") - except Exception as err: - print("Error in writing protocol schema:", err) + except OSError as e: + print(f"Error creating directory {protocol_dir}: {e}") + except IOError as e: + print(f"Error writing to file {file_path}: {e}") def parse_language_iso_codes(input_string): soup = BeautifulSoup(input_string, 'lxml') return [element.get('lang') for element in soup.find_all(True, {'lang': True})] -def main(csv_path, schema_context_url): +def process_csv(csv_path, schema_context_url, schema_map, input_type_map, ui_list, response_list, additional_notes_list, protocol_name): + datas = {} + order = {} + languages = [] + + with open(csv_path, mode='r', encoding='utf-8') as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + form_name = row['Form Name'] + if form_name not in datas: + datas[form_name] = [] + order[form_name] = [] + os.makedirs(f'activities/{form_name}/items', exist_ok=True) + + datas[form_name].append(row) + + if not languages: + languages = parse_language_iso_codes(row['Field Label']) + + for field in datas[form_name]: + field_name = field['Variable / Field Name'] + order[form_name].append(f"items/{field_name}") + process_row(schema_context_url, form_name, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list) + + os.makedirs(f'protocols/{protocol_name}', exist_ok=True) + return datas, order, languages + +def main(csv_path, schema_context_url, protocol_name, protocol_display_name, protocol_description): # Initialize variables schema_map = { - "Variable / Field Name": "@id", + "Variable / Field Name": "@id", # column A "Item Display Name": "prefLabel", - "Field Annotation": "description", - "Section Header": "preamble", - "Field Label": "question", - "Field Type": "inputType", + "Field Annotation": "description", # column R + "Section Header": "preamble", # column C (need double-check) + "Field Label": "question", # column E + "Field Type": "inputType", # column D "Allow": "allow", - "Required Field?": "requiredValue", - "Text Validation Min": "minValue", - "Text Validation Max": "maxValue", - "Choices, Calculations, OR Slider Labels": "choices", - "Branching Logic (Show field only if...)": "visibility", - "Custom Alignment": "customAlignment", - "Identifier?": "identifiable", + "Required Field?": "requiredValue", # column M + "Text Validation Min": "minValue", # column I + "Text Validation Max": "maxValue", # column J + "Choices, Calculations, OR Slider Labels": "choices", # column F + "Branching Logic (Show field only if...)": "visibility", # column L + "Custom Alignment": "customAlignment", # column N + "Identifier?": "identifiable", # column K "multipleChoice": "multipleChoice", "responseType": "@type" } @@ -315,71 +291,95 @@ def main(csv_path, schema_context_url): ui_list = ['inputType', 'shuffle', 'allow', 'customAlignment'] response_list = ['valueType', 'minValue', 'maxValue', 'requiredValue', 'multipleChoice'] additional_notes_list = ['Field Note', 'Question Number (surveys only)'] - datas = {} - order = {} - bl_list = [] - sl_list = [] - visibility_obj = {} - scores_obj = {} - scores_list = [] - visibility_list = [] - languages = [] - variable_map = [] - matrix_list = [] + + # Process the CSV file + datas, order, languages = process_csv( + csv_path, schema_context_url, schema_map, + input_type_map, ui_list, response_list, additional_notes_list, + protocol_name + ) + # Initialize other variables for protocol context and schema protocol_variable_map = [] protocol_visibility_obj = {} protocol_order = [] - # Read and process the CSV file - with open(csv_path, mode='r', encoding='utf-8') as csvfile: - reader = csv.DictReader(csvfile) - for row in reader: - form_name = row['Form Name'] - datas.setdefault(form_name, []).append(row) - os.makedirs(f'activities/{form_name}/items', exist_ok=True) - os.makedirs(f'protocols/{protocol_name}', exist_ok=True) - - scores_list = [] - order[form_name] = [] - bl_list = [] - visibility_list = [] - variable_map = [] - matrix_list = [] - activity_display_name = row['Form Name'] - activity_description = row['Form Note'] - - for field in datas[form_name]: - if not languages: - languages = parse_language_iso_codes(field['Field Label']) - - field_name = field['Variable / Field Name'] - visibility_obj = process_visibility(field) - bl_list.append(visibility_obj) - variable_map.append({"variableName": field_name, "isAbout": f"items/{field_name}"}) - - if field.get('Matrix Group Name') or field.get('Matrix Ranking?'): - matrix_list.append({"variableName": field_name, "matrixGroupName": field['Matrix Group Name'], "matrixRanking": field['Matrix Ranking?']}) - - order[form_name].append(f"items/{field_name}") - process_row(schema_context_url, form_name, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list) - - create_form_schema(form_name, activity_display_name, activity_description, order[form_name], bl_list, matrix_list, scores_list) + # Create form schemas and process activities + for form_name, rows in datas.items(): + bl_list = [] + scores_list = [] + matrix_list = [] + + for field in rows: + visibility_obj = process_visibility(field) + bl_list.append(visibility_obj) + + if field.get('Matrix Group Name') or field.get('Matrix Ranking?'): + matrix_list.append({ + "variableName": field['Variable / Field Name'], + "matrixGroupName": field['Matrix Group Name'], + "matrixRanking": field['Matrix Ranking?'] + }) + + activity_display_name = rows[0]['Form Name'] + activity_description = rows[0]['Form Note'] + create_form_schema( + schema_context_url, + form_name, + activity_display_name, + activity_description, + order.get(form_name, []), + bl_list, + matrix_list, + scores_list + ) + + process_activities( + form_name, + protocol_visibility_obj, + protocol_variable_map, + protocol_order + ) + + # Create protocol schema + create_protocol_schema( + schema_context_url, + protocol_name, + protocol_display_name, + protocol_description, + protocol_variable_map, + protocol_order, + protocol_visibility_obj + ) - # Create protocol context and schema - activity_list = list(datas.keys()) - for activity_name in activity_list: - process_activities(activity_name, protocol_visibility_obj, protocol_variable_map, protocol_order) +if __name__ == "__main__": + + schema_context_url = 'https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic' # we may also want to keep this schema version updated or in the yaml file + + args = parse_arguments() - create_protocol_schema(schema_context_url, protocol_name, protocol_display_name, protocol_description, protocol_variable_map, protocol_order, protocol_visibility_obj) + # Read the CSV file path + csv_path = args.csv_file -if __name__ == "__main__": - # Make sure we got a filename on the command line - if len(sys.argv) < 3: - print(f'Usage: {sys.argv[0]} your_data_dic.csv') + # Read the YAML configuration + yaml_path = args.yaml_file + try: + with open(yaml_path, 'r') as f: + protocol = yaml.safe_load(f) + except FileNotFoundError: + print(f"Error: YAML file '{yaml_path}' not found.") sys.exit(1) - # Read the CSV file - csv_path = sys.argv[2] - schema_context_url = 'https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic' + # Extract values from YAML file + protocol_name = protocol.get('protocol_name') + protocol_display_name = protocol.get('protocol_display_name') + protocol_description = protocol.get('protocol_description') + repo_url = protocol.get('repo_url') + + # git clone the repo + subprocess.run(['git', 'clone', repo_url]) + # set up branch and checkout + subprocess.run(['git', 'checkout', 'main']) + # cd to the repo + os.chdir(repo_url.split('/')[-1]) - main(csv_path, schema_context_url) + main(csv_path, schema_context_url, protocol_name, protocol_display_name, protocol_description) From 788130573214a45b71a3bdf266375c5c9a11f83c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 25 Dec 2023 21:18:32 +0000 Subject: [PATCH 10/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- README.md | 4 +- reproschema/redcap2reproschema.py | 398 +++++++++++++++++++----------- templates/redcap2rs.yaml | 2 +- 3 files changed, 253 insertions(+), 151 deletions(-) diff --git a/README.md b/README.md index bd26e1a..7ba69ae 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,8 @@ Commands: ### Prerequisites Before using the conversion script, ensure you have the following: -1. **GitHub Repository**: - - [Create a GitHub repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository) named `reproschema` to store all your reproschema protocols. +1. **GitHub Repository**: + - [Create a GitHub repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository) named `reproschema` to store all your reproschema protocols. - This repository should be set up before converting any data using the script. 2. **YAML Configuration File**: diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index b53a836..6ae975b 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -9,12 +9,16 @@ from collections import defaultdict from bs4 import BeautifulSoup + def parse_arguments(): - parser = argparse.ArgumentParser(description='Process REDCap data dictionary and reproschema protocol.') - parser.add_argument('csv_file', help='Path to the REDCap data dictionary CSV file.') - parser.add_argument('yaml_file', help='Path to the reproschema protocol YAML file.') + parser = argparse.ArgumentParser( + description="Process REDCap data dictionary and reproschema protocol." + ) + parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") + parser.add_argument("yaml_file", help="Path to the reproschema protocol YAML file.") return parser.parse_args() + def normalize_condition(condition_str): re_parentheses = re.compile(r"\(([0-9]*)\)") re_non_gt_lt_equal = re.compile(r"([^>|<])=") @@ -26,68 +30,73 @@ def normalize_condition(condition_str): condition_str = re_brackets.sub(r" \1 ", condition_str) return condition_str + def process_visibility(data): - condition = data.get('Branching Logic (Show field only if...)') + condition = data.get("Branching Logic (Show field only if...)") if condition: condition = normalize_condition(condition) else: condition = True visibility_obj = { - "variableName": data['Variable / Field Name'], + "variableName": data["Variable / Field Name"], "isAbout": f"items/{data['Variable / Field Name']}", - "isVis": condition + "isVis": condition, } return visibility_obj + def parse_field_type_and_value(data, input_type_map): - field_type = data.get('Field Type', '') - + field_type = data.get("Field Type", "") + input_type = input_type_map.get(field_type, field_type) - + value_type_map = { - 'number': 'xsd:int', - 'date_': 'xsd:date', - 'datetime_': 'datetime', - 'time_': 'xsd:date', - 'email': 'email', - 'phone': 'phone' + "number": "xsd:int", + "date_": "xsd:date", + "datetime_": "datetime", + "time_": "xsd:date", + "email": "email", + "phone": "phone", } - validation_type = data.get('Text Validation Type OR Show Slider Number', '') - - value_type = value_type_map.get(validation_type, 'xsd:string') + validation_type = data.get("Text Validation Type OR Show Slider Number", "") + + value_type = value_type_map.get(validation_type, "xsd:string") return input_type, value_type + def process_choices(choices_str): choices = [] - for choice in choices_str.split('|'): - parts = choice.split(', ') - choice_obj = {'schema:value': int(parts[0]), 'schema:name': parts[1]} + for choice in choices_str.split("|"): + parts = choice.split(", ") + choice_obj = {"schema:value": int(parts[0]), "schema:name": parts[1]} if len(parts) == 3: # TODO: handle image url - choice_obj['schema:image'] = f"{parts[2]}.png" + choice_obj["schema:image"] = f"{parts[2]}.png" choices.append(choice_obj) return choices + def write_to_file(form_name, field_name, rowData): - file_path = os.path.join('activities', form_name, 'items', f'{field_name}') + file_path = os.path.join("activities", form_name, "items", f"{field_name}") os.makedirs(os.path.dirname(file_path), exist_ok=True) try: - with open(file_path, 'w') as file: + with open(file_path, "w") as file: json.dump(rowData, file, indent=4) print(f"Item schema for {form_name} written successfully.") except Exception as e: print(f"Error in writing item schema for {form_name}: {e}") -def parse_html(input_string, default_language='en'): + +def parse_html(input_string, default_language="en"): result = {} - soup = BeautifulSoup(input_string, 'html.parser') + soup = BeautifulSoup(input_string, "html.parser") - lang_elements = soup.find_all(True, {'lang': True}) + lang_elements = soup.find_all(True, {"lang": True}) if lang_elements: for element in lang_elements: - lang = element.get('lang', default_language) + lang = element.get("lang", default_language) text = element.get_text(strip=True) if text: result[lang] = text @@ -98,58 +107,97 @@ def parse_html(input_string, default_language='en'): return result -def process_row(schema_context_url, form_name, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list): + +def process_row( + schema_context_url, + form_name, + field, + schema_map, + input_type_map, + ui_list, + response_list, + additional_notes_list, +): rowData = { - '@context': schema_context_url, - '@type': 'reproschema:Field', + "@context": schema_context_url, + "@type": "reproschema:Field", } - field_type = field.get('Field Type', '') - schema_map['Choices, Calculations, OR Slider Labels'] = 'scoringLogic' if field_type == 'calc' else 'choices' + field_type = field.get("Field Type", "") + schema_map["Choices, Calculations, OR Slider Labels"] = ( + "scoringLogic" if field_type == "calc" else "choices" + ) input_type, value_type = parse_field_type_and_value(field, input_type_map) - rowData['ui'] = {'inputType': input_type} + rowData["ui"] = {"inputType": input_type} if value_type: - rowData['responseOptions'] = {'valueType': value_type} + rowData["responseOptions"] = {"valueType": value_type} for key, value in field.items(): - if schema_map.get(key) == 'allow' and value: - rowData.setdefault('ui', {}).update({schema_map[key]: value.split(', ')}) + if schema_map.get(key) == "allow" and value: + rowData.setdefault("ui", {}).update({schema_map[key]: value.split(", ")}) elif key in ui_list and value: - rowData.setdefault('ui', {}).update({schema_map[key]: input_type_map.get(value, value)}) + rowData.setdefault("ui", {}).update( + {schema_map[key]: input_type_map.get(value, value)} + ) elif key in response_list and value: - if key == 'multipleChoice': - value = value == '1' - rowData.setdefault('responseOptions', {}).update({schema_map[key]: value}) + if key == "multipleChoice": + value = value == "1" + rowData.setdefault("responseOptions", {}).update({schema_map[key]: value}) - elif schema_map.get(key) == 'choices' and value: - rowData.setdefault('responseOptions', {}).update({'choices': process_choices(value)}) + elif schema_map.get(key) == "choices" and value: + rowData.setdefault("responseOptions", {}).update( + {"choices": process_choices(value)} + ) - elif schema_map.get(key) == 'scoringLogic' and value: + elif schema_map.get(key) == "scoringLogic" and value: condition = normalize_condition(value) - rowData.setdefault('ui', {}).update({'hidden': True}) - rowData.setdefault('scoringLogic', []).append({"variableName": field['Variable / Field Name'], "jsExpression": condition}) - - elif schema_map.get(key) == 'visibility' and value: + rowData.setdefault("ui", {}).update({"hidden": True}) + rowData.setdefault("scoringLogic", []).append( + { + "variableName": field["Variable / Field Name"], + "jsExpression": condition, + } + ) + + elif schema_map.get(key) == "visibility" and value: condition = normalize_condition(value) - rowData.setdefault('visibility', []).append({"variableName": field['Variable / Field Name'], "isVis": condition}) + rowData.setdefault("visibility", []).append( + {"variableName": field["Variable / Field Name"], "isVis": condition} + ) - elif key in ['question', 'schema:description', 'preamble'] and value: + elif key in ["question", "schema:description", "preamble"] and value: rowData.update({schema_map[key]: parse_html(value)}) - elif key == 'Identifier?' and value: - identifier_val = value.lower() == 'y' - rowData.update({schema_map[key]: [{"legalStandard": "unknown", "isIdentifier": identifier_val}]}) + elif key == "Identifier?" and value: + identifier_val = value.lower() == "y" + rowData.update( + { + schema_map[key]: [ + {"legalStandard": "unknown", "isIdentifier": identifier_val} + ] + } + ) elif key in additional_notes_list and value: notes_obj = {"source": "redcap", "column": key, "value": value} - rowData.setdefault('additionalNotesObj', []).append(notes_obj) + rowData.setdefault("additionalNotesObj", []).append(notes_obj) - write_to_file(form_name, field['Variable / Field Name'], rowData) + write_to_file(form_name, field["Variable / Field Name"], rowData) -def create_form_schema(schema_context_url, form_name, activity_display_name, activity_description, order, bl_list, matrix_list, scores_list): + +def create_form_schema( + schema_context_url, + form_name, + activity_display_name, + activity_description, + order, + bl_list, + matrix_list, + scores_list, +): # Construct the JSON-LD structure json_ld = { "@context": schema_context_url, @@ -162,21 +210,21 @@ def create_form_schema(schema_context_url, form_name, activity_display_name, act "ui": { "order": order.get(form_name, []), "addProperties": bl_list, - "shuffle": False - } + "shuffle": False, + }, } if matrix_list: - json_ld['matrixInfo'] = matrix_list + json_ld["matrixInfo"] = matrix_list if scores_list: - json_ld['scoringLogic'] = scores_list + json_ld["scoringLogic"] = scores_list - path = os.path.join('activities', form_name) - filename = f'{form_name}_schema' + path = os.path.join("activities", form_name) + filename = f"{form_name}_schema" file_path = os.path.join(path, filename) try: os.makedirs(path, exist_ok=True) - with open(file_path, 'w') as file: + with open(file_path, "w") as file: json.dump(json_ld, file, indent=4) print(f"{form_name} Instrument schema created") except OSError as e: @@ -184,18 +232,29 @@ def create_form_schema(schema_context_url, form_name, activity_display_name, act except IOError as e: print(f"Error writing to file {file_path}: {e}") -def process_activities(activity_name, protocol_visibility_obj, protocol_variable_map, protocol_order): + +def process_activities( + activity_name, protocol_visibility_obj, protocol_variable_map, protocol_order +): # Set default visibility condition protocol_visibility_obj[activity_name] = True # Add activity to variableMap and Order - protocol_variable_map.append({ - "variableName": activity_name, - "isAbout": f"items/{activity_name}" - }) + protocol_variable_map.append( + {"variableName": activity_name, "isAbout": f"items/{activity_name}"} + ) protocol_order.append(activity_name) -def create_protocol_schema(schema_context_url, protocol_name, protocol_display_name, protocol_description, protocol_variable_map, protocol_order, protocol_visibility_obj): + +def create_protocol_schema( + schema_context_url, + protocol_name, + protocol_display_name, + protocol_description, + protocol_variable_map, + protocol_order, + protocol_visibility_obj, +): # Construct the protocol schema protocol_schema = { "@context": schema_context_url, @@ -210,17 +269,17 @@ def create_protocol_schema(schema_context_url, protocol_name, protocol_display_n "ui": { "order": protocol_order, "shuffle": False, - "visibility": protocol_visibility_obj - } + "visibility": protocol_visibility_obj, + }, } - protocol_dir = f'{protocol_name}' - schema_file = f'{protocol_name}_schema' + protocol_dir = f"{protocol_name}" + schema_file = f"{protocol_name}_schema" file_path = os.path.join(protocol_dir, schema_file) try: os.makedirs(protocol_dir, exist_ok=True) - with open(file_path, 'w') as file: + with open(file_path, "w") as file: json.dump(protocol_schema, file, indent=4) print("Protocol schema created") except OSError as e: @@ -228,56 +287,83 @@ def create_protocol_schema(schema_context_url, protocol_name, protocol_display_n except IOError as e: print(f"Error writing to file {file_path}: {e}") -def parse_language_iso_codes(input_string): - soup = BeautifulSoup(input_string, 'lxml') - return [element.get('lang') for element in soup.find_all(True, {'lang': True})] -def process_csv(csv_path, schema_context_url, schema_map, input_type_map, ui_list, response_list, additional_notes_list, protocol_name): +def parse_language_iso_codes(input_string): + soup = BeautifulSoup(input_string, "lxml") + return [element.get("lang") for element in soup.find_all(True, {"lang": True})] + + +def process_csv( + csv_path, + schema_context_url, + schema_map, + input_type_map, + ui_list, + response_list, + additional_notes_list, + protocol_name, +): datas = {} order = {} languages = [] - with open(csv_path, mode='r', encoding='utf-8') as csvfile: + with open(csv_path, mode="r", encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) for row in reader: - form_name = row['Form Name'] + form_name = row["Form Name"] if form_name not in datas: datas[form_name] = [] order[form_name] = [] - os.makedirs(f'activities/{form_name}/items', exist_ok=True) + os.makedirs(f"activities/{form_name}/items", exist_ok=True) datas[form_name].append(row) if not languages: - languages = parse_language_iso_codes(row['Field Label']) + languages = parse_language_iso_codes(row["Field Label"]) for field in datas[form_name]: - field_name = field['Variable / Field Name'] + field_name = field["Variable / Field Name"] order[form_name].append(f"items/{field_name}") - process_row(schema_context_url, form_name, field, schema_map, input_type_map, ui_list, response_list, additional_notes_list) - - os.makedirs(f'protocols/{protocol_name}', exist_ok=True) + process_row( + schema_context_url, + form_name, + field, + schema_map, + input_type_map, + ui_list, + response_list, + additional_notes_list, + ) + + os.makedirs(f"protocols/{protocol_name}", exist_ok=True) return datas, order, languages -def main(csv_path, schema_context_url, protocol_name, protocol_display_name, protocol_description): + +def main( + csv_path, + schema_context_url, + protocol_name, + protocol_display_name, + protocol_description, +): # Initialize variables schema_map = { - "Variable / Field Name": "@id", # column A + "Variable / Field Name": "@id", # column A "Item Display Name": "prefLabel", - "Field Annotation": "description", # column R - "Section Header": "preamble", # column C (need double-check) - "Field Label": "question", # column E - "Field Type": "inputType", # column D + "Field Annotation": "description", # column R + "Section Header": "preamble", # column C (need double-check) + "Field Label": "question", # column E + "Field Type": "inputType", # column D "Allow": "allow", - "Required Field?": "requiredValue", # column M - "Text Validation Min": "minValue", # column I - "Text Validation Max": "maxValue", # column J - "Choices, Calculations, OR Slider Labels": "choices", # column F - "Branching Logic (Show field only if...)": "visibility", # column L - "Custom Alignment": "customAlignment", # column N - "Identifier?": "identifiable", # column K + "Required Field?": "requiredValue", # column M + "Text Validation Min": "minValue", # column I + "Text Validation Max": "maxValue", # column J + "Choices, Calculations, OR Slider Labels": "choices", # column F + "Branching Logic (Show field only if...)": "visibility", # column L + "Custom Alignment": "customAlignment", # column N + "Identifier?": "identifiable", # column K "multipleChoice": "multipleChoice", - "responseType": "@type" + "responseType": "@type", } input_type_map = { @@ -285,18 +371,29 @@ def main(csv_path, schema_context_url, protocol_name, protocol_display_name, pro "checkbox": "radio", "descriptive": "static", "dropdown": "select", - "notes": "text" + "notes": "text", } - ui_list = ['inputType', 'shuffle', 'allow', 'customAlignment'] - response_list = ['valueType', 'minValue', 'maxValue', 'requiredValue', 'multipleChoice'] - additional_notes_list = ['Field Note', 'Question Number (surveys only)'] + ui_list = ["inputType", "shuffle", "allow", "customAlignment"] + response_list = [ + "valueType", + "minValue", + "maxValue", + "requiredValue", + "multipleChoice", + ] + additional_notes_list = ["Field Note", "Question Number (surveys only)"] # Process the CSV file datas, order, languages = process_csv( - csv_path, schema_context_url, schema_map, - input_type_map, ui_list, response_list, additional_notes_list, - protocol_name + csv_path, + schema_context_url, + schema_map, + input_type_map, + ui_list, + response_list, + additional_notes_list, + protocol_name, ) # Initialize other variables for protocol context and schema protocol_variable_map = [] @@ -313,48 +410,47 @@ def main(csv_path, schema_context_url, protocol_name, protocol_display_name, pro visibility_obj = process_visibility(field) bl_list.append(visibility_obj) - if field.get('Matrix Group Name') or field.get('Matrix Ranking?'): - matrix_list.append({ - "variableName": field['Variable / Field Name'], - "matrixGroupName": field['Matrix Group Name'], - "matrixRanking": field['Matrix Ranking?'] - }) - - activity_display_name = rows[0]['Form Name'] - activity_description = rows[0]['Form Note'] + if field.get("Matrix Group Name") or field.get("Matrix Ranking?"): + matrix_list.append( + { + "variableName": field["Variable / Field Name"], + "matrixGroupName": field["Matrix Group Name"], + "matrixRanking": field["Matrix Ranking?"], + } + ) + + activity_display_name = rows[0]["Form Name"] + activity_description = rows[0]["Form Note"] create_form_schema( - schema_context_url, - form_name, - activity_display_name, - activity_description, - order.get(form_name, []), - bl_list, - matrix_list, - scores_list + schema_context_url, + form_name, + activity_display_name, + activity_description, + order.get(form_name, []), + bl_list, + matrix_list, + scores_list, ) process_activities( - form_name, - protocol_visibility_obj, - protocol_variable_map, - protocol_order + form_name, protocol_visibility_obj, protocol_variable_map, protocol_order ) # Create protocol schema create_protocol_schema( - schema_context_url, - protocol_name, - protocol_display_name, - protocol_description, - protocol_variable_map, - protocol_order, - protocol_visibility_obj + schema_context_url, + protocol_name, + protocol_display_name, + protocol_description, + protocol_variable_map, + protocol_order, + protocol_visibility_obj, ) + if __name__ == "__main__": - - schema_context_url = 'https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic' # we may also want to keep this schema version updated or in the yaml file - + schema_context_url = "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic" # we may also want to keep this schema version updated or in the yaml file + args = parse_arguments() # Read the CSV file path @@ -363,23 +459,29 @@ def main(csv_path, schema_context_url, protocol_name, protocol_display_name, pro # Read the YAML configuration yaml_path = args.yaml_file try: - with open(yaml_path, 'r') as f: + with open(yaml_path, "r") as f: protocol = yaml.safe_load(f) except FileNotFoundError: print(f"Error: YAML file '{yaml_path}' not found.") sys.exit(1) # Extract values from YAML file - protocol_name = protocol.get('protocol_name') - protocol_display_name = protocol.get('protocol_display_name') - protocol_description = protocol.get('protocol_description') - repo_url = protocol.get('repo_url') + protocol_name = protocol.get("protocol_name") + protocol_display_name = protocol.get("protocol_display_name") + protocol_description = protocol.get("protocol_description") + repo_url = protocol.get("repo_url") # git clone the repo - subprocess.run(['git', 'clone', repo_url]) + subprocess.run(["git", "clone", repo_url]) # set up branch and checkout - subprocess.run(['git', 'checkout', 'main']) + subprocess.run(["git", "checkout", "main"]) # cd to the repo - os.chdir(repo_url.split('/')[-1]) - - main(csv_path, schema_context_url, protocol_name, protocol_display_name, protocol_description) + os.chdir(repo_url.split("/")[-1]) + + main( + csv_path, + schema_context_url, + protocol_name, + protocol_display_name, + protocol_description, + ) diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml index 4033ad4..b8bf76e 100644 --- a/templates/redcap2rs.yaml +++ b/templates/redcap2rs.yaml @@ -18,4 +18,4 @@ repo_url: "https://github.com/your_github_username/reproschema" # Protocol Description: # Provide a brief description of your protocol. -protocol_description: "Description for your protocol" # Example: "This protocol is for ..." \ No newline at end of file +protocol_description: "Description for your protocol" # Example: "This protocol is for ..." From f3d8992b9a40d63b56f456583f70a869db6b9069 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 26 Dec 2023 17:44:17 +0000 Subject: [PATCH 11/94] convert rs2redcap.js to python --- reproschema/models/reproschema2redcap.py | 162 +++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 reproschema/models/reproschema2redcap.py diff --git a/reproschema/models/reproschema2redcap.py b/reproschema/models/reproschema2redcap.py new file mode 100644 index 0000000..fc40c1b --- /dev/null +++ b/reproschema/models/reproschema2redcap.py @@ -0,0 +1,162 @@ +import sys +import json +import csv +from pathlib import Path + +def read_json_file(file_path): + try: + with open(file_path, 'r', encoding='utf-8') as file: + return json.load(file) + except Exception as e: + print(f"Error reading file {file_path}: {e}") + return None + +def find_Ftype_and_colH(item_json, row_data): + """ + Find the field type and column header based on the given item_json. + + Args: + item_json (dict): The JSON object containing the item information. + row_data (dict): The row data dictionary. + + Returns: + dict: The updated row data dictionary with field type and column header. + + """ + # Extract the input type from the item_json + f_type = item_json.get('ui', {}).get('inputType', '') + col_h = '' + + # Check the input type and update the field type and column header accordingly + if f_type == 'integer': + f_type = 'text' + col_h = 'number' + elif f_type == 'select': + f_type = 'dropdown' + elif f_type == 'date': + f_type = 'text' + col_h = 'ddate_mdy' + + # Update the row_data dictionary with the field type + row_data['field_type'] = f_type + + # Update the row_data dictionary with the column header if available + if col_h: + row_data['val_type_OR_slider'] = col_h + + return row_data + +def process_item(item_json, activity_name): + """ + Process an item in JSON format and extract relevant information into a dictionary. + + Args: + item_json (dict): The JSON object representing the item. + activity_name (str): The name of the activity. + + Returns: + dict: A dictionary containing the extracted information. + """ + row_data = {} + + # Extract min and max values from response options, if available + response_options = item_json.get('responseOptions', {}) + row_data['val_min'] = response_options.get('schema:minValue', '') + row_data['val_max'] = response_options.get('schema:maxValue', '') + + choices = response_options.get('choices') + if choices: + if isinstance(choices, list): + # Extract choice values and names, and join them with a '|' + item_choices = [ + f"{ch.get('schema:value', ch.get('value', ''))}, {ch.get('schema:name', ch.get('name', ''))}" + for ch in choices + ] + row_data['choices'] = ' | '.join(item_choices) + elif isinstance(choices, str): + row_data['choices'] = choices + else: + row_data['choices'] = '' + + row_data['required'] = response_options.get('requiredValue', '') + + row_data['field_notes'] = item_json.get('skos:altLabel', '') + + row_data['var_name'] = item_json.get('@id', '') + row_data['activity'] = activity_name + + question = item_json.get('question') + if isinstance(question, dict): + row_data['field_label'] = question.get('en', '') + elif isinstance(question, str): + row_data['field_label'] = question + else: + row_data['field_label'] = '' + + # Call helper function to find Ftype and colH values and update row_data + row_data = find_Ftype_and_colH(item_json, row_data) + + return row_data + +def get_csv_data(dir_path): + csv_data = [] + + # Iterate over directories in dir_path + for protocol_dir in dir_path.iterdir(): + if protocol_dir.is_dir(): + # Check for a _schema file in each directory + schema_file = next(protocol_dir.glob('*_schema'), None) + if schema_file: + # Process the found _schema file + parsed_protocol_json = read_json_file(schema_file) + + activity_order = parsed_protocol_json.get('ui', {}).get('order', []) + for relative_activity_path in activity_order: + # Normalize the relative path and construct the absolute path + normalized_relative_path = Path(relative_activity_path.lstrip("../")) + activity_path = dir_path / normalized_relative_path + parsed_activity_json = read_json_file(activity_path) + + if parsed_activity_json: + item_order = parsed_activity_json.get('ui', {}).get('order', []) + for item in item_order: + item_path = activity_path.parent / item + item_json = read_json_file(item_path) + if item_json: + row_data = process_item(item_json, activity_path.stem) + csv_data.append(row_data) + + # Break after finding the first _schema file + break + + return csv_data + +def write_to_csv(csv_data, output_csv_filename): + # Define the headers for the CSV file as per the JavaScript file + headers = [ + 'var_name', 'activity', 'section', 'field_type', 'field_label', + 'choices', 'field_notes', 'val_type_OR_slider', 'val_min', 'val_max', + 'identifier', 'visibility', 'required' + ] + + # Writing to the CSV file + with open(output_csv_filename, 'w', newline='', encoding='utf-8') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=headers) + writer.writeheader() + for row in csv_data: + writer.writerow(row) + + print('The CSV file was written successfully') + +def main(input_dir_path, output_csv_filename): + csv_data = get_csv_data(input_dir_path) + write_to_csv(csv_data, output_csv_filename) + +if __name__ == "__main__": + # check if input_dir_path and output_csv_filename are provided + if len(sys.argv) < 3: + print("Usage: python reproschema2redcap.py ") + sys.exit(1) + input_dir_path = Path(sys.argv[1]) + output_csv_filename = sys.argv[2] + main(input_dir_path, output_csv_filename) \ No newline at end of file From 7fd5716dc792420002df9ae544d8fba51ced1798 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 26 Dec 2023 19:08:28 +0000 Subject: [PATCH 12/94] update cli.py with reproschema2redcap --- README.md | 32 +++++++++++++++++++ reproschema/cli.py | 14 ++++++++ .../{models => }/reproschema2redcap.py | 0 3 files changed, 46 insertions(+) rename reproschema/{models => }/reproschema2redcap.py (100%) diff --git a/README.md b/README.md index bc6d120..9bb6117 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,38 @@ Commands: validate ``` +## `reproschema2redcap.py` Usage + +### Command-Line Usage + +You can use the `reproschema2redcap.py` script from the command line to convert ReproSchema JSON files to REDCap CSV format. + +``` +python reproschema2redcap.py +``` + +- ``: The path to the root folder of a protocol. For example, to convert the reproschema-demo-protocol provided by ReproNim, you can use the following commands: + ```bash + git clone https://github.com/ReproNim/reproschema-demo-protocol.git + cd reproschema-demo-protocol + pwd + ``` + In this case, `path-to/reproschema-demo-protocol` should be your ``. +- ``: The name of the output CSV file. + +### Python Function Usage + +You can also use the reproschema2redcap function from the `reproschema-py` package in your Python code. + +```python +from reproschema import reproschema2redcap + +input_dir_path = "path-to/reproschema-demo-protocol" +output_csv_filename = "output.csv" + +reproschema2redcap(input_dir_path, output_csv_filename) +``` + ## Developer installation Install repo in developer mode: diff --git a/reproschema/cli.py b/reproschema/cli.py index adbf509..4d5c947 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -3,6 +3,7 @@ from . import get_logger, set_logger_level from . import __version__ +from .reproschema2redcap import main as rs2redcap lgr = get_logger() @@ -95,3 +96,16 @@ def serve(port): from .utils import start_server start_server(port=port) + +@main.command("reproschema2redcap") +@click.argument("input_path", type=click.Path(exists=True, dir_okay=True)) +@click.argument("output_csv_path", type=click.Path(writable=True)) +def reproschema2redcap(input_path, output_csv_path): + """ + Convert reproschema JSON to Redcap CSV format. + + INPUT_PATH: Directory containing reproschema JSON files. + OUTPUT_CSV_PATH: Path to the output CSV file. + """ + rs2redcap(input_path, output_csv_path) + click.echo(f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}") diff --git a/reproschema/models/reproschema2redcap.py b/reproschema/reproschema2redcap.py similarity index 100% rename from reproschema/models/reproschema2redcap.py rename to reproschema/reproschema2redcap.py From 0c5d5146de6246c91f97b13e8a1eed7143b0b733 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 26 Dec 2023 19:13:23 +0000 Subject: [PATCH 13/94] update readme for instruction --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9bb6117..2e4ac6b 100644 --- a/README.md +++ b/README.md @@ -38,14 +38,14 @@ Commands: validate ``` -## `reproschema2redcap.py` Usage +## `reproschema2redcap` Usage ### Command-Line Usage -You can use the `reproschema2redcap.py` script from the command line to convert ReproSchema JSON files to REDCap CSV format. +You can use this feature directly from the command line. To convert ReproSchema protocol to REDCap CSV format, use the following command ``` -python reproschema2redcap.py +reproschema reproschema2redcap ``` - ``: The path to the root folder of a protocol. For example, to convert the reproschema-demo-protocol provided by ReproNim, you can use the following commands: @@ -54,12 +54,12 @@ python reproschema2redcap.py cd reproschema-demo-protocol pwd ``` - In this case, `path-to/reproschema-demo-protocol` should be your ``. -- ``: The name of the output CSV file. + In this case, the output from `pwd` (which shows your current directory path)should be your ``. +- ``: The name of the output CSV file where the converted data will be saved. ### Python Function Usage -You can also use the reproschema2redcap function from the `reproschema-py` package in your Python code. +You can also use the `reproschema2redcap` function from the `reproschema-py` package in your Python code. ```python from reproschema import reproschema2redcap From 3aae7fa259ed440d8bee2b6103d49620bfd51b97 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 26 Dec 2023 19:15:09 +0000 Subject: [PATCH 14/94] update readme for instruction --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2e4ac6b..302a585 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ Commands: create serve validate + reproschema2redcap ``` ## `reproschema2redcap` Usage From 5485e3d2a1fa32263514e19e1beaa58a3e93cc2e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 26 Dec 2023 19:22:13 +0000 Subject: [PATCH 15/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/cli.py | 5 +- reproschema/reproschema2redcap.py | 105 ++++++++++++++++++------------ 2 files changed, 67 insertions(+), 43 deletions(-) diff --git a/reproschema/cli.py b/reproschema/cli.py index 4d5c947..b7fcfe5 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -97,6 +97,7 @@ def serve(port): start_server(port=port) + @main.command("reproschema2redcap") @click.argument("input_path", type=click.Path(exists=True, dir_okay=True)) @click.argument("output_csv_path", type=click.Path(writable=True)) @@ -108,4 +109,6 @@ def reproschema2redcap(input_path, output_csv_path): OUTPUT_CSV_PATH: Path to the output CSV file. """ rs2redcap(input_path, output_csv_path) - click.echo(f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}") + click.echo( + f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}" + ) diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index fc40c1b..3400d51 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -3,14 +3,16 @@ import csv from pathlib import Path + def read_json_file(file_path): try: - with open(file_path, 'r', encoding='utf-8') as file: + with open(file_path, "r", encoding="utf-8") as file: return json.load(file) except Exception as e: print(f"Error reading file {file_path}: {e}") return None + def find_Ftype_and_colH(item_json, row_data): """ Find the field type and column header based on the given item_json. @@ -24,28 +26,29 @@ def find_Ftype_and_colH(item_json, row_data): """ # Extract the input type from the item_json - f_type = item_json.get('ui', {}).get('inputType', '') - col_h = '' + f_type = item_json.get("ui", {}).get("inputType", "") + col_h = "" # Check the input type and update the field type and column header accordingly - if f_type == 'integer': - f_type = 'text' - col_h = 'number' - elif f_type == 'select': - f_type = 'dropdown' - elif f_type == 'date': - f_type = 'text' - col_h = 'ddate_mdy' + if f_type == "integer": + f_type = "text" + col_h = "number" + elif f_type == "select": + f_type = "dropdown" + elif f_type == "date": + f_type = "text" + col_h = "ddate_mdy" # Update the row_data dictionary with the field type - row_data['field_type'] = f_type + row_data["field_type"] = f_type # Update the row_data dictionary with the column header if available if col_h: - row_data['val_type_OR_slider'] = col_h + row_data["val_type_OR_slider"] = col_h return row_data + def process_item(item_json, activity_name): """ Process an item in JSON format and extract relevant information into a dictionary. @@ -60,11 +63,11 @@ def process_item(item_json, activity_name): row_data = {} # Extract min and max values from response options, if available - response_options = item_json.get('responseOptions', {}) - row_data['val_min'] = response_options.get('schema:minValue', '') - row_data['val_max'] = response_options.get('schema:maxValue', '') + response_options = item_json.get("responseOptions", {}) + row_data["val_min"] = response_options.get("schema:minValue", "") + row_data["val_max"] = response_options.get("schema:maxValue", "") - choices = response_options.get('choices') + choices = response_options.get("choices") if choices: if isinstance(choices, list): # Extract choice values and names, and join them with a '|' @@ -72,32 +75,33 @@ def process_item(item_json, activity_name): f"{ch.get('schema:value', ch.get('value', ''))}, {ch.get('schema:name', ch.get('name', ''))}" for ch in choices ] - row_data['choices'] = ' | '.join(item_choices) + row_data["choices"] = " | ".join(item_choices) elif isinstance(choices, str): - row_data['choices'] = choices + row_data["choices"] = choices else: - row_data['choices'] = '' + row_data["choices"] = "" - row_data['required'] = response_options.get('requiredValue', '') + row_data["required"] = response_options.get("requiredValue", "") - row_data['field_notes'] = item_json.get('skos:altLabel', '') + row_data["field_notes"] = item_json.get("skos:altLabel", "") - row_data['var_name'] = item_json.get('@id', '') - row_data['activity'] = activity_name + row_data["var_name"] = item_json.get("@id", "") + row_data["activity"] = activity_name - question = item_json.get('question') + question = item_json.get("question") if isinstance(question, dict): - row_data['field_label'] = question.get('en', '') + row_data["field_label"] = question.get("en", "") elif isinstance(question, str): - row_data['field_label'] = question + row_data["field_label"] = question else: - row_data['field_label'] = '' + row_data["field_label"] = "" # Call helper function to find Ftype and colH values and update row_data row_data = find_Ftype_and_colH(item_json, row_data) return row_data + def get_csv_data(dir_path): csv_data = [] @@ -105,20 +109,22 @@ def get_csv_data(dir_path): for protocol_dir in dir_path.iterdir(): if protocol_dir.is_dir(): # Check for a _schema file in each directory - schema_file = next(protocol_dir.glob('*_schema'), None) + schema_file = next(protocol_dir.glob("*_schema"), None) if schema_file: # Process the found _schema file parsed_protocol_json = read_json_file(schema_file) - - activity_order = parsed_protocol_json.get('ui', {}).get('order', []) + + activity_order = parsed_protocol_json.get("ui", {}).get("order", []) for relative_activity_path in activity_order: # Normalize the relative path and construct the absolute path - normalized_relative_path = Path(relative_activity_path.lstrip("../")) + normalized_relative_path = Path( + relative_activity_path.lstrip("../") + ) activity_path = dir_path / normalized_relative_path parsed_activity_json = read_json_file(activity_path) - + if parsed_activity_json: - item_order = parsed_activity_json.get('ui', {}).get('order', []) + item_order = parsed_activity_json.get("ui", {}).get("order", []) for item in item_order: item_path = activity_path.parent / item item_json = read_json_file(item_path) @@ -128,35 +134,50 @@ def get_csv_data(dir_path): # Break after finding the first _schema file break - + return csv_data + def write_to_csv(csv_data, output_csv_filename): # Define the headers for the CSV file as per the JavaScript file headers = [ - 'var_name', 'activity', 'section', 'field_type', 'field_label', - 'choices', 'field_notes', 'val_type_OR_slider', 'val_min', 'val_max', - 'identifier', 'visibility', 'required' + "var_name", + "activity", + "section", + "field_type", + "field_label", + "choices", + "field_notes", + "val_type_OR_slider", + "val_min", + "val_max", + "identifier", + "visibility", + "required", ] # Writing to the CSV file - with open(output_csv_filename, 'w', newline='', encoding='utf-8') as csvfile: + with open(output_csv_filename, "w", newline="", encoding="utf-8") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() for row in csv_data: writer.writerow(row) - print('The CSV file was written successfully') + print("The CSV file was written successfully") + def main(input_dir_path, output_csv_filename): csv_data = get_csv_data(input_dir_path) write_to_csv(csv_data, output_csv_filename) + if __name__ == "__main__": # check if input_dir_path and output_csv_filename are provided if len(sys.argv) < 3: - print("Usage: python reproschema2redcap.py ") + print( + "Usage: python reproschema2redcap.py " + ) sys.exit(1) input_dir_path = Path(sys.argv[1]) output_csv_filename = sys.argv[2] - main(input_dir_path, output_csv_filename) \ No newline at end of file + main(input_dir_path, output_csv_filename) From a3606fb27aee9436ed39ef1e757bc03fa45bd374 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 26 Dec 2023 19:30:17 +0000 Subject: [PATCH 16/94] integrate redcap2rs in cli.py --- reproschema/cli.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/reproschema/cli.py b/reproschema/cli.py index adbf509..1a4385b 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -3,6 +3,7 @@ from . import get_logger, set_logger_level from . import __version__ +from .redcap2reproschema import main as redcap2rs lgr = get_logger() @@ -95,3 +96,24 @@ def serve(port): from .utils import start_server start_server(port=port) + +@main.command() +@click.argument('csv_path', type=click.Path(exists=True, dir_okay=False)) +@click.argument('yaml_path', type=click.Path(exists=True, dir_okay=False)) +@click.option('--schema-url', default='https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic', show_default=True, help='URL of the schema context') +def redcap2reproschema(csv_path, yaml_path, schema_url): + """ + Convert REDCap CSV files to Reproschema format. + + Provide the path to the REDCap CSV file and the YAML configuration file. + """ + if not os.path.exists(csv_path): + raise click.ClickException(f"CSV file not found at {csv_path}") + if not os.path.exists(yaml_path): + raise click.ClickException(f"YAML file not found at {yaml_path}") + + try: + # Call the redcap2reproschema main function with provided arguments + redcap2rs(csv_path, schema_url, yaml_path) + except Exception as e: + raise click.ClickException(f"Error during conversion: {e}") \ No newline at end of file From 73da5714499f16c18164c464f83539c4afb61d0e Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 26 Dec 2023 20:11:51 +0000 Subject: [PATCH 17/94] rewrite main() for cli use --- README.md | 24 ++++++++-- reproschema/cli.py | 12 ++--- reproschema/redcap2reproschema.py | 80 ++++++++++++++----------------- 3 files changed, 63 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index 7ba69ae..33b12cd 100644 --- a/README.md +++ b/README.md @@ -38,10 +38,11 @@ Commands: validate ``` -## redcap2reproschema.py Usage +## redcap2reproschema Usage +The `redcap2reproschema` function is designed to process a given REDCap CSV file and YAML configuration to generate the output in the reproschema format. ### Prerequisites -Before using the conversion script, ensure you have the following: +Before the conversion, ensure you have the following: 1. **GitHub Repository**: - [Create a GitHub repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository) named `reproschema` to store all your reproschema protocols. @@ -67,8 +68,25 @@ user_name: "john_doe" repo_name: "reproschema" protocol_description: "This protocol is for assessing cognitive skills." ``` +### Command-Line Usage -### Using the Script +The `redcap2reproschema`` function has been integrated into a CLI tool, use the following command: +```bash +reproschema redcap2reproschema path/to/your_redcap_data_dic.csv path/to/your_redcap2rs.yaml +``` + +### Python Function Usage + +You can also use the `redcap2reproschema` function from the `reproschema-py` package in your Python code. + +```python +from reproschema import redcap2reproschema + +csv_path = "path-to/your_redcap_data_dic.csv" +yaml_path = "path-to/your_redcap2rs.yaml" + +reproschema2redcap(input_dir_path, output_csv_filename) +``` After configuring the YAML file: diff --git a/reproschema/cli.py b/reproschema/cli.py index 1a4385b..88655e5 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -1,5 +1,6 @@ import os import click +import yaml from . import get_logger, set_logger_level from . import __version__ @@ -100,11 +101,10 @@ def serve(port): @main.command() @click.argument('csv_path', type=click.Path(exists=True, dir_okay=False)) @click.argument('yaml_path', type=click.Path(exists=True, dir_okay=False)) -@click.option('--schema-url', default='https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic', show_default=True, help='URL of the schema context') -def redcap2reproschema(csv_path, yaml_path, schema_url): +def redcap2reproschema(csv_path, yaml_path): """ Convert REDCap CSV files to Reproschema format. - + Provide the path to the REDCap CSV file and the YAML configuration file. """ if not os.path.exists(csv_path): @@ -113,7 +113,7 @@ def redcap2reproschema(csv_path, yaml_path, schema_url): raise click.ClickException(f"YAML file not found at {yaml_path}") try: - # Call the redcap2reproschema main function with provided arguments - redcap2rs(csv_path, schema_url, yaml_path) + redcap2rs(csv_path, yaml_path) + click.echo("Converted REDCap data dictionary to Reproschema format.") except Exception as e: - raise click.ClickException(f"Error during conversion: {e}") \ No newline at end of file + raise click.ClickException(f"Error during conversion: {e}") diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 6ae975b..c08c6b1 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -6,19 +6,8 @@ import json import re import yaml -from collections import defaultdict from bs4 import BeautifulSoup - -def parse_arguments(): - parser = argparse.ArgumentParser( - description="Process REDCap data dictionary and reproschema protocol." - ) - parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") - parser.add_argument("yaml_file", help="Path to the reproschema protocol YAML file.") - return parser.parse_args() - - def normalize_condition(condition_str): re_parentheses = re.compile(r"\(([0-9]*)\)") re_non_gt_lt_equal = re.compile(r"([^>|<])=") @@ -339,13 +328,28 @@ def process_csv( return datas, order, languages -def main( - csv_path, - schema_context_url, - protocol_name, - protocol_display_name, - protocol_description, -): +def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): + """ + Convert a REDCap data dictionary to Reproschema format. + + :param csv_path: Path to the REDCap CSV file. + :param yaml_path: Path to the YAML configuration file. + :param schema_context_url: URL of the schema context. Optional. + """ + if schema_context_url is None: + schema_context_url = "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic" + + # Read YAML configuration + try: + with open(yaml_path, "r") as f: + protocol_info = yaml.safe_load(f) + except FileNotFoundError: + raise FileNotFoundError(f"YAML file '{yaml_path}' not found.") + + protocol_name = protocol.get("protocol_name") + protocol_display_name = protocol.get("protocol_display_name") + protocol_description = protocol.get("protocol_description") + # Initialize variables schema_map = { "Variable / Field Name": "@id", # column A @@ -447,41 +451,29 @@ def main( protocol_visibility_obj, ) - -if __name__ == "__main__": - schema_context_url = "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic" # we may also want to keep this schema version updated or in the yaml file - - args = parse_arguments() - - # Read the CSV file path - csv_path = args.csv_file +def main(): + import argparse + parser = argparse.ArgumentParser(description="Convert REDCap data dictionary to Reproschema format.") + parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") + parser.add_argument("yaml_file", help="Path to the Reproschema protocol YAML file.") + args = parser.parse_args() # Read the YAML configuration - yaml_path = args.yaml_file try: - with open(yaml_path, "r") as f: + with open(args.yaml_file, "r") as f: protocol = yaml.safe_load(f) except FileNotFoundError: - print(f"Error: YAML file '{yaml_path}' not found.") - sys.exit(1) + raise FileNotFoundError(f"YAML file '{args.yaml_file}' not found.") - # Extract values from YAML file - protocol_name = protocol.get("protocol_name") - protocol_display_name = protocol.get("protocol_display_name") - protocol_description = protocol.get("protocol_description") repo_url = protocol.get("repo_url") - # git clone the repo + # Git operations subprocess.run(["git", "clone", repo_url]) - # set up branch and checkout subprocess.run(["git", "checkout", "main"]) - # cd to the repo os.chdir(repo_url.split("/")[-1]) - main( - csv_path, - schema_context_url, - protocol_name, - protocol_display_name, - protocol_description, - ) + # Call the main conversion function + redcap2reproschema(args.csv_file, args.yaml_file) + +if __name__ == "__main__": + main() \ No newline at end of file From 4906d7606975b3ff2f4192e2983c2c9b8d2e623f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 26 Dec 2023 20:11:58 +0000 Subject: [PATCH 18/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/cli.py | 5 +++-- reproschema/redcap2reproschema.py | 10 ++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/reproschema/cli.py b/reproschema/cli.py index 88655e5..663ce56 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -98,9 +98,10 @@ def serve(port): start_server(port=port) + @main.command() -@click.argument('csv_path', type=click.Path(exists=True, dir_okay=False)) -@click.argument('yaml_path', type=click.Path(exists=True, dir_okay=False)) +@click.argument("csv_path", type=click.Path(exists=True, dir_okay=False)) +@click.argument("yaml_path", type=click.Path(exists=True, dir_okay=False)) def redcap2reproschema(csv_path, yaml_path): """ Convert REDCap CSV files to Reproschema format. diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index c08c6b1..de24ae9 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -8,6 +8,7 @@ import yaml from bs4 import BeautifulSoup + def normalize_condition(condition_str): re_parentheses = re.compile(r"\(([0-9]*)\)") re_non_gt_lt_equal = re.compile(r"([^>|<])=") @@ -451,9 +452,13 @@ def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): protocol_visibility_obj, ) + def main(): import argparse - parser = argparse.ArgumentParser(description="Convert REDCap data dictionary to Reproschema format.") + + parser = argparse.ArgumentParser( + description="Convert REDCap data dictionary to Reproschema format." + ) parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") parser.add_argument("yaml_file", help="Path to the Reproschema protocol YAML file.") args = parser.parse_args() @@ -475,5 +480,6 @@ def main(): # Call the main conversion function redcap2reproschema(args.csv_file, args.yaml_file) + if __name__ == "__main__": - main() \ No newline at end of file + main() From 25932f8268fcc6a67c0ee313313f3c1171adf5fa Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Wed, 27 Dec 2023 20:39:12 +0000 Subject: [PATCH 19/94] update the template --- reproschema/redcap2reproschema.py | 4 +++- templates/redcap2rs.yaml | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index de24ae9..5dbce46 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -470,7 +470,9 @@ def main(): except FileNotFoundError: raise FileNotFoundError(f"YAML file '{args.yaml_file}' not found.") - repo_url = protocol.get("repo_url") + user_name = protocol.get("user_name") + repo_name = protocol.get("repo_name") + repo_url = f"https://github.com/{user_name}/{repo_name}" # Git operations subprocess.run(["git", "clone", repo_url]) diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml index b8bf76e..ed56cd1 100644 --- a/templates/redcap2rs.yaml +++ b/templates/redcap2rs.yaml @@ -14,7 +14,6 @@ protocol_display_name: "Your protocol display name" # Replace 'your_github_username' with your actual GitHub username. user_name: "your_github_username" repo_name: "reproschema" # Recommended name; can be different if preferred. -repo_url: "https://github.com/your_github_username/reproschema" # Protocol Description: # Provide a brief description of your protocol. From 451af3cccf4300ba3a0cca5357111004d3cf5191 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Wed, 27 Dec 2023 20:39:31 +0000 Subject: [PATCH 20/94] major updates for converting --- reproschema/redcap2reproschema.py | 140 +++++++++++++++++------------- 1 file changed, 82 insertions(+), 58 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 5dbce46..da8880c 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -68,8 +68,8 @@ def process_choices(choices_str): return choices -def write_to_file(form_name, field_name, rowData): - file_path = os.path.join("activities", form_name, "items", f"{field_name}") +def write_to_file(abs_repo_path, form_name, field_name, rowData): + file_path = os.path.join(f"{abs_repo_path}", "activities", form_name, "items", f"{field_name}") os.makedirs(os.path.dirname(file_path), exist_ok=True) try: with open(file_path, "w") as file: @@ -99,15 +99,16 @@ def parse_html(input_string, default_language="en"): def process_row( - schema_context_url, - form_name, - field, - schema_map, - input_type_map, - ui_list, - response_list, - additional_notes_list, -): + abs_repo_path, + schema_context_url, + form_name, + field, + schema_map, + input_type_map, + ui_list, + response_list, + additional_notes_list, + ): rowData = { "@context": schema_context_url, "@type": "reproschema:Field", @@ -175,19 +176,20 @@ def process_row( notes_obj = {"source": "redcap", "column": key, "value": value} rowData.setdefault("additionalNotesObj", []).append(notes_obj) - write_to_file(form_name, field["Variable / Field Name"], rowData) + write_to_file(abs_repo_path, form_name, field["Variable / Field Name"], rowData) def create_form_schema( - schema_context_url, - form_name, - activity_display_name, - activity_description, - order, - bl_list, - matrix_list, - scores_list, -): + abs_repo_path, + schema_context_url, + form_name, + activity_display_name, + activity_description, + order, + bl_list, + matrix_list, + scores_list, + ): # Construct the JSON-LD structure json_ld = { "@context": schema_context_url, @@ -209,7 +211,7 @@ def create_form_schema( if scores_list: json_ld["scoringLogic"] = scores_list - path = os.path.join("activities", form_name) + path = os.path.join(f"{abs_repo_path}", "activities", form_name) filename = f"{form_name}_schema" file_path = os.path.join(path, filename) try: @@ -237,14 +239,15 @@ def process_activities( def create_protocol_schema( - schema_context_url, - protocol_name, - protocol_display_name, - protocol_description, - protocol_variable_map, - protocol_order, - protocol_visibility_obj, -): + abs_repo_path, + schema_context_url, + protocol_name, + protocol_display_name, + protocol_description, + protocol_variable_map, + protocol_order, + protocol_visibility_obj, + ): # Construct the protocol schema protocol_schema = { "@context": schema_context_url, @@ -257,13 +260,27 @@ def create_protocol_schema( "schema:version": "0.0.1", "variableMap": protocol_variable_map, "ui": { + "addProperties": [], "order": protocol_order, "shuffle": False, - "visibility": protocol_visibility_obj, }, } - - protocol_dir = f"{protocol_name}" + + # Populate addProperties list + for activity in protocol_order: + add_property = { + "isAbout": f"../activities/{activity}/{activity}_schema", + "variableName": f"{activity}_schema", + # Assuming activity name as prefLabel, update as needed + "prefLabel": activity.replace("_", " ").title() + } + protocol_schema["ui"]["addProperties"].append(add_property) + + # Add visibility if needed + if protocol_visibility_obj: + protocol_schema["ui"]["visibility"] = protocol_visibility_obj + + protocol_dir = f"{abs_repo_path}/{protocol_name}" schema_file = f"{protocol_name}_schema" file_path = os.path.join(protocol_dir, schema_file) @@ -285,6 +302,7 @@ def parse_language_iso_codes(input_string): def process_csv( csv_path, + abs_repo_path, schema_context_url, schema_map, input_type_map, @@ -304,7 +322,7 @@ def process_csv( if form_name not in datas: datas[form_name] = [] order[form_name] = [] - os.makedirs(f"activities/{form_name}/items", exist_ok=True) + os.makedirs(f"{abs_repo_path}/activities/{form_name}/items", exist_ok=True) datas[form_name].append(row) @@ -315,6 +333,7 @@ def process_csv( field_name = field["Variable / Field Name"] order[form_name].append(f"items/{field_name}") process_row( + abs_repo_path, schema_context_url, form_name, field, @@ -325,11 +344,11 @@ def process_csv( additional_notes_list, ) - os.makedirs(f"protocols/{protocol_name}", exist_ok=True) + os.makedirs(f"{abs_repo_path}/protocols/{protocol_name}", exist_ok=True) return datas, order, languages -def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): +def redcap2reproschema(csv_path, abs_repo_path, protocol_name, protocol_display_name, protocol_description, schema_context_url=None): """ Convert a REDCap data dictionary to Reproschema format. @@ -340,17 +359,6 @@ def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): if schema_context_url is None: schema_context_url = "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic" - # Read YAML configuration - try: - with open(yaml_path, "r") as f: - protocol_info = yaml.safe_load(f) - except FileNotFoundError: - raise FileNotFoundError(f"YAML file '{yaml_path}' not found.") - - protocol_name = protocol.get("protocol_name") - protocol_display_name = protocol.get("protocol_display_name") - protocol_description = protocol.get("protocol_description") - # Initialize variables schema_map = { "Variable / Field Name": "@id", # column A @@ -390,8 +398,9 @@ def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): additional_notes_list = ["Field Note", "Question Number (surveys only)"] # Process the CSV file - datas, order, languages = process_csv( + datas, order, _ = process_csv( csv_path, + abs_repo_path, schema_context_url, schema_map, input_type_map, @@ -425,13 +434,15 @@ def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): ) activity_display_name = rows[0]["Form Name"] - activity_description = rows[0]["Form Note"] + activity_description = rows[0].get("Form Note", "Default description") + create_form_schema( + abs_repo_path, schema_context_url, form_name, activity_display_name, activity_description, - order.get(form_name, []), + order, bl_list, matrix_list, scores_list, @@ -443,6 +454,7 @@ def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): # Create protocol schema create_protocol_schema( + abs_repo_path, schema_context_url, protocol_name, protocol_display_name, @@ -452,7 +464,6 @@ def redcap2reproschema(csv_path, yaml_path, schema_context_url=None): protocol_visibility_obj, ) - def main(): import argparse @@ -472,16 +483,29 @@ def main(): user_name = protocol.get("user_name") repo_name = protocol.get("repo_name") - repo_url = f"https://github.com/{user_name}/{repo_name}" + protocol_name = protocol.get("protocol_name") + protocol_display_name = protocol.get("protocol_display_name") + protocol_description = protocol.get("protocol_description") - # Git operations - subprocess.run(["git", "clone", repo_url]) - subprocess.run(["git", "checkout", "main"]) - os.chdir(repo_url.split("/")[-1]) + if not user_name or not repo_name: + raise ValueError("User name and/or repo name not specified in the YAML file.") + repo_url = f"https://github.com/{user_name}/{repo_name}" + local_repo_path = repo_name # Assuming repo is cloned into a folder with the repo's name + + # Check if the directory already exists + if not os.path.exists(local_repo_path): + # Git operations + subprocess.run(["git", "clone", repo_url]) + + # Get absolute path of the local repository + abs_repo_path = os.path.abspath(local_repo_path) + print(f"Local repository path: {abs_repo_path}") + os.chdir(abs_repo_path) + subprocess.run(["git", "checkout", "main"]) + os.chdir('..') # Call the main conversion function - redcap2reproschema(args.csv_file, args.yaml_file) - + redcap2reproschema(args.csv_file, abs_repo_path, protocol_name, protocol_display_name, protocol_description) if __name__ == "__main__": main() From 5582c74c720003f20dc858792ae3d2bbe0336337 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 27 Dec 2023 20:39:49 +0000 Subject: [PATCH 21/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/redcap2reproschema.py | 97 +++++++++++++++++++------------ 1 file changed, 59 insertions(+), 38 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index da8880c..20c5de3 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -69,7 +69,9 @@ def process_choices(choices_str): def write_to_file(abs_repo_path, form_name, field_name, rowData): - file_path = os.path.join(f"{abs_repo_path}", "activities", form_name, "items", f"{field_name}") + file_path = os.path.join( + f"{abs_repo_path}", "activities", form_name, "items", f"{field_name}" + ) os.makedirs(os.path.dirname(file_path), exist_ok=True) try: with open(file_path, "w") as file: @@ -99,16 +101,16 @@ def parse_html(input_string, default_language="en"): def process_row( - abs_repo_path, - schema_context_url, - form_name, - field, - schema_map, - input_type_map, - ui_list, - response_list, - additional_notes_list, - ): + abs_repo_path, + schema_context_url, + form_name, + field, + schema_map, + input_type_map, + ui_list, + response_list, + additional_notes_list, +): rowData = { "@context": schema_context_url, "@type": "reproschema:Field", @@ -180,16 +182,16 @@ def process_row( def create_form_schema( - abs_repo_path, - schema_context_url, - form_name, - activity_display_name, - activity_description, - order, - bl_list, - matrix_list, - scores_list, - ): + abs_repo_path, + schema_context_url, + form_name, + activity_display_name, + activity_description, + order, + bl_list, + matrix_list, + scores_list, +): # Construct the JSON-LD structure json_ld = { "@context": schema_context_url, @@ -239,15 +241,15 @@ def process_activities( def create_protocol_schema( - abs_repo_path, - schema_context_url, - protocol_name, - protocol_display_name, - protocol_description, - protocol_variable_map, - protocol_order, - protocol_visibility_obj, - ): + abs_repo_path, + schema_context_url, + protocol_name, + protocol_display_name, + protocol_description, + protocol_variable_map, + protocol_order, + protocol_visibility_obj, +): # Construct the protocol schema protocol_schema = { "@context": schema_context_url, @@ -265,14 +267,14 @@ def create_protocol_schema( "shuffle": False, }, } - + # Populate addProperties list for activity in protocol_order: add_property = { "isAbout": f"../activities/{activity}/{activity}_schema", "variableName": f"{activity}_schema", # Assuming activity name as prefLabel, update as needed - "prefLabel": activity.replace("_", " ").title() + "prefLabel": activity.replace("_", " ").title(), } protocol_schema["ui"]["addProperties"].append(add_property) @@ -322,7 +324,9 @@ def process_csv( if form_name not in datas: datas[form_name] = [] order[form_name] = [] - os.makedirs(f"{abs_repo_path}/activities/{form_name}/items", exist_ok=True) + os.makedirs( + f"{abs_repo_path}/activities/{form_name}/items", exist_ok=True + ) datas[form_name].append(row) @@ -348,7 +352,14 @@ def process_csv( return datas, order, languages -def redcap2reproschema(csv_path, abs_repo_path, protocol_name, protocol_display_name, protocol_description, schema_context_url=None): +def redcap2reproschema( + csv_path, + abs_repo_path, + protocol_name, + protocol_display_name, + protocol_description, + schema_context_url=None, +): """ Convert a REDCap data dictionary to Reproschema format. @@ -464,6 +475,7 @@ def redcap2reproschema(csv_path, abs_repo_path, protocol_name, protocol_display_ protocol_visibility_obj, ) + def main(): import argparse @@ -491,21 +503,30 @@ def main(): raise ValueError("User name and/or repo name not specified in the YAML file.") repo_url = f"https://github.com/{user_name}/{repo_name}" - local_repo_path = repo_name # Assuming repo is cloned into a folder with the repo's name + local_repo_path = ( + repo_name # Assuming repo is cloned into a folder with the repo's name + ) # Check if the directory already exists if not os.path.exists(local_repo_path): # Git operations subprocess.run(["git", "clone", repo_url]) - + # Get absolute path of the local repository abs_repo_path = os.path.abspath(local_repo_path) print(f"Local repository path: {abs_repo_path}") os.chdir(abs_repo_path) subprocess.run(["git", "checkout", "main"]) - os.chdir('..') + os.chdir("..") # Call the main conversion function - redcap2reproschema(args.csv_file, abs_repo_path, protocol_name, protocol_display_name, protocol_description) + redcap2reproschema( + args.csv_file, + abs_repo_path, + protocol_name, + protocol_display_name, + protocol_description, + ) + if __name__ == "__main__": main() From 4b93d4767765cb632fd3296c9262d6af28a7e660 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Wed, 27 Dec 2023 15:49:51 -0500 Subject: [PATCH 22/94] add pyyaml to ga --- .github/workflows/pythonpublish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpublish.yml b/.github/workflows/pythonpublish.yml index 73ac449..b2b39f5 100644 --- a/.github/workflows/pythonpublish.yml +++ b/.github/workflows/pythonpublish.yml @@ -21,7 +21,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install setuptools wheel twine + pip install setuptools wheel twine pyyaml - name: Build and publish env: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} From 4d862299806a669e26a667e4e923eb34532d2d88 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Wed, 27 Dec 2023 16:03:11 -0500 Subject: [PATCH 23/94] add pyyaml to setup.cfg --- setup.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.cfg b/setup.cfg index ef22d32..f01cdfc 100644 --- a/setup.cfg +++ b/setup.cfg @@ -31,6 +31,7 @@ install_requires = PyLD requests requests_cache + pyyaml test_requires = pytest >= 4.4.0 From d5e4b8bb54be783311bdc07d1fe21d5a2c3f7718 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Wed, 27 Dec 2023 16:13:09 -0500 Subject: [PATCH 24/94] Update to ubuntu-latest --- .github/workflows/pythonpackage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 2837ae3..64bf566 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -15,7 +15,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [macos-latest, ubuntu-18.04] + os: [macos-latest, ubuntu-latest] python-version: [3.7, 3.8, 3.9, "3.10"] steps: From b6685e0ce1f0f2de354349b5b3c413cfbac3c6b6 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 28 Dec 2023 19:40:37 +0000 Subject: [PATCH 25/94] remove the github part --- README.md | 12 +----- reproschema/redcap2reproschema.py | 72 ++++++++++++------------------- templates/redcap2rs.yaml | 8 +--- 3 files changed, 30 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 33b12cd..8eedf83 100644 --- a/README.md +++ b/README.md @@ -44,28 +44,20 @@ The `redcap2reproschema` function is designed to process a given REDCap CSV file ### Prerequisites Before the conversion, ensure you have the following: -1. **GitHub Repository**: - - [Create a GitHub repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository) named `reproschema` to store all your reproschema protocols. - - This repository should be set up before converting any data using the script. - -2. **YAML Configuration File**: - - Fill out the `templates/redcap2rs.yaml` file with your protocol details. +**YAML Configuration File**: + - Download [templates/redcap2rs.yaml](templates/redcap2rs.yaml) and fill it out with your protocol details. ### YAML File Configuration In the `templates/redcap2rs.yaml` file, provide the following information: - **protocol_name**: This is a unique identifier for your protocol. Use underscores for spaces and avoid special characters. - **protocol_display_name**: The name that will appear in the application. -- **user_name**: Your GitHub username. -- **repo_name**: The repository name where your protocols are stored. It's recommended to use `reproschema`. - **protocol_description**: A brief description of your protocol. Example: ```yaml protocol_name: "My_Protocol" protocol_display_name: "Assessment Protocol" -user_name: "john_doe" -repo_name: "reproschema" protocol_description: "This protocol is for assessing cognitive skills." ``` ### Command-Line Usage diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 20c5de3..03a8e54 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -68,9 +68,9 @@ def process_choices(choices_str): return choices -def write_to_file(abs_repo_path, form_name, field_name, rowData): +def write_to_file(abs_folder_path, form_name, field_name, rowData): file_path = os.path.join( - f"{abs_repo_path}", "activities", form_name, "items", f"{field_name}" + f"{abs_folder_path}", "activities", form_name, "items", f"{field_name}" ) os.makedirs(os.path.dirname(file_path), exist_ok=True) try: @@ -101,7 +101,7 @@ def parse_html(input_string, default_language="en"): def process_row( - abs_repo_path, + abs_folder_path, schema_context_url, form_name, field, @@ -178,11 +178,11 @@ def process_row( notes_obj = {"source": "redcap", "column": key, "value": value} rowData.setdefault("additionalNotesObj", []).append(notes_obj) - write_to_file(abs_repo_path, form_name, field["Variable / Field Name"], rowData) + write_to_file(abs_folder_path, form_name, field["Variable / Field Name"], rowData) def create_form_schema( - abs_repo_path, + abs_folder_path, schema_context_url, form_name, activity_display_name, @@ -213,7 +213,7 @@ def create_form_schema( if scores_list: json_ld["scoringLogic"] = scores_list - path = os.path.join(f"{abs_repo_path}", "activities", form_name) + path = os.path.join(f"{abs_folder_path}", "activities", form_name) filename = f"{form_name}_schema" file_path = os.path.join(path, filename) try: @@ -241,7 +241,7 @@ def process_activities( def create_protocol_schema( - abs_repo_path, + abs_folder_path, schema_context_url, protocol_name, protocol_display_name, @@ -282,7 +282,7 @@ def create_protocol_schema( if protocol_visibility_obj: protocol_schema["ui"]["visibility"] = protocol_visibility_obj - protocol_dir = f"{abs_repo_path}/{protocol_name}" + protocol_dir = f"{abs_folder_path}/{protocol_name}" schema_file = f"{protocol_name}_schema" file_path = os.path.join(protocol_dir, schema_file) @@ -304,7 +304,7 @@ def parse_language_iso_codes(input_string): def process_csv( csv_path, - abs_repo_path, + abs_folder_path, schema_context_url, schema_map, input_type_map, @@ -325,7 +325,7 @@ def process_csv( datas[form_name] = [] order[form_name] = [] os.makedirs( - f"{abs_repo_path}/activities/{form_name}/items", exist_ok=True + f"{abs_folder_path}/activities/{form_name}/items", exist_ok=True ) datas[form_name].append(row) @@ -337,7 +337,7 @@ def process_csv( field_name = field["Variable / Field Name"] order[form_name].append(f"items/{field_name}") process_row( - abs_repo_path, + abs_folder_path, schema_context_url, form_name, field, @@ -348,13 +348,13 @@ def process_csv( additional_notes_list, ) - os.makedirs(f"{abs_repo_path}/protocols/{protocol_name}", exist_ok=True) + os.makedirs(f"{abs_folder_path}/protocols/{protocol_name}", exist_ok=True) return datas, order, languages def redcap2reproschema( csv_path, - abs_repo_path, + abs_folder_path, protocol_name, protocol_display_name, protocol_description, @@ -411,7 +411,7 @@ def redcap2reproschema( # Process the CSV file datas, order, _ = process_csv( csv_path, - abs_repo_path, + abs_folder_path, schema_context_url, schema_map, input_type_map, @@ -448,7 +448,7 @@ def redcap2reproschema( activity_description = rows[0].get("Form Note", "Default description") create_form_schema( - abs_repo_path, + abs_folder_path, schema_context_url, form_name, activity_display_name, @@ -465,7 +465,7 @@ def redcap2reproschema( # Create protocol schema create_protocol_schema( - abs_repo_path, + abs_folder_path, schema_context_url, protocol_name, protocol_display_name, @@ -475,58 +475,40 @@ def redcap2reproschema( protocol_visibility_obj, ) - def main(): - import argparse - - parser = argparse.ArgumentParser( - description="Convert REDCap data dictionary to Reproschema format." - ) + parser = argparse.ArgumentParser(description="Convert REDCap data dictionary to Reproschema format.") parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") parser.add_argument("yaml_file", help="Path to the Reproschema protocol YAML file.") args = parser.parse_args() # Read the YAML configuration - try: - with open(args.yaml_file, "r") as f: + with open(args.yaml_file, "r") as f: protocol = yaml.safe_load(f) - except FileNotFoundError: - raise FileNotFoundError(f"YAML file '{args.yaml_file}' not found.") - user_name = protocol.get("user_name") - repo_name = protocol.get("repo_name") protocol_name = protocol.get("protocol_name") protocol_display_name = protocol.get("protocol_display_name") protocol_description = protocol.get("protocol_description") - if not user_name or not repo_name: - raise ValueError("User name and/or repo name not specified in the YAML file.") + if not protocol_name: + raise ValueError("Protocol name not specified in the YAML file.") - repo_url = f"https://github.com/{user_name}/{repo_name}" - local_repo_path = ( - repo_name # Assuming repo is cloned into a folder with the repo's name - ) + protocol_name = protocol_name.replace(' ', '_') # Replacing spaces with underscores # Check if the directory already exists - if not os.path.exists(local_repo_path): - # Git operations - subprocess.run(["git", "clone", repo_url]) + if not os.path.exists(protocol_name): + os.mkdir(protocol_name) # Create the directory if it doesn't exist # Get absolute path of the local repository - abs_repo_path = os.path.abspath(local_repo_path) - print(f"Local repository path: {abs_repo_path}") - os.chdir(abs_repo_path) - subprocess.run(["git", "checkout", "main"]) - os.chdir("..") + abs_folder_path = os.path.abspath(protocol_name) + # Call the main conversion function redcap2reproschema( args.csv_file, - abs_repo_path, + abs_folder_path, protocol_name, protocol_display_name, protocol_description, ) - if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml index ed56cd1..262ee1c 100644 --- a/templates/redcap2rs.yaml +++ b/templates/redcap2rs.yaml @@ -9,12 +9,6 @@ protocol_name: "your_protocol_name" # Example: "My_Protocol" # This name will be displayed in the application. protocol_display_name: "Your protocol display name" -# GitHub Repository Information: -# Create a GitHub repository named 'reproschema' to store your reproschema protocols. -# Replace 'your_github_username' with your actual GitHub username. -user_name: "your_github_username" -repo_name: "reproschema" # Recommended name; can be different if preferred. - # Protocol Description: # Provide a brief description of your protocol. -protocol_description: "Description for your protocol" # Example: "This protocol is for ..." +protocol_description: "Description for your protocol" # Example: "This protocol is for ..." \ No newline at end of file From 3e72f256b69a969365a65bae1200975062b310ea Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 28 Dec 2023 20:20:23 +0000 Subject: [PATCH 26/94] add test for redcap2reproschema --- reproschema/tests/test_data/redcap2rs.yaml | 21 +++++++++++++ reproschema/tests/test_data/redcap_dict.csv | 31 ++++++++++++++++++++ reproschema/tests/test_redcap2reproschema.py | 28 ++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 reproschema/tests/test_data/redcap2rs.yaml create mode 100644 reproschema/tests/test_data/redcap_dict.csv create mode 100644 reproschema/tests/test_redcap2reproschema.py diff --git a/reproschema/tests/test_data/redcap2rs.yaml b/reproschema/tests/test_data/redcap2rs.yaml new file mode 100644 index 0000000..3330f3b --- /dev/null +++ b/reproschema/tests/test_data/redcap2rs.yaml @@ -0,0 +1,21 @@ +# Reproschema Protocol Configuration + +# Protocol Name: +# Use underscores for spaces and avoid special characters. +# This is the unique identifier for your protocol. +protocol_name: "test_redcap2rs" # Example: "My_Protocol" + +# Protocol Display Name: +# This name will be displayed in the application. +protocol_display_name: "redcap protocols" + +# GitHub Repository Information: +# Create a GitHub repository named 'reproschema' to store your reproschema protocols. +# Replace 'your_github_username' with your actual GitHub username. +user_name: "yibeichan" +repo_name: "redcap2reproschema" # Recommended name; can be different if preferred. +repo_url: "https://github.com/{{user_name}}/{{repo_name}}" + +# Protocol Description: +# Provide a brief description of your protocol. +protocol_description: "testing" # Example: "This protocol is for ..." diff --git a/reproschema/tests/test_data/redcap_dict.csv b/reproschema/tests/test_data/redcap_dict.csv new file mode 100644 index 0000000..6f48394 --- /dev/null +++ b/reproschema/tests/test_data/redcap_dict.csv @@ -0,0 +1,31 @@ +"Variable / Field Name","Form Name","Section Header","Field Type","Field Label","Choices, Calculations, OR Slider Labels","Field Note","Text Validation Type OR Show Slider Number","Text Validation Min","Text Validation Max",Identifier?,"Branching Logic (Show field only if...)","Required Field?","Custom Alignment","Question Number (surveys only)","Matrix Group Name","Matrix Ranking?","Field Annotation" +record_id,autism_parenting_stress_index_apsi,,text,"Record ID",,,,,,,,,,,,, +apsi_date,autism_parenting_stress_index_apsi,"Autism Parenting Stress Index for the Qigong Sensory Training Program Instructions: 1. Before beginning Qigong Sensory Training therapy with your child, complete the form on the following page. 2. Enter the date, name of your child, and who is completing the checklist. (It is very important that the same parent/caretaker complete the form each time the form is used.) 3. Choose the response for each item that most accurately describes your child. 4. Add all of the numbers chosen. 5. Enter total into the space provided. After using Qigong Sensory Training therapy on your child once a day for a five months, have the same parent complete the form again. Total numbers circled. Compare this number to the number at the beginning. If Qigong Sensory Training therapy is being implemented successfully, the total number should decrease over time.",text,Date:,,,date_ymd,,,,,,,,,, +apsi_name_of_child,autism_parenting_stress_index_apsi,,text,"Name of child:",,,,,,,,,,,,, +apsi_person_completing,autism_parenting_stress_index_apsi,,text,"Person completing checklist:",,,,,,,,,,,,, +apsi_social_dev,autism_parenting_stress_index_apsi,"Stress Ratings Please rate the following aspects of your child's health according to how much stress it causes you and/or your family by clicking on the button that best describes your situation.",radio,"Your child's social development ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_communicate,autism_parenting_stress_index_apsi,,radio,"Your child's ability to communicate ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_tantrums,autism_parenting_stress_index_apsi,,radio,"Tantrums/meltdowns ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_agressive,autism_parenting_stress_index_apsi,,radio,"Aggressive behavior (siblings, peers) ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_self_injure,autism_parenting_stress_index_apsi,,radio,"Self-injurious behavior ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_transitions,autism_parenting_stress_index_apsi,,radio,"Difficulty making transitions from one activity to another ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_sleep,autism_parenting_stress_index_apsi,,radio,"Sleep problems ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_diet,autism_parenting_stress_index_apsi,,radio,"Your child's diet ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_bowel,autism_parenting_stress_index_apsi,,radio,"Bowel problems (diarrhea, constipation) ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_potty,autism_parenting_stress_index_apsi,,radio,"Potty training ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_not_close,autism_parenting_stress_index_apsi,,radio,"Not feeling close to your child ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_accepted,autism_parenting_stress_index_apsi,,radio,"Concern for the future of your child being accepted by others ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_independently,autism_parenting_stress_index_apsi,,radio,"Concern for the future of your child living independently ","0, 0 - Not stressful | 1, 1 - Sometimes creates stress | 2, 2 - Often creates stress | 3, 3 - Very stressful on a daily basis | 5, 5 - So stressful sometimes we feel we can't cope",,,,,,,,,,,, +apsi_total,autism_parenting_stress_index_apsi,,text,Total,,,integer,,,,,,,,,, +cams_r_1,cognitive_and_affective_mindfulness_scalerevised_c,"Instructions: People have a variety of ways of relating to their thoughts and feelings. For each of the items below, rate how much each of these ways applies to you.",radio,"1. It is easy for me to concentrate on what I am doing.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_2,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"2. I am preoccupied by the future.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_3,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"3. I can tolerate emotional pain.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_4,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"4. I can accept things I cannot change.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_5,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"5. I can usually describe how I feel at the moment in considerable detail.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_6,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"6. I am easily distracted.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_7,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"7. I am preoccupied by the past.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_8,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"8. It's easy for me to keep track of my thoughts and feelings.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_9,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"9. I try to notice my thoughts without judging them.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_10,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"10. I am able to accept the thoughts and feelings I have.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_11,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"11. I am able to focus on the present moment.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, +cams_r_12,cognitive_and_affective_mindfulness_scalerevised_c,,radio,"12. I am able to pay close attention to one thing for a long period of time.","1, 1 - Rarely/Not at all | 2, 2 - Sometimes | 3, 3 - Often | 4, 4 - Almost Always",,,,,,,,,,,, diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py new file mode 100644 index 0000000..776f0e6 --- /dev/null +++ b/reproschema/tests/test_redcap2reproschema.py @@ -0,0 +1,28 @@ +import os +import shutil +import pytest +from click.testing import CliRunner +from ..cli import main # Import the Click group + +# Assuming your test files are located in a 'tests' directory +CSV_FILE_NAME = "redcap_dict.csv" +YAML_FILE_NAME = "redcap2rs.yaml" +CSV_TEST_FILE = os.path.join( + os.path.dirname(__file__), "test_data", CSV_FILE_NAME +) +YAML_TEST_FILE = os.path.join( + os.path.dirname(__file__), "test_data", YAML_FILE_NAME +) + +def test_redcap2reproschema_success(): + runner = CliRunner() + + with runner.isolated_filesystem(): + # Copy the test files to the isolated filesystem + shutil.copy(CSV_TEST_FILE, CSV_FILE_NAME) + shutil.copy(YAML_TEST_FILE, YAML_FILE_NAME) + + # Run the command within the isolated filesystem + result = runner.invoke(main, ['redcap2reproschema', CSV_FILE_NAME, YAML_FILE_NAME]) + print(result.output) + assert result.exit_code == 0 \ No newline at end of file From 587b388cb61929f103e10e625b3eb8d49d2279de Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 28 Dec 2023 20:20:36 +0000 Subject: [PATCH 27/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/redcap2reproschema.py | 12 ++++++++---- reproschema/tests/test_redcap2reproschema.py | 15 +++++++-------- templates/redcap2rs.yaml | 2 +- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 03a8e54..fe8a80e 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -475,15 +475,18 @@ def redcap2reproschema( protocol_visibility_obj, ) + def main(): - parser = argparse.ArgumentParser(description="Convert REDCap data dictionary to Reproschema format.") + parser = argparse.ArgumentParser( + description="Convert REDCap data dictionary to Reproschema format." + ) parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") parser.add_argument("yaml_file", help="Path to the Reproschema protocol YAML file.") args = parser.parse_args() # Read the YAML configuration with open(args.yaml_file, "r") as f: - protocol = yaml.safe_load(f) + protocol = yaml.safe_load(f) protocol_name = protocol.get("protocol_name") protocol_display_name = protocol.get("protocol_display_name") @@ -492,7 +495,7 @@ def main(): if not protocol_name: raise ValueError("Protocol name not specified in the YAML file.") - protocol_name = protocol_name.replace(' ', '_') # Replacing spaces with underscores + protocol_name = protocol_name.replace(" ", "_") # Replacing spaces with underscores # Check if the directory already exists if not os.path.exists(protocol_name): @@ -510,5 +513,6 @@ def main(): protocol_description, ) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py index 776f0e6..de2f630 100644 --- a/reproschema/tests/test_redcap2reproschema.py +++ b/reproschema/tests/test_redcap2reproschema.py @@ -7,12 +7,9 @@ # Assuming your test files are located in a 'tests' directory CSV_FILE_NAME = "redcap_dict.csv" YAML_FILE_NAME = "redcap2rs.yaml" -CSV_TEST_FILE = os.path.join( - os.path.dirname(__file__), "test_data", CSV_FILE_NAME -) -YAML_TEST_FILE = os.path.join( - os.path.dirname(__file__), "test_data", YAML_FILE_NAME -) +CSV_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_data", CSV_FILE_NAME) +YAML_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_data", YAML_FILE_NAME) + def test_redcap2reproschema_success(): runner = CliRunner() @@ -23,6 +20,8 @@ def test_redcap2reproschema_success(): shutil.copy(YAML_TEST_FILE, YAML_FILE_NAME) # Run the command within the isolated filesystem - result = runner.invoke(main, ['redcap2reproschema', CSV_FILE_NAME, YAML_FILE_NAME]) + result = runner.invoke( + main, ["redcap2reproschema", CSV_FILE_NAME, YAML_FILE_NAME] + ) print(result.output) - assert result.exit_code == 0 \ No newline at end of file + assert result.exit_code == 0 diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml index 262ee1c..1e1dbc3 100644 --- a/templates/redcap2rs.yaml +++ b/templates/redcap2rs.yaml @@ -11,4 +11,4 @@ protocol_display_name: "Your protocol display name" # Protocol Description: # Provide a brief description of your protocol. -protocol_description: "Description for your protocol" # Example: "This protocol is for ..." \ No newline at end of file +protocol_description: "Description for your protocol" # Example: "This protocol is for ..." From a4e21a1212a142ce01e86a2710a5fa6f66607136 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 28 Dec 2023 20:23:22 +0000 Subject: [PATCH 28/94] missing commits fpr cli --- reproschema/cli.py | 10 +---- reproschema/redcap2reproschema.py | 66 +++++++++++++------------------ 2 files changed, 28 insertions(+), 48 deletions(-) diff --git a/reproschema/cli.py b/reproschema/cli.py index 663ce56..317d64f 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -1,10 +1,9 @@ import os import click -import yaml from . import get_logger, set_logger_level from . import __version__ -from .redcap2reproschema import main as redcap2rs +from .redcap2reproschema import redcap2reproschema as redcap2rs lgr = get_logger() @@ -105,14 +104,7 @@ def serve(port): def redcap2reproschema(csv_path, yaml_path): """ Convert REDCap CSV files to Reproschema format. - - Provide the path to the REDCap CSV file and the YAML configuration file. """ - if not os.path.exists(csv_path): - raise click.ClickException(f"CSV file not found at {csv_path}") - if not os.path.exists(yaml_path): - raise click.ClickException(f"YAML file not found at {yaml_path}") - try: redcap2rs(csv_path, yaml_path) click.echo("Converted REDCap data dictionary to Reproschema format.") diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 03a8e54..f1a1d6e 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -303,7 +303,7 @@ def parse_language_iso_codes(input_string): def process_csv( - csv_path, + csv_file, abs_folder_path, schema_context_url, schema_map, @@ -317,7 +317,7 @@ def process_csv( order = {} languages = [] - with open(csv_path, mode="r", encoding="utf-8") as csvfile: + with open(csv_file, mode="r", encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) for row in reader: form_name = row["Form Name"] @@ -352,21 +352,35 @@ def process_csv( return datas, order, languages -def redcap2reproschema( - csv_path, - abs_folder_path, - protocol_name, - protocol_display_name, - protocol_description, - schema_context_url=None, -): +def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): """ Convert a REDCap data dictionary to Reproschema format. - :param csv_path: Path to the REDCap CSV file. + :param csv_file: Path to the REDCap CSV file. :param yaml_path: Path to the YAML configuration file. :param schema_context_url: URL of the schema context. Optional. """ + + # Read the YAML configuration + with open(yaml_file, "r") as f: + protocol = yaml.safe_load(f) + + protocol_name = protocol.get("protocol_name") + protocol_display_name = protocol.get("protocol_display_name") + protocol_description = protocol.get("protocol_description") + + if not protocol_name: + raise ValueError("Protocol name not specified in the YAML file.") + + protocol_name = protocol_name.replace(' ', '_') # Replacing spaces with underscores + + # Check if the directory already exists + if not os.path.exists(protocol_name): + os.mkdir(protocol_name) # Create the directory if it doesn't exist + + # Get absolute path of the local repository + abs_folder_path = os.path.abspath(protocol_name) + if schema_context_url is None: schema_context_url = "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic" @@ -410,7 +424,7 @@ def redcap2reproschema( # Process the CSV file datas, order, _ = process_csv( - csv_path, + csv_file, abs_folder_path, schema_context_url, schema_map, @@ -481,34 +495,8 @@ def main(): parser.add_argument("yaml_file", help="Path to the Reproschema protocol YAML file.") args = parser.parse_args() - # Read the YAML configuration - with open(args.yaml_file, "r") as f: - protocol = yaml.safe_load(f) - - protocol_name = protocol.get("protocol_name") - protocol_display_name = protocol.get("protocol_display_name") - protocol_description = protocol.get("protocol_description") - - if not protocol_name: - raise ValueError("Protocol name not specified in the YAML file.") - - protocol_name = protocol_name.replace(' ', '_') # Replacing spaces with underscores - - # Check if the directory already exists - if not os.path.exists(protocol_name): - os.mkdir(protocol_name) # Create the directory if it doesn't exist - - # Get absolute path of the local repository - abs_folder_path = os.path.abspath(protocol_name) - # Call the main conversion function - redcap2reproschema( - args.csv_file, - abs_folder_path, - protocol_name, - protocol_display_name, - protocol_description, - ) + redcap2reproschema(args.csv_file, args.yaml_file) if __name__ == "__main__": main() \ No newline at end of file From 8838e0620fedb061177a85efac72688852126163 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 28 Dec 2023 20:28:14 +0000 Subject: [PATCH 29/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/redcap2reproschema.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 85c1bbb..54ac316 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -349,6 +349,7 @@ def process_csv( os.makedirs(f"{abs_folder_path}/protocols/{protocol_name}", exist_ok=True) return datas, order, languages + def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): """ Convert a REDCap data dictionary to Reproschema format. @@ -360,7 +361,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): # Read the YAML configuration with open(yaml_file, "r") as f: - protocol = yaml.safe_load(f) + protocol = yaml.safe_load(f) protocol_name = protocol.get("protocol_name") protocol_display_name = protocol.get("protocol_display_name") @@ -369,7 +370,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): if not protocol_name: raise ValueError("Protocol name not specified in the YAML file.") - protocol_name = protocol_name.replace(' ', '_') # Replacing spaces with underscores + protocol_name = protocol_name.replace(" ", "_") # Replacing spaces with underscores # Check if the directory already exists if not os.path.exists(protocol_name): @@ -486,6 +487,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): protocol_visibility_obj, ) + def main(): parser = argparse.ArgumentParser( description="Convert REDCap data dictionary to Reproschema format." @@ -497,5 +499,6 @@ def main(): # Call the main conversion function redcap2reproschema(args.csv_file, args.yaml_file) + if __name__ == "__main__": main() From ad2bab44d49ed2ef8f2842bb236f5be81bfd0231 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 28 Dec 2023 21:07:37 +0000 Subject: [PATCH 30/94] add cli for rs2redcap (need test data) --- reproschema/cli.py | 12 +++--- reproschema/reproschema2redcap.py | 1 + reproschema/tests/test_reproschema2redcap.py | 43 ++++++++++++++++++++ 3 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 reproschema/tests/test_reproschema2redcap.py diff --git a/reproschema/cli.py b/reproschema/cli.py index b7fcfe5..1827875 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -1,5 +1,6 @@ import os import click +from pathlib import Path from . import get_logger, set_logger_level from . import __version__ @@ -104,11 +105,8 @@ def serve(port): def reproschema2redcap(input_path, output_csv_path): """ Convert reproschema JSON to Redcap CSV format. - - INPUT_PATH: Directory containing reproschema JSON files. - OUTPUT_CSV_PATH: Path to the output CSV file. """ - rs2redcap(input_path, output_csv_path) - click.echo( - f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}" - ) + # Convert input_path to a Path object + input_path_obj = Path(input_path) + rs2redcap(input_path_obj, output_csv_path) + click.echo(f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}") \ No newline at end of file diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 3400d51..05350fc 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -121,6 +121,7 @@ def get_csv_data(dir_path): relative_activity_path.lstrip("../") ) activity_path = dir_path / normalized_relative_path + print(f"Processing activity {activity_path}") parsed_activity_json = read_json_file(activity_path) if parsed_activity_json: diff --git a/reproschema/tests/test_reproschema2redcap.py b/reproschema/tests/test_reproschema2redcap.py new file mode 100644 index 0000000..374d8b7 --- /dev/null +++ b/reproschema/tests/test_reproschema2redcap.py @@ -0,0 +1,43 @@ +import os +import pytest +from click.testing import CliRunner +from ..cli import main +from shutil import copytree +from pathlib import Path +import csv + +def test_reproschema2redcap_success(): + runner = CliRunner() + + with runner.isolated_filesystem(): + # Copy necessary test data into the isolated filesystem + original_data_dir = os.path.join(os.path.dirname(__file__), "test_rs2redcap_data") + copytree(original_data_dir, "input_data") + + input_path = Path("input_data") # Using Path object + output_csv_path = "output.csv" + + # Invoke the reproschema2redcap command + result = runner.invoke(main, ['reproschema2redcap', str(input_path), output_csv_path]) + + # Print the output for debugging + print(result.output) + + # Assert the expected outcomes + assert result.exit_code == 0 + assert f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}" in result.output + + # Check if the output CSV file has been created + assert os.path.exists(output_csv_path) + + # Read and print the contents of the CSV file + with open(output_csv_path, 'r', encoding='utf-8') as csv_file: + reader = csv.reader(csv_file) + csv_contents = list(reader) + print("CSV File Contents:") + for row in csv_contents: + print(row) + + # Optionally, assert conditions about the CSV contents + # For example, assert that the file is not empty + assert len(csv_contents) > 0 \ No newline at end of file From ad7191a728db6f1c9038b2624c2406179661deb4 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 28 Dec 2023 21:12:04 +0000 Subject: [PATCH 31/94] remove protocol_variable_map --- reproschema/redcap2reproschema.py | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 85c1bbb..d71f15c 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -226,15 +226,11 @@ def create_form_schema( def process_activities( - activity_name, protocol_visibility_obj, protocol_variable_map, protocol_order + activity_name, protocol_visibility_obj, protocol_order ): # Set default visibility condition protocol_visibility_obj[activity_name] = True - # Add activity to variableMap and Order - protocol_variable_map.append( - {"variableName": activity_name, "isAbout": f"items/{activity_name}"} - ) protocol_order.append(activity_name) @@ -244,21 +240,19 @@ def create_protocol_schema( protocol_name, protocol_display_name, protocol_description, - protocol_variable_map, protocol_order, protocol_visibility_obj, ): # Construct the protocol schema protocol_schema = { "@context": schema_context_url, - "@type": "reproschema:ActivitySet", + "@type": "reproschema:Protocol", "@id": f"{protocol_name}_schema", "skos:prefLabel": protocol_display_name, "skos:altLabel": f"{protocol_name}_schema", "schema:description": protocol_description, "schema:schemaVersion": "1.0.0-rc4", "schema:version": "0.0.1", - "variableMap": protocol_variable_map, "ui": { "addProperties": [], "order": protocol_order, @@ -432,7 +426,6 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): protocol_name, ) # Initialize other variables for protocol context and schema - protocol_variable_map = [] protocol_visibility_obj = {} protocol_order = [] @@ -471,7 +464,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): ) process_activities( - form_name, protocol_visibility_obj, protocol_variable_map, protocol_order + form_name, protocol_visibility_obj, protocol_order ) # Create protocol schema @@ -481,7 +474,6 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): protocol_name, protocol_display_name, protocol_description, - protocol_variable_map, protocol_order, protocol_visibility_obj, ) From e5e60915c5235914bf17964176745d065d77484c Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 28 Dec 2023 21:13:55 +0000 Subject: [PATCH 32/94] fix protocol path --- reproschema/redcap2reproschema.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 07543a1..1111f9a 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -340,7 +340,7 @@ def process_csv( additional_notes_list, ) - os.makedirs(f"{abs_folder_path}/protocols/{protocol_name}", exist_ok=True) + os.makedirs(f"{abs_folder_path}/{protocol_name}", exist_ok=True) return datas, order, languages From f5dd9c5b646e09a0b2ff6f11218696d88ce00ff3 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 28 Dec 2023 21:14:16 +0000 Subject: [PATCH 33/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/redcap2reproschema.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 1111f9a..16b80c7 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -225,9 +225,7 @@ def create_form_schema( print(f"Error writing to file {file_path}: {e}") -def process_activities( - activity_name, protocol_visibility_obj, protocol_order -): +def process_activities(activity_name, protocol_visibility_obj, protocol_order): # Set default visibility condition protocol_visibility_obj[activity_name] = True @@ -464,9 +462,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): scores_list, ) - process_activities( - form_name, protocol_visibility_obj, protocol_order - ) + process_activities(form_name, protocol_visibility_obj, protocol_order) # Create protocol schema create_protocol_schema( From ba5a62b3406d77df77c251095c31e08471dbef09 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 14:59:46 -0500 Subject: [PATCH 34/94] add developer mode installation --- README.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8eedf83..d0249dc 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,7 @@ # Reproschema Python library and Command Line Interface (CLI) - -### Installation +## Installation reproschema requires Python 3.7+. @@ -11,6 +10,16 @@ reproschema requires Python 3.7+. pip install reproschema ``` +### Developer installation + +To install in developer mode: + +``` +git clone git@github.com:ReproNim/reproschema-py.git +cd reproschema-py +pip install -e ".[dev]" +``` + ## CLI usage This package installs `reproschema` a CLI. From f511f323b2a7d878d155bb4bd11b8ebd27792244 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 20:12:14 +0000 Subject: [PATCH 35/94] manually resolve conflicts --- reproschema/cli.py | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/reproschema/cli.py b/reproschema/cli.py index 362a798..30bb939 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -100,18 +100,6 @@ def serve(port): start_server(port=port) -@main.command() -@click.argument("csv_path", type=click.Path(exists=True, dir_okay=False)) -@click.argument("yaml_path", type=click.Path(exists=True, dir_okay=False)) -def redcap2reproschema(csv_path, yaml_path): - """ - Convert REDCap CSV files to Reproschema format. - """ - try: - redcap2rs(csv_path, yaml_path) - click.echo("Converted REDCap data dictionary to Reproschema format.") - except Exception as e: - raise click.ClickException(f"Error during conversion: {e}") @main.command() @click.argument("csv_path", type=click.Path(exists=True, dir_okay=False)) @click.argument("yaml_path", type=click.Path(exists=True, dir_okay=False)) From 8bdb8ec97fd386ad6d1f6464518bb5b4f5a4726d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 8 Jan 2024 20:12:23 +0000 Subject: [PATCH 36/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/cli.py | 4 +++- reproschema/tests/test_reproschema2redcap.py | 20 ++++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/reproschema/cli.py b/reproschema/cli.py index 30bb939..edd1657 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -124,4 +124,6 @@ def reproschema2redcap(input_path, output_csv_path): # Convert input_path to a Path object input_path_obj = Path(input_path) rs2redcap(input_path_obj, output_csv_path) - click.echo(f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}") \ No newline at end of file + click.echo( + f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}" + ) diff --git a/reproschema/tests/test_reproschema2redcap.py b/reproschema/tests/test_reproschema2redcap.py index 374d8b7..f8438ac 100644 --- a/reproschema/tests/test_reproschema2redcap.py +++ b/reproschema/tests/test_reproschema2redcap.py @@ -1,37 +1,45 @@ import os import pytest from click.testing import CliRunner -from ..cli import main +from ..cli import main from shutil import copytree from pathlib import Path import csv + def test_reproschema2redcap_success(): runner = CliRunner() with runner.isolated_filesystem(): # Copy necessary test data into the isolated filesystem - original_data_dir = os.path.join(os.path.dirname(__file__), "test_rs2redcap_data") + original_data_dir = os.path.join( + os.path.dirname(__file__), "test_rs2redcap_data" + ) copytree(original_data_dir, "input_data") input_path = Path("input_data") # Using Path object output_csv_path = "output.csv" # Invoke the reproschema2redcap command - result = runner.invoke(main, ['reproschema2redcap', str(input_path), output_csv_path]) + result = runner.invoke( + main, ["reproschema2redcap", str(input_path), output_csv_path] + ) # Print the output for debugging print(result.output) # Assert the expected outcomes assert result.exit_code == 0 - assert f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}" in result.output + assert ( + f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}" + in result.output + ) # Check if the output CSV file has been created assert os.path.exists(output_csv_path) # Read and print the contents of the CSV file - with open(output_csv_path, 'r', encoding='utf-8') as csv_file: + with open(output_csv_path, "r", encoding="utf-8") as csv_file: reader = csv.reader(csv_file) csv_contents = list(reader) print("CSV File Contents:") @@ -40,4 +48,4 @@ def test_reproschema2redcap_success(): # Optionally, assert conditions about the CSV contents # For example, assert that the file is not empty - assert len(csv_contents) > 0 \ No newline at end of file + assert len(csv_contents) > 0 From 3d48305bc33ed73daaa6ac39e3ab658b8cdd87b1 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 20:31:23 +0000 Subject: [PATCH 37/94] add test data for rs2redcap --- .../autism_parenting_stress_index_apsi_schema | 277 ++++++++++++++++++ .../items/apsi_accepted | 32 ++ .../items/apsi_agressive | 32 ++ .../items/apsi_bowel | 32 ++ .../items/apsi_communicate | 32 ++ .../items/apsi_date | 10 + .../items/apsi_diet | 32 ++ .../items/apsi_independently | 32 ++ .../items/apsi_name_of_child | 10 + .../items/apsi_not_close | 32 ++ .../items/apsi_person_completing | 10 + .../items/apsi_potty | 32 ++ .../items/apsi_self_injure | 32 ++ .../items/apsi_sleep | 32 ++ .../items/apsi_social_dev | 32 ++ .../items/apsi_tantrums | 32 ++ .../items/apsi_total | 10 + .../items/apsi_transitions | 32 ++ .../items/record_id | 10 + ...ffective_mindfulness_scalerevised_c_schema | 154 ++++++++++ .../items/cams_r_1 | 28 ++ .../items/cams_r_10 | 28 ++ .../items/cams_r_11 | 28 ++ .../items/cams_r_12 | 28 ++ .../items/cams_r_2 | 28 ++ .../items/cams_r_3 | 28 ++ .../items/cams_r_4 | 28 ++ .../items/cams_r_5 | 28 ++ .../items/cams_r_6 | 28 ++ .../items/cams_r_7 | 28 ++ .../items/cams_r_8 | 28 ++ .../items/cams_r_9 | 28 ++ .../test_redcap2rs/test_redcap2rs_schema | 33 +++ 33 files changed, 1266 insertions(+) create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 create mode 100644 reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema new file mode 100644 index 0000000..c831460 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema @@ -0,0 +1,277 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Activity", + "@id": "autism_parenting_stress_index_apsi_schema", + "prefLabel": "autism_parenting_stress_index_apsi", + "description": "Default description", + "schemaVersion": "1.0.0-rc4", + "version": "0.0.1", + "ui": { + "order": [ + "items/record_id", + "items/record_id", + "items/apsi_date", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/apsi_bowel", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/apsi_bowel", + "items/apsi_potty", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/apsi_bowel", + "items/apsi_potty", + "items/apsi_not_close", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/apsi_bowel", + "items/apsi_potty", + "items/apsi_not_close", + "items/apsi_accepted", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/apsi_bowel", + "items/apsi_potty", + "items/apsi_not_close", + "items/apsi_accepted", + "items/apsi_independently", + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/apsi_bowel", + "items/apsi_potty", + "items/apsi_not_close", + "items/apsi_accepted", + "items/apsi_independently", + "items/apsi_total" + ], + "addProperties": [ + { + "variableName": "record_id", + "isAbout": "items/record_id", + "isVis": true + }, + { + "variableName": "apsi_date", + "isAbout": "items/apsi_date", + "isVis": true + }, + { + "variableName": "apsi_name_of_child", + "isAbout": "items/apsi_name_of_child", + "isVis": true + }, + { + "variableName": "apsi_person_completing", + "isAbout": "items/apsi_person_completing", + "isVis": true + }, + { + "variableName": "apsi_social_dev", + "isAbout": "items/apsi_social_dev", + "isVis": true + }, + { + "variableName": "apsi_communicate", + "isAbout": "items/apsi_communicate", + "isVis": true + }, + { + "variableName": "apsi_tantrums", + "isAbout": "items/apsi_tantrums", + "isVis": true + }, + { + "variableName": "apsi_agressive", + "isAbout": "items/apsi_agressive", + "isVis": true + }, + { + "variableName": "apsi_self_injure", + "isAbout": "items/apsi_self_injure", + "isVis": true + }, + { + "variableName": "apsi_transitions", + "isAbout": "items/apsi_transitions", + "isVis": true + }, + { + "variableName": "apsi_sleep", + "isAbout": "items/apsi_sleep", + "isVis": true + }, + { + "variableName": "apsi_diet", + "isAbout": "items/apsi_diet", + "isVis": true + }, + { + "variableName": "apsi_bowel", + "isAbout": "items/apsi_bowel", + "isVis": true + }, + { + "variableName": "apsi_potty", + "isAbout": "items/apsi_potty", + "isVis": true + }, + { + "variableName": "apsi_not_close", + "isAbout": "items/apsi_not_close", + "isVis": true + }, + { + "variableName": "apsi_accepted", + "isAbout": "items/apsi_accepted", + "isVis": true + }, + { + "variableName": "apsi_independently", + "isAbout": "items/apsi_independently", + "isVis": true + }, + { + "variableName": "apsi_total", + "isAbout": "items/apsi_total", + "isVis": true + } + ], + "shuffle": false + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date new file mode 100644 index 0000000..7310eb3 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date @@ -0,0 +1,10 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child new file mode 100644 index 0000000..7310eb3 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child @@ -0,0 +1,10 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing new file mode 100644 index 0000000..7310eb3 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing @@ -0,0 +1,10 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total new file mode 100644 index 0000000..7310eb3 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total @@ -0,0 +1,10 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions new file mode 100644 index 0000000..b4ebefd --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions @@ -0,0 +1,32 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 0, + "schema:name": "0 - Not stressful " + }, + { + "schema:value": 1, + "schema:name": "1 - Sometimes creates stress " + }, + { + "schema:value": 2, + "schema:name": "2 - Often creates stress " + }, + { + "schema:value": 3, + "schema:name": "3 - Very stressful on a daily basis " + }, + { + "schema:value": 5, + "schema:name": "5 - So stressful sometimes we feel we can't cope" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id new file mode 100644 index 0000000..7310eb3 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id @@ -0,0 +1,10 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema new file mode 100644 index 0000000..7e32adb --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema @@ -0,0 +1,154 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Activity", + "@id": "cognitive_and_affective_mindfulness_scalerevised_c_schema", + "prefLabel": "cognitive_and_affective_mindfulness_scalerevised_c", + "description": "Default description", + "schemaVersion": "1.0.0-rc4", + "version": "0.0.1", + "ui": { + "order": [ + "items/cams_r_1", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_7", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_7", + "items/cams_r_8", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_7", + "items/cams_r_8", + "items/cams_r_9", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_7", + "items/cams_r_8", + "items/cams_r_9", + "items/cams_r_10", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_7", + "items/cams_r_8", + "items/cams_r_9", + "items/cams_r_10", + "items/cams_r_11", + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_7", + "items/cams_r_8", + "items/cams_r_9", + "items/cams_r_10", + "items/cams_r_11", + "items/cams_r_12" + ], + "addProperties": [ + { + "variableName": "cams_r_1", + "isAbout": "items/cams_r_1", + "isVis": true + }, + { + "variableName": "cams_r_2", + "isAbout": "items/cams_r_2", + "isVis": true + }, + { + "variableName": "cams_r_3", + "isAbout": "items/cams_r_3", + "isVis": true + }, + { + "variableName": "cams_r_4", + "isAbout": "items/cams_r_4", + "isVis": true + }, + { + "variableName": "cams_r_5", + "isAbout": "items/cams_r_5", + "isVis": true + }, + { + "variableName": "cams_r_6", + "isAbout": "items/cams_r_6", + "isVis": true + }, + { + "variableName": "cams_r_7", + "isAbout": "items/cams_r_7", + "isVis": true + }, + { + "variableName": "cams_r_8", + "isAbout": "items/cams_r_8", + "isVis": true + }, + { + "variableName": "cams_r_9", + "isAbout": "items/cams_r_9", + "isVis": true + }, + { + "variableName": "cams_r_10", + "isAbout": "items/cams_r_10", + "isVis": true + }, + { + "variableName": "cams_r_11", + "isAbout": "items/cams_r_11", + "isVis": true + }, + { + "variableName": "cams_r_12", + "isAbout": "items/cams_r_12", + "isVis": true + } + ], + "shuffle": false + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 new file mode 100644 index 0000000..b8b6b37 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 @@ -0,0 +1,28 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Field", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:string", + "choices": [ + { + "schema:value": 1, + "schema:name": "1 - Rarely/Not at all " + }, + { + "schema:value": 2, + "schema:name": "2 - Sometimes " + }, + { + "schema:value": 3, + "schema:name": "3 - Often " + }, + { + "schema:value": 4, + "schema:name": "4 - Almost Always" + } + ] + } +} \ No newline at end of file diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema new file mode 100644 index 0000000..b013169 --- /dev/null +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema @@ -0,0 +1,33 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic", + "@type": "reproschema:Protocol", + "@id": "test_redcap2rs_schema", + "skos:prefLabel": "redcap protocols", + "skos:altLabel": "test_redcap2rs_schema", + "schema:description": "testing", + "schema:schemaVersion": "1.0.0-rc4", + "schema:version": "0.0.1", + "ui": { + "addProperties": [ + { + "isAbout": "../activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema", + "variableName": "autism_parenting_stress_index_apsi_schema", + "prefLabel": "Autism Parenting Stress Index Apsi" + }, + { + "isAbout": "../activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema", + "variableName": "cognitive_and_affective_mindfulness_scalerevised_c_schema", + "prefLabel": "Cognitive And Affective Mindfulness Scalerevised C" + } + ], + "order": [ + "autism_parenting_stress_index_apsi", + "cognitive_and_affective_mindfulness_scalerevised_c" + ], + "shuffle": false, + "visibility": { + "autism_parenting_stress_index_apsi": true, + "cognitive_and_affective_mindfulness_scalerevised_c": true + } + } +} \ No newline at end of file From 559e4f50c09330b10a7f8a03e957b7c46f8a871c Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 20:39:47 +0000 Subject: [PATCH 38/94] remove redundancy --- reproschema/cli.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/reproschema/cli.py b/reproschema/cli.py index 30bb939..8da2aaf 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -114,14 +114,14 @@ def redcap2reproschema(csv_path, yaml_path): raise click.ClickException(f"Error during conversion: {e}") -@main.command("reproschema2redcap") +@main.command() @click.argument("input_path", type=click.Path(exists=True, dir_okay=True)) @click.argument("output_csv_path", type=click.Path(writable=True)) def reproschema2redcap(input_path, output_csv_path): """ - Convert reproschema JSON to Redcap CSV format. + Convert reproschema protocol to Redcap CSV format. """ # Convert input_path to a Path object input_path_obj = Path(input_path) rs2redcap(input_path_obj, output_csv_path) - click.echo(f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}") \ No newline at end of file + click.echo(f"Converted reproschema protocol from {input_path} to Redcap CSV at {output_csv_path}") \ No newline at end of file From 7ed30f19d944eb936c512d1b039886d8c76216ad Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 15:41:17 -0500 Subject: [PATCH 39/94] move developer installation upwards --- README.md | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index d0249dc..5e11f02 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,22 @@ pip install reproschema ### Developer installation -To install in developer mode: +Install repo in developer mode: ``` -git clone git@github.com:ReproNim/reproschema-py.git +git clone https://github.com/ReproNim/reproschema-py.git cd reproschema-py -pip install -e ".[dev]" +pip install -e .[dev] ``` +It is also useful to install pre-commit, which takes care of styling when +committing code. When pre-commit is used you may have to run git commit twice, +since pre-commit may make additional changes to your code for styling and will +not commit these changes by default: + +``` +pre-commit install +``` ## CLI usage This package installs `reproschema` a CLI. @@ -40,9 +48,9 @@ Options: Log level name [default: INFO] --help Show this message and exit. -Commands: - convert +convert create + redcap2reproschema Convert REDCap CSV files to Reproschema format. serve validate ``` @@ -97,22 +105,3 @@ After configuring the YAML file: ### Notes 1. The script requires an active internet connection to access the GitHub repository. 2. Make sure you use `git add`, `git commit`, `git push` properly afterwards to maintain a good version control for your converted data. - -## Developer installation - -Install repo in developer mode: - -``` -git clone https://github.com/ReproNim/reproschema-py.git -cd reproschema-py -pip install -e .[dev] -``` - -It is also useful to install pre-commit, which takes care of styling when -committing code. When pre-commit is used you may have to run git commit twice, -since pre-commit may make additional changes to your code for styling and will -not commit these changes by default: - -``` -pre-commit install -``` From b3071e53fd0dae8d0d858f2ad1fd565f5d1e0d62 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 8 Jan 2024 20:42:42 +0000 Subject: [PATCH 40/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/cli.py | 4 +++- .../autism_parenting_stress_index_apsi_schema | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_accepted | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_agressive | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_bowel | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_communicate | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_date | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_diet | 2 +- .../items/apsi_independently | 2 +- .../items/apsi_name_of_child | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_not_close | 2 +- .../items/apsi_person_completing | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_potty | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_self_injure | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_sleep | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_social_dev | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_tantrums | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_total | 2 +- .../autism_parenting_stress_index_apsi/items/apsi_transitions | 2 +- .../autism_parenting_stress_index_apsi/items/record_id | 2 +- .../cognitive_and_affective_mindfulness_scalerevised_c_schema | 2 +- .../items/cams_r_1 | 2 +- .../items/cams_r_10 | 2 +- .../items/cams_r_11 | 2 +- .../items/cams_r_12 | 2 +- .../items/cams_r_2 | 2 +- .../items/cams_r_3 | 2 +- .../items/cams_r_4 | 2 +- .../items/cams_r_5 | 2 +- .../items/cams_r_6 | 2 +- .../items/cams_r_7 | 2 +- .../items/cams_r_8 | 2 +- .../items/cams_r_9 | 2 +- .../test_redcap2rs/test_redcap2rs/test_redcap2rs_schema | 2 +- 34 files changed, 36 insertions(+), 34 deletions(-) diff --git a/reproschema/cli.py b/reproschema/cli.py index 8da2aaf..b5290e5 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -124,4 +124,6 @@ def reproschema2redcap(input_path, output_csv_path): # Convert input_path to a Path object input_path_obj = Path(input_path) rs2redcap(input_path_obj, output_csv_path) - click.echo(f"Converted reproschema protocol from {input_path} to Redcap CSV at {output_csv_path}") \ No newline at end of file + click.echo( + f"Converted reproschema protocol from {input_path} to Redcap CSV at {output_csv_path}" + ) diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema index c831460..6ab115c 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema @@ -274,4 +274,4 @@ ], "shuffle": false } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date index 7310eb3..9ea1ef5 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date @@ -7,4 +7,4 @@ "responseOptions": { "valueType": "xsd:string" } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child index 7310eb3..9ea1ef5 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child @@ -7,4 +7,4 @@ "responseOptions": { "valueType": "xsd:string" } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing index 7310eb3..9ea1ef5 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing @@ -7,4 +7,4 @@ "responseOptions": { "valueType": "xsd:string" } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total index 7310eb3..9ea1ef5 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total @@ -7,4 +7,4 @@ "responseOptions": { "valueType": "xsd:string" } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions index b4ebefd..f6327ed 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions @@ -29,4 +29,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id index 7310eb3..9ea1ef5 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id @@ -7,4 +7,4 @@ "responseOptions": { "valueType": "xsd:string" } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema index 7e32adb..a16c618 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema @@ -151,4 +151,4 @@ ], "shuffle": false } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 index b8b6b37..61872e6 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 @@ -25,4 +25,4 @@ } ] } -} \ No newline at end of file +} diff --git a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema index b013169..02382d8 100644 --- a/reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema +++ b/reproschema/tests/test_rs2redcap_data/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema @@ -30,4 +30,4 @@ "cognitive_and_affective_mindfulness_scalerevised_c": true } } -} \ No newline at end of file +} From 9772d9808667592fc4c3b5c3be695e4f53fedf1a Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 20:49:02 +0000 Subject: [PATCH 41/94] remove useless assertation --- reproschema/tests/test_reproschema2redcap.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/reproschema/tests/test_reproschema2redcap.py b/reproschema/tests/test_reproschema2redcap.py index f8438ac..c946c9b 100644 --- a/reproschema/tests/test_reproschema2redcap.py +++ b/reproschema/tests/test_reproschema2redcap.py @@ -30,11 +30,7 @@ def test_reproschema2redcap_success(): # Assert the expected outcomes assert result.exit_code == 0 - assert ( - f"Converted reproschema JSON from {input_path} to Redcap CSV at {output_csv_path}" - in result.output - ) - + # Check if the output CSV file has been created assert os.path.exists(output_csv_path) From aae814e8b60ad7f7a8fa7454af77c1a1a9ec950a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 8 Jan 2024 20:49:39 +0000 Subject: [PATCH 42/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/tests/test_reproschema2redcap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reproschema/tests/test_reproschema2redcap.py b/reproschema/tests/test_reproschema2redcap.py index c946c9b..f0a02ce 100644 --- a/reproschema/tests/test_reproschema2redcap.py +++ b/reproschema/tests/test_reproschema2redcap.py @@ -30,7 +30,7 @@ def test_reproschema2redcap_success(): # Assert the expected outcomes assert result.exit_code == 0 - + # Check if the output CSV file has been created assert os.path.exists(output_csv_path) From abba86adbab7b0cf47220f98e65c7646440d40fb Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 21:04:29 +0000 Subject: [PATCH 43/94] fix minors --- README.md | 7 ++++--- reproschema/cli.py | 2 +- .../{test_data => test_redcap2rs_data}/redcap2rs.yaml | 0 .../{test_data => test_redcap2rs_data}/redcap_dict.csv | 0 4 files changed, 5 insertions(+), 4 deletions(-) rename reproschema/tests/{test_data => test_redcap2rs_data}/redcap2rs.yaml (100%) rename reproschema/tests/{test_data => test_redcap2rs_data}/redcap_dict.csv (100%) diff --git a/README.md b/README.md index 0168670..17d18ab 100644 --- a/README.md +++ b/README.md @@ -48,12 +48,13 @@ Options: Log level name [default: INFO] --help Show this message and exit. -convert +Commands: + convert create redcap2reproschema Convert REDCap CSV files to Reproschema format. + reproschema2redcap Convert reproschema protocol to REDCap CSV format. serve validate - reproschema2redcap ``` ## `reproschema2redcap` Usage @@ -88,7 +89,7 @@ output_csv_filename = "output.csv" reproschema2redcap(input_dir_path, output_csv_filename) ``` -## redcap2reproschema Usage +## `redcap2reproschema` Usage The `redcap2reproschema` function is designed to process a given REDCap CSV file and YAML configuration to generate the output in the reproschema format. ### Prerequisites diff --git a/reproschema/cli.py b/reproschema/cli.py index b5290e5..e31b03e 100644 --- a/reproschema/cli.py +++ b/reproschema/cli.py @@ -119,7 +119,7 @@ def redcap2reproschema(csv_path, yaml_path): @click.argument("output_csv_path", type=click.Path(writable=True)) def reproschema2redcap(input_path, output_csv_path): """ - Convert reproschema protocol to Redcap CSV format. + Convert reproschema protocol to REDCap CSV format. """ # Convert input_path to a Path object input_path_obj = Path(input_path) diff --git a/reproschema/tests/test_data/redcap2rs.yaml b/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml similarity index 100% rename from reproschema/tests/test_data/redcap2rs.yaml rename to reproschema/tests/test_redcap2rs_data/redcap2rs.yaml diff --git a/reproschema/tests/test_data/redcap_dict.csv b/reproschema/tests/test_redcap2rs_data/redcap_dict.csv similarity index 100% rename from reproschema/tests/test_data/redcap_dict.csv rename to reproschema/tests/test_redcap2rs_data/redcap_dict.csv From 683bb5367f81dc5405b120d53cf668df0f23e3fc Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 21:06:31 +0000 Subject: [PATCH 44/94] match test path --- reproschema/tests/test_redcap2reproschema.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py index de2f630..815a3e2 100644 --- a/reproschema/tests/test_redcap2reproschema.py +++ b/reproschema/tests/test_redcap2reproschema.py @@ -7,8 +7,8 @@ # Assuming your test files are located in a 'tests' directory CSV_FILE_NAME = "redcap_dict.csv" YAML_FILE_NAME = "redcap2rs.yaml" -CSV_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_data", CSV_FILE_NAME) -YAML_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_data", YAML_FILE_NAME) +CSV_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_redcap2rs_data", CSV_FILE_NAME) +YAML_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_redcap2rs_data", YAML_FILE_NAME) def test_redcap2reproschema_success(): From f091fa820cc648929461911790998861933e8046 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 8 Jan 2024 21:14:28 +0000 Subject: [PATCH 45/94] reformating --- reproschema/tests/test_redcap2reproschema.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py index 815a3e2..2386a8c 100644 --- a/reproschema/tests/test_redcap2reproschema.py +++ b/reproschema/tests/test_redcap2reproschema.py @@ -7,8 +7,12 @@ # Assuming your test files are located in a 'tests' directory CSV_FILE_NAME = "redcap_dict.csv" YAML_FILE_NAME = "redcap2rs.yaml" -CSV_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_redcap2rs_data", CSV_FILE_NAME) -YAML_TEST_FILE = os.path.join(os.path.dirname(__file__), "test_redcap2rs_data", YAML_FILE_NAME) +CSV_TEST_FILE = os.path.join( + os.path.dirname(__file__), "test_redcap2rs_data", CSV_FILE_NAME +) +YAML_TEST_FILE = os.path.join( + os.path.dirname(__file__), "test_redcap2rs_data", YAML_FILE_NAME +) def test_redcap2reproschema_success(): From 82851ebf0bcc4a5fbfaa0c8bc41c69e1ca9028bc Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 9 Jan 2024 19:32:38 +0000 Subject: [PATCH 46/94] fix matching with redcap --- reproschema/reproschema2redcap.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 05350fc..03b4c64 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -30,25 +30,33 @@ def find_Ftype_and_colH(item_json, row_data): col_h = "" # Check the input type and update the field type and column header accordingly - if f_type == "integer": + if f_type in ["text", "textarea", "email"]: + f_type = "text" + elif f_type == "integer": + f_type = "text" + col_h = "integer" + elif f_type == "number" or f_type == "float": f_type = "text" col_h = "number" - elif f_type == "select": - f_type = "dropdown" elif f_type == "date": f_type = "text" - col_h = "ddate_mdy" + col_h = "date_mdy" + elif f_type in ["radio", "checkbox", "dropdown", "file"]: + # No change needed, these are valid REDCap field types + pass + else: + # Fallback for unsupported types + f_type = "text" # Update the row_data dictionary with the field type - row_data["field_type"] = f_type + row_data["field_type"] = f_type.lower() # Update the row_data dictionary with the column header if available if col_h: - row_data["val_type_OR_slider"] = col_h + row_data["val_type_OR_slider"] = col_h.lower() return row_data - def process_item(item_json, activity_name): """ Process an item in JSON format and extract relevant information into a dictionary. From 74199d720953aa6da6174d79985c478ce20b2935 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 9 Jan 2024 22:25:43 +0000 Subject: [PATCH 47/94] make better field mappings --- reproschema/reproschema2redcap.py | 106 ++++++++++++++++++++++-------- 1 file changed, 77 insertions(+), 29 deletions(-) diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 03b4c64..060b7ce 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -2,7 +2,7 @@ import json import csv from pathlib import Path - +import requests def read_json_file(file_path): try: @@ -12,7 +12,28 @@ def read_json_file(file_path): print(f"Error reading file {file_path}: {e}") return None +def fetch_choices_from_url(url): + try: + response = requests.get(url) + response.raise_for_status() + data = response.json() + + # Check if the data is a list or a dictionary and process accordingly + if isinstance(data, list): + # Assuming each item in the list is a dictionary with one key-value pair + choices = [list(item.values())[0] for item in data if isinstance(item, dict) and item] + elif isinstance(data, dict): + # Extracting the values from the dictionary + choices = list(data.values()) + else: + # If data is neither a list nor a dictionary, return an empty string + return "" + return " | ".join(str(choice) for choice in choices) + except Exception as e: + print(f"Error fetching choices from {url}: {e}") + return "" + def find_Ftype_and_colH(item_json, row_data): """ Find the field type and column header based on the given item_json. @@ -44,6 +65,9 @@ def find_Ftype_and_colH(item_json, row_data): elif f_type in ["radio", "checkbox", "dropdown", "file"]: # No change needed, these are valid REDCap field types pass + elif f_type == "select": + multiple_choice = item_json.get("responseOptions", {}).get("multipleChoice", False) + f_type = "checkbox" if multiple_choice else "radio" else: # Fallback for unsupported types f_type = "text" @@ -68,43 +92,43 @@ def process_item(item_json, activity_name): Returns: dict: A dictionary containing the extracted information. """ - row_data = {} + row_data = { + "val_min": "", + "val_max": "", + "choices": "", + "required": "", + "field_notes": "", + "var_name": "", + "activity": activity_name.lower(), + "field_label": "", + } # Extract min and max values from response options, if available response_options = item_json.get("responseOptions", {}) row_data["val_min"] = response_options.get("schema:minValue", "") row_data["val_max"] = response_options.get("schema:maxValue", "") + # 'choices' processing is now handled in 'find_Ftype_and_colH' if it's a URL choices = response_options.get("choices") - if choices: + if choices and not isinstance(choices, str): if isinstance(choices, list): - # Extract choice values and names, and join them with a '|' item_choices = [ f"{ch.get('schema:value', ch.get('value', ''))}, {ch.get('schema:name', ch.get('name', ''))}" for ch in choices ] row_data["choices"] = " | ".join(item_choices) - elif isinstance(choices, str): - row_data["choices"] = choices - else: - row_data["choices"] = "" row_data["required"] = response_options.get("requiredValue", "") - row_data["field_notes"] = item_json.get("skos:altLabel", "") - row_data["var_name"] = item_json.get("@id", "") - row_data["activity"] = activity_name question = item_json.get("question") if isinstance(question, dict): row_data["field_label"] = question.get("en", "") elif isinstance(question, str): row_data["field_label"] = question - else: - row_data["field_label"] = "" - # Call helper function to find Ftype and colH values and update row_data + # Call helper function to find field type and validation type (if any) and update row_data row_data = find_Ftype_and_colH(item_json, row_data) return row_data @@ -148,28 +172,52 @@ def get_csv_data(dir_path): def write_to_csv(csv_data, output_csv_filename): - # Define the headers for the CSV file as per the JavaScript file + # REDCap-specific headers headers = [ - "var_name", - "activity", - "section", - "field_type", - "field_label", - "choices", - "field_notes", - "val_type_OR_slider", - "val_min", - "val_max", - "identifier", - "visibility", - "required", + "Variable / Field Name", + "Form Name", + "Section Header", + "Field Type", + "Field Label", + "Choices, Calculations, OR Slider Labels", + "Field Note", + "Text Validation Type OR Show Slider Number", + "Text Validation Min", + "Text Validation Max", + "Identifier?", + "Branching Logic (Show field only if...)", + "Required Field?", + "Custom Alignment", + "Question Number (surveys only)", + "Matrix Group Name", + "Matrix Ranking?", + "Field Annotation" ] # Writing to the CSV file with open(output_csv_filename, "w", newline="", encoding="utf-8") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) - writer.writeheader() + + # Map the data from your format to REDCap format + redcap_data = [] for row in csv_data: + redcap_row = { + "Variable / Field Name": row["var_name"], + "Form Name": row["activity"], + "Section Header": "", # Update this if your data includes section headers + "Field Type": row["field_type"], + "Field Label": row["field_label"], + "Choices, Calculations, OR Slider Labels": row["choices"], + "Field Note": row["field_notes"], + "Text Validation Type OR Show Slider Number": row.get("val_type_OR_slider", ""), + "Text Validation Min": row["val_min"], + "Text Validation Max": row["val_max"], + # Add other fields as necessary based on your data + } + redcap_data.append(redcap_row) + + writer.writeheader() + for row in redcap_data: writer.writerow(row) print("The CSV file was written successfully") From ce5af6256a24c68fd74531a1f819d3f3c893ae6c Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 9 Jan 2024 23:42:40 +0000 Subject: [PATCH 48/94] fix inputype start with select --- reproschema/reproschema2redcap.py | 30 ++++++++++-------------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 060b7ce..db58d80 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -35,47 +35,37 @@ def fetch_choices_from_url(url): return "" def find_Ftype_and_colH(item_json, row_data): - """ - Find the field type and column header based on the given item_json. - - Args: - item_json (dict): The JSON object containing the item information. - row_data (dict): The row data dictionary. - - Returns: - dict: The updated row data dictionary with field type and column header. - - """ # Extract the input type from the item_json f_type = item_json.get("ui", {}).get("inputType", "") col_h = "" - # Check the input type and update the field type and column header accordingly if f_type in ["text", "textarea", "email"]: f_type = "text" elif f_type == "integer": f_type = "text" col_h = "integer" - elif f_type == "number" or f_type == "float": + elif f_type in ["number", "float"]: f_type = "text" col_h = "number" elif f_type == "date": f_type = "text" col_h = "date_mdy" - elif f_type in ["radio", "checkbox", "dropdown", "file"]: - # No change needed, these are valid REDCap field types - pass elif f_type == "select": multiple_choice = item_json.get("responseOptions", {}).get("multipleChoice", False) - f_type = "checkbox" if multiple_choice else "radio" + f_type = "checkbox" if multiple_choice else "dropdown" + elif f_type.startswith("select"): + # Adjusting for selectCountry, selectLanguage, selectState types + f_type = "radio" + choices_url = item_json.get("responseOptions", {}).get("choices", "") + if choices_url and isinstance(choices_url, str): + choices_data = fetch_choices_from_url(choices_url) + if choices_data: + row_data["choices"] = choices_data else: - # Fallback for unsupported types f_type = "text" - # Update the row_data dictionary with the field type row_data["field_type"] = f_type.lower() - # Update the row_data dictionary with the column header if available if col_h: row_data["val_type_OR_slider"] = col_h.lower() From 259a2e1f624c6867d7d9c627cc784540b2cc23b2 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 9 Jan 2024 23:49:03 +0000 Subject: [PATCH 49/94] reformat choices --- reproschema/reproschema2redcap.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index db58d80..9b2289e 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -18,18 +18,16 @@ def fetch_choices_from_url(url): response.raise_for_status() data = response.json() - # Check if the data is a list or a dictionary and process accordingly if isinstance(data, list): - # Assuming each item in the list is a dictionary with one key-value pair choices = [list(item.values())[0] for item in data if isinstance(item, dict) and item] elif isinstance(data, dict): - # Extracting the values from the dictionary choices = list(data.values()) else: - # If data is neither a list nor a dictionary, return an empty string return "" - return " | ".join(str(choice) for choice in choices) + # Format choices as 'code, description' + formatted_choices = [f"{idx}, {choice}" for idx, choice in enumerate(choices)] + return " | ".join(formatted_choices) except Exception as e: print(f"Error fetching choices from {url}: {e}") return "" From bd841467ae83b7b993159d258cd3e25186a904df Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Wed, 10 Jan 2024 03:22:59 +0000 Subject: [PATCH 50/94] account for media as input --- reproschema/reproschema2redcap.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 9b2289e..8e9d038 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -59,6 +59,8 @@ def find_Ftype_and_colH(item_json, row_data): choices_data = fetch_choices_from_url(choices_url) if choices_data: row_data["choices"] = choices_data + elif f_type.startswith(("audio", "video", "image", "document")): + f_type = "file" else: f_type = "text" From 01e6c1c8ae3e0147fed47cba7c94a82adae275e4 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 17:08:41 +0000 Subject: [PATCH 51/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/reproschema2redcap.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 8e9d038..3d03cf3 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -4,6 +4,7 @@ from pathlib import Path import requests + def read_json_file(file_path): try: with open(file_path, "r", encoding="utf-8") as file: @@ -12,6 +13,7 @@ def read_json_file(file_path): print(f"Error reading file {file_path}: {e}") return None + def fetch_choices_from_url(url): try: response = requests.get(url) @@ -19,7 +21,11 @@ def fetch_choices_from_url(url): data = response.json() if isinstance(data, list): - choices = [list(item.values())[0] for item in data if isinstance(item, dict) and item] + choices = [ + list(item.values())[0] + for item in data + if isinstance(item, dict) and item + ] elif isinstance(data, dict): choices = list(data.values()) else: @@ -31,7 +37,8 @@ def fetch_choices_from_url(url): except Exception as e: print(f"Error fetching choices from {url}: {e}") return "" - + + def find_Ftype_and_colH(item_json, row_data): # Extract the input type from the item_json f_type = item_json.get("ui", {}).get("inputType", "") @@ -49,7 +56,9 @@ def find_Ftype_and_colH(item_json, row_data): f_type = "text" col_h = "date_mdy" elif f_type == "select": - multiple_choice = item_json.get("responseOptions", {}).get("multipleChoice", False) + multiple_choice = item_json.get("responseOptions", {}).get( + "multipleChoice", False + ) f_type = "checkbox" if multiple_choice else "dropdown" elif f_type.startswith("select"): # Adjusting for selectCountry, selectLanguage, selectState types @@ -71,6 +80,7 @@ def find_Ftype_and_colH(item_json, row_data): return row_data + def process_item(item_json, activity_name): """ Process an item in JSON format and extract relevant information into a dictionary. @@ -181,7 +191,7 @@ def write_to_csv(csv_data, output_csv_filename): "Question Number (surveys only)", "Matrix Group Name", "Matrix Ranking?", - "Field Annotation" + "Field Annotation", ] # Writing to the CSV file @@ -199,7 +209,9 @@ def write_to_csv(csv_data, output_csv_filename): "Field Label": row["field_label"], "Choices, Calculations, OR Slider Labels": row["choices"], "Field Note": row["field_notes"], - "Text Validation Type OR Show Slider Number": row.get("val_type_OR_slider", ""), + "Text Validation Type OR Show Slider Number": row.get( + "val_type_OR_slider", "" + ), "Text Validation Min": row["val_min"], "Text Validation Max": row["val_max"], # Add other fields as necessary based on your data From 9f61bdbc73e5801794b87e2a1b3c575a0f7d0760 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 11 Jan 2024 21:30:09 +0000 Subject: [PATCH 52/94] allow choice to be non-integer --- reproschema/redcap2reproschema.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 16b80c7..6535334 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -53,15 +53,22 @@ def parse_field_type_and_value(data, input_type_map): return input_type, value_type - def process_choices(choices_str): choices = [] for choice in choices_str.split("|"): parts = choice.split(", ") - choice_obj = {"schema:value": int(parts[0]), "schema:name": parts[1]} + # Try to convert the first part to an integer, if it fails, keep it as a string + try: + value = int(parts[0]) + except ValueError: + value = parts[0] + + choice_obj = {"schema:value": value, "schema:name": parts[1]} + if len(parts) == 3: # TODO: handle image url choice_obj["schema:image"] = f"{parts[2]}.png" + choices.append(choice_obj) return choices From 87073fcf5720ed5f2c06a98e828a086ed927cc32 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 11 Jan 2024 23:36:30 +0000 Subject: [PATCH 53/94] add yesno fieldtype conversion --- reproschema/redcap2reproschema.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 6535334..909b554 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -33,7 +33,6 @@ def process_visibility(data): } return visibility_obj - def parse_field_type_and_value(data, input_type_map): field_type = data.get("Field Type", "") @@ -53,10 +52,17 @@ def parse_field_type_and_value(data, input_type_map): return input_type, value_type -def process_choices(choices_str): +def process_choices(field_type, choices_str): + if field_type not in ['radio', 'dropdown']: # Handle only radio and dropdown types + return None + choices = [] for choice in choices_str.split("|"): parts = choice.split(", ") + if len(parts) < 2: + print(f"Warning: Skipping invalid choice format '{choice}' in a {field_type} field") + continue + # Try to convert the first part to an integer, if it fails, keep it as a string try: value = int(parts[0]) @@ -64,15 +70,12 @@ def process_choices(choices_str): value = parts[0] choice_obj = {"schema:value": value, "schema:name": parts[1]} - if len(parts) == 3: - # TODO: handle image url + # Handle image url choice_obj["schema:image"] = f"{parts[2]}.png" - choices.append(choice_obj) return choices - def write_to_file(abs_folder_path, form_name, field_name, rowData): file_path = os.path.join( f"{abs_folder_path}", "activities", form_name, "items", f"{field_name}" @@ -131,6 +134,15 @@ def process_row( if value_type: rowData["responseOptions"] = {"valueType": value_type} + if field_type == "yesno": + rowData["responseOptions"] = { + "valueType": "xsd:boolean", + "choices": [ + {"schema:value": 1, "schema:name": "Yes"}, + {"schema:value": 0, "schema:name": "No"} + ] + } + for key, value in field.items(): if schema_map.get(key) == "allow" and value: rowData.setdefault("ui", {}).update({schema_map[key]: value.split(", ")}) From eee664ac0442849050863b53f1af18dc7051ba68 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 11 Jan 2024 23:39:40 +0000 Subject: [PATCH 54/94] fix missing argument in process_choice --- reproschema/redcap2reproschema.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 909b554..a28e261 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -158,10 +158,12 @@ def process_row( rowData.setdefault("responseOptions", {}).update({schema_map[key]: value}) elif schema_map.get(key) == "choices" and value: + # Pass both field_type and value to process_choices rowData.setdefault("responseOptions", {}).update( - {"choices": process_choices(value)} + {"choices": process_choices(field_type, value)} ) + elif schema_map.get(key) == "scoringLogic" and value: condition = normalize_condition(value) rowData.setdefault("ui", {}).update({"hidden": True}) From 2491c475009fd475640f947ab9275490c71aaf38 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Fri, 12 Jan 2024 00:09:02 +0000 Subject: [PATCH 55/94] fix language parse --- reproschema/redcap2reproschema.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index a28e261..a9b2426 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -100,10 +100,10 @@ def parse_html(input_string, default_language="en"): text = element.get_text(strip=True) if text: result[lang] = text - if not result: + if not result: # If no text was extracted result[default_language] = soup.get_text(strip=True) else: - result[default_language] = input_string + result[default_language] = soup.get_text(strip=True) # Use the entire text as default language text return result From d6685a2c10ea5a96bc1d4829c42ba675a69491ba Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Fri, 12 Jan 2024 00:28:19 +0000 Subject: [PATCH 56/94] add print --- reproschema/redcap2reproschema.py | 1 + 1 file changed, 1 insertion(+) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index a9b2426..6beb731 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -181,6 +181,7 @@ def process_row( ) elif key in ["question", "schema:description", "preamble"] and value: + print(key, value) rowData.update({schema_map[key]: parse_html(value)}) elif key == "Identifier?" and value: From b95822f7caf3e748afd648425283ff7745eec3c9 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Fri, 12 Jan 2024 00:30:38 +0000 Subject: [PATCH 57/94] add new test print --- reproschema/redcap2reproschema.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 6beb731..f6f06a2 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -144,6 +144,7 @@ def process_row( } for key, value in field.items(): + print(f"Key: {key}, Value: {value}") if schema_map.get(key) == "allow" and value: rowData.setdefault("ui", {}).update({schema_map[key]: value.split(", ")}) @@ -181,7 +182,6 @@ def process_row( ) elif key in ["question", "schema:description", "preamble"] and value: - print(key, value) rowData.update({schema_map[key]: parse_html(value)}) elif key == "Identifier?" and value: From 34b7b99e1235e4741be13b11d6d2c42a4a652ee4 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Fri, 12 Jan 2024 00:34:47 +0000 Subject: [PATCH 58/94] another print test --- reproschema/redcap2reproschema.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index f6f06a2..1f5329c 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -144,7 +144,7 @@ def process_row( } for key, value in field.items(): - print(f"Key: {key}, Value: {value}") + print(f"Schema Map Key: {schema_map.get(key)}, Original Key: {key}, Value: {value}") if schema_map.get(key) == "allow" and value: rowData.setdefault("ui", {}).update({schema_map[key]: value.split(", ")}) From 5b53e0726e179cda9a5481353981fd3f96b2ec5f Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Fri, 12 Jan 2024 00:38:59 +0000 Subject: [PATCH 59/94] fix schema_map.get(key) error --- reproschema/redcap2reproschema.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 1f5329c..349a067 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -144,7 +144,6 @@ def process_row( } for key, value in field.items(): - print(f"Schema Map Key: {schema_map.get(key)}, Original Key: {key}, Value: {value}") if schema_map.get(key) == "allow" and value: rowData.setdefault("ui", {}).update({schema_map[key]: value.split(", ")}) @@ -181,7 +180,7 @@ def process_row( {"variableName": field["Variable / Field Name"], "isVis": condition} ) - elif key in ["question", "schema:description", "preamble"] and value: + elif schema_map.get(key) in ["question", "schema:description", "preamble"] and value: rowData.update({schema_map[key]: parse_html(value)}) elif key == "Identifier?" and value: From ffed151960f8f962187145c517951edcbc447035 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Fri, 12 Jan 2024 00:42:08 +0000 Subject: [PATCH 60/94] fix presentation order in item --- reproschema/redcap2reproschema.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 349a067..0885aac 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -144,7 +144,10 @@ def process_row( } for key, value in field.items(): - if schema_map.get(key) == "allow" and value: + if schema_map.get(key) in ["question", "schema:description", "preamble"] and value: + rowData.update({schema_map[key]: parse_html(value)}) + + elif schema_map.get(key) == "allow" and value: rowData.setdefault("ui", {}).update({schema_map[key]: value.split(", ")}) elif key in ui_list and value: @@ -180,9 +183,6 @@ def process_row( {"variableName": field["Variable / Field Name"], "isVis": condition} ) - elif schema_map.get(key) in ["question", "schema:description", "preamble"] and value: - rowData.update({schema_map[key]: parse_html(value)}) - elif key == "Identifier?" and value: identifier_val = value.lower() == "y" rowData.update( From c8d915fdb8f5b43fac41e07499c1620d3d0db7f7 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 18 Jan 2024 17:09:00 +0000 Subject: [PATCH 61/94] add id to items --- reproschema/redcap2reproschema.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 0885aac..7ed5183 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -6,6 +6,7 @@ import yaml from bs4 import BeautifulSoup +matrix_group_count = {} def normalize_condition(condition_str): re_parentheses = re.compile(r"\(([0-9]*)\)") @@ -119,9 +120,19 @@ def process_row( response_list, additional_notes_list, ): + matrix_group_name = field.get("Matrix Group Name") + if matrix_group_name: + matrix_group_count[matrix_group_name] = matrix_group_count.get(matrix_group_name, 0) + 1 + item_id = f"{matrix_group_name}_{matrix_group_count[matrix_group_name]}" + else: + item_id = field["Variable / Field Name"] + rowData = { "@context": schema_context_url, "@type": "reproschema:Field", + "@id": item_id, + "prefLabel": item_id, + "description": f"{item_id} of {form_name}" } field_type = field.get("Field Type", "") From 585b516336969c47ce33d08d6efd6bb63c7d2088 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 18 Jan 2024 12:38:52 -0500 Subject: [PATCH 62/94] add test --- reproschema/redcap2reproschema.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 7ed5183..64aa1e8 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -120,12 +120,14 @@ def process_row( response_list, additional_notes_list, ): - matrix_group_name = field.get("Matrix Group Name") + global matrix_group_count + + matrix_group_name = field.get("Matrix Group Name", "") if matrix_group_name: matrix_group_count[matrix_group_name] = matrix_group_count.get(matrix_group_name, 0) + 1 item_id = f"{matrix_group_name}_{matrix_group_count[matrix_group_name]}" else: - item_id = field["Variable / Field Name"] + item_id = field.get("Variable / Field Name", "") rowData = { "@context": schema_context_url, @@ -155,6 +157,7 @@ def process_row( } for key, value in field.items(): + print(key, value, filed) if schema_map.get(key) in ["question", "schema:description", "preamble"] and value: rowData.update({schema_map[key]: parse_html(value)}) From c86d80d56e748a5f7f301df3cfa39c9a3e3bc3d6 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 18 Jan 2024 12:40:44 -0500 Subject: [PATCH 63/94] add test --- reproschema/redcap2reproschema.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 64aa1e8..a3fc5e4 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -359,6 +359,7 @@ def process_csv( languages = parse_language_iso_codes(row["Field Label"]) for field in datas[form_name]: + print(f"process_csv-field: {field}") field_name = field["Variable / Field Name"] order[form_name].append(f"items/{field_name}") process_row( @@ -518,6 +519,7 @@ def main(): parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") parser.add_argument("yaml_file", help="Path to the Reproschema protocol YAML file.") args = parser.parse_args() + print("Start processing") # Call the main conversion function redcap2reproschema(args.csv_file, args.yaml_file) From 6ec5d715a593d1168fc94a6654215b93c0c7cca1 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 18 Jan 2024 12:46:01 -0500 Subject: [PATCH 64/94] remove BOM --- reproschema/redcap2reproschema.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index a3fc5e4..10c4467 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -8,6 +8,9 @@ matrix_group_count = {} +def clean_header(header): + return {k.lstrip('\ufeff'): v for k, v in header.items()} + def normalize_condition(condition_str): re_parentheses = re.compile(r"\(([0-9]*)\)") re_non_gt_lt_equal = re.compile(r"([^>|<])=") @@ -345,6 +348,7 @@ def process_csv( with open(csv_file, mode="r", encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) for row in reader: + row = clean_header(row) form_name = row["Form Name"] if form_name not in datas: datas[form_name] = [] @@ -359,7 +363,6 @@ def process_csv( languages = parse_language_iso_codes(row["Field Label"]) for field in datas[form_name]: - print(f"process_csv-field: {field}") field_name = field["Variable / Field Name"] order[form_name].append(f"items/{field_name}") process_row( From 683f601c7f34d83857b2b6d7ca056707104bf53b Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 18 Jan 2024 12:48:54 -0500 Subject: [PATCH 65/94] add prints to test --- reproschema/redcap2reproschema.py | 1 + 1 file changed, 1 insertion(+) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 10c4467..e3e0463 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -363,6 +363,7 @@ def process_csv( languages = parse_language_iso_codes(row["Field Label"]) for field in datas[form_name]: + print(f"process_csv-field: {field}, datas: {datas}") field_name = field["Variable / Field Name"] order[form_name].append(f"items/{field_name}") process_row( From 9a35ee9aa20e527738eb7e65a99e4a65cf587a2f Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 18 Jan 2024 12:52:07 -0500 Subject: [PATCH 66/94] add prints to test --- reproschema/redcap2reproschema.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index e3e0463..b7f50c0 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -124,8 +124,9 @@ def process_row( additional_notes_list, ): global matrix_group_count - + print(f"process_row-field-before: {field}") matrix_group_name = field.get("Matrix Group Name", "") + print(f"process_row-field-after: {field}") if matrix_group_name: matrix_group_count[matrix_group_name] = matrix_group_count.get(matrix_group_name, 0) + 1 item_id = f"{matrix_group_name}_{matrix_group_count[matrix_group_name]}" From 7e931457c6cd6ac4f8bca35f665b6dfab6f12c74 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 18 Jan 2024 12:57:19 -0500 Subject: [PATCH 67/94] fix typo --- reproschema/redcap2reproschema.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index b7f50c0..4ae98d6 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -37,8 +37,9 @@ def process_visibility(data): } return visibility_obj -def parse_field_type_and_value(data, input_type_map): - field_type = data.get("Field Type", "") +def parse_field_type_and_value(field, input_type_map): + print(f"parse_field_type_and_value-field: {field}") + field_type = field.get("Field Type", "") input_type = input_type_map.get(field_type, field_type) @@ -50,7 +51,7 @@ def parse_field_type_and_value(data, input_type_map): "email": "email", "phone": "phone", } - validation_type = data.get("Text Validation Type OR Show Slider Number", "") + validation_type = field.get("Text Validation Type OR Show Slider Number", "") value_type = value_type_map.get(validation_type, "xsd:string") @@ -124,9 +125,7 @@ def process_row( additional_notes_list, ): global matrix_group_count - print(f"process_row-field-before: {field}") matrix_group_name = field.get("Matrix Group Name", "") - print(f"process_row-field-after: {field}") if matrix_group_name: matrix_group_count[matrix_group_name] = matrix_group_count.get(matrix_group_name, 0) + 1 item_id = f"{matrix_group_name}_{matrix_group_count[matrix_group_name]}" @@ -161,7 +160,6 @@ def process_row( } for key, value in field.items(): - print(key, value, filed) if schema_map.get(key) in ["question", "schema:description", "preamble"] and value: rowData.update({schema_map[key]: parse_html(value)}) From 003e850006f4e22f06886d9eda62953ed8974fbd Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 18 Jan 2024 19:17:43 -0500 Subject: [PATCH 68/94] improve responseOptions --- reproschema/redcap2reproschema.py | 40 ++++++++++++++++++------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 4ae98d6..c551b50 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -38,22 +38,31 @@ def process_visibility(data): return visibility_obj def parse_field_type_and_value(field, input_type_map): - print(f"parse_field_type_and_value-field: {field}") field_type = field.get("Field Type", "") - input_type = input_type_map.get(field_type, field_type) + # Initialize the default value type as string + value_type = "xsd:string" + + # Map certain field types directly to xsd types value_type_map = { - "number": "xsd:int", + "text": "xsd:string", "date_": "xsd:date", - "datetime_": "datetime", - "time_": "xsd:date", - "email": "email", - "phone": "phone", - } - validation_type = field.get("Text Validation Type OR Show Slider Number", "") - - value_type = value_type_map.get(validation_type, "xsd:string") + "datetime_": "xsd:dateTime", + "time_": "xsd:time", + "email": "xsd:string", + "phone": "xsd:string", + } # todo: input_type="signature" + + # Get the validation type from the field, if available + validation_type = field.get("Text Validation Type OR Show Slider Number", "").strip() + + if validation_type: + # Map the validation type to an XSD type if it's in the map + value_type = value_type_map.get(validation_type, "xsd:string") + elif field_type in ["radio", "dropdown"]: + # If there's no validation type, but the field type is radio or dropdown, use xsd:integer + value_type = "xsd:integer" return input_type, value_type @@ -74,7 +83,7 @@ def process_choices(field_type, choices_str): except ValueError: value = parts[0] - choice_obj = {"schema:value": value, "schema:name": parts[1]} + choice_obj = {"name": parts[1], "value": value} if len(parts) == 3: # Handle image url choice_obj["schema:image"] = f"{parts[2]}.png" @@ -154,8 +163,8 @@ def process_row( rowData["responseOptions"] = { "valueType": "xsd:boolean", "choices": [ - {"schema:value": 1, "schema:name": "Yes"}, - {"schema:value": 0, "schema:name": "No"} + {"name": "Yes", "value": 1}, + {"name": "No", "value": 0} ] } @@ -362,7 +371,6 @@ def process_csv( languages = parse_language_iso_codes(row["Field Label"]) for field in datas[form_name]: - print(f"process_csv-field: {field}, datas: {datas}") field_name = field["Variable / Field Name"] order[form_name].append(f"items/{field_name}") process_row( @@ -522,9 +530,7 @@ def main(): parser.add_argument("csv_file", help="Path to the REDCap data dictionary CSV file.") parser.add_argument("yaml_file", help="Path to the Reproschema protocol YAML file.") args = parser.parse_args() - print("Start processing") - # Call the main conversion function redcap2reproschema(args.csv_file, args.yaml_file) From 37853b23d69c09397c91c6b3941ab967cd24df6a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 19 Jan 2024 00:26:21 +0000 Subject: [PATCH 69/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/redcap2reproschema.py | 42 ++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index c551b50..47473cb 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -8,8 +8,10 @@ matrix_group_count = {} + def clean_header(header): - return {k.lstrip('\ufeff'): v for k, v in header.items()} + return {k.lstrip("\ufeff"): v for k, v in header.items()} + def normalize_condition(condition_str): re_parentheses = re.compile(r"\(([0-9]*)\)") @@ -37,6 +39,7 @@ def process_visibility(data): } return visibility_obj + def parse_field_type_and_value(field, input_type_map): field_type = field.get("Field Type", "") input_type = input_type_map.get(field_type, field_type) @@ -52,10 +55,12 @@ def parse_field_type_and_value(field, input_type_map): "time_": "xsd:time", "email": "xsd:string", "phone": "xsd:string", - } # todo: input_type="signature" + } # todo: input_type="signature" # Get the validation type from the field, if available - validation_type = field.get("Text Validation Type OR Show Slider Number", "").strip() + validation_type = field.get( + "Text Validation Type OR Show Slider Number", "" + ).strip() if validation_type: # Map the validation type to an XSD type if it's in the map @@ -66,15 +71,18 @@ def parse_field_type_and_value(field, input_type_map): return input_type, value_type + def process_choices(field_type, choices_str): - if field_type not in ['radio', 'dropdown']: # Handle only radio and dropdown types + if field_type not in ["radio", "dropdown"]: # Handle only radio and dropdown types return None choices = [] for choice in choices_str.split("|"): parts = choice.split(", ") if len(parts) < 2: - print(f"Warning: Skipping invalid choice format '{choice}' in a {field_type} field") + print( + f"Warning: Skipping invalid choice format '{choice}' in a {field_type} field" + ) continue # Try to convert the first part to an integer, if it fails, keep it as a string @@ -90,6 +98,7 @@ def process_choices(field_type, choices_str): choices.append(choice_obj) return choices + def write_to_file(abs_folder_path, form_name, field_name, rowData): file_path = os.path.join( f"{abs_folder_path}", "activities", form_name, "items", f"{field_name}" @@ -117,7 +126,9 @@ def parse_html(input_string, default_language="en"): if not result: # If no text was extracted result[default_language] = soup.get_text(strip=True) else: - result[default_language] = soup.get_text(strip=True) # Use the entire text as default language text + result[default_language] = soup.get_text( + strip=True + ) # Use the entire text as default language text return result @@ -136,7 +147,9 @@ def process_row( global matrix_group_count matrix_group_name = field.get("Matrix Group Name", "") if matrix_group_name: - matrix_group_count[matrix_group_name] = matrix_group_count.get(matrix_group_name, 0) + 1 + matrix_group_count[matrix_group_name] = ( + matrix_group_count.get(matrix_group_name, 0) + 1 + ) item_id = f"{matrix_group_name}_{matrix_group_count[matrix_group_name]}" else: item_id = field.get("Variable / Field Name", "") @@ -146,7 +159,7 @@ def process_row( "@type": "reproschema:Field", "@id": item_id, "prefLabel": item_id, - "description": f"{item_id} of {form_name}" + "description": f"{item_id} of {form_name}", } field_type = field.get("Field Type", "") @@ -162,16 +175,16 @@ def process_row( if field_type == "yesno": rowData["responseOptions"] = { "valueType": "xsd:boolean", - "choices": [ - {"name": "Yes", "value": 1}, - {"name": "No", "value": 0} - ] + "choices": [{"name": "Yes", "value": 1}, {"name": "No", "value": 0}], } for key, value in field.items(): - if schema_map.get(key) in ["question", "schema:description", "preamble"] and value: + if ( + schema_map.get(key) in ["question", "schema:description", "preamble"] + and value + ): rowData.update({schema_map[key]: parse_html(value)}) - + elif schema_map.get(key) == "allow" and value: rowData.setdefault("ui", {}).update({schema_map[key]: value.split(", ")}) @@ -191,7 +204,6 @@ def process_row( {"choices": process_choices(field_type, value)} ) - elif schema_map.get(key) == "scoringLogic" and value: condition = normalize_condition(value) rowData.setdefault("ui", {}).update({"hidden": True}) From 1533f114af2dab5db12fabcb791a04b2463f80b5 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Fri, 19 Jan 2024 11:55:14 -0500 Subject: [PATCH 70/94] get unique order --- reproschema/redcap2reproschema.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 47473cb..a2c5596 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -248,6 +248,10 @@ def create_form_schema( matrix_list, scores_list, ): + + # Use a set to track unique items and preserve order + unique_order = list(dict.fromkeys(order.get(form_name, []))) + # Construct the JSON-LD structure json_ld = { "@context": schema_context_url, @@ -258,7 +262,7 @@ def create_form_schema( "schemaVersion": "1.0.0-rc4", "version": "0.0.1", "ui": { - "order": order.get(form_name, []), + "order": unique_order, "addProperties": bl_list, "shuffle": False, }, From 891d5809b78703b6f38595d129d291e13ac1950f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 19 Jan 2024 16:55:29 +0000 Subject: [PATCH 71/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/redcap2reproschema.py | 1 - 1 file changed, 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index a2c5596..f267a2f 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -248,7 +248,6 @@ def create_form_schema( matrix_list, scores_list, ): - # Use a set to track unique items and preserve order unique_order = list(dict.fromkeys(order.get(form_name, []))) From 87f7a6ac6263ee05ef5a1546b5ec3ccb67b7aa0f Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 25 Jan 2024 11:25:44 -0500 Subject: [PATCH 72/94] add print for testing --- reproschema/redcap2reproschema.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index f267a2f..c6b7dfd 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -371,7 +371,9 @@ def process_csv( with open(csv_file, mode="r", encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) for row in reader: + print(f"process_csv: {row}") row = clean_header(row) + print(f"process_csv: {row} - after") form_name = row["Form Name"] if form_name not in datas: datas[form_name] = [] From 31627829ffd6c92a7897e82bb6efc243ef1b1b94 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 25 Jan 2024 11:30:34 -0500 Subject: [PATCH 73/94] update clear_header --- reproschema/redcap2reproschema.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index c6b7dfd..6f9cea4 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -10,7 +10,12 @@ def clean_header(header): - return {k.lstrip("\ufeff"): v for k, v in header.items()} + cleaned_header = {} + for k, v in header.items(): + # Strip BOM, whitespace, and enclosing quotation marks if present + cleaned_key = k.lstrip('\ufeff').strip().strip('"') + cleaned_header[cleaned_key] = v + return cleaned_header def normalize_condition(condition_str): From 64521d9e45053f2327b4ca5164d305fe289e2498 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 25 Jan 2024 12:39:08 -0500 Subject: [PATCH 74/94] remove print --- reproschema/redcap2reproschema.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 6f9cea4..f8c5fdf 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -376,9 +376,7 @@ def process_csv( with open(csv_file, mode="r", encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) for row in reader: - print(f"process_csv: {row}") row = clean_header(row) - print(f"process_csv: {row} - after") form_name = row["Form Name"] if form_name not in datas: datas[form_name] = [] From 4c1081af6f130505fcfa90132e01927409f08bee Mon Sep 17 00:00:00 2001 From: yibeichan Date: Wed, 7 Feb 2024 11:35:51 -0500 Subject: [PATCH 75/94] fix order and other errors --- reproschema/redcap2reproschema.py | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index f8c5fdf..35b758a 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -19,16 +19,24 @@ def clean_header(header): def normalize_condition(condition_str): + # Regular expressions for various pattern replacements re_parentheses = re.compile(r"\(([0-9]*)\)") re_non_gt_lt_equal = re.compile(r"([^>|<])=") re_brackets = re.compile(r"\[([^\]]*)\]") + re_extra_spaces = re.compile(r"\s+") + re_double_quotes = re.compile(r'"') + # Apply regex replacements condition_str = re_parentheses.sub(r"___\1", condition_str) condition_str = re_non_gt_lt_equal.sub(r"\1 ==", condition_str) condition_str = condition_str.replace(" and ", " && ").replace(" or ", " || ") condition_str = re_brackets.sub(r" \1 ", condition_str) - return condition_str + # Trim extra spaces and replace double quotes with single quotes + condition_str = re_extra_spaces.sub(' ', condition_str) # Reduce multiple spaces to a single space + condition_str = re_double_quotes.sub("'", condition_str) # Replace double quotes with single quotes + + return condition_str.strip() def process_visibility(data): condition = data.get("Branching Logic (Show field only if...)") @@ -245,6 +253,7 @@ def process_row( def create_form_schema( abs_folder_path, schema_context_url, + redcap_version, form_name, activity_display_name, activity_description, @@ -264,7 +273,7 @@ def create_form_schema( "prefLabel": activity_display_name, "description": activity_description, "schemaVersion": "1.0.0-rc4", - "version": "0.0.1", + "version": redcap_version, "ui": { "order": unique_order, "addProperties": bl_list, @@ -301,6 +310,7 @@ def process_activities(activity_name, protocol_visibility_obj, protocol_order): def create_protocol_schema( abs_folder_path, schema_context_url, + redcap_version, protocol_name, protocol_display_name, protocol_description, @@ -316,27 +326,27 @@ def create_protocol_schema( "skos:altLabel": f"{protocol_name}_schema", "schema:description": protocol_description, "schema:schemaVersion": "1.0.0-rc4", - "schema:version": "0.0.1", + "schema:version": redcap_version, "ui": { "addProperties": [], - "order": protocol_order, + "order": [], "shuffle": False, }, } # Populate addProperties list for activity in protocol_order: + full_path = f"../activities/{activity_name}/{activity_name}_schema" add_property = { - "isAbout": f"../activities/{activity}/{activity}_schema", + "isAbout": full_path, "variableName": f"{activity}_schema", # Assuming activity name as prefLabel, update as needed "prefLabel": activity.replace("_", " ").title(), + "isVis": protocol_visibility_obj.get(activity, True), # Default to True if not specified } protocol_schema["ui"]["addProperties"].append(add_property) - - # Add visibility if needed - if protocol_visibility_obj: - protocol_schema["ui"]["visibility"] = protocol_visibility_obj + # Add the full path to the order list + protocol_schema["ui"]["order"].append(full_path) protocol_dir = f"{abs_folder_path}/{protocol_name}" schema_file = f"{protocol_name}_schema" @@ -425,6 +435,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): protocol_name = protocol.get("protocol_name") protocol_display_name = protocol.get("protocol_display_name") protocol_description = protocol.get("protocol_description") + redcap_version = protocol.get("redcap_version") if not protocol_name: raise ValueError("Protocol name not specified in the YAML file.") @@ -520,6 +531,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): create_form_schema( abs_folder_path, schema_context_url, + redcap_version, form_name, activity_display_name, activity_description, @@ -535,6 +547,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): create_protocol_schema( abs_folder_path, schema_context_url, + redcap_version, protocol_name, protocol_display_name, protocol_description, From 50fe4ceb234e386876ed1b12ee9ed32896275679 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Wed, 7 Feb 2024 11:41:14 -0500 Subject: [PATCH 76/94] change ui yesno to radio --- reproschema/redcap2reproschema.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 35b758a..aa0e655 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -55,7 +55,11 @@ def process_visibility(data): def parse_field_type_and_value(field, input_type_map): field_type = field.get("Field Type", "") - input_type = input_type_map.get(field_type, field_type) + # Check if field_type is 'yesno' and directly assign 'radio' as the input type + if field_type == "yesno": + input_type = "radio" # Directly set to 'radio' for 'yesno' fields + else: + input_type = input_type_map.get(field_type, field_type) # Original logic # Initialize the default value type as string value_type = "xsd:string" @@ -68,7 +72,8 @@ def parse_field_type_and_value(field, input_type_map): "time_": "xsd:time", "email": "xsd:string", "phone": "xsd:string", - } # todo: input_type="signature" + # No change needed here for 'yesno', as it's handled above + } # Get the validation type from the field, if available validation_type = field.get( @@ -85,6 +90,7 @@ def parse_field_type_and_value(field, input_type_map): return input_type, value_type + def process_choices(field_type, choices_str): if field_type not in ["radio", "dropdown"]: # Handle only radio and dropdown types return None From 4359791a214e7ed1b64d58eb29482340e941859d Mon Sep 17 00:00:00 2001 From: yibeichan Date: Wed, 7 Feb 2024 11:47:16 -0500 Subject: [PATCH 77/94] fix typo --- reproschema/redcap2reproschema.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index aa0e655..3959d1b 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -342,7 +342,7 @@ def create_protocol_schema( # Populate addProperties list for activity in protocol_order: - full_path = f"../activities/{activity_name}/{activity_name}_schema" + full_path = f"../activities/{activity}/{activity}_schema" add_property = { "isAbout": full_path, "variableName": f"{activity}_schema", From b17b5c7c93dc492104f3720dd4ddbd7702a2b905 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 22 Feb 2024 17:09:00 -0500 Subject: [PATCH 78/94] update context, field->item, fix isVis --- reproschema/redcap2reproschema.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 3959d1b..b9e223c 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -25,15 +25,21 @@ def normalize_condition(condition_str): re_brackets = re.compile(r"\[([^\]]*)\]") re_extra_spaces = re.compile(r"\s+") re_double_quotes = re.compile(r'"') + re_or = re.compile(r'\bor\b') # Match 'or' as whole word # Apply regex replacements condition_str = re_parentheses.sub(r"___\1", condition_str) condition_str = re_non_gt_lt_equal.sub(r"\1 ==", condition_str) - condition_str = condition_str.replace(" and ", " && ").replace(" or ", " || ") condition_str = re_brackets.sub(r" \1 ", condition_str) + # Replace 'or' with '||', ensuring not to replace '||' + condition_str = re_or.sub('||', condition_str) + + # Replace 'and' with '&&' + condition_str = condition_str.replace(" and ", " && ") + # Trim extra spaces and replace double quotes with single quotes - condition_str = re_extra_spaces.sub(' ', condition_str) # Reduce multiple spaces to a single space + condition_str = re_extra_spaces.sub(' ', condition_str).strip() # Reduce multiple spaces to a single space condition_str = re_double_quotes.sub("'", condition_str) # Replace double quotes with single quotes return condition_str.strip() @@ -175,7 +181,7 @@ def process_row( rowData = { "@context": schema_context_url, - "@type": "reproschema:Field", + "@type": "reproschema:Item", "@id": item_id, "prefLabel": item_id, "description": f"{item_id} of {form_name}", @@ -456,7 +462,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): abs_folder_path = os.path.abspath(protocol_name) if schema_context_url is None: - schema_context_url = "https://raw.githubusercontent.com/ReproNim/reproschema/1.0.0-rc4/contexts/generic" + schema_context_url = "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new" # Initialize variables schema_map = { From ca3162de5bed4017ea9088ec1f8ae04f62d2a655 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Thu, 22 Feb 2024 21:35:12 -0500 Subject: [PATCH 79/94] remove useless due to failed validation --- reproschema/redcap2reproschema.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index b9e223c..d3aee9d 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -119,7 +119,7 @@ def process_choices(field_type, choices_str): choice_obj = {"name": parts[1], "value": value} if len(parts) == 3: # Handle image url - choice_obj["schema:image"] = f"{parts[2]}.png" + choice_obj["image"] = f"{parts[2]}.png" choices.append(choice_obj) return choices @@ -205,7 +205,7 @@ def process_row( for key, value in field.items(): if ( - schema_map.get(key) in ["question", "schema:description", "preamble"] + schema_map.get(key) in ["question", "description", "preamble"] and value ): rowData.update({schema_map[key]: parse_html(value)}) @@ -334,11 +334,11 @@ def create_protocol_schema( "@context": schema_context_url, "@type": "reproschema:Protocol", "@id": f"{protocol_name}_schema", - "skos:prefLabel": protocol_display_name, - "skos:altLabel": f"{protocol_name}_schema", - "schema:description": protocol_description, - "schema:schemaVersion": "1.0.0-rc4", - "schema:version": redcap_version, + "prefLabel": protocol_display_name, + # "altLabel": f"{protocol_name}_schema", + "description": protocol_description, + "schemaVersion": "1.0.0-rc4", + "version": redcap_version, "ui": { "addProperties": [], "order": [], From 4288f8aa2bd7a1ae9e48643fa2a538854e310d00 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Fri, 23 Feb 2024 15:28:41 -0500 Subject: [PATCH 80/94] remove visibility at the item level & remove matrixInfo --- reproschema/redcap2reproschema.py | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index d3aee9d..b1dcd52 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -239,12 +239,6 @@ def process_row( } ) - elif schema_map.get(key) == "visibility" and value: - condition = normalize_condition(value) - rowData.setdefault("visibility", []).append( - {"variableName": field["Variable / Field Name"], "isVis": condition} - ) - elif key == "Identifier?" and value: identifier_val = value.lower() == "y" rowData.update( @@ -293,8 +287,9 @@ def create_form_schema( }, } - if matrix_list: - json_ld["matrixInfo"] = matrix_list + # remove matrixInfo to pass validataion + # if matrix_list: + # json_ld["matrixInfo"] = matrix_list if scores_list: json_ld["scoringLogic"] = scores_list @@ -335,7 +330,7 @@ def create_protocol_schema( "@type": "reproschema:Protocol", "@id": f"{protocol_name}_schema", "prefLabel": protocol_display_name, - # "altLabel": f"{protocol_name}_schema", + "altLabel": f"{protocol_name}_schema", "description": protocol_description, "schemaVersion": "1.0.0-rc4", "version": redcap_version, From 57ca52e16d3966dd0ef03cc73cea74fc874b9bcf Mon Sep 17 00:00:00 2001 From: yibeichan Date: Sun, 25 Feb 2024 17:54:03 -0500 Subject: [PATCH 81/94] fix choice --- reproschema/redcap2reproschema.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index b1dcd52..8afdc5b 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -116,10 +116,11 @@ def process_choices(field_type, choices_str): except ValueError: value = parts[0] - choice_obj = {"name": parts[1], "value": value} - if len(parts) == 3: - # Handle image url - choice_obj["image"] = f"{parts[2]}.png" + choice_obj = {"name": " ".join(parts[1:]), "value": value} + # remove image for now + # if len(parts) == 3: + # # Handle image url + # choice_obj["image"] = f"{parts[2]}.png" choices.append(choice_obj) return choices From 82e2300566080acd5cef3b0225510abe9fb2eea0 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Wed, 28 Feb 2024 11:33:26 -0500 Subject: [PATCH 82/94] remove identifier --- reproschema/redcap2reproschema.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 8afdc5b..d7d881c 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -240,15 +240,15 @@ def process_row( } ) - elif key == "Identifier?" and value: - identifier_val = value.lower() == "y" - rowData.update( - { - schema_map[key]: [ - {"legalStandard": "unknown", "isIdentifier": identifier_val} - ] - } - ) + # elif key == "Identifier?" and value: + # identifier_val = value.lower() == "y" + # rowData.update( + # { + # schema_map[key]: [ + # {"legalStandard": "unknown", "isIdentifier": identifier_val} + # ] + # } + # ) elif key in additional_notes_list and value: notes_obj = {"source": "redcap", "column": key, "value": value} @@ -475,7 +475,7 @@ def redcap2reproschema(csv_file, yaml_file, schema_context_url=None): "Choices, Calculations, OR Slider Labels": "choices", # column F "Branching Logic (Show field only if...)": "visibility", # column L "Custom Alignment": "customAlignment", # column N - "Identifier?": "identifiable", # column K + # "Identifier?": "identifiable", # column K "multipleChoice": "multipleChoice", "responseType": "@type", } From 3c7049fa7c81b5b110cb687dffd2021b4849f80c Mon Sep 17 00:00:00 2001 From: yibeichan Date: Sat, 20 Apr 2024 21:33:27 -0400 Subject: [PATCH 83/94] fix conversion tests --- reproschema/redcap2reproschema.py | 2 - reproschema/reproschema2redcap.py | 13 +- reproschema/tests/test_redcap2reproschema.py | 26 ++-- .../tests/test_redcap2rs_data/redcap2rs.yaml | 9 +- reproschema/tests/test_reproschema2redcap.py | 18 ++- templates/redcap2rs.yaml | 2 + .../autism_parenting_stress_index_apsi_schema | 124 ++++++++++++++++++ .../items/apsi_accepted | 38 ++++++ .../items/apsi_agressive | 38 ++++++ .../items/apsi_bowel | 38 ++++++ .../items/apsi_communicate | 38 ++++++ .../items/apsi_date | 19 +++ .../items/apsi_diet | 38 ++++++ .../items/apsi_independently | 38 ++++++ .../items/apsi_name_of_child | 16 +++ .../items/apsi_not_close | 38 ++++++ .../items/apsi_person_completing | 16 +++ .../items/apsi_potty | 38 ++++++ .../items/apsi_self_injure | 38 ++++++ .../items/apsi_sleep | 38 ++++++ .../items/apsi_social_dev | 41 ++++++ .../items/apsi_tantrums | 38 ++++++ .../items/apsi_total | 16 +++ .../items/apsi_transitions | 38 ++++++ .../items/record_id | 16 +++ ...ffective_mindfulness_scalerevised_c_schema | 88 +++++++++++++ .../items/cams_r_1 | 37 ++++++ .../items/cams_r_10 | 34 +++++ .../items/cams_r_11 | 34 +++++ .../items/cams_r_12 | 34 +++++ .../items/cams_r_2 | 34 +++++ .../items/cams_r_3 | 34 +++++ .../items/cams_r_4 | 34 +++++ .../items/cams_r_5 | 34 +++++ .../items/cams_r_6 | 34 +++++ .../items/cams_r_7 | 34 +++++ .../items/cams_r_8 | 34 +++++ .../items/cams_r_9 | 34 +++++ .../test_redcap2rs/test_redcap2rs_schema | 31 +++++ 39 files changed, 1273 insertions(+), 31 deletions(-) create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions create mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 create mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 create mode 100644 test_redcap2rs/test_redcap2rs/test_redcap2rs_schema diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index d7d881c..799a795 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -8,7 +8,6 @@ matrix_group_count = {} - def clean_header(header): cleaned_header = {} for k, v in header.items(): @@ -17,7 +16,6 @@ def clean_header(header): cleaned_header[cleaned_key] = v return cleaned_header - def normalize_condition(condition_str): # Regular expressions for various pattern replacements re_parentheses = re.compile(r"\(([0-9]*)\)") diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 3d03cf3..3e1af67 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -142,6 +142,7 @@ def get_csv_data(dir_path): if protocol_dir.is_dir(): # Check for a _schema file in each directory schema_file = next(protocol_dir.glob("*_schema"), None) + print(f"Found schema file: {schema_file}") if schema_file: # Process the found _schema file parsed_protocol_json = read_json_file(schema_file) @@ -149,11 +150,10 @@ def get_csv_data(dir_path): activity_order = parsed_protocol_json.get("ui", {}).get("order", []) for relative_activity_path in activity_order: # Normalize the relative path and construct the absolute path - normalized_relative_path = Path( - relative_activity_path.lstrip("../") - ) - activity_path = dir_path / normalized_relative_path - print(f"Processing activity {activity_path}") + normalized_relative_path = Path(relative_activity_path.lstrip("../")) + + activity_path = dir_path / "activities" / normalized_relative_path / (normalized_relative_path.name + "_schema") + parsed_activity_json = read_json_file(activity_path) if parsed_activity_json: @@ -164,6 +164,7 @@ def get_csv_data(dir_path): if item_json: row_data = process_item(item_json, activity_path.stem) csv_data.append(row_data) + print(f"Processed item {item_path}") # Break after finding the first _schema file break @@ -239,4 +240,4 @@ def main(input_dir_path, output_csv_filename): sys.exit(1) input_dir_path = Path(sys.argv[1]) output_csv_filename = sys.argv[2] - main(input_dir_path, output_csv_filename) + main(input_dir_path, output_csv_filename) \ No newline at end of file diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py index 2386a8c..2486714 100644 --- a/reproschema/tests/test_redcap2reproschema.py +++ b/reproschema/tests/test_redcap2reproschema.py @@ -1,10 +1,10 @@ import os import shutil import pytest +import yaml from click.testing import CliRunner -from ..cli import main # Import the Click group +from ..cli import main -# Assuming your test files are located in a 'tests' directory CSV_FILE_NAME = "redcap_dict.csv" YAML_FILE_NAME = "redcap2rs.yaml" CSV_TEST_FILE = os.path.join( @@ -14,18 +14,24 @@ os.path.dirname(__file__), "test_redcap2rs_data", YAML_FILE_NAME ) - -def test_redcap2reproschema_success(): +def test_redcap2reproschema_success(tmpdir): runner = CliRunner() - with runner.isolated_filesystem(): - # Copy the test files to the isolated filesystem - shutil.copy(CSV_TEST_FILE, CSV_FILE_NAME) - shutil.copy(YAML_TEST_FILE, YAML_FILE_NAME) + # Copy the test files to the custom temporary directory + shutil.copy(CSV_TEST_FILE, tmpdir.join(CSV_FILE_NAME)) + shutil.copy(YAML_TEST_FILE, tmpdir.join(YAML_FILE_NAME)) + + # Set the working directory to tmpdir + with tmpdir.as_cwd(): + # Read YAML to find the expected output directory name + with open(YAML_FILE_NAME, 'r') as file: + protocol = yaml.safe_load(file) + protocol_name = protocol.get("protocol_name", "").replace(" ", "_") - # Run the command within the isolated filesystem result = runner.invoke( main, ["redcap2reproschema", CSV_FILE_NAME, YAML_FILE_NAME] ) - print(result.output) + + # Assertions assert result.exit_code == 0 + assert os.path.isdir(protocol_name), f"Expected output directory '{protocol_name}' does not exist" diff --git a/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml b/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml index 3330f3b..c201323 100644 --- a/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml +++ b/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml @@ -9,13 +9,8 @@ protocol_name: "test_redcap2rs" # Example: "My_Protocol" # This name will be displayed in the application. protocol_display_name: "redcap protocols" -# GitHub Repository Information: -# Create a GitHub repository named 'reproschema' to store your reproschema protocols. -# Replace 'your_github_username' with your actual GitHub username. -user_name: "yibeichan" -repo_name: "redcap2reproschema" # Recommended name; can be different if preferred. -repo_url: "https://github.com/{{user_name}}/{{repo_name}}" - # Protocol Description: # Provide a brief description of your protocol. protocol_description: "testing" # Example: "This protocol is for ..." + +redcap_version: "3.0.0" \ No newline at end of file diff --git a/reproschema/tests/test_reproschema2redcap.py b/reproschema/tests/test_reproschema2redcap.py index f0a02ce..5860121 100644 --- a/reproschema/tests/test_reproschema2redcap.py +++ b/reproschema/tests/test_reproschema2redcap.py @@ -2,23 +2,26 @@ import pytest from click.testing import CliRunner from ..cli import main -from shutil import copytree +from shutil import copytree, rmtree from pathlib import Path import csv - +import tempfile def test_reproschema2redcap_success(): runner = CliRunner() with runner.isolated_filesystem(): + # Create a temporary directory for output + temp_dir = tempfile.mkdtemp(dir='.') + print(f"Temporary directory: {temp_dir}") # Copy necessary test data into the isolated filesystem original_data_dir = os.path.join( - os.path.dirname(__file__), "test_rs2redcap_data" + os.path.dirname(__file__), "test_rs2redcap_data", "test_redcap2rs" ) copytree(original_data_dir, "input_data") input_path = Path("input_data") # Using Path object - output_csv_path = "output.csv" + output_csv_path = os.path.join(temp_dir, "output.csv") # Invoke the reproschema2redcap command result = runner.invoke( @@ -43,5 +46,8 @@ def test_reproschema2redcap_success(): print(row) # Optionally, assert conditions about the CSV contents - # For example, assert that the file is not empty - assert len(csv_contents) > 0 + # For example, assert that the file has more than just headers + assert len(csv_contents) > 1 # More than one row indicates content beyond headers + + # Clean up temporary directory after use (optional) + # rmtree(temp_dir) \ No newline at end of file diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml index 1e1dbc3..aa2f831 100644 --- a/templates/redcap2rs.yaml +++ b/templates/redcap2rs.yaml @@ -12,3 +12,5 @@ protocol_display_name: "Your protocol display name" # Protocol Description: # Provide a brief description of your protocol. protocol_description: "Description for your protocol" # Example: "This protocol is for ..." + +redcap_version: "x.y.z" # Example: "3.0.0" \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema new file mode 100644 index 0000000..fff03c4 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema @@ -0,0 +1,124 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Activity", + "@id": "autism_parenting_stress_index_apsi_schema", + "prefLabel": "autism_parenting_stress_index_apsi", + "description": "Default description", + "schemaVersion": "1.0.0-rc4", + "version": "3.0.0", + "ui": { + "order": [ + "items/record_id", + "items/apsi_date", + "items/apsi_name_of_child", + "items/apsi_person_completing", + "items/apsi_social_dev", + "items/apsi_communicate", + "items/apsi_tantrums", + "items/apsi_agressive", + "items/apsi_self_injure", + "items/apsi_transitions", + "items/apsi_sleep", + "items/apsi_diet", + "items/apsi_bowel", + "items/apsi_potty", + "items/apsi_not_close", + "items/apsi_accepted", + "items/apsi_independently", + "items/apsi_total" + ], + "addProperties": [ + { + "variableName": "record_id", + "isAbout": "items/record_id", + "isVis": true + }, + { + "variableName": "apsi_date", + "isAbout": "items/apsi_date", + "isVis": true + }, + { + "variableName": "apsi_name_of_child", + "isAbout": "items/apsi_name_of_child", + "isVis": true + }, + { + "variableName": "apsi_person_completing", + "isAbout": "items/apsi_person_completing", + "isVis": true + }, + { + "variableName": "apsi_social_dev", + "isAbout": "items/apsi_social_dev", + "isVis": true + }, + { + "variableName": "apsi_communicate", + "isAbout": "items/apsi_communicate", + "isVis": true + }, + { + "variableName": "apsi_tantrums", + "isAbout": "items/apsi_tantrums", + "isVis": true + }, + { + "variableName": "apsi_agressive", + "isAbout": "items/apsi_agressive", + "isVis": true + }, + { + "variableName": "apsi_self_injure", + "isAbout": "items/apsi_self_injure", + "isVis": true + }, + { + "variableName": "apsi_transitions", + "isAbout": "items/apsi_transitions", + "isVis": true + }, + { + "variableName": "apsi_sleep", + "isAbout": "items/apsi_sleep", + "isVis": true + }, + { + "variableName": "apsi_diet", + "isAbout": "items/apsi_diet", + "isVis": true + }, + { + "variableName": "apsi_bowel", + "isAbout": "items/apsi_bowel", + "isVis": true + }, + { + "variableName": "apsi_potty", + "isAbout": "items/apsi_potty", + "isVis": true + }, + { + "variableName": "apsi_not_close", + "isAbout": "items/apsi_not_close", + "isVis": true + }, + { + "variableName": "apsi_accepted", + "isAbout": "items/apsi_accepted", + "isVis": true + }, + { + "variableName": "apsi_independently", + "isAbout": "items/apsi_independently", + "isVis": true + }, + { + "variableName": "apsi_total", + "isAbout": "items/apsi_total", + "isVis": true + } + ], + "shuffle": false + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted new file mode 100644 index 0000000..5833f48 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_accepted", + "prefLabel": "apsi_accepted", + "description": "apsi_accepted of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Concern for the future of your child being accepted by others" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive new file mode 100644 index 0000000..8717b1b --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_agressive", + "prefLabel": "apsi_agressive", + "description": "apsi_agressive of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Aggressive behavior (siblings, peers)" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel new file mode 100644 index 0000000..7b06f0f --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_bowel", + "prefLabel": "apsi_bowel", + "description": "apsi_bowel of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Bowel problems (diarrhea, constipation)" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate new file mode 100644 index 0000000..cc0bada --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_communicate", + "prefLabel": "apsi_communicate", + "description": "apsi_communicate of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Your child's ability to communicate" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date new file mode 100644 index 0000000..4af48ba --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date @@ -0,0 +1,19 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_date", + "prefLabel": "apsi_date", + "description": "apsi_date of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + }, + "preamble": { + "en": "Autism Parenting Stress Index for the Qigong Sensory Training Program Instructions: 1. Before beginning Qigong Sensory Training therapy with your child, complete the form on the following page. 2. Enter the date, name of your child, and who is completing the checklist. (It is very important that the same parent/caretaker complete the form each time the form is used.) 3. Choose the response for each item that most accurately describes your child. 4. Add all of the numbers chosen. 5. Enter total into the space provided. After using Qigong Sensory Training therapy on your child once a day for a five months, have the same parent complete the form again. Total numbers circled. Compare this number to the number at the beginning. If Qigong Sensory Training therapy is being implemented successfully, the total number should decrease over time." + }, + "question": { + "en": "Date:" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet new file mode 100644 index 0000000..f1bb04c --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_diet", + "prefLabel": "apsi_diet", + "description": "apsi_diet of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Your child's diet" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently new file mode 100644 index 0000000..0389638 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_independently", + "prefLabel": "apsi_independently", + "description": "apsi_independently of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Concern for the future of your child living independently" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child new file mode 100644 index 0000000..195af9a --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child @@ -0,0 +1,16 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_name_of_child", + "prefLabel": "apsi_name_of_child", + "description": "apsi_name_of_child of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + }, + "question": { + "en": "Name of child:" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close new file mode 100644 index 0000000..a2b8fa7 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_not_close", + "prefLabel": "apsi_not_close", + "description": "apsi_not_close of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Not feeling close to your child" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing new file mode 100644 index 0000000..76cfd23 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing @@ -0,0 +1,16 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_person_completing", + "prefLabel": "apsi_person_completing", + "description": "apsi_person_completing of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + }, + "question": { + "en": "Person completing checklist:" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty new file mode 100644 index 0000000..6640aae --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_potty", + "prefLabel": "apsi_potty", + "description": "apsi_potty of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Potty training" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure new file mode 100644 index 0000000..29d8837 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_self_injure", + "prefLabel": "apsi_self_injure", + "description": "apsi_self_injure of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Self-injurious behavior" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep new file mode 100644 index 0000000..dbd01be --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_sleep", + "prefLabel": "apsi_sleep", + "description": "apsi_sleep of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Sleep problems" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev new file mode 100644 index 0000000..333be63 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev @@ -0,0 +1,41 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_social_dev", + "prefLabel": "apsi_social_dev", + "description": "apsi_social_dev of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "preamble": { + "en": "Stress Ratings Please rate the following aspects of your child'shealth according to how much stress it causes you and/or your familyby clicking on the button that best describes your situation." + }, + "question": { + "en": "Your child's social development" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums new file mode 100644 index 0000000..e07f99d --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_tantrums", + "prefLabel": "apsi_tantrums", + "description": "apsi_tantrums of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Tantrums/meltdowns" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total new file mode 100644 index 0000000..15328ec --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total @@ -0,0 +1,16 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_total", + "prefLabel": "apsi_total", + "description": "apsi_total of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + }, + "question": { + "en": "Total" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions new file mode 100644 index 0000000..ce9782c --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions @@ -0,0 +1,38 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "apsi_transitions", + "prefLabel": "apsi_transitions", + "description": "apsi_transitions of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "0 - Not stressful ", + "value": 0 + }, + { + "name": "1 - Sometimes creates stress ", + "value": 1 + }, + { + "name": "2 - Often creates stress ", + "value": 2 + }, + { + "name": "3 - Very stressful on a daily basis ", + "value": 3 + }, + { + "name": "5 - So stressful sometimes we feel we can't cope", + "value": 5 + } + ] + }, + "question": { + "en": "Difficulty making transitions from one activity to another" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id new file mode 100644 index 0000000..3971398 --- /dev/null +++ b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id @@ -0,0 +1,16 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "record_id", + "prefLabel": "record_id", + "description": "record_id of autism_parenting_stress_index_apsi", + "ui": { + "inputType": "text" + }, + "responseOptions": { + "valueType": "xsd:string" + }, + "question": { + "en": "Record ID" + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema new file mode 100644 index 0000000..ed06073 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema @@ -0,0 +1,88 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Activity", + "@id": "cognitive_and_affective_mindfulness_scalerevised_c_schema", + "prefLabel": "cognitive_and_affective_mindfulness_scalerevised_c", + "description": "Default description", + "schemaVersion": "1.0.0-rc4", + "version": "3.0.0", + "ui": { + "order": [ + "items/cams_r_1", + "items/cams_r_2", + "items/cams_r_3", + "items/cams_r_4", + "items/cams_r_5", + "items/cams_r_6", + "items/cams_r_7", + "items/cams_r_8", + "items/cams_r_9", + "items/cams_r_10", + "items/cams_r_11", + "items/cams_r_12" + ], + "addProperties": [ + { + "variableName": "cams_r_1", + "isAbout": "items/cams_r_1", + "isVis": true + }, + { + "variableName": "cams_r_2", + "isAbout": "items/cams_r_2", + "isVis": true + }, + { + "variableName": "cams_r_3", + "isAbout": "items/cams_r_3", + "isVis": true + }, + { + "variableName": "cams_r_4", + "isAbout": "items/cams_r_4", + "isVis": true + }, + { + "variableName": "cams_r_5", + "isAbout": "items/cams_r_5", + "isVis": true + }, + { + "variableName": "cams_r_6", + "isAbout": "items/cams_r_6", + "isVis": true + }, + { + "variableName": "cams_r_7", + "isAbout": "items/cams_r_7", + "isVis": true + }, + { + "variableName": "cams_r_8", + "isAbout": "items/cams_r_8", + "isVis": true + }, + { + "variableName": "cams_r_9", + "isAbout": "items/cams_r_9", + "isVis": true + }, + { + "variableName": "cams_r_10", + "isAbout": "items/cams_r_10", + "isVis": true + }, + { + "variableName": "cams_r_11", + "isAbout": "items/cams_r_11", + "isVis": true + }, + { + "variableName": "cams_r_12", + "isAbout": "items/cams_r_12", + "isVis": true + } + ], + "shuffle": false + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 new file mode 100644 index 0000000..433ff0b --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 @@ -0,0 +1,37 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_1", + "prefLabel": "cams_r_1", + "description": "cams_r_1 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "preamble": { + "en": "Instructions: People have a variety of ways of relating to their thoughts and feelings. For each of the items below, rate how much each of these ways applies to you." + }, + "question": { + "en": "1. It is easy for me to concentrate on what I am doing." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 new file mode 100644 index 0000000..2d39b9e --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_10", + "prefLabel": "cams_r_10", + "description": "cams_r_10 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "10. I am able to accept the thoughts and feelings I have." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 new file mode 100644 index 0000000..cd236fb --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_11", + "prefLabel": "cams_r_11", + "description": "cams_r_11 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "11. I am able to focus on the present moment." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 new file mode 100644 index 0000000..69c0020 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_12", + "prefLabel": "cams_r_12", + "description": "cams_r_12 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "12. I am able to pay close attention to one thing for a long period of time." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 new file mode 100644 index 0000000..701fe6f --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_2", + "prefLabel": "cams_r_2", + "description": "cams_r_2 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "2. I am preoccupied by the future." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 new file mode 100644 index 0000000..3bf5196 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_3", + "prefLabel": "cams_r_3", + "description": "cams_r_3 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "3. I can tolerate emotional pain." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 new file mode 100644 index 0000000..85598a5 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_4", + "prefLabel": "cams_r_4", + "description": "cams_r_4 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "4. I can accept things I cannot change." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 new file mode 100644 index 0000000..8df3dc3 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_5", + "prefLabel": "cams_r_5", + "description": "cams_r_5 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "5. I can usually describe how I feel at the moment in considerable detail." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 new file mode 100644 index 0000000..ee98bb5 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_6", + "prefLabel": "cams_r_6", + "description": "cams_r_6 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "6. I am easily distracted." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 new file mode 100644 index 0000000..8f264e2 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_7", + "prefLabel": "cams_r_7", + "description": "cams_r_7 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "7. I am preoccupied by the past." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 new file mode 100644 index 0000000..7bae21c --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_8", + "prefLabel": "cams_r_8", + "description": "cams_r_8 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "8. It's easy for me to keep track of my thoughts and feelings." + } +} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 new file mode 100644 index 0000000..2b628a7 --- /dev/null +++ b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 @@ -0,0 +1,34 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Item", + "@id": "cams_r_9", + "prefLabel": "cams_r_9", + "description": "cams_r_9 of cognitive_and_affective_mindfulness_scalerevised_c", + "ui": { + "inputType": "radio" + }, + "responseOptions": { + "valueType": "xsd:integer", + "choices": [ + { + "name": "1 - Rarely/Not at all ", + "value": 1 + }, + { + "name": "2 - Sometimes ", + "value": 2 + }, + { + "name": "3 - Often ", + "value": 3 + }, + { + "name": "4 - Almost Always", + "value": 4 + } + ] + }, + "question": { + "en": "9. I try to notice my thoughts without judging them." + } +} \ No newline at end of file diff --git a/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema b/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema new file mode 100644 index 0000000..423c39b --- /dev/null +++ b/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema @@ -0,0 +1,31 @@ +{ + "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", + "@type": "reproschema:Protocol", + "@id": "test_redcap2rs_schema", + "prefLabel": "redcap protocols", + "altLabel": "test_redcap2rs_schema", + "description": "testing", + "schemaVersion": "1.0.0-rc4", + "version": "3.0.0", + "ui": { + "addProperties": [ + { + "isAbout": "../activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema", + "variableName": "autism_parenting_stress_index_apsi_schema", + "prefLabel": "Autism Parenting Stress Index Apsi", + "isVis": true + }, + { + "isAbout": "../activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema", + "variableName": "cognitive_and_affective_mindfulness_scalerevised_c_schema", + "prefLabel": "Cognitive And Affective Mindfulness Scalerevised C", + "isVis": true + } + ], + "order": [ + "../activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema", + "../activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema" + ], + "shuffle": false + } +} \ No newline at end of file From a60612fc96369c1bcdeb1655aee2a02355eb7810 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Sat, 20 Apr 2024 21:34:38 -0400 Subject: [PATCH 84/94] remove test output --- .../autism_parenting_stress_index_apsi_schema | 124 ------------------ .../items/apsi_accepted | 38 ------ .../items/apsi_agressive | 38 ------ .../items/apsi_bowel | 38 ------ .../items/apsi_communicate | 38 ------ .../items/apsi_date | 19 --- .../items/apsi_diet | 38 ------ .../items/apsi_independently | 38 ------ .../items/apsi_name_of_child | 16 --- .../items/apsi_not_close | 38 ------ .../items/apsi_person_completing | 16 --- .../items/apsi_potty | 38 ------ .../items/apsi_self_injure | 38 ------ .../items/apsi_sleep | 38 ------ .../items/apsi_social_dev | 41 ------ .../items/apsi_tantrums | 38 ------ .../items/apsi_total | 16 --- .../items/apsi_transitions | 38 ------ .../items/record_id | 16 --- ...ffective_mindfulness_scalerevised_c_schema | 88 ------------- .../items/cams_r_1 | 37 ------ .../items/cams_r_10 | 34 ----- .../items/cams_r_11 | 34 ----- .../items/cams_r_12 | 34 ----- .../items/cams_r_2 | 34 ----- .../items/cams_r_3 | 34 ----- .../items/cams_r_4 | 34 ----- .../items/cams_r_5 | 34 ----- .../items/cams_r_6 | 34 ----- .../items/cams_r_7 | 34 ----- .../items/cams_r_8 | 34 ----- .../items/cams_r_9 | 34 ----- .../test_redcap2rs/test_redcap2rs_schema | 31 ----- 33 files changed, 1234 deletions(-) delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions delete mode 100644 test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 delete mode 100644 test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 delete mode 100644 test_redcap2rs/test_redcap2rs/test_redcap2rs_schema diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema deleted file mode 100644 index fff03c4..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema +++ /dev/null @@ -1,124 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Activity", - "@id": "autism_parenting_stress_index_apsi_schema", - "prefLabel": "autism_parenting_stress_index_apsi", - "description": "Default description", - "schemaVersion": "1.0.0-rc4", - "version": "3.0.0", - "ui": { - "order": [ - "items/record_id", - "items/apsi_date", - "items/apsi_name_of_child", - "items/apsi_person_completing", - "items/apsi_social_dev", - "items/apsi_communicate", - "items/apsi_tantrums", - "items/apsi_agressive", - "items/apsi_self_injure", - "items/apsi_transitions", - "items/apsi_sleep", - "items/apsi_diet", - "items/apsi_bowel", - "items/apsi_potty", - "items/apsi_not_close", - "items/apsi_accepted", - "items/apsi_independently", - "items/apsi_total" - ], - "addProperties": [ - { - "variableName": "record_id", - "isAbout": "items/record_id", - "isVis": true - }, - { - "variableName": "apsi_date", - "isAbout": "items/apsi_date", - "isVis": true - }, - { - "variableName": "apsi_name_of_child", - "isAbout": "items/apsi_name_of_child", - "isVis": true - }, - { - "variableName": "apsi_person_completing", - "isAbout": "items/apsi_person_completing", - "isVis": true - }, - { - "variableName": "apsi_social_dev", - "isAbout": "items/apsi_social_dev", - "isVis": true - }, - { - "variableName": "apsi_communicate", - "isAbout": "items/apsi_communicate", - "isVis": true - }, - { - "variableName": "apsi_tantrums", - "isAbout": "items/apsi_tantrums", - "isVis": true - }, - { - "variableName": "apsi_agressive", - "isAbout": "items/apsi_agressive", - "isVis": true - }, - { - "variableName": "apsi_self_injure", - "isAbout": "items/apsi_self_injure", - "isVis": true - }, - { - "variableName": "apsi_transitions", - "isAbout": "items/apsi_transitions", - "isVis": true - }, - { - "variableName": "apsi_sleep", - "isAbout": "items/apsi_sleep", - "isVis": true - }, - { - "variableName": "apsi_diet", - "isAbout": "items/apsi_diet", - "isVis": true - }, - { - "variableName": "apsi_bowel", - "isAbout": "items/apsi_bowel", - "isVis": true - }, - { - "variableName": "apsi_potty", - "isAbout": "items/apsi_potty", - "isVis": true - }, - { - "variableName": "apsi_not_close", - "isAbout": "items/apsi_not_close", - "isVis": true - }, - { - "variableName": "apsi_accepted", - "isAbout": "items/apsi_accepted", - "isVis": true - }, - { - "variableName": "apsi_independently", - "isAbout": "items/apsi_independently", - "isVis": true - }, - { - "variableName": "apsi_total", - "isAbout": "items/apsi_total", - "isVis": true - } - ], - "shuffle": false - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted deleted file mode 100644 index 5833f48..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_accepted +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_accepted", - "prefLabel": "apsi_accepted", - "description": "apsi_accepted of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Concern for the future of your child being accepted by others" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive deleted file mode 100644 index 8717b1b..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_agressive +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_agressive", - "prefLabel": "apsi_agressive", - "description": "apsi_agressive of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Aggressive behavior (siblings, peers)" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel deleted file mode 100644 index 7b06f0f..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_bowel +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_bowel", - "prefLabel": "apsi_bowel", - "description": "apsi_bowel of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Bowel problems (diarrhea, constipation)" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate deleted file mode 100644 index cc0bada..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_communicate +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_communicate", - "prefLabel": "apsi_communicate", - "description": "apsi_communicate of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Your child's ability to communicate" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date deleted file mode 100644 index 4af48ba..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_date +++ /dev/null @@ -1,19 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_date", - "prefLabel": "apsi_date", - "description": "apsi_date of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "text" - }, - "responseOptions": { - "valueType": "xsd:string" - }, - "preamble": { - "en": "Autism Parenting Stress Index for the Qigong Sensory Training Program Instructions: 1. Before beginning Qigong Sensory Training therapy with your child, complete the form on the following page. 2. Enter the date, name of your child, and who is completing the checklist. (It is very important that the same parent/caretaker complete the form each time the form is used.) 3. Choose the response for each item that most accurately describes your child. 4. Add all of the numbers chosen. 5. Enter total into the space provided. After using Qigong Sensory Training therapy on your child once a day for a five months, have the same parent complete the form again. Total numbers circled. Compare this number to the number at the beginning. If Qigong Sensory Training therapy is being implemented successfully, the total number should decrease over time." - }, - "question": { - "en": "Date:" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet deleted file mode 100644 index f1bb04c..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_diet +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_diet", - "prefLabel": "apsi_diet", - "description": "apsi_diet of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Your child's diet" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently deleted file mode 100644 index 0389638..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_independently +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_independently", - "prefLabel": "apsi_independently", - "description": "apsi_independently of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Concern for the future of your child living independently" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child deleted file mode 100644 index 195af9a..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_name_of_child +++ /dev/null @@ -1,16 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_name_of_child", - "prefLabel": "apsi_name_of_child", - "description": "apsi_name_of_child of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "text" - }, - "responseOptions": { - "valueType": "xsd:string" - }, - "question": { - "en": "Name of child:" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close deleted file mode 100644 index a2b8fa7..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_not_close +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_not_close", - "prefLabel": "apsi_not_close", - "description": "apsi_not_close of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Not feeling close to your child" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing deleted file mode 100644 index 76cfd23..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_person_completing +++ /dev/null @@ -1,16 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_person_completing", - "prefLabel": "apsi_person_completing", - "description": "apsi_person_completing of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "text" - }, - "responseOptions": { - "valueType": "xsd:string" - }, - "question": { - "en": "Person completing checklist:" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty deleted file mode 100644 index 6640aae..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_potty +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_potty", - "prefLabel": "apsi_potty", - "description": "apsi_potty of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Potty training" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure deleted file mode 100644 index 29d8837..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_self_injure +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_self_injure", - "prefLabel": "apsi_self_injure", - "description": "apsi_self_injure of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Self-injurious behavior" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep deleted file mode 100644 index dbd01be..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_sleep +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_sleep", - "prefLabel": "apsi_sleep", - "description": "apsi_sleep of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Sleep problems" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev deleted file mode 100644 index 333be63..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_social_dev +++ /dev/null @@ -1,41 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_social_dev", - "prefLabel": "apsi_social_dev", - "description": "apsi_social_dev of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "preamble": { - "en": "Stress Ratings Please rate the following aspects of your child'shealth according to how much stress it causes you and/or your familyby clicking on the button that best describes your situation." - }, - "question": { - "en": "Your child's social development" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums deleted file mode 100644 index e07f99d..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_tantrums +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_tantrums", - "prefLabel": "apsi_tantrums", - "description": "apsi_tantrums of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Tantrums/meltdowns" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total deleted file mode 100644 index 15328ec..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_total +++ /dev/null @@ -1,16 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_total", - "prefLabel": "apsi_total", - "description": "apsi_total of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "text" - }, - "responseOptions": { - "valueType": "xsd:string" - }, - "question": { - "en": "Total" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions deleted file mode 100644 index ce9782c..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/apsi_transitions +++ /dev/null @@ -1,38 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "apsi_transitions", - "prefLabel": "apsi_transitions", - "description": "apsi_transitions of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "0 - Not stressful ", - "value": 0 - }, - { - "name": "1 - Sometimes creates stress ", - "value": 1 - }, - { - "name": "2 - Often creates stress ", - "value": 2 - }, - { - "name": "3 - Very stressful on a daily basis ", - "value": 3 - }, - { - "name": "5 - So stressful sometimes we feel we can't cope", - "value": 5 - } - ] - }, - "question": { - "en": "Difficulty making transitions from one activity to another" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id b/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id deleted file mode 100644 index 3971398..0000000 --- a/test_redcap2rs/activities/autism_parenting_stress_index_apsi/items/record_id +++ /dev/null @@ -1,16 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "record_id", - "prefLabel": "record_id", - "description": "record_id of autism_parenting_stress_index_apsi", - "ui": { - "inputType": "text" - }, - "responseOptions": { - "valueType": "xsd:string" - }, - "question": { - "en": "Record ID" - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema deleted file mode 100644 index ed06073..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema +++ /dev/null @@ -1,88 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Activity", - "@id": "cognitive_and_affective_mindfulness_scalerevised_c_schema", - "prefLabel": "cognitive_and_affective_mindfulness_scalerevised_c", - "description": "Default description", - "schemaVersion": "1.0.0-rc4", - "version": "3.0.0", - "ui": { - "order": [ - "items/cams_r_1", - "items/cams_r_2", - "items/cams_r_3", - "items/cams_r_4", - "items/cams_r_5", - "items/cams_r_6", - "items/cams_r_7", - "items/cams_r_8", - "items/cams_r_9", - "items/cams_r_10", - "items/cams_r_11", - "items/cams_r_12" - ], - "addProperties": [ - { - "variableName": "cams_r_1", - "isAbout": "items/cams_r_1", - "isVis": true - }, - { - "variableName": "cams_r_2", - "isAbout": "items/cams_r_2", - "isVis": true - }, - { - "variableName": "cams_r_3", - "isAbout": "items/cams_r_3", - "isVis": true - }, - { - "variableName": "cams_r_4", - "isAbout": "items/cams_r_4", - "isVis": true - }, - { - "variableName": "cams_r_5", - "isAbout": "items/cams_r_5", - "isVis": true - }, - { - "variableName": "cams_r_6", - "isAbout": "items/cams_r_6", - "isVis": true - }, - { - "variableName": "cams_r_7", - "isAbout": "items/cams_r_7", - "isVis": true - }, - { - "variableName": "cams_r_8", - "isAbout": "items/cams_r_8", - "isVis": true - }, - { - "variableName": "cams_r_9", - "isAbout": "items/cams_r_9", - "isVis": true - }, - { - "variableName": "cams_r_10", - "isAbout": "items/cams_r_10", - "isVis": true - }, - { - "variableName": "cams_r_11", - "isAbout": "items/cams_r_11", - "isVis": true - }, - { - "variableName": "cams_r_12", - "isAbout": "items/cams_r_12", - "isVis": true - } - ], - "shuffle": false - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 deleted file mode 100644 index 433ff0b..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_1 +++ /dev/null @@ -1,37 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_1", - "prefLabel": "cams_r_1", - "description": "cams_r_1 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "preamble": { - "en": "Instructions: People have a variety of ways of relating to their thoughts and feelings. For each of the items below, rate how much each of these ways applies to you." - }, - "question": { - "en": "1. It is easy for me to concentrate on what I am doing." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 deleted file mode 100644 index 2d39b9e..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_10 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_10", - "prefLabel": "cams_r_10", - "description": "cams_r_10 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "10. I am able to accept the thoughts and feelings I have." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 deleted file mode 100644 index cd236fb..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_11 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_11", - "prefLabel": "cams_r_11", - "description": "cams_r_11 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "11. I am able to focus on the present moment." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 deleted file mode 100644 index 69c0020..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_12 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_12", - "prefLabel": "cams_r_12", - "description": "cams_r_12 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "12. I am able to pay close attention to one thing for a long period of time." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 deleted file mode 100644 index 701fe6f..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_2 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_2", - "prefLabel": "cams_r_2", - "description": "cams_r_2 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "2. I am preoccupied by the future." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 deleted file mode 100644 index 3bf5196..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_3 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_3", - "prefLabel": "cams_r_3", - "description": "cams_r_3 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "3. I can tolerate emotional pain." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 deleted file mode 100644 index 85598a5..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_4 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_4", - "prefLabel": "cams_r_4", - "description": "cams_r_4 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "4. I can accept things I cannot change." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 deleted file mode 100644 index 8df3dc3..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_5 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_5", - "prefLabel": "cams_r_5", - "description": "cams_r_5 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "5. I can usually describe how I feel at the moment in considerable detail." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 deleted file mode 100644 index ee98bb5..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_6 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_6", - "prefLabel": "cams_r_6", - "description": "cams_r_6 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "6. I am easily distracted." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 deleted file mode 100644 index 8f264e2..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_7 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_7", - "prefLabel": "cams_r_7", - "description": "cams_r_7 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "7. I am preoccupied by the past." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 deleted file mode 100644 index 7bae21c..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_8 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_8", - "prefLabel": "cams_r_8", - "description": "cams_r_8 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "8. It's easy for me to keep track of my thoughts and feelings." - } -} \ No newline at end of file diff --git a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 b/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 deleted file mode 100644 index 2b628a7..0000000 --- a/test_redcap2rs/activities/cognitive_and_affective_mindfulness_scalerevised_c/items/cams_r_9 +++ /dev/null @@ -1,34 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Item", - "@id": "cams_r_9", - "prefLabel": "cams_r_9", - "description": "cams_r_9 of cognitive_and_affective_mindfulness_scalerevised_c", - "ui": { - "inputType": "radio" - }, - "responseOptions": { - "valueType": "xsd:integer", - "choices": [ - { - "name": "1 - Rarely/Not at all ", - "value": 1 - }, - { - "name": "2 - Sometimes ", - "value": 2 - }, - { - "name": "3 - Often ", - "value": 3 - }, - { - "name": "4 - Almost Always", - "value": 4 - } - ] - }, - "question": { - "en": "9. I try to notice my thoughts without judging them." - } -} \ No newline at end of file diff --git a/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema b/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema deleted file mode 100644 index 423c39b..0000000 --- a/test_redcap2rs/test_redcap2rs/test_redcap2rs_schema +++ /dev/null @@ -1,31 +0,0 @@ -{ - "@context": "https://raw.githubusercontent.com/ReproNim/reproschema/efb74e155c09e13aa009ea04609ba4f1152fcbc6/contexts/reproschema_new", - "@type": "reproschema:Protocol", - "@id": "test_redcap2rs_schema", - "prefLabel": "redcap protocols", - "altLabel": "test_redcap2rs_schema", - "description": "testing", - "schemaVersion": "1.0.0-rc4", - "version": "3.0.0", - "ui": { - "addProperties": [ - { - "isAbout": "../activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema", - "variableName": "autism_parenting_stress_index_apsi_schema", - "prefLabel": "Autism Parenting Stress Index Apsi", - "isVis": true - }, - { - "isAbout": "../activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema", - "variableName": "cognitive_and_affective_mindfulness_scalerevised_c_schema", - "prefLabel": "Cognitive And Affective Mindfulness Scalerevised C", - "isVis": true - } - ], - "order": [ - "../activities/autism_parenting_stress_index_apsi/autism_parenting_stress_index_apsi_schema", - "../activities/cognitive_and_affective_mindfulness_scalerevised_c/cognitive_and_affective_mindfulness_scalerevised_c_schema" - ], - "shuffle": false - } -} \ No newline at end of file From e1e847d342c1921fa422a8f96674bfcf16d860ea Mon Sep 17 00:00:00 2001 From: yibeichan Date: Sat, 20 Apr 2024 21:47:56 -0400 Subject: [PATCH 85/94] change test output directory --- reproschema/tests/test_redcap2reproschema.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py index 2486714..840ac4f 100644 --- a/reproschema/tests/test_redcap2reproschema.py +++ b/reproschema/tests/test_redcap2reproschema.py @@ -17,21 +17,27 @@ def test_redcap2reproschema_success(tmpdir): runner = CliRunner() - # Copy the test files to the custom temporary directory - shutil.copy(CSV_TEST_FILE, tmpdir.join(CSV_FILE_NAME)) - shutil.copy(YAML_TEST_FILE, tmpdir.join(YAML_FILE_NAME)) + # Define the paths to the CSV and YAML files in the temporary directory + temp_csv_file = tmpdir.join(CSV_FILE_NAME) + temp_yaml_file = tmpdir.join(YAML_FILE_NAME) - # Set the working directory to tmpdir + # Copy the test files to the temporary directory + shutil.copy(CSV_TEST_FILE, str(temp_csv_file)) # Convert to string + shutil.copy(YAML_TEST_FILE, str(temp_yaml_file)) # Convert to string + + # Change the current working directory to tmpdir with tmpdir.as_cwd(): # Read YAML to find the expected output directory name - with open(YAML_FILE_NAME, 'r') as file: + with open(str(temp_yaml_file), 'r') as file: # Convert to string protocol = yaml.safe_load(file) protocol_name = protocol.get("protocol_name", "").replace(" ", "_") + # Run the command with the path arguments pointing to the temp directory files result = runner.invoke( - main, ["redcap2reproschema", CSV_FILE_NAME, YAML_FILE_NAME] + main, ["redcap2reproschema", str(temp_csv_file), str(temp_yaml_file)] # Convert to string ) # Assertions - assert result.exit_code == 0 + assert result.exit_code == 0, f"The command failed to execute successfully: {result.output}" assert os.path.isdir(protocol_name), f"Expected output directory '{protocol_name}' does not exist" + print("Command output:", result.output) \ No newline at end of file From 51d30b7bd1a0203ebe28622e7eeebd3d61fa1413 Mon Sep 17 00:00:00 2001 From: yibeichan Date: Sat, 20 Apr 2024 21:54:53 -0400 Subject: [PATCH 86/94] final improvments on tests --- reproschema/redcap2reproschema.py | 3 ++- reproschema/reproschema2redcap.py | 1 - reproschema/tests/test_redcap2reproschema.py | 7 +------ reproschema/tests/test_reproschema2redcap.py | 22 ++++---------------- 4 files changed, 7 insertions(+), 26 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 799a795..253c6b5 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -16,6 +16,7 @@ def clean_header(header): cleaned_header[cleaned_key] = v return cleaned_header + def normalize_condition(condition_str): # Regular expressions for various pattern replacements re_parentheses = re.compile(r"\(([0-9]*)\)") @@ -42,6 +43,7 @@ def normalize_condition(condition_str): return condition_str.strip() + def process_visibility(data): condition = data.get("Branching Logic (Show field only if...)") if condition: @@ -94,7 +96,6 @@ def parse_field_type_and_value(field, input_type_map): return input_type, value_type - def process_choices(field_type, choices_str): if field_type not in ["radio", "dropdown"]: # Handle only radio and dropdown types return None diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index 3e1af67..ffb7eea 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -164,7 +164,6 @@ def get_csv_data(dir_path): if item_json: row_data = process_item(item_json, activity_path.stem) csv_data.append(row_data) - print(f"Processed item {item_path}") # Break after finding the first _schema file break diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py index 840ac4f..4dff719 100644 --- a/reproschema/tests/test_redcap2reproschema.py +++ b/reproschema/tests/test_redcap2reproschema.py @@ -14,14 +14,12 @@ os.path.dirname(__file__), "test_redcap2rs_data", YAML_FILE_NAME ) -def test_redcap2reproschema_success(tmpdir): +def test_redcap2reproschema(tmpdir): runner = CliRunner() - # Define the paths to the CSV and YAML files in the temporary directory temp_csv_file = tmpdir.join(CSV_FILE_NAME) temp_yaml_file = tmpdir.join(YAML_FILE_NAME) - # Copy the test files to the temporary directory shutil.copy(CSV_TEST_FILE, str(temp_csv_file)) # Convert to string shutil.copy(YAML_TEST_FILE, str(temp_yaml_file)) # Convert to string @@ -32,12 +30,9 @@ def test_redcap2reproschema_success(tmpdir): protocol = yaml.safe_load(file) protocol_name = protocol.get("protocol_name", "").replace(" ", "_") - # Run the command with the path arguments pointing to the temp directory files result = runner.invoke( main, ["redcap2reproschema", str(temp_csv_file), str(temp_yaml_file)] # Convert to string ) - # Assertions assert result.exit_code == 0, f"The command failed to execute successfully: {result.output}" assert os.path.isdir(protocol_name), f"Expected output directory '{protocol_name}' does not exist" - print("Command output:", result.output) \ No newline at end of file diff --git a/reproschema/tests/test_reproschema2redcap.py b/reproschema/tests/test_reproschema2redcap.py index 5860121..c652d3d 100644 --- a/reproschema/tests/test_reproschema2redcap.py +++ b/reproschema/tests/test_reproschema2redcap.py @@ -5,49 +5,35 @@ from shutil import copytree, rmtree from pathlib import Path import csv -import tempfile -def test_reproschema2redcap_success(): +def test_reproschema2redcap(tmpdir): runner = CliRunner() with runner.isolated_filesystem(): - # Create a temporary directory for output - temp_dir = tempfile.mkdtemp(dir='.') - print(f"Temporary directory: {temp_dir}") # Copy necessary test data into the isolated filesystem original_data_dir = os.path.join( os.path.dirname(__file__), "test_rs2redcap_data", "test_redcap2rs" ) copytree(original_data_dir, "input_data") - input_path = Path("input_data") # Using Path object - output_csv_path = os.path.join(temp_dir, "output.csv") + input_path = Path("input_data") + output_csv_path = os.path.join(tmpdir, "output.csv") - # Invoke the reproschema2redcap command result = runner.invoke( main, ["reproschema2redcap", str(input_path), output_csv_path] ) - # Print the output for debugging print(result.output) - # Assert the expected outcomes assert result.exit_code == 0 - # Check if the output CSV file has been created assert os.path.exists(output_csv_path) - # Read and print the contents of the CSV file with open(output_csv_path, "r", encoding="utf-8") as csv_file: reader = csv.reader(csv_file) csv_contents = list(reader) - print("CSV File Contents:") - for row in csv_contents: - print(row) - # Optionally, assert conditions about the CSV contents - # For example, assert that the file has more than just headers assert len(csv_contents) > 1 # More than one row indicates content beyond headers # Clean up temporary directory after use (optional) - # rmtree(temp_dir) \ No newline at end of file + # rmtree(tmpdir) \ No newline at end of file From ab7c051dbd4ebfce92917ce154a8053343a011e7 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 21 Apr 2024 02:02:04 +0000 Subject: [PATCH 87/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/redcap2reproschema.py | 28 +++++++++++-------- reproschema/reproschema2redcap.py | 15 +++++++--- reproschema/tests/test_redcap2reproschema.py | 20 +++++++++---- .../tests/test_redcap2rs_data/redcap2rs.yaml | 2 +- reproschema/tests/test_reproschema2redcap.py | 9 ++++-- templates/redcap2rs.yaml | 2 +- 6 files changed, 50 insertions(+), 26 deletions(-) diff --git a/reproschema/redcap2reproschema.py b/reproschema/redcap2reproschema.py index 253c6b5..e7f67c7 100644 --- a/reproschema/redcap2reproschema.py +++ b/reproschema/redcap2reproschema.py @@ -8,11 +8,12 @@ matrix_group_count = {} + def clean_header(header): cleaned_header = {} for k, v in header.items(): # Strip BOM, whitespace, and enclosing quotation marks if present - cleaned_key = k.lstrip('\ufeff').strip().strip('"') + cleaned_key = k.lstrip("\ufeff").strip().strip('"') cleaned_header[cleaned_key] = v return cleaned_header @@ -24,7 +25,7 @@ def normalize_condition(condition_str): re_brackets = re.compile(r"\[([^\]]*)\]") re_extra_spaces = re.compile(r"\s+") re_double_quotes = re.compile(r'"') - re_or = re.compile(r'\bor\b') # Match 'or' as whole word + re_or = re.compile(r"\bor\b") # Match 'or' as whole word # Apply regex replacements condition_str = re_parentheses.sub(r"___\1", condition_str) @@ -32,16 +33,20 @@ def normalize_condition(condition_str): condition_str = re_brackets.sub(r" \1 ", condition_str) # Replace 'or' with '||', ensuring not to replace '||' - condition_str = re_or.sub('||', condition_str) + condition_str = re_or.sub("||", condition_str) # Replace 'and' with '&&' condition_str = condition_str.replace(" and ", " && ") # Trim extra spaces and replace double quotes with single quotes - condition_str = re_extra_spaces.sub(' ', condition_str).strip() # Reduce multiple spaces to a single space - condition_str = re_double_quotes.sub("'", condition_str) # Replace double quotes with single quotes + condition_str = re_extra_spaces.sub( + " ", condition_str + ).strip() # Reduce multiple spaces to a single space + condition_str = re_double_quotes.sub( + "'", condition_str + ) # Replace double quotes with single quotes - return condition_str.strip() + return condition_str.strip() def process_visibility(data): @@ -116,7 +121,7 @@ def process_choices(field_type, choices_str): value = parts[0] choice_obj = {"name": " ".join(parts[1:]), "value": value} - # remove image for now + # remove image for now # if len(parts) == 3: # # Handle image url # choice_obj["image"] = f"{parts[2]}.png" @@ -204,10 +209,7 @@ def process_row( } for key, value in field.items(): - if ( - schema_map.get(key) in ["question", "description", "preamble"] - and value - ): + if schema_map.get(key) in ["question", "description", "preamble"] and value: rowData.update({schema_map[key]: parse_html(value)}) elif schema_map.get(key) == "allow" and value: @@ -349,7 +351,9 @@ def create_protocol_schema( "variableName": f"{activity}_schema", # Assuming activity name as prefLabel, update as needed "prefLabel": activity.replace("_", " ").title(), - "isVis": protocol_visibility_obj.get(activity, True), # Default to True if not specified + "isVis": protocol_visibility_obj.get( + activity, True + ), # Default to True if not specified } protocol_schema["ui"]["addProperties"].append(add_property) # Add the full path to the order list diff --git a/reproschema/reproschema2redcap.py b/reproschema/reproschema2redcap.py index ffb7eea..298c56e 100644 --- a/reproschema/reproschema2redcap.py +++ b/reproschema/reproschema2redcap.py @@ -150,10 +150,17 @@ def get_csv_data(dir_path): activity_order = parsed_protocol_json.get("ui", {}).get("order", []) for relative_activity_path in activity_order: # Normalize the relative path and construct the absolute path - normalized_relative_path = Path(relative_activity_path.lstrip("../")) + normalized_relative_path = Path( + relative_activity_path.lstrip("../") + ) + + activity_path = ( + dir_path + / "activities" + / normalized_relative_path + / (normalized_relative_path.name + "_schema") + ) - activity_path = dir_path / "activities" / normalized_relative_path / (normalized_relative_path.name + "_schema") - parsed_activity_json = read_json_file(activity_path) if parsed_activity_json: @@ -239,4 +246,4 @@ def main(input_dir_path, output_csv_filename): sys.exit(1) input_dir_path = Path(sys.argv[1]) output_csv_filename = sys.argv[2] - main(input_dir_path, output_csv_filename) \ No newline at end of file + main(input_dir_path, output_csv_filename) diff --git a/reproschema/tests/test_redcap2reproschema.py b/reproschema/tests/test_redcap2reproschema.py index 4dff719..bbf2df7 100644 --- a/reproschema/tests/test_redcap2reproschema.py +++ b/reproschema/tests/test_redcap2reproschema.py @@ -3,7 +3,7 @@ import pytest import yaml from click.testing import CliRunner -from ..cli import main +from ..cli import main CSV_FILE_NAME = "redcap_dict.csv" YAML_FILE_NAME = "redcap2rs.yaml" @@ -14,6 +14,7 @@ os.path.dirname(__file__), "test_redcap2rs_data", YAML_FILE_NAME ) + def test_redcap2reproschema(tmpdir): runner = CliRunner() @@ -26,13 +27,22 @@ def test_redcap2reproschema(tmpdir): # Change the current working directory to tmpdir with tmpdir.as_cwd(): # Read YAML to find the expected output directory name - with open(str(temp_yaml_file), 'r') as file: # Convert to string + with open(str(temp_yaml_file), "r") as file: # Convert to string protocol = yaml.safe_load(file) protocol_name = protocol.get("protocol_name", "").replace(" ", "_") result = runner.invoke( - main, ["redcap2reproschema", str(temp_csv_file), str(temp_yaml_file)] # Convert to string + main, + [ + "redcap2reproschema", + str(temp_csv_file), + str(temp_yaml_file), + ], # Convert to string ) - assert result.exit_code == 0, f"The command failed to execute successfully: {result.output}" - assert os.path.isdir(protocol_name), f"Expected output directory '{protocol_name}' does not exist" + assert ( + result.exit_code == 0 + ), f"The command failed to execute successfully: {result.output}" + assert os.path.isdir( + protocol_name + ), f"Expected output directory '{protocol_name}' does not exist" diff --git a/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml b/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml index c201323..95d4a9c 100644 --- a/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml +++ b/reproschema/tests/test_redcap2rs_data/redcap2rs.yaml @@ -13,4 +13,4 @@ protocol_display_name: "redcap protocols" # Provide a brief description of your protocol. protocol_description: "testing" # Example: "This protocol is for ..." -redcap_version: "3.0.0" \ No newline at end of file +redcap_version: "3.0.0" diff --git a/reproschema/tests/test_reproschema2redcap.py b/reproschema/tests/test_reproschema2redcap.py index c652d3d..eff26b3 100644 --- a/reproschema/tests/test_reproschema2redcap.py +++ b/reproschema/tests/test_reproschema2redcap.py @@ -6,6 +6,7 @@ from pathlib import Path import csv + def test_reproschema2redcap(tmpdir): runner = CliRunner() @@ -16,7 +17,7 @@ def test_reproschema2redcap(tmpdir): ) copytree(original_data_dir, "input_data") - input_path = Path("input_data") + input_path = Path("input_data") output_csv_path = os.path.join(tmpdir, "output.csv") result = runner.invoke( @@ -33,7 +34,9 @@ def test_reproschema2redcap(tmpdir): reader = csv.reader(csv_file) csv_contents = list(reader) - assert len(csv_contents) > 1 # More than one row indicates content beyond headers + assert ( + len(csv_contents) > 1 + ) # More than one row indicates content beyond headers # Clean up temporary directory after use (optional) - # rmtree(tmpdir) \ No newline at end of file + # rmtree(tmpdir) diff --git a/templates/redcap2rs.yaml b/templates/redcap2rs.yaml index aa2f831..4bbf78f 100644 --- a/templates/redcap2rs.yaml +++ b/templates/redcap2rs.yaml @@ -13,4 +13,4 @@ protocol_display_name: "Your protocol display name" # Provide a brief description of your protocol. protocol_description: "Description for your protocol" # Example: "This protocol is for ..." -redcap_version: "x.y.z" # Example: "3.0.0" \ No newline at end of file +redcap_version: "x.y.z" # Example: "3.0.0" From 78b81674045681f17c5ad3a07c80d6d657ba4c2e Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 29 Apr 2024 16:13:55 +0000 Subject: [PATCH 88/94] remove 3.7, add 3.11 --- .github/workflows/pythonpackage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 64bf566..5f31dd3 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -16,7 +16,7 @@ jobs: strategy: matrix: os: [macos-latest, ubuntu-latest] - python-version: [3.7, 3.8, 3.9, "3.10"] + python-version: [3.8, 3.9, "3.10", "3.11"] steps: - uses: actions/checkout@v2 From 9af90543370218eeee34bb4074b035dddc843e5e Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Mon, 29 Apr 2024 16:21:42 +0000 Subject: [PATCH 89/94] add py3.12 --- .github/workflows/pythonpackage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 5f31dd3..48e15ef 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -16,7 +16,7 @@ jobs: strategy: matrix: os: [macos-latest, ubuntu-latest] - python-version: [3.8, 3.9, "3.10", "3.11"] + python-version: [3.8, 3.9, "3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v2 From 7379fcdd3edf8d7c9af7951f2887004d03808a78 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Tue, 30 Apr 2024 13:44:34 +0000 Subject: [PATCH 90/94] remove 3.12 --- .github/workflows/pythonpackage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 48e15ef..5f31dd3 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -16,7 +16,7 @@ jobs: strategy: matrix: os: [macos-latest, ubuntu-latest] - python-version: [3.8, 3.9, "3.10", "3.11", "3.12"] + python-version: [3.8, 3.9, "3.10", "3.11"] steps: - uses: actions/checkout@v2 From b4a82002fe1cd44b070ef93950be798bdde1dee6 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 2 May 2024 18:37:36 +0000 Subject: [PATCH 91/94] Update Versioneer to latest version --- .gitattributes | 1 + reproschema/__init__.py | 3 + reproschema/_version.py | 451 +++++++++++++++++++++++++--------------- 3 files changed, 293 insertions(+), 162 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e228630 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +reproschema/_version.py export-subst diff --git a/reproschema/__init__.py b/reproschema/__init__.py index f5ddeda..53eedfa 100644 --- a/reproschema/__init__.py +++ b/reproschema/__init__.py @@ -45,3 +45,6 @@ def set_logger_level(lgr, level): lgr.warning( "Failed to check for a more recent version available with etelemetry: %s", exc ) + +from . import _version +__version__ = _version.get_versions()['version'] diff --git a/reproschema/_version.py b/reproschema/_version.py index da2b4c4..3665dc1 100644 --- a/reproschema/_version.py +++ b/reproschema/_version.py @@ -1,11 +1,13 @@ + # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) +# This file is released into the public domain. +# Generated by versioneer-0.29 +# https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" @@ -14,9 +16,11 @@ import re import subprocess import sys +from typing import Any, Callable, Dict, List, Optional, Tuple +import functools -def get_keywords(): +def get_keywords() -> Dict[str, str]: """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must @@ -32,8 +36,15 @@ def get_keywords(): class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + parentdir_prefix: str + versionfile_source: str + verbose: bool + -def get_config(): +def get_config() -> VersioneerConfig: """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py @@ -42,7 +53,7 @@ def get_config(): cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "" - cfg.versionfile_source = "pydra/_version.py" + cfg.versionfile_source = "reproschema/_version.py" cfg.verbose = False return cfg @@ -51,41 +62,50 @@ class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" -LONG_VERSION_PY = {} -HANDLERS = {} - +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f - return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, - cwd=cwd, - env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr else None), - ) + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -96,18 +116,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= if verbose: print("unable to find command, tried %s" % (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -116,64 +138,64 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return { - "version": dirname[len(parentdir_prefix) :], - "full-revisionid": None, - "dirty": False, - "error": None, - "date": None, - } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: - print( - "Tried directories %s but none started with prefix %s" - % (str(rootdirs), parentdir_prefix) - ) + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. - keywords = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -186,11 +208,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -199,7 +221,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -207,30 +229,33 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix) :] + r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue if verbose: print("picking %s" % r) - return { - "version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": None, - "date": date, - } + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return { - "version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": "no suitable tags", - "date": None, - } + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, + root: str, + verbose: bool, + runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -241,7 +266,15 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -249,33 +282,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command( - GITS, - [ - "describe", - "--tags", - "--dirty", - "--always", - "--long", - "--match", - "%s*" % tag_prefix, - ], - cwd=root, - ) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -284,16 +341,17 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[: git_describe.rindex("-dirty")] + git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out + # unparsable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) return pieces # tag @@ -302,12 +360,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( - full_tag, - tag_prefix, - ) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix) :] + pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -318,26 +374,27 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -355,29 +412,78 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] + rendered = "0.post0.dev%d" % pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -404,12 +510,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -426,7 +561,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -446,7 +581,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -466,26 +601,28 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: - return { - "version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None, - } + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -495,16 +632,12 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - return { - "version": rendered, - "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], - "error": None, - "date": pieces.get("date"), - } + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} -def get_versions(): +def get_versions() -> Dict[str, Any]: """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some @@ -515,7 +648,8 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) except NotThisMethod: pass @@ -524,16 +658,13 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split("/"): + for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None, - } + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) @@ -547,10 +678,6 @@ def get_versions(): except NotThisMethod: pass - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", - "date": None, - } + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} From b3bcb78c9bad58d7dd0eddbb7013510315399ac3 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 2 May 2024 18:37:59 +0000 Subject: [PATCH 92/94] Update Versioneer to latest version --- versioneer.py | 1354 +++++++++++++++++++++++++++++++------------------ 1 file changed, 873 insertions(+), 481 deletions(-) diff --git a/versioneer.py b/versioneer.py index 2b54540..1e3753e 100644 --- a/versioneer.py +++ b/versioneer.py @@ -1,4 +1,5 @@ -# Version: 0.18 + +# Version: 0.29 """The Versioneer - like a rocketeer, but for versions. @@ -6,18 +7,14 @@ ============== * like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer +* https://github.com/python-versioneer/python-versioneer * Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based +* License: Public Domain (Unlicense) +* Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3 +* [![Latest Version][pypi-image]][pypi-url] +* [![Build Status][travis-image]][travis-url] + +This is a tool for managing a recorded version number in setuptools-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control @@ -26,9 +23,38 @@ ## Quick Install -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results +Versioneer provides two installation modes. The "classic" vendored mode installs +a copy of versioneer into your repository. The experimental build-time dependency mode +is intended to allow you to skip this step and simplify the process of upgrading. + +### Vendored mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) + * Note that you will need to add `tomli; python_version < "3.11"` to your + build-time dependencies if you use `pyproject.toml` +* run `versioneer install --vendor` in your source tree, commit the results +* verify version information with `python setup.py version` + +### Build-time dependency mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) +* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) + to the `requires` key of the `build-system` table in `pyproject.toml`: + ```toml + [build-system] + requires = ["setuptools", "versioneer[toml]"] + build-backend = "setuptools.build_meta" + ``` +* run `versioneer install --no-vendor` in your source tree, commit the results +* verify version information with `python setup.py version` ## Version Identifiers @@ -60,7 +86,7 @@ for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. +uncommitted changes). The version identifier is used for multiple purposes: @@ -165,7 +191,7 @@ Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github -[issues page](https://github.com/warner/python-versioneer/issues). +[issues page](https://github.com/python-versioneer/python-versioneer/issues). ### Subprojects @@ -179,7 +205,7 @@ `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other langauges) in subdirectories. + provide bindings to Python (and perhaps other languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs @@ -193,9 +219,9 @@ Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking +[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the +[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve @@ -223,31 +249,20 @@ cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes +[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. -### Unicode version strings - -While Versioneer works (and is continually tested) with both Python 2 and -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. -Newer releases probably generate unicode version strings on py2. It's not -clear that this is wrong, but it may be surprising for applications when then -write these strings to a network connection or include them in bytes-oriented -APIs like cryptographic checksums. - -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates -this question. - ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace +* edit `setup.cfg` and `pyproject.toml`, if necessary, + to include any new configuration settings indicated by the release notes. + See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install --[no-]vendor` in your source tree, to replace `SRC/_version.py` * commit any changed files @@ -264,36 +279,70 @@ direction and include code from all supported VCS systems, reducing the number of intermediate scripts. +## Similar projects + +* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time + dependency +* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of + versioneer +* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools + plugin ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . +Specifically, both are released under the "Unlicense", as described in +https://unlicense.org/. -""" +[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg +[pypi-url]: https://pypi.python.org/pypi/versioneer/ +[travis-image]: +https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg +[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer -from __future__ import print_function +""" +# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring +# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements +# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error +# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with +# pylint:disable=attribute-defined-outside-init,too-many-arguments -try: - import configparser -except ImportError: - import ConfigParser as configparser +import configparser import errno import json import os import re import subprocess import sys +from pathlib import Path +from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union +from typing import NoReturn +import functools + +have_tomllib = True +if sys.version_info >= (3, 11): + import tomllib +else: + try: + import tomli as tomllib + except ImportError: + have_tomllib = False class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + versionfile_source: str + versionfile_build: Optional[str] + parentdir_prefix: Optional[str] + verbose: Optional[bool] -def get_root(): + +def get_root() -> str: """Get the project root directory. We require that all commands are run from the project root, i.e. the @@ -301,20 +350,28 @@ def get_root(): """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") + pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + if not ( + os.path.exists(setup_py) + or os.path.exists(pyproject_toml) + or os.path.exists(versioneer_py) + ): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") + pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ( - "Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND')." - ) + if not ( + os.path.exists(setup_py) + or os.path.exists(pyproject_toml) + or os.path.exists(versioneer_py) + ): + err = ("Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools @@ -323,46 +380,62 @@ def get_root(): # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) + my_path = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: - print( - "Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py) - ) + if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): + print("Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(my_path), versioneer_py)) except NameError: pass return root -def get_config_from_root(root): +def get_config_from_root(root: str) -> VersioneerConfig: """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or + # This might raise OSError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: - parser.readfp(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None + root_pth = Path(root) + pyproject_toml = root_pth / "pyproject.toml" + setup_cfg = root_pth / "setup.cfg" + section: Union[Dict[str, Any], configparser.SectionProxy, None] = None + if pyproject_toml.exists() and have_tomllib: + try: + with open(pyproject_toml, 'rb') as fobj: + pp = tomllib.load(fobj) + section = pp['tool']['versioneer'] + except (tomllib.TOMLDecodeError, KeyError) as e: + print(f"Failed to load config from {pyproject_toml}: {e}") + print("Try to load it from setup.cfg") + if not section: + parser = configparser.ConfigParser() + with open(setup_cfg) as cfg_file: + parser.read_file(cfg_file) + parser.get("versioneer", "VCS") # raise error if missing + + section = parser["versioneer"] + + # `cast`` really shouldn't be used, but its simplest for the + # common VersioneerConfig users at the moment. We verify against + # `None` values elsewhere where it matters cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): + cfg.VCS = section['VCS'] + cfg.style = section.get("style", "") + cfg.versionfile_source = cast(str, section.get("versionfile_source")) + cfg.versionfile_build = section.get("versionfile_build") + cfg.tag_prefix = cast(str, section.get("tag_prefix")) + if cfg.tag_prefix in ("''", '""', None): cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") + cfg.parentdir_prefix = section.get("parentdir_prefix") + if isinstance(section, configparser.SectionProxy): + # Make sure configparser translates to bool + cfg.verbose = section.getboolean("verbose") + else: + cfg.verbose = section.get("verbose") + return cfg @@ -371,41 +444,48 @@ class NotThisMethod(Exception): # these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - - def decorate(f): +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f + HANDLERS.setdefault(vcs, {})[method] = f return f - return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, - cwd=cwd, - env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr else None), - ) + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -416,28 +496,25 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= if verbose: print("unable to find command, tried %s" % (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -LONG_VERSION_PY[ - "git" -] = ''' +LONG_VERSION_PY['git'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) +# This file is released into the public domain. +# Generated by versioneer-0.29 +# https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" @@ -446,9 +523,11 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= import re import subprocess import sys +from typing import Any, Callable, Dict, List, Optional, Tuple +import functools -def get_keywords(): +def get_keywords() -> Dict[str, str]: """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must @@ -464,8 +543,15 @@ def get_keywords(): class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + parentdir_prefix: str + versionfile_source: str + verbose: bool + -def get_config(): +def get_config() -> VersioneerConfig: """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py @@ -483,13 +569,13 @@ class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" -LONG_VERSION_PY = {} -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} @@ -498,22 +584,35 @@ def decorate(f): return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -524,18 +623,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -544,15 +645,14 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% @@ -561,41 +661,48 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. - keywords = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -608,11 +715,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d @@ -621,7 +728,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: @@ -630,6 +737,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue if verbose: print("picking %%s" %% r) return {"version": r, @@ -645,7 +757,12 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, + root: str, + verbose: bool, + runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -656,8 +773,15 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) @@ -665,24 +789,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -699,7 +856,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces @@ -724,26 +881,27 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() + date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -768,23 +926,71 @@ def render_pep440(pieces): return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%%d" %% (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] + rendered = "0.post0.dev%%d" %% pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -811,12 +1017,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -833,7 +1068,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -853,7 +1088,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -873,7 +1108,7 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", @@ -887,10 +1122,14 @@ def render(pieces, style): if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -905,7 +1144,7 @@ def render(pieces, style): "date": pieces.get("date")} -def get_versions(): +def get_versions() -> Dict[str, Any]: """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some @@ -926,7 +1165,7 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, @@ -953,41 +1192,48 @@ def get_versions(): @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. - keywords = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -1000,11 +1246,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -1013,7 +1259,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -1021,30 +1267,33 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix) :] + r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue if verbose: print("picking %s" % r) - return { - "version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": None, - "date": date, - } + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return { - "version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": "no suitable tags", - "date": None, - } + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, + root: str, + verbose: bool, + runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -1055,7 +1304,15 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -1063,33 +1320,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command( - GITS, - [ - "describe", - "--tags", - "--dirty", - "--always", - "--long", - "--match", - "%s*" % tag_prefix, - ], - cwd=root, - ) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -1098,16 +1379,17 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[: git_describe.rindex("-dirty")] + git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out + # unparsable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) return pieces # tag @@ -1116,12 +1398,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( - full_tag, - tag_prefix, - ) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix) :] + pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -1132,19 +1412,20 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def do_vcs_install(manifest_in, versionfile_source, ipy): +def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None: """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py @@ -1153,36 +1434,40 @@ def do_vcs_install(manifest_in, versionfile_source, ipy): GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] + files = [versionfile_source] if ipy: files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) + if "VERSIONEER_PEP518" not in globals(): + try: + my_path = __file__ + if my_path.endswith((".pyc", ".pyo")): + my_path = os.path.splitext(my_path)[0] + ".py" + versioneer_file = os.path.relpath(my_path) + except NameError: + versioneer_file = "versioneer.py" + files.append(versioneer_file) present = False try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: + with open(".gitattributes", "r") as fobj: + for line in fobj: + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + break + except OSError: pass if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() + with open(".gitattributes", "a+") as fobj: + fobj.write(f"{versionfile_source} export-subst\n") files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -1191,30 +1476,23 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return { - "version": dirname[len(parentdir_prefix) :], - "full-revisionid": None, - "dirty": False, - "error": None, - "date": None, - } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: - print( - "Tried directories %s but none started with prefix %s" - % (str(rootdirs), parentdir_prefix) - ) + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.18) from +# This file was generated by 'versioneer.py' (0.29) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. @@ -1231,43 +1509,41 @@ def get_versions(): """ -def versions_from_file(filename): +def versions_from_file(filename: str) -> Dict[str, Any]: """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() - except EnvironmentError: + except OSError: raise NotThisMethod("unable to read _version.py") - mo = re.search( - r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S - ) + mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) if not mo: - mo = re.search( - r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S - ) + mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) -def write_to_version_file(filename, versions): +def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) + contents = json.dumps(versions, sort_keys=True, + indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -1285,29 +1561,78 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] + rendered = "0.post0.dev%d" % pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -1334,12 +1659,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -1356,7 +1710,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -1376,7 +1730,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -1396,26 +1750,28 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: - return { - "version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None, - } + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -1425,20 +1781,16 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - return { - "version": rendered, - "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], - "error": None, - "date": pieces.get("date"), - } + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" -def get_versions(verbose=False): +def get_versions(verbose: bool = False) -> Dict[str, Any]: """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. @@ -1453,10 +1805,9 @@ def get_versions(verbose=False): assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert ( - cfg.versionfile_source is not None - ), "please set versioneer.versionfile_source" + verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` + assert cfg.versionfile_source is not None, \ + "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) @@ -1510,22 +1861,22 @@ def get_versions(verbose=False): if verbose: print("unable to compute version") - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", - "date": None, - } + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, "error": "unable to compute version", + "date": None} -def get_version(): +def get_version() -> str: """Get the short version string for this project.""" return get_versions()["version"] -def get_cmdclass(): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" +def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None): + """Get the custom setuptools subclasses used by Versioneer. + + If the package uses a different cmdclass (e.g. one from numpy), it + should be provide as an argument. + """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and @@ -1539,25 +1890,25 @@ def get_cmdclass(): # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 + # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - cmds = {} + cmds = {} if cmdclass is None else cmdclass.copy() - # we add "version" to both distutils and setuptools - from distutils.core import Command + # we add "version" to setuptools + from setuptools import Command class cmd_version(Command): description = "report generated version string" - user_options = [] - boolean_options = [] + user_options: List[Tuple[str, str, str]] = [] + boolean_options: List[str] = [] - def initialize_options(self): + def initialize_options(self) -> None: pass - def finalize_options(self): + def finalize_options(self) -> None: pass - def run(self): + def run(self) -> None: vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) @@ -1565,10 +1916,9 @@ def run(self): print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - # we override "build_py" in both distutils and setuptools + # we override "build_py" in setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py @@ -1583,30 +1933,68 @@ def run(self): # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? + # pip install -e . and setuptool/editable_wheel will invoke build_py + # but the build_py command is not expected to copy any files. + # we override different "build_py" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py + if 'build_py' in cmds: + _build_py: Any = cmds['build_py'] else: - from distutils.command.build_py import build_py as _build_py + from setuptools.command.build_py import build_py as _build_py class cmd_build_py(_build_py): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) + if getattr(self, "editable_mode", False): + # During editable installs `.py` and data files are + # not copied to build_lib + return # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe + if 'build_ext' in cmds: + _build_ext: Any = cmds['build_ext'] + else: + from setuptools.command.build_ext import build_ext as _build_ext + + class cmd_build_ext(_build_ext): + def run(self) -> None: + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_ext.run(self) + if self.inplace: + # build_ext --inplace will only build extensions in + # build/lib<..> dir with no _version.py to write to. + # As in place builds will already have a _version.py + # in the module dir, we do not need to write one. + return + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if not cfg.versionfile_build: + return + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + if not os.path.exists(target_versionfile): + print(f"Warning: {target_versionfile} does not exist, skipping " + "version update. This can happen if you are running build_ext " + "without first running build_py.") + return + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_ext"] = cmd_build_ext + if "cx_Freeze" in sys.modules: # cx_freeze enabled? + from cx_Freeze.dist import build_exe as _build_exe # type: ignore # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ @@ -1615,7 +2003,7 @@ def run(self): # ... class cmd_build_exe(_build_exe): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() @@ -1627,28 +2015,24 @@ def run(self): os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] - if "py2exe" in sys.modules: # py2exe enabled? + if 'py2exe' in sys.modules: # py2exe enabled? try: - from py2exe.distutils_buildexe import py2exe as _py2exe # py3 + from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore except ImportError: - from py2exe.build_exe import py2exe as _py2exe # py2 + from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore class cmd_py2exe(_py2exe): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() @@ -1660,27 +2044,60 @@ def run(self): os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) cmds["py2exe"] = cmd_py2exe + # sdist farms its file list building out to egg_info + if 'egg_info' in cmds: + _egg_info: Any = cmds['egg_info'] + else: + from setuptools.command.egg_info import egg_info as _egg_info + + class cmd_egg_info(_egg_info): + def find_sources(self) -> None: + # egg_info.find_sources builds the manifest list and writes it + # in one shot + super().find_sources() + + # Modify the filelist and normalize it + root = get_root() + cfg = get_config_from_root(root) + self.filelist.append('versioneer.py') + if cfg.versionfile_source: + # There are rare cases where versionfile_source might not be + # included by default, so we must be explicit + self.filelist.append(cfg.versionfile_source) + self.filelist.sort() + self.filelist.remove_duplicates() + + # The write method is hidden in the manifest_maker instance that + # generated the filelist and was thrown away + # We will instead replicate their final normalization (to unicode, + # and POSIX-style paths) + from setuptools import unicode_utils + normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') + for f in self.filelist.files] + + manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') + with open(manifest_filename, 'w') as fobj: + fobj.write('\n'.join(normalized)) + + cmds['egg_info'] = cmd_egg_info + # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist + if 'sdist' in cmds: + _sdist: Any = cmds['sdist'] else: - from distutils.command.sdist import sdist as _sdist + from setuptools.command.sdist import sdist as _sdist class cmd_sdist(_sdist): - def run(self): + def run(self) -> None: versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old @@ -1688,7 +2105,7 @@ def run(self): self.distribution.metadata.version = versions["version"] return _sdist.run(self) - def make_release_tree(self, base_dir, files): + def make_release_tree(self, base_dir: str, files: List[str]) -> None: root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) @@ -1697,10 +2114,8 @@ def make_release_tree(self, base_dir, files): # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) - write_to_version_file( - target_versionfile, self._versioneer_generated_versions - ) - + write_to_version_file(target_versionfile, + self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds @@ -1743,25 +2158,28 @@ def make_release_tree(self, base_dir, files): """ -INIT_PY_SNIPPET = """ +OLD_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ +INIT_PY_SNIPPET = """ +from . import {0} +__version__ = {0}.get_versions()['version'] +""" + -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" +def do_setup() -> int: + """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) - except ( - EnvironmentError, - configparser.NoSectionError, - configparser.NoOptionError, - ) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", file=sys.stderr) + except (OSError, configparser.NoSectionError, + configparser.NoOptionError) as e: + if isinstance(e, (OSError, configparser.NoSectionError)): + print("Adding sample versioneer config to setup.cfg", + file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) @@ -1770,76 +2188,46 @@ def do_setup(): print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") + f.write(LONG % {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), + "__init__.py") + maybe_ipy: Optional[str] = ipy if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() - except EnvironmentError: + except OSError: old = "" - if INIT_PY_SNIPPET not in old: + module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] + snippet = INIT_PY_SNIPPET.format(module) + if OLD_SNIPPET in old: + print(" replacing boilerplate in %s" % ipy) + with open(ipy, "w") as f: + f.write(old.replace(OLD_SNIPPET, snippet)) + elif snippet not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) + f.write(snippet) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print( - " appending versionfile_source ('%s') to MANIFEST.in" - % cfg.versionfile_source - ) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") + maybe_ipy = None # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) + do_vcs_install(cfg.versionfile_source, maybe_ipy) return 0 -def scan_setup_py(): +def scan_setup_py() -> int: """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False @@ -1876,10 +2264,14 @@ def scan_setup_py(): return errors +def setup_command() -> NoReturn: + """Set up Versioneer and exit with appropriate error code.""" + errors = do_setup() + errors += scan_setup_py() + sys.exit(1 if errors else 0) + + if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1) + setup_command() From 6943e897c3fecaede94543bd4d29d54009d65464 Mon Sep 17 00:00:00 2001 From: Yibei Chen Date: Thu, 2 May 2024 18:41:10 +0000 Subject: [PATCH 93/94] update action & python version --- .github/workflows/pythonpackage.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 5f31dd3..72f6446 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -16,12 +16,12 @@ jobs: strategy: matrix: os: [macos-latest, ubuntu-latest] - python-version: [3.8, 3.9, "3.10", "3.11"] + python-version: [3.8, 3.9, "3.10", "3.11", "3.12"] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies From 7f378ece80b2b3eb2505d1a22bf63b43f49e7b77 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 2 May 2024 18:42:03 +0000 Subject: [PATCH 94/94] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- reproschema/__init__.py | 3 +- reproschema/_version.py | 157 ++++++++++++-------- versioneer.py | 309 ++++++++++++++++++++++++---------------- 3 files changed, 280 insertions(+), 189 deletions(-) diff --git a/reproschema/__init__.py b/reproschema/__init__.py index 53eedfa..192028a 100644 --- a/reproschema/__init__.py +++ b/reproschema/__init__.py @@ -47,4 +47,5 @@ def set_logger_level(lgr, level): ) from . import _version -__version__ = _version.get_versions()['version'] + +__version__ = _version.get_versions()["version"] diff --git a/reproschema/_version.py b/reproschema/_version.py index 3665dc1..fc5908f 100644 --- a/reproschema/_version.py +++ b/reproschema/_version.py @@ -1,4 +1,3 @@ - # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build @@ -68,12 +67,14 @@ class NotThisMethod(Exception): def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f + return decorate @@ -100,10 +101,14 @@ def run_command( try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) + process = subprocess.Popen( + [command] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, + ) break except OSError as e: if e.errno == errno.ENOENT: @@ -141,15 +146,21 @@ def versions_from_parentdir( for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} + return { + "version": dirname[len(parentdir_prefix) :], + "full-revisionid": None, + "dirty": False, + "error": None, + "date": None, + } rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -212,7 +223,7 @@ def git_versions_from_keywords( # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -221,7 +232,7 @@ def git_versions_from_keywords( # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} + tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -229,32 +240,36 @@ def git_versions_from_keywords( for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') - if not re.match(r'\d', r): + if not re.match(r"\d", r): continue if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command + tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command ) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. @@ -273,8 +288,7 @@ def git_pieces_from_vcs( env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -282,10 +296,19 @@ def git_pieces_from_vcs( # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) + describe_out, rc = runner( + GITS, + [ + "describe", + "--tags", + "--dirty", + "--always", + "--long", + "--match", + f"{tag_prefix}[[:digit:]]*", + ], + cwd=root, + ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") @@ -300,8 +323,7 @@ def git_pieces_from_vcs( pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") @@ -341,17 +363,16 @@ def git_pieces_from_vcs( dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -360,10 +381,12 @@ def git_pieces_from_vcs( if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -412,8 +435,7 @@ def render_pep440(pieces: Dict[str, Any]) -> str: rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -442,8 +464,7 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str: rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -604,11 +625,13 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str: def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default @@ -632,9 +655,13 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } def get_versions() -> Dict[str, Any]: @@ -648,8 +675,7 @@ def get_versions() -> Dict[str, Any]: verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass @@ -658,13 +684,16 @@ def get_versions() -> Dict[str, Any]: # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): + for _ in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None, + } try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) @@ -678,6 +707,10 @@ def get_versions() -> Dict[str, Any]: except NotThisMethod: pass - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } diff --git a/versioneer.py b/versioneer.py index 1e3753e..de97d90 100644 --- a/versioneer.py +++ b/versioneer.py @@ -1,4 +1,3 @@ - # Version: 0.29 """The Versioneer - like a rocketeer, but for versions. @@ -367,11 +366,13 @@ def get_root() -> str: or os.path.exists(pyproject_toml) or os.path.exists(versioneer_py) ): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") + err = ( + "Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND')." + ) raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools @@ -384,8 +385,10 @@ def get_root() -> str: me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(my_path), versioneer_py)) + print( + "Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(my_path), versioneer_py) + ) except NameError: pass return root @@ -403,9 +406,9 @@ def get_config_from_root(root: str) -> VersioneerConfig: section: Union[Dict[str, Any], configparser.SectionProxy, None] = None if pyproject_toml.exists() and have_tomllib: try: - with open(pyproject_toml, 'rb') as fobj: + with open(pyproject_toml, "rb") as fobj: pp = tomllib.load(fobj) - section = pp['tool']['versioneer'] + section = pp["tool"]["versioneer"] except (tomllib.TOMLDecodeError, KeyError) as e: print(f"Failed to load config from {pyproject_toml}: {e}") print("Try to load it from setup.cfg") @@ -422,7 +425,7 @@ def get_config_from_root(root: str) -> VersioneerConfig: # `None` values elsewhere where it matters cfg = VersioneerConfig() - cfg.VCS = section['VCS'] + cfg.VCS = section["VCS"] cfg.style = section.get("style", "") cfg.versionfile_source = cast(str, section.get("versionfile_source")) cfg.versionfile_build = section.get("versionfile_build") @@ -450,10 +453,12 @@ class NotThisMethod(Exception): def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" HANDLERS.setdefault(vcs, {})[method] = f return f + return decorate @@ -480,10 +485,14 @@ def run_command( try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) + process = subprocess.Popen( + [command] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, + ) break except OSError as e: if e.errno == errno.ENOENT: @@ -505,7 +514,9 @@ def run_command( return stdout, process.returncode -LONG_VERSION_PY['git'] = r''' +LONG_VERSION_PY[ + "git" +] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build @@ -1250,7 +1261,7 @@ def git_versions_from_keywords( # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -1259,7 +1270,7 @@ def git_versions_from_keywords( # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} + tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -1267,32 +1278,36 @@ def git_versions_from_keywords( for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') - if not re.match(r'\d', r): + if not re.match(r"\d", r): continue if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command + tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command ) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. @@ -1311,8 +1326,7 @@ def git_pieces_from_vcs( env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -1320,10 +1334,19 @@ def git_pieces_from_vcs( # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) + describe_out, rc = runner( + GITS, + [ + "describe", + "--tags", + "--dirty", + "--always", + "--long", + "--match", + f"{tag_prefix}[[:digit:]]*", + ], + cwd=root, + ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") @@ -1338,8 +1361,7 @@ def git_pieces_from_vcs( pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") @@ -1379,17 +1401,16 @@ def git_pieces_from_vcs( dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -1398,10 +1419,12 @@ def git_pieces_from_vcs( if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -1479,15 +1502,21 @@ def versions_from_parentdir( for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} + return { + "version": dirname[len(parentdir_prefix) :], + "full-revisionid": None, + "dirty": False, + "error": None, + "date": None, + } rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -1516,11 +1545,13 @@ def versions_from_file(filename: str) -> Dict[str, Any]: contents = f.read() except OSError: raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) + mo = re.search( + r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S + ) if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) + mo = re.search( + r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S + ) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) @@ -1528,8 +1559,7 @@ def versions_from_file(filename: str) -> Dict[str, Any]: def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: """Write the given version number to the given _version.py file.""" - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) + contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) @@ -1561,8 +1591,7 @@ def render_pep440(pieces: Dict[str, Any]) -> str: rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -1591,8 +1620,7 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str: rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -1753,11 +1781,13 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str: def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default @@ -1781,9 +1811,13 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } class VersioneerBadRootError(Exception): @@ -1806,8 +1840,9 @@ def get_versions(verbose: bool = False) -> Dict[str, Any]: handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" + assert ( + cfg.versionfile_source is not None + ), "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) @@ -1861,9 +1896,13 @@ def get_versions(verbose: bool = False) -> Dict[str, Any]: if verbose: print("unable to compute version") - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } def get_version() -> str: @@ -1916,6 +1955,7 @@ def run(self) -> None: print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version # we override "build_py" in setuptools @@ -1937,8 +1977,8 @@ def run(self) -> None: # but the build_py command is not expected to copy any files. # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py: Any = cmds['build_py'] + if "build_py" in cmds: + _build_py: Any = cmds["build_py"] else: from setuptools.command.build_py import build_py as _build_py @@ -1955,14 +1995,14 @@ def run(self) -> None: # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py - if 'build_ext' in cmds: - _build_ext: Any = cmds['build_ext'] + if "build_ext" in cmds: + _build_ext: Any = cmds["build_ext"] else: from setuptools.command.build_ext import build_ext as _build_ext @@ -1982,19 +2022,22 @@ def run(self) -> None: # it with an updated value if not cfg.versionfile_build: return - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) if not os.path.exists(target_versionfile): - print(f"Warning: {target_versionfile} does not exist, skipping " - "version update. This can happen if you are running build_ext " - "without first running build_py.") + print( + f"Warning: {target_versionfile} does not exist, skipping " + "version update. This can happen if you are running build_ext " + "without first running build_py." + ) return print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) + cmds["build_ext"] = cmd_build_ext if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # type: ignore + # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ @@ -2015,17 +2058,21 @@ def run(self) -> None: os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) + f.write( + LONG + % { + "DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + } + ) + cmds["build_exe"] = cmd_build_exe del cmds["build_py"] - if 'py2exe' in sys.modules: # py2exe enabled? + if "py2exe" in sys.modules: # py2exe enabled? try: from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore except ImportError: @@ -2044,18 +2091,22 @@ def run(self) -> None: os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) + f.write( + LONG + % { + "DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + } + ) + cmds["py2exe"] = cmd_py2exe # sdist farms its file list building out to egg_info - if 'egg_info' in cmds: - _egg_info: Any = cmds['egg_info'] + if "egg_info" in cmds: + _egg_info: Any = cmds["egg_info"] else: from setuptools.command.egg_info import egg_info as _egg_info @@ -2068,7 +2119,7 @@ def find_sources(self) -> None: # Modify the filelist and normalize it root = get_root() cfg = get_config_from_root(root) - self.filelist.append('versioneer.py') + self.filelist.append("versioneer.py") if cfg.versionfile_source: # There are rare cases where versionfile_source might not be # included by default, so we must be explicit @@ -2081,18 +2132,21 @@ def find_sources(self) -> None: # We will instead replicate their final normalization (to unicode, # and POSIX-style paths) from setuptools import unicode_utils - normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') - for f in self.filelist.files] - manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') - with open(manifest_filename, 'w') as fobj: - fobj.write('\n'.join(normalized)) + normalized = [ + unicode_utils.filesys_decode(f).replace(os.sep, "/") + for f in self.filelist.files + ] + + manifest_filename = os.path.join(self.egg_info, "SOURCES.txt") + with open(manifest_filename, "w") as fobj: + fobj.write("\n".join(normalized)) - cmds['egg_info'] = cmd_egg_info + cmds["egg_info"] = cmd_egg_info # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist: Any = cmds['sdist'] + if "sdist" in cmds: + _sdist: Any = cmds["sdist"] else: from setuptools.command.sdist import sdist as _sdist @@ -2114,8 +2168,10 @@ def make_release_tree(self, base_dir: str, files: List[str]) -> None: # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) + write_to_version_file( + target_versionfile, self._versioneer_generated_versions + ) + cmds["sdist"] = cmd_sdist return cmds @@ -2175,11 +2231,9 @@ def do_setup() -> int: root = get_root() try: cfg = get_config_from_root(root) - except (OSError, configparser.NoSectionError, - configparser.NoOptionError) as e: + except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (OSError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) + print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) @@ -2188,15 +2242,18 @@ def do_setup() -> int: print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") + f.write( + LONG + % { + "DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + } + ) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") maybe_ipy: Optional[str] = ipy if os.path.exists(ipy): try: