Skip to content

Instantly share code, notes, and snippets.

@iliajie
Last active November 3, 2021 15:36
Show Gist options
  • Save iliajie/6d55a1d900b320936014836f99a9fa6c to your computer and use it in GitHub Desktop.
Save iliajie/6d55a1d900b320936014836f99a9fa6c to your computer and use it in GitHub Desktop.
Apache config formatter
sub format_config
{
my ($data, $indent) = @_;
# Default single indent equals 4 spaces
$indent ||= 4;
$indent = " " x $indent;
my $formatter = sub {
my ($conf_lref) = @_;
# At first check if Apache blocks are ballanced
my $conf_block_opening;
my $conf_block_closing;
foreach my $l (@$conf_lref) {
# If line doesn't start with # disregard of trailing spaces
if ($l !~ /^\s*#/) {
# This is a new block, count it
if ($l =~ /(.*<[a-zA-Z].*)/) {
$conf_block_opening++;
}
# This is a new closing block, count it
if ($l =~ /(.*<\/[a-zA-Z].*)/) {
$conf_block_closing++;
}
}
}
# If the number of closing and opening blocks
# is the same then generate proper indents
if ($conf_block_opening &&
$conf_block_closing &&
$conf_block_opening == $conf_block_closing) {
my $conf_lvl = 0;
foreach my $l (@$conf_lref) {
my $indent_current = $indent x $conf_lvl;
# If line doesn't start with # disregard of trailing spaces
if ($l !~ /^\s*#/) {
# Indent up next line if a new block
if ($l =~ /(.*<[a-zA-Z].*)/) {
$conf_lvl++;
}
# Indent down next line if a closing block
if ($l =~ /(.*<\/[a-zA-Z].*)/) {
$conf_lvl--;
# Change current indent right now as it is a closing block
$indent_current = $indent x $conf_lvl;
}
}
# Replace beginning spaces with needed indent (which we could make configurable)
$l =~ s/^\s*/$indent_current/;
}
}
return $conf_lref;
};
# Do it for a file
if (-r $data) {
# Lock file
&lock_file($data);
# Open file
my $conf_lref = &read_file_lines($data);
# Format
&$formatter($conf_lref);
# Write file
&flush_file_lines($data);
# Unlock file
&unlock_file($data);
}
else {
return &$formatter($data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment