id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
143,948
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/db/backends.py
health_check.db.backends.DatabaseBackend
class DatabaseBackend(BaseHealthCheckBackend): def check_status(self): try: obj = TestModel.objects.create(title="test") obj.title = "newtest" obj.save() obj.delete() except IntegrityError: raise ServiceReturnedUnexpectedResult("Integrity Error") except DatabaseError: raise ServiceUnavailable("Database error")
class DatabaseBackend(BaseHealthCheckBackend): def check_status(self): pass
2
0
10
0
10
0
3
0
1
3
3
0
1
0
1
8
11
0
11
3
9
0
11
3
9
3
1
1
3
143,949
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_plugins.py
tests.test_plugins.FakePlugin
class FakePlugin(BaseHealthCheckBackend): def check_status(self): pass
class FakePlugin(BaseHealthCheckBackend): def check_status(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
8
3
0
3
2
1
0
3
2
1
1
1
0
1
143,950
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/contrib/rabbitmq/apps.py
health_check.contrib.rabbitmq.apps.HealthCheckConfig
class HealthCheckConfig(AppConfig): name = "health_check.contrib.rabbitmq" def ready(self): from .backends import RabbitMQHealthCheck plugin_dir.register(RabbitMQHealthCheck)
class HealthCheckConfig(AppConfig): def ready(self): pass
2
0
4
1
3
0
1
0
1
1
1
0
1
0
1
1
7
2
5
4
2
0
5
4
2
1
1
0
1
143,951
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_mixins.py
tests.test_mixins.OkPlugin
class OkPlugin(BaseHealthCheckBackend): def check_status(self): pass
class OkPlugin(BaseHealthCheckBackend): def check_status(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
8
3
0
3
2
1
0
3
2
1
1
1
0
1
143,952
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_migrations.py
tests.test_migrations.TestMigrationsHealthCheck
class TestMigrationsHealthCheck(TestCase): def test_check_status_work(self): with patch( "health_check.contrib.migrations.backends.MigrationsHealthCheck.get_migration_plan", return_value=[], ): backend = MigrationsHealthCheck() backend.run_check() self.assertFalse(backend.errors) def test_check_status_raises_error_if_there_are_migrations(self): with patch( "health_check.contrib.migrations.backends.MigrationsHealthCheck.get_migration_plan", return_value=[(MockMigration, False)], ): backend = MigrationsHealthCheck() backend.run_check() self.assertTrue(backend.errors)
class TestMigrationsHealthCheck(TestCase): def test_check_status_work(self): pass def test_check_status_raises_error_if_there_are_migrations(self): pass
3
0
8
0
8
0
1
0
1
2
2
0
2
0
2
2
18
1
17
5
14
0
11
5
8
1
1
1
2
143,953
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/exceptions.py
health_check.exceptions.HealthCheckException
class HealthCheckException(Exception): message_type = _("unknown error") def __init__(self, message): self.message = message def __str__(self): return "%s: %s" % (self.message_type, self.message)
class HealthCheckException(Exception): def __init__(self, message): pass def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
3
2
1
2
12
8
2
6
5
3
0
6
5
3
1
3
0
2
143,954
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/exceptions.py
health_check.exceptions.ServiceReturnedUnexpectedResult
class ServiceReturnedUnexpectedResult(HealthCheckException): message_type = _("unexpected result")
class ServiceReturnedUnexpectedResult(HealthCheckException): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
12
2
0
2
2
1
0
2
2
1
0
4
0
0
143,955
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/exceptions.py
health_check.exceptions.ServiceUnavailable
class ServiceUnavailable(HealthCheckException): message_type = _("unavailable")
class ServiceUnavailable(HealthCheckException): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
12
2
0
2
2
1
0
2
2
1
0
4
0
0
143,956
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/exceptions.py
health_check.exceptions.ServiceWarning
class ServiceWarning(HealthCheckException): """ Warning of service misbehavior. If the ``HEALTH_CHECK['WARNINGS_AS_ERRORS']`` is set to ``False``, these exceptions will not case a 500 status response. """ message_type = _("warning")
class ServiceWarning(HealthCheckException): ''' Warning of service misbehavior. If the ``HEALTH_CHECK['WARNINGS_AS_ERRORS']`` is set to ``False``, these exceptions will not case a 500 status response. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
12
9
2
2
2
1
5
2
2
1
0
4
0
0
143,957
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/management/commands/health_check.py
health_check.management.commands.health_check.Command
class Command(CheckMixin, BaseCommand): help = "Run health checks and exit 0 if everything went well." def add_arguments(self, parser): parser.add_argument("-s", "--subset", type=str, nargs=1) def handle(self, *args, **options): # perform all checks subset = options.get("subset", []) subset = subset[0] if subset else None try: errors = self.check(subset=subset) except Http404 as e: self.stdout.write(str(e)) sys.exit(1) for plugin_identifier, plugin in self.filter_plugins(subset=subset).items(): style_func = self.style.SUCCESS if not plugin.errors else self.style.ERROR self.stdout.write( "{:<24} ... {}\n".format( plugin_identifier, style_func(plugin.pretty_status()) ) ) if errors: sys.exit(1)
class Command(CheckMixin, BaseCommand): def add_arguments(self, parser): pass def handle(self, *args, **options): pass
3
0
11
1
10
1
4
0.05
2
1
0
0
2
0
2
7
26
4
21
9
18
1
17
8
14
6
1
1
7
143,958
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/mixins.py
health_check.mixins.CheckMixin
class CheckMixin: _errors = None _plugins = None @property def errors(self): if not self._errors: self._errors = self.run_check() return self._errors def check(self, subset=None): return self.run_check(subset=subset) @property def plugins(self): if not plugin_dir._registry: return OrderedDict({}) if not self._plugins: registering_plugins = ( plugin_class(**copy.deepcopy(options)) for plugin_class, options in plugin_dir._registry ) registering_plugins = sorted( registering_plugins, key=lambda plugin: plugin.identifier() ) self._plugins = OrderedDict( {plugin.identifier(): plugin for plugin in registering_plugins} ) return self._plugins def filter_plugins(self, subset=None): if subset is None: return self.plugins health_check_subsets = HEALTH_CHECK["SUBSETS"] if subset not in health_check_subsets or not self.plugins: raise Http404(f"Subset: '{subset}' does not exist.") selected_subset = set(health_check_subsets[subset]) return { plugin_identifier: v for plugin_identifier, v in self.plugins.items() if plugin_identifier in selected_subset } def run_check(self, subset=None): errors = [] def _run(plugin): plugin.run_check() try: return plugin finally: from django.db import connections connections.close_all() def _collect_errors(plugin): if plugin.critical_service: if not HEALTH_CHECK["WARNINGS_AS_ERRORS"]: errors.extend( e for e in plugin.errors if not isinstance(e, ServiceWarning) ) else: errors.extend(plugin.errors) plugins = self.filter_plugins(subset=subset) plugin_instances = plugins.values() if HEALTH_CHECK["DISABLE_THREADING"]: for plugin in plugin_instances: _run(plugin) _collect_errors(plugin) else: with ThreadPoolExecutor(max_workers=len(plugin_instances) or 1) as executor: for plugin in executor.map(_run, plugin_instances): _collect_errors(plugin) return errors
class CheckMixin: @property def errors(self): pass def check(self, subset=None): pass @property def plugins(self): pass def filter_plugins(self, subset=None): pass def run_check(self, subset=None): pass def _run(plugin): pass def _collect_errors(plugin): pass
10
0
12
1
11
0
2
0
0
3
1
3
5
0
5
5
79
13
66
21
55
0
48
18
39
4
0
3
17
143,959
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/plugins.py
health_check.plugins.HealthCheckPluginDirectory
class HealthCheckPluginDirectory: """Django health check registry.""" def __init__(self): self._registry = [] # plugin_class class -> plugin options def reset(self): """Reset registry state, e.g. for testing purposes.""" self._registry = [] def register(self, plugin, **options): """Add the given plugin from the registry.""" # Instantiate the admin class to save in the registry self._registry.append((plugin, options))
class HealthCheckPluginDirectory: '''Django health check registry.''' def __init__(self): pass def reset(self): '''Reset registry state, e.g. for testing purposes.''' pass def register(self, plugin, **options): '''Add the given plugin from the registry.''' pass
4
3
3
0
2
1
1
0.71
0
0
0
0
3
1
3
3
14
3
7
5
3
5
7
5
3
1
0
0
3
143,960
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/storage/apps.py
health_check.storage.apps.HealthCheckConfig
class HealthCheckConfig(AppConfig): name = "health_check.storage" def ready(self): from .backends import DefaultFileStorageHealthCheck plugin_dir.register(DefaultFileStorageHealthCheck)
class HealthCheckConfig(AppConfig): def ready(self): pass
2
0
4
1
3
0
1
0
1
1
1
0
1
0
1
1
7
2
5
4
2
0
5
4
2
1
1
0
1
143,961
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/storage/backends.py
health_check.storage.backends.DefaultFileStorageHealthCheck
class DefaultFileStorageHealthCheck(StorageHealthCheck): storage_alias = "default" storage = default_storage
class DefaultFileStorageHealthCheck(StorageHealthCheck): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
3
0
3
3
2
0
3
3
2
0
2
0
0
143,962
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/views.py
health_check.views.MediaType
class MediaType: """ Sortable object representing HTTP's accept header. .. seealso:: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept """ pattern = re.compile( r""" ^ (?P<mime_type> (\w+|\*) # Media type, or wildcard / ([\w\d\-+.]+|\*) # subtype, or wildcard ) ( \s*;\s* # parameter separator with optional whitespace q= # q is expected to be the first parameter, by RFC2616 (?P<weight> 1([.]0{1,3})? # 1 with up to three digits of precision | 0([.]\d{1,3})? # 0.000 to 0.999 with optional precision ) )? ( \s*;\s* # parameter separator with optional whitespace [-!#$%&'*+.^_`|~0-9a-zA-Z]+ # any token from legal characters = [-!#$%&'*+.^_`|~0-9a-zA-Z]+ # any value from legal characters )* $ """, re.VERBOSE, ) def __init__(self, mime_type, weight=1.0): self.mime_type = mime_type self.weight = float(weight) @classmethod def from_string(cls, value): """Return single instance parsed from given accept header string.""" match = cls.pattern.search(value) if match is None: raise ValueError('"%s" is not a valid media type' % value) try: return cls(match.group("mime_type"), float(match.group("weight") or 1)) except ValueError: return cls(value) @classmethod def parse_header(cls, value="*/*"): """Parse HTTP accept header and return instances sorted by weight.""" yield from sorted( ( cls.from_string(token.strip()) for token in value.split(",") if token.strip() ), reverse=True, ) def __str__(self): return "%s; q=%s" % (self.mime_type, self.weight) def __repr__(self): return "%s: %s" % (type(self).__name__, self.__str__()) def __eq__(self, other): return self.weight == other.weight and self.mime_type == other.mime_type def __lt__(self, other): return self.weight.__lt__(other.weight)
class MediaType: ''' Sortable object representing HTTP's accept header. .. seealso:: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept ''' def __init__(self, mime_type, weight=1.0): pass @classmethod def from_string(cls, value): '''Return single instance parsed from given accept header string.''' pass @classmethod def parse_header(cls, value="*/*"): '''Parse HTTP accept header and return instances sorted by weight.''' pass def __str__(self): pass def __repr__(self): pass def __eq__(self, other): pass def __lt__(self, other): pass
10
3
4
0
4
0
1
0.26
0
3
0
0
5
2
7
7
73
9
58
14
48
15
23
12
15
3
0
1
9
143,963
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_autodiscover.py
tests.test_autodiscover.TestAutoDiscover
class TestAutoDiscover: def test_autodiscover(self): health_check_plugins = list( filter( lambda x: x.startswith("health_check.") and "celery" not in x, settings.INSTALLED_APPS, ) ) non_celery_plugins = [ x for x in plugin_dir._registry if not issubclass(x[0], (CeleryHealthCheck, CeleryPingHealthCheck)) ] # The number of installed apps excluding celery should equal to all plugins except celery assert len(non_celery_plugins) == len(health_check_plugins) def test_discover_celery_queues(self): celery_plugins = [ x for x in plugin_dir._registry if issubclass(x[0], CeleryHealthCheck) ] assert len(celery_plugins) == len(current_app.amqp.queues)
class TestAutoDiscover: def test_autodiscover(self): pass def test_discover_celery_queues(self): pass
3
0
11
1
9
1
1
0.05
0
4
2
0
2
0
2
2
23
3
19
6
16
1
8
6
5
1
0
0
2
143,964
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_backends.py
tests.test_backends.TestBaseHealthCheckBackend
class TestBaseHealthCheckBackend: def test_run_check(self): with pytest.raises(NotImplementedError): BaseHealthCheckBackend().run_check() def test_identifier(self): assert BaseHealthCheckBackend().identifier() == "BaseHealthCheckBackend" class MyHeathCheck(BaseHealthCheckBackend): pass assert MyHeathCheck().identifier() == "MyHeathCheck" class MyHeathCheck(BaseHealthCheckBackend): foo = "bar" def identifier(self): return self.foo assert MyHeathCheck().identifier() == "bar" def test_status(self): ht = BaseHealthCheckBackend() assert ht.status == 1 ht.errors = [1] assert ht.status == 0 def test_pretty_status(self): ht = BaseHealthCheckBackend() assert ht.pretty_status() == "working" ht.errors = ["foo"] assert ht.pretty_status() == "foo" ht.errors.append("bar") assert ht.pretty_status() == "foo\nbar" ht.errors.append(123) assert ht.pretty_status() == "foo\nbar\n123" def test_add_error(self): ht = BaseHealthCheckBackend() e = HealthCheckException("foo") ht.add_error(e) assert ht.errors[0] is e ht = BaseHealthCheckBackend() ht.add_error("bar") assert isinstance(ht.errors[0], HealthCheckException) assert str(ht.errors[0]) == "unknown error: bar" ht = BaseHealthCheckBackend() ht.add_error(type) assert isinstance(ht.errors[0], HealthCheckException) assert str(ht.errors[0]) == "unknown error: unknown error" def test_add_error_cause(self): ht = BaseHealthCheckBackend() logger = logging.getLogger("health-check") with StringIO() as stream: stream_handler = logging.StreamHandler(stream) logger.addHandler(stream_handler) try: raise Exception("bar") except Exception as e: ht.add_error("foo", e) stream.seek(0) log = stream.read() assert "foo" in log assert "bar" in log assert "Traceback" in log assert "Exception: bar" in log logger.removeHandler(stream_handler) with StringIO() as stream: stream_handler = logging.StreamHandler(stream) logger.addHandler(stream_handler) try: raise Exception("bar") except Exception: ht.add_error("foo") stream.seek(0) log = stream.read() assert "foo" in log assert "bar" not in log assert "Traceback" not in log assert "Exception: bar" not in log logger.removeHandler(stream_handler)
class TestBaseHealthCheckBackend: def test_run_check(self): pass def test_identifier(self): pass class MyHeathCheck(BaseHealthCheckBackend): class MyHeathCheck(BaseHealthCheckBackend): def identifier(self): pass def test_status(self): pass def test_pretty_status(self): pass def test_add_error(self): pass def test_add_error_cause(self): pass
10
0
12
1
10
0
1
0
0
8
3
0
6
0
6
6
87
15
72
21
62
0
72
19
62
3
0
2
9
143,965
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_cache.py
tests.test_cache.MockCache
class MockCache(BaseCache): """ A Mock Cache used for testing. set_works - set to False to make the mocked set method fail, but not raise set_raises - The Exception to be raised when set() is called, if any """ key = None value = None set_works = None set_raises = None def __init__(self, set_works=True, set_raises=None): super(MockCache, self).__init__(params={}) self.set_works = set_works self.set_raises = set_raises def set(self, key, value, *args, **kwargs): if self.set_raises is not None: raise self.set_raises elif self.set_works: self.key = key self.value = value else: self.key = key self.value = None def get(self, key, *args, **kwargs): if key == self.key: return self.value else: return None
class MockCache(BaseCache): ''' A Mock Cache used for testing. set_works - set to False to make the mocked set method fail, but not raise set_raises - The Exception to be raised when set() is called, if any ''' def __init__(self, set_works=True, set_raises=None): pass def set(self, key, value, *args, **kwargs): pass def get(self, key, *args, **kwargs): pass
4
1
6
0
6
0
2
0.22
1
1
0
0
3
0
3
3
32
4
23
8
19
5
20
8
16
3
1
1
6
143,966
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_celery_ping.py
tests.test_celery_ping.TestCeleryPingHealthCheckApps
class TestCeleryPingHealthCheckApps: def test_apps(self): assert HealthCheckConfig.name == "health_check.contrib.celery_ping" celery_ping = apps.get_app_config("celery_ping") assert celery_ping.name == "health_check.contrib.celery_ping"
class TestCeleryPingHealthCheckApps: def test_apps(self): pass
2
0
5
1
4
0
1
0
0
1
1
0
1
0
1
1
6
1
5
3
3
0
5
3
3
1
0
0
1
143,967
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_db.py
tests.test_db.MockDBModel
class MockDBModel(Model): """ A Mock database used for testing. error_thrown - The Exception to be raised when save() is called, if any """ error_thrown = None def __init__(self, error_thrown=None, *args, **kwargs): super(MockDBModel, self).__init__(*args, **kwargs) self.error_thrown = error_thrown def save(self, *args, **kwargs): if self.error_thrown is not None: raise self.error_thrown else: return True def delete(self, *args, **kwargs): return True
class MockDBModel(Model): ''' A Mock database used for testing. error_thrown - The Exception to be raised when save() is called, if any ''' def __init__(self, error_thrown=None, *args, **kwargs): pass def save(self, *args, **kwargs): pass def delete(self, *args, **kwargs): pass
4
1
3
0
3
0
1
0.33
1
1
0
0
3
0
3
3
20
4
12
5
8
4
11
5
7
2
1
1
4
143,968
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_migrations.py
tests.test_migrations.MockMigration
class MockMigration(Migration): ...
class MockMigration(Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
143,969
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/tests/test_mixins.py
tests.test_mixins.FailPlugin
class FailPlugin(BaseHealthCheckBackend): def check_status(self): self.add_error("Oops")
class FailPlugin(BaseHealthCheckBackend): def check_status(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
8
3
0
3
2
1
0
3
2
1
1
1
0
1
143,970
KristianOellegaard/django-health-check
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KristianOellegaard_django-health-check/tests/test_cache.py
tests.test_cache.HealthCheckCacheTests
class HealthCheckCacheTests(TestCase): """ Tests health check behavior with a mocked cache backend. Ensures check_status returns/raises the expected result when the cache works, fails, or raises exceptions. """ @patch("health_check.cache.backends.caches", dict(default=MockCache())) def test_check_status_working(self): cache_backend = CacheBackend() cache_backend.run_check() self.assertFalse(cache_backend.errors) @patch( "health_check.cache.backends.caches", dict(default=MockCache(), broken=MockCache(set_works=False)), ) def test_multiple_backends_check_default(self): # default backend works while other is broken cache_backend = CacheBackend("default") cache_backend.run_check() self.assertFalse(cache_backend.errors) @patch( "health_check.cache.backends.caches", dict(default=MockCache(), broken=MockCache(set_works=False)), ) def test_multiple_backends_check_broken(self): cache_backend = CacheBackend("broken") cache_backend.run_check() self.assertTrue(cache_backend.errors) self.assertIn("does not match", cache_backend.pretty_status()) # check_status should raise ServiceUnavailable when values at cache key do not match @patch( "health_check.cache.backends.caches", dict( default=MockCache(set_works=False)) ) def test_set_fails(self): cache_backend = CacheBackend() cache_backend.run_check() self.assertTrue(cache_backend.errors) self.assertIn("does not match", cache_backend.pretty_status()) # check_status should catch generic exceptions raised by set and convert to ServiceUnavailable @patch( "health_check.cache.backends.caches", dict(default=MockCache(set_raises=Exception)), ) def test_set_raises_generic(self): cache_backend = CacheBackend() with self.assertRaises(Exception): cache_backend.run_check() # check_status should catch CacheKeyWarning and convert to ServiceReturnedUnexpectedResult @patch( "health_check.cache.backends.caches", dict(default=MockCache(set_raises=CacheKeyWarning)), ) def test_set_raises_cache_key_warning(self): cache_backend = CacheBackend() cache_backend.check_status() cache_backend.run_check() self.assertIn( "unexpected result: Cache key warning", cache_backend.pretty_status() )
class HealthCheckCacheTests(TestCase): ''' Tests health check behavior with a mocked cache backend. Ensures check_status returns/raises the expected result when the cache works, fails, or raises exceptions. ''' @patch("health_check.cache.backends.caches", dict(default=MockCache())) def test_check_status_working(self): pass @patch( "health_check.cache.backends.caches", dict(default=MockCache(), broken=MockCache(set_works=False)), ) def test_multiple_backends_check_default(self): pass @patch( "health_check.cache.backends.caches", dict(default=MockCache(), broken=MockCache(set_works=False)), ) def test_multiple_backends_check_broken(self): pass @patch( "health_check.cache.backends.caches", dict( default=MockCache(set_works=False)) ) def test_set_fails(self): pass @patch( "health_check.cache.backends.caches", dict(default=MockCache(set_raises=Exception)), ) def test_set_raises_generic(self): pass @patch( "health_check.cache.backends.caches", dict(default=MockCache(set_raises=CacheKeyWarning)), ) def test_set_raises_cache_key_warning(self): pass
13
1
5
0
5
0
1
0.16
1
2
1
0
6
0
6
6
64
6
50
33
23
8
28
13
21
1
1
1
6
143,971
KristianOellegaard/django-health-check
KristianOellegaard_django-health-check/health_check/db/migrations/0001_initial.py
health_check.db.migrations.0001_initial.Migration
class Migration(migrations.Migration): initial = True replaces = [ ("health_check_db", "0001_initial"), ] dependencies = [] operations = [ migrations.CreateModel( name="TestModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("title", models.CharField(max_length=128)), ], options={ "db_table": "health_check_db_testmodel", }, ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
29
3
26
5
25
0
5
5
4
0
1
0
0
143,972
KristianOellegaard/django-health-check
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KristianOellegaard_django-health-check/health_check/views.py
health_check.views.MainView
class MainView(CheckMixin, TemplateView): template_name = "health_check/index.html" @method_decorator(never_cache) def get(self, request, *args, **kwargs): subset = kwargs.get("subset", None) health_check_has_error = self.check(subset) status_code = 500 if health_check_has_error else 200 format_override = request.GET.get("format") if format_override == "json": return self.render_to_response_json( self.filter_plugins(subset=subset), status_code ) accept_header = request.META.get("HTTP_ACCEPT", "*/*") for media in MediaType.parse_header(accept_header): if media.mime_type in ( "text/html", "application/xhtml+xml", "text/*", "*/*", ): context = self.get_context_data(**kwargs) return self.render_to_response(context, status=status_code) elif media.mime_type in ("application/json", "application/*"): return self.render_to_response_json( self.filter_plugins(subset=subset), status_code ) return HttpResponse( "Not Acceptable: Supported content types: text/html, application/json", status=406, content_type="text/plain", ) def get_context_data(self, **kwargs): subset = kwargs.get("subset", None) return { **super().get_context_data(**kwargs), "plugins": self.filter_plugins(subset=subset).values(), } def render_to_response_json(self, plugins, status): return JsonResponse( { str(plugin_identifier): str(p.pretty_status()) for plugin_identifier, p in plugins.items() }, status=status, )
class MainView(CheckMixin, TemplateView): @method_decorator(never_cache) def get(self, request, *args, **kwargs): pass def get_context_data(self, **kwargs): pass def render_to_response_json(self, plugins, status): pass
5
0
15
1
14
0
3
0
2
3
1
0
3
0
3
8
50
5
45
14
40
0
21
13
17
6
1
2
8
143,973
KristianOellegaard/django-health-check
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KristianOellegaard_django-health-check/health_check/db/models.py
health_check.db.models.TestModel.Meta
class Meta: db_table = "health_check_db_testmodel"
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
143,974
KristianOellegaard/django-health-check
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KristianOellegaard_django-health-check/health_check/cache/backends.py
health_check.cache.backends.RedisError
class RedisError(Exception): pass
class RedisError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
143,975
KristianOellegaard/django-health-check
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KristianOellegaard_django-health-check/tests/test_backends.py
tests.test_backends.TestBaseHealthCheckBackend.test_identifier.MyHeathCheck
class MyHeathCheck(BaseHealthCheckBackend): foo = "bar" def identifier(self): return self.foo
class MyHeathCheck(BaseHealthCheckBackend): def identifier(self): pass
2
0
0
0
0
0
0
0
1
0
0
0
0
0
0
7
2
0
2
1
1
0
2
1
1
0
1
0
0
143,976
KristianOellegaard/django-health-check
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KristianOellegaard_django-health-check/tests/test_backends.py
tests.test_backends.TestBaseHealthCheckBackend.test_identifier.MyHeathCheck
class MyHeathCheck(BaseHealthCheckBackend): foo = "bar" def identifier(self): return self.foo
class MyHeathCheck(BaseHealthCheckBackend): def identifier(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
8
5
1
4
3
2
0
4
3
2
1
1
0
1
143,977
Kroisse/FormEncode-Jinja2
Kroisse_FormEncode-Jinja2/formencode_jinja2/formfill.py
formencode_jinja2.formfill.FormFillExtension
class FormFillExtension(jinja2.ext.Extension): """Jinja2 extension for filling HTML forms via :mod:`formencode.htmlfill`. For example, this code: .. code-block:: html+jinja {% formfill {'username': 'robert', 'email': 'robert153@usrobots.com'} with {'username': 'This name is invalid'} %} <form action="/register" method="POST"> <input type="text" name="username" /> <form:error name="username"> <input type="password" name="password" /> <input type="email" name="email" /> </form> {% endformfill %} will be rendered like below: .. code-block:: html <form action="/register" method="POST"> <input type="text" name="username" class="error" value="robert" /> <span class="error-message">This name is invalid</span> <input type="password" name="password" value="" /> <input type="email" name="email" value="robert153@usrobots.com" /> </form> **Syntax:** .. code-block:: jinja {% formfill <defaults> [with <errors>] %} body {% endformfill %} :param defaults: a :term:`mapping` that contains default values of the input field (including ``select`` and ``textarea``) surrounded in the template tag. Keys contain a value of ``name`` attribute of the input field, and values contain its default value. :param errors: a :term:`mapping` that contains error messages of the input fields. this value will also effect ``class`` attribute of the input field. :returns: rendered forms This extension provides the additional variables in the Jinja2 environment: .. attribute:: jinja2.Environment.formfill_config The default rendering configuration of the ``formfill`` tag. This property accepts the same arguments of :func:`formencode.htmlfill.render`, except ``form``, ``defaults``, ``errors`` and ``error_formatters``. .. attribute:: jinja2.Environment.formfill_error_formatters The :term:`mapping` of error formatters and its name. Formatters are functions or callable objects that take the error text as a single argument, and returns a formatted text as a string. .. seealso:: http://www.formencode.org/en/latest/htmlfill.html#errors """ tags = frozenset(['formfill']) def __init__(self, environment): super(FormFillExtension, self).__init__(environment) environment.extend( formfill_config={}, formfill_error_formatters=dict(DEFAULT_ERROR_FORMATTERS), ) def parse(self, parser): token = next(parser.stream) defaults = parser.parse_expression() if parser.stream.skip_if('name:with'): errors = parser.parse_expression() else: errors = nodes.Const({}) body = parser.parse_statements(['name:endformfill'], drop_needle=True) return nodes.CallBlock( self.call_method('_formfill_support', [defaults, errors]), [], [], body).set_lineno(token.lineno) def _formfill_support(self, defaults, errors, caller): if isinstance(defaults, jinja2.runtime.Undefined): defaults = {} if isinstance(errors, jinja2.runtime.Undefined): errors = {} if not isinstance(defaults, collections.Mapping): raise TypeError("argument 'defaults' should be " "collections.Mapping, not {0!r}".format(defaults)) if not isinstance(errors, collections.Mapping): raise TypeError("argument 'errors' should be collections.Mapping, " "not {0!r}".format(errors)) rv = caller() return formencode.htmlfill.render( rv, defaults, errors, error_formatters=self.environment.formfill_error_formatters, **self.environment.formfill_config)
class FormFillExtension(jinja2.ext.Extension): '''Jinja2 extension for filling HTML forms via :mod:`formencode.htmlfill`. For example, this code: .. code-block:: html+jinja {% formfill {'username': 'robert', 'email': 'robert153@usrobots.com'} with {'username': 'This name is invalid'} %} <form action="/register" method="POST"> <input type="text" name="username" /> <form:error name="username"> <input type="password" name="password" /> <input type="email" name="email" /> </form> {% endformfill %} will be rendered like below: .. code-block:: html <form action="/register" method="POST"> <input type="text" name="username" class="error" value="robert" /> <span class="error-message">This name is invalid</span> <input type="password" name="password" value="" /> <input type="email" name="email" value="robert153@usrobots.com" /> </form> **Syntax:** .. code-block:: jinja {% formfill <defaults> [with <errors>] %} body {% endformfill %} :param defaults: a :term:`mapping` that contains default values of the input field (including ``select`` and ``textarea``) surrounded in the template tag. Keys contain a value of ``name`` attribute of the input field, and values contain its default value. :param errors: a :term:`mapping` that contains error messages of the input fields. this value will also effect ``class`` attribute of the input field. :returns: rendered forms This extension provides the additional variables in the Jinja2 environment: .. attribute:: jinja2.Environment.formfill_config The default rendering configuration of the ``formfill`` tag. This property accepts the same arguments of :func:`formencode.htmlfill.render`, except ``form``, ``defaults``, ``errors`` and ``error_formatters``. .. attribute:: jinja2.Environment.formfill_error_formatters The :term:`mapping` of error formatters and its name. Formatters are functions or callable objects that take the error text as a single argument, and returns a formatted text as a string. .. seealso:: http://www.formencode.org/en/latest/htmlfill.html#errors ''' def __init__(self, environment): pass def parse(self, parser): pass def _formfill_support(self, defaults, errors, caller): pass
4
1
11
0
11
0
3
1.31
1
5
0
0
3
0
3
11
101
20
35
10
31
46
24
10
20
5
1
1
8
143,978
Kroisse/FormEncode-Jinja2
Kroisse_FormEncode-Jinja2/setup.py
setup.PyTest
class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) exit(errno)
class PyTest(TestCommand): def finalize_options(self): pass def run_tests(self): pass
3
0
4
0
4
0
1
0
1
0
0
0
2
2
2
2
10
1
9
7
5
0
9
7
5
1
1
0
2
143,979
Kroisse/FormEncode-Jinja2
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kroisse_FormEncode-Jinja2/formencode_jinja2/test_formfill.py
formencode_jinja2.test_formfill.test_with_expr.Form
class Form(object): defaults = {'username': 'john doe'} errors = {'username': 'Invalid Username'}
class Form(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
143,980
Krokop/python-xmlstats
Krokop_python-xmlstats/xmlstats/__init__.py
xmlstats.XMLStats
class XMLStats: def __init__(self, access_token, email): self.access_token = access_token self.user_agent = "python-xmlstats/{version} ({email})".format(email=email, version=__version__) def make_request(self, host, sport, method, id, format, parameters): url = self._build_url(host, sport, method, id, format, parameters) req = request.Request(url) req.add_header("Authorization", "Bearer " + self.access_token) # Set user agent req.add_header("User-agent", self.user_agent) # Tell server we can handle gzipped content req.add_header("Accept-encoding", "gzip") try: response = request.urlopen(req) except request.HTTPError as err: if err.code == 429: future = int(err.headers['xmlstats-api-reset']) now = int(datetime.now().strftime('%s')) delta = future-now print('wait {0} sec'.format(delta)) sleep(delta) return self.make_request(host, sport, method, id, format, parameters) raise ServerError( "Server returned {code} error code!\n{message}".format( code=err.code, message=json.loads(err.read().decode('utf-8'))), err.code) except request.URLError as err: raise UrlError( "Error retrieving file: {}".format( err.reason)) data = None if "gzip" == response.info().get("Content-encoding"): buf = io.BytesIO(response.read()) f = gzip.GzipFile(fileobj=buf) data = f.read() else: data = response.read() return json.loads(data.decode('utf-8')) def _build_url(self, host, sport, method, id, format, parameters): """ build url from args """ path = "/".join(filter(None, (sport, method, id))) url = "https://" + host + "/" + path + "." + format if parameters: paramstring = urllib.parse.urlencode(parameters) url = url + "?" + paramstring return url def get_teams(self): """ Return json current roster of team """ return self.make_request(host="erikberg.com", sport='nba', method="teams", id=None, format="json", parameters={})
class XMLStats: def __init__(self, access_token, email): pass def make_request(self, host, sport, method, id, format, parameters): pass def _build_url(self, host, sport, method, id, format, parameters): ''' build url from args ''' pass def get_teams(self): ''' Return json current roster of team ''' pass
5
2
15
1
12
2
2
0.12
0
9
2
0
4
2
4
4
64
8
50
20
45
6
39
19
34
5
0
2
9
143,981
Krokop/python-xmlstats
Krokop_python-xmlstats/xmlstats/__init__.py
xmlstats.UrlError
class UrlError(Exception): """ raise when url error """ pass
class UrlError(Exception): ''' raise when url error ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
10
5
0
2
1
1
3
2
1
1
0
3
0
0
143,982
Krokop/python-xmlstats
Krokop_python-xmlstats/xmlstats/__init__.py
xmlstats.ServerError
class ServerError(Exception): """ raise when take error from server """ pass
class ServerError(Exception): ''' raise when take error from server ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
10
5
0
2
1
1
3
2
1
1
0
3
0
0
143,983
Kromey/django-simplecaptcha
Kromey_django-simplecaptcha/simplecaptcha/widgets.py
simplecaptcha.widgets.CaptchaWidget
class CaptchaWidget(forms.widgets.MultiWidget): """The captcha widget generates captcha questions and supplies them to the form Captcha questions are generated by the widget, and the required values put into a set of form fields. Captchas do not rely on any server-side state; instead the answer and the time it was generated are cryptographically hashed and then included in the form itself. Validation simply requires repeating the hashing and verifying that the hash has not expired. """ def __init__(self, attrs=None): """Initialize the various widgets in this MultiWidget""" widgets = ( forms.TextInput(attrs=attrs), forms.HiddenInput(), forms.HiddenInput() ) super().__init__(widgets, attrs) def decompress(self, value): """Don't actually parse out the values, just get ours""" return self._values def format_output(self, rendered_widgets): """All we want to do is stick all the widgets together""" return ''.join(rendered_widgets) def render(self, name, value, attrs=None, renderer=None): """Override the render() method to replace value with our current values This approach is based on the approach that Django's PasswordInput widget uses to ensure that passwords are not re-rendered in forms, except instead of prohibiting initial values we set them to those for our generated captcha. """ value = self._values return super().render(name, value, attrs=attrs, renderer=renderer) def generate_captcha(self): """Generated a fresh captcha This method randomly generates a simple captcha question. It then generates a timestamp for the current time, and signs the answer cryptographically to protect against tampering and replay attacks. """ # Generate a fresh question self._question, answer = self._generate_question() # Get the current time, then sign the answer cryptographically timestamp = time.time() hashed = self.hash_answer(answer, timestamp) # Now stash all our values self._values = ['', timestamp, hashed] def _generate_question(self): """Generate a random arithmetic question This method randomly generates a simple addition, subtraction, or multiplication question with two integers between 1 and 10, and then returns both question (formatted as a string) and answer. """ x = random.randint(1, 10) y = random.randint(1, 10) operator = random.choice(('+', '-', '*',)) if operator == '+': answer = x + y elif operator == '-': # Ensure we'll get a non-negative answer if x < y: x, y = y, x answer = x - y else: # Multiplication is hard, make it easier x = math.ceil(x/2) y = math.ceil(y/2) answer = x * y # Use a prettied-up HTML multiplication character operator = '&times;' # Format the answer nicely, then mark it as safe so Django won't escape it question = '{} {} {}'.format(x, operator, y) return mark_safe(question), answer def hash_answer(self, answer, timestamp): """Cryptographically hash the answer with the provided timestamp This method allows the widget to securely generate time-sensitive signatures that will both prevent tampering with the answer as well as provide some protection against replay attacks by limiting how long a given signature is valid for. Using this same method, the field can validate the submitted answer against the signature also provided in the form. """ # Ensure our values are string before we start hashing timestamp = str(timestamp) answer = str(answer) hashed = '' # Hashing multiple times increases the security of the signature for _ in range(ITERATIONS): # We use Django's own "salted HMAC" for cryptographic signatures hashed = salted_hmac(timestamp, answer).hexdigest() return hashed
class CaptchaWidget(forms.widgets.MultiWidget): '''The captcha widget generates captcha questions and supplies them to the form Captcha questions are generated by the widget, and the required values put into a set of form fields. Captchas do not rely on any server-side state; instead the answer and the time it was generated are cryptographically hashed and then included in the form itself. Validation simply requires repeating the hashing and verifying that the hash has not expired. ''' def __init__(self, attrs=None): '''Initialize the various widgets in this MultiWidget''' pass def decompress(self, value): '''Don't actually parse out the values, just get ours''' pass def format_output(self, rendered_widgets): '''All we want to do is stick all the widgets together''' pass def render(self, name, value, attrs=None, renderer=None): '''Override the render() method to replace value with our current values This approach is based on the approach that Django's PasswordInput widget uses to ensure that passwords are not re-rendered in forms, except instead of prohibiting initial values we set them to those for our generated captcha. ''' pass def generate_captcha(self): '''Generated a fresh captcha This method randomly generates a simple captcha question. It then generates a timestamp for the current time, and signs the answer cryptographically to protect against tampering and replay attacks. ''' pass def _generate_question(self): '''Generate a random arithmetic question This method randomly generates a simple addition, subtraction, or multiplication question with two integers between 1 and 10, and then returns both question (formatted as a string) and answer. ''' pass def hash_answer(self, answer, timestamp): '''Cryptographically hash the answer with the provided timestamp This method allows the widget to securely generate time-sensitive signatures that will both prevent tampering with the answer as well as provide some protection against replay attacks by limiting how long a given signature is valid for. Using this same method, the field can validate the submitted answer against the signature also provided in the form. ''' pass
8
8
13
2
6
5
2
1
1
3
0
0
7
2
7
7
106
18
44
20
36
44
38
20
30
4
1
2
11
143,984
Kromey/django-simplecaptcha
Kromey_django-simplecaptcha/simplecaptcha/fields.py
simplecaptcha.fields.CaptchaField
class CaptchaField(forms.MultiValueField): """A field that contains and validates a simple catcha question WARNING: If you use this field directly in your own forms, you may be caught by surprise by the fact that Django forms rely upon class object rather than instance objects for its fields. This means that your captcha will not be updated when you instantiate a new form, and you'll end up asking your users the same question over and over -- largely defeating the purpose of a captcha! To solve this, either use the @decorator instead, or be sure to call upon the widget to update its captcha question. """ widget = CaptchaWidget def __init__(self, *args, **kwargs): """Sets up the MultiValueField""" fields = ( forms.CharField(), forms.CharField(), forms.CharField(), ) super().__init__(fields, *args, **kwargs) def compress(self, data_list): """Validates the captcha answer and returns the result If no data is provided, this method will simply return None. Otherwise, it will validate that the provided answer and timestamp hash to the supplied hash value, and that the timestamp is within the configured time that captchas are considered valid. """ if data_list: # Calculate the hash of the supplied values hashed = self.widget.hash_answer(answer=data_list[0], timestamp=data_list[1]) # Current time timestamp = time.time() if float(data_list[1]) < timestamp - DURATION: raise ValidationError("Captcha expired, please try again", code='invalid') elif hashed != data_list[2]: raise ValidationError("Incorrect answer", code='invalid') # Return the supplied answer return data_list[0] else: return None @property def label(self): """The captcha field's label is the captcha question itself""" return self.widget._question @label.setter def label(self, value): """The question is generated by the widget and cannot be externally set""" pass
class CaptchaField(forms.MultiValueField): '''A field that contains and validates a simple catcha question WARNING: If you use this field directly in your own forms, you may be caught by surprise by the fact that Django forms rely upon class object rather than instance objects for its fields. This means that your captcha will not be updated when you instantiate a new form, and you'll end up asking your users the same question over and over -- largely defeating the purpose of a captcha! To solve this, either use the @decorator instead, or be sure to call upon the widget to update its captcha question. ''' def __init__(self, *args, **kwargs): '''Sets up the MultiValueField''' pass def compress(self, data_list): '''Validates the captcha answer and returns the result If no data is provided, this method will simply return None. Otherwise, it will validate that the provided answer and timestamp hash to the supplied hash value, and that the timestamp is within the configured time that captchas are considered valid. ''' pass @property def label(self): '''The captcha field's label is the captcha question itself''' pass @label.setter def label(self): '''The question is generated by the widget and cannot be externally set''' pass
7
5
9
1
6
3
2
0.81
1
2
0
0
4
0
4
4
55
8
26
11
19
21
18
9
13
4
1
2
7
143,985
Kronuz/pyScss
Kronuz_pyScss/conftest.py
conftest.SassFile
class SassFile(pytest.File): def collect(self): parent_name = self.fspath.dirpath().basename if not fontforge and parent_name == 'fonts': pytest.skip("font tests require fontforge") if hasattr(SassItem, "from_parent"): yield SassItem.from_parent(parent=self, name=str(self.fspath)) else: yield SassItem(str(self.fspath), self)
class SassFile(pytest.File): def collect(self): pass
2
0
9
1
8
0
3
0
1
2
1
0
1
0
1
1
10
1
9
3
7
0
8
3
6
3
1
1
3
143,986
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.ArgspecLiteral
class ArgspecLiteral(Expression): """Contains pairs of argument names and values, as parsed from a function definition or function call. Note that the semantics are somewhat ambiguous. Consider parsing: $foo, $bar: 3 If this appeared in a function call, $foo would refer to a value; if it appeared in a function definition, $foo would refer to an existing variable. This it's up to the caller to use the right iteration function. """ def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, repr(self.argpairs)) def __init__(self, argpairs, slurp=None): # argpairs is a list of 2-tuples, parsed as though this were a function # call, so (variable name as string or None, default value as AST # node). # slurp is the name of a variable to receive slurpy arguments. self.argpairs = tuple(argpairs) if slurp is all: # DEVIATION: special syntax to allow injecting arbitrary arguments # from the caller to the callee self.inject = True self.slurp = None elif slurp: self.inject = False self.slurp = Variable(slurp) else: self.inject = False self.slurp = None def iter_list_argspec(self): yield None, ListLiteral(zip(*self.argpairs)[1]) def iter_def_argspec(self): """Interpreting this literal as a function definition, yields pairs of (variable name as a string, default value as an AST node or None). """ started_kwargs = False seen_vars = set() for var, value in self.argpairs: if var is None: # value is actually the name var = value value = None if started_kwargs: raise SyntaxError( "Required argument %r must precede optional arguments" % (var.name,)) else: started_kwargs = True if not isinstance(var, Variable): raise SyntaxError("Expected variable name, got %r" % (var,)) if var.name in seen_vars: raise SyntaxError("Duplicate argument %r" % (var.name,)) seen_vars.add(var.name) yield var.name, value def evaluate_call_args(self, calculator): """Interpreting this literal as a function call, return a 2-tuple of ``(args, kwargs)``. """ args = [] kwargs = OrderedDict() # Sass kwargs preserve order for var_node, value_node in self.argpairs: value = value_node.evaluate(calculator, divide=True) if var_node is None: # Positional args.append(value) else: # Named if not isinstance(var_node, Variable): raise TypeError( "Expected variable name, got {0!r}".format(var_node)) kwargs[var_node.name] = value # Slurpy arguments go on the end of the args if self.slurp: args.extend(self.slurp.evaluate(calculator, divide=True)) return args, kwargs
class ArgspecLiteral(Expression): '''Contains pairs of argument names and values, as parsed from a function definition or function call. Note that the semantics are somewhat ambiguous. Consider parsing: $foo, $bar: 3 If this appeared in a function call, $foo would refer to a value; if it appeared in a function definition, $foo would refer to an existing variable. This it's up to the caller to use the right iteration function. ''' def __repr__(self): pass def __init__(self, argpairs, slurp=None): pass def iter_list_argspec(self): pass def iter_def_argspec(self): '''Interpreting this literal as a function definition, yields pairs of (variable name as a string, default value as an AST node or None). ''' pass def evaluate_call_args(self, calculator): '''Interpreting this literal as a function call, return a 2-tuple of ``(args, kwargs)``. ''' pass
6
3
15
2
10
3
3
0.5
1
8
2
0
5
3
5
7
89
15
50
16
44
25
43
16
37
6
2
3
16
143,987
Kronuz/pyScss
Kronuz_pyScss/scss/namespace.py
scss.namespace.ImportScope
class ImportScope(Scope): pass
class ImportScope(Scope): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
8
2
0
2
1
1
0
2
1
1
0
2
0
0
143,988
Kronuz/pyScss
Kronuz_pyScss/scss/namespace.py
scss.namespace.FunctionScope
class FunctionScope(Scope): def __repr__(self): return "<%s(%s) at 0x%x>" % (type(self).__name__, ', '.join('[%s]' % ', '.join('%s:%s' % (f, n) for f, n in sorted(map.keys())) for map in self.maps), id(self))
class FunctionScope(Scope): def __repr__(self): pass
2
0
2
0
2
0
1
0
1
2
0
0
1
0
1
9
3
0
3
3
1
0
3
2
1
1
2
0
1
143,989
Kronuz/pyScss
Kronuz_pyScss/scss/less2scss.py
scss.less2scss.Less2Scss
class Less2Scss(object): at_re = re.compile(r'@(?!(media|import|mixin|font-face)(\s|\())') mixin_re = re.compile(r'\.([\w\-]*)\s*\((.*)\)\s*\{') include_re = re.compile(r'(\s|^)\.([\w\-]*\(?.*\)?;)') functions_map = { 'spin': 'adjust-hue', } functions_re = re.compile(r'(%s)\(' % '|'.join(functions_map)) def convert(self, content): content = self.convertVariables(content) content = self.convertMixins(content) content = self.includeMixins(content) content = self.convertFunctions(content) return content def convertVariables(self, content): # Matches any @ that doesn't have 'media ' or 'import ' after it. content = self.at_re.sub('$', content) return content def convertMixins(self, content): content = self.mixin_re.sub('@mixin \1(\2) {', content) return content def includeMixins(self, content): content = self.mixin_re.sub('\1@include \2', content) return content def convertFunctions(self, content): content = self.functions_re.sub(lambda m: '%s(' % self.functions_map[m.group(0)], content) return content
class Less2Scss(object): def convert(self, content): pass def convertVariables(self, content): pass def convertMixins(self, content): pass def includeMixins(self, content): pass def convertFunctions(self, content): pass
6
0
4
0
4
0
1
0.04
1
0
0
0
5
0
5
5
32
5
26
11
20
1
24
11
18
1
1
0
5
143,990
Kronuz/pyScss
Kronuz_pyScss/scss/legacy.py
scss.legacy.Scss
class Scss(object): """Original programmatic interface to the compiler. This class is now DEPRECATED. See :mod:`scss.compiler` for the replacement. """ def __init__( self, scss_vars=None, scss_opts=None, scss_files=None, super_selector='', live_errors=False, library=None, func_registry=None, search_paths=None): self.super_selector = super_selector self._scss_vars = {} if scss_vars: calculator = Calculator() for var_name, value in scss_vars.items(): if isinstance(value, six.string_types): scss_value = calculator.evaluate_expression(value) if scss_value is None: # TODO warning? scss_value = String.unquoted(value) else: scss_value = value self._scss_vars[var_name] = scss_value self._scss_opts = scss_opts or {} self._scss_files = scss_files self._library = func_registry or library self._search_paths = search_paths # If true, swallow compile errors and embed them in the output instead self.live_errors = live_errors def compile( self, scss_string=None, scss_file=None, source_files=None, super_selector=None, filename=None, is_sass=None, line_numbers=True, import_static_css=False): """Compile Sass to CSS. Returns a single CSS string. This method is DEPRECATED; see :mod:`scss.compiler` instead. """ # Derive our root namespace self.scss_vars = _default_scss_vars.copy() if self._scss_vars is not None: self.scss_vars.update(self._scss_vars) root_namespace = Namespace( variables=self.scss_vars, functions=self._library, ) # Figure out search paths. Fall back from provided explicitly to # defined globally to just searching the current directory search_paths = ['.'] if self._search_paths is not None: assert not isinstance(self._search_paths, six.string_types), \ "`search_paths` should be an iterable, not a string" search_paths.extend(self._search_paths) else: if config.LOAD_PATHS: if isinstance(config.LOAD_PATHS, six.string_types): # Back-compat: allow comma-delimited search_paths.extend(config.LOAD_PATHS.split(',')) else: search_paths.extend(config.LOAD_PATHS) search_paths.extend(self._scss_opts.get('load_paths', [])) # Normalize a few old styles of options output_style = self._scss_opts.get('style', config.STYLE) if output_style is True: output_style = 'compressed' elif output_style is False: output_style = 'legacy' fixed_search_path = [] for path in search_paths: if isinstance(path, six.string_types): fixed_search_path.append(Path(path)) else: fixed_search_path.append(path) # Build the compiler compiler = Compiler( namespace=root_namespace, extensions=[ CoreExtension, ExtraExtension, FontsExtension, CompassExtension, BootstrapExtension, ], search_path=fixed_search_path, import_static_css=import_static_css, live_errors=self.live_errors, generate_source_map=self._scss_opts.get('debug_info', False), output_style=output_style, warn_unused_imports=self._scss_opts.get('warn_unused', False), ignore_parse_errors=config.DEBUG, loops_have_own_scopes=config.CONTROL_SCOPING, undefined_variables_fatal=config.FATAL_UNDEFINED, super_selector=super_selector or self.super_selector, ) # Gonna add the source files manually compilation = compiler.make_compilation() # Inject the files we know about # TODO how does this work with the expectation of absoluteness if source_files is not None: for source in source_files: compilation.add_source(source) elif scss_string is not None: source = SourceFile.from_string( scss_string, relpath=filename, is_sass=is_sass, ) compilation.add_source(source) elif scss_file is not None: # This is now the only way to allow forcibly overriding the # filename a source "thinks" it is with open(scss_file, 'rb') as f: source = SourceFile.from_file( f, relpath=filename or scss_file, is_sass=is_sass, ) compilation.add_source(source) # Plus the ones from the constructor if self._scss_files: for name, contents in list(self._scss_files.items()): source = SourceFile.from_string(contents, relpath=name) compilation.add_source(source) compiled = compiler.call_and_catch_errors(compilation.run) self.source_files = list(SourceFileTuple(*os.path.split(s.path)) for s in compilation.source_index.values()) return compiled # Old, old alias Compilation = compile def get_scss_constants(self): scss_vars = self.root_namespace.variables return dict( (k, v) for k, v in scss_vars.items() if k and (not k.startswith('$') or k[1].isupper()) ) def get_scss_vars(self): scss_vars = self.root_namespace.variables return dict( (k, v) for k, v in scss_vars.items() if k and not (not k.startswith('$') and k[1].isupper()) )
class Scss(object): '''Original programmatic interface to the compiler. This class is now DEPRECATED. See :mod:`scss.compiler` for the replacement. ''' def __init__( self, scss_vars=None, scss_opts=None, scss_files=None, super_selector='', live_errors=False, library=None, func_registry=None, search_paths=None): pass def compile( self, scss_string=None, scss_file=None, source_files=None, super_selector=None, filename=None, is_sass=None, line_numbers=True, import_static_css=False): '''Compile Sass to CSS. Returns a single CSS string. This method is DEPRECATED; see :mod:`scss.compiler` instead. ''' pass def get_scss_constants(self): pass def get_scss_vars(self): pass
5
2
36
4
29
4
6
0.19
1
13
10
0
4
9
4
4
157
19
116
38
104
22
65
30
60
15
1
4
22
143,991
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.AnyOp
class AnyOp(Expression): def __repr__(self): return '<%s(*%s)>' % (self.__class__.__name__, repr(self.operands)) def __init__(self, *operands): self.operands = operands def evaluate(self, calculator, divide=False): for operand in self.operands: value = operand.evaluate(calculator, divide=True) if value: return value return value
class AnyOp(Expression): def __repr__(self): pass def __init__(self, *operands): pass def evaluate(self, calculator, divide=False): pass
4
0
3
0
3
0
2
0
1
0
0
0
3
1
3
5
13
2
11
7
7
0
11
7
7
3
2
2
5
143,992
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.AlphaFunctionLiteral
class AlphaFunctionLiteral(Expression): """Wraps an existing AST node in a literal (unevaluated) function call, prepending "opacity=" to the contents. """ def __init__(self, child): self.child = child def evaluate(self, calculator, divide=False): child = self.child.evaluate(calculator, divide) if isinstance(child, String): contents = child.value else: # TODO compress contents = child.render() return Function('opacity=' + contents, 'alpha', quotes=None)
class AlphaFunctionLiteral(Expression): '''Wraps an existing AST node in a literal (unevaluated) function call, prepending "opacity=" to the contents. ''' def __init__(self, child): pass def evaluate(self, calculator, divide=False): pass
3
1
5
0
5
1
2
0.4
1
2
2
0
2
1
2
4
15
1
10
6
7
4
9
6
6
2
2
1
3
143,993
Kronuz/pyScss
Kronuz_pyScss/scss/grammar/scanner.py
scss.grammar.scanner.Parser
class Parser(object): def __init__(self, scanner): self._scanner = scanner self._pos = 0 self._char_pos = 0 def reset(self, input): self._scanner.reset(input) self._pos = 0 self._char_pos = 0 def _peek(self, types): """ Returns the token type for lookahead; if there are any args then the list of args is the set of token types to allow """ tok = self._scanner.token(self._pos, types) return tok[2] def _scan(self, type): """ Returns the matched text, and moves to the next token """ tok = self._scanner.token(self._pos, frozenset([type])) self._char_pos = tok[0] if tok[2] != type: raise SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to find " + type)) self._pos += 1 return tok[3]
class Parser(object): def __init__(self, scanner): pass def reset(self, input): pass def _peek(self, types): ''' Returns the token type for lookahead; if there are any args then the list of args is the set of token types to allow ''' pass def _scan(self, type): ''' Returns the matched text, and moves to the next token ''' pass
5
2
6
0
5
2
1
0.37
1
2
0
1
4
3
4
4
29
3
19
10
14
7
19
10
14
2
1
1
5
143,994
Kronuz/pyScss
Kronuz_pyScss/scss/grammar/expression.py
scss.grammar.expression.SassExpressionScanner
class SassExpressionScanner(Scanner): patterns = None _patterns = [ ('"="', '='), ('":"', ':'), ('","', ','), ('SINGLE_STRING_GUTS', "([^'\\\\#]|[\\\\].|#(?![{]))*"), ('DOUBLE_STRING_GUTS', '([^"\\\\#]|[\\\\].|#(?![{]))*'), ('INTERP_ANYTHING', '([^#]|#(?![{]))*'), ('INTERP_NO_VARS', '([^#$]|#(?![{]))*'), ('INTERP_NO_PARENS', '([^#()]|#(?![{]))*'), ('INTERP_START_URL_HACK', '(?=[#][{])'), ('INTERP_START', '#[{]'), ('SPACE', '[ \r\t\n]+'), ('[ \r\t\n]+', '[ \r\t\n]+'), ('LPAR', '\\(|\\['), ('RPAR', '\\)|\\]'), ('END', '$'), ('MUL', '[*]'), ('DIV', '/'), ('MOD', '(?<=\\s)%'), ('ADD', '[+]'), ('SUB', '-\\s'), ('SIGN', '-(?![a-zA-Z_])'), ('AND', '(?<![-\\w])and(?![-\\w])'), ('OR', '(?<![-\\w])or(?![-\\w])'), ('NOT', '(?<![-\\w])not(?![-\\w])'), ('NE', '!='), ('INV', '!'), ('EQ', '=='), ('LE', '<='), ('GE', '>='), ('LT', '<'), ('GT', '>'), ('DOTDOTDOT', '[.]{3}'), ('SINGLE_QUOTE', "'"), ('DOUBLE_QUOTE', '"'), ('BAREURL_HEAD_HACK', '((?:[\\\\].|[^#$\'"()\\x00-\\x08\\x0b\\x0e-\\x20\\x7f]|#(?![{]))+)(?=#[{]|\\s*[)])'), ('BAREURL', '(?:[\\\\].|[^#$\'"()\\x00-\\x08\\x0b\\x0e-\\x20\\x7f]|#(?![{]))+'), ('UNITS', '(?<!\\s)(?:[a-zA-Z]+|%)(?![-\\w])'), ('NUM', '(?:\\d+(?:\\.\\d*)?|\\.\\d+)'), ('COLOR', '#(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})(?![a-fA-F0-9])'), ('KWVAR', '\\$[-a-zA-Z0-9_]+(?=\\s*:)'), ('SLURPYVAR', '\\$[-a-zA-Z0-9_]+(?=[.][.][.])'), ('VAR', '\\$[-a-zA-Z0-9_]+'), ('LITERAL_FUNCTION', '(-moz-calc|-webkit-calc|calc|expression|progid:[\\w.]+)(?=[(])'), ('ALPHA_FUNCTION', 'alpha(?=[(])'), ('OPACITY', '(?i)(opacity)'), ('URL_FUNCTION', 'url(?=[(])'), ('IF_FUNCTION', 'if(?=[(])'), ('FNCT', '[-a-zA-Z_][-a-zA-Z0-9_]*(?=\\()'), ('BAREWORD', '(?!\\d)(\\\\[0-9a-fA-F]{1,6}|\\\\.|[-a-zA-Z0-9_])+'), ('BANG_IMPORTANT', '!\\s*important'), ('INTERP_END', '[}]'), ] def __init__(self, input=None): if hasattr(self, 'setup_patterns'): self.setup_patterns(self._patterns) elif self.patterns is None: self.__class__.patterns = [] for t, p in self._patterns: self.patterns.append((t, re.compile(p))) super(SassExpressionScanner, self).__init__(None, ['[ \r\t\n]+'], input)
class SassExpressionScanner(Scanner): def __init__(self, input=None): pass
2
0
8
0
8
0
4
0.16
1
1
0
0
1
0
1
1
64
1
63
5
61
10
10
5
8
4
1
2
4
143,995
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.AllOp
class AllOp(Expression): def __repr__(self): return '<%s(*%s)>' % (self.__class__.__name__, repr(self.operands)) def __init__(self, *operands): self.operands = operands def evaluate(self, calculator, divide=False): for operand in self.operands: value = operand.evaluate(calculator, divide=True) if not value: return value return value
class AllOp(Expression): def __repr__(self): pass def __init__(self, *operands): pass def evaluate(self, calculator, divide=False): pass
4
0
3
0
3
0
2
0
1
0
0
0
3
1
3
5
13
2
11
7
7
0
11
7
7
3
2
2
5
143,996
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Undefined
class Undefined(Null): sass_type_name = 'undefined' def __init__(self, value=None): pass def __add__(self, other): return self def __radd__(self, other): return self def __sub__(self, other): return self def __rsub__(self, other): return self def __div__(self, other): return self def __rdiv__(self, other): return self def __truediv__(self, other): return self def __rtruediv__(self, other): return self def __floordiv__(self, other): return self def __rfloordiv__(self, other): return self def __mul__(self, other): return self def __rmul__(self, other): return self def __pos__(self): return self def __neg__(self): return self
class Undefined(Null): def __init__(self, value=None): pass def __add__(self, other): pass def __radd__(self, other): pass def __sub__(self, other): pass def __rsub__(self, other): pass def __div__(self, other): pass def __rdiv__(self, other): pass def __truediv__(self, other): pass def __rtruediv__(self, other): pass def __floordiv__(self, other): pass def __rfloordiv__(self, other): pass def __mul__(self, other): pass def __rmul__(self, other): pass def __pos__(self): pass def __neg__(self): pass
16
0
2
0
2
0
1
0
1
0
0
0
15
0
15
49
47
15
32
17
16
0
32
17
16
1
3
0
15
143,997
Kronuz/pyScss
Kronuz_pyScss/scss/src/build.py
build.build_ext
class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) self.build_temp = './' self.build_lib = '../grammar/'
class build_ext(_build_ext): def finalize_options(self): pass
2
0
4
0
4
0
1
0
1
0
0
0
1
2
1
49
5
0
5
4
3
0
5
4
3
1
2
0
1
143,998
Kronuz/pyScss
Kronuz_pyScss/conftest.py
conftest.SassItem
class SassItem(pytest.Item): """A Sass test input file, collected as its own test item. A file of the same name but with a .css extension is assumed to contain the expected output. """ _nodeid = None @property def nodeid(self): # Rig the nodeid to be "directory::filename", so all the files in the # same directory are treated as grouped together if not self._nodeid: self._nodeid = "{0}::{1}".format( self.fspath.dirpath().relto(self.session.fspath), self.fspath.basename, ) return self._nodeid def reportinfo(self): return ( self.fspath.dirpath(), None, self.fspath.relto(self.session.fspath), ) def _prunetraceback(self, excinfo): # Traceback implements __getitem__, but list implements __getslice__, # which wins in Python 2 excinfo.traceback = excinfo.traceback.cut(__file__) def runtest(self): scss_file = Path(str(self.fspath)) css_file = scss_file.with_suffix('.css') with css_file.open('rb') as fh: # Output is Unicode, so decode this here expected = fh.read().decode('utf8') scss.config.STATIC_ROOT = str(scss_file.parent / 'static') search_path = [] include = scss_file.parent / 'include' if include.exists(): search_path.append(include) search_path.append(scss_file.parent) try: actual = compile_file( scss_file, output_style='expanded', search_path=search_path, extensions=[ CoreExtension, ExtraExtension, FontsExtension, CompassExtension, ], ) except SassEvaluationError as e: # Treat any missing dependencies (PIL not installed, fontforge not # installed) as skips # TODO this is slightly cumbersome and sorta defeats the purpose of # having separate exceptions if isinstance(e.exc, SassMissingDependency): pytest.skip(e.format_message()) else: raise # Normalize leading and trailing newlines actual = actual.strip('\n') expected = expected.strip('\n') assert expected == actual
class SassItem(pytest.Item): '''A Sass test input file, collected as its own test item. A file of the same name but with a .css extension is assumed to contain the expected output. ''' @property def nodeid(self): pass def reportinfo(self): pass def _prunetraceback(self, excinfo): pass def runtest(self): pass
6
1
16
2
12
3
2
0.29
1
8
6
0
4
0
4
4
74
11
49
15
43
14
30
12
25
4
1
2
8
143,999
Kronuz/pyScss
Kronuz_pyScss/scss/grammar/expression.py
scss.grammar.expression.SassExpression
class SassExpression(Parser): def goal(self): expr_lst = self.expr_lst() END = self._scan('END') return expr_lst def goal_argspec(self): argspec = self.argspec() END = self._scan('END') return argspec def argspec(self): _token_ = self._peek(self.argspec_rsts) if _token_ not in self.argspec_chks: if self._peek(self.argspec_rsts_) not in self.argspec_chks_: argspec_items = self.argspec_items() args, slurpy = argspec_items return ArgspecLiteral(args, slurp=slurpy) return ArgspecLiteral([]) elif _token_ == 'SLURPYVAR': SLURPYVAR = self._scan('SLURPYVAR') DOTDOTDOT = self._scan('DOTDOTDOT') return ArgspecLiteral([], slurp=SLURPYVAR) else: # == 'DOTDOTDOT' DOTDOTDOT = self._scan('DOTDOTDOT') return ArgspecLiteral([], slurp=all) def argspec_items(self): slurpy = None argspec_item = self.argspec_item() args = [argspec_item] if self._peek(self.argspec_items_rsts) == '","': self._scan('","') if self._peek(self.argspec_items_rsts_) not in self.argspec_chks_: _token_ = self._peek(self.argspec_items_rsts__) if _token_ == 'SLURPYVAR': SLURPYVAR = self._scan('SLURPYVAR') DOTDOTDOT = self._scan('DOTDOTDOT') slurpy = SLURPYVAR elif _token_ == 'DOTDOTDOT': DOTDOTDOT = self._scan('DOTDOTDOT') slurpy = all else: # in self.argspec_items_chks argspec_items = self.argspec_items() more_args, slurpy = argspec_items args.extend(more_args) return args, slurpy def argspec_item(self): _token_ = self._peek(self.argspec_items_chks) if _token_ == 'KWVAR': KWVAR = self._scan('KWVAR') self._scan('":"') expr_slst = self.expr_slst() return (Variable(KWVAR), expr_slst) else: # in self.argspec_item_chks expr_slst = self.expr_slst() return (None, expr_slst) def expr_map_or_list(self): expr_slst = self.expr_slst() first = expr_slst _token_ = self._peek(self.expr_map_or_list_rsts) if _token_ == '":"': self._scan('":"') expr_slst = self.expr_slst() pairs = [(first, expr_slst)] while self._peek(self.expr_map_or_list_rsts_) == '","': self._scan('","') map_item = None, None if self._peek(self.expr_map_or_list_rsts__) not in self.expr_map_or_list_rsts_: map_item = self.map_item() pairs.append(map_item) return MapLiteral(pairs) else: # in self.expr_map_or_list_rsts_ items = [first]; use_list = False while self._peek(self.expr_map_or_list_rsts_) == '","': self._scan('","') use_list = True expr_slst = self.expr_slst() items.append(expr_slst) return ListLiteral(items) if use_list else items[0] def map_item(self): expr_slst = self.expr_slst() left = expr_slst self._scan('":"') expr_slst = self.expr_slst() return (left, expr_slst) def expr_lst(self): expr_slst = self.expr_slst() v = [expr_slst] while self._peek(self.expr_lst_rsts) == '","': self._scan('","') expr_slst = self.expr_slst() v.append(expr_slst) return ListLiteral(v) if len(v) > 1 else v[0] def expr_slst(self): or_expr = self.or_expr() v = [or_expr] while self._peek(self.expr_slst_rsts) not in self.expr_slst_chks: or_expr = self.or_expr() v.append(or_expr) return ListLiteral(v, comma=False) if len(v) > 1 else v[0] def or_expr(self): and_expr = self.and_expr() v = and_expr while self._peek(self.or_expr_rsts) == 'OR': OR = self._scan('OR') and_expr = self.and_expr() v = AnyOp(v, and_expr) return v def and_expr(self): not_expr = self.not_expr() v = not_expr while self._peek(self.and_expr_rsts) == 'AND': AND = self._scan('AND') not_expr = self.not_expr() v = AllOp(v, not_expr) return v def not_expr(self): _token_ = self._peek(self.argspec_item_chks) if _token_ != 'NOT': comparison = self.comparison() return comparison else: # == 'NOT' NOT = self._scan('NOT') not_expr = self.not_expr() return NotOp(not_expr) def comparison(self): a_expr = self.a_expr() v = a_expr while self._peek(self.comparison_rsts) in self.comparison_chks: _token_ = self._peek(self.comparison_chks) if _token_ == 'LT': LT = self._scan('LT') a_expr = self.a_expr() v = BinaryOp(operator.lt, v, a_expr) elif _token_ == 'GT': GT = self._scan('GT') a_expr = self.a_expr() v = BinaryOp(operator.gt, v, a_expr) elif _token_ == 'LE': LE = self._scan('LE') a_expr = self.a_expr() v = BinaryOp(operator.le, v, a_expr) elif _token_ == 'GE': GE = self._scan('GE') a_expr = self.a_expr() v = BinaryOp(operator.ge, v, a_expr) elif _token_ == 'EQ': EQ = self._scan('EQ') a_expr = self.a_expr() v = BinaryOp(operator.eq, v, a_expr) else: # == 'NE' NE = self._scan('NE') a_expr = self.a_expr() v = BinaryOp(operator.ne, v, a_expr) return v def a_expr(self): m_expr = self.m_expr() v = m_expr while self._peek(self.a_expr_rsts) in self.a_expr_chks: _token_ = self._peek(self.a_expr_chks) if _token_ == 'ADD': ADD = self._scan('ADD') m_expr = self.m_expr() v = BinaryOp(operator.add, v, m_expr) else: # == 'SUB' SUB = self._scan('SUB') m_expr = self.m_expr() v = BinaryOp(operator.sub, v, m_expr) return v def m_expr(self): u_expr = self.u_expr() v = u_expr while self._peek(self.m_expr_rsts) in self.m_expr_chks: _token_ = self._peek(self.m_expr_chks) if _token_ == 'MUL': MUL = self._scan('MUL') u_expr = self.u_expr() v = BinaryOp(operator.mul, v, u_expr) elif _token_ == 'DIV': DIV = self._scan('DIV') u_expr = self.u_expr() v = BinaryOp(operator.truediv, v, u_expr) else: # == 'MOD' MOD = self._scan('MOD') u_expr = self.u_expr() v = BinaryOp(operator.mod, v, u_expr) return v def u_expr(self): _token_ = self._peek(self.u_expr_rsts) if _token_ == 'SIGN': SIGN = self._scan('SIGN') u_expr = self.u_expr() return UnaryOp(operator.neg, u_expr) elif _token_ == 'ADD': ADD = self._scan('ADD') u_expr = self.u_expr() return UnaryOp(operator.pos, u_expr) else: # in self.u_expr_chks atom = self.atom() return atom def atom(self): _token_ = self._peek(self.u_expr_chks) if _token_ == 'LPAR': LPAR = self._scan('LPAR') _token_ = self._peek(self.atom_rsts) if _token_ == 'RPAR': v = ListLiteral([], comma=False) else: # in self.argspec_item_chks expr_map_or_list = self.expr_map_or_list() v = expr_map_or_list RPAR = self._scan('RPAR') return Parentheses(v) elif _token_ == 'URL_FUNCTION': URL_FUNCTION = self._scan('URL_FUNCTION') LPAR = self._scan('LPAR') interpolated_url = self.interpolated_url() RPAR = self._scan('RPAR') return interpolated_url elif _token_ == 'ALPHA_FUNCTION': ALPHA_FUNCTION = self._scan('ALPHA_FUNCTION') LPAR = self._scan('LPAR') _token_ = self._peek(self.atom_rsts_) if _token_ == 'OPACITY': OPACITY = self._scan('OPACITY') self._scan('"="') atom = self.atom() RPAR = self._scan('RPAR') return AlphaFunctionLiteral(atom) else: # in self.atom_chks argspec = self.argspec() RPAR = self._scan('RPAR') return CallOp("alpha", argspec) elif _token_ == 'IF_FUNCTION': IF_FUNCTION = self._scan('IF_FUNCTION') LPAR = self._scan('LPAR') expr_lst = self.expr_lst() RPAR = self._scan('RPAR') return TernaryOp(expr_lst) elif _token_ == 'LITERAL_FUNCTION': LITERAL_FUNCTION = self._scan('LITERAL_FUNCTION') LPAR = self._scan('LPAR') interpolated_function = self.interpolated_function() RPAR = self._scan('RPAR') return Interpolation.maybe(interpolated_function, type=Function, function_name=LITERAL_FUNCTION) elif _token_ == 'FNCT': FNCT = self._scan('FNCT') LPAR = self._scan('LPAR') argspec = self.argspec() RPAR = self._scan('RPAR') return CallOp(FNCT, argspec) elif _token_ == 'BANG_IMPORTANT': BANG_IMPORTANT = self._scan('BANG_IMPORTANT') return Literal(String.unquoted("!important", literal=True)) elif _token_ in self.atom_chks_: interpolated_bareword = self.interpolated_bareword() return Interpolation.maybe(interpolated_bareword) elif _token_ == 'NUM': NUM = self._scan('NUM') UNITS = None if self._peek(self.atom_rsts__) == 'UNITS': UNITS = self._scan('UNITS') return Literal(Number(float(NUM), unit=UNITS)) elif _token_ not in self.atom_chks__: interpolated_string = self.interpolated_string() return interpolated_string elif _token_ == 'COLOR': COLOR = self._scan('COLOR') return Literal(Color.from_hex(COLOR, literal=True)) else: # == 'VAR' VAR = self._scan('VAR') return Variable(VAR) def interpolation(self): INTERP_START = self._scan('INTERP_START') expr_lst = self.expr_lst() INTERP_END = self._scan('INTERP_END') return expr_lst def interpolated_url(self): _token_ = self._peek(self.interpolated_url_rsts) if _token_ in self.interpolated_url_chks: interpolated_bare_url = self.interpolated_bare_url() return Interpolation.maybe(interpolated_bare_url, type=Url, quotes=None) else: # in self.argspec_item_chks expr_lst = self.expr_lst() return FunctionLiteral(expr_lst, "url") def interpolated_bare_url(self): _token_ = self._peek(self.interpolated_url_chks) if _token_ == 'BAREURL_HEAD_HACK': BAREURL_HEAD_HACK = self._scan('BAREURL_HEAD_HACK') parts = [BAREURL_HEAD_HACK] else: # == 'INTERP_START_URL_HACK' INTERP_START_URL_HACK = self._scan('INTERP_START_URL_HACK') parts = [''] while self._peek(self.interpolated_bare_url_rsts) == 'INTERP_START': interpolation = self.interpolation() parts.append(interpolation) _token_ = self._peek(self.interpolated_bare_url_rsts_) if _token_ == 'BAREURL': BAREURL = self._scan('BAREURL') parts.append(BAREURL) elif _token_ == 'SPACE': SPACE = self._scan('SPACE') return parts else: # in self.interpolated_bare_url_rsts parts.append('') return parts def interpolated_string(self): _token_ = self._peek(self.interpolated_string_rsts) if _token_ == 'SINGLE_QUOTE': interpolated_string_single = self.interpolated_string_single() return Interpolation.maybe(interpolated_string_single, quotes="'") else: # == 'DOUBLE_QUOTE' interpolated_string_double = self.interpolated_string_double() return Interpolation.maybe(interpolated_string_double, quotes='"') def interpolated_string_single(self): SINGLE_QUOTE = self._scan('SINGLE_QUOTE') SINGLE_STRING_GUTS = self._scan('SINGLE_STRING_GUTS') parts = [unescape(SINGLE_STRING_GUTS)] while self._peek(self.interpolated_string_single_rsts) == 'INTERP_START': interpolation = self.interpolation() parts.append(interpolation) SINGLE_STRING_GUTS = self._scan('SINGLE_STRING_GUTS') parts.append(unescape(SINGLE_STRING_GUTS)) SINGLE_QUOTE = self._scan('SINGLE_QUOTE') return parts def interpolated_string_double(self): DOUBLE_QUOTE = self._scan('DOUBLE_QUOTE') DOUBLE_STRING_GUTS = self._scan('DOUBLE_STRING_GUTS') parts = [unescape(DOUBLE_STRING_GUTS)] while self._peek(self.interpolated_string_double_rsts) == 'INTERP_START': interpolation = self.interpolation() parts.append(interpolation) DOUBLE_STRING_GUTS = self._scan('DOUBLE_STRING_GUTS') parts.append(unescape(DOUBLE_STRING_GUTS)) DOUBLE_QUOTE = self._scan('DOUBLE_QUOTE') return parts def interpolated_bareword(self): _token_ = self._peek(self.atom_chks_) if _token_ == 'BAREWORD': BAREWORD = self._scan('BAREWORD') parts = [BAREWORD] if self._peek(self.interpolated_bareword_rsts) == 'SPACE': SPACE = self._scan('SPACE') return parts else: # == 'INTERP_START' interpolation = self.interpolation() parts = ['', interpolation] _token_ = self._peek(self.interpolated_bareword_rsts_) if _token_ == 'BAREWORD': BAREWORD = self._scan('BAREWORD') parts.append(BAREWORD) elif _token_ == 'SPACE': SPACE = self._scan('SPACE') return parts elif 1: parts.append('') while self._peek(self.interpolated_bareword_rsts__) == 'INTERP_START': interpolation = self.interpolation() parts.append(interpolation) _token_ = self._peek(self.interpolated_bareword_rsts_) if _token_ == 'BAREWORD': BAREWORD = self._scan('BAREWORD') parts.append(BAREWORD) elif _token_ == 'SPACE': SPACE = self._scan('SPACE') return parts elif 1: parts.append('') return parts def interpolated_function(self): interpolated_function_parens = self.interpolated_function_parens() parts = interpolated_function_parens while self._peek(self.interpolated_bare_url_rsts) == 'INTERP_START': interpolation = self.interpolation() parts.append(interpolation) interpolated_function_parens = self.interpolated_function_parens() parts.extend(interpolated_function_parens) return parts def interpolated_function_parens(self): INTERP_NO_PARENS = self._scan('INTERP_NO_PARENS') parts = [INTERP_NO_PARENS] while self._peek(self.interpolated_function_parens_rsts) == 'LPAR': LPAR = self._scan('LPAR') interpolated_function = self.interpolated_function() parts = parts[:-1] + [parts[-1] + LPAR + interpolated_function[0]] + interpolated_function[1:] RPAR = self._scan('RPAR') INTERP_NO_PARENS = self._scan('INTERP_NO_PARENS') parts[-1] += RPAR + INTERP_NO_PARENS return parts def goal_interpolated_literal(self): INTERP_ANYTHING = self._scan('INTERP_ANYTHING') parts = [INTERP_ANYTHING] while self._peek(self.goal_interpolated_literal_rsts) == 'INTERP_START': interpolation = self.interpolation() parts.append(interpolation) INTERP_ANYTHING = self._scan('INTERP_ANYTHING') parts.append(INTERP_ANYTHING) END = self._scan('END') return Interpolation.maybe(parts) def goal_interpolated_literal_with_vars(self): INTERP_NO_VARS = self._scan('INTERP_NO_VARS') parts = [INTERP_NO_VARS] while self._peek(self.goal_interpolated_literal_with_vars_rsts) != 'END': _token_ = self._peek(self.goal_interpolated_literal_with_vars_rsts_) if _token_ == 'INTERP_START': interpolation = self.interpolation() parts.append(interpolation) else: # == 'VAR' VAR = self._scan('VAR') parts.append(Variable(VAR)) INTERP_NO_VARS = self._scan('INTERP_NO_VARS') parts.append(INTERP_NO_VARS) END = self._scan('END') return Interpolation.maybe(parts) atom_chks_ = frozenset(['BAREWORD', 'INTERP_START']) expr_map_or_list_rsts__ = frozenset(['LPAR', 'RPAR', 'BANG_IMPORTANT', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'DOUBLE_QUOTE', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'NUM', 'VAR', 'FNCT', 'NOT', 'IF_FUNCTION', 'SINGLE_QUOTE', '","']) u_expr_chks = frozenset(['LPAR', 'DOUBLE_QUOTE', 'BANG_IMPORTANT', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'VAR', 'NUM', 'FNCT', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'SINGLE_QUOTE']) m_expr_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'SUB', 'ALPHA_FUNCTION', 'RPAR', 'MUL', 'INTERP_END', 'BANG_IMPORTANT', 'DIV', 'LE', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NE', 'LT', 'NUM', '":"', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'GT', 'END', 'SIGN', 'BAREWORD', 'GE', 'FNCT', 'VAR', 'EQ', 'AND', 'ADD', 'SINGLE_QUOTE', 'NOT', 'MOD', 'OR', '","']) interpolated_bare_url_rsts_ = frozenset(['RPAR', 'INTERP_START', 'BAREURL', 'SPACE']) argspec_items_rsts = frozenset(['RPAR', 'END', '","']) expr_slst_chks = frozenset(['INTERP_END', 'RPAR', 'END', '":"', '","']) expr_lst_rsts = frozenset(['INTERP_END', 'RPAR', 'END', '","']) goal_interpolated_literal_rsts = frozenset(['END', 'INTERP_START']) expr_map_or_list_rsts = frozenset(['RPAR', '":"', '","']) goal_interpolated_literal_with_vars_rsts = frozenset(['VAR', 'END', 'INTERP_START']) argspec_item_chks = frozenset(['LPAR', 'DOUBLE_QUOTE', 'BANG_IMPORTANT', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'NUM', 'VAR', 'FNCT', 'NOT', 'IF_FUNCTION', 'SINGLE_QUOTE']) a_expr_chks = frozenset(['ADD', 'SUB']) interpolated_function_parens_rsts = frozenset(['LPAR', 'RPAR', 'INTERP_START']) expr_slst_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'ALPHA_FUNCTION', 'RPAR', 'INTERP_END', 'BANG_IMPORTANT', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NUM', '":"', 'BAREWORD', 'IF_FUNCTION', 'END', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'FNCT', 'VAR', 'NOT', 'SINGLE_QUOTE', '","']) interpolated_bareword_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'SUB', 'ALPHA_FUNCTION', 'RPAR', 'MUL', 'INTERP_END', 'BANG_IMPORTANT', 'DIV', 'LE', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NE', 'LT', 'NUM', '":"', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'GT', 'END', 'SPACE', 'SIGN', 'BAREWORD', 'GE', 'FNCT', 'VAR', 'EQ', 'AND', 'ADD', 'SINGLE_QUOTE', 'NOT', 'MOD', 'OR', '","']) atom_rsts__ = frozenset(['LPAR', 'DOUBLE_QUOTE', 'SUB', 'ALPHA_FUNCTION', 'RPAR', 'VAR', 'MUL', 'INTERP_END', 'BANG_IMPORTANT', 'DIV', 'LE', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NE', 'LT', 'NUM', '":"', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'GT', 'END', 'SIGN', 'BAREWORD', 'GE', 'FNCT', 'UNITS', 'EQ', 'AND', 'ADD', 'SINGLE_QUOTE', 'NOT', 'MOD', 'OR', '","']) or_expr_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'ALPHA_FUNCTION', 'RPAR', 'INTERP_END', 'BANG_IMPORTANT', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NUM', '":"', 'BAREWORD', 'IF_FUNCTION', 'END', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'FNCT', 'VAR', 'OR', 'NOT', 'SINGLE_QUOTE', '","']) argspec_chks_ = frozenset(['END', 'RPAR']) interpolated_string_single_rsts = frozenset(['SINGLE_QUOTE', 'INTERP_START']) interpolated_bareword_rsts_ = frozenset(['LPAR', 'DOUBLE_QUOTE', 'SUB', 'ALPHA_FUNCTION', 'RPAR', 'MUL', 'DIV', 'BANG_IMPORTANT', 'INTERP_END', 'LE', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NE', 'LT', 'NUM', '":"', 'BAREWORD', 'IF_FUNCTION', 'GT', 'END', 'SPACE', 'SIGN', 'LITERAL_FUNCTION', 'GE', 'FNCT', 'VAR', 'EQ', 'AND', 'ADD', 'SINGLE_QUOTE', 'NOT', 'MOD', 'OR', '","']) and_expr_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'ALPHA_FUNCTION', 'RPAR', 'INTERP_END', 'BANG_IMPORTANT', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NUM', '":"', 'BAREWORD', 'IF_FUNCTION', 'END', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'FNCT', 'VAR', 'AND', 'SINGLE_QUOTE', 'NOT', 'OR', '","']) comparison_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'ALPHA_FUNCTION', 'RPAR', 'INTERP_END', 'BANG_IMPORTANT', 'LE', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NE', 'LT', 'NUM', '":"', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'GT', 'END', 'SIGN', 'BAREWORD', 'ADD', 'FNCT', 'VAR', 'EQ', 'AND', 'GE', 'SINGLE_QUOTE', 'NOT', 'OR', '","']) argspec_chks = frozenset(['DOTDOTDOT', 'SLURPYVAR']) atom_rsts_ = frozenset(['KWVAR', 'LPAR', 'DOUBLE_QUOTE', 'SLURPYVAR', 'ALPHA_FUNCTION', 'RPAR', 'BANG_IMPORTANT', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NUM', 'BAREWORD', 'IF_FUNCTION', 'END', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'FNCT', 'VAR', 'OPACITY', 'DOTDOTDOT', 'NOT', 'SINGLE_QUOTE']) interpolated_string_double_rsts = frozenset(['DOUBLE_QUOTE', 'INTERP_START']) atom_chks__ = frozenset(['COLOR', 'VAR']) expr_map_or_list_rsts_ = frozenset(['RPAR', '","']) u_expr_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'BANG_IMPORTANT', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'SIGN', 'VAR', 'ADD', 'NUM', 'FNCT', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'SINGLE_QUOTE']) interpolated_url_chks = frozenset(['INTERP_START_URL_HACK', 'BAREURL_HEAD_HACK']) atom_chks = frozenset(['KWVAR', 'LPAR', 'DOUBLE_QUOTE', 'SLURPYVAR', 'ALPHA_FUNCTION', 'RPAR', 'BANG_IMPORTANT', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NUM', 'BAREWORD', 'IF_FUNCTION', 'END', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'FNCT', 'VAR', 'DOTDOTDOT', 'NOT', 'SINGLE_QUOTE']) interpolated_url_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'BANG_IMPORTANT', 'SINGLE_QUOTE', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'NUM', 'VAR', 'FNCT', 'NOT', 'INTERP_START_URL_HACK', 'IF_FUNCTION', 'BAREURL_HEAD_HACK']) comparison_chks = frozenset(['GT', 'GE', 'NE', 'LT', 'LE', 'EQ']) argspec_items_rsts_ = frozenset(['KWVAR', 'LPAR', 'DOUBLE_QUOTE', 'SLURPYVAR', 'ALPHA_FUNCTION', 'RPAR', 'BANG_IMPORTANT', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NUM', 'BAREWORD', 'IF_FUNCTION', 'END', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'FNCT', 'VAR', 'DOTDOTDOT', 'NOT', 'SINGLE_QUOTE']) a_expr_rsts = frozenset(['LPAR', 'DOUBLE_QUOTE', 'SUB', 'ALPHA_FUNCTION', 'RPAR', 'INTERP_END', 'BANG_IMPORTANT', 'LE', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NE', 'LT', 'NUM', '":"', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'GT', 'END', 'SIGN', 'BAREWORD', 'GE', 'FNCT', 'VAR', 'EQ', 'AND', 'ADD', 'SINGLE_QUOTE', 'NOT', 'OR', '","']) interpolated_string_rsts = frozenset(['DOUBLE_QUOTE', 'SINGLE_QUOTE']) interpolated_bareword_rsts__ = frozenset(['LPAR', 'DOUBLE_QUOTE', 'SUB', 'ALPHA_FUNCTION', 'RPAR', 'MUL', 'INTERP_END', 'BANG_IMPORTANT', 'DIV', 'LE', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NE', 'LT', 'NUM', '":"', 'LITERAL_FUNCTION', 'IF_FUNCTION', 'GT', 'END', 'SIGN', 'BAREWORD', 'GE', 'FNCT', 'VAR', 'EQ', 'AND', 'ADD', 'SINGLE_QUOTE', 'NOT', 'MOD', 'OR', '","']) m_expr_chks = frozenset(['MUL', 'DIV', 'MOD']) goal_interpolated_literal_with_vars_rsts_ = frozenset(['VAR', 'INTERP_START']) interpolated_bare_url_rsts = frozenset(['RPAR', 'INTERP_START']) argspec_items_chks = frozenset(['KWVAR', 'LPAR', 'DOUBLE_QUOTE', 'BANG_IMPORTANT', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'NUM', 'VAR', 'FNCT', 'NOT', 'IF_FUNCTION', 'SINGLE_QUOTE']) argspec_rsts = frozenset(['KWVAR', 'LPAR', 'DOUBLE_QUOTE', 'SLURPYVAR', 'ALPHA_FUNCTION', 'RPAR', 'BANG_IMPORTANT', 'URL_FUNCTION', 'INTERP_START', 'COLOR', 'NUM', 'BAREWORD', 'IF_FUNCTION', 'END', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'FNCT', 'VAR', 'DOTDOTDOT', 'NOT', 'SINGLE_QUOTE']) atom_rsts = frozenset(['BANG_IMPORTANT', 'LPAR', 'DOUBLE_QUOTE', 'IF_FUNCTION', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'NUM', 'VAR', 'FNCT', 'NOT', 'RPAR', 'SINGLE_QUOTE']) argspec_items_rsts__ = frozenset(['KWVAR', 'LPAR', 'DOUBLE_QUOTE', 'BANG_IMPORTANT', 'SLURPYVAR', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'DOTDOTDOT', 'INTERP_START', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'NUM', 'VAR', 'FNCT', 'NOT', 'IF_FUNCTION', 'SINGLE_QUOTE']) argspec_rsts_ = frozenset(['KWVAR', 'LPAR', 'DOUBLE_QUOTE', 'IF_FUNCTION', 'END', 'URL_FUNCTION', 'BAREWORD', 'COLOR', 'ALPHA_FUNCTION', 'INTERP_START', 'BANG_IMPORTANT', 'SIGN', 'LITERAL_FUNCTION', 'ADD', 'NUM', 'VAR', 'FNCT', 'NOT', 'RPAR', 'SINGLE_QUOTE'])
class SassExpression(Parser): def goal(self): pass def goal_argspec(self): pass def argspec(self): pass def argspec_items(self): pass def argspec_items(self): pass def expr_map_or_list(self): pass def map_item(self): pass def expr_lst(self): pass def expr_slst(self): pass def or_expr(self): pass def and_expr(self): pass def not_expr(self): pass def comparison(self): pass def a_expr(self): pass def m_expr(self): pass def u_expr(self): pass def atom(self): pass def interpolation(self): pass def interpolated_url(self): pass def interpolated_bare_url(self): pass def interpolated_string(self): pass def interpolated_string_single(self): pass def interpolated_string_double(self): pass def interpolated_bareword(self): pass def interpolated_function(self): pass def interpolated_function_parens(self): pass def goal_interpolated_literal(self): pass def goal_interpolated_literal_with_vars(self): pass
29
0
15
0
15
1
3
0.04
1
22
21
0
28
0
28
32
484
28
456
211
427
18
416
212
387
15
2
3
97
144,000
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Url
class Url(Function): # Bare URLs may not contain quotes, parentheses, or unprintables. Quoted # URLs may, of course, contain whatever they like. # Ref: http://dev.w3.org/csswg/css-syntax-3/#consume-a-url-token0 bad_identifier_rx = re.compile("[$'\"()\\x00-\\x08\\x0b\\x0e-\\x1f\\x7f]") def __init__(self, string, **kwargs): super(Url, self).__init__(string, 'url', **kwargs) def render(self, compress=False): if self.quotes is None: return self.render_interpolated(compress) else: inside = self._render_quoted() return "url(" + inside + ")" def render_interpolated(self, compress=False): # Always render without quotes. # When doing that, we need to escape some stuff to make sure the result # is valid CSS. inside = self.bad_identifier_rx.sub( self._escape_character, self.value) return "url(" + inside + ")"
class Url(Function): def __init__(self, string, **kwargs): pass def render(self, compress=False): pass def render_interpolated(self, compress=False): pass
4
0
5
0
4
1
1
0.43
1
1
0
0
3
0
3
44
24
4
14
7
10
6
12
7
8
2
4
1
4
144,001
Kronuz/pyScss
Kronuz_pyScss/scss/namespace.py
scss.namespace.Namespace
class Namespace(object): """...""" _mutable = True def __init__(self, variables=None, functions=None, mixins=None, mutable=True): self._mutable = mutable if variables is None: self._variables = VariableScope() else: # TODO parse into sass values once that's a thing, or require them # all to be self._variables = VariableScope([variables]) if functions is None: self._functions = FunctionScope() else: self._functions = FunctionScope([functions._functions]) self._mixins = MixinScope() self._imports = ImportScope() def _assert_mutable(self): if not self._mutable: raise AttributeError("This Namespace instance is immutable") @classmethod def derive_from(cls, *others): self = cls() if len(others) == 1: self._variables = others[0]._variables.new_child() self._functions = others[0]._functions.new_child() self._mixins = others[0]._mixins.new_child() self._imports = others[0]._imports.new_child() else: # Note that this will create a 2-dimensional scope where each of # these scopes is checked first in order. TODO is this right? self._variables = VariableScope(other._variables for other in others) self._functions = FunctionScope(other._functions for other in others) self._mixins = MixinScope(other._mixins for other in others) self._imports = ImportScope(other._imports for other in others) return self def derive(self): """Return a new child namespace. All existing variables are still readable and writeable, but any new variables will only exist within a new scope. """ return type(self).derive_from(self) def declare(self, function): """Insert a Python function into this Namespace, detecting its name and argument count automatically. """ self._auto_register_function(function, function.__name__) return function def declare_alias(self, name): """Insert a Python function into this Namespace with an explicitly-given name, but detect its argument count automatically. """ def decorator(f): self._auto_register_function(f, name) return f return decorator def declare_internal(self, function): """Like declare(), but the registered function will also receive the current namespace as its first argument. Useful for functions that inspect the state of the compilation, like ``variable-exists()``. Probably not so useful for anything else. """ function._pyscss_needs_namespace = True self._auto_register_function(function, function.__name__, 1) return function def _auto_register_function(self, function, name, ignore_args=0): name = name.replace('_', '-').rstrip('-') try: argspec = inspect.getfullargspec(function) varkw = argspec.varkw except AttributeError: # In python 2.7, getfulargspec does not exist. # Let's use getargspec as fallback. argspec = inspect.getargspec(function) varkw = argspec.keywords if argspec.varargs or varkw: # Accepts some arbitrary number of arguments arities = [None] else: # Accepts a fixed range of arguments if argspec.defaults: num_optional = len(argspec.defaults) else: num_optional = 0 num_args = len(argspec.args) - ignore_args arities = range(num_args - num_optional, num_args + 1) for arity in arities: self.set_function(name, arity, function) @property def variables(self): return dict((k, self._variables[k]) for k in self._variables.keys()) def variable(self, name, throw=False): name = normalize_var(name) return self._variables[name] def set_variable(self, name, value, local_only=False): self._assert_mutable() name = normalize_var(name) if not isinstance(value, Value): raise TypeError("Expected a Sass type, while setting %s got %r" % (name, value,)) self._variables.set(name, value, force_local=local_only) def has_import(self, source): return source.path in self._imports def add_import(self, source, parent_rule): self._assert_mutable() self._imports[source.path] = [ 0, parent_rule.source_file.path, parent_rule.file_and_line, ] def use_import(self, import_key): self._assert_mutable() if import_key and import_key in self._imports: imports = self._imports[import_key] imports[0] += 1 self.use_import(imports[1]) def unused_imports(self): unused = [] for import_key in self._imports.keys(): imports = self._imports[import_key] if not imports[0]: unused.append((import_key[0], imports[2])) return unused def _get_callable(self, chainmap, name, arity): name = normalize_var(name) if arity is not None: # With explicit arity, try the particular arity before falling back # to the general case (None) try: return chainmap[name, arity] except KeyError: pass return chainmap[name, None] def _set_callable(self, chainmap, name, arity, cb): name = normalize_var(name) chainmap[name, arity] = cb def mixin(self, name, arity): return self._get_callable(self._mixins, name, arity) def set_mixin(self, name, arity, cb): self._assert_mutable() self._set_callable(self._mixins, name, arity, cb) def function(self, name, arity): return self._get_callable(self._functions, name, arity) def set_function(self, name, arity, cb): self._assert_mutable() self._set_callable(self._functions, name, arity, cb)
class Namespace(object): '''...''' def __init__(self, variables=None, functions=None, mixins=None, mutable=True): pass def _assert_mutable(self): pass @classmethod def derive_from(cls, *others): pass def derive_from(cls, *others): '''Return a new child namespace. All existing variables are still readable and writeable, but any new variables will only exist within a new scope. ''' pass def declare(self, function): '''Insert a Python function into this Namespace, detecting its name and argument count automatically. ''' pass def declare_alias(self, name): '''Insert a Python function into this Namespace with an explicitly-given name, but detect its argument count automatically. ''' pass def decorator(f): pass def declare_internal(self, function): '''Like declare(), but the registered function will also receive the current namespace as its first argument. Useful for functions that inspect the state of the compilation, like ``variable-exists()``. Probably not so useful for anything else. ''' pass def _auto_register_function(self, function, name, ignore_args=0): pass @property def variables(self): pass def variables(self): pass def set_variable(self, name, value, local_only=False): pass def has_import(self, source): pass def add_import(self, source, parent_rule): pass def use_import(self, import_key): pass def unused_imports(self): pass def _get_callable(self, chainmap, name, arity): pass def _set_callable(self, chainmap, name, arity, cb): pass def mixin(self, name, arity): pass def set_mixin(self, name, arity, cb): pass def function(self, name, arity): pass def set_function(self, name, arity, cb): pass
25
5
7
0
5
1
2
0.22
1
11
5
0
20
4
21
21
174
29
119
41
94
26
108
39
85
5
1
2
36
144,002
Kronuz/pyScss
Kronuz_pyScss/scss/extension/compass/layouts.py
scss.extension.compass.layouts.PackedSpritesLayout
class PackedSpritesLayout(SpritesLayout): @staticmethod def MAXSIDE(a, b): """maxside: Sort pack by maximum sides""" return cmp(max(b[0], b[1]), max(a[0], a[1])) or cmp(min(b[0], b[1]), min(a[0], a[1])) or cmp(b[1], a[1]) or cmp(b[0], a[0]) @staticmethod def WIDTH(a, b): """width: Sort pack by width""" return cmp(b[0], a[0]) or cmp(b[1], a[1]) @staticmethod def HEIGHT(a, b): """height: Sort pack by height""" return cmp(b[1], a[1]) or cmp(b[0], a[0]) @staticmethod def AREA(a, b): """area: Sort pack by area""" return cmp(b[0] * b[1], a[0] * a[1]) or cmp(b[1], a[1]) or cmp(b[0], a[0]) def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None, methods=None): super(PackedSpritesLayout, self).__init__(blocks, padding, margin, ppadding, pmargin) ratio = 0 if methods is None: methods = (self.MAXSIDE, self.WIDTH, self.HEIGHT, self.AREA) for method in methods: sorted_blocks = sorted( self.blocks, cmp=method, ) root = LayoutNode( x=0, y=0, w=sorted_blocks[0][0] if sorted_blocks else 0, h=sorted_blocks[0][1] if sorted_blocks else 0 ) area = 0 nodes = [None] * self.num_blocks for block in sorted_blocks: w, h, width, height, i = block node = self._findNode(root, w, h) if node: node = self._splitNode(node, w, h) else: root = self._growNode(root, w, h) node = self._findNode(root, w, h) if node: node = self._splitNode(node, w, h) else: node = None nodes[i] = node node.width = width node.height = height area += node.area this_ratio = area / float(root.w * root.h) # print method.__doc__, "%g%%" % (this_ratio * 100) if ratio < this_ratio: self.root = root self.nodes = nodes self.method = method ratio = this_ratio if ratio > 0.96: break # print self.method.__doc__, "%g%%" % (ratio * 100) def __iter__(self): for i, node in enumerate(self.nodes): margin, padding = self.margin[i], self.padding[i] pmargin, ppadding = self.pmargin[i], self.ppadding[i] cssw = node.width + padding[3] + padding[1] + int(round(node.width * (ppadding[3] + ppadding[1]))) # image width plus padding cssh = node.height + padding[0] + padding[2] + int(round(node.height * (ppadding[0] + ppadding[2]))) # image height plus padding cssx = node.x + margin[3] + int(round(node.width * pmargin[3])) cssy = node.y + margin[0] + int(round(node.height * pmargin[0])) x = cssx + padding[3] + int(round(node.width * ppadding[3])) y = cssy + padding[0] + int(round(node.height * ppadding[0])) yield x, y, node.width, node.height, cssx, cssy, cssw, cssh @property def width(self): return self.root.w @property def height(self): return self.root.h def _findNode(self, root, w, h): if root.used: return self._findNode(root.right, w, h) or self._findNode(root.down, w, h) elif w <= root.w and h <= root.h: return root else: return None def _splitNode(self, node, w, h): node.used = True node.down = LayoutNode( x=node.x, y=node.y + h, w=node.w, h=node.h - h ) node.right = LayoutNode( x=node.x + w, y=node.y, w=node.w - w, h=h ) return node def _growNode(self, root, w, h): canGrowDown = w <= root.w canGrowRight = h <= root.h shouldGrowRight = canGrowRight and (root.h >= root.w + w) # attempt to keep square-ish by growing right when height is much greater than width shouldGrowDown = canGrowDown and (root.w >= root.h + h) # attempt to keep square-ish by growing down when width is much greater than height if shouldGrowRight: return self._growRight(root, w, h) elif shouldGrowDown: return self._growDown(root, w, h) elif canGrowRight: return self._growRight(root, w, h) elif canGrowDown: return self._growDown(root, w, h) else: # need to ensure sensible root starting size to avoid this happening assert False, "Blocks must be properly sorted!" def _growRight(self, root, w, h): root = LayoutNode( used=True, x=0, y=0, w=root.w + w, h=root.h, down=root, right=LayoutNode( x=root.w, y=0, w=w, h=root.h ) ) return root def _growDown(self, root, w, h): root = LayoutNode( used=True, x=0, y=0, w=root.w, h=root.h + h, down=LayoutNode( x=0, y=root.h, w=root.w, h=h ), right=root ) return root
class PackedSpritesLayout(SpritesLayout): @staticmethod def MAXSIDE(a, b): '''maxside: Sort pack by maximum sides''' pass @staticmethod def WIDTH(a, b): '''width: Sort pack by width''' pass @staticmethod def HEIGHT(a, b): '''height: Sort pack by height''' pass @staticmethod def AREA(a, b): '''area: Sort pack by area''' pass def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None, methods=None): pass def __iter__(self): pass @property def width(self): pass @property def height(self): pass def _findNode(self, root, w, h): pass def _splitNode(self, node, w, h): pass def _growNode(self, root, w, h): pass def _growRight(self, root, w, h): pass def _growDown(self, root, w, h): pass
20
4
11
1
10
1
2
0.08
1
5
1
0
9
4
13
14
168
20
141
47
121
11
83
40
69
10
2
4
29
144,003
Kronuz/pyScss
Kronuz_pyScss/scss/extension/compass/layouts.py
scss.extension.compass.layouts.SpritesLayout
class SpritesLayout(object): def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None): self.num_blocks = len(blocks) if margin is None: margin = [[0] * 4] * self.num_blocks elif not isinstance(margin, (tuple, list)): margin = [[margin] * 4] * self.num_blocks elif not isinstance(margin[0], (tuple, list)): margin = [margin] * self.num_blocks if padding is None: padding = [[0] * 4] * self.num_blocks elif not isinstance(padding, (tuple, list)): padding = [[padding] * 4] * self.num_blocks elif not isinstance(padding[0], (tuple, list)): padding = [padding] * self.num_blocks if pmargin is None: pmargin = [[0.0] * 4] * self.num_blocks elif not isinstance(pmargin, (tuple, list)): pmargin = [[pmargin] * 4] * self.num_blocks elif not isinstance(pmargin[0], (tuple, list)): pmargin = [pmargin] * self.num_blocks if ppadding is None: ppadding = [[0.0] * 4] * self.num_blocks elif not isinstance(ppadding, (tuple, list)): ppadding = [[ppadding] * 4] * self.num_blocks elif not isinstance(ppadding[0], (tuple, list)): ppadding = [ppadding] * self.num_blocks self.blocks = tuple(( b[0] + padding[i][3] + padding[i][1] + margin[i][3] + margin[i][1] + int(round(b[0] * (ppadding[i][3] + ppadding[i][1] + pmargin[i][3] + pmargin[i][1]))), b[1] + padding[i][0] + padding[i][2] + margin[i][0] + margin[i][2] + int(round(b[1] * (ppadding[i][0] + ppadding[i][2] + pmargin[i][0] + pmargin[i][2]))), b[0], b[1], i ) for i, b in enumerate(blocks)) self.margin = margin self.padding = padding self.pmargin = pmargin self.ppadding = ppadding
class SpritesLayout(object): def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None): pass
2
0
43
6
37
0
13
0
1
4
0
4
1
6
1
1
44
6
38
8
36
0
24
8
22
13
1
1
13
144,004
Kronuz/pyScss
Kronuz_pyScss/scss/extension/compass/layouts.py
scss.extension.compass.layouts.VerticalSpritesLayout
class VerticalSpritesLayout(SpritesLayout): def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None, position=None): super(VerticalSpritesLayout, self).__init__(blocks, padding, margin, ppadding, pmargin) self.width = max(block[0] for block in self.blocks) self.height = sum(block[1] for block in self.blocks) if position is None: position = [0.0] * self.num_blocks elif not isinstance(position, (tuple, list)): position = [position] * self.num_blocks self.position = position def __iter__(self): cy = 0 for i, block in enumerate(self.blocks): w, h, width, height, i = block margin, padding = self.margin[i], self.padding[i] pmargin, ppadding = self.pmargin[i], self.ppadding[i] position = self.position[i] cssw = width + padding[3] + padding[1] + int(round(width * (ppadding[3] + ppadding[1]))) # image width plus padding cssh = height + padding[0] + padding[2] + int(round(height * (ppadding[0] + ppadding[2]))) # image height plus padding cssx = int(round((self.width - cssw) * position)) # centered horizontally cssy = cy + margin[0] + int(round(height * pmargin[0])) # anchored at y x = cssx + padding[3] + int(round(width * ppadding[3])) # image drawn offset to account for padding y = cssy + padding[0] + int(round(height * ppadding[0])) # image drawn offset to account for padding yield x, y, width, height, cssx, cssy, cssw, cssh cy += cssh + margin[0] + margin[2] + int(round(height * (pmargin[0] + pmargin[2])))
class VerticalSpritesLayout(SpritesLayout): def __init__(self, blocks, padding=None, margin=None, ppadding=None, pmargin=None, position=None): pass def __iter__(self): pass
3
0
13
1
12
3
3
0.24
1
5
0
0
2
3
2
3
28
3
25
18
22
6
24
18
21
3
2
1
5
144,005
Kronuz/pyScss
Kronuz_pyScss/scss/extension/core.py
scss.extension.core.CoreExtension
class CoreExtension(Extension): name = 'core' namespace = Namespace() def handle_import(self, name, compilation, rule): """Implementation of the core Sass import mechanism, which just looks for files on disk. """ # TODO this is all not terribly well-specified by Sass. at worst, # it's unclear how far "upwards" we should be allowed to go. but i'm # also a little fuzzy on e.g. how relative imports work from within a # file that's not actually in the search path. # TODO i think with the new origin semantics, i've made it possible to # import relative to the current file even if the current file isn't # anywhere in the search path. is that right? path = PurePosixPath(name) search_exts = list(compilation.compiler.dynamic_extensions) if path.suffix and path.suffix in search_exts: basename = path.stem else: basename = path.name relative_to = path.parent search_path = [] # tuple of (origin, start_from) if relative_to.is_absolute(): relative_to = PurePosixPath(*relative_to.parts[1:]) elif rule.source_file.origin: # Search relative to the current file first, only if not doing an # absolute import search_path.append(( rule.source_file.origin, rule.source_file.relpath.parent / relative_to, )) search_path.extend( (origin, relative_to) for origin in compilation.compiler.search_path ) for prefix, suffix in product(('_', ''), search_exts): filename = prefix + basename + suffix for origin, relative_to in search_path: relpath = relative_to / filename # Lexically (ignoring symlinks!) eliminate .. from the part # of the path that exists within Sass-space. pathlib # deliberately doesn't do this, but os.path does. relpath = PurePosixPath(os.path.normpath(str(relpath))) if rule.source_file.key == (origin, relpath): # Avoid self-import # TODO is this what ruby does? continue path = origin / relpath if not path.exists(): continue # All good! # TODO if this file has already been imported, we'll do the # source preparation twice. make it lazy. return SourceFile.read(origin, relpath)
class CoreExtension(Extension): def handle_import(self, name, compilation, rule): '''Implementation of the core Sass import mechanism, which just looks for files on disk. ''' pass
2
1
56
5
31
21
8
0.62
1
5
1
0
1
0
1
4
60
6
34
12
32
21
26
12
24
8
2
3
8
144,006
Kronuz/pyScss
Kronuz_pyScss/scss/extension/extra.py
scss.extension.extra.ExtraExtension
class ExtraExtension(Extension): """Extra functions unique to the pyScss library.""" name = 'extra' namespace = Namespace()
class ExtraExtension(Extension): '''Extra functions unique to the pyScss library.''' pass
1
1
0
0
0
0
0
0.33
1
0
0
0
0
0
0
3
4
0
3
3
2
1
3
3
2
0
2
0
0
144,007
Kronuz/pyScss
Kronuz_pyScss/scss/extension/fonts.py
scss.extension.fonts.FontsExtension
class FontsExtension(Extension): """Functions for creating and manipulating fonts.""" name = 'fonts' namespace = Namespace()
class FontsExtension(Extension): '''Functions for creating and manipulating fonts.''' pass
1
1
0
0
0
0
0
0.33
1
0
0
0
0
0
0
3
4
0
3
3
2
1
3
3
2
0
2
0
0
144,008
Kronuz/pyScss
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kronuz_pyScss/scss/grammar/scanner.py
scss.grammar.scanner.NoMoreTokens
class NoMoreTokens(Exception): """ Another exception object, for when we run out of tokens """ pass
class NoMoreTokens(Exception): ''' Another exception object, for when we run out of tokens ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
10
5
0
2
1
1
3
2
1
1
0
3
0
0
144,009
Kronuz/pyScss
Kronuz_pyScss/scss/namespace.py
scss.namespace.MixinScope
class MixinScope(Scope): def __repr__(self): return "<%s(%s) at 0x%x>" % (type(self).__name__, ', '.join('[%s]' % ', '.join('%s:%s' % (f, n) for f, n in sorted(map.keys())) for map in self.maps), id(self))
class MixinScope(Scope): def __repr__(self): pass
2
0
2
0
2
0
1
0
1
2
0
0
1
0
1
9
3
0
3
3
1
0
3
2
1
1
2
0
1
144,010
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Boolean
class Boolean(Value): sass_type_name = 'bool' def __init__(self, value): self.value = bool(value) def __str__(self): return 'true' if self.value else 'false' def __hash__(self): return hash(self.value) def __bool__(self): return self.value def render(self, compress=False): if self.value: return 'true' else: return 'false'
class Boolean(Value): def __init__(self, value): pass def __str__(self): pass def __hash__(self): pass def __bool__(self): pass def render(self, compress=False): pass
6
0
3
0
3
0
1
0
1
1
0
0
5
1
5
30
20
5
15
8
9
0
14
8
8
2
2
1
7
144,011
Kronuz/pyScss
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kronuz_pyScss/scss/util.py
scss.util.tmemoize
class tmemoize(object): """ Memoize With Timeout Usage: @tmemoize() def z(a,b): return a + b @tmemoize(timeout=5) def x(a,b): return a + b """ _caches = {} _timeouts = {} _collected = time.time() def __init__(self, timeout=60, gc=3600): self.timeout = timeout self.gc = gc def collect(self): """Clear cache of results which have timed out""" for func in self._caches: cache = {} for key in self._caches[func]: if (time.time() - self._caches[func][key][1]) < self._timeouts[func]: cache[key] = self._caches[func][key] self._caches[func] = cache def __call__(self, func): self._caches[func] = {} self._timeouts[func] = self.timeout @wraps(func) def wrapper(*args): key = args now = time.time() cache = self._caches[func] try: ret, last = cache[key] if now - last > self.timeout: raise KeyError except KeyError: ret, last = cache[key] = (func(*args), now) if now - self._collected > self.gc: self.collect() self._collected = time.time() return ret return wrapper
class tmemoize(object): ''' Memoize With Timeout Usage: @tmemoize() def z(a,b): return a + b @tmemoize(timeout=5) def x(a,b): return a + b ''' def __init__(self, timeout=60, gc=3600): pass def collect(self): '''Clear cache of results which have timed out''' pass def __call__(self, func): pass @wraps(func) def wrapper(*args): pass
6
2
11
0
11
0
3
0.33
1
1
0
0
3
2
3
3
50
6
33
18
27
11
32
17
27
4
1
3
10
144,012
Kronuz/pyScss
Kronuz_pyScss/scss/rule.py
scss.rule.BlockHeader
class BlockHeader(object): """...""" # TODO doc me depending on how UnparsedBlock is handled... is_atrule = False is_scope = False is_selector = False @classmethod def parse(cls, prop, has_contents=False): num_lines = prop.count('\n') prop = prop.strip() # Simple pre-processing if prop.startswith('+') and not has_contents: # Expand '+' at the beginning of a rule as @include. But not if # there's a block, because that's probably a CSS selector. # DEVIATION: this is some semi hybrid of Sass and xCSS syntax prop = '@include ' + prop[1:] try: if '(' not in prop or prop.index(':') < prop.index('('): prop = prop.replace(':', '(', 1) if '(' in prop: prop += ')' except ValueError: pass elif prop.startswith('='): # Expand '=' at the beginning of a rule as @mixin prop = '@mixin ' + prop[1:] elif prop.startswith('@prototype '): # Remove '@prototype ' # TODO what is @prototype?? prop = prop[11:] # Minor parsing if prop.startswith('@'): # This pattern MUST NOT BE ABLE TO FAIL! # This is slightly more lax than the CSS syntax technically allows, # e.g. identifiers aren't supposed to begin with three hyphens. # But we don't care, and will just spit it back out anyway. m = re.match( '@(else if|[-_a-zA-Z0-9\U00000080-\U0010FFFF]*)\\b', prop, re.I) directive = m.group(0).lower() argument = prop[len(directive):].strip() if not argument: argument = None return BlockAtRuleHeader(directive, argument, num_lines) elif prop.split(None, 1)[0].endswith(':'): # Syntax is "<scope>: [prop]" -- if the optional prop exists, it # becomes the first rule with no suffix scope, unscoped_value = prop.split(':', 1) scope = scope.rstrip() unscoped_value = unscoped_value.lstrip() return BlockScopeHeader(scope, unscoped_value, num_lines) else: return BlockSelectorHeader(prop, num_lines)
class BlockHeader(object): '''...''' @classmethod def parse(cls, prop, has_contents=False): pass
3
1
48
2
32
14
10
0.43
1
4
3
3
0
0
1
1
57
4
37
11
34
16
30
10
28
10
1
4
10
144,013
Kronuz/pyScss
Kronuz_pyScss/setup.py
setup.ve_build_ext
class ve_build_ext(build_ext): """This class allows C extension building to fail.""" def run(self): try: build_ext.run(self) except DistutilsPlatformError: raise BuildFailed() def build_extension(self, ext): try: build_ext.build_extension(self, ext) except ext_errors: raise BuildFailed() except ValueError: # this can happen on Windows 64 bit, see Python issue 7511 if "'path'" in str(sys.exc_info()[1]): # works with Python 2 and 3 raise BuildFailed() raise
class ve_build_ext(build_ext): '''This class allows C extension building to fail.''' def run(self): pass def build_extension(self, ext): pass
3
1
8
0
7
1
3
0.2
1
4
1
0
2
0
2
50
19
2
15
3
12
3
15
3
12
4
2
2
6
144,014
Kronuz/pyScss
Kronuz_pyScss/scss/rule.py
scss.rule.BlockAtRuleHeader
class BlockAtRuleHeader(BlockHeader): is_atrule = True def __init__(self, directive, argument, num_lines=0): self.directive = directive self.argument = argument self.num_lines = num_lines def __repr__(self): return "<%s %r %r>" % (type(self).__name__, self.directive, self.argument) def render(self): if self.argument: return "%s %s" % (self.directive, self.argument) else: return self.directive
class BlockAtRuleHeader(BlockHeader): def __init__(self, directive, argument, num_lines=0): pass def __repr__(self): pass def render(self): pass
4
0
4
0
4
0
1
0
1
1
0
0
3
3
3
4
17
4
13
8
9
0
12
8
8
2
2
1
4
144,015
Kronuz/pyScss
Kronuz_pyScss/scss/namespace.py
scss.namespace.VariableScope
class VariableScope(Scope): pass
class VariableScope(Scope): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
8
2
0
2
1
1
0
2
1
1
0
2
0
0
144,016
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.BinaryOp
class BinaryOp(Expression): OPERATORS = { operator.lt: '<', operator.gt: '>', operator.le: '<=', operator.ge: '>=', operator.eq: '==', operator.eq: '!=', operator.add: '+', operator.sub: '-', operator.mul: '*', operator.truediv: '/', operator.mod: '%', } def __repr__(self): return '<%s(%s, %s, %s)>' % (self.__class__.__name__, repr(self.op), repr(self.left), repr(self.right)) def __init__(self, op, left, right): self.op = op self.left = left self.right = right def evaluate(self, calculator, divide=False): left = self.left.evaluate(calculator, divide=True) right = self.right.evaluate(calculator, divide=True) # Determine whether to actually evaluate, or just print the operator # literally. literal = False # If either operand starts with an interpolation, treat the whole # shebang as literal. if any(isinstance(operand, Interpolation) and operand.parts[0] == '' for operand in (self.left, self.right)): literal = True # Special handling of division: treat it as a literal slash if both # operands are literals, there are no parentheses, and this isn't part # of a bigger expression. # The first condition is covered by the type check. The other two are # covered by the `divide` argument: other nodes that perform arithmetic # will pass in True, indicating that this should always be a division. elif ( self.op is operator.truediv and not divide and isinstance(self.left, Literal) and isinstance(self.right, Literal) ): literal = True if literal: # TODO we don't currently preserve the spacing, whereas Sass # remembers whether there was space on either side op = " {0} ".format(self.OPERATORS[self.op]) return String.unquoted(left.render() + op + right.render()) return self.op(left, right)
class BinaryOp(Expression): def __repr__(self): pass def __init__(self, op, left, right): pass def evaluate(self, calculator, divide=False): pass
4
0
14
2
8
4
2
0.32
1
3
3
0
3
3
3
5
58
8
38
12
34
12
19
12
15
4
2
1
6
144,017
Kronuz/pyScss
Kronuz_pyScss/scss/namespace.py
scss.namespace.Scope
class Scope(object): """Implements Sass variable scoping. Similar to `ChainMap`, except that assigning a new value will replace an existing value, not mask it. """ def __init__(self, maps=()): maps = list(maps) self.maps = [dict()] + maps def __repr__(self): return "<%s(%s) at 0x%x>" % (type(self).__name__, ', '.join(repr(map) for map in self.maps), id(self)) def __getitem__(self, key): for map in self.maps: if key in map: return map[key] raise KeyError(key) def __setitem__(self, key, value): self.set(key, value) def __contains__(self, key): for map in self.maps: if key in map: return True return False def keys(self): # For mapping interface keys = set() for map in self.maps: keys.update(map.keys()) return list(keys) def set(self, key, value, force_local=False): if not force_local: for map in self.maps: if key in map: if isinstance(map[key], Undefined): break map[key] = value return self.maps[0][key] = value def new_child(self): return type(self)(self.maps)
class Scope(object): '''Implements Sass variable scoping. Similar to `ChainMap`, except that assigning a new value will replace an existing value, not mask it. ''' def __init__(self, maps=()): pass def __repr__(self): pass def __getitem__(self, key): pass def __setitem__(self, key, value): pass def __contains__(self, key): pass def keys(self): pass def set(self, key, value, force_local=False): pass def new_child(self): pass
9
1
5
0
4
0
2
0.15
1
7
1
4
8
1
8
8
49
10
34
16
25
5
34
15
25
5
1
4
17
144,018
Kronuz/pyScss
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kronuz_pyScss/scss/tool.py
scss.tool.watch_sources.ScssEventHandler
class ScssEventHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): super(ScssEventHandler, self).__init__(*args, **kwargs) self.css = Scss(scss_opts={ 'style': options.style, 'debug_info': options.debug_info, }, search_paths=options.load_paths, ) self.output = options.output self.suffix = options.suffix def is_valid(self, path): return os.path.isfile(path) and (path.endswith('.scss') or path.endswith('.sass')) and not os.path.basename(path).startswith('_') def process(self, path): if os.path.isdir(path): for f in os.listdir(path): full = os.path.join(path, f) if self.is_valid(full): self.compile(full) elif self.is_valid(path): self.compile(path) def compile(self, src_path): fname = os.path.basename(src_path) if fname.endswith('.scss') or fname.endswith('.sass'): fname = fname[:-5] if self.suffix: fname += '.' + self.suffix fname += '.css' else: # you didn't give me a file of the correct type! return False if self.output: dest_path = os.path.join(self.output, fname) else: dest_path = os.path.join(os.path.dirname(src_path), fname) print("Compiling %s => %s" % (src_path, dest_path)) dest_file = open(dest_path, 'wb') dest_file.write(self.css.compile( scss_file=src_path).encode('utf-8')) def on_moved(self, event): super(ScssEventHandler, self).on_moved(event) self.process(event.dest_path) def on_created(self, event): super(ScssEventHandler, self).on_created(event) self.process(event.src_path) def on_modified(self, event): super(ScssEventHandler, self).on_modified(event) self.process(event.src_path)
class ScssEventHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): pass def is_valid(self, path): pass def process(self, path): pass def compile(self, src_path): pass def on_moved(self, event): pass def on_created(self, event): pass def on_modified(self, event): pass
8
0
7
0
6
0
2
0.02
1
2
1
0
7
3
7
7
55
8
46
16
38
1
38
16
30
5
1
3
14
144,019
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.CallOp
class CallOp(Expression): def __repr__(self): return '<%s(%s, %s)>' % (self.__class__.__name__, repr(self.func_name), repr(self.argspec)) def __init__(self, func_name, argspec): self.func_name = func_name self.argspec = argspec def evaluate(self, calculator, divide=False): # TODO bake this into the context and options "dicts", plus library func_name = normalize_var(self.func_name) argspec_node = self.argspec # Turn the pairs of arg tuples into *args and **kwargs # TODO unclear whether this is correct -- how does arg, kwarg, arg # work? args, kwargs = argspec_node.evaluate_call_args(calculator) argspec_len = len(args) + len(kwargs) # Translate variable names to Python identifiers # TODO what about duplicate kw names? should this happen in argspec? # how does that affect mixins? kwargs = dict( (key.lstrip('$').replace('-', '_'), value) for key, value in kwargs.items()) # TODO merge this with the library funct = None try: funct = calculator.namespace.function(func_name, argspec_len) except KeyError: try: # DEVIATION: Fall back to single parameter funct = calculator.namespace.function(func_name, 1) args = [List(args, use_comma=True)] except KeyError: if not is_builtin_css_function(func_name): log.error("Function not found: %s:%s", func_name, argspec_len, extra={'stack': True}) if funct: if getattr(funct, '_pyscss_needs_namespace', False): # @functions and some Python functions take the namespace as an # extra first argument ret = funct(calculator.namespace, *args, **kwargs) else: ret = funct(*args, **kwargs) if not isinstance(ret, Value): raise TypeError("Expected Sass type as return value, got %r" % (ret,)) return ret # No matching function found, so render the computed values as a CSS # function call. Slurpy arguments are expanded and named arguments are # unsupported. if kwargs: raise TypeError("The CSS function %s doesn't support keyword arguments." % (func_name,)) # TODO another candidate for a "function call" sass type rendered_args = [arg.render() for arg in args] return String( "%s(%s)" % (func_name, ", ".join(rendered_args)), quotes=None)
class CallOp(Expression): def __repr__(self): pass def __init__(self, func_name, argspec): pass def evaluate(self, calculator, divide=False): pass
4
0
20
3
12
5
3
0.39
1
6
3
0
3
2
3
5
63
10
38
13
34
15
33
13
29
8
2
3
10
144,020
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.Literal
class Literal(Expression): def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, repr(self.value)) def __init__(self, value): self.value = value @classmethod def from_bareword(cls, word): if word in COLOR_NAMES: value = Color.from_name(word) elif word == 'null': value = Null() elif word == 'undefined': value = Undefined() elif word == 'true': value = Boolean(True) elif word == 'false': value = Boolean(False) else: value = String(word, quotes=None) return cls(value) def evaluate(self, calculator, divide=False): if (isinstance(self.value, Undefined) and calculator.undefined_variables_fatal): raise SyntaxError("Undefined literal.") return self.value
class Literal(Expression): def __repr__(self): pass def __init__(self, value): pass @classmethod def from_bareword(cls, word): pass def evaluate(self, calculator, divide=False): pass
6
0
6
1
6
0
3
0
1
6
5
0
3
1
4
6
30
5
25
8
19
0
18
7
13
6
2
1
10
144,021
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.Interpolation
class Interpolation(Expression): """A string that may contain any number of interpolations: foo#{...}bar#{...}baz """ def __init__(self, parts, quotes=None, type=String, **kwargs): self.parts = parts self.quotes = quotes self.type = type self.kwargs = kwargs def __repr__(self): repr_parts = [] for i, part in enumerate(self.parts): if i % 2 == 0: if part: repr_parts.append(repr(part)) else: repr_parts.append('#{' + repr(part) + '}') return "<{0} {1}>".format(type(self).__name__, " ".join(repr_parts)) @classmethod def maybe(cls, parts, quotes=None, type=String, **kwargs): """Returns an interpolation if there are multiple parts, otherwise a plain Literal. This keeps the AST somewhat simpler, but also is the only way `Literal.from_bareword` gets called. """ if len(parts) > 1: return cls(parts, quotes=quotes, type=type, **kwargs) if quotes is None and type is String: return Literal.from_bareword(parts[0]) return Literal(type(parts[0], quotes=quotes, **kwargs)) def evaluate(self, calculator, divide=False): result = [] for i, part in enumerate(self.parts): if i % 2 == 0: # First part and other odd parts are literal string result.append(part) else: # Interspersed (even) parts are nodes value = part.evaluate(calculator, divide) # TODO need to know whether to pass `compress` here result.append(value.render_interpolated()) return self.type(''.join(result), quotes=self.quotes, **self.kwargs)
class Interpolation(Expression): '''A string that may contain any number of interpolations: foo#{...}bar#{...}baz ''' def __init__(self, parts, quotes=None, type=String, **kwargs): pass def __repr__(self): pass @classmethod def maybe(cls, parts, quotes=None, type=String, **kwargs): '''Returns an interpolation if there are multiple parts, otherwise a plain Literal. This keeps the AST somewhat simpler, but also is the only way `Literal.from_bareword` gets called. ''' pass def evaluate(self, calculator, divide=False): pass
6
2
10
1
7
2
3
0.35
1
4
2
0
3
4
4
6
49
8
31
15
25
11
28
14
23
4
2
3
11
144,022
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Number
class Number(Value): sass_type_name = 'number' def __init__(self, amount, unit=None, unit_numer=(), unit_denom=()): if isinstance(amount, Number): assert not unit and not unit_numer and not unit_denom self.value = amount.value self.unit_numer = amount.unit_numer self.unit_denom = amount.unit_denom return # Numbers with units are stored internally as a "base" unit, which can # involve float division, which can lead to precision errors in obscure # cases. Storing the original units would only partially solve this # problem, because there'd still be a possible loss of precision when # converting in Sass-land. Almost all of the conversion factors are # simple ratios of small whole numbers, so using Fraction across the # board preserves as much precision as possible. # TODO in fact, i wouldn't mind parsing Sass values as fractions of a # power of ten! # TODO this slowed the test suite down by about 10%, ha if isinstance(amount, (int, float)): amount = Fraction.from_float(amount) elif isinstance(amount, Fraction): pass else: raise TypeError("Expected number, got %r" % (amount,)) if unit is not None: unit_numer = unit_numer + (unit.lower(),) # Cancel out any convertable units on the top and bottom numerator_base_units = count_base_units(unit_numer) denominator_base_units = count_base_units(unit_denom) # Count which base units appear both on top and bottom cancelable_base_units = {} for unit, count in numerator_base_units.items(): cancelable_base_units[unit] = min( count, denominator_base_units.get(unit, 0)) # Actually remove the units numer_factor, unit_numer = cancel_base_units(unit_numer, cancelable_base_units) denom_factor, unit_denom = cancel_base_units(unit_denom, cancelable_base_units) # And we're done self.unit_numer = tuple(unit_numer) self.unit_denom = tuple(unit_denom) self.value = amount * (numer_factor / denom_factor) def __repr__(self): value = self.value int_value = int(value) if value == int_value: value = int_value full_unit = ' * '.join(self.unit_numer) if self.unit_denom: full_unit += ' / ' full_unit += ' * '.join(self.unit_denom) if full_unit: full_unit = ' ' + full_unit return "<{0} {1}{2}>".format(type(self).__name__, value, full_unit) def __hash__(self): return hash((self.value, self.unit_numer, self.unit_denom)) def __int__(self): return int(self.value) def __float__(self): return float(self.value) def __pos__(self): return self def __neg__(self): return self * Number(-1) def __str__(self): return self.render() def __eq__(self, other): if not isinstance(other, Number): return Boolean(False) return self._compare(other, operator.__eq__, soft_fail=True) def __lt__(self, other): return self._compare(other, operator.__lt__) def __le__(self, other): return self._compare(other, operator.__le__) def __gt__(self, other): return self._compare(other, operator.__gt__) def __ge__(self, other): return self._compare(other, operator.__ge__) def _compare(self, other, op, soft_fail=False): if not isinstance(other, Number): raise TypeError("Can't compare %r and %r" % (self, other)) # A unitless operand is treated as though it had the other operand's # units, and zero values can cast to anything, so in both cases the # units can be ignored if (self.is_unitless or other.is_unitless or self.value == 0 or other.value == 0): left = self right = other else: left = self.to_base_units() right = other.to_base_units() if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom: if soft_fail: # Used for equality only, where == should never fail return Boolean(False) else: raise ValueError("Can't reconcile units: %r and %r" % (self, other)) return Boolean(op(round(left.value, PRECISION), round(right.value, PRECISION))) def __pow__(self, exp): if not isinstance(exp, Number): raise TypeError("Can't raise %r to power %r" % (self, exp)) if not exp.is_unitless: raise TypeError("Exponent %r cannot have units" % (exp,)) if self.is_unitless: return Number(self.value ** exp.value) # Units can only be exponentiated to integral powers -- what's the # square root of 'px'? (Well, it's sqrt(px), but supporting that is # a bit out of scope.) if exp.value != int(exp.value): raise ValueError("Can't raise units of %r to non-integral power %r" % (self, exp)) return Number( self.value ** int(exp.value), unit_numer=self.unit_numer * int(exp.value), unit_denom=self.unit_denom * int(exp.value), ) def __mul__(self, other): if not isinstance(other, Number): return NotImplemented amount = self.value * other.value numer = self.unit_numer + other.unit_numer denom = self.unit_denom + other.unit_denom return Number(amount, unit_numer=numer, unit_denom=denom) def __div__(self, other): if not isinstance(other, Number): return NotImplemented amount = self.value / other.value numer = self.unit_numer + other.unit_denom denom = self.unit_denom + other.unit_numer return Number(amount, unit_numer=numer, unit_denom=denom) def __mod__(self, other): if not isinstance(other, Number): return NotImplemented amount = self.value % other.value if self.is_unitless: return Number(amount) if not other.is_unitless: left = self.to_base_units() right = other.to_base_units() if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom: raise ValueError("Can't reconcile units: %r and %r" % (self, other)) return Number(amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom) def __add__(self, other): # Numbers auto-cast to strings when added to other strings if isinstance(other, String): return String(self.render(), quotes=None) + other return self._add_sub(other, operator.add) def __sub__(self, other): return self._add_sub(other, operator.sub) def _add_sub(self, other, op): """Implements both addition and subtraction.""" if not isinstance(other, Number): return NotImplemented # If either side is unitless, inherit the other side's units. Skip all # the rest of the conversion math, too. if self.is_unitless or other.is_unitless: return Number( op(self.value, other.value), unit_numer=self.unit_numer or other.unit_numer, unit_denom=self.unit_denom or other.unit_denom, ) # Likewise, if either side is zero, it can auto-cast to any units if self.value == 0: return Number( op(self.value, other.value), unit_numer=other.unit_numer, unit_denom=other.unit_denom, ) elif other.value == 0: return Number( op(self.value, other.value), unit_numer=self.unit_numer, unit_denom=self.unit_denom, ) # Reduce both operands to the same units left = self.to_base_units() right = other.to_base_units() if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom: raise ValueError("Can't reconcile units: %r and %r" % (self, other)) new_amount = op(left.value, right.value) # Convert back to the left side's units if left.value != 0: new_amount = new_amount * self.value / left.value return Number(new_amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom) ### Helper methods, mostly used internally def to_base_units(self): """Convert to a fixed set of "base" units. The particular units are arbitrary; what's important is that they're consistent. Used for addition and comparisons. """ # Convert to "standard" units, as defined by the conversions dict above amount = self.value numer_factor, numer_units = convert_units_to_base_units(self.unit_numer) denom_factor, denom_units = convert_units_to_base_units(self.unit_denom) return Number( amount * numer_factor / denom_factor, unit_numer=numer_units, unit_denom=denom_units, ) ### Utilities for public consumption @classmethod def wrap_python_function(cls, fn): """Wraps an unary Python math function, translating the argument from Sass to Python on the way in, and vice versa for the return value. Used to wrap simple Python functions like `ceil`, `floor`, etc. """ def wrapped(sass_arg): # TODO enforce no units for trig? python_arg = sass_arg.value python_ret = fn(python_arg) sass_ret = cls( python_ret, unit_numer=sass_arg.unit_numer, unit_denom=sass_arg.unit_denom) return sass_ret return wrapped def to_python_index(self, length, check_bounds=True, circular=False): """Return a plain Python integer appropriate for indexing a sequence of the given length. Raise if this is impossible for any reason whatsoever. """ if not self.is_unitless: raise ValueError("Index cannot have units: {0!r}".format(self)) ret = int(self.value) if ret != self.value: raise ValueError("Index must be an integer: {0!r}".format(ret)) if ret == 0: raise ValueError("Index cannot be zero") if check_bounds and not circular and abs(ret) > length: raise ValueError("Index {0!r} out of bounds for length {1}".format(ret, length)) if ret > 0: ret -= 1 if circular: ret = ret % length return ret @property def has_simple_unit(self): """Returns True iff the unit is expressible in CSS, i.e., has no denominator and at most one unit in the numerator. """ return len(self.unit_numer) <= 1 and not self.unit_denom def is_simple_unit(self, unit): """Return True iff the unit is simple (as above) and matches the given unit. """ if self.unit_denom or len(self.unit_numer) > 1: return False if not self.unit_numer: # Empty string historically means no unit return unit == '' return self.unit_numer[0] == unit @property def is_unitless(self): return not self.unit_numer and not self.unit_denom def render(self, compress=False): if not self.has_simple_unit: raise ValueError("Can't express compound units in CSS: %r" % (self,)) if self.unit_numer: unit = self.unit_numer[0] else: unit = '' value = self.value if compress and unit in ZEROABLE_UNITS and value == 0: return '0' if value == 0: # -0.0 is plain 0 value = 0 val = ('%%0.0%df' % PRECISION) % round(value, PRECISION) val = val.rstrip('0').rstrip('.') if compress and val.startswith('0.'): # Strip off leading zero when compressing val = val[1:] return val + unit
class Number(Value): def __init__(self, amount, unit=None, unit_numer=(), unit_denom=()): pass def __repr__(self): pass def __hash__(self): pass def __int__(self): pass def __float__(self): pass def __pos__(self): pass def __neg__(self): pass def __str__(self): pass def __eq__(self, other): pass def __lt__(self, other): pass def __le__(self, other): pass def __gt__(self, other): pass def __ge__(self, other): pass def _compare(self, other, op, soft_fail=False): pass def __pow__(self, exp): pass def __mul__(self, other): pass def __div__(self, other): pass def __mod__(self, other): pass def __add__(self, other): pass def __sub__(self, other): pass def _add_sub(self, other, op): '''Implements both addition and subtraction.''' pass def to_base_units(self): '''Convert to a fixed set of "base" units. The particular units are arbitrary; what's important is that they're consistent. Used for addition and comparisons. ''' pass @classmethod def wrap_python_function(cls, fn): '''Wraps an unary Python math function, translating the argument from Sass to Python on the way in, and vice versa for the return value. Used to wrap simple Python functions like `ceil`, `floor`, etc. ''' pass def wrapped(sass_arg): pass def to_python_index(self, length, check_bounds=True, circular=False): '''Return a plain Python integer appropriate for indexing a sequence of the given length. Raise if this is impossible for any reason whatsoever. ''' pass @property def has_simple_unit(self): '''Returns True iff the unit is expressible in CSS, i.e., has no denominator and at most one unit in the numerator. ''' pass def is_simple_unit(self, unit): '''Return True iff the unit is simple (as above) and matches the given unit. ''' pass @property def is_unitless(self): pass def render(self, compress=False): pass
33
6
11
2
8
2
2
0.24
1
9
2
0
27
3
28
53
352
81
219
70
186
53
185
67
155
7
2
3
72
144,023
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Null
class Null(Value): is_null = True sass_type_name = 'null' def __init__(self, value=None): pass def __str__(self): return self.sass_type_name def __repr__(self): return "<{0}>".format(type(self).__name__) def __hash__(self): return hash(None) def __bool__(self): return False def __eq__(self, other): return Boolean(isinstance(other, Null)) def __ne__(self, other): return Boolean(not self.__eq__(other)) def render(self, compress=False): return self.sass_type_name def render_interpolated(self, compress=False): # Interpolating a null gives you nothing. return ''
class Null(Value): def __init__(self, value=None): pass def __str__(self): pass def __repr__(self): pass def __hash__(self): pass def __bool__(self): pass def __eq__(self, other): pass def __ne__(self, other): pass def render(self, compress=False): pass def render_interpolated(self, compress=False): pass
10
0
2
0
2
0
1
0.05
1
2
1
1
9
0
9
34
31
9
21
12
11
1
21
12
11
1
2
0
9
144,024
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Map
class Map(Value): sass_type_name = 'map' def __init__(self, pairs, index=None): self.pairs = tuple(pairs) if index is None: self.index = {} for key, value in pairs: self.index[key] = value else: self.index = index def __repr__(self): return "<Map: (%s)>" % (", ".join("%s: %s" % pair for pair in self.pairs),) def __hash__(self): return hash(self.pairs) def __len__(self): return len(self.pairs) def __iter__(self): return iter(self.pairs) def __getitem__(self, index): return List(self.pairs[index], use_comma=True) def __eq__(self, other): try: return self.pairs == other.to_pairs() except ValueError: return NotImplemented def to_dict(self): return self.index def to_pairs(self): return self.pairs def render(self, compress=False): raise TypeError("Cannot render map %r as CSS" % (self,))
class Map(Value): def __init__(self, pairs, index=None): pass def __repr__(self): pass def __hash__(self): pass def __len__(self): pass def __iter__(self): pass def __getitem__(self, index): pass def __eq__(self, other): pass def to_dict(self): pass def to_pairs(self): pass def render(self, compress=False): pass
11
0
3
0
3
0
1
0
1
4
1
0
10
2
10
35
42
11
31
15
20
0
30
15
19
3
2
2
13
144,025
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.List
class List(Value): """A list of other values. May be delimited by commas or spaces. Lists of one item don't make much sense in CSS, but can exist in Sass. Use ...... Lists may also contain zero items, but these are forbidden from appearing in CSS output. """ sass_type_name = 'list' def __init__(self, iterable, separator=None, use_comma=None, literal=False): if isinstance(iterable, List): iterable = iterable.value if (not isinstance(iterable, Iterable) or isinstance(iterable, six.string_types)): raise TypeError("Expected list, got %r" % (iterable,)) self.value = list(iterable) for item in self.value: if not isinstance(item, Value): raise TypeError("Expected a Sass type, got %r" % (item,)) # TODO remove separator argument entirely if use_comma is None: self.use_comma = separator == "," else: self.use_comma = use_comma self.literal = literal @classmethod def maybe_new(cls, values, use_comma=True): """If `values` contains only one item, return that item. Otherwise, return a List as normal. """ if len(values) == 1: return values[0] else: return cls(values, use_comma=use_comma) def maybe(self): """If this List contains only one item, return it. Otherwise, return the List. """ if len(self.value) == 1: return self.value[0] else: return self @classmethod def from_maybe(cls, values, use_comma=True): """If `values` appears to not be a list, return a list containing it. Otherwise, return a List as normal. """ if values is None: values = [] return values @classmethod def from_maybe_starargs(cls, args, use_comma=True): """If `args` has one element which appears to be a list, return it. Otherwise, return a list as normal. Mainly used by Sass function implementations that predate `...` support, so they can accept both a list of arguments and a single list stored in a variable. """ if len(args) == 1: if isinstance(args[0], cls): return args[0] elif isinstance(args[0], (list, tuple)): return cls(args[0], use_comma=use_comma) return cls(args, use_comma=use_comma) def __repr__(self): return "<{0} {1}>".format( type(self).__name__, self.delimiter().join(repr(item) for item in self), ) def __hash__(self): return hash((tuple(self.value), self.use_comma)) def delimiter(self, compress=False): if self.use_comma: if compress: return ',' else: return ', ' else: return ' ' def __len__(self): return len(self.value) def __str__(self): return self.render() def __iter__(self): return iter(self.value) def __contains__(self, item): return item in self.value def __getitem__(self, key): return self.value[key] def to_pairs(self): pairs = [] for item in self: if len(item) != 2: return super(List, self).to_pairs() pairs.append(tuple(item)) return pairs def render(self, compress=False): if not self.value: raise ValueError("Can't render empty list as CSS") delim = self.delimiter(compress) if self.literal: value = self.value else: # Non-literal lists have nulls stripped value = [item for item in self.value if not item.is_null] # Non-empty lists containing only nulls become nothing, just like # single nulls if not value: return '' return delim.join( item.render(compress=compress) for item in value ) def render_interpolated(self, compress=False): return self.delimiter(compress).join( item.render_interpolated(compress) for item in self) # DEVIATION: binary ops on lists and scalars act element-wise def __add__(self, other): if isinstance(other, List): max_list, min_list = (self, other) if len(self) > len(other) else (other, self) return List([item + max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma) elif isinstance(other, String): # UN-DEVIATION: adding a string should fall back to canonical # behavior of string addition return super(List, self).__add__(other) else: return List([item + other for item in self], use_comma=self.use_comma) def __sub__(self, other): if isinstance(other, List): max_list, min_list = (self, other) if len(self) > len(other) else (other, self) return List([item - max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma) return List([item - other for item in self], use_comma=self.use_comma) def __mul__(self, other): if isinstance(other, List): max_list, min_list = (self, other) if len(self) > len(other) else (other, self) max_list, min_list = (self, other) if len(self) > len(other) else (other, self) return List([item * max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma) return List([item * other for item in self], use_comma=self.use_comma) def __div__(self, other): if isinstance(other, List): max_list, min_list = (self, other) if len(self) > len(other) else (other, self) return List([item / max_list[i] for i, item in enumerate(min_list)], use_comma=self.use_comma) return List([item / other for item in self], use_comma=self.use_comma) def __pos__(self): return self def __neg__(self): return List([-item for item in self], use_comma=self.use_comma)
class List(Value): '''A list of other values. May be delimited by commas or spaces. Lists of one item don't make much sense in CSS, but can exist in Sass. Use ...... Lists may also contain zero items, but these are forbidden from appearing in CSS output. ''' def __init__(self, iterable, separator=None, use_comma=None, literal=False): pass @classmethod def maybe_new(cls, values, use_comma=True): '''If `values` contains only one item, return that item. Otherwise, return a List as normal. ''' pass def maybe_new(cls, values, use_comma=True): '''If this List contains only one item, return it. Otherwise, return the List. ''' pass @classmethod def from_maybe(cls, values, use_comma=True): '''If `values` appears to not be a list, return a list containing it. Otherwise, return a List as normal. ''' pass @classmethod def from_maybe_starargs(cls, args, use_comma=True): '''If `args` has one element which appears to be a list, return it. Otherwise, return a list as normal. Mainly used by Sass function implementations that predate `...` support, so they can accept both a list of arguments and a single list stored in a variable. ''' pass def __repr__(self): pass def __hash__(self): pass def delimiter(self, compress=False): pass def __len__(self): pass def __str__(self): pass def __iter__(self): pass def __contains__(self, item): pass def __getitem__(self, key): pass def to_pairs(self): pass def render(self, compress=False): pass def render_interpolated(self, compress=False): pass def __add__(self, other): pass def __sub__(self, other): pass def __mul__(self, other): pass def __div__(self, other): pass def __pos__(self): pass def __neg__(self): pass
26
5
7
1
5
1
2
0.23
1
9
1
1
19
3
22
47
187
42
118
39
92
27
98
36
75
6
2
2
50
144,026
Kronuz/pyScss
Kronuz_pyScss/scss/rule.py
scss.rule.BlockScopeHeader
class BlockScopeHeader(BlockHeader): is_scope = True def __init__(self, scope, unscoped_value, num_lines=0): self.scope = scope if unscoped_value: self.unscoped_value = unscoped_value else: self.unscoped_value = None self.num_lines = num_lines
class BlockScopeHeader(BlockHeader): def __init__(self, scope, unscoped_value, num_lines=0): pass
2
0
9
2
7
0
2
0
1
0
0
0
1
3
1
2
12
3
9
6
7
0
8
6
6
2
2
1
2
144,027
Kronuz/pyScss
Kronuz_pyScss/scss/rule.py
scss.rule.BlockSelectorHeader
class BlockSelectorHeader(BlockHeader): is_selector = True def __init__(self, selectors, num_lines=0): self.selectors = tuple(selectors) self.num_lines = num_lines def __repr__(self): return "<%s %r>" % (type(self).__name__, self.selectors) def render(self, sep=', ', super_selector=''): return sep.join(sort( super_selector + s.render() for s in self.selectors if not s.has_placeholder))
class BlockSelectorHeader(BlockHeader): def __init__(self, selectors, num_lines=0): pass def __repr__(self): pass def render(self, sep=', ', super_selector=''): pass
4
0
4
0
3
0
1
0
1
2
0
0
3
2
3
4
16
4
12
7
8
0
9
7
5
1
2
0
3
144,028
Kronuz/pyScss
Kronuz_pyScss/scss/rule.py
scss.rule.RuleAncestry
class RuleAncestry(object): def __init__(self, headers=()): self.headers = tuple(headers) def __repr__(self): return "<%s %r>" % (type(self).__name__, self.headers) def __len__(self): return len(self.headers) def with_nested_selectors(self, c_selectors): if self.headers and self.headers[-1].is_selector: # Need to merge with parent selectors p_selectors = self.headers[-1].selectors new_selectors = [] for p_selector in p_selectors: for c_selector in c_selectors: new_selectors.append(c_selector.with_parent(p_selector)) # Replace the last header with the new merged selectors new_headers = self.headers[:-1] + (BlockSelectorHeader(new_selectors),) return RuleAncestry(new_headers) else: # Whoops, no parent selectors. Just need to double-check that # there are no uses of `&`. for c_selector in c_selectors: if c_selector.has_parent_reference: raise ValueError("Can't use parent selector '&' in top-level rules") # Add the children as a new header new_headers = self.headers + (BlockSelectorHeader(c_selectors),) return RuleAncestry(new_headers) def with_more_selectors(self, selectors): """Return a new ancestry that also matches the given selectors. No nesting is done. """ if self.headers and self.headers[-1].is_selector: new_selectors = extend_unique( self.headers[-1].selectors, selectors) new_headers = self.headers[:-1] + ( BlockSelectorHeader(new_selectors),) return RuleAncestry(new_headers) else: new_headers = self.headers + (BlockSelectorHeader(selectors),) return RuleAncestry(new_headers)
class RuleAncestry(object): def __init__(self, headers=()): pass def __repr__(self): pass def __len__(self): pass def with_nested_selectors(self, c_selectors): pass def with_more_selectors(self, selectors): '''Return a new ancestry that also matches the given selectors. No nesting is done. ''' pass
6
1
9
1
6
2
2
0.24
1
4
1
0
5
1
5
5
49
8
33
14
27
8
28
14
22
6
1
3
11
144,029
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.String
class String(Value): """Represents both CSS quoted string values and CSS identifiers (such as `left`). Makes no distinction between single and double quotes, except that the same quotes are preserved on string literals that pass through unmodified. Otherwise, double quotes are used. """ sass_type_name = 'string' bad_identifier_rx = re.compile('[^-_a-zA-Z\x80-\U0010FFFF]') def __init__(self, value, quotes='"', literal=False): if isinstance(value, String): # TODO unclear if this should be here, but many functions rely on # it value = value.value elif isinstance(value, Number): # TODO this may only be necessary in the case of __radd__ and # number values value = six.text_type(value) if isinstance(value, six.binary_type): warn(FutureWarning( "String got a bytes type {0!r} " "-- this will no longer be supported in pyScss 2.0" .format(value) )) value = value.decode(DEFAULT_STRING_ENCODING) if not isinstance(value, six.text_type): raise TypeError("Expected string, got {0!r}".format(value)) self.value = value self.quotes = quotes # TODO this isn't quite used yet if literal: self.original_literal = value else: self.original_literal = None @classmethod def unquoted(cls, value, literal=False): """Helper to create a string with no quotes.""" return cls(value, quotes=None, literal=literal) def __hash__(self): return hash(self.value) def __repr__(self): if self.quotes: quotes = '(' + self.quotes + ')' else: quotes = '' return "<{0}{1} {2!r}>".format( type(self).__name__, quotes, self.value) def __eq__(self, other): return Boolean(isinstance(other, String) and self.value == other.value) def __add__(self, other): if isinstance(other, String): other_value = other.value else: other_value = other.render() return String( self.value + other_value, quotes='"' if self.quotes else None) def __mul__(self, other): # DEVIATION: Ruby Sass doesn't do this, because Ruby doesn't. But # Python does, and in Ruby Sass it's just fatal anyway. if not isinstance(other, Number): return super(String, self).__mul__(other) if not other.is_unitless: raise TypeError("Can only multiply strings by unitless numbers") n = other.value if n != int(n): raise ValueError("Can only multiply strings by integers") return String(self.value * int(other.value), quotes=self.quotes) def _escape_character(self, match): """Given a single character, return it appropriately CSS-escaped.""" # TODO is there any case where we'd want to use unicode escaping? # TODO unsure if this works with newlines return '\\' + match.group(0) def _is_name_start(self, ch): if ch == '_': return True if ord(ch) >= 128: return True if ch in string.ascii_letters: return True return False def render(self, compress=False): # TODO should preserve original literals here too -- even the quotes. # or at least that's what sass does. # Escape and add quotes as appropriate. if self.quotes is None: # If you deliberately construct a bareword with bogus CSS in it, # you're assumed to know what you're doing return self.value else: return self._render_quoted() def render_interpolated(self, compress=False): # Always render without quotes return self.value def _render_bareword(self): # TODO this is currently unused, and only implemented due to an # oversight, but would make for a much better implementation of # escape() # This is a bareword, so almost anything outside \w needs escaping ret = self.value ret = self.bad_identifier_rx.sub(self._escape_character, ret) # Also apply some minor quibbling rules about how barewords can # start: with a "name start", an escape, a hyphen followed by one # of those, or two hyphens. if not ret: # TODO is an unquoted empty string allowed to be rendered? pass elif ret[0] == '-': if ret[1] in '-\\' or self._is_name_start(ret[1]): pass else: # Escape the second character # TODO what if it's a digit, oops ret = ret[0] + '\\' + ret[1:] elif ret[0] == '\\' or self._is_name_start(ret[0]): pass else: # Escape the first character # TODO what if it's a digit, oops ret = '\\' + ret return ret def _render_quoted(self): # Strictly speaking, the only things we need to quote are the quotes # themselves, backslashes, and newlines. # TODO Ruby Sass takes backslashes in barewords literally, but treats # backslashes in quoted strings as escapes -- their mistake? # TODO In Ruby Sass, generated strings never have single quotes -- but # neither do variable interpolations, so I'm not sure what they're # doing quote = self.quotes ret = self.value ret = ret.replace('\\', '\\\\') ret = ret.replace(quote, '\\' + quote) # Note that a literal newline is ignored when escaped, so we have to # use the codepoint instead. But we'll leave the newline as well, to # aid readability. ret = ret.replace('\n', '\\a\\\n') return quote + ret + quote
class String(Value): '''Represents both CSS quoted string values and CSS identifiers (such as `left`). Makes no distinction between single and double quotes, except that the same quotes are preserved on string literals that pass through unmodified. Otherwise, double quotes are used. ''' def __init__(self, value, quotes='"', literal=False): pass @classmethod def unquoted(cls, value, literal=False): '''Helper to create a string with no quotes.''' pass def __hash__(self): pass def __repr__(self): pass def __eq__(self, other): pass def __add__(self, other): pass def __mul__(self, other): pass def _escape_character(self, match): '''Given a single character, return it appropriately CSS-escaped.''' pass def _is_name_start(self, ch): pass def render(self, compress=False): pass def render_interpolated(self, compress=False): pass def _render_bareword(self): pass def _render_quoted(self): pass
15
3
11
1
7
3
2
0.48
1
8
2
1
12
3
13
38
165
27
93
26
78
45
76
25
62
6
2
2
32
144,030
Kronuz/pyScss
Kronuz_pyScss/scss/rule.py
scss.rule.SassRule
class SassRule(object): """At its heart, a CSS rule: combination of a selector and zero or more properties. But this is Sass, so it also tracks some Sass-flavored metadata, like `@extend` rules and `@media` nesting. """ def __init__( self, source_file, import_key=None, unparsed_contents=None, num_header_lines=0, options=None, legacy_compiler_options=None, properties=None, namespace=None, lineno=0, extends_selectors=frozenset(), ancestry=None, nested=0, from_source_file=None, from_lineno=0): self.from_source_file = from_source_file self.from_lineno = from_lineno self.source_file = source_file self.import_key = import_key self.lineno = lineno self.num_header_lines = num_header_lines self.unparsed_contents = unparsed_contents self.legacy_compiler_options = legacy_compiler_options or {} self.options = options or {} self.extends_selectors = extends_selectors if namespace is None: assert False self.namespace = Namespace() else: self.namespace = namespace if properties is None: self.properties = [] else: self.properties = properties if ancestry is None: self.ancestry = RuleAncestry() else: self.ancestry = ancestry self.nested = nested self.descendants = 0 def __repr__(self): # TODO probably want to encode this with string_escape on python 2, and # similar elsewhere, especially since this file has unicode_literals return "<SassRule %s, %d props>" % ( self.ancestry, len(self.properties), ) @property def selectors(self): # TEMPORARY if self.ancestry.headers and self.ancestry.headers[-1].is_selector: return self.ancestry.headers[-1].selectors else: return () @property def file_and_line(self): """Return the filename and line number where this rule originally appears, in the form "foo.scss:3". Used for error messages. """ ret = "%s:%d" % (self.source_file.path, self.lineno) if self.from_source_file: ret += " (%s:%d)" % (self.from_source_file.path, self.from_lineno) return ret @property def is_empty(self): """Return whether this rule is considered "empty" -- i.e., has no contents that should end up in the final CSS. """ if self.properties: # Rules containing CSS properties are never empty return False if not self.descendants: for header in self.ancestry.headers: if header.is_atrule and header.directive != '@media': # At-rules should always be preserved, UNLESS they are @media # blocks, which are known to be noise if they don't have any # contents of their own return False return True @property def is_pure_placeholder(self): selectors = self.selectors if not selectors: return False for s in selectors: if not s.has_placeholder: return False return True def copy(self): return type(self)( source_file=self.source_file, lineno=self.lineno, from_source_file=self.from_source_file, from_lineno=self.from_lineno, unparsed_contents=self.unparsed_contents, legacy_compiler_options=self.legacy_compiler_options, options=self.options, #properties=list(self.properties), properties=self.properties, extends_selectors=self.extends_selectors, #ancestry=list(self.ancestry), ancestry=self.ancestry, namespace=self.namespace.derive(), nested=self.nested, )
class SassRule(object): '''At its heart, a CSS rule: combination of a selector and zero or more properties. But this is Sass, so it also tracks some Sass-flavored metadata, like `@extend` rules and `@media` nesting. ''' def __init__( self, source_file, import_key=None, unparsed_contents=None, num_header_lines=0, options=None, legacy_compiler_options=None, properties=None, namespace=None, lineno=0, extends_selectors=frozenset(), ancestry=None, nested=0, from_source_file=None, from_lineno=0): pass def __repr__(self): pass @property def selectors(self): pass @property def file_and_line(self): '''Return the filename and line number where this rule originally appears, in the form "foo.scss:3". Used for error messages. ''' pass @property def is_empty(self): '''Return whether this rule is considered "empty" -- i.e., has no contents that should end up in the final CSS. ''' pass @property def is_pure_placeholder(self): pass def copy(self): pass
12
3
16
2
11
2
3
0.22
1
4
2
0
7
15
7
7
126
22
85
39
65
19
53
27
45
5
1
3
19
144,031
Kronuz/pyScss
Kronuz_pyScss/scss/rule.py
scss.rule.UnparsedBlock
class UnparsedBlock(object): """A Sass block whose contents have not yet been parsed. At the top level, CSS (and Sass) documents consist of a sequence of blocks. A block may be a ruleset: selector { block; block; block... } Or it may be an @-rule: @rule arguments { block; block; block... } Or it may be only a single property declaration: property: value pyScss's first parsing pass breaks the document into these blocks, and each block becomes an instance of this class. """ def __init__(self, parent_rule, lineno, prop, unparsed_contents): self.parent_rule = parent_rule self.header = BlockHeader.parse(prop, has_contents=bool(unparsed_contents)) # Basic properties self.lineno = ( parent_rule.lineno - parent_rule.num_header_lines + lineno - 1) self.prop = prop self.unparsed_contents = unparsed_contents @property def directive(self): return self.header.directive @property def argument(self): return self.header.argument ### What kind of thing is this? @property def is_atrule(self): return self.header.is_atrule @property def is_scope(self): return self.header.is_scope
class UnparsedBlock(object): '''A Sass block whose contents have not yet been parsed. At the top level, CSS (and Sass) documents consist of a sequence of blocks. A block may be a ruleset: selector { block; block; block... } Or it may be an @-rule: @rule arguments { block; block; block... } Or it may be only a single property declaration: property: value pyScss's first parsing pass breaks the document into these blocks, and each block becomes an instance of this class. ''' def __init__(self, parent_rule, lineno, prop, unparsed_contents): pass @property def directive(self): pass @property def argument(self): pass @property def is_atrule(self): pass @property def is_scope(self): pass
10
1
3
0
3
0
1
0.65
1
2
1
0
5
5
5
5
47
14
20
15
10
13
15
11
9
1
1
0
5
144,032
Kronuz/pyScss
Kronuz_pyScss/scss/selector.py
scss.selector.Selector
class Selector(object): """A single CSS selector.""" def __init__(self, simples): """Return a selector containing a sequence of `SimpleSelector`s. You probably want to use `parse_many` or `parse_one` instead. """ # TODO enforce uniqueness self.simple_selectors = tuple(simples) @classmethod def parse_many(cls, selector): selector = selector.strip() ret = [] pending = dict( simples=[], combinator=' ', tokens=[], ) def promote_simple(): if pending['tokens']: pending['simples'].append( SimpleSelector(pending['combinator'], pending['tokens'])) pending['combinator'] = ' ' pending['tokens'] = [] def promote_selector(): promote_simple() if pending['combinator'] != ' ': pending['simples'].append( SimpleSelector(pending['combinator'], [])) pending['combinator'] = ' ' if pending['simples']: ret.append(cls(pending['simples'])) pending['simples'] = [] pos = 0 while pos < len(selector): # TODO i don't think this deals with " + " correctly. anywhere. # TODO this used to turn "1.5%" into empty string; why does error # not work? m = SELECTOR_TOKENIZER.match(selector, pos) if not m: # TODO prettify me raise SyntaxError("Couldn't parse selector: %r" % (selector,)) token = m.group(0) pos += len(token) # Kill any extraneous space, BUT make sure not to turn a lone space # into an empty string token = token.strip() or ' ' if token == ',': # End current selector promote_selector() elif token in ' +>~': # End current simple selector promote_simple() pending['combinator'] = token else: # Add to pending simple selector pending['tokens'].append(token) # Deal with any remaining pending bits promote_selector() return ret @classmethod def parse_one(cls, selector_string): selectors = cls.parse_many(selector_string) if len(selectors) != 1: # TODO better error raise ValueError return selectors[0] def __repr__(self): return "<%s: %r>" % (type(self).__name__, self.render()) def __hash__(self): return hash(self.simple_selectors) def __eq__(self, other): if not isinstance(other, Selector): return NotImplemented return self.simple_selectors == other.simple_selectors @property def has_parent_reference(self): for simple in self.simple_selectors: if simple.has_parent_reference: return True return False @property def has_placeholder(self): for simple in self.simple_selectors: if simple.has_placeholder: return True return False def with_parent(self, parent): saw_parent_ref = False new_simples = [] for simple in self.simple_selectors: if simple.has_parent_reference: new_simples.extend(simple.replace_parent(parent.simple_selectors)) saw_parent_ref = True else: new_simples.append(simple) if not saw_parent_ref: new_simples = parent.simple_selectors + tuple(new_simples) return type(self)(new_simples) def lookup_key(self): """Build a key from the "important" parts of a selector: elements, classes, ids. """ parts = set() for node in self.simple_selectors: for token in node.tokens: if token[0] not in ':[': parts.add(token) if not parts: # Should always have at least ONE key; selectors with no elements, # no classes, and no ids can be indexed as None to avoid a scan of # every selector in the entire document parts.add(None) return frozenset(parts) def is_superset_of(self, other): assert isinstance(other, Selector) idx = 0 for other_node in other.simple_selectors: if idx >= len(self.simple_selectors): return False while idx < len(self.simple_selectors): node = self.simple_selectors[idx] idx += 1 if node.is_superset_of(other_node): break return True def substitute(self, target, replacement): """Return a list of selectors obtained by replacing the `target` selector with `replacement`. Herein lie the guts of the Sass @extend directive. In general, for a selector ``a X b Y c``, a target ``X Y``, and a replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b Z c``. Note in particular that no more than two selectors will be returned, and the permutation of ancestors will never insert new simple selectors "inside" the target selector. """ # Find the target in the parent selector, and split it into # before/after p_before, p_extras, p_after = self.break_around(target.simple_selectors) # The replacement has no hinge; it only has the most specific simple # selector (which is the part that replaces "self" in the parent) and # whatever preceding simple selectors there may be r_trail = replacement.simple_selectors[:-1] r_extras = replacement.simple_selectors[-1] # TODO what if the prefix doesn't match? who wins? should we even get # this far? focal_nodes = (p_extras.merge_into(r_extras),) befores = _merge_selectors(p_before, r_trail) cls = type(self) return [ cls(before + focal_nodes + p_after) for before in befores] def break_around(self, hinge): """Given a simple selector node contained within this one (a "hinge"), break it in half and return a parent selector, extra specifiers for the hinge, and a child selector. That is, given a hinge X, break the selector A + X.y B into A, + .y, and B. """ hinge_start = hinge[0] for i, node in enumerate(self.simple_selectors): # In this particular case, a ' ' combinator actually means "no" (or # any) combinator, so it should be ignored if hinge_start.is_superset_of(node, soft_combinator=True): start_idx = i break else: raise ValueError( "Couldn't find hinge %r in compound selector %r" % (hinge_start, self.simple_selectors)) for i, hinge_node in enumerate(hinge): if i == 0: # We just did this continue self_node = self.simple_selectors[start_idx + i] if hinge_node.is_superset_of(self_node): continue # TODO this isn't true; consider finding `a b` in `a c a b` raise ValueError( "Couldn't find hinge %r in compound selector %r" % (hinge_node, self.simple_selectors)) end_idx = start_idx + len(hinge) - 1 focal_node = self.simple_selectors[end_idx] extras = focal_node.difference(hinge[-1]) return ( self.simple_selectors[:start_idx], extras, self.simple_selectors[end_idx + 1:]) def render(self): return ' '.join(simple.render() for simple in self.simple_selectors)
class Selector(object): '''A single CSS selector.''' def __init__(self, simples): '''Return a selector containing a sequence of `SimpleSelector`s. You probably want to use `parse_many` or `parse_one` instead. ''' pass @classmethod def parse_many(cls, selector): pass def promote_simple(): pass def promote_selector(): pass @classmethod def parse_one(cls, selector_string): pass def __repr__(self): pass def __hash__(self): pass def __eq__(self, other): pass @property def has_parent_reference(self): pass @property def has_placeholder(self): pass def with_parent(self, parent): pass def lookup_key(self): '''Build a key from the "important" parts of a selector: elements, classes, ids. ''' pass def is_superset_of(self, other): pass def substitute(self, target, replacement): '''Return a list of selectors obtained by replacing the `target` selector with `replacement`. Herein lie the guts of the Sass @extend directive. In general, for a selector ``a X b Y c``, a target ``X Y``, and a replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b Z c``. Note in particular that no more than two selectors will be returned, and the permutation of ancestors will never insert new simple selectors "inside" the target selector. ''' pass def break_around(self, hinge): '''Given a simple selector node contained within this one (a "hinge"), break it in half and return a parent selector, extra specifiers for the hinge, and a child selector. That is, given a hinge X, break the selector A + X.y B into A, + .y, and B. ''' pass def render(self): pass
21
5
15
2
9
3
3
0.34
1
9
1
0
12
1
14
14
237
48
141
53
120
48
119
49
102
6
1
3
45
144,033
Kronuz/pyScss
Kronuz_pyScss/scss/selector.py
scss.selector.SimpleSelector
class SimpleSelector(object): """A simple selector, by CSS 2.1 terminology: a combination of element name, class selectors, id selectors, and other criteria that all apply to a single element. Note that CSS 3 considers EACH of those parts to be a "simple selector", and calls a group of them a "sequence of simple selectors". That's a terrible class name, so we're going with 2.1 here. For lack of a better name, each of the individual parts is merely called a "token". Note that it's possible to have zero tokens. This isn't legal CSS, but it's perfectly legal Sass, since you might nest blocks like so: body > { div { ... } } """ def __init__(self, combinator, tokens): self.combinator = combinator # TODO enforce that only one element name (including *) appears in a # selector. only one pseudo, too. # TODO remove duplicates? self.tokens = tuple(tokens) def __repr__(self): return "<%s: %r>" % (type(self).__name__, self.render()) def __hash__(self): return hash((self.combinator, self.tokens)) def __eq__(self, other): if not isinstance(other, SimpleSelector): return NotImplemented return ( self.combinator == other.combinator and self.tokens == other.tokens) @property def has_parent_reference(self): return '&' in self.tokens or 'self' in self.tokens @property def has_placeholder(self): for token in self.tokens: if token.startswith('%'): return True return False def is_superset_of(self, other, soft_combinator=False): """Return True iff this selector matches the same elements as `other`, and perhaps others. That is, ``.foo`` is a superset of ``.foo.bar``, because the latter is more specific. Set `soft_combinator` true to ignore the specific case of this selector having a descendent combinator and `other` having anything else. This is for superset checking for ``@extend``, where a space combinator really means "none". """ # Combinators must match, OR be compatible -- space is a superset of >, # ~ is a superset of + if soft_combinator and self.combinator == ' ': combinator_superset = True else: combinator_superset = ( self.combinator == other.combinator or (self.combinator == ' ' and other.combinator == '>') or (self.combinator == '~' and other.combinator == '+')) return ( combinator_superset and set(self.tokens) <= set(other.tokens)) def replace_parent(self, parent_simples): """If ``&`` (or the legacy xCSS equivalent ``self``) appears in this selector, replace it with the given iterable of parent selectors. Returns a tuple of simple selectors. """ assert parent_simples ancestors = parent_simples[:-1] parent = parent_simples[-1] did_replace = False new_tokens = [] for token in self.tokens: if not did_replace and token in ('&', 'self'): did_replace = True new_tokens.extend(parent.tokens) if token == 'self': warn(FutureWarning( "The xCSS 'self' selector is deprecated and will be " "removed in 2.0. Use & instead. ({0!r})" .format(self) )) else: new_tokens.append(token) if not did_replace: # This simple selector doesn't contain a parent reference so just # stick it on the end return parent_simples + (self,) # This simple selector was merged into the direct parent. merged_self = type(self)(parent.combinator, new_tokens) selector = ancestors + (merged_self,) # Our combinator goes on the first ancestor, i.e., substituting "foo # bar baz" into "+ &.quux" produces "+ foo bar baz.quux". This means a # potential conflict with the first ancestor's combinator! root = selector[0] if not _is_combinator_subset_of(self.combinator, root.combinator): raise ValueError( "Can't sub parent {0!r} into {1!r}: " "combinators {2!r} and {3!r} conflict!" .format( parent_simples, self, self.combinator, root.combinator)) root = type(self)(self.combinator, root.tokens) selector = (root,) + selector[1:] return tuple(selector) def merge_into(self, other): """Merge two simple selectors together. This is expected to be the selector being injected into `other` -- that is, `other` is the selector for a block using ``@extend``, and `self` is a selector being extended. Element tokens must come first, and pseudo-element tokens must come last, and there can only be one of each. The final selector thus looks something like:: [element] [misc self tokens] [misc other tokens] [pseudo-element] This method does not check for duplicate tokens; those are assumed to have been removed earlier, during the search for a hinge. """ # TODO it shouldn't be possible to merge two elements or two pseudo # elements, /but/ it shouldn't just be a fatal error here -- it # shouldn't even be considered a candidate for extending! # TODO this is slightly inconsistent with ruby, which treats a trailing # set of self tokens like ':before.foo' as a single unit to be stuck at # the end. but that's completely bogus anyway. element = [] middle = [] pseudo = [] for token in self.tokens + other.tokens: if token in CSS2_PSEUDO_ELEMENTS or token.startswith('::'): pseudo.append(token) elif token[0] in BODY_TOKEN_SIGILS: middle.append(token) else: element.append(token) new_tokens = element + middle + pseudo if self.combinator == ' ' or self.combinator == other.combinator: combinator = other.combinator elif other.combinator == ' ': combinator = self.combinator else: raise ValueError( "Don't know how to merge conflicting combinators: " "{0!r} and {1!r}" .format(self, other)) return type(self)(combinator, new_tokens) def difference(self, other): new_tokens = tuple(token for token in self.tokens if token not in set(other.tokens)) return type(self)(self.combinator, new_tokens) def render(self): # TODO fail if there are no tokens, or if one is a placeholder? rendered = ''.join(self.tokens) if self.combinator == ' ': return rendered elif rendered: return self.combinator + ' ' + rendered else: return self.combinator
class SimpleSelector(object): '''A simple selector, by CSS 2.1 terminology: a combination of element name, class selectors, id selectors, and other criteria that all apply to a single element. Note that CSS 3 considers EACH of those parts to be a "simple selector", and calls a group of them a "sequence of simple selectors". That's a terrible class name, so we're going with 2.1 here. For lack of a better name, each of the individual parts is merely called a "token". Note that it's possible to have zero tokens. This isn't legal CSS, but it's perfectly legal Sass, since you might nest blocks like so: body > { div { ... } } ''' def __init__(self, combinator, tokens): pass def __repr__(self): pass def __hash__(self): pass def __eq__(self, other): pass @property def has_parent_reference(self): pass @property def has_placeholder(self): pass def is_superset_of(self, other, soft_combinator=False): '''Return True iff this selector matches the same elements as `other`, and perhaps others. That is, ``.foo`` is a superset of ``.foo.bar``, because the latter is more specific. Set `soft_combinator` true to ignore the specific case of this selector having a descendent combinator and `other` having anything else. This is for superset checking for ``@extend``, where a space combinator really means "none". ''' pass def replace_parent(self, parent_simples): '''If ``&`` (or the legacy xCSS equivalent ``self``) appears in this selector, replace it with the given iterable of parent selectors. Returns a tuple of simple selectors. ''' pass def merge_into(self, other): '''Merge two simple selectors together. This is expected to be the selector being injected into `other` -- that is, `other` is the selector for a block using ``@extend``, and `self` is a selector being extended. Element tokens must come first, and pseudo-element tokens must come last, and there can only be one of each. The final selector thus looks something like:: [element] [misc self tokens] [misc other tokens] [pseudo-element] This method does not check for duplicate tokens; those are assumed to have been removed earlier, during the search for a hinge. ''' pass def difference(self, other): pass def render(self): pass
14
4
14
1
9
4
2
0.59
1
5
0
0
11
2
11
11
185
28
99
34
85
58
71
32
59
6
1
3
27
144,034
Kronuz/pyScss
Kronuz_pyScss/scss/source.py
scss.source.MISSING
class MISSING(object): def __repr__(self): return "<MISSING>"
class MISSING(object): def __repr__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
144,035
Kronuz/pyScss
Kronuz_pyScss/scss/source.py
scss.source.SourceFile
class SourceFile(object): """A single input file to be fed to the compiler. Detects the encoding (according to CSS spec rules) and performs some light pre-processing. This class is mostly internal and you shouldn't have to worry about it. Source files are uniquely identified by their ``.key``, a 2-tuple of ``(origin, relpath)``. ``origin`` is an object from the compiler's search path, most often a directory represented by a :class:`pathlib.Path`. ``relpath`` is a relative path from there to the actual file, again usually a ``Path``. The idea here is that source files don't always actually come from the filesystem, yet import semantics are expressed in terms of paths. By keeping the origin and relative path separate, it's possible for e.g. Django to swap in an object that has the ``Path`` interface, but actually looks for files in an arbitrary storage backend. In that case it would make no sense to key files by their absolute path, as they may not exist on disk or even on the same machine. Also, relative imports can then continue to work, because they're guaranteed to only try the same origin. The ``origin`` may thus be anything that implements a minimal ``Path``ish interface (division operator, ``.parent``, ``.resolve()``). It may also be ``None``, indicating that the file came from a string or some other origin that can't usefully produce other files. ``relpath``, however, should always be a ``Path``. or string. XXX only when origin (There's little advantage to making it anything else.) A ``relpath`` may **never** contain ".."; there is nothing above the origin. Note that one minor caveat of this setup is that it's possible for the same file on disk to be imported under two different names (even though symlinks are always resolved), if directories in the search path happen to overlap. """ key = None """A 2-tuple of ``(origin, relpath)`` that uniquely identifies where the file came from and how to find its siblings. """ def __init__( self, origin, relpath, contents, encoding=None, is_sass=None): """Not normally used. See the three alternative constructors: :func:`SourceFile.from_file`, :func:`SourceFile.from_path`, and :func:`SourceFile.from_string`. """ if not isinstance(contents, six.text_type): raise TypeError( "Expected text for 'contents', got {0}" .format(type(contents))) if origin and '..' in relpath.parts: raise ValueError( "relpath cannot contain ..: {0!r}".format(relpath)) self.origin = origin self.relpath = relpath self.key = origin, relpath self.encoding = encoding if is_sass is None: # TODO autodetect from the contents if the extension is bogus # or missing? if origin: self.is_sass = relpath.suffix == '.sass' else: self.is_sass = False else: self.is_sass = is_sass self.contents = self.prepare_source(contents) @property def path(self): """Concatenation of ``origin`` and ``relpath``, as a string. Used in stack traces and other debugging places. """ if self.origin: return six.text_type(self.origin / self.relpath) else: return six.text_type(self.relpath) def __repr__(self): return "<{0} {1!r} from {2!r}>".format( type(self).__name__, self.relpath, self.origin) def __hash__(self): return hash(self.key) def __eq__(self, other): if self is other: return True if not isinstance(other, SourceFile): return NotImplemented return self.key == other.key def __ne__(self, other): return not self == other @classmethod def _key_from_path(cls, path, origin=MISSING): # Given an origin (which may be MISSING) and an absolute path, # return a key. if origin is MISSING: # Resolve only the parent, in case the file itself is a symlink origin = path.parent.resolve() relpath = Path(path.name) else: # Again, resolving the origin is fine; we just don't want to # resolve anything inside it, lest we ruin some intended symlink # structure origin = origin.resolve() # pathlib balks if this requires lexically ascending <3 relpath = path.relative_to(origin) return origin, relpath @classmethod def read(cls, origin, relpath, **kwargs): """Read a source file from an ``(origin, relpath)`` tuple, as would happen from an ``@import`` statement. """ path = origin / relpath with path.open('rb') as f: return cls.from_file(f, origin, relpath, **kwargs) @classmethod def from_path(cls, path, origin=MISSING, **kwargs): """Read Sass source from a :class:`pathlib.Path`. If no origin is given, it's assumed to be the file's parent directory. """ origin, relpath = cls._key_from_path(path, origin) # Open in binary mode so we can reliably detect the encoding with path.open('rb') as f: return cls.from_file(f, origin, relpath, **kwargs) # back-compat @classmethod def from_filename(cls, path_string, origin=MISSING, **kwargs): """ Read Sass source from a String specifying the path """ path = Path(path_string) return cls.from_path(path, origin, **kwargs) @classmethod def from_file(cls, f, origin=MISSING, relpath=MISSING, **kwargs): """Read Sass source from a file or file-like object. If `origin` or `relpath` are missing, they are derived from the file's ``.name`` attribute as with `from_path`. If it doesn't have one, the origin becomes None and the relpath becomes the file's repr. """ contents = f.read() encoding = determine_encoding(contents) if isinstance(contents, six.binary_type): contents = contents.decode(encoding) if origin is MISSING or relpath is MISSING: filename = getattr(f, 'name', None) if filename is None: origin = None relpath = repr(f) else: origin, relpath = cls._key_from_path(Path(filename), origin) return cls(origin, relpath, contents, encoding=encoding, **kwargs) @classmethod def from_string(cls, string, relpath=None, encoding=None, is_sass=None): """Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...". """ if isinstance(string, six.text_type): # Already decoded; we don't know what encoding to use for output, # though, so still check for a @charset. # TODO what if the given encoding conflicts with the one in the # file? do we care? if encoding is None: encoding = determine_encoding(string) byte_contents = string.encode(encoding) text_contents = string elif isinstance(string, six.binary_type): encoding = determine_encoding(string) byte_contents = string text_contents = string.decode(encoding) else: raise TypeError("Expected text or bytes, got {0!r}".format(string)) origin = None if relpath is None: m = hashlib.sha256() m.update(byte_contents) relpath = repr("string:{0}:{1}".format( m.hexdigest()[:16], text_contents[:100])) return cls( origin, relpath, text_contents, encoding=encoding, is_sass=is_sass, ) def parse_scss_line(self, line, state): ret = '' if line is None: line = '' line = state['line_buffer'] + line if line and line[-1] == '\\': state['line_buffer'] = line[:-1] return '' else: state['line_buffer'] = '' output = state['prev_line'] output = output.strip() state['prev_line'] = line ret += output ret += '\n' return ret def parse_sass_line(self, line, state): ret = '' if line is None: line = '' line = state['line_buffer'] + line if line and line[-1] == '\\': state['line_buffer'] = line[:-1] return ret else: state['line_buffer'] = '' indent = len(line) - len(line.lstrip()) # make sure we support multi-space indent as long as indent is # consistent if indent and not state['indent_marker']: state['indent_marker'] = indent if state['indent_marker']: indent //= state['indent_marker'] if indent == state['prev_indent']: # same indentation as previous line if state['prev_line']: state['prev_line'] += ';' elif indent > state['prev_indent']: # new indentation is greater than previous, we just entered a new # block state['prev_line'] += ' {' state['nested_blocks'] += 1 else: # indentation is reset, we exited a block block_diff = state['prev_indent'] - indent if state['prev_line']: state['prev_line'] += ';' state['prev_line'] += ' }' * block_diff state['nested_blocks'] -= block_diff output = state['prev_line'] output = output.strip() state['prev_indent'] = indent state['prev_line'] = line ret += output ret += '\n' return ret def prepare_source(self, codestr, sass=False): state = { 'line_buffer': '', 'prev_line': '', 'prev_indent': 0, 'nested_blocks': 0, 'indent_marker': 0, } if self.is_sass: parse_line = self.parse_sass_line else: parse_line = self.parse_scss_line _codestr = codestr codestr = '' for line in _codestr.splitlines(): codestr += parse_line(line, state) # parse the last line stored in prev_line buffer codestr += parse_line(None, state) # pop off the extra \n parse_line puts at the beginning codestr = codestr[1:] # protects codestr: "..." strings codestr = _strings_re.sub( lambda m: _reverse_safe_strings_re.sub( lambda n: _reverse_safe_strings[n.group(0)], m.group(0)), codestr) codestr = _urls_re.sub( lambda m: _reverse_safe_strings_re.sub( lambda n: _reverse_safe_strings[n.group(0)], m.group(0)), codestr) # removes multiple line comments codestr = _ml_comment_re.sub('', codestr) # removes inline comments, but not :// (protocol) codestr = _sl_comment_re.sub('', codestr) codestr = _safe_strings_re.sub( lambda m: _safe_strings[m.group(0)], codestr) # collapse the space in properties blocks codestr = _collapse_properties_space_re.sub(r'\1{', codestr) return codestr
class SourceFile(object): '''A single input file to be fed to the compiler. Detects the encoding (according to CSS spec rules) and performs some light pre-processing. This class is mostly internal and you shouldn't have to worry about it. Source files are uniquely identified by their ``.key``, a 2-tuple of ``(origin, relpath)``. ``origin`` is an object from the compiler's search path, most often a directory represented by a :class:`pathlib.Path`. ``relpath`` is a relative path from there to the actual file, again usually a ``Path``. The idea here is that source files don't always actually come from the filesystem, yet import semantics are expressed in terms of paths. By keeping the origin and relative path separate, it's possible for e.g. Django to swap in an object that has the ``Path`` interface, but actually looks for files in an arbitrary storage backend. In that case it would make no sense to key files by their absolute path, as they may not exist on disk or even on the same machine. Also, relative imports can then continue to work, because they're guaranteed to only try the same origin. The ``origin`` may thus be anything that implements a minimal ``Path``ish interface (division operator, ``.parent``, ``.resolve()``). It may also be ``None``, indicating that the file came from a string or some other origin that can't usefully produce other files. ``relpath``, however, should always be a ``Path``. or string. XXX only when origin (There's little advantage to making it anything else.) A ``relpath`` may **never** contain ".."; there is nothing above the origin. Note that one minor caveat of this setup is that it's possible for the same file on disk to be imported under two different names (even though symlinks are always resolved), if directories in the search path happen to overlap. ''' def __init__( self, origin, relpath, contents, encoding=None, is_sass=None): '''Not normally used. See the three alternative constructors: :func:`SourceFile.from_file`, :func:`SourceFile.from_path`, and :func:`SourceFile.from_string`. ''' pass @property def path(self): '''Concatenation of ``origin`` and ``relpath``, as a string. Used in stack traces and other debugging places. ''' pass def __repr__(self): pass def __hash__(self): pass def __eq__(self, other): pass def __ne__(self, other): pass @classmethod def _key_from_path(cls, path, origin=MISSING): pass @classmethod def read(cls, origin, relpath, **kwargs): '''Read a source file from an ``(origin, relpath)`` tuple, as would happen from an ``@import`` statement. ''' pass @classmethod def from_path(cls, path, origin=MISSING, **kwargs): '''Read Sass source from a :class:`pathlib.Path`. If no origin is given, it's assumed to be the file's parent directory. ''' pass @classmethod def from_filename(cls, path_string, origin=MISSING, **kwargs): ''' Read Sass source from a String specifying the path ''' pass @classmethod def from_filename(cls, path_string, origin=MISSING, **kwargs): '''Read Sass source from a file or file-like object. If `origin` or `relpath` are missing, they are derived from the file's ``.name`` attribute as with `from_path`. If it doesn't have one, the origin becomes None and the relpath becomes the file's repr. ''' pass @classmethod def from_string(cls, string, relpath=None, encoding=None, is_sass=None): '''Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...". ''' pass def parse_scss_line(self, line, state): pass def parse_sass_line(self, line, state): pass def prepare_source(self, codestr, sass=False): pass
23
8
18
3
12
3
3
0.44
1
5
1
0
9
5
15
15
327
61
185
54
160
81
143
43
127
9
1
2
42
144,036
Kronuz/pyScss
Kronuz_pyScss/scss/tool.py
scss.tool.SassRepl
class SassRepl(object): def __init__(self, is_sass=False): # TODO it would be lovely to get these out of here, somehow self.namespace = Namespace(variables=_default_scss_vars) self.compiler = Compiler(namespace=self.namespace) self.compilation = self.compiler.make_compilation() self.legacy_compiler_options = {} self.source_file = SourceFile.from_string('', '<shell>', is_sass=is_sass) self.calculator = Calculator(self.namespace) def __call__(self, s): # TODO this is kind of invasive; surely it's possible to do this # without calling only private methods from pprint import pformat if s in ('exit', 'quit'): raise KeyboardInterrupt for s in s.split(';'): s = self.source_file.prepare_source(s.strip()) if not s: continue elif s.startswith('@'): scope = None properties = [] children = deque() rule = SassRule(self.source_file, namespace=self.namespace, legacy_compiler_options=self.legacy_compiler_options, properties=properties) block = UnparsedBlock(rule, 1, s, None) code, name = (s.split(None, 1) + [''])[:2] if code == '@option': self.compilation._at_options(self.calculator, rule, scope, block) continue elif code == '@import': # TODO this doesn't really work either since there's no path self.compilation._at_import(self.calculator, rule, scope, block) continue elif code == '@include': final_cont = '' self.compilation._at_include(self.calculator, rule, scope, block) code = self.compilation._print_properties(properties).rstrip('\n') if code: final_cont += code if children: # TODO this almost certainly doesn't work, and is kind of goofy anyway since @mixin isn't supported self.compilation.children.extendleft(children) self.compilation.parse_children() code = self.compilation._create_css(self.compilation.rules).rstrip('\n') if code: final_cont += code yield final_cont continue elif s == 'ls' or s.startswith('show(') or s.startswith('show ') or s.startswith('ls(') or s.startswith('ls '): m = re.match(r'(?:show|ls)(\()?\s*([^,/\\) ]*)(?:[,/\\ ]([^,/\\ )]+))*(?(1)\))', s, re.IGNORECASE) if m: name = m.group(2) code = m.group(3) name = name and name.strip().rstrip('s') # remove last 's' as in functions code = code and code.strip() ns = self.namespace if not name: yield pformat(list(sorted(['vars', 'options', 'mixins', 'functions']))) elif name in ('v', 'var', 'variable'): variables = dict(ns._variables) if code == '*': pass elif code: variables = dict((k, v) for k, v in variables.items() if code in k) else: variables = dict((k, v) for k, v in variables.items() if not k.startswith('$--')) yield pformat(variables) elif name in ('o', 'opt', 'option'): opts = self.legacy_compiler_options if code == '*': pass elif code: opts = dict((k, v) for k, v in opts.items() if code in k) else: opts = dict((k, v) for k, v in opts.items()) yield pformat(opts) elif name in ('m', 'mix', 'mixin', 'f', 'func', 'funct', 'function'): if name.startswith('m'): funcs = dict(ns._mixins) elif name.startswith('f'): funcs = dict(ns._functions) if code == '*': pass elif code: funcs = dict((k, v) for k, v in funcs.items() if code in k[0]) else: pass # TODO print source when possible yield pformat(funcs) continue elif s.startswith('$') and (':' in s or '=' in s): prop, value = [a.strip() for a in _prop_split_re.split(s, 1)] prop = self.calculator.do_glob_math(prop) value = self.calculator.calculate(value) self.namespace.set_variable(prop, value) continue # TODO respect compress? try: yield(self.calculator.calculate(s).render()) except (SyntaxError, SassEvaluationError) as e: print("%s" % e, file=sys.stderr)
class SassRepl(object): def __init__(self, is_sass=False): pass def __call__(self, s): pass
3
0
53
3
47
4
14
0.09
1
11
7
0
2
6
2
2
108
7
94
24
90
8
79
23
75
27
1
5
28
144,037
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Arglist
class Arglist(List): """An argument list. Acts mostly like a list, with keyword arguments sort of tacked on separately, and only accessible via Python (or the Sass `keywords` function). """ sass_type_name = 'arglist' keywords_retrieved = False def __init__(self, args, kwargs): self._kwargs = Map(kwargs) super(Arglist, self).__init__(args, use_comma=True) def extract_keywords(self): self.keywords_retrieved = True return self._kwargs
class Arglist(List): '''An argument list. Acts mostly like a list, with keyword arguments sort of tacked on separately, and only accessible via Python (or the Sass `keywords` function). ''' def __init__(self, args, kwargs): pass def extract_keywords(self): pass
3
1
3
0
3
0
1
0.44
1
2
1
0
2
1
2
49
15
2
9
6
6
4
9
6
6
1
3
0
2
144,038
Kronuz/pyScss
Kronuz_pyScss/scss/types.py
scss.types.Function
class Function(String): """Function call pseudo-type, which crops up frequently in CSS as a string marker. Acts mostly like a string, but has a function name and parentheses around it. """ def __init__(self, string, function_name, quotes='"', literal=False): super(Function, self).__init__(string, quotes=quotes, literal=literal) self.function_name = function_name def render(self, compress=False): return "{0}({1})".format( self.function_name, super(Function, self).render(compress), ) def render_interpolated(self, compress=False): return "{0}({1})".format( self.function_name, super(Function, self).render_interpolated(compress), )
class Function(String): '''Function call pseudo-type, which crops up frequently in CSS as a string marker. Acts mostly like a string, but has a function name and parentheses around it. ''' def __init__(self, string, function_name, quotes='"', literal=False): pass def render(self, compress=False): pass def render_interpolated(self, compress=False): pass
4
1
4
0
4
0
1
0.29
1
1
0
1
3
1
3
41
20
2
14
5
10
4
8
5
4
1
3
0
3
144,039
Kronuz/pyScss
Kronuz_pyScss/scss/errors.py
scss.errors.SassParseError
class SassParseError(SassError): """Error raised when parsing a Sass expression fails.""" def format_prefix(self): decorated_expr, line = add_error_marker(self.expression, self.expression_pos or -1) return """Error parsing expression at {1}:\n{0}\n""".format(decorated_expr, self.expression_pos)
class SassParseError(SassError): '''Error raised when parsing a Sass expression fails.''' def format_prefix(self): pass
2
1
3
0
3
0
1
0.25
1
0
0
0
1
0
1
23
6
1
4
3
2
1
4
3
2
1
5
0
1
144,040
Kronuz/pyScss
Kronuz_pyScss/scss/errors.py
scss.errors.SassMissingDependency
class SassMissingDependency(SassBaseError): """Error raised when an optional library (e.g., PIL or fontforge) is missing. """ def __init__(self, library, activity, **kwargs): super(SassMissingDependency, self).__init__(**kwargs) self.library = library self.activity = activity def format_message(self): return "{0} requires {1}, which is not installed".format( self.activity, self.library)
class SassMissingDependency(SassBaseError): '''Error raised when an optional library (e.g., PIL or fontforge) is missing. ''' def __init__(self, library, activity, **kwargs): pass def format_message(self): pass
3
1
4
1
4
0
1
0.38
1
1
0
0
2
2
2
18
14
3
8
5
5
3
7
5
4
1
4
0
2
144,041
Kronuz/pyScss
Kronuz_pyScss/scss/errors.py
scss.errors.SassImportError
class SassImportError(SassBaseError): """Error raised when unable to resolve an @import.""" def __init__(self, bad_name, compiler, **kwargs): super(SassImportError, self).__init__(**kwargs) self.bad_name = bad_name self.compiler = compiler def format_message(self): return ( "Couldn't find anything to import: {0}\n" "Extensions: {1}\n" "Search path:\n {2}" .format( self.bad_name, ", ".join(repr(ext) for ext in self.compiler.extensions), "\n ".join(str(path) for path in self.compiler.search_path), ) )
class SassImportError(SassBaseError): '''Error raised when unable to resolve an @import.''' def __init__(self, bad_name, compiler, **kwargs): pass def format_message(self): pass
3
1
8
1
8
0
1
0.06
1
2
0
0
2
2
2
18
20
3
16
5
13
1
7
5
4
1
4
0
2
144,042
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.ListLiteral
class ListLiteral(Expression): def __repr__(self): return '<%s(%s, comma=%s)>' % (self.__class__.__name__, repr(self.items), repr(self.comma)) def __init__(self, items, comma=True): self.items = items self.comma = comma def evaluate(self, calculator, divide=False): items = [item.evaluate(calculator, divide=divide) for item in self.items] # Whether this is a "plain" literal matters for null removal: nulls are # left alone if this is a completely vanilla CSS property literal = True if divide: # TODO sort of overloading "divide" here... rename i think literal = False elif not all(isinstance(item, Literal) for item in self.items): literal = False return List(items, use_comma=self.comma, literal=literal)
class ListLiteral(Expression): def __repr__(self): pass def __init__(self, items, comma=True): pass def evaluate(self, calculator, divide=False): pass
4
0
6
1
4
1
2
0.21
1
2
2
0
3
2
3
5
21
4
14
8
10
3
13
8
9
3
2
1
5
144,043
Kronuz/pyScss
Kronuz_pyScss/scss/extension/compass/layouts.py
scss.extension.compass.layouts.LayoutNode
class LayoutNode(object): def __init__(self, x, y, w, h, down=None, right=None, used=False): self.x = x self.y = y self.w = w self.h = h self.down = down self.right = right self.used = used self.width = 0 self.height = 0 @property def area(self): return self.width * self.height def __repr__(self): return '<%s (%s, %s) [%sx%s]>' % (self.__class__.__name__, self.x, self.y, self.w, self.h)
class LayoutNode(object): def __init__(self, x, y, w, h, down=None, right=None, used=False): pass @property def area(self): pass def __repr__(self): pass
5
0
5
0
5
0
1
0
1
0
0
0
3
9
3
3
18
2
16
14
11
0
15
13
11
1
1
0
3
144,044
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.MapLiteral
class MapLiteral(Expression): def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, repr(self.pairs)) def __init__(self, pairs): self.pairs = tuple((var, value) for var, value in pairs if value is not None) def evaluate(self, calculator, divide=False): scss_pairs = [] for key, value in self.pairs: scss_pairs.append(( key.evaluate(calculator), value.evaluate(calculator), )) return Map(scss_pairs)
class MapLiteral(Expression): def __repr__(self): pass def __init__(self, pairs): pass def evaluate(self, calculator, divide=False): pass
4
0
4
0
4
0
1
0
1
2
1
0
3
1
3
5
16
3
13
7
9
0
10
7
6
2
2
1
4
144,045
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.NotOp
class NotOp(Expression): def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, repr(self.operand)) def __init__(self, operand): self.operand = operand def evaluate(self, calculator, divide=False): operand = self.operand.evaluate(calculator, divide=True) return Boolean(not(operand))
class NotOp(Expression): def __repr__(self): pass def __init__(self, operand): pass def evaluate(self, calculator, divide=False): pass
4
0
2
0
2
0
1
0
1
1
1
0
3
1
3
5
10
2
8
6
4
0
8
6
4
1
2
0
3
144,046
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.Parentheses
class Parentheses(Expression): """An expression of the form `(foo)`. Only exists to force a slash to be interpreted as division when contained within parentheses. """ def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, repr(self.contents)) def __init__(self, contents): self.contents = contents def evaluate(self, calculator, divide=False): return self.contents.evaluate(calculator, divide=True)
class Parentheses(Expression): '''An expression of the form `(foo)`. Only exists to force a slash to be interpreted as division when contained within parentheses. ''' def __repr__(self): pass def __init__(self, contents): pass def evaluate(self, calculator, divide=False): pass
4
1
2
0
2
0
1
0.57
1
0
0
0
3
1
3
5
14
3
7
5
3
4
7
5
3
1
2
0
3
144,047
Kronuz/pyScss
Kronuz_pyScss/scss/ast.py
scss.ast.TernaryOp
class TernaryOp(Expression): """Sass implements this with a function: prop: if(condition, true-value, false-value); However, the second and third arguments are guaranteed not to be evaluated unless necessary. Functions always receive evaluated arguments, so this is a syntactic construct in disguise. """ def __repr__(self): return '<%s(%r, %r, %r)>' % ( self.__class__.__name__, self.condition, self.true_expression, self.false_expression, ) def __init__(self, list_literal): args = list_literal.items if len(args) != 3: raise SyntaxError("if() must have exactly 3 arguments") self.condition, self.true_expression, self.false_expression = args def evaluate(self, calculator, divide=False): if self.condition.evaluate(calculator, divide=True): return self.true_expression.evaluate(calculator, divide=True) else: return self.false_expression.evaluate(calculator, divide=True)
class TernaryOp(Expression): '''Sass implements this with a function: prop: if(condition, true-value, false-value); However, the second and third arguments are guaranteed not to be evaluated unless necessary. Functions always receive evaluated arguments, so this is a syntactic construct in disguise. ''' def __repr__(self): pass def __init__(self, list_literal): pass def evaluate(self, calculator, divide=False): pass
4
1
6
0
6
0
2
0.33
1
1
0
0
3
3
3
5
28
4
18
6
14
6
12
6
8
2
2
1
5