Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check Python runtime version using tuple comparison instead of string parsing #208

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions shared/src/main/scala/io/kaitai/struct/format/KSVersion.scala
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ case class KSVersion(nums: List[Int]) extends Ordered[KSVersion] {
val v1 :: v2 :: v3 :: _ = nums ++ List.fill(3 - nums.size)(0)
"%d.%03d_%03d".format(v1, v2, v3)
}

/**
* Dumps a version as a tuple of ints in Python syntax,
* that is 1.2.3 becomes "(1, 2, 3)".
* There are no limitations on the number of version components or the range
* of values for each component.
* @return version as a tuple of ints in Python syntax
*/
def toPythonTuple: String = nums.mkString("(", ", ", ")")
}

object KSVersion {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ class PythonCompiler(typeProvider: ClassTypeProvider, config: RuntimeConfig)
outHeader.puts(s"# $headerComment")
outHeader.puts

importList.add("from pkg_resources import parse_version")
importList.add("import kaitaistruct")
importList.add(s"from kaitaistruct import $kstructName, $kstreamName, BytesIO")

Expand All @@ -52,9 +51,16 @@ class PythonCompiler(typeProvider: ClassTypeProvider, config: RuntimeConfig)

// API compatibility check
out.puts(
"if parse_version(kaitaistruct.__version__) < parse_version('" +
KSVersion.minimalRuntime +
"'):"
// The API_VERSION tuple attribute was introduced in version 0.9 of the
// Python runtime. Runtime version 0.8 and older only have a __version__
// attribute that stores the version in string form.
// We don't need to include any complex handling for runtimes that don't
// have the API_VERSION attribute - we know that such a runtime must have
// version 0.8 or older, which means that it is incompatible with code
// generated by newer compiler versions.
"if getattr(kaitaistruct, 'API_VERSION', (0, 8)) < " +
KSVersion.minimalRuntime.toPythonTuple +
":"
)
out.inc
out.puts(
Expand Down