sass4 4.0.4 → 4.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b021450fcc4e657986b7fbddb76101e9c998d3bf0cc7d410bce53bfdd92fd470
4
- data.tar.gz: 3bed1c189f812c0ed4bc13008a6136bfb247b0acf5be20a9c20bc29da5a9d8c2
3
+ metadata.gz: 11baf535153d1d5ef14f1a22f183d930d4c4687b3f56e6db6d011aaf6a6f0e7b
4
+ data.tar.gz: 15acd11e9524c20aa2c7090196b41d7050909c271d713e7664716da8e448da1f
5
5
  SHA512:
6
- metadata.gz: b682b82f391271420c1af276c61748aa49f47ba6cc6e64fac6ef866367cff6fd5e33ec016852c316ec08289f547d287491c7d1fcddc0845ace1abded2dd24e62
7
- data.tar.gz: f092c181f50eb32ac4e0dc3080bb532e53cb36201bfc4dfe5368e1320da14d8cb87234740748320207349393a8c6fae972591047cb0be669b4428284238ac6b7
6
+ metadata.gz: 8e90e62e32c69a69d8dc768ccbaa05d41c62e45535546ad6f3b02c71c4e3d48d842bb8c788dca9206d8e9a622c1eeb9fc106f375fcf528b4b4f977b0fef9de4b
7
+ data.tar.gz: '0569e2259f0124deb4ebc5f05f68197a7da82c011dd1777d440985fcd9b53769f8c8f4cd421aa0f65253db0fa735e7c11afd17dbfa0fc0fc7b00eea6e818d331'
data/CONTRIBUTING.md CHANGED
@@ -39,26 +39,9 @@ merging.
39
39
 
40
40
  ### Testing
41
41
 
42
- Tests for changes to the Sass language go in
43
- [sass-spec](https://github.com/sass/sass-spec) so that other
44
- implementations (E.g. libSass) can be tested against the same test
45
- suite. The sass-spec repo follows a "trunk development" model in that
46
- the tests there test against different version of the Sass language (as
47
- opposed to having branches that track different Sass versions). When
48
- contributing changes to Sass, update the Gemfile to use sass-spec from a
49
- branch or fork that has the new tests. When the feature lands in Sass,
50
- the committer will also merge the corresponding sass-spec changes.
51
-
52
- The [documentation of
53
- sass-spec](https://github.com/sass/sass-spec/blob/master/README.md)
54
- explains how to run sass-spec and contribute changes. In development,
55
- Change the Gemfile(s) to use the `:path` option against the sass-spec gem
56
- to link your local checkout of sass and sass-spec together in one or
57
- both directions.
58
-
59
- Changes to Sass internals or Ruby Sass specific features (E.g.
60
- the `sass-convert` tool) should always have tests in the Sass `test`
61
- directory following the conventions you see there.
42
+ Add regression tests under `test/sass/` following the conventions of nearby
43
+ tests. Run the suite with `bundle exec rake test`, or run a single file with
44
+ `bundle exec ruby -Ilib:test test/sass/functions_test.rb`.
62
45
 
63
46
  ### Feature Branches
64
47
 
data/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ # sass4
2
+
3
+ `sass4` is a fork of Ruby Sass for existing projects. It adds compatibility with modern Ruby and support for selected modern CSS syntax, including CSS variables and space-separated `rgb()` and `hsl()` colors.
4
+
1
5
  ## Ruby Sass Has Reached End-of-Life
2
6
 
3
7
  Ruby Sass should no longer be used, and will no longer be receiving any updates.
@@ -13,7 +17,7 @@ See [the Sass blog][], and consider switching to the [`sassc` gem].
13
17
 
14
18
  This project has been updated for compatibility with modern Ruby versions.
15
19
 
16
- # Sass [![Travis Build Status](https://travis-ci.org/sass/ruby-sass.svg?branch=next)](https://travis-ci.org/sass/ruby-sass) [![Gem Version](https://badge.fury.io/rb/sass.svg)](http://badge.fury.io/rb/sass) [![Inline docs](http://inch-ci.org/github/sass/sass.svg)](http://inch-ci.org/github/sass/sass)
20
+ [![CI](https://github.com/VladimirIvanin/ruby-sass/actions/workflows/ci.yml/badge.svg)](https://github.com/VladimirIvanin/ruby-sass/actions/workflows/ci.yml) [![Gem version](https://badge.fury.io/rb/sass4.svg)](https://rubygems.org/gems/sass4)
17
21
 
18
22
  **Sass makes CSS fun again**. Sass is an extension of CSS,
19
23
  adding nested rules, variables, mixins, selector inheritance, and more.
@@ -41,7 +45,7 @@ Sass can be used from the command line
41
45
  or as part of a web framework.
42
46
  The first step is to install the gem:
43
47
 
44
- gem install sass
48
+ gem install sass4
45
49
 
46
50
  After you convert some CSS to Sass, you can run
47
51
 
@@ -52,14 +56,7 @@ For more information on these commands, check out
52
56
 
53
57
  sass --help
54
58
 
55
- To install Sass in Rails 2,
56
- just add `config.gem "sass"` to `config/environment.rb`.
57
- In Rails 3, add `gem "sass"` to your Gemfile instead.
58
- `.sass` or `.scss` files should be placed in `public/stylesheets/sass`,
59
- where they'll be automatically compiled
60
- to corresponding CSS files in `public/stylesheets` when needed
61
- (the Sass template directory is customizable...
62
- see [the Sass reference](https://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#template_location-option) for details).
59
+ If your project uses Bundler, add `gem 'sass4', :require => 'sass'` to your Gemfile.
63
60
 
64
61
  Sass can also be used with any Rack-enabled web framework.
65
62
  To do so, just add
@@ -76,6 +73,37 @@ will be compiled into CSS files in `public/stylesheets` on every request.
76
73
  To use Sass programmatically,
77
74
  check out the [YARD documentation](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#using_sass).
78
75
 
76
+ ## Development and releases
77
+
78
+ Run the Ruby test suite with Bundler and Rake.
79
+
80
+ ```sh
81
+ bundle install
82
+ bundle exec rake test
83
+ ```
84
+
85
+ CI runs the suite on Ruby 3.3, 4.0.10, and the latest stable MRI release.
86
+ To build the gem and source archive locally, run `bundle exec rake package`.
87
+ To build the API documentation, install the optional `docs` group with
88
+ `BUNDLE_WITH=docs bundle install` and run `BUNDLE_WITH=docs bundle exec rake doc`.
89
+
90
+ Configure a [RubyGems trusted publisher] for `sass4` with owner `VladimirIvanin`,
91
+ repository `ruby-sass`, and workflow filename `release.yml`. Leave the environment
92
+ field blank.
93
+
94
+ Commit the release version in `VERSION`, then create and push its matching `v` tag.
95
+ For example, with `VERSION` set to `4.0.6`, run the following commands.
96
+
97
+ ```sh
98
+ git tag -a v4.0.6 -m 'Release sass4 4.0.6'
99
+ git push origin v4.0.6
100
+ ```
101
+
102
+ GitHub Actions runs the CI matrix and checks the tag against `VERSION` before
103
+ building and publishing the gem to RubyGems.org.
104
+
105
+ [RubyGems trusted publisher]: https://guides.rubygems.org/trusted-publishing/#adding-a-trusted-publisher-to-an-existing-gem
106
+
79
107
  ## Formatting
80
108
 
81
109
  Sass is an extension of CSS
data/VERSION CHANGED
@@ -1 +1 @@
1
- 4.0.4
1
+ 4.0.6
@@ -688,8 +688,8 @@ module Sass::Script
688
688
  # Legacy comma-separated syntax
689
689
  red, green, blue = args
690
690
  if green.nil?
691
- return unquoted_string("rgb(#{red})") if red.is_var?
692
- raise ArgumentError.new("wrong number of arguments (1 for 3)")
691
+ return unquoted_string("rgb(#{red})") if red&.is_var?
692
+ raise ArgumentError.new("wrong number of arguments (#{args.size} for 3)")
693
693
  elsif blue.nil?
694
694
  return unquoted_string("rgb(#{red}, #{green})") if red.is_var? || green.is_var?
695
695
  raise ArgumentError.new("wrong number of arguments (2 for 3)")
@@ -891,8 +891,8 @@ module Sass::Script
891
891
  # Legacy comma-separated syntax
892
892
  hue, saturation, lightness = args
893
893
  if saturation.nil?
894
- return unquoted_string("hsl(#{hue})") if hue.is_var?
895
- raise ArgumentError.new("wrong number of arguments (1 for 3)")
894
+ return unquoted_string("hsl(#{hue})") if hue&.is_var?
895
+ raise ArgumentError.new("wrong number of arguments (#{args.size} for 3)")
896
896
  elsif lightness.nil?
897
897
  return unquoted_string("hsl(#{hue}, #{saturation})") if hue.is_var? || saturation.is_var?
898
898
  raise ArgumentError.new("wrong number of arguments (2 for 3)")
@@ -968,8 +968,8 @@ module Sass::Script
968
968
  # Legacy comma-separated syntax
969
969
  hue, saturation, lightness, alpha = args
970
970
  if saturation.nil?
971
- return unquoted_string("hsla(#{hue})") if hue.is_var?
972
- raise ArgumentError.new("wrong number of arguments (1 for 4)")
971
+ return unquoted_string("hsla(#{hue})") if hue&.is_var?
972
+ raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
973
973
  elsif lightness.nil?
974
974
  return unquoted_string("hsla(#{hue}, #{saturation})") if hue.is_var? || saturation.is_var?
975
975
  raise ArgumentError.new("wrong number of arguments (2 for 4)")
@@ -977,7 +977,7 @@ module Sass::Script
977
977
  if hue.is_var? || saturation.is_var? || lightness.is_var?
978
978
  return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness})")
979
979
  else
980
- raise ArgumentError.new("wrong number of arguments (2 for 4)")
980
+ raise ArgumentError.new("wrong number of arguments (3 for 4)")
981
981
  end
982
982
  end
983
983
 
@@ -300,13 +300,13 @@ module Sass::Script::Tree
300
300
  message = "wrong number of arguments (#{given} for #{expected})"
301
301
  end
302
302
  end
303
- elsif (md = /^wrong number of arguments \(given (\d+), expected (\d+)\)/.match(e.message)) &&
304
- e.backtrace[0] =~ /:in `#{ruby_name}'$/
305
- # Handle ruby 2.3 error formatting
306
- message = "wrong number of arguments (#{md[1]} for #{md[2]})"
307
- elsif e.message =~ /^wrong number of arguments/ &&
308
- e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
309
- raise e
303
+ elsif message.start_with?('wrong number of arguments')
304
+ callee, call_site = e.backtrace_locations
305
+ raise e unless callee && callee.base_label == ruby_name &&
306
+ call_site && call_site.base_label == '_perform' && call_site.path == __FILE__
307
+
308
+ counts = message.match(/\Awrong number of arguments \(given (\d+), expected (\d+(?:\.\.\d+|\+)?)\)/)
309
+ message = "wrong number of arguments (#{counts[1]} for #{counts[2]})" if counts
310
310
  end
311
311
  raise Sass::SyntaxError.new("#{message} for `#{name}'")
312
312
  end
@@ -905,6 +905,7 @@ module Sass
905
905
  #
906
906
  # [token consumption algorithm]: https://drafts.csswg.org/css-syntax-3/#consume-token.
907
907
  result = sass_variable_in_custom_property ||
908
+ declaration_value_quoted_url ||
908
909
  tok(%r{
909
910
  (
910
911
  (?!
@@ -943,6 +944,25 @@ module Sass
943
944
  end
944
945
  end
945
946
 
947
+ # url("...") and url('...') inside custom property values (Dart Sass
948
+ # handles these via bracket/string scanning; our url lexer only matched
949
+ # unquoted URLCHAR, so quoted data URIs failed before any '(' token).
950
+ def declaration_value_quoted_url
951
+ start = @scanner.pos
952
+ return unless tok(/url\(#{W}/i)
953
+ inner = interp_string
954
+ unless inner
955
+ @scanner.pos = start
956
+ return
957
+ end
958
+ ss
959
+ unless tok(/\)/)
960
+ @scanner.pos = start
961
+ return
962
+ end
963
+ ['url(', *inner, ')']
964
+ end
965
+
946
966
  def declaration
947
967
  # This allows the "*prop: val", ":prop: val", "#prop: val", and ".prop:
948
968
  # val" hacks.
data/lib/sass/util.rb CHANGED
@@ -439,11 +439,9 @@ module Sass
439
439
  def caller_info(entry = nil)
440
440
  # JRuby evaluates `caller` incorrectly when it's in an actual default argument.
441
441
  entry ||= caller[1]
442
- info = entry.scan(/^((?:[A-Za-z]:)?.*?):(-?.*?)(?::.*`(.+)')?$/).first
443
- info[1] = info[1].to_i
444
- # This is added by Rubinius to designate a block, but we don't care about it.
445
- info[2].sub!(/ \{\}\Z/, '') if info[2]
446
- info
442
+ match = entry.match(/\A((?:[A-Za-z]:)?.*?):(-?\d+)(?::\s*in (?:`(.+)'|'(.+)'))?\z/)
443
+ method = match[3]&.sub(/ \{\}\z/, '') || match[4]&.sub(/\A.*[.#]/, '')
444
+ [match[1], match[2].to_i, method]
447
445
  end
448
446
 
449
447
  # Returns whether one version string represents a more recent version than another.
metadata CHANGED
@@ -1,17 +1,16 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sass4
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.0.4
4
+ version: 4.0.6
5
5
  platform: ruby
6
6
  authors:
7
7
  - Natalie Weizenbaum
8
8
  - Chris Eppstein
9
9
  - Hampton Catlin
10
10
  - Vladimir Ivanin
11
- autorequire:
12
11
  bindir: bin
13
12
  cert_chain: []
14
- date: 2026-04-03 00:00:00.000000000 Z
13
+ date: 1980-01-02 00:00:00.000000000 Z
15
14
  dependencies:
16
15
  - !ruby/object:Gem::Dependency
17
16
  name: sass-listen
@@ -27,62 +26,6 @@ dependencies:
27
26
  - - "~>"
28
27
  - !ruby/object:Gem::Version
29
28
  version: 4.0.0
30
- - !ruby/object:Gem::Dependency
31
- name: yard
32
- requirement: !ruby/object:Gem::Requirement
33
- requirements:
34
- - - "~>"
35
- - !ruby/object:Gem::Version
36
- version: 0.9.0
37
- type: :development
38
- prerelease: false
39
- version_requirements: !ruby/object:Gem::Requirement
40
- requirements:
41
- - - "~>"
42
- - !ruby/object:Gem::Version
43
- version: 0.9.0
44
- - !ruby/object:Gem::Dependency
45
- name: redcarpet
46
- requirement: !ruby/object:Gem::Requirement
47
- requirements:
48
- - - "~>"
49
- - !ruby/object:Gem::Version
50
- version: 3.6.0
51
- type: :development
52
- prerelease: false
53
- version_requirements: !ruby/object:Gem::Requirement
54
- requirements:
55
- - - "~>"
56
- - !ruby/object:Gem::Version
57
- version: 3.6.0
58
- - !ruby/object:Gem::Dependency
59
- name: nokogiri
60
- requirement: !ruby/object:Gem::Requirement
61
- requirements:
62
- - - "~>"
63
- - !ruby/object:Gem::Version
64
- version: 1.15.0
65
- type: :development
66
- prerelease: false
67
- version_requirements: !ruby/object:Gem::Requirement
68
- requirements:
69
- - - "~>"
70
- - !ruby/object:Gem::Version
71
- version: 1.15.0
72
- - !ruby/object:Gem::Dependency
73
- name: minitest
74
- requirement: !ruby/object:Gem::Requirement
75
- requirements:
76
- - - "~>"
77
- - !ruby/object:Gem::Version
78
- version: '5.20'
79
- type: :development
80
- prerelease: false
81
- version_requirements: !ruby/object:Gem::Requirement
82
- requirements:
83
- - - "~>"
84
- - !ruby/object:Gem::Version
85
- version: '5.20'
86
29
  description: |2
87
30
  This is a fork of Ruby Sass with modern Ruby compatibility (Ruby 3.0+).
88
31
  Original Ruby Sass is deprecated! See https://github.com/sass/ruby-sass for details.
@@ -100,7 +43,6 @@ extensions: []
100
43
  extra_rdoc_files: []
101
44
  files:
102
45
  - ".yardopts"
103
- - AGENTS.md
104
46
  - CODE_OF_CONDUCT.md
105
47
  - CONTRIBUTING.md
106
48
  - MIT-LICENSE
@@ -110,7 +52,6 @@ files:
110
52
  - bin/sass
111
53
  - bin/sass-convert
112
54
  - bin/scss
113
- - extra/sass-spec-ref.sh
114
55
  - extra/update_watch.rb
115
56
  - init.rb
116
57
  - lib/sass.rb
@@ -276,8 +217,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
276
217
  - !ruby/object:Gem::Version
277
218
  version: '0'
278
219
  requirements: []
279
- rubygems_version: 3.3.7
280
- signing_key:
220
+ rubygems_version: 4.0.20
281
221
  specification_version: 4
282
222
  summary: A powerful but elegant CSS compiler that makes CSS fun again.
283
223
  test_files: []
224
+ ...
data/AGENTS.md DELETED
@@ -1,587 +0,0 @@
1
- # AGENTS.md - Ruby Sass Project Guide
2
-
3
- ## Обзор проекта
4
-
5
- **Ruby Sass** - это оригинальная реализация препроцессора CSS Sass на Ruby. Проект достиг конца жизненного цикла (end-of-life) и больше не поддерживается. Рекомендуется использовать Dart Sass или sassc gem.
6
-
7
- **Версия:** 3.7.4.7a50eae
8
- **Лицензия:** MIT
9
- **Статус:** End-of-life (не рекомендуется к использованию)
10
-
11
- ## Архитектура проекта
12
-
13
- ### Основные компоненты
14
-
15
- ```
16
- lib/sass/
17
- ├── engine.rb # Основной движок компиляции
18
- ├── tree/ # AST (Abstract Syntax Tree) узлы
19
- │ ├── node.rb # Базовый класс для всех узлов
20
- │ ├── import_node.rb # Обработка @import директив
21
- │ ├── if_node.rb # Обработка @if/@else директив
22
- │ ├── rule_node.rb # CSS правила
23
- │ └── visitors/ # Паттерн Visitor для обхода AST
24
- │ ├── perform.rb # Выполнение динамических узлов
25
- │ ├── convert.rb # Конвертация в исходный код
26
- │ └── to_css.rb # Генерация CSS
27
- ├── script/ # SassScript (выражения и функции)
28
- ├── scss/ # SCSS парсер
29
- ├── importers/ # Система импорта файлов
30
- ├── cache_stores/ # Кэширование
31
- └── plugin/ # Интеграции с фреймворками
32
- ```
33
-
34
- ### Ключевые классы
35
-
36
- - **Sass::Engine** - основной класс для компиляции Sass/SCSS
37
- - **Sass::Tree::Node** - базовый класс для всех AST узлов
38
- - **Sass::Tree::Visitors::Perform** - visitor для выполнения динамических операций
39
- - **Sass::Tree::Visitors::ToCss** - visitor для генерации CSS
40
- - **Sass::Importers::Filesystem** - импортер файлов из файловой системы
41
-
42
- ## Тестовая структура
43
-
44
- ### Организация тестов
45
-
46
- Проект использует **Minitest** как основной фреймворк тестирования с двумя типами тестов:
47
-
48
- 1. **Ruby тесты** (`test:ruby`) - внутренние тесты проекта
49
- 2. **Sass-spec тесты** (`test:spec`) - тесты из официальной спецификации
50
-
51
- ### Структура тестов
52
-
53
- ```
54
- test/
55
- ├── test_helper.rb # Общие утилиты для тестов
56
- ├── sass/
57
- │ ├── engine_test.rb # Основные тесты движка (1500+ тестов)
58
- │ ├── templates/ # Sass/SCSS файлы для тестирования
59
- │ │ ├── basic.sass # Базовые тесты
60
- │ │ ├── import.sass # Тесты импорта
61
- │ │ ├── if.sass # Тесты условных директив
62
- │ │ ├── nested.sass # Тесты вложенности
63
- │ │ └── ...
64
- │ ├── results/ # Ожидаемые CSS результаты
65
- │ │ ├── basic.css
66
- │ │ ├── import.css
67
- │ │ └── ...
68
- │ ├── cache_test.rb # Тесты кэширования
69
- │ ├── functions_test.rb # Тесты встроенных функций
70
- │ ├── importer_test.rb # Тесты системы импорта
71
- │ └── util/ # Тесты утилит
72
- ```
73
-
74
- ### Типы тестов
75
-
76
- #### 1. Функциональные тесты (engine_test.rb)
77
- - **1500+ тестов** покрывающих все аспекты компиляции
78
- - Тестирование синтаксиса Sass и SCSS
79
- - Проверка обработки ошибок
80
- - Тесты производительности
81
-
82
- #### 2. Тесты на основе файлов
83
- ```ruby
84
- def renders_correctly(name, options={})
85
- sass_file = load_file(name, "sass")
86
- css_file = load_file(name, "css")
87
- css_result = Sass::Engine.new(sass_file, options).render
88
- assert_equal css_file, css_result
89
- end
90
- ```
91
-
92
- #### 3. Тесты импорта
93
- ```ruby
94
- def test_import_in_rule
95
- assert_equal(<<CSS, render(<<SASS, :load_paths => [File.dirname(__FILE__) + '/templates/']))
96
- .foo #foo {
97
- background-color: #baf; }
98
- CSS
99
- .foo
100
- @import partial
101
- SASS
102
- end
103
- ```
104
-
105
- ### Запуск тестов
106
-
107
- лучше запускать тесты через rake
108
-
109
- ```bash
110
- # Все тесты
111
- bundle exec rake test
112
-
113
- # Только Ruby тесты
114
- bundle exec rake test:ruby
115
-
116
- # Только Sass-spec тесты
117
- bundle exec rake test:spec
118
-
119
- # Конкретный тест
120
- ruby -Ilib:test test/sass/engine_test.rb -n test_import_in_rule
121
- ```
122
-
123
- ### Тестовые утилиты
124
-
125
- #### test_helper.rb предоставляет:
126
-
127
- ```ruby
128
- # Проверка преобразований
129
- def assert_converts(sass, scss, options: {})
130
- assert_sass_to_sass(sass, options: options)
131
- assert_scss_to_sass(sass, scss, options: options)
132
- assert_scss_to_scss(scss, options: options)
133
- assert_sass_to_scss(scss, sass, options: options)
134
- end
135
-
136
- # Проверка предупреждений
137
- def assert_warning(message)
138
- # Перехватывает stderr и проверяет сообщения
139
- end
140
-
141
- # Проверка исключений
142
- def assert_raise_message(klass, message)
143
- # Проверяет тип и сообщение исключения
144
- end
145
- ```
146
-
147
- ## Ключевые области для тестирования
148
-
149
- ### 1. Парсинг и AST
150
- - **Файлы:** `scss/parser.rb`, `script/parser.rb`
151
- - **Тесты:** `scss_test.rb`, `script_test.rb`
152
- - **Фокус:** Корректность парсинга различных конструкций
153
-
154
- ### 2. Система импорта
155
- - **Файлы:** `importers/`, `tree/import_node.rb`
156
- - **Тесты:** `importer_test.rb`, тесты в `engine_test.rb`
157
- - **Фокус:** Разрешение путей, кэширование, циклические зависимости
158
-
159
- ### 3. Выполнение SassScript
160
- - **Файлы:** `script/`, `tree/visitors/perform.rb`
161
- - **Тесты:** `script_test.rb`, `functions_test.rb`
162
- - **Фокус:** Математические операции, функции, переменные
163
-
164
- ### 4. Генерация CSS
165
- - **Файлы:** `tree/visitors/to_css.rb`
166
- - **Тесты:** Все тесты в `templates/` и `results/`
167
- - **Фокус:** Корректность вывода CSS
168
-
169
- ### 5. Кэширование
170
- - **Файлы:** `cache_stores/`
171
- - **Тесты:** `cache_test.rb`
172
- - **Фокус:** Производительность, инвалидация кэша
173
-
174
- ## Паттерны тестирования
175
-
176
- ### 1. Тестирование на основе файлов
177
- ```ruby
178
- # templates/test.sass -> results/test.css
179
- def test_basic
180
- renders_correctly "basic"
181
- end
182
- ```
183
-
184
- ### 2. Inline тестирование
185
- ```ruby
186
- def test_variables
187
- assert_equal(<<CSS, render(<<SASS))
188
- .foo {
189
- color: red; }
190
- CSS
191
- $color: red
192
- .foo
193
- color: $color
194
- SASS
195
- end
196
- ```
197
-
198
- ### 3. Тестирование ошибок
199
- ```ruby
200
- def test_invalid_syntax
201
- assert_raise_message(Sass::SyntaxError, "Invalid property") do
202
- render("invalid: syntax")
203
- end
204
- end
205
- ```
206
-
207
- ### 4. Тестирование предупреждений
208
- ```ruby
209
- def test_deprecation_warning
210
- assert_warning(/deprecated/) do
211
- render("deprecated-feature")
212
- end
213
- end
214
- ```
215
-
216
- ## Особенности тестирования
217
-
218
- ### 1. Поддержка двух синтаксисов
219
- Все тесты должны работать как для Sass, так и для SCSS:
220
- ```ruby
221
- def assert_converts(sass, scss, options: {})
222
- # Проверяет преобразования в обе стороны
223
- end
224
- ```
225
-
226
- ### 2. Тестирование с разными опциями
227
- ```ruby
228
- def test_with_options
229
- assert_equal(expected, render(input, :style => :compressed))
230
- end
231
- ```
232
-
233
- ### 3. Mock импортеры
234
- ```ruby
235
- # test/sass/mock_importer.rb
236
- class MockImporter < Sass::Importers::Base
237
- def add_import(name, content)
238
- # Добавляет виртуальные файлы для тестирования
239
- end
240
- end
241
- ```
242
-
243
- ## Рекомендации для разработчиков
244
-
245
- ### 1. При добавлении новых функций
246
- - Добавить тесты в `functions_test.rb`
247
- - Обновить документацию
248
- - Проверить совместимость с Sass-spec
249
-
250
- ### 2. При изменении парсера
251
- - Добавить тесты в соответствующие `*_test.rb` файлы
252
- - Проверить обработку ошибок
253
- - Убедиться в обратной совместимости
254
-
255
- ### 3. При оптимизации производительности
256
- - Добавить бенчмарки в тесты
257
- - Проверить кэширование
258
- - Убедиться в корректности результатов
259
-
260
- ### 4. При исправлении багов
261
- - Создать минимальный тест, воспроизводящий баг
262
- - Добавить регрессионный тест
263
- - Проверить edge cases
264
-
265
- ## Инструменты разработки
266
-
267
- ### 1. Rake задачи
268
- ```bash
269
- rake test # Все тесты
270
- rake test:ruby # Ruby тесты
271
- rake test:spec # Sass-spec тесты
272
- rake package # Сборка gem
273
- ```
274
-
275
- ### 2. Отладка
276
- ```ruby
277
- # Включение трассировки селекторов
278
- options[:trace_selectors] = true
279
-
280
- # Включение отладочной информации
281
- options[:debug_info] = true
282
- ```
283
-
284
- ### 3. Профилирование
285
- ```ruby
286
- # Измерение времени выполнения
287
- require 'benchmark'
288
- Benchmark.measure { engine.render }
289
- ```
290
-
291
- ## Запуск тестов
292
-
293
- ### Требования к системе
294
-
295
- **Ruby**: >= 3.0.0 (рекомендуется Ruby 3.1.2+)
296
-
297
- Файлы для управления версиями Ruby:
298
- - `.ruby-version` - указывает версию Ruby (3.1.2)
299
- - `.ruby-gemset` - указывает gemset для RVM (ruby-sass)
300
-
301
- ### Обновленные зависимости
302
-
303
- Проект был обновлен для совместимости с Ruby 3.1+:
304
-
305
- - **Rake**: ~> 13.0
306
- - **Minitest**: ~> 5.20
307
- - **Nokogiri**: ~> 1.15.0
308
- - **YARD**: ~> 0.9.0
309
- - **Redcarpet**: ~> 3.6.0
310
-
311
- ### Проблемы с зависимостями (решенные)
312
-
313
- 1. ✅ **MiniTest vs Minitest**: Исправлено во всех тестовых файлах
314
- 2. ✅ **Nokogiri**: Обновлен до версии 1.15.0
315
- 3. ⚠️ **Sass-spec**: Проблемы с ruby-terminfo, временно отключен
316
-
317
- ### Решение проблем
318
-
319
- #### 1. Исправление test_helper.rb
320
- ```ruby
321
- # В test/test_helper.rb заменить:
322
- class MiniTest::Test
323
- # На:
324
- class Minitest::Test
325
- ```
326
-
327
- #### 2. Настройка окружения
328
- ```bash
329
- # Если используете RVM
330
- rvm use 3.1.2
331
- rvm gemset create ruby-sass
332
- rvm gemset use ruby-sass
333
-
334
- # Если используете rbenv
335
- rbenv install 3.1.2
336
- rbenv local 3.1.2
337
-
338
- # Установка зависимостей
339
- bundle install
340
- ```
341
-
342
- #### 3. Запуск тестов
343
- ```bash
344
- # Запуск всех Ruby тестов (2122 теста)
345
- bundle exec rake test:ruby
346
-
347
- # Запуск конкретного теста
348
- bundle exec ruby -Ilib:test test/sass/css_level4_selectors_test.rb
349
-
350
- # Запуск всех тестов (включая sass-spec, если доступен)
351
- bundle exec rake test
352
- ```
353
-
354
- #### 4. Установка sass-spec по тегу
355
- Для работы с sass-spec можно использовать тег v3.5.4, который соответствует версии Ruby Sass:
356
-
357
- ```ruby
358
- # В Gemfile
359
- gem "sass-spec", :git => 'https://github.com/sass/sass-spec.git', :tag => 'v3.5.4'
360
- ```
361
-
362
- #### 5. Создание простых тестов
363
- Для избежания проблем с зависимостями можно создавать простые тесты без minitest/autorun:
364
-
365
- ```ruby
366
- #!/usr/bin/env ruby
367
- require_relative '../../lib/sass'
368
-
369
- class MyTest
370
- def test_something
371
- # Ваш тест
372
- result = Sass::Engine.new("body { color: red; }").render
373
- assert_equal "body {\n color: red; }\n", result
374
- end
375
-
376
- def assert_equal(expected, actual, message = nil)
377
- unless expected == actual
378
- raise "#{message || 'Assertion failed'}: expected '#{expected}', got '#{actual}'"
379
- end
380
- end
381
-
382
- def run_all_tests
383
- # Логика запуска всех тестов
384
- end
385
- end
386
-
387
- if __FILE__ == $0
388
- test = MyTest.new
389
- test.run_all_tests
390
- end
391
- ```
392
-
393
- ### Структура тестов
394
-
395
- ```
396
- test/
397
- ├── test_helper.rb # Общие утилиты (требует исправления)
398
- ├── sass/
399
- │ ├── engine_test.rb # Основные тесты движка
400
- │ ├── css_level4_selectors_test.rb # Тесты CSS Level 4 селекторов
401
- │ └── ...
402
- ```
403
-
404
- ### Рекомендации
405
-
406
- 1. **Для новых тестов**: Используйте простую структуру без minitest/autorun
407
- 2. **Для существующих тестов**: Исправьте test_helper.rb и запускайте через `ruby -Ilib:test`
408
- 3. **Для полного тестирования**: Обновите зависимости или используйте Docker с совместимой версией Ruby
409
-
410
- ## Реализация CSS Color Level 4 синтаксиса
411
-
412
- ### Обзор реализации
413
-
414
- Была реализована полная поддержка CSS Color Level 4 синтаксиса для цветовых функций `rgb()`, `rgba()`, `hsl()`, `hsla()`:
415
-
416
- **Новый синтаксис:**
417
- - **Space-separated значения**: `rgb(255 0 0)` вместо `rgb(255, 0, 0)`
418
- - **Slash-separated alpha**: `rgb(255 0 0 / 0.5)` вместо `rgba(255, 0, 0, 0.5)`
419
-
420
- **Поддержка special numbers (CSS функций):**
421
- - `var()` - CSS Custom Properties
422
- - `calc()` - математические вычисления
423
- - `env()` - environment variables
424
- - `attr()` - атрибуты элементов
425
- - `clamp()` - ограничение значений
426
- - `min()` / `max()` - минимум/максимум
427
-
428
- **Примеры:**
429
- ```scss
430
- // CSS Custom Properties
431
- .element {
432
- color: rgb(var(--r), var(--g), var(--b));
433
- background: hsl(var(--hue) 50% 50%);
434
- }
435
-
436
- // Вычисления
437
- .dynamic {
438
- color: rgb(255 128 0 / calc(0.5 * 2));
439
- border-color: hsl(calc(180deg + 10deg), 50%, 50%);
440
- }
441
-
442
- // Новый синтаксис
443
- .modern {
444
- color: rgb(255 128 0 / 0.5); // space-separated с alpha
445
- }
446
- ```
447
-
448
- ### Архитектурное решение
449
-
450
- #### Проблема 1: Парсинг slash-separated синтаксиса
451
-
452
- Парсер Ruby Sass интерпретировал символ `/` как оператор деления в выражениях типа `rgb(255 0 0 / 0.5)`, создавая неправильную AST структуру.
453
-
454
- **Решение:**
455
- 1. **Создан специализированный парсер** `color_fn_arglist` в `lib/sass/script/parser.rb`
456
- 2. **Модифицирован** метод `funcall` для использования `color_fn_arglist` для функций `rgb/rgba/hsl/hsla`
457
- 3. **Парсинг на уровне `unary_plus`** вместо `equals` для избежания интерпретации `/` как деления
458
-
459
- #### Проблема 2: Поддержка CSS special numbers
460
-
461
- CSS функции типа `var()`, `calc()` должны передаваться в CSS без вычисления, но Ruby Sass пытался их обработать.
462
-
463
- **Решение:**
464
- 1. **Добавлены методы проверки** в базовый класс `Value`:
465
- - `is_special_number?` - проверяет, является ли значение CSS функцией
466
- - `is_var?` - специальная проверка для `var()`
467
-
468
- 2. **Реализовано в `String` классе**:
469
- ```ruby
470
- def is_special_number?
471
- type == :identifier && value =~ /(calc|var|env|attr|clamp|min|max)\s*\(/i
472
- end
473
- ```
474
-
475
- 3. **Обновлена вспомогательная функция** `special_number?` в `lib/sass/script/value/helpers.rb` для поддержки всех CSS функций
476
-
477
- 4. **Модифицированы цветовые функции** для проверки special numbers и возврата CSS-строки вместо вычисления
478
-
479
- #### Детали реализации
480
-
481
- ##### 1. Парсер (lib/sass/script/parser.rb)
482
-
483
- Создан метод `color_fn_arglist` который:
484
- - Парсит аргументы используя `unary_plus` вместо `equals` чтобы избежать интерпретации `/` как деления
485
- - Определяет тип синтаксиса по следующему токену:
486
- - `:colon` → keyword arguments
487
- - `:comma` → legacy syntax
488
- - иначе → CSS Color Level 4 space/slash-separated
489
- - Создает правильную AST структуру для slash-separated alpha
490
-
491
- ##### 2. Функции цвета (lib/sass/script/functions.rb)
492
-
493
- Обновлены функции `rgb()`, `rgba()`, `hsl()`, `hsla()`:
494
-
495
- ```ruby
496
- def rgb(*args)
497
- if args.length == 1 && args[0].is_a?(Sass::Script::Value::List)
498
- list = args[0]
499
-
500
- # Проверка на var() - передаем как есть
501
- return unquoted_string("rgb(#{list})") if list.is_var?
502
-
503
- if list.separator == :space
504
- # Новый синтаксис
505
- if list.value.length == 2
506
- rgb_list, alpha_list = list.value
507
- # Проверка на special numbers
508
- if [red, green, blue, alpha].any? { |v| v.is_special_number? }
509
- return format_color_function("rgb", list)
510
- end
511
- # Обычное вычисление цвета
512
- end
513
- end
514
- end
515
- # Legacy syntax...
516
- end
517
- ```
518
-
519
- ##### 3. Форматирование вывода (lib/sass/script/value/helpers.rb)
520
-
521
- Добавлена функция `format_color_function` для правильного форматирования slash-separated синтаксиса:
522
-
523
- ```ruby
524
- def format_color_function(function_name, list)
525
- # Проверяет структуру списка и форматирует как "rgb(255 128 0 / 0.5)"
526
- # вместо "rgb(255 128 0 0.5)"
527
- end
528
- ```
529
-
530
- ### Результаты тестирования
531
-
532
- #### Тесты CSS Color Level 4 (`test/sass/css_color_level4_test.rb`)
533
-
534
- **29 тестов, все проходят:**
535
-
536
- **Special numbers:**
537
- - ✅ `rgb(var(--r), var(--g), var(--b))`
538
- - ✅ `rgb(calc(200 + 55), 100, 50)`
539
- - ✅ `rgb(env(--r), 128, 0)`
540
- - ✅ `rgb(clamp(0, 255, 300), 128, 0)`
541
- - ✅ `rgb(min(200, 255), max(100, 128), 0)`
542
-
543
- **Новый синтаксис с special numbers:**
544
- - ✅ `rgb(255 128 0 / var(--alpha))`
545
- - ✅ `rgb(255 128 0 / calc(0.5 * 2))`
546
- - ✅ `hsl(calc(180deg + 10deg), 50%, 50%)`
547
- - ✅ `hsl(180 50% 50% / calc(0.5 + 0.3))`
548
-
549
- **Обратная совместимость:**
550
- - ✅ Legacy синтаксис работает: `rgb(255, 128, 0)`
551
- - ✅ Новый синтаксис без special numbers: `rgb(255 128 0)`
552
- - ✅ Sass переменные: `rgba($color, var(--alpha))`
553
-
554
- #### Обратная совместимость
555
- - Все существующие тесты проходят
556
- - Legacy синтаксис полностью поддерживается
557
- - Keyword arguments работают
558
- - Sass переменные можно комбинировать с CSS функциями
559
-
560
- ### Ключевые уроки
561
-
562
- 1. **Архитектурный подход** - правильное решение на уровне парсера лучше чем обходные пути в функциях
563
- 2. **Приоритет операторов** - парсинг на уровне `unary_plus` избегает проблем с `/` как делением
564
- 3. **Объектно-ориентированная проверка** - методы `is_special_number?` и `is_var?` в классах Value обеспечивают чистую архитектуру
565
- 4. **Обратная совместимость** - критически важно сохранять работу всего существующего кода
566
-
567
- ### Файлы изменений
568
-
569
- **Основные изменения:**
570
- - `lib/sass/script/parser.rb` - добавлен `color_fn_arglist`, модифицирован `funcall`
571
- - `lib/sass/script/functions.rb` - обновлены `rgb`, `rgba`, `hsl`, `hsla`
572
- - `lib/sass/script/value/base.rb` - добавлены методы `is_special_number?` и `is_var?`
573
- - `lib/sass/script/value/string.rb` - реализованы методы проверки special numbers
574
- - `lib/sass/script/value/helpers.rb` - обновлен `special_number?`, добавлен `format_color_function`
575
-
576
- **Тесты:**
577
- - `test/sass/css_color_level4_test.rb` - 29 тестов для всех новых возможностей
578
-
579
- **Поддержка была добавлена ранее:**
580
- - `lib/sass/script/tree/list_literal.rb` - поддержка `:slash` разделителя
581
- - `lib/sass/script/value/list.rb` - поддержка `:slash` разделителя
582
-
583
- ## Заключение
584
-
585
- Ruby Sass имеет обширную тестовую базу с более чем 1500 тестами, покрывающими все аспекты функциональности. Тесты организованы по функциональным областям и используют как файловые, так и inline подходы. При работе с проектом важно понимать архитектуру AST и паттерн Visitor, а также следовать установленным паттернам тестирования.
586
-
587
- **Важно:** Проект достиг конца жизненного цикла. Для новых проектов рекомендуется использовать Dart Sass или sassc gem.
@@ -1,40 +0,0 @@
1
- #!/bin/bash -e
2
- # Copyright 2016 Google Inc. Use of this source code is governed by an MIT-style
3
- # license that can be found in the LICENSE file or at
4
- # https://opensource.org/licenses/MIT.
5
-
6
- # Echoes the sass-spec Git ref that should be checked out for the current Travis
7
- # run. If we're running specs for a pull request which refers to a sass-spec
8
- # pull request, we'll run against the latter rather than sass-spec master.
9
-
10
- default=master
11
-
12
- if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
13
- >&2 echo "TRAVIS_PULL_REQUEST: $TRAVIS_PULL_REQUEST."
14
- >&2 echo "Ref: $default."
15
- echo "$default"
16
- exit 0
17
- fi
18
-
19
- >&2 echo "Fetching pull request $TRAVIS_PULL_REQUEST..."
20
-
21
- url=https://api.github.com/repos/sass/ruby-sass/pulls/$TRAVIS_PULL_REQUEST
22
- if [ -z "$GITHUB_AUTH" ]; then
23
- >&2 echo "Fetching pull request info without authentication"
24
- JSON=$(curl -L -sS $url)
25
- else
26
- >&2 echo "Fetching pull request info as sassbot"
27
- JSON=$(curl -u "sassbot:$GITHUB_AUTH" -L -sS $url)
28
- fi
29
- >&2 echo "$JSON"
30
-
31
- RE_SPEC_PR="sass\/sass-spec(#|\/pull\/)([0-9]+)"
32
-
33
- if [[ $JSON =~ $RE_SPEC_PR ]]; then
34
- ref="pull/${BASH_REMATCH[2]}/head"
35
- >&2 echo "Ref: $ref."
36
- echo "$ref"
37
- else
38
- >&2 echo "Ref: $default."
39
- echo "$default"
40
- fi