Class: Rundoc::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/rundoc/cli.rb

Instance Method Summary collapse

Instance Method Details

#build(path:) ⇒ Object



3
4
5
6
7
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
# File 'lib/rundoc/cli.rb', line 3

def build(path:)
  @path = Pathname.new(path).expand_path
  raise "#{@path} does not exist" unless File.exist?(@path)
  raise "Expecting #{@path} to be a rundoc markdown file" unless File.file?(@path)
  @working_dir = Pathname.new(File.expand_path("../", @path))

  dot_env_path = File.expand_path("../.env", @path)
  if File.exist?(dot_env_path)
    require "dotenv"
    Dotenv.load(dot_env_path)
    ENV["AWS_ACCESS_KEY_ID"] ||= ENV["BUCKETEER_AWS_ACCESS_KEY_ID"]
    ENV["AWS_REGION"] ||= ENV["BUCKETEER_AWS_REGION"]
    ENV["AWS_SECRET_ACCESS_KEY"] ||= ENV["BUCKETEER_AWS_SECRET_ACCESS_KEY"]
    ENV["AWS_BUCKET_NAME"] ||= ENV["BUCKETEER_BUCKET_NAME"]
  end

  source_contents = File.read(@path)
  tmp_dir = @working_dir.join("tmp")

  FileUtils.remove_entry_secure(tmp_dir) if tmp_dir.exist?
  tmp_dir.mkdir
  banner = <<~HEREDOC
    <!-- STOP
      This file was generated by a rundoc script, do not modify it.

      Instead modify the rundoc script and re-run it.

      Command: #{$0} #{$*.join(" ")}
    STOP -->
  HEREDOC

  puts "== Running your docs"
  Dir.chdir(tmp_dir) do
    @output = Rundoc::Parser.new(source_contents, document_path: @path).to_md
    Rundoc.sanitize(@output)
    @output = "#{banner}\n#{@output}"
  end

  puts "== Done, run was successful"
  project_name = if Rundoc.project_root
    Rundoc.project_root.split("/").last
  else
    "project"
  end

  project_dir = @working_dir.join(project_name)

  FileUtils.remove_entry_secure(project_dir) if project_dir.exist?

  cp_root = if Rundoc.project_root
    tmp_dir.join(Rundoc.project_root, ".")
  else
    tmp_dir.join(".")
  end

  FileUtils.cp_r(cp_root, project_dir)

  FileUtils.remove_entry_secure(tmp_dir) if tmp_dir.exist?

  source_path = project_dir.join("README.md")
  puts "== Done, writing original source to #{source_path}"
  File.write(source_path, @output)

  puts "== Copying source"
  source_path = project_dir.join("copied-#{@path.to_s.split("/").last}")
  File.write(source_path, source_contents)

  Dir.chdir(project_dir) do
    Rundoc.run_after_build
  end
ensure
  Rundoc::CodeCommand::Background::ProcessSpawn.tasks.each do |name, task|
    next unless task.alive?

    puts "Warning background task is still running, cleaning up: name: #{name}"
    task.stop
  end
end