Skip to content

Commit 6166eff

Browse files
authored
add MCF migration support (#352)
* add MCF migration support * fix flake8 * qualify version migrations, add additional error message
1 parent 085a103 commit 6166eff

7 files changed

Lines changed: 327 additions & 3 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ pygeometa metadata import path/to/file.xml --schema=iso19139
6767
# import a metadata document to MCF, autodetecting the metadata file format
6868
pygeometa metadata import path/to/file.xml --schema=autodetect # --schema=autodetect is default
6969

70+
# migrate an MCF document
71+
pygeometa metadata migrate path/to/file.mcf.yml
72+
7073
# transform from one metadata representation to another
7174
pygeometa metadata transform path/to/file.xml --input-schema=iso19139 --output-schema=oarec-record
7275

‎docs/content/tutorial.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ pygeometa metadata import path/to/file.xml --schema=iso19139
6565
# import a metadata document to MCF, autodetecting the metadata file format
6666
pygeometa metadata import path/to/file.xml --schema=autodetect # --schema=autodetect is default
6767

68+
# migrate an MCF document
69+
pygeometa metadata migrate path/to/file.mcf.yml
70+
6871
# transform from one metadata representation to another
6972
pygeometa metadata transform path/to/file.xml --input-schema=iso19139 --output-schema=oarec-record
7073

‎pygeometa/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848

4949
from pygeometa.core import (generate, import_, info, schemas,
5050
transform, validate)
51+
from pygeometa.migrations import migrate_
5152
from pygeometa.util import get_package_version
5253

5354
__version__ = get_package_version()
@@ -68,6 +69,7 @@ def metadata():
6869
metadata.add_command(generate)
6970
metadata.add_command(import_)
7071
metadata.add_command(info)
72+
metadata.add_command(migrate_)
7173
metadata.add_command(schemas)
7274
metadata.add_command(transform)
7375
metadata.add_command(validate)

‎pygeometa/core.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,11 +224,13 @@ def prune_transfer_option(formats: dict, language: str) -> list:
224224
return unique_transfer
225225

226226

227-
def read_mcf(mcf: Union[dict, str]) -> dict:
227+
def read_mcf(mcf: Union[dict, str], skip_version_fail: bool = False) -> dict:
228228
"""
229229
returns dict of YAML file from filepath, string or dict
230230
231231
:param mcf: str, dict or filepath of MCF data
232+
:param skip_version_fail: bool of whether to skip
233+
version failures (default=False)
232234
233235
:returns: dict of MCF data
234236
"""
@@ -321,8 +323,9 @@ def __parse_mcf_dict_recursive(dict2):
321323
raise MCFReadError(msg)
322324

323325
for mcf_version_ in mcf_versions:
324-
if not mcf_version_.startswith(mcf_version):
325-
msg = f'invalid / unsupported version {mcf_version}'
326+
if not mcf_version_.startswith(mcf_version) and not skip_version_fail:
327+
msg = (f'invalid / unsupported version {mcf_version}; '
328+
f'please migrate to the latest MCF version')
326329
LOGGER.error(msg)
327330
raise MCFReadError(msg)
328331

‎pygeometa/migrations.py‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
# =================================================================
2+
#
3+
# Terms and Conditions of Use
4+
#
5+
# Unless otherwise noted, computer program source code of this
6+
# distribution # is covered under Crown Copyright, Government of
7+
# Canada, and is distributed under the MIT License.
8+
#
9+
# The Canada wordmark and related graphics associated with this
10+
# distribution are protected under trademark law and copyright law.
11+
# No permission is granted to use them outside the parameters of
12+
# the Government of Canada's corporate identity program. For
13+
# more information, see
14+
# http://www.tbs-sct.gc.ca/fip-pcim/index-eng.asp
15+
#
16+
# Copyright title to all 3rd party software distributed with this
17+
# software is held by the respective copyright holders as noted in
18+
# those files. Users are asked to read the 3rd Party Licenses
19+
# referenced with those assets.
20+
#
21+
# Copyright (c) 2026 Tom Kralidis
22+
#
23+
# Permission is hereby granted, free of charge, to any person
24+
# obtaining a copy of this software and associated documentation
25+
# files (the "Software"), to deal in the Software without
26+
# restriction, including without limitation the rights to use,
27+
# copy, modify, merge, publish, distribute, sublicense, and/or sell
28+
# copies of the Software, and to permit persons to whom the
29+
# Software is furnished to do so, subject to the following
30+
# conditions:
31+
#
32+
# The above copyright notice and this permission notice shall be
33+
# included in all copies or substantial portions of the Software.
34+
#
35+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
36+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
37+
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
38+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
39+
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
40+
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
41+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
42+
# OTHER DEALINGS IN THE SOFTWARE.
43+
#
44+
# =================================================================
45+
46+
import click
47+
import logging
48+
49+
import yaml
50+
51+
from pygeometa import cli_options
52+
from pygeometa.core import read_mcf
53+
54+
LOGGER = logging.getLogger(__name__)
55+
56+
57+
def migrate_from_1_0_to_2_0(mcf_dict: dict) -> dict:
58+
"""
59+
migrate MCF from 1.0
60+
61+
:param mcf_dict: `dict` of MCF
62+
63+
:returns: `dict` of MCF migrated from 1.0
64+
"""
65+
66+
mcf_dict['mcf']['version'] = LATEST_MCF
67+
68+
mcf_dict['metadata']['dates'] = {
69+
'creation': mcf_dict['metadata'].pop('datestamp', None)
70+
}
71+
72+
return mcf_dict
73+
74+
75+
LATEST_MCF = 2.0
76+
77+
MIGRATIONS = {
78+
'1.0': migrate_from_1_0_to_2_0
79+
}
80+
81+
82+
def migrate(mcf: dict) -> dict:
83+
"""
84+
migrate MCF document
85+
86+
:param mcf_dict: `dict` of MCF
87+
88+
:returns: `dict` of MCF migrated from 1.0
89+
"""
90+
91+
mcf_dict = read_mcf(mcf, skip_version_fail=True)
92+
93+
mcf_version = str(mcf_dict['mcf']['version'])
94+
LOGGER.info(f'Migrating MCF from version {mcf_version}')
95+
96+
if mcf_version == str(LATEST_MCF):
97+
LOGGER.info('MCF is already at the latest version')
98+
return mcf_dict
99+
100+
if mcf_version not in MIGRATIONS.keys():
101+
msg = 'Unsupported version for migration'
102+
raise RuntimeError(msg)
103+
104+
return MIGRATIONS[mcf_version](mcf_dict)
105+
106+
107+
@click.command('migrate')
108+
@click.pass_context
109+
@cli_options.ARGUMENT_MCF
110+
@cli_options.OPTION_OUTPUT
111+
@cli_options.OPTION_VERBOSITY
112+
def migrate_(ctx, mcf, output, verbosity):
113+
"""migrate an MCF document"""
114+
115+
try:
116+
content = migrate(mcf)
117+
except RuntimeError as err:
118+
raise click.ClickException(err)
119+
120+
if output is None:
121+
click.echo(yaml.dump(content))
122+
else:
123+
output.write(yaml.dump(content, indent=4))

‎tests/run_tests.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
MCFValidationError, SCHEMAS, transform_metadata,
6161
validate_mcf)
6262
from pygeometa.helpers import generate_datetime, json_dumps
63+
from pygeometa.migrations import migrate
6364
from pygeometa.schemas import (get_supported_schemas, InvalidSchemaError,
6465
load_schema)
6566
from pygeometa.schemas.iso19139 import ISO19139OutputSchema
@@ -608,6 +609,38 @@ def test_get_geojson_geometry(self):
608609
self.assertEqual(geometry['type'], spatial['type'],
609610
f"Expected geometry type {spatial['type']}")
610611

612+
def test_migrate(self):
613+
"""Test pygeometa.migrations.migrate"""
614+
615+
with open(get_abspath('sample-1.0.mcf.yml')) as fh:
616+
mcf_dict = yaml.load(fh, Loader=yaml.FullLoader)
617+
618+
self.assertEqual(mcf_dict['mcf']['version'], 1.0)
619+
self.assertTrue('datestamp' in mcf_dict['metadata'])
620+
self.assertFalse('dates' in mcf_dict['metadata'])
621+
622+
mcf_dict = migrate(mcf_dict)
623+
624+
self.assertEqual(mcf_dict['mcf']['version'], 2.0)
625+
self.assertFalse('datestamp' in mcf_dict['metadata'])
626+
self.assertTrue('dates' in mcf_dict['metadata'])
627+
self.assertTrue('creation' in mcf_dict['metadata']['dates'])
628+
629+
with open(get_abspath('../sample.mcf.yml')) as fh:
630+
mcf_dict = yaml.load(fh, Loader=yaml.FullLoader)
631+
632+
self.assertEqual(mcf_dict['mcf']['version'], 2.0)
633+
self.assertFalse('datestamp' in mcf_dict['metadata'])
634+
self.assertTrue('dates' in mcf_dict['metadata'])
635+
self.assertTrue('creation' in mcf_dict['metadata']['dates'])
636+
637+
mcf_dict = migrate(mcf_dict)
638+
639+
self.assertEqual(mcf_dict['mcf']['version'], 2.0)
640+
self.assertFalse('datestamp' in mcf_dict['metadata'])
641+
self.assertTrue('dates' in mcf_dict['metadata'])
642+
self.assertTrue('creation' in mcf_dict['metadata']['dates'])
643+
611644

612645
def get_abspath(filepath):
613646
"""helper function absolute file access"""

‎tests/sample-1.0.mcf.yml‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
mcf:
2+
version: 1.0
3+
4+
metadata:
5+
identifier: 3f342f64-9348-11df-ba6a-0014c2c00eab
6+
additional_identifiers:
7+
- identifier: 10.277/3f342f64-9348
8+
scheme: https://doi.org
9+
language: en
10+
language_alternate: fr
11+
charset: utf8
12+
parentidentifier: someparentid
13+
relations:
14+
- identifier: 10.278/45e22-11223-2
15+
scheme: http://doi.org
16+
type: source
17+
hierarchylevel: dataset
18+
datestamp: 2014-11-11
19+
dataseturi: http://some/minted/uri
20+
21+
spatial:
22+
datatype: vector
23+
geomtype: point
24+
25+
identification:
26+
language: eng; CAN
27+
charset: utf8
28+
title:
29+
en: title in English
30+
fr: title in French
31+
abstract:
32+
en: abstract in English
33+
fr: abstract in French
34+
edition: 1.8.0
35+
dates:
36+
creation: 2000-09-01T00:00:00Z
37+
publication: 2001-11-11
38+
keywords:
39+
default:
40+
keywords:
41+
en: [kw1 in English,kw2 in English,kw3 in English]
42+
fr: [kw1 in French,kw2 in French,kw3 in French]
43+
wmo:
44+
keywords:
45+
en: [FOO,BAR]
46+
keywords_type: theme
47+
vocabulary:
48+
name:
49+
en: My vocabulary
50+
fr: Mon vocabulaire
51+
url: http://example.org/vocab
52+
gc_cst:
53+
keywords:
54+
en: [kw1,kw2]
55+
fr: [kw1,kw2]
56+
topiccategory:
57+
- climatologyMeteorologyAtmosphere
58+
extents:
59+
spatial:
60+
- bbox: [-141,42,-52,84]
61+
crs: 4326
62+
temporal:
63+
- begin: 1950-07-31
64+
end: now
65+
resolution: P1Y
66+
fees: None
67+
accessconstraints: otherRestrictions
68+
license:
69+
name: CC BY 4.0
70+
url: https://creativecommons.org/licenses/by/4.0
71+
rights:
72+
en: Copyright (c) 2010 Her Majesty the Queen in Right of Canada
73+
fr: Copyright (c) 2010 Her Majesty the Queen in Right of Canada
74+
url: http://geogratis.ca/geogratis/en/product/search.do?id=08DB5E85-7405-FE3A-2860-CC3663245625
75+
status: onGoing
76+
maintenancefrequency: continual
77+
78+
content_info:
79+
type: image
80+
cloud_cover: 72
81+
processing_level: "1.0"
82+
attributes:
83+
- name: TS_OBS
84+
title: Observation timestamp
85+
type: datetime
86+
- name: CA_MG_L
87+
title: Calcium content in MG per L
88+
type: number
89+
url: https://en.wikipedia.org/wiki/Calcium
90+
units: MilliGM-PER-L
91+
- name: MG_MG_L
92+
title: Magnesium content in MG per L
93+
type: number
94+
url: https://en.wikipedia.org/wiki/Magnesium
95+
units: MilliGM-PER-L
96+
dimensions:
97+
- name: B1
98+
units: nm
99+
min: 932
100+
max: 958
101+
102+
# platform metadata, applicable to iso19139-2 output
103+
acquisition:
104+
platforms:
105+
- identifier: LANDSAT_8
106+
description: Landsat 8
107+
instruments:
108+
- identifier: OLI_TIRS
109+
type: INS-NOBS
110+
111+
contact:
112+
pointOfContact: &contact_poc
113+
organization: Environment Canada
114+
url: https://www.ec.gc.ca/
115+
individualname: Tom Kralidis
116+
positionname: Senior Systems Scientist
117+
phone: +01-123-456-7890
118+
fax: +01-123-456-7890
119+
address: 4905 Dufferin Street
120+
city: Toronto
121+
administrativearea: Ontario
122+
postalcode: M3H 5T4
123+
country: Canada
124+
email: foo@bar.tld
125+
hoursofservice: 0700h - 1500h EST
126+
contactinstructions: email
127+
128+
distributor: *contact_poc
129+
130+
distribution:
131+
waf:
132+
url: https://example.org/data
133+
type: WWW:LINK
134+
rel: canonical
135+
name: my waf
136+
description:
137+
en: description in English
138+
fr: description in French
139+
function: download
140+
141+
wms:
142+
url: https://example.org/wms
143+
type: OGC:WMS
144+
rel: service
145+
name:
146+
en: roads
147+
fr: routes
148+
description:
149+
en: description in English
150+
fr: description in French
151+
function: download
152+
153+
dataquality:
154+
scope:
155+
level: dataset
156+
lineage:
157+
statement: this dataset was derived from a custom process against dataset xyz

0 commit comments

Comments
 (0)