Module: Shai::Commands::Configurations

Included in:
Shai::CLI
Defined in:
lib/shai/commands/configurations.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
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
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
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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
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
449
450
451
452
453
454
455
456
457
458
# File 'lib/shai/commands/configurations.rb', line 8

def self.included(base)
  base.class_eval do
    desc "list", "List your configurations"
    def list
      require_auth!

      begin
        response = ui.spinner("Fetching configurations...") do
          api.list_configurations
        end

        configs = response.is_a?(Array) ? response : response["configurations"]

        if configs.empty?
          ui.info("You don't have any configurations yet.")
          ui.info("Run `shai init` to create one.")
        else
          ui.header("Your configurations:")
          ui.blank
          configs.each do |config|
            ui.display_configuration(config)
            ui.indent("Updated: #{time_ago(config["updated_at"])}")
            ui.blank
          end
        end
      rescue NetworkError => e
        ui.error(e.message)
        exit EXIT_NETWORK_ERROR
      end
    end

    desc "search QUERY", "Search public configurations"
    option :tag, type: :array, default: [], desc: "Filter by tags"
    def search(query = nil)
      tags = options[:tag] || []

      if query.nil? && tags.empty?
        ui.error("Please provide a search query or tags")
        exit EXIT_INVALID_INPUT
      end

      begin
        response = ui.spinner("Searching...") do
          api.search_configurations(query: query, tags: tags)
        end

        configs = response.is_a?(Array) ? response : response["configurations"]
        search_term = query ? "\"#{query}\"" : "tags: #{tags.join(", ")}"

        if configs.empty?
          ui.info("No configurations found for #{search_term}")
        else
          ui.header("Search results for #{search_term}:")
          ui.blank
          configs.each do |config|
            ui.display_configuration(config, detailed: true)
            ui.blank
          end
          ui.info("Found #{configs.length} configuration(s). Use `shai install <name>` to install.")
        end
      rescue NetworkError => e
        ui.error(e.message)
        exit EXIT_NETWORK_ERROR
      end
    end

    desc "install CONFIGURATION", "Install a configuration"
    option :force, type: :boolean, aliases: "-f", default: false, desc: "Overwrite existing files"
    option :dry_run, type: :boolean, default: false, desc: "Show what would be installed"
    option :path, type: :string, desc: "Install to specific directory"
    option :global, type: :boolean, default: false, desc: "Install to home directory (~)"
    option :local, type: :boolean, default: false, desc: "Install to current directory (./)"
    def install(configuration)
      owner, slug = parse_configuration_name(configuration)
      display_name = owner ? "#{owner}/#{slug}" : slug
      base_path = resolve_install_path
      shairc_path = File.join(base_path, ".shairc")

      registry = InstallRegistry.new

      # Check if already installed elsewhere
      if registry.has?(display_name) && !options[:force]
        existing_path = registry.path_for(display_name)
        if File.expand_path(existing_path) != base_path
          ui.error("'#{display_name}' is already installed at #{existing_path}")
          ui.info("Run `shai uninstall #{display_name}` first, or use --force to reinstall.")
          exit EXIT_INVALID_INPUT
        end
      end

      installed = InstalledProjects.new(base_path)

      # Check if this exact project is already installed
      if installed.has_project?(display_name) && !options[:force]
        ui.error("'#{display_name}' is already installed in this directory.")
        ui.info("Use --force to reinstall, or run `shai uninstall #{display_name}` first.")
        exit EXIT_INVALID_INPUT
      end

      # Check if a .shairc exists (authored config)
      if File.exist?(shairc_path) && !options[:force]
        existing_config = begin
          YAML.safe_load_file(shairc_path)
        rescue
          {}
        end
        existing_slug = existing_config["slug"]

        if existing_slug
          ui.error("This directory contains an authored configuration (.shairc).")
          ui.indent("Existing: #{existing_slug}")
          ui.blank
          ui.info("Installing here may cause conflicts with your authored config.")
          ui.info("Use --force to install anyway.")
          exit EXIT_INVALID_INPUT
        end
      end

      begin
        response = ui.spinner("Fetching #{display_name}...") do
          api.get_tree(display_name)
        end

        tree = response["tree"]

        # Security: Validate all paths before any file operations
        validate_tree_paths!(tree, base_path)

        # Get file paths from tree (excluding folders)
        new_files = tree.reject { |n| n["kind"] == "folder" }.map { |n| n["path"] }

        # Check for conflicts with existing local files
        local_conflicts = []
        tree.each do |node|
          next if node["kind"] == "folder"
          local_path = File.join(base_path, node["path"])
          local_conflicts << node["path"] if File.exist?(local_path)
        end

        # Check for conflicts with other installed projects
        project_conflicts = installed.find_conflicts(new_files)

        if options[:dry_run]
          ui.header("Would install:")
          tree.each { |node| ui.display_file_operation(:would_create, node["path"]) }

          if project_conflicts.any?
            ui.blank
            ui.warning("Would conflict with installed projects:")
            project_conflicts.each do |file, owner|
              ui.indent("#{file} (from #{owner})")
            end
          end

          ui.blank
          ui.info("No changes made (dry run)")
          return
        end

        # Handle conflicts
        if (local_conflicts.any? || project_conflicts.any?) && !options[:force]
          ui.blank

          if project_conflicts.any?
            ui.warning("The following files conflict with already installed projects:")
            project_conflicts.each do |file, owner|
              ui.indent("#{file} #{ui.dim("(from #{owner})")}")
            end
            ui.blank
          end

          other_local_conflicts = local_conflicts - project_conflicts.keys
          if other_local_conflicts.any?
            ui.warning("The following local files will be overwritten:")
            other_local_conflicts.each { |path| ui.display_file_operation(:conflict, path) }
            ui.blank
          end

          choice = ui.select("How would you like to proceed?", [
            {name: "Overwrite files (conflicting projects will be updated)", value: :yes},
            {name: "Cancel installation", value: :no},
            {name: "Show diff", value: :diff}
          ])

          if choice == :diff
            show_install_diff(tree, base_path, local_conflicts)
            return unless ui.yes?("Proceed with installation?")
          elsif choice == :no
            ui.info("Installation cancelled")
            return
          end
        end

        ui.header("Installing #{display_name}...")
        ui.blank

        # Remove conflicting files from their original projects
        if project_conflicts.any?
          affected_projects = project_conflicts.values.uniq
          affected_projects.each do |project_slug|
            files_to_remove = project_conflicts.select { |_, owner| owner == project_slug }.keys
            installed.remove_files_from_project(project_slug, files_to_remove)
          end
        end

        # Create folders and files
        created_files = []
        tree.sort_by { |n| (n["kind"] == "folder") ? 0 : 1 }.each do |node|
          local_path = File.join(base_path, node["path"])

          if node["kind"] == "folder"
            FileUtils.mkdir_p(local_path)
            ui.display_file_operation(:created, node["path"] + "/")
          else
            FileUtils.mkdir_p(File.dirname(local_path))
            File.write(local_path, node["content"])
            ui.display_file_operation(:created, node["path"])
            created_files << node["path"]
          end
        end

        # Track the installed project
        installed.add_project(display_name, created_files)
        registry.add(display_name, base_path)

        # Record the install for analytics (fire and forget)
        begin
          api.record_install(display_name)
        rescue
          # Silently ignore install tracking errors
        end

        ui.blank
        ui.success("Installed #{display_name}")

        if installed.project_count > 1
          ui.indent("#{installed.project_count} configurations now installed in this directory")
        end
      rescue NotFoundError
        ui.error("Configuration '#{display_name}' not found.")
        exit EXIT_NOT_FOUND
      rescue PermissionDeniedError
        ui.error("You don't have permission to access '#{display_name}'.")
        exit EXIT_PERMISSION_DENIED
      rescue NetworkError => e
        ui.error(e.message)
        exit EXIT_NETWORK_ERROR
      end
    end

    desc "open CONFIGURATION", "Open a configuration in the browser"
    def open(configuration)
      owner, slug = parse_configuration_name(configuration)
      display_name = owner ? "#{owner}/#{slug}" : slug
      base_url = Shai.configuration.api_url

      # Fetch configuration details to determine ownership and visibility
      begin
        config = ui.spinner("Fetching #{display_name}...") do
          api.get_configuration(display_name)
        end

        config_owner = config["owner"]
        config_slug = config["slug"]
        visibility = config["visibility"]
        current_username = credentials.authenticated? ? credentials.username : nil

        # Determine the appropriate URL based on ownership
        if current_username && config_owner == current_username
          # User owns this config - open in configuration_projects
          url = "#{base_url}/configuration_projects/#{config_slug}"
        elsif visibility == "public"
          # Public config owned by someone else - open in explore
          url = "#{base_url}/explore/#{config_owner}/#{config_slug}"
        else
          # Private config not owned by user - can't access
          ui.error("Configuration '#{display_name}' is private and you don't have access.")
          exit EXIT_PERMISSION_DENIED
        end

        ui.info("Opening #{display_name} in browser...")

        begin
          require "launchy"
          Launchy.open(url)
        rescue LoadError
          ui.warning("Could not open browser automatically.")
          ui.info("Visit: #{url}")
        rescue Launchy::Error => e
          ui.warning("Could not open browser: #{e.message}")
          ui.info("Visit: #{url}")
        end
      rescue NotFoundError
        if owner
          ui.error("Configuration '#{display_name}' not found.")
          ui.info("It may be private or doesn't exist.")
        else
          ui.error("Configuration '#{display_name}' not found in your projects.")
          ui.info("Use 'owner/slug' format to open someone else's public configuration.")
        end
        exit EXIT_NOT_FOUND
      rescue PermissionDeniedError
        ui.error("You don't have permission to access '#{display_name}'.")
        ui.info("This configuration may be private.")
        exit EXIT_PERMISSION_DENIED
      rescue NetworkError => e
        ui.error(e.message)
        exit EXIT_NETWORK_ERROR
      end
    end

    desc "uninstall [CONFIGURATION]", "Remove an installed configuration"
    option :dry_run, type: :boolean, default: false, desc: "Show what would be removed"
    option :global, type: :boolean, default: false, desc: "Uninstall from home directory (~)"
    option :local, type: :boolean, default: false, desc: "Uninstall from current directory (./)"
    def uninstall(configuration = nil)
      registry = InstallRegistry.new

      # Resolve base_path: explicit flag, registry lookup, or fallback to "."
      base_path = resolve_uninstall_path(configuration, registry)
      installed = InstalledProjects.new(base_path)

      # If no configuration specified, determine which to uninstall
      if configuration.nil?
        if installed.empty?
          ui.error("No configurations installed in #{base_path}")
          ui.info("Usage: shai uninstall <configuration>")
          exit EXIT_INVALID_INPUT
        elsif installed.project_count == 1
          configuration = installed.project_slugs.first
          ui.info("Uninstalling #{configuration}...")
        else
          ui.info("Multiple configurations installed:")
          configuration = ui.select("Which configuration do you want to uninstall?",
            installed.project_slugs.map { |s| {name: s, value: s} } + [{name: "Cancel", value: nil}])

          if configuration.nil?
            ui.info("Uninstall cancelled")
            return
          end
        end
      end

      owner, slug = parse_configuration_name(configuration)
      display_name = owner ? "#{owner}/#{slug}" : slug

      # Get files to remove - either from tracking or from remote tree
      tracked_files = installed.files_for_project(display_name)

      if tracked_files.empty?
        # Fall back to fetching from remote (for v1 migrations or manual installs)
        begin
          response = ui.spinner("Fetching #{display_name}...") do
            api.get_tree(display_name)
          end

          tree = response.is_a?(Array) ? response : response["tree"]
          validate_tree_paths!(tree, base_path)

          tracked_files = tree.reject { |n| n["kind"] == "folder" }.map { |n| n["path"] }
        rescue NotFoundError
          ui.error("Configuration '#{display_name}' not found and no tracked files.")
          exit EXIT_NOT_FOUND
        rescue PermissionDeniedError
          ui.error("You don't have permission to access '#{display_name}'.")
          exit EXIT_PERMISSION_DENIED
        rescue NetworkError => e
          ui.error(e.message)
          exit EXIT_NETWORK_ERROR
        end
      end

      # Find files that exist locally
      files_to_remove = []
      folders_to_check = Set.new

      tracked_files.each do |path|
        local_path = File.join(base_path, path)
        if File.exist?(local_path)
          files_to_remove << path
          # Track parent folders for potential removal
          dir = File.dirname(path)
          while dir != "."
            folders_to_check << dir
            dir = File.dirname(dir)
          end
        end
      end

      if files_to_remove.empty?
        ui.info("No files from '#{display_name}' found in #{base_path}")

        # Still remove from tracking if it exists
        if installed.has_project?(display_name)
          installed.remove_project(display_name)
          installed.delete! if installed.empty?
        end
        return
      end

      if options[:dry_run]
        ui.header("Would remove:")
        files_to_remove.each { |path| ui.display_file_operation(:would_create, path) }
        ui.blank
        ui.info("No changes made (dry run)")
        return
      end

      unless ui.yes?("Remove #{files_to_remove.length} files from '#{display_name}'?")
        ui.info("Uninstall cancelled")
        return
      end

      ui.header("Uninstalling #{display_name}...")
      ui.blank

      # Remove files
      files_to_remove.each do |path|
        local_path = File.join(base_path, path)
        File.delete(local_path)
        ui.display_file_operation(:deleted, path)
      end

      # Remove empty folders (deepest first)
      folders_to_check.to_a.sort.reverse_each do |path|
        local_path = File.join(base_path, path)
        if Dir.exist?(local_path) && Dir.empty?(local_path)
          Dir.rmdir(local_path)
          ui.display_file_operation(:deleted, path + "/")
        end
      end

      # Update tracking
      installed.remove_project(display_name)
      registry.remove(display_name)

      # Remove tracking file if no more projects
      if installed.empty?
        installed.delete!
        ui.display_file_operation(:deleted, InstalledProjects::FILENAME)
      end

      ui.blank
      ui.success("Uninstalled #{display_name}")

      if installed.project_count > 0
        ui.indent("#{installed.project_count} configuration(s) still installed")
      end
    end
  end
end