Class: Markymark::ServerSimple

Inherits:
Sinatra::Base
  • Object
show all
Defined in:
lib/markymark/server_simple.rb

Overview

Bulletproof simple Sinatra server for markdown browsing No SSE, no watcher, no threading, no JavaScript complexity

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.real_root_pathObject

Returns the value of attribute real_root_path.



27
28
29
# File 'lib/markymark/server_simple.rb', line 27

def real_root_path
  @real_root_path
end

.root_pathObject

Returns the value of attribute root_path.



27
28
29
# File 'lib/markymark/server_simple.rb', line 27

def root_path
  @root_path
end

Class Method Details

.add_bookmark(name, path) ⇒ Object



227
228
229
230
231
232
233
# File 'lib/markymark/server_simple.rb', line 227

def add_bookmark(name, path)
  bookmarks = load_bookmarks
  # Avoid duplicates
  return if bookmarks.any? { |b| b['path'] == path }
  bookmarks << { 'name' => name, 'path' => path }
  save_bookmarks(bookmarks)
end

.bookmarks_fileObject

Bookmark management methods



211
212
213
# File 'lib/markymark/server_simple.rb', line 211

def bookmarks_file
  File.expand_path('~/.markymark/bookmarks.json')
end

.delete_pid_fileObject



251
252
253
# File 'lib/markymark/server_simple.rb', line 251

def delete_pid_file
  File.delete(pid_file_path) if File.exist?(pid_file_path)
end

.find_markdown_files(root_path = @root_path) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/markymark/server_simple.rb', line 80

def find_markdown_files(root_path = @root_path)
  pattern = File.join(root_path, '**', '*.{md,markdown}')
  begin
    Dir.glob(pattern, File::FNM_CASEFOLD).map do |full_path|
      Pathname.new(full_path).relative_path_from(Pathname.new(root_path)).to_s
    end.sort
  rescue Errno::EPERM, Errno::EACCES => e
    # Permission denied on some subdirectory - fall back to non-recursive scan
    warn "Warning: Permission denied scanning #{root_path}, using non-recursive scan"
    find_markdown_files_safe(root_path)
  end
end

.find_markdown_files_safe(root_path) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/markymark/server_simple.rb', line 93

def find_markdown_files_safe(root_path)
  # Non-recursive scan that skips protected directories
  files = []
  dirs_to_scan = [root_path]

  while dirs_to_scan.any?
    dir = dirs_to_scan.shift
    begin
      Dir.entries(dir).each do |entry|
        next if entry.start_with?('.')
        full_path = File.join(dir, entry)
        if File.directory?(full_path)
          # Skip known protected directories
          next if full_path.include?('/Library/')
          dirs_to_scan << full_path
        elsif entry.match?(/\.(md|markdown)$/i)
          files << Pathname.new(full_path).relative_path_from(Pathname.new(root_path)).to_s
        end
      end
    rescue Errno::EPERM, Errno::EACCES
      # Skip directories we can't access
      next
    end
  end
  files.sort
end

.group_files_by_directory(files) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/markymark/server_simple.rb', line 120

def group_files_by_directory(files)
  grouped = {}
  files.each do |file|
    dir = File.dirname(file)
    dir = "." if dir == "."
    grouped[dir] ||= []
    grouped[dir] << File.basename(file)
  end
  # Sort directories, with "." (root) first
  sorted_dirs = grouped.keys.sort do |a, b|
    if a == "."
      -1
    elsif b == "."
      1
    else
      a <=> b
    end
  end
  sorted_dirs.map { |dir| [dir, grouped[dir].sort] }.to_h
end

.launch(cli) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/markymark/server_simple.rb', line 29

def launch(cli)
  @root_path = cli.root_path
  @real_root_path = File.realpath(@root_path)

  # Print startup message
  base_url = "http://localhost:#{cli.port}"
  puts "markymark serving #{@root_path} on #{base_url}"

  # Build URL with optional file parameter
  url = if cli.initial_file
    "#{base_url}/?file=#{CGI.escape(cli.initial_file)}"
  else
    base_url
  end

  # Open browser if requested (before forking)
  Launchy.open(url) if cli.open_browser

  # Fork the process to run server in background
  pid = fork do
    # In child process - run the server

    # Detach from terminal
    Process.setsid

    # Redirect output to /dev/null
    $stdout.reopen('/dev/null', 'w')
    $stderr.reopen('/dev/null', 'w')

    # Write PID file for server detection
    write_pid_file(cli.port)

    # Clean up PID file on exit
    at_exit do
      delete_pid_file
    end

    # Start server
    set :port, cli.port
    run!
  end

  # In parent process - detach child and exit
  Process.detach(pid)

  # Give server a moment to start
  sleep 1

  puts "Server started in background (PID: #{pid})"
end

.load_bookmarksObject



215
216
217
218
219
220
# File 'lib/markymark/server_simple.rb', line 215

def load_bookmarks
  return [] unless File.exist?(bookmarks_file)
  JSON.parse(File.read(bookmarks_file))
rescue JSON::ParserError, Errno::ENOENT
  []
end

.pid_file_pathObject

PID file management for server detection



242
243
244
# File 'lib/markymark/server_simple.rb', line 242

def pid_file_path
  File.expand_path('~/.markymark/server.pid')
end

.remove_bookmark(index) ⇒ Object



235
236
237
238
239
# File 'lib/markymark/server_simple.rb', line 235

def remove_bookmark(index)
  bookmarks = load_bookmarks
  bookmarks.delete_at(index.to_i)
  save_bookmarks(bookmarks)
end

.render_markdown(file_path, root_path = @root_path) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/markymark/server_simple.rb', line 141

def render_markdown(file_path, root_path = @root_path)
  full_path = File.join(root_path, file_path)
  return nil unless File.exist?(full_path) && File.file?(full_path)

  content = File.read(full_path, encoding: 'UTF-8')
  html = Kramdown::Document.new(content, input: 'GFM', syntax_highlighter: 'rouge').to_html

  # Convert mermaid code blocks to divs for mermaid.js rendering
  html = html.gsub(/<pre><code class="language-mermaid">(.*?)<\/code><\/pre>/m) do
    "<div class=\"mermaid\">#{$1}</div>"
  end

  # Rewrite relative markdown links to use query parameters
  html = rewrite_markdown_links(html, file_path, root_path)

  html
rescue => e
  "<p>Error rendering markdown: #{e.message}</p>"
end


161
162
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
# File 'lib/markymark/server_simple.rb', line 161

def rewrite_markdown_links(html, current_file, root_path)
  # Get the directory of the current file for resolving relative paths
  current_dir = File.dirname(current_file)
  current_dir = "." if current_dir == "."

  # Rewrite relative links to .md or .markdown files
  html.gsub(/<a\s+href=["']([^"']+)["']([^>]*)>/i) do
    full_match = $&
    href = $1
    rest_of_tag = $2

    # Skip if it's an absolute URL (http://, https://, //, ftp://, mailto:, etc.)
    if href =~ %r{^([a-z][a-z0-9+.-]*:|//)}i
      next full_match
    end

    # Skip if it's an anchor link
    if href.start_with?('#')
      next full_match
    end

    # Only rewrite links to markdown files
    if href =~ /\.(md|markdown)$/i
      # Resolve the relative path from the current file's directory
      if current_dir == "."
        target_file = href
      else
        target_file = File.join(current_dir, href)
      end

      # Normalize the path (remove ./ and resolve ../)
      target_file = Pathname.new(target_file).cleanpath.to_s

      # Rewrite to use query parameters
      encoded_file = CGI.escape(target_file)
      encoded_dir = CGI.escape(root_path)
      %Q{<a href="/?file=#{encoded_file}&dir=#{encoded_dir}"#{rest_of_tag}>}
    else
      # Not a markdown file, leave as-is
      full_match
    end
  end
end

.save_bookmarks(bookmarks) ⇒ Object



222
223
224
225
# File 'lib/markymark/server_simple.rb', line 222

def save_bookmarks(bookmarks)
  FileUtils.mkdir_p(File.dirname(bookmarks_file))
  File.write(bookmarks_file, JSON.pretty_generate(bookmarks))
end

.within_root?(real_path, real_root_path = @real_root_path) ⇒ Boolean

Returns:

  • (Boolean)


205
206
207
208
# File 'lib/markymark/server_simple.rb', line 205

def within_root?(real_path, real_root_path = @real_root_path)
  return false unless real_path && real_root_path
  real_path == real_root_path || real_path.start_with?(File.join(real_root_path, ''))
end

.write_pid_file(port) ⇒ Object



246
247
248
249
# File 'lib/markymark/server_simple.rb', line 246

def write_pid_file(port)
  FileUtils.mkdir_p(File.dirname(pid_file_path))
  File.write(pid_file_path, "port=#{port}\npid=#{Process.pid}\n")
end

Instance Method Details

#json_or_text_error(message, status) ⇒ Object

Helper method for dual-format error responses



360
361
362
363
364
365
366
367
# File 'lib/markymark/server_simple.rb', line 360

def json_or_text_error(message, status)
  if request.accept?('application/json') || request.env['HTTP_ACCEPT']&.include?('application/json')
    content_type :json
    halt status, { error: message }.to_json
  else
    halt status, message
  end
end