Skip to content

Commit

Permalink
python lang support
Browse files Browse the repository at this point in the history
  • Loading branch information
ismailbayram committed Jul 30, 2023
1 parent bccef52 commit 8362a7a
Show file tree
Hide file tree
Showing 62 changed files with 2,315 additions and 22 deletions.
3 changes: 2 additions & 1 deletion .bigpicture.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"port": 44525,
"ignore": [
"web"
"web",
"internal/browser/pyproject"
],
"validators": [
{
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
.idea
node_modules
node_modules
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ like in the `.github/workflows/codequality.yml`.

# Supported Languages
- Go
- Python
- Java (Under Development)
- Python (Under Development)
- C# (Under Development)
- JS (Under Development)

Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/kr/pretty v0.1.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/sbinet/go-python v0.1.0 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/sys v0.10.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sbinet/go-python v0.1.0 h1:WlS8dGoxKMt9/c54U4XQuVhQt79p0uJUdzopuDR4QaI=
github.com/sbinet/go-python v0.1.0/go.mod h1:Pq31TCdgxj39xSYY/VAfsWWrFphYSmx3jmPHtotzQNY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
Expand Down
8 changes: 4 additions & 4 deletions internal/browser/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

const (
LangGo = "go"
LangJS = "js"
LangPy = "py"
)

Expand All @@ -21,10 +20,11 @@ func NewBrowser(lang string, tree *graph.Tree, ignoredPaths []string) Browser {
ignoredPaths: ignoredPaths,
tree: tree,
}
case LangJS:
return nil
case LangPy:
return nil
return &PythonBrowser{
ignoredPaths: ignoredPaths,
tree: tree,
}
}
return nil
}
5 changes: 1 addition & 4 deletions internal/browser/browser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@ func TestNewBrowser(t *testing.T) {
browser := NewBrowser(LangGo, nil, nil)
assert.NotNil(t, browser)

browser = NewBrowser(LangJS, nil, nil)
assert.Nil(t, browser)

browser = NewBrowser(LangPy, nil, nil)
assert.Nil(t, browser)
assert.NotNil(t, browser)
}
18 changes: 13 additions & 5 deletions internal/browser/go.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"go/parser"
"go/token"
"os"
"regexp"
"strings"
)

Expand All @@ -32,13 +33,20 @@ func (b *GoBrowser) getModuleName() string {
}

func (b *GoBrowser) isIgnored(entryPath string) bool {
entryPath = entryPath[2:]
for _, path := range b.ignoredPaths {
if strings.HasPrefix(entryPath, path) {
return true
isIgnored := false
for _, ignore := range b.ignoredPaths {
regxp := ignore
if strings.HasPrefix(ignore, "*") {
regxp = fmt.Sprintf("^%s$", ignore)
}
re := regexp.MustCompile(regxp)
if re.MatchString(entryPath) {
isIgnored = true
break
}
}
return false

return isIgnored
}

func (b *GoBrowser) browse(parentPath string, parentNode *graph.Node) {
Expand Down
11 changes: 6 additions & 5 deletions internal/browser/go_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"testing"
)

func TestGetModuleName(t *testing.T) {
func TestGoBrowser_GetModuleName(t *testing.T) {
os.Chdir("../..")

browser := &GoBrowser{
Expand All @@ -19,7 +19,7 @@ func TestGetModuleName(t *testing.T) {
assert.Equal(t, "github.com/ismailbayram/bigpicture", moduleName)
}

func TestIsIgnored(t *testing.T) {
func TestGoBrowser_IsIgnored(t *testing.T) {
browser := &GoBrowser{
ignoredPaths: []string{"internal/browser"},
tree: nil,
Expand All @@ -29,7 +29,7 @@ func TestIsIgnored(t *testing.T) {
assert.False(t, browser.isIgnored("./internal/other/other.go"))
}

func TestParseFile(t *testing.T) {
func TestGoBrowser_ParseFile(t *testing.T) {
browser := &GoBrowser{
ignoredPaths: []string{},
tree: nil,
Expand Down Expand Up @@ -57,8 +57,9 @@ func TestGoBrowser_Browse(t *testing.T) {
}

func TestGoBrowser_browse(t *testing.T) {
browser := NewBrowser(LangGo, graph.NewTree("root"), []string{}).(*GoBrowser)
browser := NewBrowser(LangGo, graph.NewTree("root"), []string{"internal/browser/pyproject"}).(*GoBrowser)

browser.browse("./internal/browser", browser.tree.Root)
assert.Equal(t, 5, len(browser.tree.Nodes))

assert.Equal(t, 7, len(browser.tree.Nodes))
}
5 changes: 5 additions & 0 deletions internal/browser/pyproject/.bigpicture.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"ignore": [
"migrations/*"
]
}
Empty file.
16 changes: 16 additions & 0 deletions internal/browser/pyproject/base/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.db import models


class StarterModel(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True, db_index=True)

class Meta:
abstract = True
ordering = ['-created_date']

def save(self, *args, **kwargs):
update_fields = kwargs.get('update_fields', None)
if update_fields is not None:
update_fields.append('modified_date')
super(StarterModel, self).save(*args, **kwargs)
41 changes: 41 additions & 0 deletions internal/browser/pyproject/base/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import logging
from django.utils.timezone import datetime
from django.conf import settings
from django.core.cache import cache
from django.utils.encoding import force_str

from washer_project.celery import app

logger = logging.getLogger(__name__)


class LockTask(app.Task):
"""this abstract class ensures the same tasks run only once at a time"""
abstract = True
TTL = getattr(settings, 'DEFAULT_TASK_LOCK_TTL', 60 * 15)

def __init__(self, *args, **kwargs):
super(LockTask, self).__init__(*args, **kwargs)

def generate_lock_cache_key(self, *args, **kwargs):
args_key = [force_str(arg) for arg in args]
kwargs_key = ['{}_{}'.format(k, force_str(v)) for k, v in
sorted(kwargs.items())]
return '_'.join([self.name] + args_key + kwargs_key)

def __call__(self, *args, **kwargs):
"""check task"""
lock_cache_key = (self.request.headers or {}).pop('cache_key', None)
if not lock_cache_key:
lock_cache_key = self.generate_lock_cache_key(*args, **kwargs)
lock_time = datetime.now().isoformat()
lock_acquired = cache.set(lock_cache_key, lock_time, nx=True,
timeout=self.TTL)

if lock_acquired:
try:
return self.run(*args, **kwargs)
finally:
cache.delete(lock_cache_key)
else:
logger.info('Task %s is already running..' % self.name)
65 changes: 65 additions & 0 deletions internal/browser/pyproject/base/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from model_mommy import mommy

from users.enums import GroupType
from users.service import UserService


class BaseTestViewMixin:
def init_users(self):
service = UserService()
self.superuser = mommy.make('users.User', is_staff=True)
self.superuser_token = service._create_token(self.superuser)

data = {
"first_name": "Customer 1",
"last_name": "CusLast",
"phone_number": "555111",
"group_type": GroupType.customer
}
self.customer, self.customer_token = service.get_or_create_user(**data)
self.customer_profile = self.customer.customer_profile

data = {
"first_name": "Customer 2",
"last_name": "CusLast 2",
"phone_number": "5551112",
"group_type": GroupType.customer
}
self.customer2, self.customer2_token = service.get_or_create_user(**data)
self.customer2_profile = self.customer2.customer_profile

data = {
"first_name": "Worker 1",
"last_name": "WorkLast",
"phone_number": "555222",
"group_type": GroupType.worker
}
self.worker, self.worker_token = service.get_or_create_user(**data)
self.worker_profile = self.worker.worker_profile

data = {
"first_name": "Worker 2",
"last_name": "WorkLast",
"phone_number": "555223",
"group_type": GroupType.worker
}
self.worker2, self.worker2_token = service.get_or_create_user(**data)
self.worker2_profile = self.worker2.worker_profile

data = {
"first_name": "Washer 1",
"last_name": "WashLast",
"phone_number": "555333",
"group_type": GroupType.washer
}
self.washer, self.washer_token = service.get_or_create_user(**data)
self.washer_profile = self.washer.washer_profile

data = {
"first_name": "Washer 2",
"last_name": "WashLast",
"phone_number": "555334",
"group_type": GroupType.washer
}
self.washer2, self.washer2_token = service.get_or_create_user(**data)
self.washer2_profile = self.washer2.washer_profile
69 changes: 69 additions & 0 deletions internal/browser/pyproject/base/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from io import BytesIO
from uuid import uuid4

from PIL import Image

from django.core.files.base import ContentFile
from django.conf import settings
from django.views.decorators.cache import cache_page as dj_cache


def ordereddict_to_dict(value):
for k, v in value.items():
if isinstance(v, dict):
value[k] = ordereddict_to_dict(v)
return dict(value)

def thumbnail_file_name_by_orginal_name(orginal_name, thumb_name):
"""
:param orginal_name: String
:param thumb_name: String
:return: String
ex:
("kadir.jpg", "20x30") # kadir_20x30.jpg
"""
pure_name = "".join(orginal_name.split(".")[0:-1])
ext_name = orginal_name.split(".")[-1]
return "{0}_{1}.{2}".format(pure_name, thumb_name, ext_name)


def generate_file_name(instance, *args, **kwargs):
ext = instance.image.name.split(".")[-1]
return "{0}.{1}".format(uuid4().hex, ext)


def compress_image(image, do_square=False):
"""
:param image: ContentFile
:param do_square: boolean
:return: ContentFile
This function compress the image to jpeg and return new image
if do_square==True then image will resize the square version
"""
not_saved_pure_name = "".join(image.name.split('.')[0:-1])
pil_image = Image.open(image)
pil_image.convert('RGB')

if do_square:
edge_size = min(pil_image.size)
pil_image = pil_image.crop((0, 0, edge_size, edge_size))

f = BytesIO()

fill_color = '#ffffff'
if pil_image.mode in ('RGBA', 'LA'):
background = Image.new(pil_image.mode[:-1], pil_image.size, fill_color)
background.paste(pil_image, pil_image.split()[-1])
pil_image = background

pil_image.save(f, "JPEG", quality=90)
image = ContentFile(f.getvalue())
image.name = "{0}.{1}".format(not_saved_pure_name, "jpeg")


return image


def cache_page(timeout=settings.CACHE_TTL):
return dj_cache(timeout)
Empty file.
5 changes: 5 additions & 0 deletions internal/browser/pyproject/baskets/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class BasketsConfig(AppConfig):
name = 'baskets'
7 changes: 7 additions & 0 deletions internal/browser/pyproject/baskets/codes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.utils.translation import ugettext_lazy as _

baskets_100_0 = {"code": "baskets_100_0",
"message": _("You can get only 1 primary service. If you wish, delete a service that is primary.")}
baskets_100_1 = {"code": "baskets_100_1", "message": _("Services that in the basket are not available.")}
baskets_100_2 = {"code": "baskets_100_2", "message": _("Your basket is empty.")}
baskets_100_3 = {"code": "baskets_100_3", "message": _("Your basket amount can not be less than 0.")}
17 changes: 17 additions & 0 deletions internal/browser/pyproject/baskets/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from enumfields import Enum


class BasketStatus(Enum):
active = 'active'
completed = 'completed'


class PromotionType(Enum):
one_free_in_nine = 'one_free_in_nine'

@property
def get_strategy(self):
from baskets.strategies import OneFreeInNineStrategy

if self.value == 'one_free_in_nine':
return OneFreeInNineStrategy
Loading

0 comments on commit 8362a7a

Please sign in to comment.