Eskil

Artifact [ce103c93d2]
Login

Artifact ce103c93d25606311b708c684582420dff1bcdc5:


##Eskil Plugin : Compare comma separated value (CSV) files

# Example file for a plugin.
# A plugin must start exactly like this one.
# The text after : is the summary you can get at the command line

# This plugin compares CSV files with some preprocessing available
# Example usage:
# eskil -plugin csv -plugininfo "-ignore {head3 head5} -key head2" -sep , \
#       examples/dir*/csv1.txt

# A plugin must define this procedure to do the job.
# side: left or right
# chi:  An input channel for reading the original file.
# cho:  An output channel for writing the processed file.
proc PreProcess {side chi cho} {
    # Pick default -sep from command line
    set opts(-sep) ","
    set i [lsearch -exact $::argv "-sep"]
    if {$i >= 0} {
        incr i
        set opts(-sep) [subst -nocommands -novariables [lindex $::argv $i]]
    }

    # Look for parameters in info string
    set opts(-ignore) ""
    set opts(-key) ""
    set opts(-header) 0
    foreach {opt val} $::Info {
        set opts($opt) $val
    }
    # If any column is given by name, assume the file starts with
    # a header line of column names
    foreach col [concat $opts(-ignore) $opts(-key)] {
        if {![string is integer $col]} {
            set opts(-header) 1
        }
    }
    if {$opts(-header)} {
        set nameLine [gets $chi]
        # Keep it first in file
        puts $cho $nameLine
        set nameList [split $nameLine $opts(-sep)]
    }

    set icol {}
    foreach col $opts(-ignore) {
        if {[string is integer $col]} {
            lappend icol $col
        } else {
            set i [lsearch $nameList $col]
            if {$i < 0} {
                return -code error "CSV Plugin Error: No such heading '$col'"
            }
            lappend icol $i
        }
    }
    set icol [lsort -integer $icol]

    set kcol {}
    foreach col $opts(-key) {
        if {[string is integer $col]} {
            lappend kcol $col
        } else {
            set i [lsearch $nameList $col]
            if {$i < 0} {
                return -code error "CSV Plugin Error: No such heading '$col'"
            }
            lappend kcol $i
        }
    }

    set olines {}
    while {[gets $chi line] >= 0} {
        set items [split $line $opts(-sep)]
        foreach i $icol {
            lset items $i ""
        }
        lappend olines $items
    }
    # Sort on keys
    foreach i [lreverse $kcol] {
        set olines [lsort -index $i $olines]
    }
    foreach items $olines {
        puts $cho [join $items $opts(-sep)]
    }

    # Signal that the file after processing should be used both
    # for comparison and for displaying.
    return 1
}