Project

Profile

Help

Revision c89c6b5b

Added by Vincent Le Goff over 4 years ago

Add the feature to write SharpScript

View differences:

src/sharp/engine.py
242 242
            i += 1
243 243

  
244 244
        return text.replace(";;", ";")
245

  
246
    def format(self, content):
247
        """Write SharpScript and return a string.
248

  
249
        This method takes as argument the SharpScript content and formats it.  It therefore replaces the default formatting.  Arguments are escaped this way:
250

  
251
        * If the argument contains space, escape it with braces.
252
        * If the argument contains new line, indent it.
253
        * If the argument contains semi colons, keep it on one line.
254

  
255
        """
256
        instructions = self.split_statements(content)
257

  
258
        # At this stage, the instructions are formatted in Python
259
        lines = []
260
        for arguments in instructions:
261
            function = arguments[0].lower()
262
            arguments = list(arguments[1:])
263

  
264
            # Escape the arguments if necessary
265
            for i, argument in enumerate(arguments):
266
                arguments[i] = self.escape_argument(argument)
267

  
268
            line = function + " " + " ".join(arguments)
269
            lines.append(line.rstrip(" "))
270

  
271
        return "\n".join(lines)
272

  
273
    @staticmethod
274
    def escape_argument(argument):
275
        """Escape the argument if needed."""
276
        if argument.startswith("{"):
277
            pass
278
        elif "\n" in argument:
279
            lines = argument.splitlines()
280
            argument = "{" + "\n    ".join(lines) + "\n}"
281
        elif " " in argument:
282
            argument = "{" + argument + "}"
283

  
284
        return argument
src/tests/sharp/test_format.py
1
# Copyright (c) 2016, LE GOFF Vincent
2
# All rights reserved.
3

  
4
# Redistribution and use in source and binary forms, with or without
5
# modification, are permitted provided that the following conditions are met:
6

  
7
# * Redistributions of source code must retain the above copyright notice, this
8
#   list of conditions and the following disclaimer.
9

  
10
# * Redistributions in binary form must reproduce the above copyright notice,
11
#   this list of conditions and the following disclaimer in the documentation
12
#   and/or other materials provided with the distribution.
13

  
14
# * Neither the name of ytranslate nor the names of its
15
#   contributors may be used to endorse or promote products derived from
16
#   this software without specific prior written permission.
17

  
18
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28

  
29
from textwrap import dedent
30
import unittest
31

  
32
from sharp.engine import SharpScript
33

  
34
class TestFormat(unittest.TestCase):
35

  
36
    """Unittest for the SharpScript format."""
37

  
38
    def setUp(self):
39
        """Create the SharpScript instance."""
40
        self.engine = SharpScript(None, None)
41

  
42
    def test_single(self):
43
        """Test a single statement."""
44
        # Test a statement on one line with one argument
45
        content = self.engine.format("#play file.wav")
46
        self.assertEqual(content, "#play file.wav")
47

  
48
        # Test a statement with an new line and no argument
49
        content = self.engine.format("#stop\n")
50
        self.assertEqual(content, "#stop")
51

  
52
        # Same test, but with some useless spaces
53
        content = self.engine.format("  #stop  \n  ")
54
        self.assertEqual(content, "#stop")
55

  
56
        # Test a statement with arguments surrounded by braces
57
        content = self.engine.format("#macro {Alt + Enter} north")
58
        self.assertEqual(content, "#macro {Alt + Enter} north")
59

  
60
        # Same test but with some useless spaces
61
        content = self.engine.format("  #macro  {Alt + Enter}  north\n  ")
62
        self.assertEqual(content, "#macro {Alt + Enter} north")
63

  
64
        # Test what happens without function names
65
        content = self.engine.format("say Hello all!\n  ")
66
        self.assertEqual(content, "#send {say Hello all!}")
67

  
68
    def test_multiple(self):
69
        """Test multiple statements at once."""
70
        # Test two statements on two lines without useless spaces
71
        content = self.engine.format("#play file.wav\n#stop")
72
        self.assertEqual(content, "#play file.wav\n#stop")
73

  
74
        # Same test, but with some useless spaces
75
        content = self.engine.format("  #play   file.wav  \n#stop  \n  ")
76
        self.assertEqual(content, "#play file.wav\n#stop")
77

  
78
    def test_python(self):
79
        """Test Python format embeeded in SharpScript."""
80
        content = self.engine.format(dedent("""
81
        #trigger {Should it work?} {+
82
            var = 2 + 3
83
            print var
84
        }""".strip("\n")))
85
        self.assertEqual(content, dedent("""
86
        #trigger {Should it work?} {+
87
            var = 2 + 3
88
            print var
89
        }""".strip("\n")))
90

  
91
    def test_flag(self):
92
        """Test the SharpScript format with flags in funciton calls."""
93
        content = self.engine.format("#say {A message} -braille +speech")
94
        self.assertEqual(content, "#say {A message} -braille +speech")
95

  
96
    def test_semicolons(self):
97
        """Test the semi-colons."""
98
        # A test with simple text
99
        content = self.engine.format("#macro F1 north;south;;east")
100
        self.assertEqual(content, "#macro F1 north;south;;east")
101

  
102
        # A test with SharpScript
103
        content = self.engine.format("#trigger ok {#play new.wav;#stop}")
104
        self.assertEqual(content, "#trigger ok {#play new.wav;#stop}")
105

  
106
    def test_escape_sharp(self):
107
        """Test the escaped sharp symbol."""
108
        # A sharp escaping with plain text
109
        content = self.engine.format("##out")
110
        self.assertEqual(content, "#send #out")
src/tests/sharp/test_syntax.py
92 92
            "say('A message', braille=False, speech=True)"
93 93
        ])
94 94

  
95
    def test_python(self):
96
        """Test Python code in SharpScript."""
95
    def test_python_top(self):
96
        """Test Python code in SharpScript at the top level."""
97 97
        statements = self.engine.feed("""{+
98 98
            print 1
99 99
            print 3

Also available in: Unified diff