Module: DocOpsLab::Dev::SyncOps

Defined in:
lib/docopslab/dev/sync_ops.rb

Class Method Summary collapse

Class Method Details

.cleanup_obsolete_files(_context, expected_targets) ⇒ Object



373
374
375
376
377
378
379
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
411
412
413
414
415
416
417
# File 'lib/docopslab/dev/sync_ops.rb', line 373

def cleanup_obsolete_files _context, expected_targets
  cleanup_count = 0
  obsolete_files = []
  # Common vendor paths to check for obsolete files
  vendor_patterns = [
    File.join(CONFIG_VENDOR_DIR, '**', '*')
  ]
  vendor_patterns.each do |pattern|
    Dir.glob(pattern).each do |file_path|
      next if File.directory?(file_path)
      next if file_path.include?('/.git/') # Skip git files

      # Check if this file is expected based on manifest
      obsolete_files << file_path unless expected_targets.include?(file_path)
    end
  end
  return 0 if obsolete_files.empty?

  puts "\n๐Ÿงน Found #{obsolete_files.length} potentially obsolete vendor files:"
  obsolete_files.sort.each do |file|
    puts "  ๐Ÿ“„ #{file}"
  end
  print "\nClean up these obsolete files? [y/N]: "
  response = $stdin.gets.chomp.downcase
  if %w[y yes].include?(response)
    obsolete_files.each do |file|
      File.delete(file)
      puts "  ๐Ÿ—‘๏ธ  Removed: #{file}"
      cleanup_count += 1
    rescue StandardError => e
      puts "  โŒ Failed to remove #{file}: #{e.message}"
    end
    # Clean up empty directories
    vendor_patterns.each do |pattern|
      base_dir = pattern.split('/**').first
      next unless Dir.exist?(base_dir)

      cleanup_empty_directories(base_dir)
    end
  else
    puts 'โญ๏ธ  Skipping cleanup of obsolete files'
  end

  cleanup_count
end

.install_vale_styles(context) ⇒ Object



12
13
14
15
16
17
# File 'lib/docopslab/dev/sync_ops.rb', line 12

def install_vale_styles context
  return unless File.exist?(CONFIG_PATHS[:vale]) && context.tool_available?('vale')

  puts "๐Ÿ“š Syncing Vale styles using Packages key in #{CONFIG_PATHS[:vale]} (local and remote packages)"
  context.run_with_fallback('vale', "vale --config=#{CONFIG_PATHS[:vale]} sync")
end

.sync_config_files(context, tool_filter: :all, offline: false) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/docopslab/dev/sync_ops.rb', line 201

def sync_config_files context, tool_filter: :all, offline: false
  # Validate tool filter parameter
  unless tool_filter == :all || tool_filter.is_a?(String) || tool_filter.is_a?(Symbol)
    puts "โŒ Invalid tool filter: #{tool_filter}. Must be :all, tool name string, or tool symbol"
    return false
  end

  puts offline ? '๐Ÿ”„ Syncing configs (offline mode)...' : '๐Ÿ”„ Syncing configuration files...'

  # Check for docopslab-dev.yml manifest
  unless File.exist?(MANIFEST_PATH)
    puts "โ„น๏ธ  No #{MANIFEST_PATH} found"
    puts "โŒ Legacy sync mode not implemented. Run 'rake labdev:init' to create manifest."
    return false
  end

  # Parse manifest
  begin
    manifest = YAML.load_file(MANIFEST_PATH)
  rescue StandardError => e
    puts "โŒ Failed to parse #{MANIFEST_PATH}: #{e.message}"
    return false
  end

  unless Dir.exist?(CONFIG_PACKS_SOURCE_DIR)
    puts 'โŒ No assets/config-packs directory found in gem'
    return false
  end

  # Get available tools from manifest for validation
  available_tools = manifest['tools']&.map { |t| t['tool'] } || []

  # Validate specific tool filter
  if tool_filter != :all
    tool_filter_str = tool_filter.to_s
    unless available_tools.include?(tool_filter_str)
      puts "โŒ Tool '#{tool_filter_str}' not found in manifest. Available tools: #{available_tools.join(', ')}"
      return false
    end
    puts "๐Ÿ“ฆ Filtering to tool: #{tool_filter_str}"
  end

  synced_count = 0
  expected_targets = Set.new

  # Process each tool from manifest
  manifest['tools']&.each do |tool_entry|
    tool_name = tool_entry['tool']
    enabled = tool_entry.fetch('enabled', true)

    # Skip if filtering to specific tool and this isn't it
    next if tool_filter != :all && tool_name != tool_filter.to_s

    unless enabled
      puts "โญ๏ธ  Skipping #{tool_name} (disabled in manifest)"
      next
    end

    puts "๐Ÿ“ฆ Processing #{tool_name} config pack..."

    # Process each file mapping
    tool_entry['files']&.each do |file_config|
      source_rel = file_config['source']
      target_path = file_config['target']
      synced = file_config.fetch('synced', true)
      file_enabled = file_config.fetch('enabled', true)

      unless file_enabled
        puts "  โญ๏ธ  Skipping #{source_rel} (disabled)"
        next
      end

      source_path = File.join(CONFIG_PACKS_SOURCE_DIR, source_rel)

      unless File.exist?(source_path)
        puts "  โŒ Source not found: #{source_rel}"
        next
      end

      # Add to expected targets for cleanup, regardless of synced status
      expected_targets.add(target_path)

      # Handle directory syncing (source ends with /)
      if source_rel.end_with?('/')
        sync_result = sync_directory(
          source_path, target_path, synced: synced, expected_targets: expected_targets)
        synced_count += sync_result
      else
        # Create destination directory if needed
        FileUtils.mkdir_p(File.dirname(target_path))

        # Determine if we should copy the file
        file_existed_before_copy = File.exist?(target_path)

        should_copy = if synced # If synced: true, copy if missing or different
                        !file_existed_before_copy || File.read(source_path) != File.read(target_path)
                      else # If synced: false, copy only if missing
                        !file_existed_before_copy
                      end

        if should_copy
          FileUtils.cp(source_path, target_path)
          message = if synced
                      "๐Ÿ“ Synced: #{target_path} (auto-sync)"
                    elsif !file_existed_before_copy
                      "โœ… Created: #{target_path}"
                    else
                      "๐Ÿ“ Synced: #{target_path}" # Fallback
                    end
          puts "  #{message}"
          synced_count += 1
        else
          puts "  โœ… Up to date: #{target_path}"
        end
      end
    end
  end

  cleanup_count = cleanup_obsolete_files(context, expected_targets)

  # Generate runtime configs after syncing base configs
  puts '๐Ÿ”ง Generating runtime configs...'
  generated_count = 0
  generated_count += 1 if context.generate_vale_config
  generated_count += 1 if context.generate_htmlproofer_config

  puts '  โœ… All runtime configs up to date' if generated_count.zero?

  total_changes = synced_count + cleanup_count + generated_count
  if total_changes.positive?
    puts "โœ… Config sync complete; #{synced_count} files updated, " \
         "#{cleanup_count} files cleaned up, #{generated_count} configs generated"
  else
    puts 'โœ… All configs up to date'
  end

  true
end

.sync_directory(source_dir, target_dir, synced: false, expected_targets: nil) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/docopslab/dev/sync_ops.rb', line 340

def sync_directory source_dir, target_dir, synced: false, expected_targets: nil
  synced_count = 0

  FileUtils.mkdir_p(target_dir)

  # Sync all files in the source directory
  Dir.glob("#{source_dir}/**/*", File::FNM_DOTMATCH).each do |source_file|
    next if File.directory?(source_file)
    next if File.basename(source_file).start_with?('.') && ['.', '..'].include?(File.basename(source_file))

    # Calculate relative path within source directory
    rel_path = Pathname.new(source_file).relative_path_from(Pathname.new(source_dir))
    target_file = File.join(target_dir, rel_path)

    # Track expected files for cleanup detection
    expected_targets&.add(target_file) if synced

    # Create target subdirectory if needed
    FileUtils.mkdir_p(File.dirname(target_file))

    # Copy file if it doesn't exist or is different
    if !File.exist?(target_file) || File.read(source_file) != File.read(target_file)
      FileUtils.cp(source_file, target_file)
      puts "  ๐Ÿ“ Synced: #{target_file}#{' (auto-sync)' if synced}"
      synced_count += 1
    else
      puts "  โœ… Up to date: #{target_file}"
    end
  end

  synced_count
end

.sync_docs(context, force: false) ⇒ Object



88
89
90
91
92
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
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
# File 'lib/docopslab/dev/sync_ops.rb', line 88

def sync_docs context, force: false
  manifest = context.load_manifest
  return false unless manifest

  docs_entries = manifest['docs']
  return false unless docs_entries.is_a?(Array)

  puts '๐Ÿ“š Syncing documentation files...'

  synced_count = 0
  skipped_count = 0
  sources_checked = []
  excluded_files = Set.new

  # First pass: collect all explicitly excluded files (synced: false)
  docs_entries.each do |entry|
    source_pattern = entry['source']
    synced = entry.fetch('synced', false)

    next unless source_pattern
    next if synced # Only collect exclusions

    # Resolve source file path
    if source_pattern.include?('*')
      # Glob pattern for exclusions
      source_glob = File.join(GEM_ROOT, source_pattern)
      Dir.glob(source_glob).each do |source_file|
        excluded_files.add(source_file) if File.file?(source_file)
      end
    else
      # Single file exclusion
      source_file = File.join(GEM_ROOT, source_pattern)
      excluded_files.add(source_file) if File.exist?(source_file)
    end
  end

  # rubocop:disable Style/CombinableLoops
  # Second pass: process inclusions, respecting exclusions
  # These loops cannot be combined as they implement different phases of a two-pass algorithm
  docs_entries.each do |entry|
    source_pattern = entry['source']
    target_path = entry['target']
    synced = entry.fetch('synced', false)

    next unless source_pattern && target_path
    next unless synced # Only process inclusions

    # Check if source is a glob pattern
    if source_pattern.include?('*')
      # Glob pattern; copy matching files
      source_glob = File.join(GEM_ROOT, source_pattern)
      matching_files = Dir.glob(source_glob)

      if matching_files.empty?
        puts "  โš ๏ธ  No files matched pattern: #{source_pattern}"
        next
      end

      matching_files.each do |source_file|
        next unless File.file?(source_file)
        next if sources_checked.include?(source_file)

        # Skip if explicitly excluded
        if excluded_files.include?(source_file)
          puts "  โญ๏ธ  Skipped #{File.basename(source_file)} (explicitly excluded)"
          next
        end

        # Determine target file path
        filename = File.basename(source_file)
        target_file = File.join(target_path, filename)

        sources_checked << source_file
        result = copy_doc_file(source_file, target_file, synced: synced, force: force)
        synced_count += 1 if result == :copied
        skipped_count += 1 if result == :skipped
      end
    else # Single file
      source_file = File.join(GEM_ROOT, source_pattern)

      unless File.exist?(source_file)
        puts "  โŒ Source file not found: #{source_file}"
        puts "     Run 'bundle exec rake gemdo:gen_agent_docs' in DocOps/lab to generate docs"
        next
      end

      next if sources_checked.include?(source_file)

      # Skip if explicitly excluded (shouldn't happen for inclusions, but safety check)
      if excluded_files.include?(source_file)
        puts "  โญ๏ธ  Skipped #{File.basename(source_file)} (explicitly excluded)"
        next
      end

      sources_checked << source_file

      result = copy_doc_file(source_file, target_path, synced: synced, force: force)
      synced_count += 1 if result == :copied
      skipped_count += 1 if result == :skipped
    end
  end
  # rubocop:enable Style/CombinableLoops

  puts "โœ… Synced #{synced_count} doc files" if synced_count.positive?
  puts "โ„น๏ธ  Skipped #{skipped_count} existing files (use --force to overwrite)" if skipped_count.positive?

  synced_count.positive? || skipped_count.positive?
end

.sync_scripts(_context) ⇒ Object



197
198
199
# File 'lib/docopslab/dev/sync_ops.rb', line 197

def sync_scripts _context
  ScriptManager.sync_scripts
end

.sync_vale_styles(context, local: false) ⇒ Object



19
20
21
22
23
24
25
26
27
28
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
79
80
81
82
83
84
85
86
# File 'lib/docopslab/dev/sync_ops.rb', line 19

def sync_vale_styles context, local: false
  puts '๐Ÿ“š Syncing Vale styles...'

  styles_source_root = if context.lab_dev_mode?
                         # Running inside lab monorepo
                         'gems/docopslab-dev/assets/config-packs/vale'
                       else
                         # Running from consumer project with path dependency
                         File.join(GEM_ROOT, 'assets', 'config-packs', 'vale')
                       end
  styles_dest_root = '.config/.vendor/vale/styles'
  FileUtils.mkdir_p(styles_dest_root)

  # Get the list of local styles from tools.yml
  begin
    tools_yml_path = if context.lab_dev_mode?
                       'gems/docopslab-dev/specs/data/tools.yml'
                     else
                       File.join(GEM_ROOT, 'specs', 'data', 'tools.yml')
                     end

    style_paths_array = YAML.load_file(tools_yml_path)
                            .find { |t| t['slug'] == 'vale' }['packaging']['packages']

    synced_styles = 0
    style_paths_array.each do |package|
      vale_name = package['target']
      src_name = package['source']
      source_style_dir = File.join(styles_source_root, src_name)
      dest_style_dir = File.join(styles_dest_root, vale_name)

      next unless File.directory?(source_style_dir)

      # Copy style directory
      FileUtils.rm_rf(dest_style_dir)
      FileUtils.cp_r(source_style_dir, dest_style_dir)
      puts "  โœ“ Synced custom style: #{vale_name}"
      synced_styles += 1
    end

    # copy style scripts directory
    scripts_source = File.join(styles_source_root, 'config', 'scripts')
    scripts_dest = File.join(styles_dest_root, 'config', 'scripts')
    if File.directory?(scripts_source)
      FileUtils.rm_rf(scripts_dest)
      FileUtils.mkdir_p(File.dirname(scripts_dest))
      FileUtils.cp_r(scripts_source, scripts_dest)
      puts '  โœ“ Synced style scripts directory'
    else
      puts "  โš ๏ธ  No style scripts directory found at #{scripts_source}; skipping"
    end

    puts "  โœ… Synced #{synced_styles} custom Vale style(s)" if synced_styles.positive?
  rescue StandardError => e
    puts "  โš ๏ธ  Error syncing local Vale styles: #{e.message}"
    false
  end

  # If not local-only, also run Vale sync for remote styles
  unless local
    puts '๐Ÿ“ฆ Syncing remote Vale packages...'
    vale_config = CONFIG_PATHS[:vale]
    context.generate_vale_config unless File.exist?(vale_config)
    context.run_with_fallback('vale', "vale --config=#{vale_config} sync")
  end

  true
end