Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: data/Media/tcl/init.tcl @ 5051

Last change on this file since 5051 was 5051, checked in by landauf, 16 years ago

some changes in init.tcl

File size: 27.0 KB
Line 
1# init.tcl --
2#
3# Default system startup file for Tcl-based applications.  Defines
4# "unknown" procedure and auto-load facilities.
5#
6# RCS: @(#) $Id: init.tcl,v 1.104 2008/03/28 17:31:44 dgp Exp $
7#
8# Copyright (c) 1991-1993 The Regents of the University of California.
9# Copyright (c) 1994-1996 Sun Microsystems, Inc.
10# Copyright (c) 1998-1999 Scriptics Corporation.
11# Copyright (c) 2004 by Kevin B. Kenny.  All rights reserved.
12#
13# See the file "license.terms" for information on usage and redistribution
14# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
15#
16
17if {[info commands package] == ""} {
18    error "version mismatch: library\nscripts expect Tcl version 7.5b1 or later but the loaded version is\nonly [info patchlevel]"
19}
20package require -exact Tcl 8.5.2
21
22# Compute the auto path to use in this interpreter.
23# The values on the path come from several locations:
24#
25# The environment variable TCLLIBPATH
26#
27# tcl_library, which is the directory containing this init.tcl script.
28# [tclInit] (Tcl_Init()) searches around for the directory containing this
29# init.tcl and defines tcl_library to that location before sourcing it.
30#
31# The parent directory of tcl_library. Adding the parent
32# means that packages in peer directories will be found automatically.
33#
34# Also add the directory ../lib relative to the directory where the
35# executable is located.  This is meant to find binary packages for the
36# same architecture as the current executable.
37#
38# tcl_pkgPath, which is set by the platform-specific initialization routines
39#       On UNIX it is compiled in
40#       On Windows, it is not used
41
42if {![info exists auto_path]} {
43    if {[info exists env(TCLLIBPATH)]} {
44        set auto_path $env(TCLLIBPATH)
45    } else {
46        set auto_path ""
47    }
48}
49namespace eval tcl {
50    variable Dir
51    foreach Dir [list $::tcl_library [file dirname $::tcl_library]] {
52        if {$Dir ni $::auto_path} {
53            lappend ::auto_path $Dir
54        }
55    }
56    set Dir [file join [file dirname [file dirname \
57            [info nameofexecutable]]] lib]
58    if {$Dir ni $::auto_path} {
59        lappend ::auto_path $Dir
60    }
61    catch {
62        foreach Dir $::tcl_pkgPath {
63            if {$Dir ni $::auto_path} {
64                lappend ::auto_path $Dir
65            }
66        }
67    }
68
69    if {![interp issafe]} {
70        variable Path [encoding dirs]
71        set Dir [file join $::tcl_library encoding]
72        if {$Dir ni $Path} {
73            lappend Path $Dir
74            encoding dirs $Path
75        }
76    }
77
78    # TIP #255 min and max functions
79    namespace eval mathfunc {
80        proc min {args} {
81            if {[llength $args] == 0} {
82                return -code error \
83                    "too few arguments to math function \"min\""
84            }
85            set val Inf
86            foreach arg $args {
87                # This will handle forcing the numeric value without
88                # ruining the internal type of a numeric object
89                if {[catch {expr {double($arg)}} err]} {
90                    return -code error $err
91                }
92                if {$arg < $val} { set val $arg }
93            }
94            return $val
95        }
96        proc max {args} {
97            if {[llength $args] == 0} {
98                return -code error \
99                    "too few arguments to math function \"max\""
100            }
101            set val -Inf
102            foreach arg $args {
103                # This will handle forcing the numeric value without
104                # ruining the internal type of a numeric object
105                if {[catch {expr {double($arg)}} err]} {
106                    return -code error $err
107                }
108                if {$arg > $val} { set val $arg }
109            }
110            return $val
111        }
112    }
113}
114
115# Windows specific end of initialization
116
117if {(![interp issafe]) && ($tcl_platform(platform) eq "windows")} {
118    namespace eval tcl {
119        proc EnvTraceProc {lo n1 n2 op} {
120            set x $::env($n2)
121            set ::env($lo) $x
122            set ::env([string toupper $lo]) $x
123        }
124        proc InitWinEnv {} {
125            global env tcl_platform
126            foreach p [array names env] {
127                set u [string toupper $p]
128                if {$u ne $p} {
129                    switch -- $u {
130                        COMSPEC -
131                        PATH {
132                            if {![info exists env($u)]} {
133                                set env($u) $env($p)
134                            }
135                            trace add variable env($p) write \
136                                    [namespace code [list EnvTraceProc $p]]
137                            trace add variable env($u) write \
138                                    [namespace code [list EnvTraceProc $p]]
139                        }
140                    }
141                }
142            }
143            if {![info exists env(COMSPEC)]} {
144                if {$tcl_platform(os) eq "Windows NT"} {
145                    set env(COMSPEC) cmd.exe
146                } else {
147                    set env(COMSPEC) command.com
148                }
149            }
150        }
151        InitWinEnv
152    }
153}
154
155# Setup the unknown package handler
156
157
158if {[interp issafe]} {
159    package unknown ::tclPkgUnknown
160} else {
161    # Set up search for Tcl Modules (TIP #189).
162    # and setup platform specific unknown package handlers
163    if {$::tcl_platform(os) eq "Darwin"
164            && $::tcl_platform(platform) eq "unix"} {
165        package unknown {::tcl::tm::UnknownHandler \
166                {::tcl::MacOSXPkgUnknown ::tclPkgUnknown}}
167    } else {
168        package unknown {::tcl::tm::UnknownHandler ::tclPkgUnknown}
169    }
170
171    # Set up the 'clock' ensemble
172
173    namespace eval ::tcl::clock [list variable TclLibDir $::tcl_library]
174
175    proc clock args {
176        namespace eval ::tcl::clock [list namespace ensemble create -command \
177                [uplevel 1 [list namespace origin [lindex [info level 0] 0]]] \
178                -subcommands {
179                    add clicks format microseconds milliseconds scan seconds
180                }]
181       
182        # Auto-loading stubs for 'clock.tcl'
183       
184        foreach cmd {add format scan} {
185            proc ::tcl::clock::$cmd args {
186                variable TclLibDir
187                source -encoding utf-8 [file join $TclLibDir clock.tcl]
188                return [uplevel 1 [info level 0]]
189            }
190        }
191
192        return [uplevel 1 [info level 0]]
193    }
194}
195
196# Conditionalize for presence of exec.
197
198if {[namespace which -command exec] eq ""} {
199
200    # Some machines do not have exec. Also, on all
201    # platforms, safe interpreters do not have exec.
202
203    set auto_noexec 1
204}
205
206# Define a log command (which can be overwitten to log errors
207# differently, specially when stderr is not available)
208
209if {[namespace which -command tclLog] eq ""} {
210    proc tclLog {string} {
211        catch {puts stderr $string}
212    }
213}
214
215# query --
216# Sends a query to the Tcl interpreter of Orxonox and
217# waits for the response.
218# This procedure will be changed to it's real function
219# by Orxonox itself.
220#
221# Arguments:
222# args - The command to send to Orxonox
223
224proc query {id args} {
225    return -code error "can't query now"
226}
227
228# orxonox --
229# This procedure will be changed by Orxonox itself.
230# Until then it will return an error message.
231# orxonox gets called by "unknown" if a command isn't known.
232#
233# Arguments:
234# args - The original command
235
236proc orxonox args {
237    return -code error "can't execute \"$args\""
238}
239
240# execute --
241# This procedure will be changed by Orxonox itself.
242# execute calls a command in Orxonox.
243#
244# Arguments:
245# args - The command
246
247proc execute args {
248}
249
250# redef_puts --
251# Redefines puts to write directly into the Orxonox console
252# if the channel is stdout or stderr.
253
254proc redef_puts {} {
255    if ![llength [info command ::tcl::puts]] {
256        rename puts ::tcl::puts
257        proc puts args {
258            set la [llength $args]
259            if {$la<1 || $la>3} {
260                error "usage: puts ?-nonewline? ?channel? string"
261            }
262            set nl \n
263            if {[lindex $args 0]=="-nonewline"} {
264                set nl ""
265                set args [lrange $args 1 end]
266            }
267            if {[llength $args]==1} {
268                set args [list stdout [join $args]] ;
269            }
270            foreach {channel s} $args break
271            if {$channel=="stdout" || $channel=="stderr"} {
272                set cmd "execute puts"
273                if {$nl==""} {lappend cmd 0} else {lappend cmd 1}
274                lappend cmd $s
275                execute log muuuuh
276                eval $cmd
277            } else {
278                set cmd ::tcl::puts
279                if {$nl==""} {lappend cmd -nonewline}
280                lappend cmd $channel $s
281                eval $cmd
282            }
283        }
284    }
285}
286
287# unknown --
288# This procedure is called when a Tcl command is invoked that doesn't
289# exist in the interpreter.  It takes the following steps to make the
290# command available:
291#
292#       1. See if the command has the form "namespace inscope ns cmd" and
293#          if so, concatenate its arguments onto the end and evaluate it.
294#       2. See if the autoload facility can locate the command in a
295#          Tcl script file.  If so, load it and execute it.
296#       3. If the command was invoked interactively at top-level:
297#           (a) see if the command exists as an executable UNIX program.
298#               If so, "exec" the command.
299#           (b) see if the command requests csh-like history substitution
300#               in one of the common forms !!, !<number>, or ^old^new.  If
301#               so, emulate csh's history substitution.
302#           (c) see if the command is a unique abbreviation for another
303#               command.  If so, invoke the command.
304#
305# Arguments:
306# args -        A list whose elements are the words of the original
307#               command, including the command name.
308
309proc unknown args {
310    variable ::tcl::UnknownPending
311    global auto_noexec auto_noload env tcl_interactive
312
313    # If the command word has the form "namespace inscope ns cmd"
314    # then concatenate its arguments onto the end and evaluate it.
315
316    set cmd [lindex $args 0]
317    if {[regexp "^:*namespace\[ \t\n\]+inscope" $cmd] && [llength $cmd] == 4} {
318        #return -code error "You need an {*}"
319        set arglist [lrange $args 1 end]
320        set ret [catch {uplevel 1 ::$cmd $arglist} result opts]
321        dict unset opts -errorinfo
322        dict incr opts -level
323        return -options $opts $result
324    }
325
326    catch {set savedErrorInfo $::errorInfo}
327    catch {set savedErrorCode $::errorCode}
328    set name $cmd
329    if {![info exists auto_noload]} {
330        #
331        # Make sure we're not trying to load the same proc twice.
332        #
333        if {[info exists UnknownPending($name)]} {
334            return -code error "self-referential recursion\
335                    in \"unknown\" for command \"$name\"";
336        }
337        set UnknownPending($name) pending;
338        set ret [catch {
339                auto_load $name [uplevel 1 {::namespace current}]
340        } msg opts]
341        unset UnknownPending($name);
342        if {$ret != 0} {
343            dict append opts -errorinfo "\n    (autoloading \"$name\")"
344            return -options $opts $msg
345        }
346        if {![array size UnknownPending]} {
347            unset UnknownPending
348        }
349        if {$msg} {
350            catch {set ::errorCode $savedErrorCode}
351            catch {set ::errorInfo $savedErrorInfo}
352            set code [catch {uplevel 1 $args} msg opts]
353            if {$code ==  1} {
354                #
355                # Compute stack trace contribution from the [uplevel].
356                # Note the dependence on how Tcl_AddErrorInfo, etc.
357                # construct the stack trace.
358                #
359                set errorInfo [dict get $opts -errorinfo]
360                set errorCode [dict get $opts -errorcode]
361                set cinfo $args
362                if {[string bytelength $cinfo] > 150} {
363                    set cinfo [string range $cinfo 0 150]
364                    while {[string bytelength $cinfo] > 150} {
365                        set cinfo [string range $cinfo 0 end-1]
366                    }
367                    append cinfo ...
368                }
369                append cinfo "\"\n    (\"uplevel\" body line 1)"
370                append cinfo "\n    invoked from within"
371                append cinfo "\n\"uplevel 1 \$args\""
372                #
373                # Try each possible form of the stack trace
374                # and trim the extra contribution from the matching case
375                #
376                set expect "$msg\n    while executing\n\"$cinfo"
377                if {$errorInfo eq $expect} {
378                    #
379                    # The stack has only the eval from the expanded command
380                    # Do not generate any stack trace here.
381                    #
382                    dict unset opts -errorinfo
383                    dict incr opts -level
384                    return -options $opts $msg
385                }
386                #
387                # Stack trace is nested, trim off just the contribution
388                # from the extra "eval" of $args due to the "catch" above.
389                #
390                set expect "\n    invoked from within\n\"$cinfo"
391                set exlen [string length $expect]
392                set eilen [string length $errorInfo]
393                set i [expr {$eilen - $exlen - 1}]
394                set einfo [string range $errorInfo 0 $i]
395                #
396                # For now verify that $errorInfo consists of what we are about
397                # to return plus what we expected to trim off.
398                #
399                if {$errorInfo ne "$einfo$expect"} {
400                    error "Tcl bug: unexpected stack trace in \"unknown\"" {} \
401                        [list CORE UNKNOWN BADTRACE $einfo $expect $errorInfo]
402                }
403                return -code error -errorcode $errorCode \
404                        -errorinfo $einfo $msg
405            } else {
406                dict incr opts -level
407                return -options $opts $msg
408            }
409        }
410    }
411
412    if {([info level] == 1) && ([info script] eq "") \
413            && [info exists tcl_interactive] && $tcl_interactive} {
414        if {![info exists auto_noexec]} {
415            set new [auto_execok $name]
416            if {$new ne ""} {
417                set redir ""
418                if {[namespace which -command console] eq ""} {
419                    set redir ">&@stdout <@stdin"
420                }
421                uplevel 1 [list ::catch \
422                        [concat exec $redir $new [lrange $args 1 end]] \
423                        ::tcl::UnknownResult ::tcl::UnknownOptions]
424                dict incr ::tcl::UnknownOptions -level
425                return -options $::tcl::UnknownOptions $::tcl::UnknownResult
426            }
427        }
428        if {$name eq "!!"} {
429            set newcmd [history event]
430        } elseif {[regexp {^!(.+)$} $name -> event]} {
431            set newcmd [history event $event]
432        } elseif {[regexp {^\^([^^]*)\^([^^]*)\^?$} $name -> old new]} {
433            set newcmd [history event -1]
434            catch {regsub -all -- $old $newcmd $new newcmd}
435        }
436        if {[info exists newcmd]} {
437            tclLog $newcmd
438            history change $newcmd 0
439            uplevel 1 [list ::catch $newcmd \
440                    ::tcl::UnknownResult ::tcl::UnknownOptions]
441            dict incr ::tcl::UnknownOptions -level
442            return -options $::tcl::UnknownOptions $::tcl::UnknownResult
443        }
444
445        set ret [catch {set candidates [info commands $name*]} msg]
446        if {$name eq "::"} {
447            set name ""
448        }
449        if {$ret != 0} {
450            dict append opts -errorinfo \
451                    "\n    (expanding command prefix \"$name\" in unknown)"
452            return -options $opts $msg
453        }
454        # Filter out bogus matches when $name contained
455        # a glob-special char [Bug 946952]
456        if {$name eq ""} {
457            # Handle empty $name separately due to strangeness
458            # in [string first] (See RFE 1243354)
459            set cmds $candidates
460        } else {
461            set cmds [list]
462            foreach x $candidates {
463                if {[string first $name $x] == 0} {
464                    lappend cmds $x
465                }
466            }
467        }
468        if {[llength $cmds] == 1} {
469            uplevel 1 [list ::catch [lreplace $args 0 0 [lindex $cmds 0]] \
470                    ::tcl::UnknownResult ::tcl::UnknownOptions]
471            dict incr ::tcl::UnknownOptions -level
472            return -options $::tcl::UnknownOptions $::tcl::UnknownResult
473        }
474        if {[llength $cmds]} {
475            return -code error "ambiguous command name \"$name\": [lsort $cmds]"
476        }
477    }
478#    return -code error "invalid command name \"$name\""
479    return [orxonox $args]
480}
481
482# auto_load --
483# Checks a collection of library directories to see if a procedure
484# is defined in one of them.  If so, it sources the appropriate
485# library file to create the procedure.  Returns 1 if it successfully
486# loaded the procedure, 0 otherwise.
487#
488# Arguments:
489# cmd -                 Name of the command to find and load.
490# namespace (optional)  The namespace where the command is being used - must be
491#                       a canonical namespace as returned [namespace current]
492#                       for instance. If not given, namespace current is used.
493
494proc auto_load {cmd {namespace {}}} {
495    global auto_index auto_path
496
497    if {$namespace eq ""} {
498        set namespace [uplevel 1 [list ::namespace current]]
499    }
500    set nameList [auto_qualify $cmd $namespace]
501    # workaround non canonical auto_index entries that might be around
502    # from older auto_mkindex versions
503    lappend nameList $cmd
504    foreach name $nameList {
505        if {[info exists auto_index($name)]} {
506            namespace eval :: $auto_index($name)
507            # There's a couple of ways to look for a command of a given
508            # name.  One is to use
509            #    info commands $name
510            # Unfortunately, if the name has glob-magic chars in it like *
511            # or [], it may not match.  For our purposes here, a better
512            # route is to use
513            #    namespace which -command $name
514            if {[namespace which -command $name] ne ""} {
515                return 1
516            }
517        }
518    }
519    if {![info exists auto_path]} {
520        return 0
521    }
522
523    if {![auto_load_index]} {
524        return 0
525    }
526    foreach name $nameList {
527        if {[info exists auto_index($name)]} {
528            namespace eval :: $auto_index($name)
529            if {[namespace which -command $name] ne ""} {
530                return 1
531            }
532        }
533    }
534    return 0
535}
536
537# auto_load_index --
538# Loads the contents of tclIndex files on the auto_path directory
539# list.  This is usually invoked within auto_load to load the index
540# of available commands.  Returns 1 if the index is loaded, and 0 if
541# the index is already loaded and up to date.
542#
543# Arguments:
544# None.
545
546proc auto_load_index {} {
547    variable ::tcl::auto_oldpath
548    global auto_index auto_path
549
550    if {[info exists auto_oldpath] && ($auto_oldpath eq $auto_path)} {
551        return 0
552    }
553    set auto_oldpath $auto_path
554
555    # Check if we are a safe interpreter. In that case, we support only
556    # newer format tclIndex files.
557
558    set issafe [interp issafe]
559    for {set i [expr {[llength $auto_path] - 1}]} {$i >= 0} {incr i -1} {
560        set dir [lindex $auto_path $i]
561        set f ""
562        if {$issafe} {
563            catch {source [file join $dir tclIndex]}
564        } elseif {[catch {set f [open [file join $dir tclIndex]]}]} {
565            continue
566        } else {
567            set error [catch {
568                set id [gets $f]
569                if {$id eq "# Tcl autoload index file, version 2.0"} {
570                    eval [read $f]
571                } elseif {$id eq "# Tcl autoload index file: each line identifies a Tcl"} {
572                    while {[gets $f line] >= 0} {
573                        if {([string index $line 0] eq "#") \
574                                || ([llength $line] != 2)} {
575                            continue
576                        }
577                        set name [lindex $line 0]
578                        set auto_index($name) \
579                                "source [file join $dir [lindex $line 1]]"
580                    }
581                } else {
582                    error "[file join $dir tclIndex] isn't a proper Tcl index file"
583                }
584            } msg opts]
585            if {$f ne ""} {
586                close $f
587            }
588            if {$error} {
589                return -options $opts $msg
590            }
591        }
592    }
593    return 1
594}
595
596# auto_qualify --
597#
598# Compute a fully qualified names list for use in the auto_index array.
599# For historical reasons, commands in the global namespace do not have leading
600# :: in the index key. The list has two elements when the command name is
601# relative (no leading ::) and the namespace is not the global one. Otherwise
602# only one name is returned (and searched in the auto_index).
603#
604# Arguments -
605# cmd           The command name. Can be any name accepted for command
606#               invocations (Like "foo::::bar").
607# namespace     The namespace where the command is being used - must be
608#               a canonical namespace as returned by [namespace current]
609#               for instance.
610
611proc auto_qualify {cmd namespace} {
612
613    # count separators and clean them up
614    # (making sure that foo:::::bar will be treated as foo::bar)
615    set n [regsub -all {::+} $cmd :: cmd]
616
617    # Ignore namespace if the name starts with ::
618    # Handle special case of only leading ::
619
620    # Before each return case we give an example of which category it is
621    # with the following form :
622    # ( inputCmd, inputNameSpace) -> output
623
624    if {[string match ::* $cmd]} {
625        if {$n > 1} {
626            # ( ::foo::bar , * ) -> ::foo::bar
627            return [list $cmd]
628        } else {
629            # ( ::global , * ) -> global
630            return [list [string range $cmd 2 end]]
631        }
632    }
633   
634    # Potentially returning 2 elements to try  :
635    # (if the current namespace is not the global one)
636
637    if {$n == 0} {
638        if {$namespace eq "::"} {
639            # ( nocolons , :: ) -> nocolons
640            return [list $cmd]
641        } else {
642            # ( nocolons , ::sub ) -> ::sub::nocolons nocolons
643            return [list ${namespace}::$cmd $cmd]
644        }
645    } elseif {$namespace eq "::"} {
646        #  ( foo::bar , :: ) -> ::foo::bar
647        return [list ::$cmd]
648    } else {
649        # ( foo::bar , ::sub ) -> ::sub::foo::bar ::foo::bar
650        return [list ${namespace}::$cmd ::$cmd]
651    }
652}
653
654# auto_import --
655#
656# Invoked during "namespace import" to make see if the imported commands
657# reside in an autoloaded library.  If so, the commands are loaded so
658# that they will be available for the import links.  If not, then this
659# procedure does nothing.
660#
661# Arguments -
662# pattern       The pattern of commands being imported (like "foo::*")
663#               a canonical namespace as returned by [namespace current]
664
665proc auto_import {pattern} {
666    global auto_index
667
668    # If no namespace is specified, this will be an error case
669
670    if {![string match *::* $pattern]} {
671        return
672    }
673
674    set ns [uplevel 1 [list ::namespace current]]
675    set patternList [auto_qualify $pattern $ns]
676
677    auto_load_index
678
679    foreach pattern $patternList {
680        foreach name [array names auto_index $pattern] {
681            if {([namespace which -command $name] eq "")
682                    && ([namespace qualifiers $pattern] eq [namespace qualifiers $name])} {
683                namespace eval :: $auto_index($name)
684            }
685        }
686    }
687}
688
689# auto_execok --
690#
691# Returns string that indicates name of program to execute if
692# name corresponds to a shell builtin or an executable in the
693# Windows search path, or "" otherwise.  Builds an associative
694# array auto_execs that caches information about previous checks,
695# for speed.
696#
697# Arguments:
698# name -                        Name of a command.
699
700if {$tcl_platform(platform) eq "windows"} {
701# Windows version.
702#
703# Note that info executable doesn't work under Windows, so we have to
704# look for files with .exe, .com, or .bat extensions.  Also, the path
705# may be in the Path or PATH environment variables, and path
706# components are separated with semicolons, not colons as under Unix.
707#
708proc auto_execok name {
709    global auto_execs env tcl_platform
710
711    if {[info exists auto_execs($name)]} {
712        return $auto_execs($name)
713    }
714    set auto_execs($name) ""
715
716    set shellBuiltins [list cls copy date del erase dir echo mkdir \
717            md rename ren rmdir rd time type ver vol]
718    if {$tcl_platform(os) eq "Windows NT"} {
719        # NT includes the 'start' built-in
720        lappend shellBuiltins "start"
721    }
722    if {[info exists env(PATHEXT)]} {
723        # Add an initial ; to have the {} extension check first.
724        set execExtensions [split ";$env(PATHEXT)" ";"]
725    } else {
726        set execExtensions [list {} .com .exe .bat]
727    }
728
729    if {$name in $shellBuiltins} {
730        # When this is command.com for some reason on Win2K, Tcl won't
731        # exec it unless the case is right, which this corrects.  COMSPEC
732        # may not point to a real file, so do the check.
733        set cmd $env(COMSPEC)
734        if {[file exists $cmd]} {
735            set cmd [file attributes $cmd -shortname]
736        }
737        return [set auto_execs($name) [list $cmd /c $name]]
738    }
739
740    if {[llength [file split $name]] != 1} {
741        foreach ext $execExtensions {
742            set file ${name}${ext}
743            if {[file exists $file] && ![file isdirectory $file]} {
744                return [set auto_execs($name) [list $file]]
745            }
746        }
747        return ""
748    }
749
750    set path "[file dirname [info nameof]];.;"
751    if {[info exists env(WINDIR)]} {
752        set windir $env(WINDIR) 
753    }
754    if {[info exists windir]} {
755        if {$tcl_platform(os) eq "Windows NT"} {
756            append path "$windir/system32;"
757        }
758        append path "$windir/system;$windir;"
759    }
760
761    foreach var {PATH Path path} {
762        if {[info exists env($var)]} {
763            append path ";$env($var)"
764        }
765    }
766
767    foreach dir [split $path {;}] {
768        # Skip already checked directories
769        if {[info exists checked($dir)] || ($dir eq {})} { continue }
770        set checked($dir) {}
771        foreach ext $execExtensions {
772            set file [file join $dir ${name}${ext}]
773            if {[file exists $file] && ![file isdirectory $file]} {
774                return [set auto_execs($name) [list $file]]
775            }
776        }
777    }
778    return ""
779}
780
781} else {
782# Unix version.
783#
784proc auto_execok name {
785    global auto_execs env
786
787    if {[info exists auto_execs($name)]} {
788        return $auto_execs($name)
789    }
790    set auto_execs($name) ""
791    if {[llength [file split $name]] != 1} {
792        if {[file executable $name] && ![file isdirectory $name]} {
793            set auto_execs($name) [list $name]
794        }
795        return $auto_execs($name)
796    }
797    foreach dir [split $env(PATH) :] {
798        if {$dir eq ""} {
799            set dir .
800        }
801        set file [file join $dir $name]
802        if {[file executable $file] && ![file isdirectory $file]} {
803            set auto_execs($name) [list $file]
804            return $auto_execs($name)
805        }
806    }
807    return ""
808}
809
810}
811
812# ::tcl::CopyDirectory --
813#
814# This procedure is called by Tcl's core when attempts to call the
815# filesystem's copydirectory function fail.  The semantics of the call
816# are that 'dest' does not yet exist, i.e. dest should become the exact
817# image of src.  If dest does exist, we throw an error. 
818#
819# Note that making changes to this procedure can change the results
820# of running Tcl's tests.
821#
822# Arguments:
823# action -              "renaming" or "copying"
824# src -                 source directory
825# dest -                destination directory
826proc tcl::CopyDirectory {action src dest} {
827    set nsrc [file normalize $src]
828    set ndest [file normalize $dest]
829
830    if {$action eq "renaming"} {
831        # Can't rename volumes.  We could give a more precise
832        # error message here, but that would break the test suite.
833        if {$nsrc in [file volumes]} {
834            return -code error "error $action \"$src\" to\
835              \"$dest\": trying to rename a volume or move a directory\
836              into itself"
837        }
838    }
839    if {[file exists $dest]} {
840        if {$nsrc eq $ndest} {
841            return -code error "error $action \"$src\" to\
842              \"$dest\": trying to rename a volume or move a directory\
843              into itself"
844        }
845        if {$action eq "copying"} {
846            # We used to throw an error here, but, looking more closely
847            # at the core copy code in tclFCmd.c, if the destination
848            # exists, then we should only call this function if -force
849            # is true, which means we just want to over-write.  So,
850            # the following code is now commented out.
851            #
852            # return -code error "error $action \"$src\" to\
853            # \"$dest\": file already exists"
854        } else {
855            # Depending on the platform, and on the current
856            # working directory, the directories '.', '..'
857            # can be returned in various combinations.  Anyway,
858            # if any other file is returned, we must signal an error.
859            set existing [glob -nocomplain -directory $dest * .*]
860            lappend existing {*}[glob -nocomplain -directory $dest \
861                    -type hidden * .*]
862            foreach s $existing {
863                if {([file tail $s] ne ".") && ([file tail $s] ne "..")} {
864                    return -code error "error $action \"$src\" to\
865                      \"$dest\": file already exists"
866                }
867            }
868        }
869    } else {
870        if {[string first $nsrc $ndest] != -1} {
871            set srclen [expr {[llength [file split $nsrc]] -1}]
872            set ndest [lindex [file split $ndest] $srclen]
873            if {$ndest eq [file tail $nsrc]} {
874                return -code error "error $action \"$src\" to\
875                  \"$dest\": trying to rename a volume or move a directory\
876                  into itself"
877            }
878        }
879        file mkdir $dest
880    }
881    # Have to be careful to capture both visible and hidden files.
882    # We will also be more generous to the file system and not
883    # assume the hidden and non-hidden lists are non-overlapping.
884    #
885    # On Unix 'hidden' files begin with '.'.  On other platforms
886    # or filesystems hidden files may have other interpretations.
887    set filelist [concat [glob -nocomplain -directory $src *] \
888      [glob -nocomplain -directory $src -types hidden *]]
889
890    foreach s [lsort -unique $filelist] {
891        if {([file tail $s] ne ".") && ([file tail $s] ne "..")} {
892            file copy -force $s [file join $dest [file tail $s]]
893        }
894    }
895    return
896}
Note: See TracBrowser for help on using the repository browser.