#!/bin/sh
#
# Removes trailing commas from array and object declarations (certain
# browsers, such as earlier versions of IE, do not parse trailing commas
# correctly)
#
# This is a very simple (dumb) system. It does not check to ensure we're not
# replacing text inside a string, nor is it 100% certain we're in an array
# or object declaration. However, until such an implementation is needed,
# I'd like to keep it as simple (and fast) as possible. The below
# implementation is suitable for our needs.
#
#  Copyright (C) 2010, 2011, 2012, 2013, 2014 Mike Gerwitz
#
#  This file is part of GNU ease.js.
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
# #

# read from stdin
cat - \
    | sed -n '
        # copy first line to hold buffer
        1h

        # if not the first line, append to hold buffer
        1!H

        # if last line, process
        $ {
            # pull from hold and perform replacement
            g
            s/,\(\s*\(\/\/[^]}\n]\+\s*\)\?[]}]\)/\1/g

            # print result
            p
        }
    '

exit 0

