Skip to content

Commit

Permalink
Merge pull request #13 from Nekotoxin/migrate_to_github_action
Browse files Browse the repository at this point in the history
fix: Migrate to GitHub action
  • Loading branch information
hsluoyz authored Jul 30, 2022
2 parents e53d75b + 7d3125f commit 715f3c4
Show file tree
Hide file tree
Showing 18 changed files with 248 additions and 132 deletions.
3 changes: 3 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[run]
include = casbin_adapter/*
omit = *migrations*, *tests*
2 changes: 2 additions & 0 deletions .github/semantic.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Always validate the PR title AND all the commits
titleAndCommits: true
104 changes: 104 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
name: build
on:
push:
branches: [master]
pull_request:
branches: [master]

jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
python-version: ['3.7', '3.8', '3.9', '3.10']
os: [ubuntu-18.04, macOS-latest, windows-latest]

steps:
- name: Checkout
uses: actions/checkout@v2

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: |
pip install -r requirements_dev.txt
pip install coveralls
pip install pytest
- name: Run tests
run: coverage run -m django test --settings=tests.settings

- name: Upload coverage data to coveralls.io
run: coveralls --service=github
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
COVERALLS_FLAG_NAME: ${{ matrix.os }} - ${{ matrix.python-version }}
COVERALLS_PARALLEL: true

lint:
name: Run Linters
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0

- name: Super-Linter
uses: github/super-linter@v4.9.2
env:
VALIDATE_ALL_CODEBASE: false
VALIDATE_PYTHON_BLACK: true
DEFAULT_BRANCH: master
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LINTER_RULES_PATH: /
PYTHON_BLACK_CONFIG_FILE: pyproject.toml

coveralls:
name: Indicate completion to coveralls.io
needs: test
runs-on: ubuntu-latest
container: python:3-slim
steps:
- name: Finished
run: |
pip3 install --upgrade coveralls
coveralls --finish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

release:
name: Release
runs-on: ubuntu-latest
needs: [ test, coveralls ]
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0

- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'

- name: Setup
run: npm install -g semantic-release @semantic-release/github @semantic-release/changelog @semantic-release/commit-analyzer @semantic-release/git @semantic-release/release-notes-generator semantic-release-pypi

- name: Set up python
uses: actions/setup-python@v2
with:
python-version: 3.8

- name: Install setuptools
run: python -m pip install --upgrade setuptools wheel twine

- name: Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
run: npx semantic-release
23 changes: 23 additions & 0 deletions .releaserc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"branches": "master",
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"semantic-release-pypi",
"@semantic-release/github",
[
"@semantic-release/changelog",
{
"changelogFile": "CHANGELOG.md",
"changelogTitle": "# Semantic Versioning Changelog"
}
],
[
"@semantic-release/git",
{
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}",
"assets": ["CHANGELOG.md", "setup.py", "setup.cfg"]
}
]
]
}
23 changes: 0 additions & 23 deletions .travis.yml

This file was deleted.

10 changes: 5 additions & 5 deletions casbin_adapter/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,22 @@ def add_policy(self, sec, ptype, rule):

def remove_policy(self, sec, ptype, rule):
"""removes a policy rule from the storage."""
query_params = {'ptype': ptype}
query_params = {"ptype": ptype}
for i, v in enumerate(rule):
query_params['v{}'.format(i)] = v
query_params["v{}".format(i)] = v
rows_deleted, _ = CasbinRule.objects.filter(**query_params).delete()
return True if rows_deleted > 0 else False

def remove_filtered_policy(self, sec, ptype, field_index, *field_values):
"""removes policy rules that match the filter from the storage.
This is part of the Auto-Save feature.
"""
query_params = {'ptype': ptype}
if not(0 <= field_index <= 5):
query_params = {"ptype": ptype}
if not (0 <= field_index <= 5):
return False
if not (1 <= field_index + len(field_values) <= 6):
return False
for i, v in enumerate(field_values):
query_params['v{}'.format(i + field_index)] = v
query_params["v{}".format(i + field_index)] = v
rows_deleted, _ = CasbinRule.objects.filter(**query_params).delete()
return True if rows_deleted > 0 else False
4 changes: 2 additions & 2 deletions casbin_adapter/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@


class CasbinAdapterConfig(AppConfig):
name = 'casbin_adapter'
name = "casbin_adapter"

def ready(self):
from .enforcer import initialize_enforcer
initialize_enforcer()

initialize_enforcer()
36 changes: 18 additions & 18 deletions casbin_adapter/enforcer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,48 @@
logger = logging.getLogger(__name__)



class ProxyEnforcer(Enforcer):
_initialized = False

def __init__(self, *args, **kwargs):
if self._initialized:
super().__init__(*args, **kwargs)
else:
logger.info('Deferring casbin enforcer initialisation until django is ready')
logger.info("Deferring casbin enforcer initialisation until django is ready")

def _load(self):
if self._initialized == False:
logger.info('Performing deferred casbin enforcer initialisation')
logger.info("Performing deferred casbin enforcer initialisation")
self._initialized = True
model = getattr(settings, 'CASBIN_MODEL')
enable_log = getattr(settings, 'CASBIN_LOG_ENABLED', False)
adapter_loc = getattr(settings, 'CASBIN_ADAPTER', 'casbin_adapter.adapter.Adapter')
adapter_args = getattr(settings, 'CASBIN_ADAPTER_ARGS', tuple())
model = getattr(settings, "CASBIN_MODEL")
enable_log = getattr(settings, "CASBIN_LOG_ENABLED", False)
adapter_loc = getattr(settings, "CASBIN_ADAPTER", "casbin_adapter.adapter.Adapter")
adapter_args = getattr(settings, "CASBIN_ADAPTER_ARGS", tuple())
Adapter = import_class(adapter_loc)
adapter = Adapter(*adapter_args)

super().__init__(model, adapter, enable_log)
logger.debug('Casbin enforcer initialised')
logger.debug("Casbin enforcer initialised")

watcher = getattr(settings, 'CASBIN_WATCHER', None)
watcher = getattr(settings, "CASBIN_WATCHER", None)
if watcher:
self.set_watcher(watcher)

role_manager = getattr(settings, 'CASBIN_ROLE_MANAGER', None)
role_manager = getattr(settings, "CASBIN_ROLE_MANAGER", None)
if role_manager:
self.set_role_manager(role_manager)

def __getattribute__(self, name):
safe_methods = ['__init__', '_load', '_initialized']
if not super().__getattribute__('_initialized') and name not in safe_methods:
safe_methods = ["__init__", "_load", "_initialized"]
if not super().__getattribute__("_initialized") and name not in safe_methods:
initialize_enforcer()
if not super().__getattribute__('_initialized'):
raise Exception((
"Calling enforcer attributes before django registry is ready. "
"Prevent making any calls to the enforcer on import/startup"
))
if not super().__getattribute__("_initialized"):
raise Exception(
(
"Calling enforcer attributes before django registry is ready. "
"Prevent making any calls to the enforcer on import/startup"
)
)

return super().__getattribute__(name)

Expand All @@ -73,4 +74,3 @@ def initialize_enforcer():
enforcer._load()
except (OperationalError, ProgrammingError):
pass

23 changes: 11 additions & 12 deletions casbin_adapter/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,23 @@ class Migration(migrations.Migration):

initial = True

dependencies = [
]
dependencies = []

operations = [
migrations.CreateModel(
name='CasbinRule',
name="CasbinRule",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ptype', models.CharField(max_length=255)),
('v0', models.CharField(max_length=255)),
('v1', models.CharField(max_length=255)),
('v2', models.CharField(max_length=255)),
('v3', models.CharField(max_length=255)),
('v4', models.CharField(max_length=255)),
('v5', models.CharField(max_length=255)),
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("ptype", models.CharField(max_length=255)),
("v0", models.CharField(max_length=255)),
("v1", models.CharField(max_length=255)),
("v2", models.CharField(max_length=255)),
("v3", models.CharField(max_length=255)),
("v4", models.CharField(max_length=255)),
("v5", models.CharField(max_length=255)),
],
options={
'db_table': 'casbin_rule',
"db_table": "casbin_rule",
},
),
]
14 changes: 7 additions & 7 deletions casbin_adapter/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@ class CasbinRule(models.Model):
v5 = models.CharField(max_length=255)

class Meta:
db_table = 'casbin_rule'
db_table = "casbin_rule"

def __str__(self):
text = self.ptype

if self.v0:
text = text + ', ' + self.v0
text = text + ", " + self.v0
if self.v1:
text = text + ', ' + self.v1
text = text + ", " + self.v1
if self.v2:
text = text + ', ' + self.v2
text = text + ", " + self.v2
if self.v3:
text = text + ', ' + self.v3
text = text + ", " + self.v3
if self.v4:
text = text + ', ' + self.v4
text = text + ", " + self.v4
if self.v5:
text = text + ', ' + self.v5
text = text + ", " + self.v5
return text

def __repr__(self):
Expand Down
5 changes: 3 additions & 2 deletions casbin_adapter/utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import importlib


def import_class(name):
"""Import class from string
e.g. `package.module.ClassToImport` returns the `ClasToImport` class"""
components = name.split('.')
module_name = '.'.join(components[:-1])
components = name.split(".")
module_name = ".".join(components[:-1])
class_name = components[-1]
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[tool.black]
line-length = 120
5 changes: 3 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
casbin
django
casbin==1.16.10
Django

3 changes: 3 additions & 0 deletions requirements_dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-r requirements.txt
setuptools==60.2.0
simpleeval==0.9.12
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[metadata]
version = 1.0.0
Loading

0 comments on commit 715f3c4

Please sign in to comment.