#!/bin/sh
# restart -*-Tcl-*- \
exec tclsh $0 $@ 

# showhist
#
# Display an emake history file in a more human-readable format.
#
# Copyright (c) 2003-2026 Electric Cloud, Inc.
# All rights reserved.

package require cmdline

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

set PARAMS {
    {p "Show prereq (autodep) dependencies, instead of serial deps."}
    {d "Show performance debugging information"}
}

array set RESERVED {
    -1 PARSE
    -2 END
    -3 REMAKE
    -4 FOLLOW
    -5 INVALID
}
set INVALID -5

# ----------------------------------------------------------------------------
# Globals
# ----------------------------------------------------------------------------

set gMakes {};                  # make signature table (list of dir names)
set gJobs {};                   # job signature table (list of target names)
set gPrereqs {};                # prereqs table (list of file names)
set gMode SERIAL;               # by default, show serial dependencies; use
                                # -p to show prereq deps

# ----------------------------------------------------------------------------
# next
#
#     Read the next integer from a list.
#
# Arguments
#
#     numList    - list of integers
#     outPos     - (in/out) name of Tcl variable containing current position,
#                  updated after call
# ----------------------------------------------------------------------------

proc next {numList outPos} {
    upvar $outPos pos
    set value [lindex $numList $pos]
    incr pos
    return $value
}

# ----------------------------------------------------------------------------
# getPath
#
#     Decode the next job path from a history dependency line. We are given
#     a list of integers representing the line, and the index at which
#     to begin reading. A history path is encoded like this:
# 
#          <numElements> <makeId> <jobId> ... 
#
#     The returned path has the form:
#
#          "<dir1> <target1> ... <dirN> <targetN>"
#
# Arguments
#
#     depLine     - list containing encoded dep line
#     outPos      - (in/out) name of Tcl variable containing current position,
#                   updated after call
# ----------------------------------------------------------------------------

proc getPath {depLine outPos} {
    global gMake gJobs gReserved
    upvar $outPos pos
    set path {}

    # First read the number of elements.

    set numElement [next $depLine pos]

    # Read pairs of elements.
    set sep {}
    for {set i 0} {$i < $numElement} {incr i 2} {

        # Get make signature  and lookup in gMake table append to path.

        set make [next $depLine pos]

        # Valid?

        if {$make < 0 || $make > [llength $gMake]} {

            # Invalid make - complain but don't die.

            puts stderr "*** WARNING: invalid make signature $make in path 
                         {$depLine}"
            append path " INVALID-MAKE=\"$make\""
        }

        append path $sep "([lindex $gMake $make])"
        set sep " "
        # Get job signature.

        set job [next $depLine pos]

        # Valid?

        if {$job <= $::INVALID || $job >= [llength $gJobs]} {

            # Invalid job - complain but don't die.

            puts stderr "*** WARNING: invalid job signature $job in path 
                        {$depLine}"
            append path " INVALID-JOB=\"$job\""

        } elseif {$job >= 0} {
            
            # Yes - look up job signature in gJobs table, append to path.

            append path " ([lindex $gJobs $job])"
        } else {

            # Negative job id, use reserved name.

            append path " $::RESERVED($job)"
        }
    }
    return $path
}

# ----------------------------------------------------------------------------
# main
# ----------------------------------------------------------------------------

proc main {} {
    global gJobs gMake argv opt

    # Parse command line options.

    if { [catch {cmdline::typedGetoptions argv $::PARAMS \
                     "\[options\] \[<args>\]\noptions:"} result] } { 
        puts stderr $argv
        puts stderr $result
        exit 1
    }
    array set opt $result

    # Dump prereq deps if '-p' given.

    if {[info exists opt(p)]} {
        set ::gMode PREREQ
    }

    # Open input file, bail if we can't.

    if {[llength $argv] > 0} {
        set historyFile [lindex $argv 0]
        if {[catch {open $historyFile r} f]} {
            puts stderr "showhist: error opening \"$historyFile\": $f"
            exit 1
        }
    } else {
        set f stdin
    }

    set start [clock clicks -milliseconds]
    fconfigure $f -buffering full -buffersize 1000000
    if {([gets $f line] == -1) || ![string match "EMAKEDATA*" $line]} {
        puts "error reading history file, bad header: $line"
    }
    
    # Skip leading comments and whitespace

    while {([gets $f line] != -1) && (([string index $line 0] == "\#")
                                      || ([string trim $line] == ""))} { }

    # Read make table.

    gets $f line
    while {$line != ""} {
        lappend gMake [string trim $line]
        if {[gets $f line] == -1} {
            break
        }
    }
    
    # Read job table.

    gets $f line
    while {[gets $f line] != -1} {
        if {$line == ""} {
            break
        }
        lappend gJobs [string trim $line]
    }

    # Read the serial dependency table.

    gets $f line
    while {[gets $f line] != -1} {

        # Stop at blank lines.

        if {$line == ""} {
            break
        }

        if { $::gMode != "SERIAL" } {
            continue
        }

        # Read the dependency line as a list of numbers.

        set dep $line
        set pos 0

        # Pull out the writer path.

        set writer [getPath $dep pos]

        # Get number of readers.

        set numReaders [next $dep pos]

        # Pull out each reader, save in array with list of writers.

        for {set r 0} {$r < $numReaders} {incr r} {
            set reader [getPath $dep pos]
            lappend readers($reader) $writer
        }
    }

    # Read prereq files table, if we're dumping prereqs.

    if { $::gMode == "PREREQ" } {
        gets $f line
        while {[gets $f line] != -1} {
            if {$line == ""} {
                break
            }
            lappend ::gPrereqs [string trim $line]
        }
    
        # Read the prereq dependency table.

        gets $f line
        while {[gets $f line] != -1} {

            # Stop at blank lines.

            if {$line == ""} {
                break
            }

            # Read the dependency line as a list of numbers.

            set dep $line
            set pos 0

            # Pull out the reader job's path.

            set reader [getPath $dep pos]

            # Skip over the prereq count.

            incr pos

            # Pull out each prereq, and save 

            foreach p [lrange $dep $pos end] {
                lappend prereqs($reader) [lindex $::gPrereqs $p]
            }
        }
    }
    set end [clock clicks -milliseconds]
    if { [info exists opt(d)] } {
        puts stderr "load: [expr {$end - $start}]"
    }

    catch {
        # Are we dumping serial deps or prereq deps?

        if {$::gMode == "SERIAL"} {
            upvar 0 readers which
        } else {
            upvar 0 prereqs which
        }

        fconfigure stdout -buffering full -buffersize 1000000
        foreach r [lsort [array names which]] {
            puts $r:
            foreach w [lsort $which($r)] {
                if {"$r" == "$w"} {
                    puts stderr "\nwarning: job depends on itself: $r\n"
                }
                puts \t$w
            }
        }
    }
}

main
