Method: NA.insert_project

Defined in:
lib/na/next_action.rb

.insert_project(target, project) ⇒ NA::Project

Insert a new project into a todo file

Parameters:

  • target (String)

    Path to the todo file

  • project (String)

    Project name

Returns:



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

def insert_project(target, project)
  path = project.split(%r{[:/]})
  todo = NA::Todo.new(file_path: target)
  built = []
  last_match = nil
  final_match = nil
  new_path = []
  matches = nil
  path.each_with_index do |part, i|
    built.push(part)
    built_path = built.join(':')
    matches = todo.projects.select { |proj| proj.project =~ /^#{Regexp.escape(built_path)}/i }
    exact_match = matches.find { |proj| proj.project.casecmp(built_path).zero? }
    if exact_match
      last_match = exact_match
    else
      final_match = last_match
      new_path = path.slice(i, path.count - i)
      break
    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
      line = todo.projects.last&.last_line || 0
      content = content.split("\n").insert(line, input.join("\n")).join("\n")
    else
      split = content.split("\n")
      line = todo.projects.first&.line || 0
      before = split.slice(0, line).join("\n")
      after = split.slice(line, split.count - 0).join("\n")
      content = "#{before}\n#{input.join("\n")}\n#{after}"
    end

    new_project = NA::Project.new(path.map(&:cap_first).join(':'), indent - 1, line, line)
  else
    line = final_match.last_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