Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
KOLANICH committed Oct 13, 2023
0 parents commit bd36de2
Show file tree
Hide file tree
Showing 18 changed files with 318 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
charset = utf-8
indent_style = tab
indent_size = 4
insert_final_newline = true
end_of_line = lf

[*.{yml,yaml}]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .github/.templateMarker
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
KOLANICH/python_project_boilerplate.py
8 changes: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
allow:
- dependency-type: "all"
15 changes: 15 additions & 0 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: CI
on:
push:
branches: [master]
pull_request:
branches: [master]

jobs:
build:
runs-on: ubuntu-22.04
steps:
- name: typical python workflow
uses: KOLANICH-GHActions/typical-python-workflow@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
__pycache__
*.pyc
*.pyo
*.egg-info
build
dist
.eggs
/monkeytype.sqlite3
/*.srctrldb
/*.srctrlbm
/*.srctrlprj
14 changes: 14 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#image: pypy:latest
image: registry.gitlab.com/kolanich-subgroups/docker-images/fixed_python:latest

variables:
DOCKER_DRIVER: overlay2
SAST_ANALYZER_IMAGE_TAG: latest
SAST_DISABLE_DIND: "true"
SAST_CONFIDENCE_LEVEL: 5
CODECLIMATE_VERSION: latest

include:
- template: SAST.gitlab-ci.yml
- template: Code-Quality.gitlab-ci.yml
- template: License-Management.gitlab-ci.yml
4 changes: 4 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[submodule "org.mdkt.compiler"]
path = org.mdkt.compiler
url = https://codeberg.org/UniGrammar/InMemoryJavaCompiler
branch = private
1 change: 1 addition & 0 deletions Code_Of_Conduct.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
No codes of conduct!
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include UNLICENSE
include *.md
include tests
include .editorconfig
8 changes: 8 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[javaMdktCompiler.py] [![Unlicensed work](https://raw.githubusercontent.com/unlicense/unlicense.org/master/static/favicon.png)](https://unlicense.org/)
=====================
~~![GitLab Build Status](https://gitlab.com/KOLANICH/javaMdktCompiler.py/badges/master/pipeline.svg)~~
~~![GitLab Coverage](https://gitlab.com/KOLANICH/javaMdktCompiler.py/badges/master/coverage.svg)~~
[![Libraries.io Status](https://img.shields.io/librariesio/github/KOLANICH/javaMdktCompiler.py.svg)](https://libraries.io/github/KOLANICH/javaMdktCompiler.py)
[![Code style: antiflash](https://img.shields.io/badge/code%20style-antiflash-FFF.svg)](https://codeberg.org/KOLANICH-tools/antiflash.py)

Just python bindings for [`org.mdkt.compiler`](https://github.com/trung/InMemoryJavaCompiler) Java lib allowing to compile and load Java sources in runtime.
24 changes: 24 additions & 0 deletions UNLICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org/>
53 changes: 53 additions & 0 deletions javaMdktCompiler/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
__all__ = ("javaCompile",)
import typing
from pathlib import Path

from JAbs import SelectedJVMInitializer

mdktNS = "org.mdkt.compiler"

neededMdktCompilerClasses = [
mdktNS + ".InMemoryJavaCompiler",
mdktNS + ".SourceCode",
mdktNS + ".CompilationException",
]

defaultBaseDir = Path(".")


def getMDKTCompilerPath(baseDir=None):
if baseDir is None:
baseDir = defaultBaseDir

candidates = sorted(defaultBaseDir.glob("InMemoryJavaCompiler-*.jar"))
if not candidates:
candidates = sorted(defaultBaseDir.glob("org.mdkt.compiler-*.jar"))

return candidates[-1]


MDKTCompilerClassPath = getMDKTCompilerPath()
ji = SelectedJVMInitializer([MDKTCompilerClassPath], neededMdktCompilerClasses)
CompilationException = ji.CompilationException

def javaCompile(filesAbstracted: typing.Iterable[typing.Union[typing.Tuple[str, str], Path]], *args, compiler=None, ignoreWarnings:bool=False):
if compiler is None:
compiler = ji.InMemoryJavaCompiler.newInstance()
if ignoreWarnings:
compiler.ignoreWarnings()

compiler.useOptions(args)

for it in filesAbstracted:
if isinstance(it, Path):
fileStem = it.stem
fileText = it.read_text(encoding="utf-8")
else:
fileStem, fileText = it
compiler.addSource(fileStem, fileText)

compiledN = compiler.compileAll()
compiled = {}
for k in compiledN:
compiled[str(k)] = ji.reflClass2Class(compiledN[k])
return compiled
Empty file added javaMdktCompiler/py.typed
Empty file.
1 change: 1 addition & 0 deletions org.mdkt.compiler
Submodule org.mdkt.compiler added at cbe63a
41 changes: 41 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
[build-system]
requires = ["setuptools>=61.2.0", "wheel", "setuptools_scm[toml]>=3.4.3"]
build-backend = "setuptools.build_meta"

[project]
name = "javaMdktCompiler"
authors = [{name = "KOLANICH"}]
description = "Just python bindings for `org.mdkt.compiler` Java lib allowing to compile and load Java sources in runtime."
keywords = ["compile", "java", "JVM"]
license = {text = "Unlicense"}
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: Public Domain",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
]
requires-python = ">=3.4"
dependencies = [
"JAbs", # @ git+https://codeberg.org/KOLANICH-libs/JAbs.py
]
dynamic = ["version"]

[project.readme]
file = "ReadMe.md"
content-type = "text/markdown"

[project.urls]
Homepage = "https://codeberg.org/UniGrammar/javaMdktCompiler.py"

[tool.setuptools]
zip-safe = true
include-package-data = false

[tool.setuptools.packages]
find = {namespaces = false}

[tool.setuptools_scm]
8 changes: 8 additions & 0 deletions tests/Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

class Test {
public Test() {}

public String test() {
return "test";
}
}
80 changes: 80 additions & 0 deletions tests/originalTests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
import sys
import unittest
from collections import OrderedDict
from pathlib import Path

dict = OrderedDict

thisDir = Path(__file__).absolute().parent
parentDir = thisDir.parent

sys.path.insert(0, str(parentDir))

from javaMdktCompiler import javaCompile, mdktNS, CompilationException, ji

testsSourcesDir = parentDir / mdktNS / "src" / "test" / "resources"

__license__ = "Apache-2.0"
__copyright__ = "Copyright 2015 trung"


class OriginalTests(unittest.TestCase):
"""
Original tests ported from Java to Python 3
See org.mdkt.compiler/src/test/java/org/mdkt/compiler/InMemoryJavaCompilerTest.java For the original
"""

def getResourceAsString(self, subpath):
return (testsSourcesDir / subpath).read_text()

def test_compile_WhenTypical(self):
helloClass = javaCompile([("org.mdkt.HelloClass", self.getResourceAsString("compile_WhenTypical/HelloClass.java"))])["org.mdkt.HelloClass"]
self.assertIsNotNone(helloClass)
self.assertEqual(1, int(ji.reflectClass(helloClass).getDeclaredMethods().length))

def test_compileAll_WhenTypical(self):
compiled = javaCompile([
("A", self.getResourceAsString("compileAll_WhenTypical/A.java")),
("B", self.getResourceAsString("compileAll_WhenTypical/B.java"))
])

self.assertIsNotNone(compiled.get("A"))
self.assertIsNotNone(compiled.get("B"))

aClass = compiled.get("A")
a = aClass()
self.assertEqual("B!", str(a.b().toString()))

def test_compile_WhenSourceContainsInnerClasses(self):
helloClass = javaCompile([("org.mdkt.HelloClass", self.getResourceAsString("compile_WhenSourceContainsInnerClasses/HelloClass.java"))])["org.mdkt.HelloClass"]
self.assertIsNotNone(helloClass)
self.assertEqual(1, int(ji.reflectClass(helloClass).getDeclaredMethods().length))

def test_compile_whenError(self):
with self.assertRaisesRegex(CompilationException, "Unable to compile the source"):
javaCompile([("org.mdkt.HelloClass", self.getResourceAsString("compile_whenError/HelloClass.java"))])["org.mdkt.HelloClass"]

def test_compile_WhenFailOnWarnings(self):
with self.assertRaises(CompilationException):
javaCompile([("org.mdkt.HelloClass", self.getResourceAsString("compile_WhenFailOnWarnings/HelloClass.java"))])["org.mdkt.HelloClass"]

def test_compile_WhenIgnoreWarnings(self):
helloClass = javaCompile(
[("org.mdkt.HelloClass", self.getResourceAsString("compile_WhenIgnoreWarnings/HelloClass.java"))],
ignoreWarnings=True
)["org.mdkt.HelloClass"]
res = helloClass().hello()
self.assertEqual(0, res.size())

def test_compile_WhenWarningsAndErrors(self):
with self.assertRaises(CompilationException):
try:
javaCompile([("org.mdkt.HelloClass", self.getResourceAsString("compile_WhenWarningsAndErrors/HelloClass.java"))])["org.mdkt.HelloClass"]
except Exception as e:
print("Exception caught: {}", e)
raise


if __name__ == "__main__":
unittest.main()
33 changes: 33 additions & 0 deletions tests/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
import sys
import unittest
from collections import OrderedDict
from pathlib import Path

thisDir = Path(__file__).absolute().parent
parentDir = thisDir.parent

sys.path.insert(0, str(parentDir))

dict = OrderedDict

from javaMdktCompiler import javaCompile, mdktNS

compilerSources = list((parentDir / mdktNS / "src" / "main" / "java" / "/".join(mdktNS.split("."))).glob("*.java"))


class Tests(unittest.TestCase):
def testCompileTest(self):
res = javaCompile([thisDir / "Test.java"])
t = res["Test"]()
tr = str(t.test())
self.assertEqual(tr, "test")

@unittest.skip
def testCompile(self):
res = javaCompile(compilerSources)
print(res)


if __name__ == "__main__":
unittest.main()

0 comments on commit bd36de2

Please sign in to comment.