llm-docs-builder 1.1.0 → 1.1.1

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.
@@ -46,21 +46,39 @@ module LlmDocsBuilder
46
46
  when 'version'
47
47
  show_version
48
48
  else
49
- puts "Unknown command: #{options[:command]}"
50
- puts "Run 'llm-docs-builder --help' for usage information"
51
- exit 1
49
+ exit_with_usage_error("Unknown command: #{options[:command]}")
52
50
  end
51
+ rescue OptionParser::ParseError => e
52
+ exit_with_usage_error("Error: #{e.message}")
53
53
  rescue LlmDocsBuilder::Errors::BaseError => e
54
- puts "Error: #{e.message}"
55
- exit 1
54
+ exit_with_error("Error: #{e.message}")
56
55
  rescue StandardError => e
57
- puts "Unexpected error: #{e.message}"
58
- puts e.backtrace.join("\n") if options&.fetch(:verbose, false)
59
- exit 1
56
+ lines = ["Unexpected error: #{e.message}"]
57
+ lines << e.backtrace.join("\n") if options&.fetch(:verbose, false)
58
+ exit_with_error(*lines)
60
59
  end
61
60
 
62
61
  private
63
62
 
63
+ # Print error lines to stderr and exit
64
+ #
65
+ # Uses $stderr directly because Kernel#warn prints nothing when warnings are disabled (-W0).
66
+ #
67
+ # @param lines [Array<String>] lines to print
68
+ # @raise [SystemExit] always, with status 1
69
+ def exit_with_error(*lines)
70
+ lines.each { |line| $stderr.puts(line) }
71
+ exit 1
72
+ end
73
+
74
+ # Print a usage error with a pointer to the help and exit
75
+ #
76
+ # @param message [String] error message
77
+ # @raise [SystemExit] always, with status 1
78
+ def exit_with_usage_error(message)
79
+ exit_with_error(message, "Run 'llm-docs-builder --help' for usage information")
80
+ end
81
+
64
82
  # Parse command-line options using OptionParser
65
83
  #
66
84
  # Extracts command and options from argv. First non-flag argument is treated as command name.
@@ -97,7 +115,7 @@ module LlmDocsBuilder
97
115
  options[:docs] = path
98
116
  end
99
117
 
100
- opts.on('-o', '--output PATH', 'Output file path') do |path|
118
+ opts.on('-o', '--output PATH', 'Output file path (transform prints to stdout without it)') do |path|
101
119
  options[:output] = path
102
120
  end
103
121
 
@@ -139,15 +157,12 @@ module LlmDocsBuilder
139
157
  # @raise [SystemExit] exits with status 1 if docs path not found
140
158
  def generate(options)
141
159
  # Load config and merge with CLI options
142
- config = LlmDocsBuilder::Config.new(options[:config])
160
+ config = load_config(options[:config])
143
161
  merged_options = config.merge_with_options(options)
144
162
 
145
163
  docs_path = merged_options[:docs]
146
164
 
147
- unless File.exist?(docs_path)
148
- puts "Documentation path not found: #{docs_path}"
149
- exit 1
150
- end
165
+ exit_with_error("Documentation path not found: #{docs_path}") unless File.exist?(docs_path)
151
166
 
152
167
  puts "Generating llms.txt from #{docs_path}..." if merged_options[:verbose]
153
168
 
@@ -175,14 +190,15 @@ module LlmDocsBuilder
175
190
  # @param options [Hash] command options from parse_options
176
191
  # @option options [String] :config path to config file
177
192
  # @option options [String] :docs path to markdown file (required)
178
- # @option options [String] :output output file path
193
+ # @option options [String] :output output file path (prints to stdout when not given;
194
+ # the config's output is not used)
179
195
  # @option options [String] :base_url base URL for link expansion
180
196
  # @option options [Boolean] :convert_urls convert .html to .md
181
197
  # @option options [Boolean] :verbose enable verbose output
182
198
  # @raise [SystemExit] exits with status 1 if file not found or -d flag missing
183
199
  def transform(options)
184
200
  # Load config and merge with CLI options
185
- config = LlmDocsBuilder::Config.new(options[:config])
201
+ config = load_config(options[:config])
186
202
  merged_options = config.merge_with_options(options)
187
203
 
188
204
  url = options[:url]
@@ -190,16 +206,10 @@ module LlmDocsBuilder
190
206
  config_file_path = config['docs']
191
207
  file_path = url ? cli_file_path : (cli_file_path || config_file_path)
192
208
 
193
- if url && cli_file_path
194
- puts 'Cannot use both --docs and --url for transform command'
195
- exit 1
196
- end
209
+ exit_with_error('Cannot use both --docs and --url for transform command') if url && cli_file_path
197
210
 
198
211
  unless file_path
199
- unless url
200
- puts 'File path required for transform command (use -d/--docs)'
201
- exit 1
202
- end
212
+ exit_with_error('File path required for transform command (use -d/--docs)') unless url
203
213
  end
204
214
 
205
215
  content =
@@ -211,10 +221,7 @@ module LlmDocsBuilder
211
221
  transform_options = merged_options.merge(content: remote_content, docs: nil, source_url: url)
212
222
  LlmDocsBuilder.transform_markdown(nil, transform_options)
213
223
  else
214
- unless File.exist?(file_path)
215
- puts "File not found: #{file_path}"
216
- exit 1
217
- end
224
+ exit_with_error("File not found: #{file_path}") unless File.exist?(file_path)
218
225
 
219
226
  puts "Transforming #{file_path}..." if merged_options[:verbose]
220
227
 
@@ -222,9 +229,10 @@ module LlmDocsBuilder
222
229
  LlmDocsBuilder.transform_markdown(file_path, merged_options)
223
230
  end
224
231
 
225
- if merged_options[:output] && merged_options[:output] != 'llms.txt'
226
- File.write(merged_options[:output], content)
227
- puts "Transformed content saved to #{merged_options[:output]}"
232
+ # The config's output names the generate target, so only -o writes a file here
233
+ if options[:output]
234
+ File.write(options[:output], content.sub(/\n?\z/, "\n"))
235
+ puts "Transformed content saved to #{options[:output]}"
228
236
  else
229
237
  puts content
230
238
  end
@@ -245,19 +253,15 @@ module LlmDocsBuilder
245
253
  # @raise [SystemExit] exits with status 1 if directory not found or transformation fails
246
254
  def bulk_transform(options)
247
255
  # Load config and merge with CLI options
248
- config = LlmDocsBuilder::Config.new(options[:config])
256
+ config = load_config(options[:config])
249
257
  merged_options = config.merge_with_options(options)
250
258
 
251
259
  docs_path = merged_options[:docs]
252
260
 
253
- unless File.exist?(docs_path)
254
- puts "Documentation path not found: #{docs_path}"
255
- exit 1
256
- end
261
+ exit_with_error("Documentation path not found: #{docs_path}") unless File.exist?(docs_path)
257
262
 
258
263
  unless File.directory?(docs_path)
259
- puts "Path must be a directory for bulk transformation: #{docs_path}"
260
- exit 1
264
+ exit_with_error("Path must be a directory for bulk transformation: #{docs_path}")
261
265
  end
262
266
 
263
267
  puts "Bulk transforming markdown files in #{docs_path}..." if merged_options[:verbose]
@@ -281,8 +285,7 @@ module LlmDocsBuilder
281
285
  end
282
286
  end
283
287
  rescue LlmDocsBuilder::Errors::BaseError => e
284
- puts "Error during bulk transformation: #{e.message}"
285
- exit 1
288
+ exit_with_error("Error during bulk transformation: #{e.message}")
286
289
  end
287
290
  end
288
291
 
@@ -290,32 +293,31 @@ module LlmDocsBuilder
290
293
  #
291
294
  # Reads and parses llms.txt file, displaying title, description, and links.
292
295
  # Defaults to 'llms.txt' in current directory if no file specified.
296
+ # The config file's docs setting is the docs directory for generate, so it is not used here.
293
297
  #
294
298
  # @param options [Hash] command options from parse_options
295
- # @option options [String] :config path to config file
296
299
  # @option options [String] :docs path to llms.txt file (defaults to 'llms.txt')
297
- # @option options [Boolean] :verbose enable verbose output with link counts
300
+ # @option options [Boolean] :verbose also list each link under its section count
298
301
  # @raise [SystemExit] exits with status 1 if file not found
299
302
  def parse(options)
300
- # Load config and merge with CLI options
301
- config = LlmDocsBuilder::Config.new(options[:config])
302
- merged_options = config.merge_with_options(options)
303
+ file_path = options[:docs] || 'llms.txt'
303
304
 
304
- file_path = merged_options[:docs] || 'llms.txt'
305
-
306
- unless File.exist?(file_path)
307
- puts "File not found: #{file_path}"
308
- exit 1
309
- end
305
+ exit_with_error("File not found: #{file_path}") unless File.exist?(file_path)
310
306
 
311
307
  parsed = LlmDocsBuilder.parse(file_path)
312
308
 
313
- if options[:verbose]
314
- puts "Title: #{parsed.title}"
315
- puts "Description: #{parsed.description}"
316
- puts "Documentation Links: #{parsed.documentation_links.size}"
317
- puts "Example Links: #{parsed.example_links.size}" if parsed.respond_to?(:example_links)
318
- puts "Optional Links: #{parsed.optional_links.size}" if parsed.respond_to?(:optional_links)
309
+ puts "Title: #{parsed.title}"
310
+ puts "Description: #{parsed.description}"
311
+
312
+ {
313
+ 'Documentation' => parsed.documentation_links,
314
+ 'Example' => parsed.example_links,
315
+ 'Optional' => parsed.optional_links
316
+ }.each do |section, links|
317
+ puts "#{section} Links: #{links.size}"
318
+ next unless options[:verbose]
319
+
320
+ links.each { |link| puts " - #{link[:title]}: #{link[:url]}" }
319
321
  end
320
322
  end
321
323
 
@@ -334,15 +336,16 @@ module LlmDocsBuilder
334
336
  url = options[:url]
335
337
 
336
338
  unless url
337
- puts 'URL required for compare command (use -u/--url)'
338
- puts ''
339
- puts 'Examples:'
340
- puts ' # Compare remote versions (different User-Agents)'
341
- puts ' llm-docs-builder compare --url https://example.com/docs/page.html'
342
- puts ''
343
- puts ' # Compare remote with local file'
344
- puts ' llm-docs-builder compare --url https://example.com/docs/page.html --file docs/page.md'
345
- exit 1
339
+ exit_with_error(
340
+ 'URL required for compare command (use -u/--url)',
341
+ '',
342
+ 'Examples:',
343
+ ' # Compare remote versions (different User-Agents)',
344
+ ' llm-docs-builder compare --url https://example.com/docs/page.html',
345
+ '',
346
+ ' # Compare remote with local file',
347
+ ' llm-docs-builder compare --url https://example.com/docs/page.html --file docs/page.md'
348
+ )
346
349
  end
347
350
 
348
351
  comparator_options = {
@@ -356,8 +359,7 @@ module LlmDocsBuilder
356
359
  result = comparator.compare
357
360
  OutputFormatter.display_comparison_results(result)
358
361
  rescue LlmDocsBuilder::Errors::BaseError => e
359
- puts "Error during comparison: #{e.message}"
360
- exit 1
362
+ exit_with_error("Error during comparison: #{e.message}")
361
363
  end
362
364
  end
363
365
 
@@ -365,22 +367,15 @@ module LlmDocsBuilder
365
367
  #
366
368
  # Checks if llms.txt file follows proper format with title, description, and documentation links.
367
369
  # Defaults to 'llms.txt' in current directory if no file specified.
370
+ # The config file's docs setting is the docs directory for generate, so it is not used here.
368
371
  #
369
372
  # @param options [Hash] command options from parse_options
370
- # @option options [String] :config path to config file
371
373
  # @option options [String] :docs path to llms.txt file (defaults to 'llms.txt')
372
374
  # @raise [SystemExit] exits with status 1 if file not found or invalid
373
375
  def validate(options)
374
- # Load config and merge with CLI options
375
- config = LlmDocsBuilder::Config.new(options[:config])
376
- merged_options = config.merge_with_options(options)
377
-
378
- file_path = merged_options[:docs] || 'llms.txt'
376
+ file_path = options[:docs] || 'llms.txt'
379
377
 
380
- unless File.exist?(file_path)
381
- puts "File not found: #{file_path}"
382
- exit 1
383
- end
378
+ exit_with_error("File not found: #{file_path}") unless File.exist?(file_path)
384
379
 
385
380
  content = File.read(file_path)
386
381
  valid = LlmDocsBuilder.validate(content)
@@ -397,6 +392,19 @@ module LlmDocsBuilder
397
392
  end
398
393
  end
399
394
 
395
+ # Load the config file given with --config, or the auto-discovered one
396
+ #
397
+ # @param config_path [String, nil] path given with --config, or nil to auto-find
398
+ # @return [LlmDocsBuilder::Config] loaded configuration
399
+ # @raise [LlmDocsBuilder::Errors::GenerationError] if the given config file does not exist
400
+ def load_config(config_path)
401
+ if config_path && !File.exist?(config_path)
402
+ raise LlmDocsBuilder::Errors::GenerationError, "Config file not found: #{config_path}"
403
+ end
404
+
405
+ LlmDocsBuilder::Config.new(config_path)
406
+ end
407
+
400
408
  # Display version information
401
409
  def show_version
402
410
  puts "llm-docs-builder version #{LlmDocsBuilder::VERSION}"
@@ -60,6 +60,8 @@ module LlmDocsBuilder
60
60
  # @option options [String] :body additional body content
61
61
  # @option options [String] :output output file path
62
62
  # @option options [Boolean] :convert_urls convert HTML URLs to markdown format
63
+ # @option options [String] :relative_links where `base_url` expansion resolves relative links from:
64
+ # `'base_url'` (default) or `'file'` (the file's directory)
63
65
  # @option options [Boolean] :remove_comments remove HTML comments
64
66
  # @option options [Boolean] :normalize_whitespace normalize whitespace
65
67
  # @option options [Boolean] :remove_badges remove badge images
@@ -68,7 +70,7 @@ module LlmDocsBuilder
68
70
  # @option options [String] :suffix suffix for transformed files
69
71
  # @option options [Array<String>] :excludes glob patterns for files to exclude
70
72
  # @option options [Boolean] :bulk enable bulk transformation mode
71
- # @option options [Boolean] :include_hidden include hidden files
73
+ # @option options [Boolean] :include_hidden include files in hidden directories (hidden files are always skipped)
72
74
  # @option options [Boolean] :remove_code_examples remove code blocks
73
75
  # @option options [Boolean] :remove_images remove image syntax
74
76
  # @option options [Boolean] :simplify_links simplify link text
@@ -86,7 +88,8 @@ module LlmDocsBuilder
86
88
  # @option options [Boolean] :calculate_compression calculate compression ratios
87
89
  # @option options [String] :content raw markdown content
88
90
  # @option options [String] :source_url source URL for content
89
- # @return [Hash] merged configuration with CLI overrides applied
91
+ # @return [Hash] merged configuration with CLI overrides applied, marked with
92
+ # `config_merged: true`; the library loads no config file for it unless `:config_file` is given
90
93
  def merge_with_options(options)
91
94
  # CLI options override config file, config file provides defaults
92
95
  {
@@ -105,6 +108,7 @@ module LlmDocsBuilder
105
108
  else
106
109
  self['convert_urls'] || false
107
110
  end,
111
+ relative_links: relative_links_option(options[:relative_links] || self['relative_links']),
108
112
  remove_comments: if options.key?(:remove_comments)
109
113
  options[:remove_comments]
110
114
  elsif !self['remove_comments'].nil?
@@ -209,6 +213,7 @@ module LlmDocsBuilder
209
213
  self['calculate_compression'] || false
210
214
  end
211
215
  }.tap do |merged|
216
+ merged[:config_merged] = true
212
217
  merged[:content] = options[:content] if options.key?(:content)
213
218
  merged[:source_url] = options[:source_url] if options.key?(:source_url)
214
219
  end
@@ -223,6 +228,22 @@ module LlmDocsBuilder
223
228
 
224
229
  private
225
230
 
231
+ # Accepted values of the relative_links option
232
+ RELATIVE_LINKS = %w[base_url file].freeze
233
+ private_constant :RELATIVE_LINKS
234
+
235
+ # Validate the relative_links option
236
+ #
237
+ # @param value [String, Symbol, nil] configured value
238
+ # @return [String] `'base_url'` or `'file'`
239
+ # @raise [Errors::GenerationError] for any other value
240
+ def relative_links_option(value)
241
+ value = (value || 'base_url').to_s
242
+ return value if RELATIVE_LINKS.include?(value)
243
+
244
+ raise Errors::GenerationError, "Invalid relative_links: #{value} (use base_url or file)"
245
+ end
246
+
226
247
  # Find config file in current directory
227
248
  #
228
249
  # Looks for config files in order of preference:
@@ -73,30 +73,11 @@ module LlmDocsBuilder
73
73
 
74
74
  # Recursively finds and analyzes markdown files in directory
75
75
  #
76
- # Sorts by priority (README, guides, etc.) and skips hidden files and bulk-transformed
77
- # files (ending with the suffix, e.g. README.llm.md)
76
+ # Sorts by priority (README, guides, etc.); see MarkdownFinder for the files it skips
78
77
  #
79
78
  # @return [Array<Hash>] sorted array of analyzed file metadata
80
79
  def find_markdown_files_in_directory
81
- files = []
82
- output_ending = "#{options.fetch(:suffix, '.llm')}.md".downcase
83
-
84
- Find.find(docs_path) do |path|
85
- # Skip hidden directories unless explicitly enabled
86
- # Don't prune the root docs_path itself (even if it's ".")
87
- if File.directory?(path) && path != docs_path && File.basename(path).start_with?('.') && !options[:include_hidden]
88
- Find.prune
89
- next
90
- end
91
-
92
- next unless File.file?(path)
93
- next unless path.match?(/\.md$/i)
94
- next if File.basename(path).start_with?('.')
95
- next if output_ending != '.md' && path.downcase.end_with?(output_ending)
96
- next if should_exclude?(path)
97
-
98
- files << analyze_file(path)
99
- end
80
+ files = MarkdownFinder.new(docs_path, options).files.map { |path| analyze_file(path) }
100
81
 
101
82
  files.sort_by { |f| f[:priority] }
102
83
  end
@@ -239,7 +220,8 @@ module LlmDocsBuilder
239
220
 
240
221
  # Assigns priority to file based on filename patterns
241
222
  #
242
- # README gets highest priority, followed by guides, tutorials, API docs
223
+ # README gets highest priority, followed by getting started docs; other pages are documentation,
224
+ # except tutorials and examples (Examples) and reference and advanced topics (Optional)
243
225
  #
244
226
  # @param file_path [String] path to file
245
227
  # @return [Integer] priority value (1-7, lower is higher priority)
@@ -250,10 +232,12 @@ module LlmDocsBuilder
250
232
  return 2 if basename.include?('getting')
251
233
  return 3 if basename.include?('guide')
252
234
  return 4 if basename.include?('tutorial')
253
- return 5 if basename.include?('api')
235
+ return 4 if basename.include?('example')
236
+ return 3 if basename.include?('api')
254
237
  return 6 if basename.include?('reference')
238
+ return 7 if basename.include?('advanced')
255
239
 
256
- 7 # default priority
240
+ 3 # default priority
257
241
  end
258
242
 
259
243
  # Applies transformations to content for compression ratio calculation
@@ -404,53 +388,6 @@ module LlmDocsBuilder
404
388
  end
405
389
  end
406
390
 
407
- # Tests if file matches any exclusion pattern from options
408
- #
409
- # Uses File.fnmatch with pathname and dotmatch flags.
410
- # Checks against both absolute path and relative path from docs_path.
411
- #
412
- # @param file_path [String] path to check
413
- # @return [Boolean] true if file should be excluded
414
- def should_exclude?(file_path)
415
- excludes = Array(options[:excludes])
416
- return false if excludes.empty?
417
-
418
- # Get relative path from docs_path for matching
419
- relative_path = begin
420
- if File.directory?(docs_path)
421
- # Convert both to absolute paths first to avoid "different prefix" error
422
- abs_file = File.expand_path(file_path)
423
- abs_docs = File.expand_path(docs_path)
424
- Pathname.new(abs_file).relative_path_from(Pathname.new(abs_docs)).to_s
425
- else
426
- File.basename(file_path)
427
- end
428
- rescue ArgumentError
429
- # If paths can't be made relative (different roots), use basename
430
- File.basename(file_path)
431
- end
432
-
433
- excludes.any? do |pattern|
434
- # Normalize pattern: ensure /** is followed by something
435
- # fnmatch requires /** to be followed by at least one component
436
- normalized_pattern = pattern.end_with?('/**') ? "#{pattern}/*" : pattern
437
-
438
- # Check both absolute and relative paths
439
- matches = File.fnmatch(normalized_pattern, file_path, File::FNM_PATHNAME | File::FNM_DOTMATCH) ||
440
- File.fnmatch(normalized_pattern, relative_path, File::FNM_PATHNAME | File::FNM_DOTMATCH)
441
-
442
- # If pattern starts with **/, also try without it (for root-level matches)
443
- # Since **/ in fnmatch doesn't match zero directories
444
- if !matches && normalized_pattern.start_with?('**/')
445
- pattern_without_prefix = normalized_pattern.sub(%r{^\*\*/}, '')
446
- matches = File.fnmatch(pattern_without_prefix, file_path, File::FNM_PATHNAME | File::FNM_DOTMATCH) ||
447
- File.fnmatch(pattern_without_prefix, relative_path, File::FNM_PATHNAME | File::FNM_DOTMATCH)
448
- end
449
-
450
- matches
451
- end
452
- end
453
-
454
391
  # Checks if any transformation options are enabled
455
392
  #
456
393
  # @return [Boolean] true if any transformation option is enabled
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmDocsBuilder
4
+ # Finds the source markdown files in a documentation directory
5
+ #
6
+ # Shared by `generate` and `bulk-transform` so both pick the same files: hidden directories
7
+ # are pruned unless `include_hidden` is set, hidden files and bulk-transformed files (ending
8
+ # with the suffix, e.g. README.llm.md) are skipped, and files matching `excludes` are left out.
9
+ #
10
+ # @api private
11
+ class MarkdownFinder
12
+ # Flags used for every exclude pattern match
13
+ FNMATCH_FLAGS = File::FNM_PATHNAME | File::FNM_DOTMATCH
14
+ private_constant :FNMATCH_FLAGS
15
+
16
+ # Matches a path whose last component starts with a dot
17
+ HIDDEN_PATH_PATTERN = %r{(?:\A|/)\.[^/]*\z}
18
+ private_constant :HIDDEN_PATH_PATTERN
19
+
20
+ # @return [String] path to documentation directory
21
+ attr_reader :docs_path
22
+
23
+ # @return [Hash] finder options
24
+ attr_reader :options
25
+
26
+ # Initialize a new finder
27
+ #
28
+ # @param docs_path [String] path to documentation directory
29
+ # @param options [Hash] finder options
30
+ # @option options [String] :suffix suffix of bulk-transformed files to skip (default: '.llm')
31
+ # @option options [Array<String>] :excludes glob patterns for files to exclude
32
+ # @option options [Boolean] :include_hidden include files in hidden directories
33
+ def initialize(docs_path, options = {})
34
+ @docs_path = docs_path
35
+ @options = options
36
+ @docs_prefix = docs_path.end_with?('/') ? docs_path : "#{docs_path}/"
37
+ @exclude_patterns = Array(options[:excludes]).map { |pattern| normalize_pattern(pattern) }
38
+ end
39
+
40
+ # Recursively finds the source markdown files in docs_path
41
+ #
42
+ # @return [Array<String>] paths to markdown files, in directory traversal order
43
+ def files
44
+ files = []
45
+ output_ending = "#{options.fetch(:suffix, '.llm')}.md".downcase
46
+
47
+ Find.find(docs_path) do |path|
48
+ if hidden_directory?(path)
49
+ Find.prune
50
+ next
51
+ end
52
+
53
+ next unless File.file?(path)
54
+ next unless path.match?(/\.md$/i)
55
+ next if path.match?(HIDDEN_PATH_PATTERN)
56
+ next if output_ending != '.md' && path.downcase.end_with?(output_ending)
57
+ next if excluded?(path)
58
+
59
+ files << path
60
+ end
61
+
62
+ files
63
+ end
64
+
65
+ # Tests if file matches any exclusion pattern from options
66
+ #
67
+ # Checks both the given path and the path relative to docs_path. A trailing `/**` matches
68
+ # files at any depth below the directory.
69
+ #
70
+ # @param file_path [String] path to check
71
+ # @return [Boolean] true if file should be excluded
72
+ def excluded?(file_path)
73
+ return false if @exclude_patterns.empty?
74
+
75
+ relative = relative_path(file_path)
76
+
77
+ @exclude_patterns.any? do |pattern|
78
+ File.fnmatch(pattern, file_path, FNMATCH_FLAGS) || File.fnmatch(pattern, relative, FNMATCH_FLAGS)
79
+ end
80
+ end
81
+
82
+ private
83
+
84
+ # Converts an exclude pattern into the fnmatch pattern that implements it
85
+ #
86
+ # @param pattern [String] exclude pattern from options
87
+ # @return [String] fnmatch pattern
88
+ def normalize_pattern(pattern)
89
+ # fnmatch requires /** to be followed by at least one component
90
+ pattern.end_with?('/**') ? "#{pattern}/*" : pattern
91
+ end
92
+
93
+ # Tests if path is a hidden directory to skip
94
+ #
95
+ # The root docs_path itself is never skipped (even if it's ".")
96
+ #
97
+ # @param path [String] path to check
98
+ # @return [Boolean] true if path is a hidden directory and include_hidden is not set
99
+ def hidden_directory?(path)
100
+ return false if options[:include_hidden] || path == docs_path
101
+
102
+ path.match?(HIDDEN_PATH_PATTERN) && File.directory?(path)
103
+ end
104
+
105
+ # Computes the path of a file relative to docs_path
106
+ #
107
+ # Paths from Find.find start with docs_path, so the prefix is stripped without Pathname.
108
+ #
109
+ # @param file_path [String] path to a file inside docs_path
110
+ # @return [String] relative path, or the basename if it can't be made relative
111
+ def relative_path(file_path)
112
+ return file_path.delete_prefix(@docs_prefix) if file_path.start_with?(@docs_prefix)
113
+
114
+ @expanded_docs_path ||= Pathname.new(File.expand_path(docs_path))
115
+ Pathname.new(File.expand_path(file_path)).relative_path_from(@expanded_docs_path).to_s
116
+ rescue ArgumentError
117
+ File.basename(file_path)
118
+ end
119
+ end
120
+ end
@@ -47,9 +47,9 @@ module LlmDocsBuilder
47
47
  #
48
48
  # Processes content through specialized transformers in order:
49
49
  # 1. ContentCleanupTransformer - Removes unwanted elements
50
- # 2. LinkTransformer - Processes links
51
- # 3. HeadingTransformer - Normalizes heading hierarchy (if enabled)
52
- # 4. TextCompressor - Advanced compression (if enabled)
50
+ # 2. LinkTransformer - Processes links, on the code detection of step 1
51
+ # 3. HeadingTransformer - Normalizes heading hierarchy (if enabled), on the code detection of step 1
52
+ # 4. TextCompressor - Advanced compression (if enabled), on the code detection of step 1
53
53
  # 5. EnhancementTransformer - Adds TOC and instructions
54
54
  # 6. WhitespaceTransformer - Normalizes whitespace
55
55
  #
@@ -58,10 +58,11 @@ module LlmDocsBuilder
58
58
  content = load_content
59
59
 
60
60
  # Build and execute transformation pipeline
61
- content = cleanup_transformer.transform(content, options)
62
- content = link_transformer.transform(content, options)
63
- content = heading_transformer.transform(content, options)
64
- content = compress_content(content) if should_compress?
61
+ content = cleanup_transformer.transform(content, options) do |text|
62
+ text = link_transformer.transform_outside_code(text, options)
63
+ text = heading_transformer.transform(text, options)
64
+ should_compress? ? compress_content(text) : text
65
+ end
65
66
  content = enhancement_transformer.transform(content, options)
66
67
  whitespace_transformer.transform(content, options)
67
68
  end
@@ -112,15 +113,15 @@ module LlmDocsBuilder
112
113
 
113
114
  # Compress content using TextCompressor
114
115
  #
115
- # @param content [String] markdown content
116
- # @return [String] compressed content
116
+ # @param content [String] content with code replaced by {Transformers::CodeBlocks} placeholders
117
+ # @return [String] compressed content, still with placeholders
117
118
  def compress_content(content)
118
119
  compressor = TextCompressor.new
119
120
  compression_methods = {
120
121
  remove_stopwords: options[:remove_stopwords],
121
122
  remove_duplicates: options[:remove_duplicates]
122
123
  }
123
- compressor.compress(content, compression_methods)
124
+ compressor.compress_outside_code(content, compression_methods)
124
125
  end
125
126
 
126
127
  # Load source content either from provided string or file path