Пример #1
0
def render_sketch_view(sketch_name, static_path):
    sketch_files = SketchFiles(sketch_name)

    content_file = sketch_files.index_html
    if static_path:
        content_file = sketch_files.sketch_dir.joinpath(static_path).resolve()
        if not str(content_file).startswith(
                str(sketch_files.sketch_dir.resolve())):
            # User tried something not allowed (as "/root/something" or "../xxx")
            return '', 403
        elif not content_file.exists():
            return '', 404
    else:
        try:
            commands.transcrypt_sketch(sketch_name)
        except PythonSketchDoesNotExist:
            return f"There's no sketch in {sketch_files.sketch_dir.resolve()}", 404

    with content_file.open() as fd:
        response = Response(fd.read())

    if static_path.endswith('js'):
        # To avoid MIME type errors
        # More can be found here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
        response.headers['Content-Type'] = 'application/javascript'

    return response
Пример #2
0
def test_transcrypt_sketch_error_if_sketch_does_not_exist(MockedFiles):
    files = Mock(spec=Pyp5jsSketchFiles)
    files.check_sketch_exists.return_value = False
    MockedFiles.return_value = files

    with patch('pyp5js.commands.compile_sketch_js') as compiler:
        with pytest.raises(SystemExit):
            commands.transcrypt_sketch(sketch_name='foo', sketch_dir='bar')
Пример #3
0
def render_sketch_view(sketch_name, static_path):
    sketch_files = SketchFiles(sketch_name)

    error = ''
    content_file = sketch_files.index_html
    if static_path:
        content_file = sketch_files.sketch_dir.joinpath(static_path).resolve()
        if not str(content_file).startswith(
                str(sketch_files.sketch_dir.resolve())):
            # User tried something not allowed (as "/root/something" or "../xxx")
            return '', 403
        elif not content_file.exists():
            return '', 404

        with content_file.open() as fd:
            response = Response(fd.read())
        if static_path.endswith('js'):
            # To avoid MIME type errors
            # More can be found here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
            response.headers['Content-Type'] = 'application/javascript'
        return response

    elif request.method == 'POST':
        py_code = request.form.get('py_code', '')
        if not py_code.strip():
            error = 'You have to input the Python code.'
        elif not 'def setup():' in py_code:
            error = 'You have to define a setup function.'
        elif not 'def draw():' in py_code:
            error = 'You have to define a draw function.'
        else:
            try:
                ast.parse(py_code, sketch_files.sketch_py.name)
                sketch_files.sketch_py.write_text(py_code)
            except SyntaxError as exc:
                error = f'SyntaxError: {exc}'

    if not error:
        try:
            commands.transcrypt_sketch(sketch_name)
        except PythonSketchDoesNotExist:
            return f"There's no sketch in {sketch_files.sketch_dir.resolve()}", 404

    context = {
        'p5_js_url': sketch_files.urls.p5_js_url,
        'sketch_js_url': sketch_files.urls.sketch_js_url,
        'sketch_name': sketch_files.sketch_name,
        'py_code': sketch_files.sketch_py.read_text(),
        'error': error,
    }
    return render_template('view_sketch.html', **context)
Пример #4
0
def test_transcrypt_sketch(files):
    files.sketch_py.touch()
    with patch('pyp5js.commands.compile_sketch_js') as compiler:
        output = commands.transcrypt_sketch('foo')

        assert output == files
        compiler.assert_called_once_with(files)
Пример #5
0
def transcrypt_sketch(sketch_name):
    """
    Command to generate the P5.js code for a python sketch

    Params:
    - sketch_name: name of the sketch

    Example:
    $ pyp5js transcrypt my_sketch
    """
    files = commands.transcrypt_sketch(sketch_name)
    cprint.ok(f"Your sketch is ready and available at file://{files.index_html.absolute()}")
Пример #6
0
def test_transcrypt_sketch(MockedFiles):
    files = Mock(spec=Pyp5jsSketchFiles)
    files.check_sketch_exists.return_value = True
    MockedFiles.return_value = files

    with patch('pyp5js.commands.compile_sketch_js') as compiler:
        output = commands.transcrypt_sketch(sketch_name='foo',
                                            sketch_dir='bar')

        assert output == files.index_html
        MockedFiles.assert_called_once_with('bar', 'foo')
        compiler.assert_called_once_with(files)
Пример #7
0
def transcrypt_sketch(sketch_name, sketch_dir):
    """
    Command to generate the P5.js code for a python sketch

    Params:
    - sketch_name: name of the sketch

    Opitionals
    - sketch_dir: sketch's directory (defaults to {sketch_name})
    """
    index_file = commands.transcrypt_sketch(sketch_name, sketch_dir)
    cprint.ok(f"Your sketch is ready and available at {index_file}")
Пример #8
0
def test_transcrypt_sketch_error_if_invalid_sketch(files):
    with patch('pyp5js.commands.compile_sketch_js') as compiler:
        with pytest.raises(InvalidName):
            commands.transcrypt_sketch('123foo')
        assert not compiler.called
Пример #9
0
def test_transcrypt_sketch_error_if_sketch_does_not_exist(files):
    with patch('pyp5js.commands.compile_sketch_js') as compiler:
        with pytest.raises(PythonSketchDoesNotExist):
            commands.transcrypt_sketch('foo')
        assert not compiler.called
Пример #10
0
 def create_sketch_with_static_files(self, name):
     sketch_files = commands.new_sketch(name)
     commands.transcrypt_sketch(name)
     return sketch_files.sketch_dir
Пример #11
0
            else:
                pc = pc.replace('loadShape(', 'loadModel(')
                pc = pc.replace('shape(', 'model(')
            # insert pyp5js import line
            pc = 'from pyp5js import *\n' + pc
            # replace any println() functions for print()
            pc = pc.replace('println(', 'print(')
            # replace any createFont() functions for loadFont()
            pc = pc.replace('createFont(', 'loadFont(')

            py_read.close()
            sketch_write = open(py_file, 'wt')
            sketch_write.write(pc)
            sketch_write.close()

    transcrypt_sketch(temp_sketch)

# move transcribed sketches to _site directory

for temp_sketch in os.listdir(SKETCHBOOK_DIR):
    target_dir = os.path.join(SKETCHBOOK_DIR, temp_sketch, 'target')
    data_dir = os.path.join(SKETCHBOOK_DIR, temp_sketch, 'data')
    # check if a data directory exists
    if os.path.exists(data_dir):
        data_files = os.listdir(data_dir)
        # copy any files from the data sub-directory into the target directory
        for data_file in data_files:
            data_file_path = os.path.join(data_dir, data_file)
            shutil.copy(data_file_path, target_dir)

    destination_dir = os.path.join(SITE_DIR, temp_sketch)