civicrm-confdump/confdump.py
2021-11-22 14:52:03 -08:00

107 lines
3.5 KiB
Python

# CiviCRM APIv4 Configuration dumper
# Prepared for Autonomic Cooperative
# For the CAAT project
# This tool can dump configuration to a directory, and reload configuration from a directory
# into a specified CiviCRM instance.
# FIXME handle username, password
import argparse
import json
import logging
import os
import pathlib
import requests
import sys
import traceback
from civicrmapi4.civicrmapi4 import APIv4
# Entities which are simply a matter of dumping and upserting without
# additional processing.
DUMP_TRIVIAL = ["FinancialType",
"PaymentProcessor",
"ContributionPage",
"Contact",
"Relationship",
"Group",
"CustomGroup",
"CustomField",
"OptionValue",
"OptionGroup"]
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(prog="confdump.py",
description=("Dump configuration from a CiviCRM instance or load a previously"
"dumped configuration."))
parser.add_argument("-v", "--verbose", help="Show debug output.", action="store_true")
parser.add_argument("baseurl",
help="The base URL for the target instance.")
subparsers = parser.add_subparsers(dest='command')
dump_sub = subparsers.add_parser('dump', help="Dump configurations.")
dump_sub.add_argument("-o",
"--output",
help="Output directory (will be created if it does not exist).",
type=pathlib.Path,
default=pathlib.Path("."))
load_sub = subparsers.add_parser("load", help="Load configurations.")
load_sub.add_argument("-i",
"--input",
help="Input directory.",
type=pathlib.Path)
return parser.parse_args()
def main() -> int:
args = parse_arguments()
if args.verbose:
try: # for Python 3
from http.client import HTTPConnection
except ImportError:
from httplib import HTTPConnection
HTTPConnection.debuglevel = 1
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
api = APIv4(args.baseurl)
username = os.environ.get('CIVICRM_USERNAME', None)
password = os.environ.get('CIVICRM_PASSWORD', None)
if (username is None) or (password is None):
print("Need to specify username and password CIVICRM_USERNAME and CIVICRM_PASSWORD enivronments.")
return 1
api.login(username, password)
if api.session is None:
print("Login failed.")
return 1
print("log in successful")
if args.command == "dump":
if (not args.output.exists()):
args.output.mkdir(parents=True)
if (not args.output.is_dir()):
print("Output directory exists and is not a directory")
return 1
for table in DUMP_TRIVIAL:
output = args.output / (table + ".json")
data = api.get(table)
if data:
print("dumping", table)
with output.open("w") as of:
of.write(json.dumps(data))
# main entry
if __name__ == "__main__":
sys.exit(main())