Permalink
Browse files

Add set-section tool

  • Loading branch information...
1 parent ce1b01a commit 036deca910555942098c9c4b4e6cec1b695ace9c @FooBarWidget FooBarWidget committed Nov 7, 2012
Showing with 87 additions and 0 deletions.
  1. +36 −0 README.md
  2. +51 −0 set-section
View
36 README.md
@@ -117,6 +117,42 @@ Removes the first instance of a line from the given file. Does nothing if the fi
# Same effect:
/tools/remove-line foo.log hello world
+### set-section
+
+Sets the content of a named section inside a text file while preserving all other text. Contents are read from stdin. A section looks like this:
+
+ ###### BEGIN #{section_name} ######
+ some text
+ ###### END #{section_name} ######
+
+If the section doesn't exist, then it will be created.
+
+ $ cat foo.txt
+ hello world
+ $ echo hamburger | /tools/set-section foo.txt "mcdonalds menu"
+ $ cat foo.txt
+ hello world
+ ##### BEGIN mcdonalds menu #####
+ hamburger
+ ##### END mcdonalds menu #####
+
+If the section already exists then its contents will be updated.
+
+ # Using above foo.txt.
+ $ echo french fries | /tools/set-section foo.txt "mcdonalds menu"
+ $ cat foo.txt
+ hello world
+ ##### BEGIN mcdonalds menu #####
+ french fries
+ ##### END mcdonalds menu #####
+
+If the content is empty then the section will be removed if it exists.
+
+ # Using above foo.txt
+ $ echo | /tools/set-section foo.txt "mcdonalds menu"
+ $ cat foo.txt
+ hello world
+
### truncate
Truncates all given files to 0 bytes.
View
51 set-section
@@ -0,0 +1,51 @@
+#!/usr/bin/env ruby
+# encoding: utf-8
+
+def set_section(filename, section_name, content)
+ section_begin_str = "###### BEGIN #{section_name} ######"
+ section_end_str = "###### END #{section_name} ######"
+
+ lines = File.open(filename, 'r') do |f|
+ f.binmode
+ f.read.split("\n", -1)
+ end
+
+ content.chomp!
+
+ start_index = lines.find_index(section_begin_str)
+ if !start_index
+ # Section is not in file.
+ return if content.empty?
+ lines << section_begin_str
+ lines << content
+ lines << section_end_str
+ else
+ end_index = start_index + 1
+ while end_index < lines.size && lines[end_index] != section_end_str
+ end_index += 1
+ end
+ if end_index == lines.size
+ # End not found. Pretend like the section is empty.
+ end_index = start_index
+ end
+ lines.slice!(start_index, end_index - start_index + 1)
+ if !content.empty?
+ lines.insert(start_index, section_begin_str, content, section_end_str)
+ end
+ end
+
+ File.open(filename, "w") do |f|
+ f.binmode
+ if lines.last && lines.last.empty?
+ lines.pop
+ end
+ f.write(lines.join("\n"))
+ f.write("\n")
+ end
+end
+
+if ARGV.size != 2
+ abort "Usage: set-section <FILENAME> <SECTION NAME>"
+else
+ set_section(ARGV[0], ARGV[1], STDIN.read)
+end

0 comments on commit 036deca

Please sign in to comment.