Class: Mbeditor::EditorsController
- Inherits:
-
ApplicationController
- Object
- ActionController::Base
- ApplicationController
- Mbeditor::EditorsController
- Defined in:
- app/controllers/mbeditor/editors_controller.rb
Constant Summary collapse
- IMAGE_EXTENSIONS =
%w[png jpg jpeg gif svg ico webp bmp avif].freeze
- MAX_OPEN_FILE_SIZE_BYTES =
5 * 1024 * 1024
- RG_AVAILABLE =
system("which rg > /dev/null 2>&1")
- STATE_MAX_BYTES =
1 * 1024 * 1024
- SAFE_BRANCH_NAME =
/\A[a-zA-Z0-9._\-\/]+\z/- MAX_REPLACE_FILES =
500
Instance Method Summary collapse
-
#branch_state ⇒ Object
GET /mbeditor/branch_state?branch=…
-
#create_dir ⇒ Object
POST /mbeditor/create_dir — create directory recursively.
-
#create_file ⇒ Object
POST /mbeditor/create_file — create file and parent directories if needed.
-
#definition ⇒ Object
GET /mbeditor/definition?symbol=…&language=…
-
#destroy_path ⇒ Object
DELETE /mbeditor/delete — remove file or directory.
-
#file_includes ⇒ Object
GET /mbeditor/file_includes?path=app/models/article.rb Returns included/extended/prepended module names and their methods.
-
#files ⇒ Object
GET /mbeditor/files — recursive file tree.
-
#format_file ⇒ Object
POST /mbeditor/format — rubocop -A on buffer content; returns corrected content WITHOUT saving to disk.
-
#git_info ⇒ Object
GET /mbeditor/git_info.
-
#git_status ⇒ Object
GET /mbeditor/git_status.
-
#index ⇒ Object
GET /mbeditor — renders the IDE shell.
-
#lint ⇒ Object
POST /mbeditor/lint — run rubocop –stdin (or haml-lint for .haml files).
-
#module_members ⇒ Object
GET /mbeditor/module_members?name=ArticlesHelper Returns methods defined in the workspace file that defines the named module/class.
-
#monaco_asset ⇒ Object
GET /mbeditor/monaco-editor/*asset_path — serve packaged Monaco files.
-
#monaco_worker ⇒ Object
GET /mbeditor/monaco_worker.js — serve packaged Monaco worker entrypoint.
-
#ping ⇒ Object
GET /mbeditor/ping — heartbeat for the frontend connectivity check Silence the log line so development consoles are not spammed.
-
#prune_branch_states ⇒ Object
POST /mbeditor/prune_branch_states — remove states for deleted branches.
-
#pwa_icon ⇒ Object
GET /mbeditor/mbeditor-icon.svg — PWA icon.
-
#pwa_manifest ⇒ Object
GET /mbeditor/manifest.webmanifest — PWA manifest.
-
#pwa_sw ⇒ Object
GET /mbeditor/sw.js — minimal PWA service worker.
-
#quick_fix ⇒ Object
POST /mbeditor/quick_fix — autocorrect the buffer with rubocop -A and return the diff as a text edit.
-
#raw ⇒ Object
GET /mbeditor/raw?path=…
-
#rename ⇒ Object
PATCH /mbeditor/rename — rename file or directory.
-
#replace_in_files ⇒ Object
POST /mbeditor/replace_in_files Replaces a string/pattern across all matching files in the workspace.
-
#run_test ⇒ Object
POST /mbeditor/test — run tests for the given file.
-
#save ⇒ Object
POST /mbeditor/file — save file.
- #save_branch_state ⇒ Object
-
#save_state ⇒ Object
POST /mbeditor/state — save workspace state.
-
#search ⇒ Object
GET /mbeditor/search?q=…&offset=0&limit=50®ex=false&match_case=false&whole_word=false.
-
#show ⇒ Object
GET /mbeditor/file?path=…
-
#state ⇒ Object
GET /mbeditor/state — load workspace state.
-
#ts_worker ⇒ Object
GET /mbeditor/ts_worker.js — serve TypeScript/JavaScript Monaco worker.
-
#unused_methods ⇒ Object
GET /mbeditor/unused_methods?path=app/models/article.rb Returns method names defined in the file that have no call-sites in the workspace.
-
#workspace ⇒ Object
GET /mbeditor/workspace — metadata about current workspace root.
Instance Method Details
#branch_state ⇒ Object
GET /mbeditor/branch_state?branch=… — load per-branch pane state
99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 99 def branch_state branch = sanitize_branch_name(params[:branch]) return render json: {}, status: :bad_request unless branch path = workspace_root.join("tmp", "mbeditor_branch_states.json") if File.exist?(path) all = JSON.parse(File.read(path)) render json: (all[branch] || {}) else render json: {} end rescue StandardError render json: {} end |
#create_dir ⇒ Object
POST /mbeditor/create_dir — create directory recursively
267 268 269 270 271 272 273 274 275 276 277 278 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 267 def create_dir path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path return render json: { error: "Cannot create directory in this path" }, status: :forbidden if path_blocked_for_operations?(path) return render json: { error: "Path already exists" }, status: :unprocessable_content if File.exist?(path) FileUtils.mkdir_p(path) broadcast_files_changed render json: { ok: true, type: "folder", path: relative_path(path), name: File.basename(path) } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#create_file ⇒ Object
POST /mbeditor/create_file — create file and parent directories if needed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 248 def create_file path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path return render json: { error: "Cannot create file in this path" }, status: :forbidden if path_blocked_for_operations?(path) return render json: { error: "File already exists" }, status: :unprocessable_content if File.exist?(path) content = params[:code].to_s return render_file_too_large(content.bytesize) if content.bytesize > MAX_OPEN_FILE_SIZE_BYTES FileUtils.mkdir_p(File.dirname(path)) File.write(path, content) broadcast_files_changed render json: { ok: true, type: "file", path: relative_path(path), name: File.basename(path) } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#definition ⇒ Object
GET /mbeditor/definition?symbol=…&language=… Looks up method definitions in workspace source files (Ripper) and in the Ruby/gem documentation via ri. Workspace results appear first.
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 327 def definition symbol = params[:symbol].to_s.strip language = params[:language].to_s.strip return render json: { results: [] } if symbol.blank? return render json: { error: "Invalid symbol" }, status: :bad_request unless symbol.match?(/\A[a-zA-Z_]\w{0,59}[!?]?\z/) results = case language when "ruby" workspace = RubyDefinitionService.call( workspace_root, symbol, excluded_dirnames: excluded_dirnames, excluded_paths: excluded_paths, included_dirs: ruby_def_include_dirs ) ri = RiDefinitionService.call(symbol) workspace + ri else [] end render json: { results: results } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#destroy_path ⇒ Object
DELETE /mbeditor/delete — remove file or directory
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 304 def destroy_path path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path # Idempotent: if already gone the desired state is already achieved. return render json: { ok: true } unless File.exist?(path) return render json: { error: "Cannot delete this path" }, status: :forbidden if path_blocked_for_operations?(path) if File.directory?(path) FileUtils.rm_rf(path) broadcast_files_changed render json: { ok: true, type: "folder", path: relative_path(path) } else File.delete(path) broadcast_files_changed render json: { ok: true, type: "file", path: relative_path(path) } end rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#file_includes ⇒ Object
GET /mbeditor/file_includes?path=app/models/article.rb Returns included/extended/prepended module names and their methods.
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 380 def file_includes path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path # Ensure workspace is scanned so include_calls are populated in the cache. # Fast no-op on subsequent calls (mtime checks only). RubyDefinitionService.scan(workspace_root, excluded_dirnames: excluded_dirnames, excluded_paths: excluded_paths, included_dirs: ruby_def_include_dirs) module_names = RubyDefinitionService.includes_in_file(path) includes = module_names.filter_map do |mod_name| mod_file = RubyDefinitionService.module_defined_in( workspace_root, mod_name, excluded_dirnames: excluded_dirnames, excluded_paths: excluded_paths, included_dirs: ruby_def_include_dirs ) next unless mod_file defs = RubyDefinitionService.defs_in_file(mod_file) methods = defs.flat_map do |method_name, entries| entries.map { |e| { name: method_name, line: e[:line], signature: e[:signature] } } end { name: mod_name, file: relative_path(mod_file), methods: methods } end render json: { includes: includes } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#files ⇒ Object
GET /mbeditor/files — recursive file tree
48 49 50 51 52 53 54 55 56 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 48 def files root = workspace_root.to_s cached = cached_file_tree(root) return render json: cached if cached tree = build_tree(root) store_file_tree(root, tree) render json: tree end |
#format_file ⇒ Object
POST /mbeditor/format — rubocop -A on buffer content; returns corrected content WITHOUT saving to disk
Accepts the current buffer content as ‘code` and formats it using a workspace-local tempfile so that RuboCop’s config discovery walks up from the source file’s own directory (finds the host app’s .rubocop.yml). Does NOT write the result back to the original file — the frontend marks the tab dirty and lets the user decide when to save.
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 877 def format_file path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path code = params[:code].to_s return render json: { error: "code required" }, status: :unprocessable_content if code.empty? ext = File.extname(File.basename(path)) Tempfile.create([".mbeditor_fmt_", ext], File.dirname(path)) do |f| f.write(code) f.flush tmpfile = f.path cmd = rubocop_command + ["--no-server", "-A", "--no-color", tmpfile] env = { 'RUBOCOP_CACHE_ROOT' => File.join(Dir.tmpdir, 'rubocop') } _out, _err, status = Open3.capture3(env, *cmd) unless status.success? || status.exitstatus == 1 return render json: { ok: false, content: code } end corrected = File.read(tmpfile, encoding: "UTF-8", invalid: :replace, undef: :replace) render json: { ok: true, content: corrected } end rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#git_info ⇒ Object
GET /mbeditor/git_info
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 568 def git_info repo = workspace_root.to_s cached = cached_git_info(repo) return render json: cached if cached branch = GitService.current_branch(repo) unless branch return render json: { ok: false, error: "Unable to determine current branch" }, status: :unprocessable_content end # Wave 1: all independent git reads run in parallel status_t = Thread.new { Open3.capture3("git", "-C", repo, "status", "--porcelain") } numstat_t = Thread.new { Open3.capture3("git", "-C", repo, "diff", "--numstat", "HEAD") } upstream_t = Thread.new { Open3.capture3("git", "-C", repo, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}") } base_t = Thread.new { GitService.find_branch_base(repo, branch) } working_output, _err, working_status = status_t.value working_tree = working_status.success? ? parse_porcelain_status(working_output) : [] numstat_out = numstat_t.value.first numstat_map = GitService.parse_numstat(numstat_out) working_tree = working_tree.map { |f| f.merge(numstat_map.fetch(f[:path], {})) } upstream_output, _err, upstream_status = upstream_t.value upstream_branch = upstream_status.success? ? upstream_output.strip : nil upstream_branch = nil unless upstream_branch&.match?(%r{\A[\w./-]+\z}) # Determine the branch's fork point relative to a base branch (develop/main/master). # This ensures History and Changes only show work unique to this branch. base_sha, base_ref = base_t.value ahead_count = 0 behind_count = 0 unpushed_files = [] unpushed_commits = [] diff_base = base_sha || upstream_branch # Wave 2: conditional parallel reads that depend on Wave 1 results wave2 = {} wave2[:counts] = Thread.new { Open3.capture3("git", "-C", repo, "rev-list", "--left-right", "--count", "HEAD...#{upstream_branch}") } if upstream_branch.present? wave2[:unp_log] = Thread.new { Open3.capture3("git", "-C", repo, "log", "#{upstream_branch}..HEAD", "--pretty=format:%H%x1f%s%x1f%an%x1f%aI%x1e") } if upstream_branch.present? wave2[:diff_name] = Thread.new { Open3.capture3("git", "-C", repo, "diff", "--name-status", "#{diff_base}..HEAD") } if diff_base.present? wave2[:diff_num] = Thread.new { Open3.capture3("git", "-C", repo, "diff", "--numstat", "#{diff_base}..HEAD") } if diff_base.present? wave2[:branch_log] = Thread.new do if base_sha Open3.capture3("git", "-C", repo, "log", "--first-parent", "#{base_sha}..HEAD", "--pretty=format:%H%x1f%s%x1f%an%x1f%aI%x1e") else Open3.capture3("git", "-C", repo, "log", "--first-parent", branch, "-n", "100", "--pretty=format:%H%x1f%s%x1f%an%x1f%aI%x1e") end end wave2.each_value(&:join) if (ct = wave2[:counts]) counts_output, _err, counts_status = ct.value if counts_status.success? ahead_str, behind_str = counts_output.strip.split("\t", 2) ahead_count = ahead_str.to_i behind_count = behind_str.to_i end end if (ul = wave2[:unp_log]) unpushed_log_output, _err, unpushed_log_status = ul.value unpushed_commits = GitService.parse_git_log(unpushed_log_output) if unpushed_log_status.success? end if (dn = wave2[:diff_name]) && (dnum = wave2[:diff_num]) diff_name_out, _err, diff_name_status = dn.value if diff_name_status.success? unpushed_files = parse_name_status(diff_name_out) unp_numstat_out = dnum.value.first unp_numstat_map = GitService.parse_numstat(unp_numstat_out) unpushed_files = unpushed_files.map { |f| f.merge(unp_numstat_map.fetch(f[:path], {})) } end end branch_log_output, _err, branch_log_status = wave2[:branch_log].value branch_commits = branch_log_status.success? ? GitService.parse_git_log(branch_log_output) : [] redmine_ticket_id = nil if Mbeditor.configuration.redmine_enabled if Mbeditor.configuration.redmine_ticket_source == :branch m = branch.match(/\A(\d+)/) redmine_ticket_id = m[1] if m else branch_commits.each do |commit| m = commit["title"]&.match(/#(\d+)/) if m redmine_ticket_id = m[1] break end end end end payload = { ok: true, branch: branch, upstreamBranch: upstream_branch, ahead: ahead_count, behind: behind_count, workingTree: working_tree, unpushedFiles: unpushed_files, unpushedCommits: unpushed_commits, branchCommits: branch_commits, branchBaseRef: base_ref, redmineTicketId: redmine_ticket_id } store_git_info(repo, payload) render json: payload rescue StandardError => e render json: { ok: false, error: e. }, status: :unprocessable_content end |
#git_status ⇒ Object
GET /mbeditor/git_status
558 559 560 561 562 563 564 565 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 558 def git_status output, _err, status = Open3.capture3("git", "-C", workspace_root.to_s, "status", "--porcelain") branch = GitService.current_branch(workspace_root.to_s) || "" files = parse_porcelain_status(output) render json: { ok: status.success?, files: files, branch: branch } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#index ⇒ Object
GET /mbeditor — renders the IDE shell
21 22 23 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 21 def index render layout: "mbeditor/application" end |
#lint ⇒ Object
POST /mbeditor/lint — run rubocop –stdin (or haml-lint for .haml files)
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 750 def lint path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path filename = File.basename(path) code = params[:code] || File.read(path) if filename.end_with?('.haml') unless haml_lint_available? return render json: { error: "haml-lint not available", markers: [] }, status: :unprocessable_content end markers = run_haml_lint(code) return render json: { markers: markers } end cmd = rubocop_command + ["--no-server", "--stdin", filename, "--format", "json", "--no-color", "--force-exclusion"] env = { 'RUBOCOP_CACHE_ROOT' => File.join(Dir.tmpdir, 'rubocop') } output = run_with_timeout(env, cmd, stdin_data: code) idx = output.index("{") result = idx ? JSON.parse(output[idx..]) : {} result = {} unless result.is_a?(Hash) offenses = result.dig("files", 0, "offenses") || [] markers = offenses.map do |offense| { severity: cop_severity(offense["severity"]), copName: offense["cop_name"], correctable: offense["correctable"] == true, message: "[#{offense['cop_name']}] #{offense['message']}", startLine: offense.dig("location", "start_line") || offense.dig("location", "line"), startCol: offense.dig("location", "start_column") || offense.dig("location", "column") || 1, endLine: offense.dig("location", "last_line") || offense.dig("location", "line"), endCol: offense.dig("location", "last_column") || offense.dig("location", "column") || 1 } end render json: { markers: markers, summary: result["summary"] } rescue StandardError => e render json: { error: e., markers: [] }, status: :unprocessable_content end |
#module_members ⇒ Object
GET /mbeditor/module_members?name=ArticlesHelper Returns methods defined in the workspace file that defines the named module/class.
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 356 def module_members name = params[:name].to_s.strip return render json: { error: "Invalid name" }, status: :bad_request \ unless name.match?(/\A[A-Z][a-zA-Z0-9_]*\z/) file = RubyDefinitionService.module_defined_in( workspace_root, name, excluded_dirnames: excluded_dirnames, excluded_paths: excluded_paths, included_dirs: ruby_def_include_dirs ) return render json: { name: name, methods: [] } unless file defs = RubyDefinitionService.defs_in_file(file) methods = defs.flat_map do |method_name, entries| entries.map { |e| { name: method_name, line: e[:line], signature: e[:signature], file: relative_path(file) } } end render json: { name: name, file: relative_path(file), methods: methods } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#monaco_asset ⇒ Object
GET /mbeditor/monaco-editor/*asset_path — serve packaged Monaco files
686 687 688 689 690 691 692 693 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 686 def monaco_asset # path_info is the path within the engine, e.g. "/monaco-editor/vs/loader.js" relative = request.path_info.delete_prefix("/") path = resolve_monaco_asset_path(relative) return head :not_found unless path send_file path, disposition: "inline", type: Mime::Type.lookup_by_extension(File.extname(path).delete_prefix(".")) || "application/octet-stream" end |
#monaco_worker ⇒ Object
GET /mbeditor/monaco_worker.js — serve packaged Monaco worker entrypoint
696 697 698 699 700 701 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 696 def monaco_worker path = monaco_worker_file.to_s return render plain: "Not found", status: :not_found unless File.file?(path) send_file path, disposition: "inline", type: "application/javascript" end |
#ping ⇒ Object
GET /mbeditor/ping — heartbeat for the frontend connectivity check Silence the log line so development consoles are not spammed.
27 28 29 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 27 def ping Rails.logger.silence { render json: { ok: true } } end |
#prune_branch_states ⇒ Object
POST /mbeditor/prune_branch_states — remove states for deleted branches
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 136 def prune_branch_states state_path = workspace_root.join("tmp", "mbeditor_branch_states.json") return render json: { pruned: [] } unless File.exist?(state_path) root = workspace_root.to_s out, _err, status = Open3.capture3("git", "-C", root, "branch", "--format=%(refname:short)") return render json: { pruned: [] } unless status.success? local_branches = out.split("\n").map(&:strip).reject(&:empty?) pruned = [] File.open(state_path, File::RDWR) do |f| f.flock(File::LOCK_EX) all = JSON.parse(f.read) rescue {} pruned = all.keys - local_branches if pruned.any? pruned.each { |b| all.delete(b) } f.truncate(0) f.rewind f.write(all.to_json) end end render json: { pruned: pruned } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#pwa_icon ⇒ Object
GET /mbeditor/mbeditor-icon.svg — PWA icon
731 732 733 734 735 736 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 731 def pwa_icon path = Mbeditor::Engine.root.join("public", "mbeditor-icon.svg").to_s return render plain: "Not found", status: :not_found unless File.file?(path) send_file path, disposition: "inline", type: "image/svg+xml" end |
#pwa_manifest ⇒ Object
GET /mbeditor/manifest.webmanifest — PWA manifest
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 704 def pwa_manifest base = request.script_name.to_s.sub(%r{/$}, "") manifest = { name: "Mbeditor — #{Rails.root.basename}", short_name: "Mbeditor", description: "Mini Browser Editor", start_url: "#{base}/", scope: "#{base}/", display: "standalone", background_color: "#1e1e2e", theme_color: "#1e1e2e", icons: [ { src: "#{base}/mbeditor-icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any maskable" } ] } render plain: JSON.generate(manifest), content_type: "application/manifest+json" end |
#pwa_sw ⇒ Object
GET /mbeditor/sw.js — minimal PWA service worker
723 724 725 726 727 728 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 723 def pwa_sw path = Mbeditor::Engine.root.join("public", "sw.js").to_s return render plain: "Not found", status: :not_found unless File.file?(path) send_file path, disposition: "inline", type: "application/javascript" end |
#quick_fix ⇒ Object
POST /mbeditor/quick_fix — autocorrect the buffer with rubocop -A and return the diff as a text edit
Runs a full ‘rubocop -A` pass on the in-memory buffer content (not the file on disk). Using a full pass (rather than –only <cop>) means coupled cops like Layout/EmptyLineAfterMagicComment are also applied in the same round, so the result is always a clean, lint-passing state. The minimal line diff returned to Monaco keeps the edit tight.
Params:
path - workspace-relative file path (used to derive the filename for rubocop)
code - current file content as a string
cop_name - the cop the user clicked on (used only for the action label; not passed to rubocop)
Returns:
{ fix: { startLine, startCol, endLine, endCol, replacement } }
or { fix: null } when rubocop produced no change
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 809 def quick_fix path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path cop_name = params[:cop_name].to_s.strip return render json: { error: "cop_name required" }, status: :unprocessable_content if cop_name.empty? return render json: { error: "Invalid cop name" }, status: :unprocessable_content unless cop_name.match?(/\A[\w\/]+\z/) code = params[:code].to_s ext = File.extname(File.basename(path)) # Use a workspace-local tempfile so RuboCop's config discovery walks up # from the source file's directory and finds the host app's .rubocop.yml. Tempfile.create([".mbeditor_fix_", ext], File.dirname(path)) do |f| f.write(code) f.flush tmpfile = f.path cmd = rubocop_command + ["--no-server", "-A", "--no-color", tmpfile] env = { 'RUBOCOP_CACHE_ROOT' => File.join(Dir.tmpdir, 'rubocop') } _out, _err, status = Open3.capture3(env, *cmd) # exit 0 = no offenses, exit 1 = offenses corrected, exit 2 = error unless status.success? || status.exitstatus == 1 return render json: { fix: nil } end corrected = File.read(tmpfile, encoding: "UTF-8", invalid: :replace, undef: :replace) fix = compute_text_edit(code, corrected) render json: { fix: fix } end rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#raw ⇒ Object
GET /mbeditor/raw?path=… — send raw file directly (for images)
220 221 222 223 224 225 226 227 228 229 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 220 def raw path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path return render json: { error: "Not found" }, status: :not_found unless File.file?(path) size = File.size(path) return render_file_too_large(size) if size > MAX_OPEN_FILE_SIZE_BYTES send_file path, disposition: "inline" end |
#rename ⇒ Object
PATCH /mbeditor/rename — rename file or directory
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 281 def rename old_path = resolve_path(params[:path]) new_path = resolve_path(params[:new_path]) return render json: { error: "Forbidden" }, status: :forbidden unless old_path && new_path return render json: { error: "Path not found" }, status: :not_found unless File.exist?(old_path) return render json: { error: "Target path already exists" }, status: :unprocessable_content if File.exist?(new_path) return render json: { error: "Cannot rename this path" }, status: :forbidden if path_blocked_for_operations?(old_path) || path_blocked_for_operations?(new_path) FileUtils.mkdir_p(File.dirname(new_path)) FileUtils.mv(old_path, new_path) broadcast_files_changed render json: { ok: true, oldPath: relative_path(old_path), path: relative_path(new_path), name: File.basename(new_path) } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#replace_in_files ⇒ Object
POST /mbeditor/replace_in_files Replaces a string/pattern across all matching files in the workspace. Returns { replaced_count:, files_affected:[], errors:[], partial: }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 464 def replace_in_files query = params[:query].to_s.strip replacement = params[:replacement].to_s use_regex = params[:regex] == 'true' match_case = params[:match_case] == 'true' whole_word = params[:whole_word] == 'true' return render json: { error: "Query is required" }, status: :bad_request if query.blank? return render json: { error: "Query too long" }, status: :bad_request if query.length > 500 # Collect all unique file paths that have at least one match. # Use a large limit to get all matching files; stream_search_results handles deduplication by file internally. raw_results = stream_search_results(query, 10_000, use_regex: use_regex, match_case: match_case, whole_word: whole_word) file_paths = raw_results.map { |r| r[:file] }.uniq # Fix 3: Cap the number of files to process if file_paths.length > MAX_REPLACE_FILES return render json: { error: "Too many files matched (#{file_paths.length}). Narrow your search." }, status: :unprocessable_entity end replaced_count = 0 files_affected = [] errors = [] # Build the Ruby Regexp to use for gsub begin pattern = if use_regex flags = match_case ? 0 : Regexp::IGNORECASE Regexp.new(whole_word ? "\\b(?:#{query})\\b" : query, flags) else flags = match_case ? 0 : Regexp::IGNORECASE Regexp.new(whole_word ? "\\b#{Regexp.escape(query)}\\b" : Regexp.escape(query), flags) end rescue RegexpError => e return render json: { error: "Invalid regex: #{e.}" }, status: :bad_request end file_paths.each do |rel_path| full_path = resolve_path(rel_path) unless full_path errors << { file: rel_path, error: "Forbidden" } next end # Fix 2: Check path_blocked_for_operations? if path_blocked_for_operations?(full_path) errors << { file: rel_path, error: "Forbidden" } next end unless File.file?(full_path) errors << { file: rel_path, error: "File not found" } next end if File.size(full_path) > MAX_OPEN_FILE_SIZE_BYTES errors << { file: rel_path, error: "File too large" } next end # Fix 1: Wrap per-file gsub/scan in a timeout to prevent ReDoS begin Timeout::timeout(5) do content = File.binread(full_path).force_encoding("UTF-8") replacements_in_file = content.scan(pattern).length new_content = content.gsub(pattern, replacement) # Fix 4: Use new_content != content instead of delta logic if new_content != content File.binwrite(full_path, new_content.encode("UTF-8", invalid: :replace, undef: :replace)) files_affected << rel_path replaced_count += replacements_in_file end end rescue Timeout::Error errors << { file: rel_path, error: "Timed out processing file" } next rescue StandardError => e errors << { file: rel_path, error: e. } next end end # Fix 5: Surface partial failure render json: { replaced_count: replaced_count, files_affected: files_affected, errors: errors, partial: errors.any? && files_affected.any? } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#run_test ⇒ Object
POST /mbeditor/test — run tests for the given file
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 845 def run_test path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path relative = relative_path(path) test_file = TestRunnerService.resolve_test_file(workspace_root.to_s, relative) return render json: { error: "No matching test file found for #{relative}" }, status: :not_found unless test_file full_test = File.join(workspace_root.to_s, test_file) return render json: { error: "Test file does not exist: #{test_file}" }, status: :not_found unless File.file?(full_test) config = Mbeditor.configuration result = TestRunnerService.run( workspace_root.to_s, test_file, framework: config.test_framework&.to_sym, command: config.test_command, timeout: config.test_timeout || 60 ) render json: result.merge(testFile: test_file) rescue StandardError => e render json: { error: e., ok: false }, status: :unprocessable_content end |
#save ⇒ Object
POST /mbeditor/file — save file
232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 232 def save path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path return render json: { error: "Cannot write to this path" }, status: :forbidden if path_blocked_for_operations?(path) content = params[:code].to_s return render_file_too_large(content.bytesize) if content.bytesize > MAX_OPEN_FILE_SIZE_BYTES File.write(path, content) broadcast_files_changed render json: { ok: true, path: relative_path(path) } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#save_branch_state ⇒ Object
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 113 def save_branch_state branch = sanitize_branch_name(params[:branch]) return render json: { error: "Invalid branch name" }, status: :bad_request unless branch payload = params[:state].to_unsafe_h return render json: { error: "State payload too large" }, status: :content_too_large if payload.to_json.bytesize > STATE_MAX_BYTES path = workspace_root.join("tmp", "mbeditor_branch_states.json") FileUtils.mkdir_p(workspace_root.join("tmp")) File.open(path, File::RDWR | File::CREAT) do |f| f.flock(File::LOCK_EX) existing = f.size > 0 ? JSON.parse(f.read) : {} existing[branch] = payload f.truncate(0) f.rewind f.write(existing.to_json) end render json: { ok: true } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#save_state ⇒ Object
POST /mbeditor/state — save workspace state
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 77 def save_state raw = params[:state] raw = raw.to_unsafe_h if raw.respond_to?(:to_unsafe_h) payload = raw.to_json return render json: { error: "State payload too large" }, status: :content_too_large if payload.bytesize > STATE_MAX_BYTES path = workspace_root.join("tmp", "mbeditor_workspace.json") FileUtils.mkdir_p(workspace_root.join("tmp")) File.open(path, File::RDWR | File::CREAT) do |f| f.flock(File::LOCK_EX) f.truncate(0) f.rewind f.write(payload) end render json: { ok: true } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#search ⇒ Object
GET /mbeditor/search?q=…&offset=0&limit=50®ex=false&match_case=false&whole_word=false
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 429 def search query = params[:q].to_s.strip offset = [params[:offset].to_i, 0].max limit = [[params[:limit].to_i > 0 ? params[:limit].to_i : 50, 200].min, 1].max use_regex = params[:regex] == 'true' match_case = params[:match_case] == 'true' whole_word = params[:whole_word] == 'true' needed = offset + limit + 1 # collect one extra to detect has_more return render json: [] if query.blank? return render json: { error: "Query too long" }, status: :bad_request if query.length > 500 # On first page, count total matches in parallel with fetching results. count_thread = offset == 0 ? Thread.new { count_search_results(query, use_regex: use_regex, match_case: match_case, whole_word: whole_word) } : nil results = stream_search_results(query, needed, use_regex: use_regex, match_case: match_case, whole_word: whole_word) has_more = results.length > offset + limit response = { results: results[offset, limit] || [], has_more: has_more } if count_thread # Give the count thread up to 100 ms; omit total_count when it hasn't finished yet # so the first page is never blocked by the counting subprocess. count_thread.join(0.1) response[:total_count] = count_thread.value unless count_thread.alive? end render json: response rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#show ⇒ Object
GET /mbeditor/file?path=…
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 163 def show path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path unless File.file?(path) return render json: missing_file_payload(params[:path]) if allow_missing_file? return render json: { error: "Not found" }, status: :not_found end start_line = params[:start_line] ? params[:start_line].to_i : nil line_count = params.key?(:line_count) ? params[:line_count].to_i : 500 line_count = [line_count, 5000].min if start_line total_bytes = File.size(path) chunk = [] total_lines = 0 File.foreach(path, encoding: "UTF-8", invalid: :replace, undef: :replace) do |line| chunk << line if total_lines >= start_line && chunk.length < line_count total_lines += 1 end return render json: { path: relative_path(path), content: chunk.join, truncated: total_lines > start_line + chunk.length, start_line: start_line, line_count: chunk.length, total_lines: total_lines, total_bytes: total_bytes } end size = File.size(path) return render_file_too_large(size) if size > MAX_OPEN_FILE_SIZE_BYTES if image_path?(path) return render json: { path: relative_path(path), image: true, size: size, content: "" } end stat = File.stat(path) etag = "#{stat.mtime.to_i}-#{stat.size}" if stale?(etag: etag, public: false) content = File.read(path, encoding: "UTF-8", invalid: :replace, undef: :replace) render json: { path: relative_path(path), content: content } end rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#state ⇒ Object
GET /mbeditor/state — load workspace state
59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 59 def state path = workspace_root.join("tmp", "mbeditor_workspace.json") if File.exist?(path) render json: JSON.parse(File.read(path)) else render json: {} end rescue Errno::ENOENT render json: {} rescue JSON::ParserError render json: {} rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#ts_worker ⇒ Object
GET /mbeditor/ts_worker.js — serve TypeScript/JavaScript Monaco worker
739 740 741 742 743 744 745 746 747 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 739 def ts_worker path = [ Mbeditor::Engine.root.join("public", "ts_worker.js"), Rails.root.join("public", "ts_worker.js") ].find { |p| p.file? }.to_s return render plain: "Not found", status: :not_found unless File.file?(path) send_file path, disposition: "inline", type: "application/javascript" end |
#unused_methods ⇒ Object
GET /mbeditor/unused_methods?path=app/models/article.rb Returns method names defined in the file that have no call-sites in the workspace.
414 415 416 417 418 419 420 421 422 423 424 425 426 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 414 def unused_methods path = resolve_path(params[:path]) return render json: { error: "Forbidden" }, status: :forbidden unless path unused = UnusedMethodsService.call( workspace_root, path, excluded_dirnames: excluded_dirnames, excluded_paths: excluded_paths ) render json: { unused: unused } rescue StandardError => e render json: { error: e. }, status: :unprocessable_content end |
#workspace ⇒ Object
GET /mbeditor/workspace — metadata about current workspace root
32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'app/controllers/mbeditor/editors_controller.rb', line 32 def workspace render json: { rootName: workspace_root.basename.to_s, rootPath: workspace_root.to_s, rubocopAvailable: rubocop_available?, rubocopConfigPath: rubocop_config_path, hamlLintAvailable: haml_lint_available?, gitAvailable: git_available?, blameAvailable: git_blame_available?, redmineEnabled: Mbeditor.configuration.redmine_enabled == true, testAvailable: test_available?, actionCableEnabled: action_cable_enabled? } end |