Debian Codegraph @

library/init.tcl

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