compass-lib 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. compass_lib-0.0.3/LICENSE +201 -0
  2. compass_lib-0.0.3/PKG-INFO +60 -0
  3. compass_lib-0.0.3/README.md +15 -0
  4. compass_lib-0.0.3/compass_lib/__init__.py +117 -0
  5. compass_lib-0.0.3/compass_lib/commands/__init__.py +2 -0
  6. compass_lib-0.0.3/compass_lib/commands/convert.py +249 -0
  7. compass_lib-0.0.3/compass_lib/commands/encrypt.py +115 -0
  8. compass_lib-0.0.3/compass_lib/commands/geojson.py +118 -0
  9. compass_lib-0.0.3/compass_lib/commands/main.py +33 -0
  10. compass_lib-0.0.3/compass_lib/constants.py +84 -0
  11. compass_lib-0.0.3/compass_lib/enums.py +356 -0
  12. compass_lib-0.0.3/compass_lib/errors.py +86 -0
  13. compass_lib-0.0.3/compass_lib/geo_utils.py +47 -0
  14. compass_lib-0.0.3/compass_lib/geojson.py +1024 -0
  15. compass_lib-0.0.3/compass_lib/interface.py +332 -0
  16. compass_lib-0.0.3/compass_lib/io.py +246 -0
  17. compass_lib-0.0.3/compass_lib/models.py +251 -0
  18. compass_lib-0.0.3/compass_lib/plot/__init__.py +28 -0
  19. compass_lib-0.0.3/compass_lib/plot/models.py +265 -0
  20. compass_lib-0.0.3/compass_lib/plot/parser.py +610 -0
  21. compass_lib-0.0.3/compass_lib/project/__init__.py +36 -0
  22. compass_lib-0.0.3/compass_lib/project/format.py +158 -0
  23. compass_lib-0.0.3/compass_lib/project/models.py +494 -0
  24. compass_lib-0.0.3/compass_lib/project/parser.py +638 -0
  25. compass_lib-0.0.3/compass_lib/survey/__init__.py +24 -0
  26. compass_lib-0.0.3/compass_lib/survey/format.py +284 -0
  27. compass_lib-0.0.3/compass_lib/survey/models.py +160 -0
  28. compass_lib-0.0.3/compass_lib/survey/parser.py +842 -0
  29. compass_lib-0.0.3/compass_lib/validation.py +74 -0
  30. compass_lib-0.0.3/pyproject.toml +245 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: compass_lib
3
+ Version: 0.0.3
4
+ Summary: Compass Parser Library.
5
+ Keywords: cave,survey,karst
6
+ Author-email: Jonathan Dekhtiar <jonathan@dekhtiar.com>
7
+ Maintainer-email: Jonathan Dekhtiar <jonathan@dekhtiar.com>
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: Topic :: Software Development :: Build Tools
15
+ Classifier: Topic :: Scientific/Engineering
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Topic :: Utilities
18
+ Classifier: License :: OSI Approved :: Apache Software License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ License-File: LICENSE
23
+ Requires-Dist: geojson>=3.2,<4
24
+ Requires-Dist: orjson>=3.10,<3.12
25
+ Requires-Dist: pydantic>=2.12,<2.13
26
+ Requires-Dist: pydantic-extra-types>=2.11,<3.0
27
+ Requires-Dist: pyIGRF14==1.0.4
28
+ Requires-Dist: pyproj>=3.7.1,<3.8
29
+ Requires-Dist: utm>=0.8.1,<0.9
30
+ Requires-Dist: cryptography>=44.0.0,<47.0.0 ; extra == "test"
31
+ Requires-Dist: python-dotenv>=1.0.0,<2.0.0 ; extra == "test"
32
+ Requires-Dist: deepdiff>=7.0,<9.0 ; extra == "test"
33
+ Requires-Dist: pytest>=8.0.0,<10.0.0 ; extra == "test"
34
+ Requires-Dist: pytest-cov>=5.0.0,<8.0.0 ; extra == "test"
35
+ Requires-Dist: pytest-dotenv>=0.5.0,<1.0.0 ; extra == "test"
36
+ Requires-Dist: pytest-env>=1.1.3,<2.0.0 ; extra == "test"
37
+ Requires-Dist: pytest-runner>=6.0.0,<7.0.0 ; extra == "test"
38
+ Requires-Dist: pytest-ordering>=0.6,<1.0.0 ; extra == "test"
39
+ Requires-Dist: parameterized>=0.9.0,<0.10 ; extra == "test"
40
+ Project-URL: Bug Reports, https://github.com/OpenSpeleo/pytool_compass_lib/issues
41
+ Project-URL: Homepage, https://pypi.org/project/compass-lib/
42
+ Project-URL: Source, https://github.com/OpenSpeleo/pytool_compass_lib
43
+ Provides-Extra: test
44
+
45
+ # Compass Python Lib
46
+
47
+ ## Conversion commands:
48
+
49
+ ```bash
50
+ # Install in dev mod
51
+ pip install -e ".[dev,test]"
52
+
53
+ # Install latest stable version
54
+ pip install compass_lib
55
+
56
+ # run some commands
57
+ compass convert --input_file=./tests/artifacts/fulford.dat --output_file=fulford.json --format=json --overwrite
58
+ compass convert --input_file=./tests/artifacts/random.dat --output_file=random.json --format=json --overwrite
59
+ ```
60
+
@@ -0,0 +1,15 @@
1
+ # Compass Python Lib
2
+
3
+ ## Conversion commands:
4
+
5
+ ```bash
6
+ # Install in dev mod
7
+ pip install -e ".[dev,test]"
8
+
9
+ # Install latest stable version
10
+ pip install compass_lib
11
+
12
+ # run some commands
13
+ compass convert --input_file=./tests/artifacts/fulford.dat --output_file=fulford.json --format=json --overwrite
14
+ compass convert --input_file=./tests/artifacts/random.dat --output_file=random.json --format=json --overwrite
15
+ ```
@@ -0,0 +1,117 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Compass Parser Library.
3
+
4
+ A Python library for parsing and formatting Compass cave survey data files.
5
+ Supports .DAT (survey data), .MAK (project files), and .PLT (plot files).
6
+
7
+ Usage:
8
+ # Load a complete project (MAK + all DAT files)
9
+ from compass_lib import load_project
10
+ project = load_project(Path("cave.mak"))
11
+
12
+ for file_dir in project.file_directives:
13
+ print(f"File: {file_dir.file}")
14
+ if file_dir.data:
15
+ for trip in file_dir.data.trips:
16
+ print(f" Survey: {trip.header.survey_name}")
17
+
18
+ # Or load individual files
19
+ from compass_lib import read_dat_file, read_mak_file
20
+ trips = read_dat_file(Path("survey.DAT"))
21
+ directives = read_mak_file(Path("project.MAK"))
22
+ """
23
+
24
+ __version__ = "0.0.3"
25
+
26
+ # Constants
27
+ from compass_lib.constants import COMPASS_ENCODING
28
+ from compass_lib.constants import FEET_TO_METERS
29
+ from compass_lib.constants import JSON_ENCODING
30
+ from compass_lib.constants import METERS_TO_FEET
31
+
32
+ # Enums
33
+ from compass_lib.enums import AzimuthUnit
34
+ from compass_lib.enums import CompassFileType
35
+ from compass_lib.enums import DrawOperation
36
+ from compass_lib.enums import FileFormat
37
+ from compass_lib.enums import InclinationUnit
38
+ from compass_lib.enums import LengthUnit
39
+ from compass_lib.enums import LrudAssociation
40
+ from compass_lib.enums import LrudItem
41
+ from compass_lib.enums import Severity
42
+ from compass_lib.enums import ShotItem
43
+ from compass_lib.errors import CompassParseError
44
+ from compass_lib.errors import CompassParseException
45
+ from compass_lib.errors import SourceLocation
46
+ from compass_lib.interface import CompassInterface
47
+ from compass_lib.io import CancellationToken
48
+ from compass_lib.io import load_project
49
+ from compass_lib.io import read_dat_file
50
+ from compass_lib.io import read_mak_and_dat_files
51
+ from compass_lib.io import read_mak_file
52
+ from compass_lib.io import save_project
53
+ from compass_lib.io import write_dat_file
54
+ from compass_lib.io import write_mak_file
55
+ from compass_lib.models import Bounds
56
+ from compass_lib.models import Location
57
+ from compass_lib.models import NEVLocation
58
+ from compass_lib.project.models import CompassMakFile
59
+ from compass_lib.project.models import FileDirective
60
+ from compass_lib.project.models import LinkStation
61
+ from compass_lib.survey.models import CompassDatFile
62
+ from compass_lib.survey.models import CompassShot
63
+ from compass_lib.survey.models import CompassTrip
64
+ from compass_lib.survey.models import CompassTripHeader
65
+ from compass_lib.validation import days_in_month
66
+ from compass_lib.validation import is_valid_station_name
67
+ from compass_lib.validation import validate_station_name
68
+
69
+ __all__ = [
70
+ # Constants
71
+ "COMPASS_ENCODING",
72
+ "FEET_TO_METERS",
73
+ "JSON_ENCODING",
74
+ "METERS_TO_FEET",
75
+ # Enums
76
+ "AzimuthUnit",
77
+ # Base Models
78
+ "Bounds",
79
+ "CancellationToken",
80
+ # Survey Models
81
+ "CompassDatFile",
82
+ "CompassFileType",
83
+ # I/O
84
+ "CompassInterface",
85
+ # Project Models
86
+ "CompassMakFile",
87
+ # Errors
88
+ "CompassParseError",
89
+ "CompassParseException",
90
+ "CompassShot",
91
+ "CompassTrip",
92
+ "CompassTripHeader",
93
+ "DrawOperation",
94
+ "FileDirective",
95
+ "FileFormat",
96
+ "InclinationUnit",
97
+ "LengthUnit",
98
+ "LinkStation",
99
+ "Location",
100
+ "LrudAssociation",
101
+ "LrudItem",
102
+ "NEVLocation",
103
+ "Severity",
104
+ "ShotItem",
105
+ "SourceLocation",
106
+ "days_in_month",
107
+ # Validation
108
+ "is_valid_station_name",
109
+ "load_project",
110
+ "read_dat_file",
111
+ "read_mak_and_dat_files",
112
+ "read_mak_file",
113
+ "save_project",
114
+ "validate_station_name",
115
+ "write_dat_file",
116
+ "write_mak_file",
117
+ ]
@@ -0,0 +1,2 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Command-line interface commands for compass_lib."""
@@ -0,0 +1,249 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Convert command for Compass files.
3
+
4
+ Supports bidirectional conversion between Compass native formats (DAT, MAK)
5
+ and JSON format using Pydantic's built-in serialization.
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ from pathlib import Path
11
+
12
+ from compass_lib.constants import COMPASS_ENCODING
13
+ from compass_lib.constants import JSON_ENCODING
14
+ from compass_lib.enums import CompassFileType
15
+ from compass_lib.enums import FileExtension
16
+ from compass_lib.enums import FileFormat
17
+ from compass_lib.enums import FormatIdentifier
18
+ from compass_lib.io import load_project
19
+ from compass_lib.io import read_dat_file
20
+ from compass_lib.project.format import format_mak_file
21
+ from compass_lib.project.models import CompassMakFile
22
+ from compass_lib.survey.format import format_dat_file
23
+ from compass_lib.survey.models import CompassDatFile
24
+
25
+
26
+ class ConversionError(Exception):
27
+ """Error raised for invalid conversion operations."""
28
+
29
+
30
+ def detect_file_format(
31
+ path: Path,
32
+ ) -> tuple[FileFormat, CompassFileType | None]:
33
+ """Detect the file format and type based on extension and content.
34
+
35
+ Args:
36
+ path: File path
37
+
38
+ Returns:
39
+ Tuple of (format_type, file_type) where:
40
+ - format_type: FileFormat.COMPASS or FileFormat.JSON
41
+ - file_type: CompassFileType.DAT or CompassFileType.MAK (or None)
42
+ """
43
+
44
+ match f_ext := path.suffix.lower():
45
+ case FileExtension.DAT.value:
46
+ return (FileFormat.COMPASS, CompassFileType.DAT)
47
+
48
+ case FileExtension.MAK.value:
49
+ return (FileFormat.COMPASS, CompassFileType.MAK)
50
+
51
+ case FileExtension.JSON.value:
52
+ # Read the file to detect format from content
53
+ content = path.read_text(encoding=JSON_ENCODING)
54
+ if (
55
+ f'"format": "{FormatIdentifier.COMPASS_DAT.value}"' in content
56
+ or f'"format":"{FormatIdentifier.COMPASS_DAT.value}"' in content
57
+ ):
58
+ return (FileFormat.JSON, CompassFileType.DAT)
59
+
60
+ if (
61
+ f'"format": "{FormatIdentifier.COMPASS_MAK.value}"' in content
62
+ or f'"format":"{FormatIdentifier.COMPASS_MAK.value}"' in content
63
+ ):
64
+ return (FileFormat.JSON, CompassFileType.MAK)
65
+
66
+ raise ValueError(f"Unknown file type found inside json: `{f_ext}`")
67
+
68
+ case _:
69
+ raise ValueError(f"Unknown file extension: `{f_ext}`")
70
+
71
+
72
+ def _convert(
73
+ input_path: Path,
74
+ output_path: Path | None = None,
75
+ target_format: FileFormat | str | None = None,
76
+ ) -> str | None:
77
+ """Convert a file between formats.
78
+
79
+ Args:
80
+ input_path: Input file path
81
+ output_path: Output file path (None = return as string)
82
+ target_format: Target format (FileFormat or string 'compass'/'json')
83
+
84
+ Returns:
85
+ Converted content as string if output_path is None,
86
+ otherwise None (writes to file)
87
+
88
+ Raises:
89
+ ConversionError: If conversion is not valid
90
+ FileNotFoundError: If input file doesn't exist
91
+ """
92
+ if not input_path.exists():
93
+ raise FileNotFoundError(f"Input file not found: {input_path}")
94
+
95
+ # Detect source format
96
+ source_format, file_type = detect_file_format(input_path)
97
+
98
+ if file_type is None:
99
+ raise ConversionError(f"Cannot determine file type for: {input_path}")
100
+
101
+ # Normalize target format to enum
102
+ if isinstance(target_format, str):
103
+ target_format = FileFormat(target_format)
104
+ elif target_format is None:
105
+ # Auto-determine: opposite of source
106
+ target_format = (
107
+ FileFormat.JSON
108
+ if source_format == FileFormat.COMPASS
109
+ else FileFormat.COMPASS
110
+ )
111
+
112
+ # Validate: no same-format conversion
113
+ if source_format == target_format:
114
+ raise ConversionError(
115
+ f"Invalid conversion: {source_format.value} => {target_format.value}. "
116
+ f"Source and target formats must be different."
117
+ )
118
+
119
+ # Perform conversion
120
+ if source_format == FileFormat.COMPASS and target_format == FileFormat.JSON:
121
+ # Compass -> JSON using Pydantic
122
+ if file_type == CompassFileType.DAT:
123
+ trips = read_dat_file(input_path)
124
+ dat_file = CompassDatFile(trips=trips)
125
+ # Wrap in format envelope for DAT files
126
+ envelope = {
127
+ "version": "1.0",
128
+ "format": FormatIdentifier.COMPASS_DAT.value,
129
+ "trips": json.loads(dat_file.model_dump_json(by_alias=True))["trips"],
130
+ }
131
+ result = json.dumps(envelope, indent=2, sort_keys=True)
132
+ else: # mak
133
+ project = load_project(input_path)
134
+ result = project.model_dump_json(indent=2, by_alias=True)
135
+
136
+ elif source_format == FileFormat.JSON and target_format == FileFormat.COMPASS:
137
+ # JSON -> Compass using Pydantic
138
+ json_str = input_path.read_text(encoding=JSON_ENCODING)
139
+ if file_type == CompassFileType.DAT:
140
+ data = json.loads(json_str)
141
+ # Handle both envelope format and raw format
142
+ trips_data = data.get("trips", [])
143
+ dat_file = CompassDatFile.model_validate({"trips": trips_data})
144
+ result = format_dat_file(dat_file.trips) or ""
145
+ else: # mak
146
+ project = CompassMakFile.model_validate_json(json_str)
147
+ result = format_mak_file(project.directives) or ""
148
+
149
+ else:
150
+ raise ConversionError(
151
+ f"Unsupported conversion: {source_format.value} => {target_format.value}"
152
+ )
153
+
154
+ # Output handling
155
+ if output_path is None:
156
+ return result
157
+
158
+ # Write to file
159
+ if target_format == FileFormat.JSON:
160
+ output_path.write_text(result, encoding=JSON_ENCODING)
161
+ else:
162
+ # Compass format uses Windows-1252
163
+ output_path.write_text(result, encoding=COMPASS_ENCODING, errors="replace")
164
+
165
+ return None
166
+
167
+
168
+ def convert(args: list[str]) -> int:
169
+ """Entry point for the convert command."""
170
+ parser = argparse.ArgumentParser(
171
+ prog="compass convert",
172
+ description="Convert Compass files between native and JSON formats",
173
+ formatter_class=argparse.RawDescriptionHelpFormatter,
174
+ epilog="""
175
+ Examples:
176
+ compass convert -i survey.DAT # Convert to JSON (stdout)
177
+ compass convert -i survey.DAT -o survey.json # Convert to JSON file
178
+ compass convert -i project.MAK -f json # Convert to JSON (stdout)
179
+ compass convert -i survey.json -o survey.DAT # Convert to Compass format
180
+ compass convert -i survey.json -f compass # Convert to Compass (stdout)
181
+
182
+ Supported conversions:
183
+ compass -> json Survey/project data to JSON
184
+ json -> compass JSON to survey/project data
185
+
186
+ Notes:
187
+ - File type (DAT/MAK) is auto-detected from extension or JSON content
188
+ - Target format is auto-detected if not specified (opposite of source)
189
+ - Cannot convert compass -> compass or json -> json
190
+ """,
191
+ )
192
+
193
+ parser.add_argument(
194
+ "-i",
195
+ "--input-file",
196
+ type=Path,
197
+ required=True,
198
+ help="Input file path (.DAT, .MAK, or .json)",
199
+ )
200
+ parser.add_argument(
201
+ "-o",
202
+ "--output-file",
203
+ type=Path,
204
+ default=None,
205
+ help="Output file path (prints to stdout if not specified)",
206
+ )
207
+ parser.add_argument(
208
+ "-f",
209
+ "--format",
210
+ choices=[FileFormat.COMPASS.value, FileFormat.JSON.value],
211
+ default=None,
212
+ dest="target_format",
213
+ help="Target format: 'compass' or 'json' (auto-detected if not specified)",
214
+ )
215
+
216
+ parsed_args = parser.parse_args(args)
217
+
218
+ try:
219
+ result = _convert(
220
+ input_path=parsed_args.input_file,
221
+ output_path=parsed_args.output_file,
222
+ target_format=parsed_args.target_format,
223
+ )
224
+
225
+ if result is not None:
226
+ # Print to stdout
227
+ pass
228
+
229
+ # Print status to stderr if writing to file
230
+ if parsed_args.output_file is not None:
231
+ source_format, _file_type = detect_file_format(parsed_args.input_file)
232
+ (
233
+ FileFormat(parsed_args.target_format)
234
+ if parsed_args.target_format
235
+ else (
236
+ FileFormat.JSON
237
+ if source_format == FileFormat.COMPASS
238
+ else FileFormat.COMPASS
239
+ )
240
+ )
241
+
242
+ except ConversionError:
243
+ return 1
244
+ except FileNotFoundError:
245
+ return 1
246
+ except Exception: # noqa: BLE001
247
+ return 1
248
+
249
+ return 0