mainframe-migration-toolkit 0.2.0__py3-none-any.whl

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 (52) hide show
  1. mainframe_migration_toolkit-0.2.0.dist-info/METADATA +16 -0
  2. mainframe_migration_toolkit-0.2.0.dist-info/RECORD +52 -0
  3. mainframe_migration_toolkit-0.2.0.dist-info/WHEEL +4 -0
  4. mainframe_migration_toolkit-0.2.0.dist-info/entry_points.txt +3 -0
  5. mainframe_toolkit/__init__.py +92 -0
  6. mainframe_toolkit/__main__.py +5 -0
  7. mainframe_toolkit/_workspace/.claude/skills/analyze-mainframe-similarity/SKILL.md +30 -0
  8. mainframe_toolkit/_workspace/.claude/skills/migrate-mainframe-job/SKILL.md +63 -0
  9. mainframe_toolkit/_workspace/.claude/skills/validate-golden-dataset/SKILL.md +12 -0
  10. mainframe_toolkit/_workspace/AGENTS.md +10 -0
  11. mainframe_toolkit/_workspace/CLAUDE.md +2 -0
  12. mainframe_toolkit/_workspace/validator-java/.mvn/wrapper/maven-wrapper.properties +3 -0
  13. mainframe_toolkit/_workspace/validator-java/mvnw +295 -0
  14. mainframe_toolkit/_workspace/validator-java/mvnw.cmd +189 -0
  15. mainframe_toolkit/_workspace/validator-java/pom.xml +116 -0
  16. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/AvroValueFormatter.java +152 -0
  17. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/CsvTabularReader.java +111 -0
  18. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/DataFormat.java +62 -0
  19. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/Difference.java +34 -0
  20. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/InputFileSet.java +45 -0
  21. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/InputOptions.java +23 -0
  22. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/JsonReportWriter.java +40 -0
  23. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/MultiFileTabularReader.java +80 -0
  24. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/Normalization.java +16 -0
  25. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/ParquetTabularReader.java +61 -0
  26. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/TabularReader.java +13 -0
  27. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/TabularReaderFactory.java +29 -0
  28. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/ValidationOptions.java +40 -0
  29. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/ValidationReport.java +44 -0
  30. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/ValidationService.java +395 -0
  31. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/ValidatorCli.java +190 -0
  32. mainframe_toolkit/_workspace/validator-java/src/main/java/io/mainframe/migration/validator/ValueNormalizer.java +27 -0
  33. mainframe_toolkit/_workspace/validator-java/src/test/java/io/mainframe/migration/validator/DirectoryValidationTest.java +70 -0
  34. mainframe_toolkit/_workspace/validator-java/src/test/java/io/mainframe/migration/validator/JsonReportWriterTest.java +43 -0
  35. mainframe_toolkit/_workspace/validator-java/src/test/java/io/mainframe/migration/validator/KeyedValidationTest.java +89 -0
  36. mainframe_toolkit/_workspace/validator-java/src/test/java/io/mainframe/migration/validator/ParquetValidationTest.java +146 -0
  37. mainframe_toolkit/_workspace/validator-java/src/test/java/io/mainframe/migration/validator/ValidationServiceTest.java +137 -0
  38. mainframe_toolkit/_workspace/validator-java/src/test/java/io/mainframe/migration/validator/ValidatorCliTest.java +102 -0
  39. mainframe_toolkit/cli.py +361 -0
  40. mainframe_toolkit/cobol.py +106 -0
  41. mainframe_toolkit/copybook.py +558 -0
  42. mainframe_toolkit/errors.py +15 -0
  43. mainframe_toolkit/external.py +48 -0
  44. mainframe_toolkit/io.py +202 -0
  45. mainframe_toolkit/jcl.py +126 -0
  46. mainframe_toolkit/pipeline.py +322 -0
  47. mainframe_toolkit/sequential.py +259 -0
  48. mainframe_toolkit/similarity.py +1171 -0
  49. mainframe_toolkit/sorting.py +60 -0
  50. mainframe_toolkit/specs.py +312 -0
  51. mainframe_toolkit/synthetic.py +108 -0
  52. mainframe_toolkit/workspace.py +133 -0
@@ -0,0 +1,189 @@
1
+ <# : batch portion
2
+ @REM ----------------------------------------------------------------------------
3
+ @REM Licensed to the Apache Software Foundation (ASF) under one
4
+ @REM or more contributor license agreements. See the NOTICE file
5
+ @REM distributed with this work for additional information
6
+ @REM regarding copyright ownership. The ASF licenses this file
7
+ @REM to you under the Apache License, Version 2.0 (the
8
+ @REM "License"); you may not use this file except in compliance
9
+ @REM with the License. You may obtain a copy of the License at
10
+ @REM
11
+ @REM http://www.apache.org/licenses/LICENSE-2.0
12
+ @REM
13
+ @REM Unless required by applicable law or agreed to in writing,
14
+ @REM software distributed under the License is distributed on an
15
+ @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ @REM KIND, either express or implied. See the License for the
17
+ @REM specific language governing permissions and limitations
18
+ @REM under the License.
19
+ @REM ----------------------------------------------------------------------------
20
+
21
+ @REM ----------------------------------------------------------------------------
22
+ @REM Apache Maven Wrapper startup batch script, version 3.3.4
23
+ @REM
24
+ @REM Optional ENV vars
25
+ @REM MVNW_REPOURL - repo url base for downloading maven distribution
26
+ @REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
27
+ @REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
28
+ @REM ----------------------------------------------------------------------------
29
+
30
+ @IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
31
+ @SET __MVNW_CMD__=
32
+ @SET __MVNW_ERROR__=
33
+ @SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
34
+ @SET PSModulePath=
35
+ @FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
36
+ IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
37
+ )
38
+ @SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
39
+ @SET __MVNW_PSMODULEP_SAVE=
40
+ @SET __MVNW_ARG0_NAME__=
41
+ @SET MVNW_USERNAME=
42
+ @SET MVNW_PASSWORD=
43
+ @IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
44
+ @echo Cannot start maven from wrapper >&2 && exit /b 1
45
+ @GOTO :EOF
46
+ : end batch / begin powershell #>
47
+
48
+ $ErrorActionPreference = "Stop"
49
+ if ($env:MVNW_VERBOSE -eq "true") {
50
+ $VerbosePreference = "Continue"
51
+ }
52
+
53
+ # calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
54
+ $distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
55
+ if (!$distributionUrl) {
56
+ Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
57
+ }
58
+
59
+ switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
60
+ "maven-mvnd-*" {
61
+ $USE_MVND = $true
62
+ $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
63
+ $MVN_CMD = "mvnd.cmd"
64
+ break
65
+ }
66
+ default {
67
+ $USE_MVND = $false
68
+ $MVN_CMD = $script -replace '^mvnw','mvn'
69
+ break
70
+ }
71
+ }
72
+
73
+ # apply MVNW_REPOURL and calculate MAVEN_HOME
74
+ # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
75
+ if ($env:MVNW_REPOURL) {
76
+ $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
77
+ $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
78
+ }
79
+ $distributionUrlName = $distributionUrl -replace '^.*/',''
80
+ $distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
81
+
82
+ $MAVEN_M2_PATH = "$HOME/.m2"
83
+ if ($env:MAVEN_USER_HOME) {
84
+ $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
85
+ }
86
+
87
+ if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
88
+ New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
89
+ }
90
+
91
+ $MAVEN_WRAPPER_DISTS = $null
92
+ if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
93
+ $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
94
+ } else {
95
+ $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
96
+ }
97
+
98
+ $MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
99
+ $MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
100
+ $MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
101
+
102
+ if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
103
+ Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
104
+ Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
105
+ exit $?
106
+ }
107
+
108
+ if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
109
+ Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
110
+ }
111
+
112
+ # prepare tmp dir
113
+ $TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
114
+ $TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
115
+ $TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
116
+ trap {
117
+ if ($TMP_DOWNLOAD_DIR.Exists) {
118
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
119
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
120
+ }
121
+ }
122
+
123
+ New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
124
+
125
+ # Download and Install Apache Maven
126
+ Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
127
+ Write-Verbose "Downloading from: $distributionUrl"
128
+ Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
129
+
130
+ $webclient = New-Object System.Net.WebClient
131
+ if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
132
+ $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
133
+ }
134
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
135
+ $webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
136
+
137
+ # If specified, validate the SHA-256 sum of the Maven distribution zip file
138
+ $distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
139
+ if ($distributionSha256Sum) {
140
+ if ($USE_MVND) {
141
+ Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
142
+ }
143
+ Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
144
+ if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
145
+ Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
146
+ }
147
+ }
148
+
149
+ # unzip and move
150
+ Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
151
+
152
+ # Find the actual extracted directory name (handles snapshots where filename != directory name)
153
+ $actualDistributionDir = ""
154
+
155
+ # First try the expected directory name (for regular distributions)
156
+ $expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
157
+ $expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
158
+ if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
159
+ $actualDistributionDir = $distributionUrlNameMain
160
+ }
161
+
162
+ # If not found, search for any directory with the Maven executable (for snapshots)
163
+ if (!$actualDistributionDir) {
164
+ Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
165
+ $testPath = Join-Path $_.FullName "bin/$MVN_CMD"
166
+ if (Test-Path -Path $testPath -PathType Leaf) {
167
+ $actualDistributionDir = $_.Name
168
+ }
169
+ }
170
+ }
171
+
172
+ if (!$actualDistributionDir) {
173
+ Write-Error "Could not find Maven distribution directory in extracted archive"
174
+ }
175
+
176
+ Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
177
+ Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
178
+ try {
179
+ Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
180
+ } catch {
181
+ if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
182
+ Write-Error "fail to move MAVEN_HOME"
183
+ }
184
+ } finally {
185
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
186
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
187
+ }
188
+
189
+ Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
@@ -0,0 +1,116 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project xmlns="http://maven.apache.org/POM/4.0.0"
3
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
5
+ <modelVersion>4.0.0</modelVersion>
6
+
7
+ <groupId>io.mainframe.migration</groupId>
8
+ <artifactId>dataset-validator</artifactId>
9
+ <version>0.1.0</version>
10
+ <name>dataset-validator</name>
11
+
12
+ <properties>
13
+ <maven.compiler.release>17</maven.compiler.release>
14
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15
+ <jackson.version>2.21.3</jackson.version>
16
+ <junit.version>5.11.4</junit.version>
17
+ </properties>
18
+
19
+ <dependencies>
20
+ <dependency>
21
+ <groupId>info.picocli</groupId>
22
+ <artifactId>picocli</artifactId>
23
+ <version>4.7.7</version>
24
+ </dependency>
25
+ <dependency>
26
+ <groupId>org.apache.commons</groupId>
27
+ <artifactId>commons-csv</artifactId>
28
+ <version>1.14.1</version>
29
+ </dependency>
30
+ <dependency>
31
+ <groupId>com.fasterxml.jackson.core</groupId>
32
+ <artifactId>jackson-databind</artifactId>
33
+ <version>${jackson.version}</version>
34
+ </dependency>
35
+ <dependency>
36
+ <groupId>org.apache.parquet</groupId>
37
+ <artifactId>parquet-avro</artifactId>
38
+ <version>1.17.1</version>
39
+ </dependency>
40
+ <dependency>
41
+ <groupId>org.apache.hadoop</groupId>
42
+ <artifactId>hadoop-client-api</artifactId>
43
+ <version>3.3.6</version>
44
+ </dependency>
45
+ <dependency>
46
+ <groupId>org.apache.hadoop</groupId>
47
+ <artifactId>hadoop-client-runtime</artifactId>
48
+ <version>3.3.6</version>
49
+ <scope>runtime</scope>
50
+ </dependency>
51
+ <dependency>
52
+ <groupId>org.slf4j</groupId>
53
+ <artifactId>slf4j-nop</artifactId>
54
+ <version>1.7.36</version>
55
+ <scope>runtime</scope>
56
+ </dependency>
57
+ <dependency>
58
+ <groupId>org.junit.jupiter</groupId>
59
+ <artifactId>junit-jupiter</artifactId>
60
+ <version>${junit.version}</version>
61
+ <scope>test</scope>
62
+ </dependency>
63
+ </dependencies>
64
+
65
+ <build>
66
+ <finalName>dataset-validator</finalName>
67
+ <plugins>
68
+ <plugin>
69
+ <groupId>org.apache.maven.plugins</groupId>
70
+ <artifactId>maven-compiler-plugin</artifactId>
71
+ <version>3.14.0</version>
72
+ </plugin>
73
+ <plugin>
74
+ <groupId>org.apache.maven.plugins</groupId>
75
+ <artifactId>maven-surefire-plugin</artifactId>
76
+ <version>3.5.2</version>
77
+ <configuration>
78
+ <useModulePath>false</useModulePath>
79
+ </configuration>
80
+ </plugin>
81
+ <plugin>
82
+ <groupId>org.apache.maven.plugins</groupId>
83
+ <artifactId>maven-shade-plugin</artifactId>
84
+ <version>3.6.1</version>
85
+ <executions>
86
+ <execution>
87
+ <phase>package</phase>
88
+ <goals>
89
+ <goal>shade</goal>
90
+ </goals>
91
+ <configuration>
92
+ <createDependencyReducedPom>false</createDependencyReducedPom>
93
+ <shadedArtifactAttached>false</shadedArtifactAttached>
94
+ <filters>
95
+ <filter>
96
+ <artifact>*:*</artifact>
97
+ <excludes>
98
+ <exclude>META-INF/*.SF</exclude>
99
+ <exclude>META-INF/*.DSA</exclude>
100
+ <exclude>META-INF/*.RSA</exclude>
101
+ </excludes>
102
+ </filter>
103
+ </filters>
104
+ <transformers>
105
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
106
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
107
+ <mainClass>io.mainframe.migration.validator.ValidatorCli</mainClass>
108
+ </transformer>
109
+ </transformers>
110
+ </configuration>
111
+ </execution>
112
+ </executions>
113
+ </plugin>
114
+ </plugins>
115
+ </build>
116
+ </project>
@@ -0,0 +1,152 @@
1
+ package io.mainframe.migration.validator;
2
+
3
+ import com.fasterxml.jackson.core.JsonProcessingException;
4
+ import com.fasterxml.jackson.databind.MapperFeature;
5
+ import com.fasterxml.jackson.databind.ObjectMapper;
6
+ import org.apache.avro.Conversions;
7
+ import org.apache.avro.LogicalTypes;
8
+ import org.apache.avro.Schema;
9
+ import org.apache.avro.generic.GenericData;
10
+ import org.apache.avro.generic.GenericFixed;
11
+ import org.apache.avro.generic.GenericRecord;
12
+
13
+ import java.math.BigDecimal;
14
+ import java.nio.ByteBuffer;
15
+ import java.time.Instant;
16
+ import java.time.LocalDate;
17
+ import java.time.LocalDateTime;
18
+ import java.time.LocalTime;
19
+ import java.time.ZoneOffset;
20
+ import java.util.ArrayList;
21
+ import java.util.Base64;
22
+ import java.util.LinkedHashMap;
23
+ import java.util.List;
24
+ import java.util.Map;
25
+ import java.util.TreeMap;
26
+
27
+ final class AvroValueFormatter {
28
+ private static final ObjectMapper JSON = new ObjectMapper()
29
+ .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
30
+
31
+ private AvroValueFormatter() {
32
+ }
33
+
34
+ static String format(Object value, Schema schema) {
35
+ if (value == null) {
36
+ return null;
37
+ }
38
+ Object canonical = canonical(value, resolveUnion(value, schema));
39
+ if (canonical instanceof BigDecimal decimal) {
40
+ return decimal.toPlainString();
41
+ }
42
+ if (canonical instanceof Map<?, ?> || canonical instanceof List<?>) {
43
+ try {
44
+ return JSON.writeValueAsString(canonical);
45
+ } catch (JsonProcessingException exception) {
46
+ throw new IllegalArgumentException("Não foi possível serializar valor Parquet", exception);
47
+ }
48
+ }
49
+ return String.valueOf(canonical);
50
+ }
51
+
52
+ private static Object canonical(Object value, Schema schema) {
53
+ if (value == null) {
54
+ return null;
55
+ }
56
+
57
+ if (schema != null && schema.getLogicalType() != null) {
58
+ Object logical = logicalValue(value, schema);
59
+ if (logical != null) {
60
+ return logical;
61
+ }
62
+ }
63
+ if (value instanceof GenericRecord record) {
64
+ Map<String, Object> result = new LinkedHashMap<>();
65
+ for (Schema.Field field : record.getSchema().getFields()) {
66
+ Object child = record.get(field.name());
67
+ result.put(field.name(), canonical(child, resolveUnion(child, field.schema())));
68
+ }
69
+ return result;
70
+ }
71
+ if (value instanceof Map<?, ?> map) {
72
+ Map<String, Object> result = new TreeMap<>();
73
+ Schema valueSchema = schema != null && schema.getType() == Schema.Type.MAP
74
+ ? schema.getValueType()
75
+ : null;
76
+ map.forEach((key, child) -> result.put(
77
+ String.valueOf(key), canonical(child, resolveUnion(child, valueSchema))));
78
+ return result;
79
+ }
80
+ if (value instanceof Iterable<?> iterable) {
81
+ List<Object> result = new ArrayList<>();
82
+ Schema elementSchema = schema != null && schema.getType() == Schema.Type.ARRAY
83
+ ? schema.getElementType()
84
+ : null;
85
+ for (Object child : iterable) {
86
+ result.add(canonical(child, resolveUnion(child, elementSchema)));
87
+ }
88
+ return result;
89
+ }
90
+ if (value instanceof ByteBuffer buffer) {
91
+ ByteBuffer copy = buffer.duplicate();
92
+ byte[] bytes = new byte[copy.remaining()];
93
+ copy.get(bytes);
94
+ return Base64.getEncoder().encodeToString(bytes);
95
+ }
96
+ if (value instanceof GenericFixed fixed) {
97
+ return Base64.getEncoder().encodeToString(fixed.bytes());
98
+ }
99
+ if (value instanceof GenericData.EnumSymbol || value instanceof CharSequence) {
100
+ return value.toString();
101
+ }
102
+ return value;
103
+ }
104
+
105
+ private static Object logicalValue(Object value, Schema schema) {
106
+ String logicalType = schema.getLogicalType().getName();
107
+ if (schema.getLogicalType() instanceof LogicalTypes.Decimal decimal) {
108
+ Conversions.DecimalConversion conversion = new Conversions.DecimalConversion();
109
+ if (value instanceof ByteBuffer bytes) {
110
+ return conversion.fromBytes(bytes.duplicate(), schema, decimal);
111
+ }
112
+ if (value instanceof GenericFixed fixed) {
113
+ return conversion.fromFixed(fixed, schema, decimal);
114
+ }
115
+ if (value instanceof BigDecimal) {
116
+ return value;
117
+ }
118
+ }
119
+ if (!(value instanceof Number number)) {
120
+ return null;
121
+ }
122
+ return switch (logicalType) {
123
+ case "date" -> LocalDate.ofEpochDay(number.longValue()).toString();
124
+ case "time-millis" -> LocalTime.ofNanoOfDay(number.longValue() * 1_000_000L).toString();
125
+ case "time-micros" -> LocalTime.ofNanoOfDay(number.longValue() * 1_000L).toString();
126
+ case "timestamp-millis" -> Instant.ofEpochMilli(number.longValue()).toString();
127
+ case "timestamp-micros" -> instantFromMicros(number.longValue()).toString();
128
+ case "local-timestamp-millis" -> LocalDateTime.ofInstant(
129
+ Instant.ofEpochMilli(number.longValue()), ZoneOffset.UTC).toString();
130
+ case "local-timestamp-micros" -> LocalDateTime.ofInstant(
131
+ instantFromMicros(number.longValue()), ZoneOffset.UTC).toString();
132
+ default -> null;
133
+ };
134
+ }
135
+
136
+ private static Instant instantFromMicros(long micros) {
137
+ long seconds = Math.floorDiv(micros, 1_000_000L);
138
+ long nanos = Math.floorMod(micros, 1_000_000L) * 1_000L;
139
+ return Instant.ofEpochSecond(seconds, nanos);
140
+ }
141
+
142
+ private static Schema resolveUnion(Object value, Schema schema) {
143
+ if (schema == null || schema.getType() != Schema.Type.UNION || value == null) {
144
+ return schema;
145
+ }
146
+ try {
147
+ return schema.getTypes().get(GenericData.get().resolveUnion(schema, value));
148
+ } catch (RuntimeException ignored) {
149
+ return schema;
150
+ }
151
+ }
152
+ }
@@ -0,0 +1,111 @@
1
+ package io.mainframe.migration.validator;
2
+
3
+ import org.apache.commons.csv.CSVFormat;
4
+ import org.apache.commons.csv.CSVParser;
5
+ import org.apache.commons.csv.CSVRecord;
6
+
7
+ import java.io.IOException;
8
+ import java.io.Reader;
9
+ import java.io.UncheckedIOException;
10
+ import java.nio.file.Files;
11
+ import java.util.ArrayList;
12
+ import java.util.Iterator;
13
+ import java.util.List;
14
+
15
+ final class CsvTabularReader implements TabularReader {
16
+ private final CSVParser parser;
17
+ private final Iterator<CSVRecord> records;
18
+ private final List<String> columns;
19
+ private final boolean namedColumns;
20
+ private List<String> bufferedRow;
21
+
22
+ CsvTabularReader(InputOptions options) throws IOException {
23
+ namedColumns = options.header();
24
+ Reader reader = Files.newBufferedReader(options.path(), options.charset());
25
+ try {
26
+ CSVFormat format = CSVFormat.DEFAULT.builder()
27
+ .setDelimiter(options.delimiter())
28
+ .setIgnoreEmptyLines(false)
29
+ .get();
30
+ parser = format.parse(reader);
31
+ records = parser.iterator();
32
+ List<String> first = nextRecord();
33
+ if (first == null) {
34
+ columns = List.of();
35
+ } else if (options.header()) {
36
+ columns = List.copyOf(stripBom(first));
37
+ } else {
38
+ bufferedRow = stripBom(first);
39
+ columns = generatedColumns(first.size());
40
+ }
41
+ } catch (Throwable throwable) {
42
+ try {
43
+ reader.close();
44
+ } catch (IOException closeError) {
45
+ throwable.addSuppressed(closeError);
46
+ }
47
+ throw throwable;
48
+ }
49
+ }
50
+
51
+ @Override
52
+ public List<String> columns() {
53
+ return columns;
54
+ }
55
+
56
+ @Override
57
+ public boolean hasNamedColumns() {
58
+ return namedColumns;
59
+ }
60
+
61
+ @Override
62
+ public List<String> readRow() throws IOException {
63
+ if (bufferedRow != null) {
64
+ List<String> row = bufferedRow;
65
+ bufferedRow = null;
66
+ return row;
67
+ }
68
+ return nextRecord();
69
+ }
70
+
71
+ private List<String> nextRecord() throws IOException {
72
+ try {
73
+ if (!records.hasNext()) {
74
+ return null;
75
+ }
76
+ CSVRecord record = records.next();
77
+ List<String> values = new ArrayList<>(record.size());
78
+ record.forEach(values::add);
79
+ return values;
80
+ } catch (UncheckedIOException exception) {
81
+ throw exception.getCause();
82
+ } catch (IllegalStateException exception) {
83
+ if (exception.getCause() instanceof IOException cause) {
84
+ throw cause;
85
+ }
86
+ throw exception;
87
+ }
88
+ }
89
+
90
+ private static List<String> generatedColumns(int size) {
91
+ List<String> names = new ArrayList<>(size);
92
+ for (int index = 1; index <= size; index++) {
93
+ names.add("COLUMN_" + index);
94
+ }
95
+ return List.copyOf(names);
96
+ }
97
+
98
+ private static List<String> stripBom(List<String> values) {
99
+ if (values.isEmpty() || values.get(0).isEmpty() || values.get(0).charAt(0) != '\uFEFF') {
100
+ return values;
101
+ }
102
+ List<String> result = new ArrayList<>(values);
103
+ result.set(0, result.get(0).substring(1));
104
+ return result;
105
+ }
106
+
107
+ @Override
108
+ public void close() throws IOException {
109
+ parser.close();
110
+ }
111
+ }
@@ -0,0 +1,62 @@
1
+ package io.mainframe.migration.validator;
2
+
3
+ import java.nio.file.Path;
4
+ import java.nio.file.Files;
5
+ import java.io.IOException;
6
+ import java.util.Locale;
7
+ import java.util.stream.Stream;
8
+
9
+ public enum DataFormat {
10
+ AUTO,
11
+ CSV,
12
+ PARQUET;
13
+
14
+ public static DataFormat parse(String value) {
15
+ try {
16
+ return valueOf(value.trim().toUpperCase(Locale.ROOT));
17
+ } catch (RuntimeException exception) {
18
+ throw new IllegalArgumentException("Formato inválido: " + value + ". Use auto, csv ou parquet.");
19
+ }
20
+ }
21
+
22
+ public DataFormat resolve(Path path) {
23
+ if (this != AUTO) {
24
+ return this;
25
+ }
26
+ if (Files.isDirectory(path)) {
27
+ boolean csv = false;
28
+ boolean parquet = false;
29
+ try (Stream<Path> entries = Files.list(path)) {
30
+ for (Path entry : entries.toList()) {
31
+ String name = entry.getFileName().toString().toLowerCase(Locale.ROOT);
32
+ if (!Files.isRegularFile(entry) || !name.startsWith("part-")) {
33
+ continue;
34
+ }
35
+ csv |= name.endsWith(".csv");
36
+ parquet |= name.endsWith(".parquet") || name.endsWith(".parq");
37
+ }
38
+ } catch (IOException exception) {
39
+ throw new IllegalArgumentException("Não foi possível listar o diretório: " + path, exception);
40
+ }
41
+ if (csv && !parquet) {
42
+ return CSV;
43
+ }
44
+ if (parquet && !csv) {
45
+ return PARQUET;
46
+ }
47
+ if (csv && parquet) {
48
+ throw new IllegalArgumentException("Diretório contém partes CSV e Parquet: " + path);
49
+ }
50
+ throw new IllegalArgumentException("Nenhum part-*.csv ou part-*.parquet encontrado em: " + path);
51
+ }
52
+ String name = path.getFileName().toString().toLowerCase(Locale.ROOT);
53
+ if (name.endsWith(".csv")) {
54
+ return CSV;
55
+ }
56
+ if (name.endsWith(".parquet") || name.endsWith(".parq")) {
57
+ return PARQUET;
58
+ }
59
+ throw new IllegalArgumentException(
60
+ "Não foi possível inferir o formato de " + path + ". Informe --format ou o override por arquivo.");
61
+ }
62
+ }
@@ -0,0 +1,34 @@
1
+ package io.mainframe.migration.validator;
2
+
3
+ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
4
+
5
+ import java.util.Collections;
6
+ import java.util.LinkedHashMap;
7
+ import java.util.Map;
8
+
9
+ @JsonPropertyOrder({"line", "key", "columnIndex", "column", "expected", "actual", "reason"})
10
+ public record Difference(
11
+ long line,
12
+ Map<String, String> key,
13
+ int columnIndex,
14
+ String column,
15
+ String expected,
16
+ String actual,
17
+ String reason) {
18
+
19
+ public Difference {
20
+ key = key == null || key.isEmpty()
21
+ ? Map.of()
22
+ : Collections.unmodifiableMap(new LinkedHashMap<>(key));
23
+ }
24
+
25
+ public Difference(
26
+ long line,
27
+ int columnIndex,
28
+ String column,
29
+ String expected,
30
+ String actual,
31
+ String reason) {
32
+ this(line, Map.of(), columnIndex, column, expected, actual, reason);
33
+ }
34
+ }