Module: GitlabInternalEventsCli::Helpers::Files

Included in:
GitlabInternalEventsCli::Helpers
Defined in:
lib/gitlab_internal_events_cli/helpers/files.rb

Constant Summary collapse

MAX_FILENAME_LENGTH =
100

Instance Method Summary collapse

Instance Method Details

#absolute_path(filepath) ⇒ Object



9
10
11
# File 'lib/gitlab_internal_events_cli/helpers/files.rb', line 9

def absolute_path(filepath)
  GitlabInternalEventsCli.configuration.absolute_path(filepath)
end

#file_saved_message(verb, filepath) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/gitlab_internal_events_cli/helpers/files.rb', line 33

def file_saved_message(verb, filepath)
  # Context/validation messages only apply to YAML definition files.
  # Other artifacts (e.g. generated Ruby class & spec files for database
  # metrics) are reported with just the success line.
  if filepath.end_with?('.yml', '.yaml')
    attributes = YAML.safe_load_file(absolute_path(filepath))

    format_prefix '    ', [
      file_saved_success_message(verb, filepath),
      file_saved_context_message(attributes),
      file_saved_validations_message(attributes)
    ].compact.join("\n")
  else
    format_prefix '    ', file_saved_success_message(verb, filepath)
  end
end

#prompt_to_save_file(filepath, content) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/gitlab_internal_events_cli/helpers/files.rb', line 13

def prompt_to_save_file(filepath, content)
  full_path = absolute_path(filepath)

  cli.say <<~TEXT.chomp
    #{format_info('Preparing to generate definition with these attributes:')}
    #{filepath}
    #{content}
  TEXT

  if File.exist?(full_path)
    cli.error("Oh no! This file already exists!\n")

    return if cli.no?(format_prompt('Overwrite file?'))

    write_to_file(filepath, content, 'update')
  elsif cli.yes?(format_prompt('Create file?'))
    write_to_file(filepath, content, 'create')
  end
end

#write_to_file(filepath, content, verb) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/gitlab_internal_events_cli/helpers/files.rb', line 50

def write_to_file(filepath, content, verb)
  full_path = absolute_path(filepath)
  dir = File.dirname(full_path)
  FileUtils.mkdir_p(dir) unless File.directory?(dir)

  File.write(full_path, content)

  file_saved_message(verb, filepath).tap do |_message|
    cli.global.reload_definitions
  end
end