hitomalu_formatter 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f3e95abbecfbc81d825e27b8e524fa921c3a12a436b0eac095585eaf0dd97d6c
4
+ data.tar.gz: c95385f93c2cf3e45d57d6c0cd568d1702a1f3092507245817b39894bbe1e39e
5
+ SHA512:
6
+ metadata.gz: a0251928b56f472a33b1811e5311d1a322710ccdceb243aec84f1169887082290340b6b7be6f16701ae0395a49cebd42f976ae8211b46825a6acb8209a4d7baa
7
+ data.tar.gz: 1c264419e16ac70dba68deca621008363503dc23a2db64fef9d6d84ad3f2cec9508eb6c3e8268b5cabcd1ae9a466da8fb9fb8267bb25bfaf303f82ec4a71cf53
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-07-21
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at satoshi_takami@dwango.co.jp. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in hitomalu_formatter.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "nokogiri"
data/Gemfile.lock ADDED
@@ -0,0 +1,38 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ hitomalu_formatter (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ diff-lcs (1.5.0)
10
+ nokogiri (1.13.7-x86_64-linux)
11
+ racc (~> 1.4)
12
+ racc (1.6.0)
13
+ rake (13.0.6)
14
+ rspec (3.11.0)
15
+ rspec-core (~> 3.11.0)
16
+ rspec-expectations (~> 3.11.0)
17
+ rspec-mocks (~> 3.11.0)
18
+ rspec-core (3.11.0)
19
+ rspec-support (~> 3.11.0)
20
+ rspec-expectations (3.11.0)
21
+ diff-lcs (>= 1.2.0, < 2.0)
22
+ rspec-support (~> 3.11.0)
23
+ rspec-mocks (3.11.1)
24
+ diff-lcs (>= 1.2.0, < 2.0)
25
+ rspec-support (~> 3.11.0)
26
+ rspec-support (3.11.0)
27
+
28
+ PLATFORMS
29
+ x86_64-linux
30
+
31
+ DEPENDENCIES
32
+ hitomalu_formatter!
33
+ nokogiri
34
+ rake (~> 13.0)
35
+ rspec (~> 3.0)
36
+
37
+ BUNDLED WITH
38
+ 2.3.18
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Satoshi-Takami
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # HitomaluFormatter
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/hitomalu_formatter`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ $ bundle add hitomalu_formatter
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ $ gem install hitomalu_formatter
16
+
17
+ ## Usage
18
+
19
+ require "hitomalu_formatter"
20
+ Hitomalu::Formatter.format(your_unformatted_html_string)
21
+
22
+ ex.
23
+
24
+ Hitomalu::Formatter.format('<DIV id=aaa>content</div>')
25
+ => "<div id=\"aaa\">content</div>"
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/hitomalu_formatter. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/hitomalu_formatter/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the HitomaluFormatter project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/hitomalu_formatter/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/hitomalu_formatter/version"
4
+ require_relative "lib/hitomalu_formatter/formatter"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "hitomalu_formatter"
8
+ spec.version = HitomaluFormatter::VERSION
9
+ spec.authors = ["t-hazawa"]
10
+ spec.email = []
11
+
12
+ spec.summary = "Format HTML string."
13
+ spec.homepage = "https://t-hazawa.hatenablog.com/"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/t-hazawa/hitomalu_formatter"
21
+ spec.metadata["changelog_uri"] = "https://github.com/t-hazawa/hitomalu_formatter/master/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = "exe"
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ["lib"]
33
+
34
+ # Uncomment to register a new dependency of your gem
35
+ # spec.add_dependency "example-gem", "~> 1.0"
36
+
37
+ # For more information and examples about making a new gem, check out our
38
+ # guide at: https://bundler.io/guides/creating_gem.html
39
+ end
@@ -0,0 +1,90 @@
1
+ require 'nokogiri'
2
+
3
+ module Hitomalu
4
+ class Formatter
5
+ CONTENT_NO_MODIFY_TAGS = [ 'pre' ]
6
+
7
+ # cf. https://developer.mozilla.org/ja/docs/Web/HTML/Inline_elements
8
+ # rp と rt は上に記載がないが、改行させたくないので追加
9
+ INLINE_TAGS = [ 'a', 'abbr', 'acronym', 'audio', 'b', 'bdi', 'bdo', 'big', 'br', 'button', 'canvas', 'cite', 'code', 'data', 'datalist', 'del', 'dfn', 'em', 'embed', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'map', 'mark', 'meter', 'noscript', 'object', 'output', 'picture', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'select', 'slot', 'small', 'span', 'strong', 'sub', 'sup', 'svg', 'template', 'textarea', 'time', 'u', 'tt', 'var', 'video', 'wbr' ]
10
+
11
+ def self.format(html)
12
+ # 改行コード \n を \r\n に統一しておく
13
+ html = html.gsub(/(?<!\r)\n/, "\r\n")
14
+
15
+ # Nokogiri は wbr (本来閉じタグをつけてはいけない)があると 勝手に閉じタグをつけ、最悪その後のHTMLをなかったことにしてしまうので、
16
+ # 先回りして、直後に </wbr> をつけておいてしまう (元から含まれる </wbr> を消して、開始タグの直後につける)
17
+ html = html.gsub(/<\s*\/\s*wbr\s*>/, "").gsub(/<\s*wbr\s*>/, "<wbr></wbr>")
18
+
19
+ doc = Nokogiri::HTML.parse(html)
20
+ # body で全体が囲われていないと、最上層に兄弟ノードを追加できないのでHTMLFragmentでは不可
21
+ body = doc.at_css('body')
22
+
23
+ body.traverse { |node|
24
+ # 中身がないと、li などの閉じタグ省略可能なタグについてNokogiriが閉じタグ省略を行い、整形をかけるたびに閉じタグがついたりなくなったりするので、
25
+ # 中身がないかスペースだけの場合、仮文字列にして最後に空文字列に置換する
26
+ # ただし、 <img src="1.jpg"> <img src="2.jpg"> のようなインライン要素の間のスペースと改行は保持する必要があるので保持する。
27
+ # <li></li> の中に |mykaramojiretsu| を入れるために + ではなく * が必要
28
+ if /\A[ ]*\Z/.match?(node.content) && (node.previous_sibling.nil? || !INLINE_TAGS.include?(node.previous_sibling.name))
29
+ node.content = "|mykaramojiretsu|"
30
+ end
31
+
32
+ # インライン要素は、ブロック内先頭やテキストノードやインライン要素の次では改行しない
33
+ # (前がブロック要素の終わりやコメントノードだと改行する)
34
+ if INLINE_TAGS.include?(node.name) && (node.previous_sibling.nil? || (node.previous_sibling.instance_of?(Nokogiri::XML::Text) || INLINE_TAGS.include?(node.previous_sibling.name)))
35
+ node.add_previous_sibling("|nobreakline|")
36
+ end
37
+
38
+ # タグ間の改行やスペースを消す(前がインライン要素でなければ)
39
+ if /\A[\s]+\Z/.match?(node.to_s)
40
+ if !node.previous_sibling.nil? && INLINE_TAGS.include?(node.previous_sibling.name)
41
+ # 前がインライン要素なら、複数改行(スペース混じりも)を改行1つにしておく。また連続スペースを1つにする
42
+ if /\r\n/.match?(node.content)
43
+ node.content = node.content.gsub(/(\s)+/, "|mykaigyo|")
44
+ end
45
+ node.content = node.content.gsub(/ {2,}/, " ").gsub(' ', '|myspace|')
46
+ else
47
+ node.content = ""
48
+ end
49
+ end
50
+
51
+ # </span>\n</div> を </span>\n</div> のままにしたいが、Nokogiri は閉じタグ間の\nを消すので一旦 |mykaigyo| にする (整形を2回かけた時用)
52
+ if node.instance_of?(Nokogiri::XML::Element) && !node.next_sibling.nil? && /\A\s*(\n|\r\n)\s*\Z/.match?(node.next_sibling.content) && node.next_sibling.next_sibling.nil?
53
+ node.next_sibling.content = "|mykaigyo|"
54
+ end
55
+
56
+ # タグの中身を整形する(見やすくするため)
57
+ if node.instance_of?(Nokogiri::XML::Text) && !CONTENT_NO_MODIFY_TAGS.include?(node.parent.name)
58
+ node.content = node.content.strip.gsub(/\s{2,}/, " ")
59
+ end
60
+
61
+ # 閉じタグとテキストノードの間に改行がなければ入れる(見やすくするため)
62
+ # (前がインライン要素以外なら。 <- 補足: 今回の場合、テキストノードは1つにまとめられるので、テキストノードの前にテキストノードは来ない...ので判定不要 )
63
+ if node.instance_of?(Nokogiri::XML::Text) && !node.previous_sibling.nil? && !/^(\n|\r\n|\|mykaigyo\||\|mykaramojiretsu\||\|nobreakline\||\|myspace\|)+.*$/.match?(node.content) && !INLINE_TAGS.include?(node.previous_sibling.name)
64
+ if !node.previous_sibling.content.eql?("|nobreakline|")
65
+ node.content = "\r\n" + node.to_s
66
+ end
67
+ end
68
+ }
69
+
70
+ # Nokogiriが勝手につける</wbr>を消して、本物の空文字列にして、改行用文字列を本物の改行にして、要らないbodyタグを消し、全体の先頭と最後に改行が付くので消す
71
+ # さらに、Nokogiriがつける改行コード \n も \r\n に統一しておく
72
+ body_str = body.to_s.gsub(/(\|mykaigyo\|)+/, "\r\n").gsub('|myspace|', ' ').gsub(/(<\/wbr>|\|mykaramojiretsu\||\A<body>(\n|\r\n)*|(\n|\r\n)*<\/body>\Z)/, "").gsub(/(?<!\r)\n/, "\r\n")
73
+
74
+ # </span></div> のような閉じタグの間に改行が無かったら改行を入れる (Nokogiri の add_next_sibling は 20000回するとメモリを6GB以上使うので文字列処理でやる)
75
+ # ただし、</ruby>の前には入れない(</rp>などの短いインライン要素が来るため)
76
+ prev_str = ""
77
+ while body_str != prev_str do
78
+ prev_str = body_str
79
+ body_str = body_str.gsub(/(<\/[a-z]+>)(<\/(?!ruby))/, "\\1\r\n\\2")
80
+ end
81
+
82
+ # 開始タグの前に改行がなければ改行を入れる (add_prev_sibling は重いので文字列処理でやる) (文章の先頭からは消す)
83
+ # その後、使い終わった改行しない印を消す
84
+ body_str = body_str.gsub(/(?<!\r\n)(?<!\|nobreakline\|)(?<!\|nobreakline\| )<(?!\/)/, "\r\n<").gsub(/(\A\r\n|\|nobreakline\|)/, "")
85
+
86
+ # <br> や <hr> や <col> の後ろに改行がなければ改行を入れる (add_next_sibling は重いので文字列処理でやる)
87
+ body_str = body_str.gsub(/(<(?:br|hr|col)>)(?!\r\n)/, "\\1\r\n")
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HitomaluFormatter
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "hitomalu_formatter/version"
4
+ require_relative "hitomalu_formatter/formatter"
5
+
6
+ module HitomaluFormatter
7
+ class Error < StandardError; end
8
+ # Your code goes here...
9
+ end
@@ -0,0 +1,4 @@
1
+ module HitomaluFormatter
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hitomalu_formatter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - t-hazawa
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-07-30 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email: []
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - ".rspec"
20
+ - CHANGELOG.md
21
+ - CODE_OF_CONDUCT.md
22
+ - Gemfile
23
+ - Gemfile.lock
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - hitomalu_formatter.gemspec
28
+ - lib/hitomalu_formatter.rb
29
+ - lib/hitomalu_formatter/formatter.rb
30
+ - lib/hitomalu_formatter/version.rb
31
+ - sig/hitomalu_formatter.rbs
32
+ homepage: https://t-hazawa.hatenablog.com/
33
+ licenses:
34
+ - MIT
35
+ metadata:
36
+ allowed_push_host: https://rubygems.org
37
+ homepage_uri: https://t-hazawa.hatenablog.com/
38
+ source_code_uri: https://github.com/t-hazawa/hitomalu_formatter
39
+ changelog_uri: https://github.com/t-hazawa/hitomalu_formatter/master/CHANGELOG.md
40
+ post_install_message:
41
+ rdoc_options: []
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: 2.6.0
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubygems_version: 3.1.2
56
+ signing_key:
57
+ specification_version: 4
58
+ summary: Format HTML string.
59
+ test_files: []