Method: NA.insert_project

Defined in:
lib/na/next_action.rb

.insert_project(target, project) ⇒ Object



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
# File 'lib/na/next_action.rb', line 165

def insert_project(target, project)
  path = project.split(%r{[:/]})
  _, _, projects = parse_actions(file_path: target)
  built = []
  last_match = nil
  final_match = nil
  new_path = []
  matches = nil
  path.each_with_index do |part, i|
    built.push(part)
    matches = projects.select { |proj| proj.project =~ /^#{built.join(':')}/i }
    if matches.count.zero?
      final_match = last_match
      new_path = path.slice(i, path.count - i)
      break
    else
      last_match = matches.last
    end
  end

  content = target.read_file
  if final_match.nil?
    indent = 0
    input = []
    new_path.each do |part|
      input.push("#{"\t" * indent}#{part.cap_first}:")
      indent += 1
    end

    if new_path.join('') =~ /Archive/i
      content = "#{content.strip}\n#{input.join("\n")}"
    else
      content = "#{input.join("\n")}\n#{content}"
    end

    new_project = NA::Project.new(path.map(&:cap_first).join(':'), indent - 1, input.count - 1, input.count - 1)
  else
    line = final_match.line + 1
    indent = final_match.indent + 1
    input = []
    new_path.each do |part|
      input.push("#{"\t" * indent}#{part.cap_first}:")
      indent += 1
    end
    content = content.split("\n").insert(line, input.join("\n")).join("\n")
    new_project = NA::Project.new(path.map(&:cap_first).join(':'), indent - 1, line + input.count - 1, line + input.count - 1)
  end

  File.open(target, 'w') do |f|
    f.puts content
  end

  new_project
end