Class: Expressir::Commands::Package

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

Overview

Package management CLI commands Handles LER package creation, inspection, validation, and extraction

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options_or_args = [], *args, **kwargs) ⇒ Package

Returns a new instance of Package.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/expressir/commands/package.rb', line 20

def initialize(options_or_args = [], *args, **kwargs)
  # Check if first argument is options hash (for testing)
  if options_or_args.is_a?(Hash) && args.empty? && kwargs.empty?
    # Direct options passed for testing - don't initialize Thor
    @options = options_or_args
  else
    # Normal Thor initialization
    super
    @options ||= {}
  end
end

Instance Attribute Details

#optionsObject

Allow options to be set for testing



18
19
20
# File 'lib/expressir/commands/package.rb', line 18

def options
  @options
end

Instance Method Details

#build(root_schema = nil, output = nil) ⇒ Object



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
196
197
198
199
200
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
# File 'lib/expressir/commands/package.rb', line 96

def build(root_schema = nil, output = nil)
  require_relative "../model/dependency_resolver"
  require_relative "../model/repository"
  require_relative "../schema_manifest"

  schema_files = if options[:manifest]
                   # Manifest-based mode
                   unless File.exist?(options[:manifest])
                     say "Error: Manifest file not found: #{options[:manifest]}",
                         :red
                     exit 1
                   end

                   # Override output if not provided
                   output ||= root_schema
                   unless output
                     say "Error: OUTPUT path is required", :red
                     say "Usage: expressir package build --manifest MANIFEST.yaml OUTPUT.ler",
                         :yellow
                     exit 1
                   end

                   # Build repository
                   say "Building LER package from manifest #{options[:manifest]}..." if options[:verbose]

                   # Load manifest for verification and data extraction
                   manifest = Expressir::SchemaManifest.from_file(options[:manifest])
                   manifest_data = YAML.load_file(options[:manifest])
                   manifest_dir = File.dirname(File.expand_path(options[:manifest]))

                   # Verify manifest unless --skip-verify is used
                   if options[:skip_verify]
                     say "⚠ Warning: Skipping manifest verification",
                         :yellow
                     say "  This set of EXPRESS schemas may not be fully internally consistent.",
                         :yellow
                     say ""
                   else
                     say "Verifying manifest integrity..."
                     require_relative "../manifest/validator"

                     validator = Expressir::Manifest::Validator.new(
                       manifest, options.merge(verbose: true)
                     )

                     # Check file existence
                     file_errors = validator.validate_file_existence
                     unless file_errors.empty?
                       say "✗ Manifest validation failed", :red
                       say ""
                       file_errors.each do |e|
                         say "  - #{e[:message]}", :red
                       end
                       exit 1
                     end

                     # Check referential integrity
                     reference_errors = validator.validate_referential_integrity
                     unless reference_errors.empty?
                       say "✗ Manifest has unresolved dependencies", :red
                       say ""
                       say "The following schema references cannot be resolved:",
                           :red
                       reference_errors.each do |e|
                         say "  - #{e[:message]}", :red
                       end
                       say ""
                       say "This package may be incomplete or inconsistent.",
                           :red
                       say "To build anyway, use: --skip-verify", :yellow
                       exit 1
                     end

                     say "✓ Manifest verified", :green
                   end

                   # Validate and collect paths
                   errors = []
                   warnings = []
                   paths = []

                   manifest_data["schemas"].each do |schema_id, schema_data|
                     schema_path = schema_data["path"]

                     if schema_path.nil? || schema_path.empty?
                       warnings << "Schema '#{schema_id}' has no path specified"
                       next
                     end

                     # Expand relative paths relative to manifest directory
                     full_path = if Pathname.new(schema_path).absolute?
                                   schema_path
                                 else
                                   File.expand_path(schema_path,
                                                    manifest_dir)
                                 end

                     unless File.exist?(full_path)
                       errors << "Schema file not found: #{full_path} (#{schema_id})"
                       next
                     end

                     paths << full_path
                   end

                   unless errors.empty?
                     say "Error: Manifest validation failed", :red
                     errors.each { |e| say "  - #{e}", :red }
                     exit 1
                   end

                   if options[:verbose] && warnings.any?
                     say "Warnings:"
                     warnings.each { |w| say "  - #{w}", :yellow }
                   end

                   say "  Using #{paths.size} schema(s) from manifest" if options[:verbose]
                   paths
                 else
                   # Auto-resolution mode
                   unless root_schema
                     say "Error: ROOT_SCHEMA is required when not using --manifest",
                         :red
                     say "Usage: expressir package build ROOT_SCHEMA OUTPUT.ler",
                         :yellow
                     exit 1
                   end

                   unless output
                     say "Error: OUTPUT path is required", :red
                     say "Usage: expressir package build ROOT_SCHEMA OUTPUT.ler",
                         :yellow
                     exit 1
                   end

                   say "Building LER package from #{root_schema}..." if options[:verbose]

                   # Resolve dependencies
                   say "Resolving dependencies..." if options[:verbose]
                   base_dirs = if options[:base_dirs]
                                 options[:base_dirs].split(",").map(&:strip)
                               else
                                 # Default to the directory containing the root schema
                                 [File.dirname(File.expand_path(root_schema))]
                               end

                   if options[:verbose] && base_dirs.size == 1
                     say "  Using base directory: #{base_dirs.first}"
                     say "  Tip: Use --base-dirs to specify additional search paths for dependencies"
                   end

                   resolver = Expressir::Model::DependencyResolver.new(
                     base_dirs: base_dirs,
                     verbose: options[:verbose],
                   )
                   resolved = resolver.resolve_dependencies(root_schema)
                   say "  Found #{resolved.size} schema(s)" if options[:verbose]
                   resolved
                 end

  # Build repository
  say "Building repository..." if options[:verbose]
  repo = Expressir::Model::Repository.from_files(schema_files)

  # Validate if requested
  # When using --skip-verify, skip validation unless explicitly requested with --validate
  should_validate = if options[:manifest] && options[:skip_verify]
                      # Check if --validate was explicitly passed
                      # Thor doesn't have a way to check if option was set by user vs default
                      # So we check if --no-validate was explicitly disabled
                      false
                    else
                      options[:validate]
                    end

  if should_validate
    say "Validating repository..." if options[:verbose]
    validation = repo.validate
    unless validation[:valid?]
      say "✗ Repository validation failed", :red
      say ""
      errors = validation[:errors] || []
      say "Validation errors (#{errors.size}):", :red
      errors.each_with_index do |e, i|
        error_msg = if e.is_a?(Hash)
                      # Format hash errors properly
                      msg = e[:message] || "Unknown error"
                      type = e[:type] ? "[#{e[:type]}] " : ""
                      "#{type}#{msg}"
                    else
                      # Fallback for string errors
                      e.to_s
                    end
        say "  #{i + 1}. #{error_msg}", :red
        if e.is_a?(Hash) && e[:schema]
          say "     Schema: #{e[:schema]}",
              :red
        end
        if e.is_a?(Hash) && e[:referenced_schema]
          say "     Referenced: #{e[:referenced_schema]}",
              :red
        end
        if e.is_a?(Hash) && e[:interface_type]
          say "     Interface: #{e[:interface_type]}",
              :red
        end
      end
      exit 1
    end
    say "  ✓ Validation passed" if options[:verbose]
  end

  # Build package
  say "Creating package..." if options[:verbose]
  repo.export_to_package(output, build_package_options)

  say "✓ Package created: #{output}", :green
  say "  Schemas: #{repo.schemas.size}", :green if options[:verbose]
rescue StandardError => e
  say "Error building package: #{e.message}", :red
  say e.backtrace.join("\n") if options[:verbose]
  exit 1
end

#extract(package_path) ⇒ Object



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/expressir/commands/package.rb', line 437

def extract(package_path)
  require "zip"
  require "fileutils"

  unless options[:output]
    say "Error: output directory is required", :red
    say "Usage: expressir package extract PACKAGE --output OUTPUT_DIR",
        :yellow
    exit 1
  end

  output_dir = options[:output]
  FileUtils.mkdir_p(output_dir)

  Zip::File.open(package_path) do |zip|
    zip.each do |entry|
      dest_path = File.join(output_dir, entry.name)
      FileUtils.mkdir_p(File.dirname(dest_path))
      entry.extract(dest_path) unless File.exist?(dest_path)
    end
  end

  say "✓ Package extracted to: #{output_dir}", :green
  say "  Files extracted: #{Dir.glob(File.join(output_dir, '**', '*')).select do |f|
    File.file?(f)
  end.size}", :green
rescue StandardError => e
  say "Error extracting package: #{e.message}", :red
  exit 1
end

#info(package_path) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/expressir/commands/package.rb', line 337

def info(package_path)
  require_relative "../model/repository"
  require_relative "../package/reader"

  repo = load_package(package_path)
   = (package_path)

  case options[:format]
  when "json"
    output_json_info(, repo)
  when "yaml"
    output_yaml_info(, repo)
  else
    output_text_info(, repo)
  end
rescue StandardError => e
  say "Error reading package info: #{e.message}", :red
  exit 1
end

#list(package_path) ⇒ Object



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

def list(package_path)
  repo = load_package(package_path)
  search_engine = Expressir::Model::SearchEngine.new(repo)

  results = search_engine.list(
    type: options[:type],
    schema: options[:schema],
    category: options[:category],
  )

  if options[:count_only]
    say results.size.to_s
    return
  end

  case options[:format]
  when "json"
    say results.to_json
  when "yaml"
    say results.to_yaml
  else
    output_text_list(results, options[:type], options[:schema],
                     options[:category])
  end
rescue StandardError => e
  say "Error listing elements: #{e.message}", :red
  exit 1
end

#search(package_path, pattern) ⇒ Object



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

def search(package_path, pattern)
  repo = load_package(package_path)
  search_engine = Expressir::Model::SearchEngine.new(repo)

  results = search_engine.search(
    pattern: pattern,
    type: options[:type],
    schema: options[:schema],
    category: options[:category],
    case_sensitive: options[:case_sensitive],
    regex: options[:regex],
    exact: options[:exact],
  )

  # Apply limit if specified
  results = results.take(options[:limit]) if options[:limit]

  if options[:count_only]
    say results.size.to_s
    return
  end

  case options[:format]
  when "json"
    say results.to_json
  when "yaml"
    say results.to_yaml
  else
    output_text_search_results(results, pattern)
  end
rescue StandardError => e
  say "Error searching: #{e.message}", :red
  exit 1
end

#tree(package_path) ⇒ Object



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

def tree(package_path)
  require "paint"

  repo = load_package(package_path)

  # Filter schemas if requested
  schemas = if options[:schema]
              (repo.schemas || []).select { |s| s.id == options[:schema] }
            else
              repo.schemas || []
            end

  if schemas.empty?
    say "No schemas found", :yellow
    return
  end

  # Display package name
  package_name = File.basename(package_path)
  say colorize(package_name, :bold)

  # Display tree
  schemas.each_with_index do |schema, idx|
    is_last_schema = idx == schemas.size - 1
    display_schema_tree(schema, is_last_schema, "", 1)
  end
rescue StandardError => e
  say "Error displaying tree: #{e.message}", :red
  exit 1
end

#validate(package_path) ⇒ Object



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/expressir/commands/package.rb', line 398

def validate(package_path)
  require_relative "../model/repository"

  repo = load_package(package_path)
  validation = repo.validate(
    strict: options[:strict],
  )

  case options[:format]
  when "json"
    output_json_validation(validation)
  when "yaml"
    output_yaml_validation(validation)
  else
    output_text_validation(validation)
  end

  exit 1 unless validation[:valid?]
rescue StandardError => e
  say "Error validating package: #{e.message}", :red
  exit 1
end