flog-lsp 0.0.1

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: 2595e43190ca9642ecf9a731be9dff01baf8be9523b8b2ab1601ef1960ecce13
4
+ data.tar.gz: 20459f663bc893bac5b0a85caa74a449016ccf89bc5995395cef00d15875bf55
5
+ SHA512:
6
+ metadata.gz: 53b0894058314bb5745552e850aceebfb4a1a6fe79941fcede047ca1c1fb7af212936108efb25892e12596b9f90370fe91538b931b4c28f6aa84516b1e7cd5de
7
+ data.tar.gz: aa269244bc6c72dcf5fa437660e85971f182551f6480f958a99b9b61626c8ff3ef9251745f87b56eb83f01b95637ab44b2bb6559c1e9a7dba499ba1f084b6c5b
data/.rubocop.yml ADDED
@@ -0,0 +1,21 @@
1
+ inherit_gem:
2
+ rubocop-shopify: rubocop.yml
3
+
4
+ require:
5
+ - rubocop-sorbet
6
+ - rubocop-rake
7
+ - rubocop-minitest
8
+
9
+ AllCops:
10
+ TargetRubyVersion: 2.6
11
+
12
+ Style/StringLiterals:
13
+ Enabled: true
14
+ EnforcedStyle: double_quotes
15
+
16
+ Style/StringLiteralsInInterpolation:
17
+ Enabled: true
18
+ EnforcedStyle: double_quotes
19
+
20
+ Layout/LineLength:
21
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.0.1] - 2024-03-22
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Chris AtLee
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,35 @@
1
+ # FlogLsp
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ 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/flog/lsp`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ 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).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/flog-lsp.
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: [:test, :rubocop]
data/exe/flog-lsp ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "flog_lsp/cli"
5
+ FlogLsp::Cli.start
data/flog-lsp.gemspec ADDED
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/flog_lsp/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "flog-lsp"
7
+ spec.version = FlogLsp::VERSION
8
+ spec.authors = ["Chris AtLee"]
9
+ spec.email = ["chris.atlee@shopify.com"]
10
+
11
+ spec.summary = "LSP for providing flog metrics in the editor"
12
+ spec.homepage = "https://github.com/catlee/flog-lsp"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 2.6.0"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = spec.homepage
18
+ spec.metadata["changelog_uri"] = "https://github.com/catlee/flog-lsp/blob/master/CHANGELOG.md"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(__dir__) do
23
+ %x(git ls-files -z).split("\x0").reject do |f|
24
+ (File.expand_path(f) == __FILE__) ||
25
+ f.start_with?("bin/", "test/", "spec/", "features/", ".git", ".github", "appveyor", "Gemfile")
26
+ end
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ spec.add_dependency("flog", "~> 4.8")
33
+ spec.add_dependency("language_server-protocol", "~> 3.16")
34
+ spec.add_dependency("sorbet-runtime", "~> 0.5")
35
+
36
+ # For more information and examples about making a new gem, check out our
37
+ # guide at: https://bundler.io/guides/creating_gem.html
38
+ end
@@ -0,0 +1,32 @@
1
+ # typed: false
2
+ # frozen_string_literal: true
3
+
4
+ require "optparse"
5
+ require "logger"
6
+ require "flog_lsp/lsp"
7
+
8
+ module FlogLsp
9
+ module Cli
10
+ class << self
11
+ def start
12
+ options = {}
13
+ OptionParser.new do |opts|
14
+ opts.banner = "Usage: flog-lsp [options]"
15
+ opts.on("-v", "--verbose", "Run verbosely") do |v|
16
+ options[:verbose] = v
17
+ end
18
+ opts.on("-h", "--help", "Prints this help") do
19
+ puts opts
20
+ exit
21
+ end
22
+ end.parse!
23
+ logger = FlogLsp.logger = Logger.new($stderr)
24
+ # logger = FlogLsp.logger = Logger.new("flog-lsp.log")
25
+ logger.level = options[:verbose] ? Logger::DEBUG : Logger::INFO
26
+ logger.info("flog-lsp version #{FlogLsp::VERSION} starting...")
27
+ lsp = FlogLsp::Server.new
28
+ lsp.start
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,195 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "language_server-protocol"
5
+ require "cgi"
6
+ require "uri"
7
+ require "flog"
8
+ require_relative "version"
9
+
10
+ # Alias for LanguageServer::Protocol
11
+ LSP = LanguageServer::Protocol
12
+
13
+ module FlogLsp
14
+ class Error < StandardError; end
15
+
16
+ class << self
17
+ def logger
18
+ @logger ||= Logger.new($stderr)
19
+ end
20
+
21
+ attr_writer :logger
22
+ end
23
+
24
+ class Server
25
+ HANDLERS = {
26
+ "initialize" => :handle_initialize,
27
+ "initialized" => :handle_initialized,
28
+ "textDocument/diagnostic" => :handle_diagnostic,
29
+ "textDocument/didOpen" => :handle_open,
30
+ "textDocument/didChange" => :handle_change,
31
+ "textDocument/didClose" => :handle_close,
32
+ "shutdown" => :handle_shutdown,
33
+ "exit" => :handle_exit,
34
+ }
35
+
36
+ def initialize
37
+ @file_data = {}
38
+ @options = {}
39
+ end
40
+
41
+ def score_threshold
42
+ @options.fetch(:score_threshold, 10)
43
+ end
44
+
45
+ def file_data(uri)
46
+ @file_data[uri] ||= begin
47
+ path = CGI.unescape(URI.parse(uri).path)
48
+ logger.debug("Loading file #{path}")
49
+ File.read(path)
50
+ end
51
+ end
52
+
53
+ def logger
54
+ FlogLsp.logger
55
+ end
56
+
57
+ def start
58
+ writer = LSP::Transport::Stdio::Writer.new
59
+ reader = LSP::Transport::Stdio::Reader.new
60
+ reader.read do |request|
61
+ response = handle(request)
62
+ unless response.nil?
63
+ writer.write(id: request[:id], result: response)
64
+ end
65
+ end
66
+ end
67
+
68
+ def handle(request)
69
+ logger.debug("Received request: #{request[:method]}")
70
+ if HANDLERS.key?(request[:method])
71
+ send(HANDLERS[request[:method]], request)
72
+ else
73
+ logger.warn("Unknown request: #{request[:method]}")
74
+ nil
75
+ end
76
+ end
77
+
78
+ def handle_initialize(request)
79
+ logger.debug("Initializing with request: #{request}")
80
+ @options = request[:params][:initializationOptions] || {}
81
+
82
+ LSP::Interface::InitializeResult.new(
83
+ capabilities: LSP::Interface::ServerCapabilities.new(
84
+ text_document_sync: LSP::Interface::TextDocumentSyncOptions.new(
85
+ change: LSP::Constant::TextDocumentSyncKind::INCREMENTAL,
86
+ open_close: true,
87
+ ),
88
+ diagnostic_provider: LSP::Interface::DiagnosticOptions.new(
89
+ identifier: "flog",
90
+ inter_file_dependencies: false,
91
+ workspace_diagnostics: false,
92
+ ),
93
+ ),
94
+ server_info: {
95
+ name: "Flog LSP",
96
+ version: FlogLsp::VERSION,
97
+ },
98
+ )
99
+ end
100
+
101
+ def handle_initialized(request)
102
+ nil
103
+ end
104
+
105
+ def handle_shutdown(request)
106
+ nil
107
+ end
108
+
109
+ def handle_exit(request)
110
+ Kernel.exit(0)
111
+ end
112
+
113
+ def handle_open(request)
114
+ # Load the file
115
+ uri = request[:params][:textDocument][:uri]
116
+ file_data(uri)
117
+ nil
118
+ end
119
+
120
+ def handle_close(request)
121
+ uri = request[:params][:textDocument][:uri]
122
+ @file_data.delete(uri)
123
+ nil
124
+ end
125
+
126
+ def get_prefix(lines, line, character)
127
+ lines[0...line].join + lines[line][0...character]
128
+ end
129
+
130
+ def get_suffix(lines, line, character)
131
+ if line >= lines.length
132
+ ""
133
+ else
134
+ lines[line][character..] + lines[line + 1..].join
135
+ end
136
+ end
137
+
138
+ def patch_contents(contents, range, text)
139
+ lines = contents.lines
140
+ prefix = get_prefix(lines, range[:start][:line], range[:start][:character])
141
+ suffix = get_suffix(lines, range[:end][:line], range[:end][:character])
142
+ prefix + text + suffix
143
+ end
144
+
145
+ def handle_change(request)
146
+ uri = request[:params][:textDocument][:uri]
147
+ request[:params][:contentChanges].each do |change|
148
+ @file_data[uri] = if change.key?(:range)
149
+ patch_contents(file_data(uri), change[:range], change[:text])
150
+ else
151
+ change[:text]
152
+ end
153
+ end
154
+ nil
155
+ end
156
+
157
+ def get_diagnostics(contents)
158
+ flog = Flog.new
159
+ flog.flog_ruby(contents)
160
+ flog.calculate_total_scores
161
+ flog.totals.filter_map do |method_name, score|
162
+ next if score <= score_threshold
163
+
164
+ location = flog.method_locations[method_name]
165
+ next unless location
166
+
167
+ _filename, range = location.split(":")
168
+ start_line, _end_line = range.split("-")
169
+ [method_name, start_line, score]
170
+ end
171
+ end
172
+
173
+ def handle_diagnostic(request)
174
+ uri = request[:params][:textDocument][:uri]
175
+ contents = file_data(uri)
176
+ diagnostics = get_diagnostics(contents).map do |method_name, start_line, score|
177
+ LSP::Interface::Diagnostic.new(
178
+ range: LSP::Interface::Range.new(
179
+ start: LSP::Interface::Position.new(line: start_line.to_i - 1, character: 0),
180
+ end: LSP::Interface::Position.new(line: start_line.to_i - 1, character: 0),
181
+ # end: LSP::Interface::Position.new(line: end_line.to_i - 1, character: 0),
182
+ ),
183
+ severity: LSP::Constant::DiagnosticSeverity::WARNING,
184
+ source: "flog",
185
+ message: "#{method_name} has a flog score of #{score.round(2)}",
186
+ data: { correctable: false },
187
+ )
188
+ end
189
+ LSP::Interface::FullDocumentDiagnosticReport.new(kind: "full", items: diagnostics)
190
+ rescue StandardError => e
191
+ logger.error("Error calculating flog: #{e}")
192
+ LSP::Interface::FullDocumentDiagnosticReport.new(kind: "full", items: [])
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,6 @@
1
+ # typed: false
2
+ # frozen_string_literal: true
3
+
4
+ module FlogLsp
5
+ VERSION = "0.0.1"
6
+ end
data/lib/flog_lsp.rb ADDED
File without changes
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: flog-lsp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Chris AtLee
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-03-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: flog
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4.8'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4.8'
27
+ - !ruby/object:Gem::Dependency
28
+ name: language_server-protocol
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.16'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.16'
41
+ - !ruby/object:Gem::Dependency
42
+ name: sorbet-runtime
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.5'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.5'
55
+ description:
56
+ email:
57
+ - chris.atlee@shopify.com
58
+ executables:
59
+ - flog-lsp
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".rubocop.yml"
64
+ - CHANGELOG.md
65
+ - LICENSE.txt
66
+ - README.md
67
+ - Rakefile
68
+ - exe/flog-lsp
69
+ - flog-lsp.gemspec
70
+ - lib/flog_lsp.rb
71
+ - lib/flog_lsp/cli.rb
72
+ - lib/flog_lsp/lsp.rb
73
+ - lib/flog_lsp/version.rb
74
+ homepage: https://github.com/catlee/flog-lsp
75
+ licenses:
76
+ - MIT
77
+ metadata:
78
+ homepage_uri: https://github.com/catlee/flog-lsp
79
+ source_code_uri: https://github.com/catlee/flog-lsp
80
+ changelog_uri: https://github.com/catlee/flog-lsp/blob/master/CHANGELOG.md
81
+ post_install_message:
82
+ rdoc_options: []
83
+ require_paths:
84
+ - lib
85
+ required_ruby_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: 2.6.0
90
+ required_rubygems_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: '0'
95
+ requirements: []
96
+ rubygems_version: 3.3.15
97
+ signing_key:
98
+ specification_version: 4
99
+ summary: LSP for providing flog metrics in the editor
100
+ test_files: []