Skip to content

Commit 0dff36b

Browse files
feat: Support all APIs required by Casbin Editor (#7)
1 parent 7968f2f commit 0dff36b

File tree

15 files changed

+1039
-67
lines changed

15 files changed

+1039
-67
lines changed

.github/workflows/release.yml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: Release
22

33
on:
44
push:
5-
branches: [master]
5+
branches: [master]
66
pull_request:
77
branches: [master]
88

@@ -52,12 +52,12 @@ jobs:
5252
uses: actions/upload-artifact@v4
5353
with:
5454
name: binaries-${{ matrix.os }}
55-
path: dist/casbin-cli-*
55+
path: dist/casbin-python-cli-*
5656

5757
release:
5858
needs: [test, build-binaries]
5959
runs-on: ubuntu-latest
60-
if: github.ref == 'refs/heads/master'
60+
if: github.event_name == 'pull_request' && github.base_ref == 'master'
6161

6262
steps:
6363
- uses: actions/checkout@v4
@@ -85,7 +85,7 @@ jobs:
8585
- name: Move binaries to dist
8686
run: |
8787
mkdir -p dist
88-
find artifacts -name "casbin-cli-*" -exec cp {} dist/ \;
88+
find artifacts -name "casbin-python-cli-*" -exec cp {} dist/ \;
8989
9090
- name: Semantic Release
9191
env:

.releaserc.json

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"branches": ["master"],
3-
"repositoryUrl": "https://github.com/casbin/casbin-python-cli",
3+
"repositoryUrl":"https://github.com/casbin/casbin-python-cli",
44
"plugins": [
55
"@semantic-release/commit-analyzer",
66
"@semantic-release/release-notes-generator",
@@ -29,7 +29,9 @@
2929
"label": "Source Distribution"
3030
},
3131
{
32-
"path": "dist/casbin-cli-*"
32+
"path": "dist/casbin-python-cli-*",
33+
"name": "casbin-python-cli-${nextRelease.version}",
34+
"label": "casbin-python-cli (${nextRelease.version})"
3335
}
3436
]
3537
}

README.md

Lines changed: 98 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,19 @@
44
![PyPI - License](https://img.shields.io/badge/license-Apache%202.0-green)
55
![PyPI - PyCasbin Version](https://img.shields.io/badge/pycasbin-1.17.0%2B-orange)
66

7+
## Features
8+
9+
- **casbin-editor Integration**: Full API compatibility with casbin-editor for multi-language backend support
10+
- **Unified JSON Response Format**: Standardized `{"allow": boolean|null, "explain": array|null}` response format
11+
- **Method Name Mapping**: Automatic conversion between Java-style command names and Python method names
12+
- **Comprehensive API Coverage**: Support for policy execution, management, RBAC operations, and data retrieval
13+
- **Cross-platform Binaries**: Automated builds for Windows, macOS, and Linux
14+
- **Dynamic Command Execution**: Reflection-based method invocation similar to Java version
15+
716
## Installation
817

918
### Prerequisites
19+
1020
- Python 3.6+
1121
- pip package manager
1222

@@ -20,16 +30,81 @@ cd casbin-python-cli
2030
pip install -r requirements.txt
2131
```
2232

23-
### Method
33+
## Usage
34+
35+
### Basic Command Structure
2436

2537
```bash
2638
python -m casbin_cli.client [command] [options] [args]
39+
```
40+
41+
### Examples
2742

43+
**Policy Execution**:
44+
```bash
45+
# Basic enforcement
2846
python -m casbin_cli.client enforce -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice" "data1" "read"
47+
{"allow":true,"explain":null}
2948

49+
# Enforcement with explanation
50+
python -m casbin_cli.client enforceEx -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice" "data1" "read"
51+
{"allow":true,"explain":["alice","data1","read"]}
52+
```
53+
54+
**Policy Management**:
55+
```bash
56+
# Add policy
57+
python -m casbin_cli.client addPolicy -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "eve" "data3" "read"
3058
{"allow":true,"explain":null}
59+
60+
# Get all policies
61+
python -m casbin_cli.client getPolicy -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv"
62+
{"allow":null,"explain":[["alice","data1","read"],["bob","data2","write"]]}
63+
```
64+
65+
**RBAC Operations**:
66+
```bash
67+
# Get user roles
68+
python -m casbin_cli.client getRolesForUser -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice"
69+
{"allow":null,"explain":["data2_admin"]}
70+
71+
# Get role users
72+
python -m casbin_cli.client getUsersForRole -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "data2_admin"
73+
{"allow":null,"explain":["alice"]}
74+
```
75+
76+
**Data Retrieval**:
77+
```bash
78+
# Get all subjects
79+
python -m casbin_cli.client getAllSubjects -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv"
80+
{"allow":null,"explain":["alice","bob","data2_admin"]}
81+
82+
# Get all objects
83+
python -m casbin_cli.client getAllObjects -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv"
84+
{"allow":null,"explain":["data1","data2"]}
3185
```
3286

87+
### API Compatibility
88+
89+
The Python CLI maintains full compatibility with the Java version through:
90+
91+
- **Command Interface**: Identical command-line arguments (`-m`, `-p`, etc.)
92+
- **Method Name Mapping**: Automatic conversion from Java camelCase to Python snake_case
93+
- **Response Format**: Standardized JSON responses matching Java implementation
94+
- **Error Handling**: Consistent error reporting across all backends
95+
96+
### Supported APIs
97+
98+
| Category | Commands | Status |
99+
| --------------------- | ------------------------------------------------------------ | ------ |
100+
| **Policy Execution** | `enforce`, `enforceEx`, `enforceWithMatcher` ||
101+
| **Policy Management** | `addPolicy`, `removePolicy`, `getPolicy`, `hasPolicy` ||
102+
| **RBAC Operations** | `getRolesForUser`, `getUsersForRole`, `hasRoleForUser` ||
103+
| **Data Retrieval** | `getAllSubjects`, `getAllObjects`, `getAllActions` ||
104+
| **Grouping Policies** | `getGroupingPolicy`, `addGroupingPolicy`, `removeGroupingPolicy` ||
105+
| **Named Policies** | `getNamedPolicy`, `getAllNamedRoles` ||
106+
| **Filtered Queries** | `getFilteredPolicy`, `getFilteredGroupingPolicy` ||
107+
33108
## Project Structure
34109

35110
```
@@ -42,35 +117,34 @@ casbin-python-cli/
42117
│ └── build_binaries.py # Binary building
43118
├── casbin_cli/
44119
│ ├── __init__.py
45-
│ ├── __version__.py # Version source
46-
│ ├── client.py # Main CLI entry point
47-
│ ├── command_executor.py # Command execution
48-
│ ├── enforcer_factory.py # Enforcer creation
49-
│ ├── response.py # Response formatting
50-
│ └── utils.py # Utilities
51-
├── examples/ # Example configurations
52-
├── .releaserc.json # Semantic release config
53-
├── package.json # Node.js dependencies
54-
├── requirements.txt # Python dependencies
55-
├── setup.py # Package setup
56-
└── README.md
120+
│ ├── __version__.py # Version information
121+
│ ├── client.py # Main CLI entry point & argument parsing
122+
│ ├── command_executor.py # Dynamic command execution & method mapping
123+
│ ├── enforcer_factory.py # PyCasbin enforcer creation
124+
│ ├── response.py # Standardized JSON response formatting
125+
│ └── utils.py # Utility functions
126+
├── examples/ # Example model and policy files
127+
│ ├── rbac_model.conf # RBAC model configuration
128+
│ ├── rbac_policy.csv # RBAC policy data
129+
│ ├── basic_model.conf # Basic model configuration
130+
│ └── basic_policy.csv # Basic policy data
131+
├── tests/ # Test files (if any)
132+
├── .releaserc.json # Semantic release configuration
133+
├── package.json # Node.js dependencies for release automation
134+
├── requirements.txt # Python dependencies
135+
├── setup.py # Package setup and distribution
136+
└── README.md # This file
57137
```
58138

59-
### Release Process
60-
61-
Releases are automated via GitHub Actions:
62-
63-
1. Push commits to `main` branch
64-
2. Semantic release analyzes commit messages
65-
3. Automatically generates version numbers and changelog
66-
4. Builds cross-platform binaries
67-
5. Publishes to PyPI and GitHub Releases
68-
69139
## Requirements
70140

71141
- Python 3.6+
72142
- PyCasbin 1.17.0+
73143

74144
## License
75145

76-
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
146+
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
147+
148+
---
149+
150+
**Note**: This Python CLI is part of the Casbin ecosystem and designed to work seamlessly with casbin-editor for multi-language backend support. For more information about Casbin, visit [casbin.org](https://casbin.org).

casbin_cli/client.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ def run(args=None):
2424
if command_name in ['-h', '--help']:
2525
Client._print_help()
2626
return ""
27-
#elif command_name in ['-v', '--version']:
28-
# print(f"casbin-python-cli {__version__}")
29-
# print("pycasbin 1.17.0")
30-
# return ""
27+
elif command_name in ['-v', '--version']:
28+
print(f"casbin-python-cli {__version__}")
29+
print("pycasbin 1.17.0")
30+
return ""
3131

3232
# Handle line breaks
3333
processed_args = [args[0]]
@@ -53,14 +53,19 @@ def run(args=None):
5353
result = executor.execute()
5454

5555
print(result)
56-
return result
57-
58-
except Exception as e:
59-
error_msg = str(e) or str(e.__cause__) if e.__cause__ else "Unknown error"
60-
print(error_msg)
61-
sys.exit(1)
56+
return result
6257

63-
return ""
58+
except Exception as e:
59+
if hasattr(e, '__cause__') and e.__cause__:
60+
error_msg = f"{str(e)}: {str(e.__cause__)}"
61+
else:
62+
error_msg = str(e) if str(e) else f"{type(e).__name__}: {repr(e)}"
63+
64+
if hasattr(sys, '_called_from_test') or 'pytest' in sys.modules:
65+
raise type(e)(error_msg) from e
66+
else:
67+
print(error_msg)
68+
sys.exit(1)
6469

6570
@staticmethod
6671
def _parse_args(args):

0 commit comments

Comments
 (0)