Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
KOLANICH committed May 6, 2022
0 parents commit 00e815c
Show file tree
Hide file tree
Showing 12 changed files with 405 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
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! Just do what you feel is right and say what you feel is right using the language you feel is right. If you feel that it is right to [make an own fork with a CoCs and SJWs](https://en.wikipedia.org/wiki/Bender_Rodriguez), just do that. We here are doing the work, not accusing each other in violating 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
10 changes: 10 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[JAbs.py] [![Unlicensed work](https://raw.githubusercontent.com/unlicense/unlicense.org/master/static/favicon.png)](https://unlicense.org/)
===========
![GitLab Build Status](https://gitlab.com/KOLANICH/ScalaJVMInitializer.py/badges/master/pipeline.svg)
![GitLab Coverage](https://gitlab.com/KOLANICH/ScalaJVMInitializer.py/badges/master/coverage.svg)
[![Coveralls Coverage](https://img.shields.io/coveralls/KOLANICH/ScalaJVMInitializer.py.svg)](https://coveralls.io/r/KOLANICH/ScalaJVMInitializer.py)
[![Libraries.io Status](https://img.shields.io/librariesio/github/KOLANICH/ScalaJVMInitializer.py.svg)](https://libraries.io/github/KOLANICH/ScalaJVMInitializer.py)

A library complementing JAbs for doing some useful things with Scala.


266 changes: 266 additions & 0 deletions ScalaJVMInitializer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
import typing
import re
from JAbs import SelectedJVMInitializer, ClassPathT, ClassesImportSpecT
from collections import OrderedDict, defaultdict
import warnings

import sys

decodeScalaSignature = None

class _ScalaMutableWrapper:
__slots__ = ("_ctor", "_data")

def __init__(self, ji, o, template=None, ctor=None, data=None):
if ctor is None:
if isinstance(o, __class__):
ctor = o._ctor
else:
ctor = o.__class__

self.__class__._ctor.__set__(self, ctor)

if data is None:
if template:
data = type(template)(template)
else:
data = ji.getSomeKindOfImmutableObjectTemplate(ctor)

for p in data.keys():
v = getattr(o, p)()
data[p] = ji.scalaWrapSomeKindOfImmutableObject(v)

self.__class__._data.__set__(self, data)

def _revertIter_(self):
for v in self._revertIter():
if isinstance(v, __class__):
v = v._revert()
yield v

def _revert(self):
return self._ctor(list(self._revertIter()))

def __repr__(self):
return self.__class__.__name__ + "<" + self._ctor.__name__ + ">(" + repr(self._data) + ")"

def merge(self, other, mergingFunction = None):
if mergingFunction is None:
mergingFunction = _defaultMergingFunction

for k in self._data.keys():
v = self._data[k]
ov = other._data[k]
if isinstance(v, _ScalaMutableWrapper):
v.merge(ov, mergingFunction)
else:
if mergingFunction(self._ctor, self._data, k, v, ov):
pass
else:
if ov is not None:
self._data[k] = ov


def _defaultMergingFunction(objScalaClass, dataDict, k, v, ov) -> bool:
return False


class ScalaMutableWrapper(_ScalaMutableWrapper):
__slots__ = ()

def _revertIter(self):
return self._data.values()

def _revert(self):
return self._ctor(*tuple(self._revertIter_()))

def __getattr__(self, k):
return self._data[k]

def __setattr__(self, k, v):
self._data[k] = v

def __dir__(self):
return self._data.keys()

#def merge(self, other, mergingFunction = None):
# raise NotImplementedError


class ScalaCollectionMutableWrapper(_ScalaMutableWrapper):
__slots__ = ()

def __init__(self, ji, o, template=None, ctor=None, data=None):
super().__init__(ji, o, ctor=ji.scalaSeq, data=[ji.scalaWrapSomeKindOfImmutableObject(el) for el in ji.JavaConverters.asJavaCollection(o)])

def __getitem__(self, k):
return self._data[k]

def __setitem__(self, k, v):
self._data[k] = v

def __getattr__(self, k):
return getattr(self._data, k)

def __setattr__(self, k, v):
setattr(self._data, k, v)

def _revertIter(self):
return self._data

def _revert(self):
return self._ctor(list(self._revertIter_()))

def merge(self, other, mergingFunction = None):
self.extend(other)



class ScalaJVMInitializer:
__slots__ = ("ji", "scalaVersion")
def __init__(self, classPathz: ClassPathT, classes2import: ClassesImportSpecT) -> None:
self.__class__.ji.__set__(self, SelectedJVMInitializer(classPathz, classes2import))
self.loadScala()

def __getattr__(self, k):
return getattr(self.ji, k)

def __setattr__(self, k, v):
setattr(self.ji, k, v)

def loadScala(self) -> None:
self.ji.ImmutArraySeq = None
self.loadClasses((
("scala.util.Properties", "ScalaProps"),
"scala.concurrent.Await",
"scala.collection.Iterable",
"scala.collection.mutable.Seq",
"scala.collection.mutable.ListBuffer",
("scala.collection.mutable.ArraySeq", "MutArraySeq"),
("scala.collection.immutable.HashMap", "ImmutHashMap"),
("scala.collection.mutable.HashMap", "MutHashMap"),
"scala.collection.JavaConverters",
"scala.Some",
("scala.None", "none"),
("scala.Predef$", "scalaPredef"),
("scala.collection.Seq$", "scalaCollSeq"),
"java.util.Arrays"
))

self.scalaVersion = tuple(int(el) for el in str(self.ScalaProps.versionNumberString()).split("."))

if self.scalaVersion > (2, 13):
self.loadClasses(
("scala.collection.immmutable.ArraySeq", "ImmutArraySeq")
)
else:
warnings.warn("Using mutable ArraySeq instead of immutable one, since immutable is not present in this version of Scala " + repr(self.scalaVersion))

self.scalaPredef = getattr(self.scalaPredef, "MODULE$")
self.scalaCollSeq = getattr(self.scalaCollSeq, "MODULE$")

def getScalaSignatureAnnotation(self, scalaClass) -> typing.Any:
return self.__class__.getScalaSignatureAnnotationFromReflectedClass(self.reflectClass(scalaClass))

@classmethod
def getScalaSignatureAnnotationFromReflectedClass(cls, classRefl) -> typing.Any:
for annot in classRefl.annotations:
if annot.annotationType().name == "scala.reflect.ScalaSignature":
return annot
return None

def _ensureScalaSignatureBytesDecoderLazyLoaded(self):
global decodeScalaSignature
if decodeScalaSignature is None:
try:
from .scalaTransformArray import decode as decodeScalaSignaturePython

def decodeScalaSignature(s: bytes) -> bytes:
s = bytearray(bytes(s))
l = decodeScalaSignaturePython(s)
return bytes(s[:l])


except ImportError:
ByteCodecs = ji.loadClass("scala.reflect.internal.pickling.ByteCodecs")

def decodeScalaSignature(s: bytes) -> bytes:
l = ByteCodecs.decode(s)
s = bytes(s)
return s[:l]

def getScalaSignatureAnnotationBytes(self) -> bytes:
self._ensureScalaSignatureBytesDecoderLazyLoaded()
scalaSignAnnot = self.getScalaSignatureAnnotation(classRefl)
if scalaSignAnnot:
s = scalaSignAnnot.bytes().getBytes("UTF-8")
return decodeScalaSignature(s)

def scalaMap(self, m, mutable=False):
if mutable:
ctor = self.MutHashMap
else:
ctor = self.ImmutHashMap

seq = ctor(len(m))
for k, v in m.items():
seq.update(k, v)
return seq

def scalaArrSeq(self, it, mutable=True):
it = list(it)
if mutable or self.ImmutArraySeq is None:
ctor = self.MutArraySeq
else:
ctor = self.ImmutArraySeq

seq = ctor(len(it))
for k, v in enumerate(it):
seq.update(k, v)
return seq

def scalaSet(self, it, mutable=True):
return self.scalaArrSeq(it, mutable=mutable).toSet()

def scalaSeq(self, it):
coll = self.scalaCollSeq.apply(self.scalaPredef.wrapRefArray(list(it)))
coll = coll.to(self.scalaCollSeq.canBuildFrom())
return coll
#return self.scalaCollSeq.apply(self.scalaPredef.wrapRefArray(list(it)))
#return self.scalaPredef.wrapRefArray(list(it))
#return self.JavaConverters.collectionAsScalaIterable(self.Arrays.asList(list(it))).toSeq()

scalaTupleRx = re.compile("^_(\\d+)$")

@classmethod
def scalaDetuple(cls, t):
res = [None] * t.productArity()
for n in dir(t):
m = cls.scalaTupleRx.match(n)
if m is not None:
res[int(m.group(1)) - 1] = getattr(t, n)()
return tuple(res)

@classmethod
def scalaDeOption(cls, o):
if o.isEmpty():
return None

return o.value()

@staticmethod
def getSomeKindOfImmutableObjectTemplate(cls):
c = max(cls.class_.getConstructors(), key=lambda ct: len(ct.getParameters()))
return OrderedDict([(str(p.getName()), None) for p in c.getParameters()])

def scalaWrapSomeKindOfImmutableObject(self, o, template=None):
if not isinstance(o, (str, self.String, int, float, bool, type(None), ScalaMutableWrapper, ScalaCollectionMutableWrapper)):
#print(o.__class__, isinstance(o, self.Iterable), o.__class__.__mro__)
if isinstance(o, self.Iterable):
return ScalaCollectionMutableWrapper(self, o)
else:
if hasattr(o, "copy$default$1"):
o = ScalaMutableWrapper(self, o)
return o
else:
return o
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/>
Loading

0 comments on commit 00e815c

Please sign in to comment.