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.



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

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



16
17
18
# File 'lib/expressir/commands/package.rb', line 16

def options
  @options
end

Instance Method Details

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



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

def build(root_schema = nil, output = nil)
  schema_files = if options[:manifest]
                   # Manifest-based mode
                   unless File.exist?(options[:manifest])
                     raise Expressir::ManifestNotFoundError.new(options[:manifest])
                   end

                   # Override output if not provided
                   output ||= root_schema
                   unless output
                     raise Expressir::MissingRequiredArgumentError.new(
                       "OUTPUT path is required",
                       usage_hint: "expressir package build --manifest MANIFEST.yaml OUTPUT.ler",
                     )
                   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..."

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

                     # Check file existence
                     file_errors = validator.validate_file_existence
                     unless file_errors.empty?
                       raise Expressir::ManifestValidationError.new(
                         "Manifest validation failed",
                         errors: file_errors.map { |e| e[:message] },
                       )
                     end

                     # Check referential integrity
                     reference_errors = validator.validate_referential_integrity
                     unless reference_errors.empty?
                       raise Expressir::ReferentialIntegrityError.new(
                         reference_errors,
                         message: "Manifest has unresolved dependencies",
                       )
                     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?
                     raise Expressir::ManifestValidationError.new(
                       "Manifest validation failed",
                       errors: errors,
                     )
                   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
                     raise Expressir::MissingRequiredArgumentError.new(
                       "ROOT_SCHEMA is required when not using --manifest",
                       usage_hint: "expressir package build ROOT_SCHEMA OUTPUT.ler",
                     )
                   end

                   unless output
                     raise Expressir::MissingRequiredArgumentError.new(
                       "OUTPUT path is required",
                       usage_hint: "expressir package build ROOT_SCHEMA OUTPUT.ler",
                     )
                   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?]
      raise Expressir::SchemaValidationError.new(
        "Repository validation failed",
        errors: (validation[:errors] || []).map do |e|
          if e.is_a?(Hash)
            msg = e[:message] || "Unknown error"
            type = e[:type] ? "[#{e[:type]}] " : ""
            schema = e[:schema] ? " (schema: #{e[:schema]})" : ""
            ref = e[:referenced_schema] ? " (referenced: #{e[:referenced_schema]})" : ""
            iface = e[:interface_type] ? " (interface: #{e[:interface_type]})" : ""
            "#{type}#{msg}#{schema}#{ref}#{iface}"
          else
            e.to_s
          end
        end,
      )
    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 Expressir::Error
  raise # Re-raise Expressir errors
rescue StandardError => e
  raise Expressir::PackageBuildError.new(
    "Error building package: #{e.message}",
    command_name: "package build",
  )
end

#extract(package_path) ⇒ Object



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/expressir/commands/package.rb', line 415

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

  unless options[:output]
    raise Expressir::MissingRequiredArgumentError.new(
      "output directory is required",
      usage_hint: "expressir package extract PACKAGE --output OUTPUT_DIR",
    )
  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 Expressir::Error
  raise # Re-raise Expressir errors
rescue StandardError => e
  raise Expressir::PackageExtractError.new(
    "Error extracting package: #{e.message}",
    command_name: "package extract",
  )
end

#info(package_path) ⇒ Object



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/expressir/commands/package.rb', line 307

def info(package_path)
  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 Expressir::Error
  raise # Re-raise Expressir errors
rescue StandardError => e
  raise Expressir::PackageReadError.new(
    "Error reading package info: #{e.message}",
    command_name: "package info",
  )
end

#list(package_path) ⇒ Object



483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/expressir/commands/package.rb', line 483

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 Expressir::Error
  raise # Re-raise Expressir errors
rescue StandardError => e
  raise Expressir::PackageListError.new(
    "Error listing elements: #{e.message}",
    command_name: "package list",
  )
end

#search(package_path, pattern) ⇒ Object



561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# File 'lib/expressir/commands/package.rb', line 561

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 Expressir::Error
  raise # Re-raise Expressir errors
rescue StandardError => e
  raise Expressir::PackageSearchError.new(
    "Error searching: #{e.message}",
    command_name: "package search",
  )
end

#tree(package_path) ⇒ Object



636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/expressir/commands/package.rb', line 636

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 Expressir::Error
  raise # Re-raise Expressir errors
rescue StandardError => e
  raise Expressir::PackageTreeError.new(
    "Error displaying tree: #{e.message}",
    command_name: "package tree",
  )
end

#validate(package_path) ⇒ Object



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

def validate(package_path)
  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

  unless validation[:valid?]
    raise Expressir::PackageValidationError.new(
      "Package validation failed",
      errors: validation[:errors] || [],
    )
  end
rescue Expressir::Error
  raise # Re-raise Expressir errors
rescue StandardError => e
  raise Expressir::PackageValidationError.new(
    "Error validating package: #{e.message}",
    command_name: "package validate",
  )
end