Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pztrick committed Jun 12, 2014
0 parents commit 4dff052
Show file tree
Hide file tree
Showing 11 changed files with 228 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# build files
*.egg-info
*.pot
*.py[co]
__pycache__
MANIFEST
dist/
build/

# cache files
*~

# ide files
.ropeproject
*.sublime-workspace
*.sublime-project
.env
1 change: 1 addition & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v0.1.0, 2014/06/12 -- Initial release.
3 changes: 3 additions & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Contributors
------------
Patrick Paul <https://github.com/pztrick>
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include *.txt
include *.md
20 changes: 20 additions & 0 deletions MIT-LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright 2014 Patrick Paul and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

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 OR COPYRIGHT HOLDERS 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.
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
### What is DjScript?

`djscript` is a Python package for using **RapydScript** in your Django application. This package installs NodeJS/npm/RapydScript in an isolated virtual environment and includes utilities for writing RapydScript `*.pjs` files in your web application.

### What is RapydScript?

From the RapydScript README: "RapydScript (pronounced 'RapidScript') is a pre-compiler for JavaScript, similar to CoffeeScript, but with cleaner, more readable syntax. The syntax is very similar to Python, but allows JavaScript as well."

* Github: <https://github.com/atsepkov/RapydScript>
* Community: <http://groups.google.com/group/rapydscript>

### Usage

For Django development, there is a convenient `djurl` template tag which will freshly compile your RapydScript on each page request. On production, the static compiled javascript is served directly from your `static/` folder.

```
# settings.py
PROJECT_HOME = os.path.abspath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_HOME, 'static') + '/'
STATIC_URL = '/static/'
DJSCRIPT_PATHS = {
'path.to.rapydscript.file': 'file.js'
}
```

```
# template.html
{% djurl 'path.to.rapydscript.file' %}
```

Your source file (e.g. *path/to/rapydscript/file.pjs*) must end in the `.pjs` extension. Your target file destination is the value specified in settings.py. Your web server must have correct file permissions to write to your `static/` folder.

### Installation

```
pip install djscript
```
1 change: 1 addition & 0 deletions djscript/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pass
Empty file.
31 changes: 31 additions & 0 deletions djscript/templatetags/djscript.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from django import template
from django.conf import settings
import os
import subprocess

register = template.Library()

djurls = getattr(settings, 'DJSCRIPT_PATHS')

# settings value
@register.simple_tag
def djurl(dot_path):
"""
DEBUG == True ? Compiles and serves file at dot_path
DEBUG == False ? Serves pre-compiled file path
Usage: {% djurl 'path.to.file' %}
"""
try:
http_path = os.path.join(getattr(settings, 'STATIC_URL', ''), djurls[dot_path])
if settings.DEBUG:
# 1) Compile!
source_path = "%s.pjs" % os.path.join(getattr(settings, 'PROJECT_HOME'), *dot_path.split('.'))
target_path = os.path.join(getattr(settings, 'STATIC_ROOT'), djurls[dot_path])

cmd = ['rapydscript', source_path, '-o', target_path]
proc = subprocess.Popen([' '.join(cmd)], shell=True)

return http_path
except KeyError:
return None
Empty file added djscript/utils.py
Empty file.
115 changes: 115 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
from setuptools import setup
import os
import sys
import subprocess
from distutils.errors import DistutilsPlatformError, DistutilsInternalError
from setuptools.command.install import install

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('djscript')

npm_dependencies = {
'rapydscript': '0.2.0'
}

class custom_install(install):
def run_npm(self):
""" h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py """

for name, version in npm_dependencies.items():
# packages are installed globally to make sure that they are
# installed in the virtualenv rather than the current directory.
# it is also necessary for packages containing scripts, e.g. less
dep_name = '%s@%s' % (name, version)
self.run_cmd(['npm', 'install', '-g', dep_name])

def run_cmd(self, cmd, cwd=None, extra_env=None):
""" h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py """
all_output = []
cmd_parts = []

for part in cmd:
if len(part) > 45:
part = part[:20] + "..." + part[-20:]
if ' ' in part or '\n' in part or '"' in part or "'" in part:
part = '"%s"' % part.replace('"', '\\"')
cmd_parts.append(part)
cmd_desc = ' '.join(cmd_parts)
logger.debug(" ** Running command %s" % cmd_desc)

# output
stdout = subprocess.PIPE

# env
if extra_env:
env = os.environ.copy()
if extra_env:
env.update(extra_env)
else:
env = None

# execute
try:
proc = subprocess.Popen(
[' '.join(cmd)], stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
cwd=cwd, env=env, shell=True)
except Exception:
e = sys.exc_info()[1]
logger.error("Error %s while executing command %s" % (e, cmd_desc))
raise

stdout = proc.stdout
while stdout:
line = stdout.readline()
if not line:
break
line = line.rstrip()
all_output.append(line)
logger.info(line)
proc.wait()

# error handler
if proc.returncode:
for s in all_output:
logger.critical(s)
raise OSError("Command %s failed with error code %s"
% (cmd_desc, proc.returncode))

return proc.returncode, all_output

def run(self):
if not os.environ.get('VIRTUAL_ENV', None):
raise DistutilsPlatformError('You must install djscript into a virtualenv. Aborting.')

install.do_egg_install(self)

# POST INSTALL
print "* * * Beginning post-install scripts"

# module_path = self.install_headers
# for thing in dir(self):
# print "%s : %s\n\n" % (thing, str(getattr(self, thing)))

# 1) Install npm depencies into virtualenv/virtual-node
print "* * * \t 1) installing npm dependencies"
self.run_npm()


setup(
cmdclass={'install': custom_install},
name='DjScript',
version='0.1.0',
author='Patrick Paul',
author_email='pztrick44@gmail.com',
packages=['djscript', ],
scripts=[],
url='https://github.com/pztrick/djscript/',
license='MIT-LICENSE.txt',
description='Django package for using the RapydScript javascript compiler',
long_description=open('README.md').read(),
install_requires=[
"Django >= 1.5.0",
"virtual-node == 0.1.0",
],
)

0 comments on commit 4dff052

Please sign in to comment.