cdist/cdist/conf/type/__ini_value/files/base.awk

139 lines
3.6 KiB
Awk

BEGIN {
bufindex = -1
buflen = 0
maxbuflen = 10
# no section means the start to the first section
if(section == "") {
is_curr_section = 1
found_section = 1
}
}
# controls the line buffer
function flush_buffer() {
while(buflen > 0)
_pop_line()
}
function flush_lines(n) {
while(buflen > 0 && n-- > 0)
_pop_line()
}
function push_line() {
linebuf[++bufindex] = $0
buflen++
while(buflen > maxbuflen) _pop_line()
}
function revert_line() {
# no delete, because it will be overwritten by the next line if any ..
bufindex--
buflen--
}
function lastline() {
if(buflen > 0) return linebuf[bufindex]
}
function pop_line() {
if(buflen > 0) _pop_line()
}
function _pop_line() {
_index = bufindex - (--buflen)
print linebuf[_index]
delete linebuf[_index]
}
# excepts the first character is the sign to check (string is trimmed)
function is_comment(line) {
# get character and check
line_sign = substr(line, 1, 1)
for(c in comment_signs)
if(line_sign == comment_signs[c])
return 1
# nothing found
return 0
}
function was_comment(line, comment) {
line = trim(line)
if(is_comment(line)) {
return trim(substr(line, 2)) == comment
}
}
# print everything if line found instead of processing it
# maybe just a function to loop through getline for lightest overhead
found {print; next}
# main loop (til the line was found)
!found {
line = trim($0)
# process if the line is not empty (or only contains spaces)
if(line != "") {
# check for a ini section
if(substr(line, 1, 1) == "[" && substr(line, length(line), 1) == "]") {
is_section = 1
curr_section = line
if(curr_section == section) {
found_section = 1
is_curr_section = 1
}
else {
# if nothing found, print it in the valid section before the next one
if(is_curr_section) {
if(!found) {
# set found as it is there now
found=1
# %codeblock_insert%
# print line as it would else only be populated below
print
next
}
is_curr_section = 0
}
}
}
else {
# only current session is interessting
if(is_curr_section) {
# check for a comment
is_com = is_comment(line)
if(is_com) {
line = trim(substr(line, 2))
}
# check for a delimiter and a key (must be at first position due to trimming)
if((idel = index(line, delimiter)) && (ikey = index(line, key)) == 1) {
# check there are only spaces between the key and delimiter
if(check_spaces(substr(line, ikey + length(key), idel - (length(key) + 1)))) {
found = 1
# %codeblock_found%
next
}
}
}
}
}
# works cause no next statement from above *structual programming*
push_line()
}
END {
# if not found, it's not already printed
if(!found) {
flush_buffer()
# print with section if not found
if(!found_section) {
# TODO check via buffer if a empty line is necessary
print section
# %codeblock_insert%
}
}
}