Class: Expressir::Commands::Manifest

Inherits:
Thor
  • Object
show all
Includes:
Thor::Actions
Defined in:
lib/expressir/commands/manifest.rb

Overview

Manifest management CLI commands Handles schema manifest creation and validation

Instance Method Summary collapse

Instance Method Details

#create(*root_schemas) ⇒ Object



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
87
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
# File 'lib/expressir/commands/manifest.rb', line 51

def create(*root_schemas)
  # Convert string keys to symbols for compatibility with tests
  opts = options.transform_keys(&:to_sym)

  if root_schemas.empty?
    say "Error: At least one root schema is required", :red
    say "Usage: expressir manifest create ROOT_SCHEMA [MORE_SCHEMAS...] -o OUTPUT.yaml",
        :yellow
    raise Thor::Error, "At least one root schema is required"
  end

  # Verify root schemas exist
  root_schemas.each do |schema|
    unless File.exist?(schema)
      say "Error: Root schema not found: #{schema}", :red
      raise Thor::Error, "Root schema not found: #{schema}"
    end
  end

  say "Creating manifest from #{root_schemas.size} root schema(s)..." if opts[:verbose]

  # Parse base directories - now an array directly from Thor
  base_dirs = if opts[:base_dirs]
                # Thor array type accepts space-separated values in a single flag
                # or we can also split comma-separated values for backward compatibility
                opts[:base_dirs].flat_map do |dir|
                  dir.split(",")
                end.map(&:strip)
              else
                # Default to directories containing root schemas
                root_schemas.map do |s|
                  File.dirname(File.expand_path(s))
                end.uniq
              end

  if opts[:verbose]
    say "  Base directories:"
    base_dirs.each_with_index do |dir, index|
      say "    - [source #{index + 1}]: #{dir}"
    end
  end

  # Resolve dependencies
  say "Resolving dependencies..." if opts[:verbose]
  resolver = Expressir::Model::DependencyResolver.new(
    base_dirs: base_dirs,
    verbose: opts[:verbose],
  )

  resolved_paths = resolver.resolve_dependencies(root_schemas.first)

  # Create manifest using existing SchemaManifest class
  manifest = Expressir::SchemaManifest.new

  # Add resolved schemas - use actual schema name from file, not filename
  resolved_paths.each do |path|
    schema_id = extract_schema_name(path)
    manifest.schemas << Expressir::SchemaManifestEntry.new(
      id: schema_id,
      path: path,
    )
  end

  # Add unresolved schemas with empty string paths (not nil to avoid serialization issues)
  resolver.unresolved.uniq { |e| e[:schema_name] }.each do |entry|
    manifest.schemas << Expressir::SchemaManifestEntry.new(
      id: entry[:schema_name],
      path: "",
    )
  end

  # Save manifest
  FileUtils.mkdir_p(File.dirname(opts[:output]))
  File.write(opts[:output], manifest.to_yaml)

  # Use validator for consistent warnings (DRY - single source of truth)
  require_relative "../manifest/validator"
  validator = Expressir::Manifest::Validator.new(manifest, opts)
  path_warnings = validator.validate_path_completeness

  unresolved_count = path_warnings.size
  resolved_count = manifest.schemas.size - unresolved_count

  say "✓ Manifest created: #{opts[:output]}", :green
  say "  Resolved schemas: #{resolved_count}", :green

  # Warn about multiple matches
  stats = resolver.statistics
  if stats[:multiple_matches].any?
    say ""
    say "⚠ Multiple matches found (#{stats[:multiple_matches].size}):",
        :yellow
    stats[:multiple_matches].each do |match_info|
      say "  Schema '#{match_info[:schema_name]}' found in #{match_info[:matches].size} locations:",
          :yellow
      match_info[:matches].each_with_index do |m, idx|
        relative_path = m[:path].sub("#{m[:base_dir]}/", "")
        marker = idx.zero? ? "[USING]" : "       "
        say "    #{marker} [source #{m[:index] + 1}] #{relative_path}",
            :yellow
      end
    end
    say ""
    say "The first match was used for each schema.", :yellow
    say "If you need a different version, manually edit #{opts[:output]}",
        :yellow
  end

  # Warn about unresolved using validator results
  if path_warnings.any?
    say ""
    say "⚠ Unresolved schemas (#{unresolved_count}):", :yellow
    path_warnings.each { |w| say "  - #{w[:schema]}", :yellow }
    say ""
    say "Please edit #{opts[:output]} and set 'path:' for unresolved schemas",
        :yellow
    say "Then validate with: expressir manifest validate #{opts[:output]}",
        :yellow
  else
    say "  All schemas resolved successfully!", :green
  end
rescue StandardError => e
  say "Error creating manifest: #{e.message}", :red
  say e.backtrace.join("\n") if options[:verbose]
  raise Thor::Error, "Failed to create manifest: #{e.message}"
end

#resolve(manifest_path) ⇒ Object



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
# File 'lib/expressir/commands/manifest.rb', line 216

def resolve(manifest_path)
  unless File.exist?(manifest_path)
    say "Error: Manifest file not found: #{manifest_path}", :red
    raise Thor::Error, "Manifest file not found: #{manifest_path}"
  end

  say "Resolving schema paths in: #{manifest_path}..." if options[:verbose]

  # Load manifest
  manifest = Expressir::SchemaManifest.from_file(manifest_path)

  # Parse base directories - now an array directly from Thor
  resolver_options = { verbose: options[:verbose] }
  if options[:base_dirs]
    # Thor array type accepts space-separated values in a single flag
    # or we can also split comma-separated values for backward compatibility
    resolver_options[:base_dirs] = options[:base_dirs].flat_map do |dir|
      dir.split(",")
    end.map(&:strip)
    if options[:verbose]
      say "  Using base directories:"
      resolver_options[:base_dirs].each_with_index do |dir, index|
        say "    - [source #{index + 1}]: #{dir}"
      end
    end
  end

  # Create resolver and resolve paths
  require_relative "../manifest/resolver"
  resolver = Expressir::Manifest::Resolver.new(manifest, resolver_options)

  say "Attempting to resolve paths..." if options[:verbose]
  resolved_manifest = resolver.resolve_paths

  # Save resolved manifest
  FileUtils.mkdir_p(File.dirname(options[:output]))
  File.write(options[:output], resolved_manifest.to_yaml)

  # Display statistics based on RESOLVED manifest (like manifest create)
  require_relative "../manifest/validator"
  validator = Expressir::Manifest::Validator.new(resolved_manifest,
                                                 options)
  path_warnings = validator.validate_path_completeness

  unresolved_count = path_warnings.size
  resolved_count = resolved_manifest.schemas.size - unresolved_count

  say "✓ Manifest resolved: #{options[:output]}", :green
  say "  Total schemas: #{resolved_manifest.schemas.size}", :green
  say "  Resolved schemas: #{resolved_count}", :green

  # Warn about unresolved (like manifest create)
  if path_warnings.any?
    say ""
    say "⚠ Unresolved schemas (#{unresolved_count}):", :yellow
    path_warnings.each { |w| say "  - #{w[:schema]}", :yellow }
    say ""
    say "These schemas could not be found in the search directories.",
        :yellow
    say "You may need to:", :yellow
    say "  1. Add more base directories with --base-dirs", :yellow
    say "  2. Manually edit #{options[:output]} and set their paths",
        :yellow
  else
    say "  All schema paths resolved successfully!", :green
  end
rescue StandardError => e
  say "Error resolving manifest: #{e.message}", :red
  say e.backtrace.join("\n") if options[:verbose]
  raise Thor::Error, "Failed to resolve manifest: #{e.message}"
end

#validate(manifest_path) ⇒ Object



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
339
340
341
342
343
344
345
346
347
# File 'lib/expressir/commands/manifest.rb', line 311

def validate(manifest_path)
  unless File.exist?(manifest_path)
    say "Error: Manifest file not found: #{manifest_path}", :red
    raise Thor::Error, "Manifest file not found: #{manifest_path}"
  end

  # Convert string keys to symbols for compatibility with tests
  opts = options.transform_keys(&:to_sym)

  say "Validating manifest: #{manifest_path}..." if opts[:verbose]

  # Load manifest
  manifest = Expressir::SchemaManifest.from_file(manifest_path)

  # Create validator - SINGLE SOURCE OF TRUTH
  require_relative "../manifest/validator"
  validator = Expressir::Manifest::Validator.new(manifest, opts)

  # Run validations using validator (NO INLINE LOGIC)
  file_errors = validator.validate_file_existence
  path_warnings = validator.validate_path_completeness
  name_errors = validator.validate_schema_names

  reference_errors = []
  if opts[:check_references]
    say "Checking referential integrity..." if opts[:verbose]
    reference_errors = validator.validate_referential_integrity
  end

  # Display results
  display_validation_results(manifest, file_errors, path_warnings,
                             name_errors, reference_errors)
rescue StandardError => e
  say "Error validating manifest: #{e.message}", :red
  say e.backtrace.join("\n") if options && options[:verbose]
  raise Thor::Error, "Failed to validate manifest: #{e.message}"
end