source: trunk/base/src/port1.0/portutil.tcl @ 29367

Last change on this file since 29367 was 29367, checked in by epimenov@…, 10 years ago

Port trace: add depends_build to configure target.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 57.5 KB
Line 
1# et:ts=4
2# portutil.tcl
3# $Id: portutil.tcl 29367 2007-09-22 12:28:53Z epimenov@macports.org $
4#
5# Copyright (c) 2004 Robert Shaw <rshaw@opendarwin.org>
6# Copyright (c) 2002 Apple Computer, Inc.
7# Copyright (c) 2006 Markus W. Weissmann <mww@macports.org>
8# All rights reserved.
9#
10# Redistribution and use in source and binary forms, with or without
11# modification, are permitted provided that the following conditions
12# are met:
13# 1. Redistributions of source code must retain the above copyright
14#    notice, this list of conditions and the following disclaimer.
15# 2. Redistributions in binary form must reproduce the above copyright
16#    notice, this list of conditions and the following disclaimer in the
17#    documentation and/or other materials provided with the distribution.
18# 3. Neither the name of Apple Computer, Inc. nor the names of its contributors
19#    may be used to endorse or promote products derived from this software
20#    without specific prior written permission.
21#
22# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32# POSSIBILITY OF SUCH DAMAGE.
33#
34
35package provide portutil 1.0
36package require Pextlib 1.0
37package require macports_dlist 1.0
38package require macports_util 1.0
39package require msgcat
40package require porttrace 1.0
41
42global targets target_uniqid all_variants
43
44set targets [list]
45set target_uniqid 0
46
47set all_variants [list]
48
49########### External High Level Procedures ###########
50
51namespace eval options {
52}
53
54# option
55# This is an accessor for Portfile options.  Targets may use
56# this in the same style as the standard Tcl "set" procedure.
57#       name  - the name of the option to read or write
58#       value - an optional value to assign to the option
59
60proc option {name args} {
61    # XXX: right now we just transparently use globals
62    # eventually this will need to bridge the options between
63    # the Portfile's interpreter and the target's interpreters.
64    global $name
65    if {[llength $args] > 0} {
66        ui_debug "setting option $name to $args"
67        set $name [lindex $args 0]
68    }
69    return [set $name]
70}
71
72# exists
73# This is an accessor for Portfile options.  Targets may use
74# this procedure to test for the existence of a Portfile option.
75#       name - the name of the option to test for existence
76
77proc exists {name} {
78    # XXX: right now we just transparently use globals
79    # eventually this will need to bridge the options between
80    # the Portfile's interpreter and the target's interpreters.
81    global $name
82    return [info exists $name]
83}
84
85# options
86# Exports options in an array as externally callable procedures
87# Thus, "options name date" would create procedures named "name"
88# and "date" that set global variables "name" and "date", respectively
89# When an option is modified in any way, options::$option is called,
90# if it exists
91# Arguments: <list of options>
92proc options {args} {
93    foreach option $args {
94        proc $option {args} [subst -nocommands {
95            global $option user_options option_procs
96            if {![info exists user_options($option)]} {
97                set $option \$args
98            }
99        }]
100        proc ${option}-delete {args} [subst -nocommands {
101            global $option user_options option_procs
102            if {![info exists user_options($option)] && [info exists $option]} {
103                set temp [set $option]
104                foreach val \$args {
105                   set temp [ldelete \$temp \$val]
106                }
107                if {\$temp eq ""} {
108                    unset $option
109                } else {
110                    set $option \$temp
111                }
112            }
113        }]
114        proc ${option}-append {args} [subst -nocommands {
115            global $option user_options option_procs
116            if {![info exists user_options($option)]} {
117                if {[info exists $option]} {
118                    set $option [concat \${$option} \$args]
119                } else {
120                    set $option \$args
121                }
122            }
123        }]
124    }
125}
126
127proc options_export {args} {
128    foreach option $args {
129        proc options::export-${option} {option action {value ""}} [subst -nocommands {
130            global $option PortInfo
131            switch \$action {
132                set {
133                    set PortInfo($option) \$value
134                }
135                delete {
136                    unset PortInfo($option)
137                }
138            }
139        }]
140        option_proc $option options::export-$option
141    }
142}
143
144# option_deprecate
145# Causes a warning to be printed when an option is set or accessed
146proc option_deprecate {option {newoption ""} } {
147    # If a new option is specified, default the option to {${newoption}}
148    # Display a warning
149    if {$newoption != ""} {
150        proc warn_deprecated_${option} {option action args} [subst -nocommands {
151            global portname $option $newoption
152            if {\$action != "read"} {
153                $newoption \$$option
154            } else {
155                ui_warn "Port \$portname using deprecated option \\\"$option\\\"."
156                $option \[set $newoption\]
157            }
158        }]
159    } else {
160        proc warn_deprecated_$option {option action args} [subst -nocommands {
161            global portname $option $newoption
162            ui_warn "Port \$portname using deprecated option \\\"$option\\\"."
163        }]
164    }
165    option_proc $option warn_deprecated_$option
166}
167
168proc option_proc {option args} {
169    global option_procs $option
170    if {[info exists option_procs($option)]} {
171        set option_procs($option) [concat $option_procs($option) $args]
172        # we're already tracing
173    } else {
174        set option_procs($option) $args
175        trace add variable $option {read write unset} option_proc_trace
176    }
177}
178
179# option_proc_trace
180# trace handler for option reads. Calls option procedures with correct arguments.
181proc option_proc_trace {optionName index op} {
182    global option_procs
183    upvar $optionName $optionName
184    switch $op {
185        write {
186            foreach p $option_procs($optionName) {
187                $p $optionName set [set $optionName]
188            }
189        }
190        read {
191            foreach p $option_procs($optionName) {
192                $p $optionName read
193            }
194        }
195        unset {
196            foreach p $option_procs($optionName) {
197                if {[catch {$p $optionName delete} result]} {
198                    ui_debug "error during unset trace ($p): $result\n$::errorInfo"
199                }
200            }
201            trace add variable $optionName {read write unset} option_proc_trace
202        }
203    }
204}
205
206# commands
207# Accepts a list of arguments, of which several options are created
208# and used to form a standard set of command options.
209proc commands {args} {
210    foreach option $args {
211        options use_${option} ${option}.dir ${option}.pre_args ${option}.args ${option}.post_args ${option}.env ${option}.type ${option}.cmd
212    }
213}
214
215# Given a command name, assemble a command string
216# composed of the command options.
217proc command_string {command} {
218    global ${command}.dir ${command}.pre_args ${command}.args ${command}.post_args ${command}.env ${command}.type ${command}.cmd
219   
220    set cmdstring ""
221    if {[info exists ${command}.dir]} {
222        set cmdstring "cd \"[set ${command}.dir]\" &&"
223    }
224   
225    if {[info exists ${command}.cmd]} {
226        foreach string [set ${command}.cmd] {
227            set cmdstring "$cmdstring $string"
228        }
229    } else {
230        set cmdstring "$cmdstring ${command}"
231    }
232    foreach var "${command}.pre_args ${command}.args ${command}.post_args" {
233        if {[info exists $var]} {
234            foreach string [set ${var}] {
235                set cmdstring "$cmdstring $string"
236            }
237        }
238    }
239    ui_debug "Assembled command: '$cmdstring'"
240    return $cmdstring
241}
242
243# Given a command name, execute it with the options.
244# command_exec command [-notty] [command_prefix [command_suffix]]
245# command                       name of the command
246# command_prefix        additional command prefix (typically pipe command)
247# command_suffix        additional command suffix (typically redirection)
248proc command_exec {command args} {
249        global ${command}.env ${command}.env_array env
250        set notty 0
251        set command_prefix ""
252        set command_suffix ""
253
254        if {[llength $args] > 0} {
255                if {[lindex $args 0] == "-notty"} {
256                        set notty 1
257                        set args [lrange $args 1 end]
258                }
259
260                if {[llength $args] > 0} {
261                        set command_prefix [lindex $args 0]
262                        if {[llength $args] > 1} {
263                                set command_suffix [lindex $args 1]
264                        }
265                }
266        }
267       
268        # Set the environment.
269        # If the array doesn't exist, we create it with the value
270        # coming from ${command}.env
271        # Otherwise, it means the caller actually played with the environment
272        # array already (e.g. configure flags).
273        if {![array exists ${command}.env_array]} {
274                parse_environment ${command}
275        }
276       
277        # Debug that.
278    ui_debug "Environment: [environment_array_to_string ${command}.env_array]"
279
280        # Get the command string.
281        set cmdstring [command_string ${command}]
282       
283        # Call this command.
284        # TODO: move that to the system native call?
285        # Save the environment.
286        array set saved_env [array get env]
287        # Set the overriden variables from the portfile.
288        array set env [array get ${command}.env_array]
289        # Call the command.
290        set fullcmdstring "$command_prefix $cmdstring $command_suffix"
291        if {$notty} {
292                set code [catch {system -notty $fullcmdstring} result]
293        } else {
294                set code [catch {system $fullcmdstring} result]
295        }
296        # Unset the command array until next time.
297        array unset ${command}.env_array
298       
299        # Restore the environment.
300        array unset env *
301        array set env [array get saved_env]
302
303        # Return as if system had been called directly.
304        return -code $code $result
305}
306
307# default
308# Sets a variable to the supplied default if it does not exist,
309# and adds a variable trace. The variable traces allows for delayed
310# variable and command expansion in the variable's default value.
311proc default {option val} {
312    global $option option_defaults
313    if {[info exists option_defaults($option)]} {
314        ui_debug "Re-registering default for $option"
315        # remove the old trace
316        trace vdelete $option rwu default_check
317    } else {
318        # If option is already set and we did not set it
319        # do not reset the value
320        if {[info exists $option]} {
321            return
322        }
323    }
324    set option_defaults($option) $val
325    set $option $val
326    trace variable $option rwu default_check
327}
328
329# default_check
330# trace handler to provide delayed variable & command expansion
331# for default variable values
332proc default_check {optionName index op} {
333    global option_defaults $optionName
334    switch $op {
335        w {
336            unset option_defaults($optionName)
337            trace vdelete $optionName rwu default_check
338            return
339        }
340        r {
341            upvar $optionName option
342            uplevel #0 set $optionName $option_defaults($optionName)
343            return
344        }
345        u {
346            unset option_defaults($optionName)
347            trace vdelete $optionName rwu default_check
348            return
349        }
350    }
351}
352
353# variant <provides> [<provides> ...] [requires <requires> [<requires>]]
354# Portfile level procedure to provide support for declaring variants
355proc variant {args} {
356    global all_variants PortInfo
357   
358    set len [llength $args]
359    set code [lindex $args end]
360    set args [lrange $args 0 [expr $len - 2]]
361   
362    set ditem [variant_new "temp-variant"]
363   
364    # mode indicates what the arg is interpreted as.
365    # possible mode keywords are: requires, conflicts, provides
366    # The default mode is provides.  Arguments are added to the
367    # most recently specified mode (left to right).
368    set mode "provides"
369    foreach arg $args {
370        switch -exact $arg {
371            description -
372            provides -
373            requires -
374            conflicts { set mode $arg }
375            default { ditem_append $ditem $mode $arg }         
376        }
377    }
378    ditem_key $ditem name "[join [ditem_key $ditem provides] -]"
379   
380    # make a user procedure named variant-blah-blah
381    # we will call this procedure during variant-run
382    makeuserproc "variant-[ditem_key $ditem name]" \{$code\}
383   
384    # Export provided variant to PortInfo
385    # (don't list it twice if the variant was already defined, which can happen
386    # with universal or group code).
387    set variant_provides [ditem_key $ditem provides]
388    if {[variant_exists $variant_provides]} {
389                # This variant was already defined. Remove it from the dlist.
390                variant_remove_ditem $variant_provides
391        } else {
392            lappend PortInfo(variants) $variant_provides
393            set vdesc [join [ditem_key $ditem description]]
394            if {$vdesc != ""} {
395                    lappend PortInfo(variant_desc) $variant_provides $vdesc
396                }
397        }
398
399        # Finally append the ditem to the dlist.
400    lappend all_variants $ditem
401}
402
403# variant_isset name
404# Returns 1 if variant name selected, otherwise 0
405proc variant_isset {name} {
406    global variations
407   
408    if {[info exists variations($name)] && $variations($name) == "+"} {
409        return 1
410    }
411    return 0
412}
413
414# variant_set name
415# Sets variant to run for current portfile
416proc variant_set {name} {
417    global variations
418   
419    set variations($name) +
420}
421
422# variant_unset name
423# Clear variant for current portfile
424proc variant_unset {name} {
425    global variations
426   
427    set variations($name) -
428}
429
430# variant_undef name
431# Undefine a variant for the current portfile.
432proc variant_undef {name} {
433    global variations PortInfo
434   
435    # Remove it from the list of selected variations.
436    array unset variations $name
437
438        # Remove the variant from the portinfo.
439        if {[info exists PortInfo(variants)]} {
440                set variant_index [lsearch -exact $PortInfo(variants) $name]
441                if {$variant_index >= 0} {
442                        set new_list [lreplace $PortInfo(variants) $variant_index $variant_index]
443                        if {"$new_list" == {}} {
444                                unset PortInfo(variants) 
445                        } else {
446                                set PortInfo(variants) $new_list
447                        }
448                }
449        }
450       
451        # And from the dlist.
452        variant_remove_ditem $name
453}
454
455# variant_remove_ditem name
456# Remove variant name's ditem from the all_variants dlist
457proc variant_remove_ditem {name} {
458        global all_variants
459        set item_index 0
460        foreach variant_item $all_variants {
461                set item_provides [ditem_key $variant_item provides]
462                if {$item_provides == $name} {
463                        set all_variants [lreplace $all_variants $item_index $item_index]
464                        break
465                }
466               
467                incr item_index
468        }
469}
470
471# variant_exists name
472# determine if a variant exists.
473proc variant_exists {name} {
474        global PortInfo
475        if {[info exists PortInfo(variants)] &&
476                [lsearch -exact $PortInfo(variants) $name] >= 0} {
477                return 1
478        }
479       
480        return 0
481}
482
483# platform <os> [<release>] [<arch>]
484# Portfile level procedure to provide support for declaring platform-specifics
485# Basically, just wrap 'variant', so that Portfiles' platform declarations can
486# be more readable, and support arch and version specifics
487proc platform {args} {
488    global all_variants PortInfo os.platform os.arch os.version os.major
489   
490    set len [llength $args]
491    set code [lindex $args end]
492    set os [lindex $args 0]
493    set args [lrange $args 1 [expr $len - 2]]
494   
495    set ditem [variant_new "temp-variant"]
496   
497    foreach arg $args {
498        if {[regexp {(^[0-9]$)} $arg match result]} {
499            set release $result
500        } elseif {[regexp {([a-zA-Z0-9]*)} $arg match result]} {
501            set arch $result
502        }
503    }
504   
505    # Add the variant for this platform
506    set platform $os
507    if {[info exists release]} { set platform ${platform}_${release} }
508    if {[info exists arch]} { set platform ${platform}_${arch} }
509   
510    # Pick up a unique name.
511    if {[variant_exists $platform]} {
512        set suffix 1
513        while {[variant_exists "$platform-$suffix"]} {
514                incr suffix
515        }
516       
517        set platform "$platform-$suffix"
518    }
519    variant $platform $code
520   
521    # Set the variant if this platform matches the platform we're on
522    set matches 1
523    if {[info exists os.platform] && ${os.platform} == $os} { 
524        set sel_platform $os
525        if {[info exists os.major] && [info exists release]} {
526            if {${os.major} == $release } { 
527                set sel_platform ${sel_platform}_${release} 
528            } else {
529                    set matches 0
530            }
531        }
532        if {$matches == 1 && [info exists arch] && [info exists os.arch]} {
533                if {${os.arch} == $arch} {
534                        set sel_platform ${sel_platform}_${arch}
535                } else {
536                        set matches 0
537                }
538    }
539    if {$matches == 1} {
540        variant_set $sel_platform
541    }
542    }
543}
544
545########### Environment utility functions ###########
546
547# Parse the environment string of a command, storing the values into the
548# associated environment array.
549proc parse_environment {command} {
550        global ${command}.env ${command}.env_array
551
552        if {[info exists ${command}.env]} {
553                # Flatten the environment string.
554                set the_environment ""
555                foreach str [set ${command}.env] {
556                        set the_environment "$the_environment $str"
557                }
558       
559                while {[regexp "^(?: *)(\[^= \]+)=(\"|'|)(\[^\"'\].*?)\\2(?: +|$)(.*)$" ${the_environment} matchVar key delimiter value remaining]} {
560                        set the_environment ${remaining}
561                        set ${command}.env_array(${key}) ${value}
562                }
563        } else {
564                array set ${command}.env_array {}
565        }
566}
567
568# Append to the value in the parsed environment.
569# Leave the environment untouched if the value is empty.
570proc append_to_environment_value {command key value} {
571        global ${command}.env_array
572
573        if {[string length $value] == 0} {
574                return
575        }
576
577        # Parse out any delimiter.
578        set append_value $value
579        if {[regexp {^("|')(.*)\1$} $append_value matchVar append_delim matchedValue]} {
580                set append_value $matchedValue
581        }
582
583        if {[info exists ${command}.env_array($key)]} {
584                set original_value [set ${command}.env_array($key)]
585                set ${command}.env_array($key) "${original_value} ${append_value}"
586        } else {
587                set ${command}.env_array($key) $append_value
588        }
589}
590
591# Append several items to a value in the parsed environment.
592proc append_list_to_environment_value {command key vallist} {
593        foreach {value} $vallist {
594                append_to_environment_value ${command} $key $value
595        }
596}
597
598# Build the environment as a string.
599# Remark: this method is only used for debugging purposes.
600proc environment_array_to_string {environment_array} {
601        upvar 1 ${environment_array} env_array
602       
603        set theString ""
604        foreach {key value} [array get env_array] {
605                if {$theString == ""} {
606                        set theString "$key='$value'"
607                } else {
608                        set theString "${theString} $key='$value'"
609                }
610        }
611       
612        return $theString
613}
614
615########### Distname utility functions ###########
616
617# Given a distribution file name, return the appended tag
618# Example: getdisttag distfile.tar.gz:tag1 returns "tag1"
619# / isn't included in the regexp, thus allowing port specification in URLs.
620proc getdisttag {name} {
621    if {[regexp {.+:([0-9A-Za-z_-]+)$} $name match tag]} {
622        return $tag
623    } else {
624        return ""
625    }
626}
627
628# Given a distribution file name, return the name without an attached tag
629# Example : getdistname distfile.tar.gz:tag1 returns "distfile.tar.gz"
630# / isn't included in the regexp, thus allowing port specification in URLs.
631proc getdistname {name} {
632    regexp {(.+):[0-9A-Za-z_-]+$} $name match name
633    return $name
634}
635
636
637########### Misc Utility Functions ###########
638
639# tbool (testbool)
640# If the variable exists in the calling procedure's namespace
641# and is set to "yes", return 1. Otherwise, return 0
642proc tbool {key} {
643    upvar $key $key
644    if {[info exists $key]} {
645        if {[string equal -nocase [set $key] "yes"]} {
646            return 1
647        }
648    }
649    return 0
650}
651
652# ldelete
653# Deletes a value from the supplied list
654proc ldelete {list value} {
655    set ix [lsearch -exact $list $value]
656    if {$ix >= 0} {
657        return [lreplace $list $ix $ix]
658    }
659    return $list
660}
661
662# reinplace
663# Provides "sed in place" functionality
664proc reinplace {args}  {
665    set extended 0
666    while 1 {
667        set arg [lindex $args 0]
668        if {[string index $arg 0] eq "-"} {
669            set args [lrange $args 1 end]
670            switch [string range $arg 1 end] {
671                E {
672                    set extended 1
673                }
674                - {
675                    break
676                }
677                default {
678                    error "reinplace: unknown flag '$arg'"
679                }
680            }
681        } else {
682            break
683        }
684    }
685    if {[llength $args] < 2} {
686        error "reinplace ?-E? pattern file ..."
687    }
688    set pattern [lindex $args 0]
689    set files [lrange $args 1 end]
690   
691    foreach file $files {
692        if {[catch {set tmpfile [mkstemp "/tmp/[file tail $file].sed.XXXXXXXX"]} error]} {
693                global errorInfo
694                ui_debug "$errorInfo"
695            ui_error "reinplace: $error"
696            return -code error "reinplace failed"
697        } else {
698            # Extract the Tcl Channel number
699            set tmpfd [lindex $tmpfile 0]
700            # Set tmpfile to only the file name
701            set tmpfile [lindex $tmpfile 1]
702        }
703       
704        set cmdline sed
705        if {$extended} {
706            lappend cmdline -E
707        }
708        set cmdline [concat $cmdline [list $pattern < $file >@ $tmpfd]]
709        if {[catch {eval exec $cmdline} error]} {
710                global errorInfo
711                ui_debug "$errorInfo"
712            ui_error "reinplace: $error"
713            file delete "$tmpfile"
714            close $tmpfd
715            return -code error "reinplace sed(1) failed"
716        }
717       
718        close $tmpfd
719       
720        set attributes [file attributes $file]
721        # We need to overwrite this file
722        if {[catch {file attributes $file -permissions u+w} error]} {
723                global errorInfo
724                ui_debug "$errorInfo"
725            ui_error "reinplace: $error"
726            file delete "$tmpfile"
727            return -code error "reinplace permissions failed"
728        }
729       
730        if {[catch {exec cp $tmpfile $file} error]} {
731                global errorInfo
732                ui_debug "$errorInfo"
733            ui_error "reinplace: $error"
734            file delete "$tmpfile"
735            return -code error "reinplace copy failed"
736        }
737       
738        for {set i 0} {$i < [llength attributes]} {incr i} {
739            set opt [lindex $attributes $i]
740            incr i
741            set arg [lindex $attributes $i]
742            file attributes $file $opt $arg
743        }
744       
745        file delete "$tmpfile"
746    }
747    return
748}
749
750# delete
751# file delete -force by itself doesn't handle directories properly
752# on systems older than Tiger. Lets recurse using fs-traverse instead
753proc delete {args} {
754    ui_debug "delete: $args"
755    fs-traverse -depth file $args {
756        file delete -force -- $file
757        continue
758    }
759}
760
761# touch
762# mimics the BSD touch command
763proc touch {args} {
764    while {[string match -* [lindex $args 0]]} {
765        set arg [string range [lindex $args 0] 1 end]
766        set args [lrange $args 1 end]
767        switch -- $arg {
768            a -
769            c -
770            m {set options($arg) yes}
771            r -
772            t {
773                set narg [lindex $args 0]
774                set args [lrange $args 1 end]
775                if {[string length $narg] == 0} {
776                    return -code error "touch: option requires an argument -- $arg"
777                }
778                set options($arg) $narg
779                set options(rt) $arg ;# later option overrides earlier
780            }
781            - break
782            default {return -code error "touch: illegal option -- $arg"}
783        }
784    }
785   
786    # parse the r/t options
787    if {[info exists options(rt)]} {
788        if {[string equal $options(rt) r]} {
789            # -r
790            # get atime/mtime from the file
791            if {[file exists $options(r)]} {
792                set atime [file atime $options(r)]
793                set mtime [file mtime $options(r)]
794            } else {
795                return -code error "touch: $options(r): No such file or directory"
796            }
797        } else {
798            # -t
799            # parse the time specification
800            # turn it into a CCyymmdd hhmmss
801            set timespec {^(?:(\d\d)?(\d\d))?(\d\d)(\d\d)(\d\d)(\d\d)(?:\.(\d\d))?$}
802            if {[regexp $timespec $options(t) {} CC YY MM DD hh mm SS]} {
803                if {[string length $YY] == 0} {
804                    set year [clock format [clock seconds] -format %Y]
805                } elseif {[string length $CC] == 0} {
806                    if {$YY >= 69 && $YY <= 99} {
807                        set year 19$YY
808                    } else {
809                        set year 20$YY
810                    }
811                } else {
812                    set year $CC$YY
813                }
814                if {[string length $SS] == 0} {
815                    set SS 00
816                }
817                set atime [clock scan "$year$MM$DD $hh$mm$SS"]
818                set mtime $atime
819            } else {
820                return -code error \
821                    {touch: out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]}
822            }
823        }
824    } else {
825        set atime [clock seconds]
826        set mtime [clock seconds]
827    }
828   
829    # do we have any files to process?
830    if {[llength $args] == 0} {
831        # print usage
832        ui_msg {usage: touch [-a] [-c] [-m] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...}
833        return
834    }
835   
836    foreach file $args {
837        if {![file exists $file]} {
838            if {[info exists options(c)]} {
839                continue
840            } else {
841                close [open $file w]
842            }
843        }
844       
845        if {[info exists options(a)] || ![info exists options(m)]} {
846            file atime $file $atime
847        }
848        if {[info exists options(m)] || ![info exists options(a)]} {
849            file mtime $file $mtime
850        }
851    }
852    return
853}
854
855# copy
856proc copy {args} {
857    eval file copy $args
858}
859
860# move
861proc move {args} {
862    eval file rename $args
863}
864
865# ln
866# Mimics the BSD ln implementation
867# ln [-f] [-h] [-s] [-v] source_file [target_file]
868# ln [-f] [-h] [-s] [-v] source_file ... target_dir
869proc ln {args} {
870    while {[string match -* [lindex $args 0]]} {
871        set arg [string range [lindex $args 0] 1 end]
872        if {[string length $arg] > 1} {
873            set remainder -[string range $arg 1 end]
874            set arg [string range $arg 0 0]
875            set args [lreplace $args 0 0 $remainder]
876        } else {
877            set args [lreplace $args 0 0]
878        }
879        switch -- $arg {
880            f -
881            h -
882            s -
883            v {set options($arg) yes}
884            - break
885            default {return -code error "ln: illegal option -- $arg"}
886        }
887    }
888   
889    if {[llength $args] == 0} {
890        ui_msg {usage: ln [-f] [-h] [-s] [-v] source_file [target_file]}
891        ui_msg {       ln [-f] [-h] [-s] [-v] file ... directory}
892        return
893    } elseif {[llength $args] == 1} {
894        set files $args
895        set target ./
896    } else {
897        set files [lrange $args 0 [expr [llength $args] - 2]]
898        set target [lindex $args end]
899    }
900   
901    foreach file $files {
902        if {[file isdirectory $file] && ![info exists options(s)]} {
903            return -code error "ln: $file: Is a directory"
904        }
905       
906        if {[file isdirectory $target] && ([file type $target] ne "link" || ![info exists options(h)])} {
907            set linktarget [file join $target [file tail $file]]
908        } else {
909            set linktarget $target
910        }
911       
912        if {![catch {file type $linktarget}]} {
913            if {[info exists options(f)]} {
914                file delete $linktarget
915            } else {
916                return -code error "ln: $linktarget: File exists"
917            }
918        }
919       
920        if {[llength $files] > 2} {
921            if {![file exists $linktarget]} {
922                return -code error "ln: $linktarget: No such file or directory"
923            } elseif {![file isdirectory $target]} {
924                # this error isn't striclty what BSD ln gives, but I think it's more useful
925                return -code error "ln: $target: Not a directory"
926            }
927        }
928       
929        if {[info exists options(v)]} {
930            ui_msg "ln: $linktarget -> $file"
931        }
932        if {[info exists options(s)]} {
933            symlink $file $linktarget
934        } else {
935            file link -hard $linktarget $file
936        }
937    }
938    return
939}
940
941# filefindbypath
942# Provides searching of the standard path for included files
943proc filefindbypath {fname} {
944    global distpath filesdir worksrcdir portpath
945   
946    if {[file readable $portpath/$fname]} {
947        return $portpath/$fname
948    } elseif {[file readable $portpath/$filesdir/$fname]} {
949        return $portpath/$filesdir/$fname
950    } elseif {[file readable $distpath/$fname]} {
951        return $distpath/$fname
952    }
953    return ""
954}
955
956# include
957# Source a file, looking for it along a standard search path.
958proc include {fname} {
959    set tgt [filefindbypath $fname]
960    if {[string length $tgt]} {
961        uplevel "source $tgt"
962    } else {
963        return -code error "Unable to find include file $fname"
964    }
965}
966
967# makeuserproc
968# This procedure re-writes the user-defined custom target to include
969# all the globals in its scope.  This is undeniably ugly, but I haven't
970# thought of any other way to do this.
971proc makeuserproc {name body} {
972    regsub -- "^\{(.*?)" $body "\{ \n foreach g \[info globals\] \{ \n global \$g \n \} \n \\1" body
973    eval "proc $name {} $body"
974}
975
976# backup
977# Operates on universal_filelist, creates universal_archlist
978# Save single-architecture files, a temporary location, preserving the original
979# directory structure.
980
981proc backup {arch} {
982    global universal_archlist universal_filelist workpath
983    lappend universal_archlist ${arch}
984    foreach file ${universal_filelist} {
985        set filedir [file dirname $file]
986        xinstall -d ${workpath}/${arch}/${filedir}
987        xinstall ${file} ${workpath}/${arch}/${filedir}
988    }
989}
990
991# lipo
992# Operates on universal_filelist, universal_archlist.
993# Run lipo(1) on a list of single-arch files.
994
995proc lipo {} {
996    global universal_archlist universal_filelist workpath
997    foreach file ${universal_filelist} {
998        xinstall -d [file dirname $file]
999        file delete ${file}
1000        set lipoSources ""
1001        foreach arch $universal_archlist {
1002            append lipoSources "-arch ${arch} ${workpath}/${arch}/${file} "
1003        }
1004        system "lipo ${lipoSources}-create -output ${file}"
1005    }
1006}
1007
1008
1009# unobscure maintainer addresses as used in Portfiles
1010# We allow two obscured forms:
1011#       (1) User name only with no domain:
1012#                       foo implies foo@macports.org
1013#       (2) Mangled name:
1014#                       subdomain.tld:username implies username@subdomain.tld
1015#
1016proc unobscure_maintainers { list } {
1017        set result {}
1018        foreach m $list {
1019                if {[string first "@" $m] < 0} {
1020                        if {[string first ":" $m] >= 0} {
1021                                set m [regsub -- "(.*):(.*)" $m "\\2@\\1"]
1022                        } else {
1023                                set m "$m@macports.org"
1024                        }
1025                }
1026                lappend result $m
1027        }
1028        return $result
1029}
1030
1031
1032
1033
1034########### Internal Dependency Manipulation Procedures ###########
1035
1036proc target_run {ditem} {
1037    global target_state_fd portpath portname portversion portrevision portvariants ports_force variations workpath ports_trace PortInfo
1038    set result 0
1039    set skipped 0
1040    set procedure [ditem_key $ditem procedure]
1041    if {$procedure != ""} {
1042        set name [ditem_key $ditem name]
1043       
1044        if {[ditem_contains $ditem init]} {
1045            set result [catch {[ditem_key $ditem init] $name} errstr]
1046        }
1047       
1048        if {$result == 0} {
1049                # Skip the step if required and explain why through ui_debug.
1050                # 1st case: the step was already done (as mentioned in the state file)
1051                if {[check_statefile target $name $target_state_fd]} {
1052                    ui_debug "Skipping completed $name ($portname)"
1053                    set skipped 1
1054                # 2nd case: the step is not to always be performed
1055                # and this exact port/version/revision/variants is already installed
1056                # and user didn't mention -f
1057                # and portfile didn't change since installation.
1058                } elseif {[ditem_key $ditem runtype] != "always"
1059                        && [registry_exists $portname $portversion $portrevision $portvariants]
1060                        && !([info exists ports_force] && $ports_force == "yes")} {
1061                                               
1062                        # Did the Portfile change since installation?
1063                        set regref [registry_open $portname $portversion $portrevision $portvariants]
1064                       
1065                        set installdate [registry_prop_retr $regref date]
1066                        if { $installdate != 0
1067                                && $installdate < [file mtime ${portpath}/Portfile]} {
1068                                ui_debug "Portfile changed since installation"
1069                        } else {
1070                                # Say we're skipping.
1071                                set skipped 1
1072                               
1073                                ui_debug "Skipping $name ($portname) since this port is already installed"
1074                        }
1075                       
1076                        # Something to close the registry entry may be called here, if it existed.
1077                # 3rd case: the same port/version/revision/Variants is already active
1078                # and user didn't mention -f
1079                } elseif {$name == "org.macports.activate"
1080                        && [registry_exists $portname $portversion $portrevision $portvariants]
1081                        && !([info exists ports_force] && $ports_force == "yes")} {
1082                       
1083                        # Is port active?
1084                        set regref [registry_open $portname $portversion $portrevision $portvariants]
1085                       
1086                        if { [registry_prop_retr $regref active] != 0 } {
1087                                # Say we're skipping.
1088                                set skipped 1
1089                               
1090                                ui_msg "Skipping $name ($portname $portvariants) since this port is already active"
1091                        }
1092                       
1093                }
1094                       
1095                # otherwise execute the task.
1096                if {$skipped == 0} {
1097                        set target [ditem_key $ditem provides]
1098                       
1099                        # Execute pre-run procedure
1100                        if {[ditem_contains $ditem prerun]} {
1101                        set result [catch {[ditem_key $ditem prerun] $name} errstr]
1102                        }               
1103                       
1104                        #start tracelib
1105                        if {($result ==0
1106                            && [info exists ports_trace]
1107                                && $ports_trace == "yes"
1108                                && $target != "clean")} {
1109                                trace_start $workpath
1110
1111                                # Enable the fence to prevent any creation/modification
1112                                # outside the sandbox.
1113                                if {$target != "activate"
1114                                        && $target != "archive"
1115                                        && $target != "fetch"
1116                                        && $target != "install"} {
1117                                        trace_enable_fence
1118                                }
1119                       
1120                                # collect deps
1121                               
1122                                # Don't check dependencies for extract (they're not honored
1123                                # anyway). This avoids warnings about bzip2.
1124                                if {$target != "extract"} {
1125                                        set depends {}
1126                                        set deptypes {}
1127                                       
1128                                        # Determine deptypes to look for based on target
1129                                        switch $target {
1130                                                configure       { set deptypes "depends_lib depends_build" }
1131                                               
1132                                                build           { set deptypes "depends_lib depends_build" }
1133                                               
1134                                                test            -
1135                                                destroot        -
1136                                                install         -
1137                                                archive         -
1138                                                pkg                     -
1139                                                mpkg            -
1140                                                rpm                     -
1141                                                srpm            -
1142                                                dpkg            -
1143                                                activate    -
1144                                                ""                      { set deptypes "depends_lib depends_build depends_run" }
1145                                        }
1146                                       
1147                                        # Gather the dependencies for deptypes
1148                                        foreach deptype $deptypes {
1149                                                # Add to the list of dependencies if the option exists and isn't empty.
1150                                                if {[info exists PortInfo($deptype)] && $PortInfo($deptype) != ""} {
1151                                                        set depends [concat $depends $PortInfo($deptype)]
1152                                                }
1153                                        }
1154       
1155                                        # Dependencies are in the form verb:[param:]port
1156                                        set depsPorts {}
1157                                        foreach depspec $depends {
1158                                                # grab the portname portion of the depspec
1159                                                set dep_portname [lindex [split $depspec :] end]
1160                                                lappend depsPorts $dep_portname
1161                                        }
1162                                       
1163                                        set portlist [recursive_collect_deps $portname $deptypes]
1164                                        #uniquer from http://aspn.activestate.com/ASPN/Cookbook/Tcl/Recipe/147663
1165                                        array set a [split "[join $portlist {::}]:" {:}]
1166                                        set depsPorts [array names a]
1167                                       
1168                                        if {[llength $deptypes] > 0} {tracelib setdeps $depsPorts}
1169                                }
1170                        }
1171                       
1172                        if {$result == 0} {
1173                        foreach pre [ditem_key $ditem pre] {
1174                                ui_debug "Executing $pre"
1175                                set result [catch {$pre $name} errstr]
1176                                if {$result != 0} { break }
1177                        }
1178                        }
1179                       
1180                        if {$result == 0} {
1181                        ui_debug "Executing $name ($portname)"
1182                        set result [catch {$procedure $name} errstr]
1183                        }
1184                       
1185                        if {$result == 0} {
1186                        foreach post [ditem_key $ditem post] {
1187                                ui_debug "Executing $post"
1188                                set result [catch {$post $name} errstr]
1189                                if {$result != 0} { break }
1190                        }
1191                        }
1192                        # Execute post-run procedure
1193                        if {[ditem_contains $ditem postrun] && $result == 0} {
1194                        set postrun [ditem_key $ditem postrun]
1195                        ui_debug "Executing $postrun"
1196                        set result [catch {$postrun $name} errstr]
1197                        }
1198
1199                        # Check dependencies & file creations outside workpath.
1200                        if {[info exists ports_trace]
1201                                && $ports_trace == "yes"
1202                                && $target!="clean"} {
1203                               
1204                                tracelib closesocket
1205                               
1206                                trace_check_violations
1207                               
1208                                # End of trace.
1209                                trace_stop
1210                        }
1211                }
1212        }
1213        if {$result == 0} {
1214                # Only write to state file if:
1215                # - we indeed performed this step.
1216                # - this step is not to always be performed
1217                # - this step must be written to file
1218                if {$skipped == 0
1219            && [ditem_key $ditem runtype] != "always"
1220            && [ditem_key $ditem state] != "no"} {
1221                write_statefile target $name $target_state_fd
1222            }
1223        } else {
1224            ui_error "Target $name returned: $errstr"
1225            set result 1
1226        }
1227       
1228    } else {
1229        ui_info "Warning: $name does not have a registered procedure"
1230        set result 1
1231    }
1232   
1233    return $result
1234}
1235
1236# recursive found depends for portname
1237# It isn't ideal, because it scan many ports multiple time
1238proc recursive_collect_deps {portname deptypes} \
1239{
1240        set res [mport_search ^$portname\$]
1241    if {[llength $res] < 2} \
1242        {
1243        return {}
1244    }
1245
1246        set depends {}
1247
1248        array set portinfo [lindex $res 1]
1249        foreach deptype $deptypes \
1250        {
1251                if {[info exists portinfo($deptype)] && $portinfo($deptype) != ""} \
1252                {
1253                        set depends [concat $depends $portinfo($deptype)]
1254                }
1255        }
1256       
1257        set portdeps {}
1258        foreach depspec $depends \
1259        {
1260                set portname [lindex [split $depspec :] end]
1261                lappend portdeps $portname
1262                set portdeps [concat $portdeps [recursive_collect_deps $portname $deptypes]]
1263        }
1264        return $portdeps
1265}
1266
1267
1268proc eval_targets {target} {
1269    global targets target_state_fd portname
1270    set dlist $targets
1271   
1272    # Select the subset of targets under $target
1273    if {$target != ""} {
1274        set matches [dlist_search $dlist provides $target]
1275       
1276        if {[llength $matches] > 0} {
1277            set dlist [dlist_append_dependents $dlist [lindex $matches 0] [list]]
1278            # Special-case 'all'
1279        } elseif {$target != "all"} {
1280            ui_error "unknown target: $target"
1281            return 1
1282        }
1283    }
1284   
1285    # Restore the state from a previous run.
1286    set target_state_fd [open_statefile]
1287   
1288    set dlist [dlist_eval $dlist "" target_run]
1289   
1290    if {[llength $dlist] > 0} {
1291        # somebody broke!
1292        set errstring "Warning: the following items did not execute (for $portname):"
1293        foreach ditem $dlist {
1294            append errstring " [ditem_key $ditem name]"
1295        }
1296        ui_info $errstring
1297        set result 1
1298    } else {
1299        set result 0
1300    }
1301   
1302    close $target_state_fd
1303    return $result
1304}
1305
1306# open_statefile
1307# open file to store name of completed targets
1308proc open_statefile {args} {
1309    global workpath worksymlink place_worksymlink portname portpath ports_ignore_older
1310   
1311    if {![file isdirectory $workpath]} {
1312        file mkdir $workpath
1313    }
1314    # flock Portfile
1315    set statefile [file join $workpath .macports.${portname}.state]
1316    if {[file exists $statefile]} {
1317        if {![file writable $statefile]} {
1318            return -code error "$statefile is not writable - check permission on port directory"
1319        }
1320        if {!([info exists ports_ignore_older] && $ports_ignore_older == "yes") && [file mtime $statefile] < [file mtime ${portpath}/Portfile]} {
1321            ui_msg "Portfile changed since last build; discarding previous state."
1322            #file delete $statefile
1323            exec rm -rf [file join $workpath]
1324            exec mkdir [file join $workpath]
1325        }
1326    }
1327
1328    # Create a symlink to the workpath for port authors
1329    if {[tbool place_worksymlink] && ![file isdirectory $worksymlink]} {
1330            exec ln -sf $workpath $worksymlink
1331    }
1332   
1333    set fd [open $statefile a+]
1334    if {[catch {flock $fd -exclusive -noblock} result]} {
1335        if {"$result" == "EAGAIN"} {
1336            ui_msg "Waiting for lock on $statefile"
1337        } elseif {"$result" == "EOPNOTSUPP"} {
1338            # Locking not supported, just return
1339            return $fd
1340        } else {
1341            return -code error "$result obtaining lock on $statefile"
1342        }
1343    }
1344    flock $fd -exclusive
1345    return $fd
1346}
1347
1348# check_statefile
1349# Check completed/selected state of target/variant $name
1350proc check_statefile {class name fd} {
1351    seek $fd 0
1352    while {[gets $fd line] >= 0} {
1353        if {$line == "$class: $name"} {
1354            return 1
1355        }
1356    }
1357    return 0
1358}
1359
1360# write_statefile
1361# Set target $name completed in the state file
1362proc write_statefile {class name fd} {
1363    if {[check_statefile $class $name $fd]} {
1364        return 0
1365    }
1366    seek $fd 0 end
1367    puts $fd "$class: $name"
1368    flush $fd
1369}
1370
1371# check_statefile_variants
1372# Check that recorded selection of variants match the current selection
1373proc check_statefile_variants {variations fd} {
1374    upvar $variations upvariations
1375   
1376    seek $fd 0
1377    while {[gets $fd line] >= 0} {
1378        if {[regexp "variant: (.*)" $line match name]} {
1379            set oldvariations([string range $name 1 end]) [string range $name 0 0]
1380        }
1381    }
1382   
1383    set mismatch 0
1384    if {[array size oldvariations] > 0} {
1385        if {[array size oldvariations] != [array size upvariations]} {
1386            set mismatch 1
1387        } else {
1388            foreach key [array names upvariations *] {
1389                if {![info exists oldvariations($key)] || $upvariations($key) != $oldvariations($key)} {
1390                    set mismatch 1
1391                    break
1392                }
1393            }
1394        }
1395    }
1396   
1397    return $mismatch
1398}
1399
1400########### Port Variants ###########
1401
1402# Each variant which provides a subset of the requested variations
1403# will be chosen.  Returns a list of the selected variants.
1404proc choose_variants {dlist variations} {
1405    upvar $variations upvariations
1406   
1407    set selected [list]
1408   
1409    foreach ditem $dlist {
1410        # Enumerate through the provides, tallying the pros and cons.
1411        set pros 0
1412        set cons 0
1413        set ignored 0
1414        foreach flavor [ditem_key $ditem provides] {
1415            if {[info exists upvariations($flavor)]} {
1416                if {$upvariations($flavor) == "+"} {
1417                    incr pros
1418                } elseif {$upvariations($flavor) == "-"} {
1419                    incr cons
1420                }
1421            } else {
1422                incr ignored
1423            }
1424        }
1425       
1426        if {$cons > 0} { continue }
1427       
1428        if {$pros > 0 && $ignored == 0} {
1429            lappend selected $ditem
1430        }
1431    }
1432    return $selected
1433}
1434
1435proc variant_run {ditem} {
1436    set name [ditem_key $ditem name]
1437    ui_debug "Executing variant $name provides [ditem_key $ditem provides]"
1438   
1439    # test for conflicting variants
1440    foreach v [ditem_key $ditem conflicts] {
1441        if {[variant_isset $v]} {
1442            ui_error "Variant $name conflicts with $v"
1443            return 1
1444        }
1445    }
1446   
1447    # execute proc with same name as variant.
1448    if {[catch "variant-${name}" result]} {
1449        global errorInfo
1450        ui_debug "$errorInfo"
1451        ui_error "Error executing $name: $result"
1452        return 1
1453    }
1454    return 0
1455}
1456
1457# Given a list of variant specifications, return a canonical string form
1458# for the registry.
1459    # The strategy is as follows: regardless of how some collection of variants
1460    # was turned on or off, a particular instance of the port is uniquely
1461    # characterized by the set of variants that are *on*. Thus, record those
1462    # variants in a string in a standard order as +var1+var2 etc.
1463    # We can skip the platform and architecture since those are always
1464    # requested.  XXX: Is that really true? What if the user explicitly
1465    # overrides the platform and architecture variants? Will the registry get
1466    # bollixed? It would seem safer to me to just leave in all the variants that
1467    # are on, but for now I'm just leaving the skipping code as it was in the
1468    # previous version.
1469proc canonicalize_variants {variants} {
1470    array set vara $variants
1471    set result ""
1472    set vlist [lsort -ascii [array names vara]]
1473    foreach v $vlist {
1474        if {$vara($v) == "+" && $v ne [option os.platform] && $v ne [option os.arch]} {
1475            append result +$v
1476        }
1477    }
1478    return $result
1479}
1480
1481proc eval_variants {variations} {
1482    global all_variants ports_force PortInfo portvariants
1483    set dlist $all_variants
1484    upvar $variations upvariations
1485    set chosen [choose_variants $dlist upvariations]
1486        set portname $PortInfo(name)
1487
1488        # Check to make sure the requested variations are available with this
1489        # port, if one is not, warn the user and remove the variant from the
1490        # array.
1491        foreach key [array names upvariations *] {
1492                if {![info exists PortInfo(variants)] ||
1493                        [lsearch $PortInfo(variants) $key] == -1} {
1494                        ui_debug "Requested variant $key is not provided by port $portname."
1495                        array unset upvariations $key
1496                }
1497        }
1498
1499    # now that we've selected variants, change all provides [a b c] to [a-b-c]
1500    # this will eliminate ambiguity between item a, b, and a-b while fulfilling requirments.
1501    #foreach obj $dlist {
1502    #    $obj set provides [list [join [$obj get provides] -]]
1503    #}
1504   
1505    set newlist [list]
1506    foreach variant $chosen {
1507                set newlist [dlist_append_dependents $dlist $variant $newlist]
1508    }
1509   
1510    set dlist [dlist_eval $newlist "" variant_run]
1511    if {[llength $dlist] > 0} {
1512                return 1
1513    }
1514
1515    # Now compute the true active array of variants. Note we do not
1516    # change upvariations any further, since that represents the
1517    # requested list of variations; but the registry for consistency
1518    # must encode the actual list of variants evaluated, however that
1519    # came to pass (dependencies, defaults, etc.) While we're at it,
1520    # it's convenient to check for inconsistent requests for
1521    # variations, namely foo +requirer -required where the 'requirer'
1522    # variant requires the 'required' one.
1523    array set activevariants [list]
1524    foreach dvar $newlist {
1525        set thevar [ditem_key $dvar provides]
1526        if {[info exists upvariations($thevar)] && $upvariations($thevar) eq "-"} {
1527            set chosenlist ""
1528            foreach choice $chosen {
1529                lappend chosenlist +[ditem_key $choice provides]
1530            }
1531            ui_error "Inconsistent variant specification: $portname variant +$thevar is required by at least one of $chosenlist, but specified -$thevar"
1532            return 1
1533        }
1534        set activevariants($thevar) "+"
1535    }
1536
1537    # Record a canonical variant string, used e.g. in accessing the registry
1538    set portvariants [canonicalize_variants [array get activevariants]]
1539
1540    # XXX: I suspect it would actually work better in the following
1541    # block to record the activevariants in the statefile rather than
1542    # the upvariations, since as far as I can see different sets of
1543    # upvariations which amount to the same activevariants in the end
1544    # can share all aspects of the build. But I'm leaving this alone
1545    # for the time being, so that someone with more extensive
1546    # experience can examine the idea before putting it into
1547    # action. -- GlenWhitney
1548
1549    return 0
1550}
1551
1552proc check_variants {variations target} {
1553    global ports_force PortInfo
1554    upvar $variations upvariations
1555    set result 0
1556    set portname $PortInfo(name)
1557   
1558    # Make sure the variations match those stored in the statefile.
1559    # If they don't match, print an error indicating a 'port clean'
1560    # should be performed. 
1561    # - Skip this test if the statefile is empty.
1562    # - Skip this test if performing a clean or submit.
1563    # - Skip this test if ports_force was specified.
1564   
1565    if { [lsearch "clean submit" $target] < 0 &&
1566                !([info exists ports_force] && $ports_force == "yes")} {
1567               
1568                set state_fd [open_statefile]
1569       
1570                if {[check_statefile_variants upvariations $state_fd]} {
1571                        ui_error "Requested variants do not match original selection.\nPlease perform 'port clean $portname' or specify the force option."
1572                        set result 1
1573                } else {
1574                        # Write variations out to the statefile
1575                        foreach key [array names upvariations *] {
1576                        write_statefile variant $upvariations($key)$key $state_fd
1577                        }
1578                }
1579               
1580                close $state_fd
1581    }
1582   
1583    return $result
1584}
1585
1586# Target class definition.
1587
1588# constructor for target object
1589proc target_new {name procedure} {
1590    global targets
1591    set ditem [ditem_create]
1592   
1593    ditem_key $ditem name $name
1594    ditem_key $ditem procedure $procedure
1595   
1596    lappend targets $ditem
1597   
1598    return $ditem
1599}
1600
1601proc target_provides {ditem args} {
1602    global targets
1603    # Register the pre-/post- hooks for use in Portfile.
1604    # Portfile syntax: pre-fetch { puts "hello world" }
1605    # User-code exceptions are caught and returned as a result of the target.
1606    # Thus if the user code breaks, dependent targets will not execute.
1607    foreach target $args {
1608        set origproc [ditem_key $ditem procedure]
1609        set ident [ditem_key $ditem name]
1610        if {[info commands $target] != ""} {
1611            ui_debug "$ident registered provides '$target', a pre-existing procedure. Target override will not be provided"
1612        } else {
1613            proc $target {args} "
1614                variable proc_index
1615                set proc_index \[llength \[ditem_key $ditem proc\]\]
1616                ditem_key $ditem procedure proc-${ident}-${target}-\${proc_index}
1617                proc proc-${ident}-${target}-\${proc_index} {name} \"
1618                    if {\\\[catch userproc-${ident}-${target}-\${proc_index} result\\\]} {
1619                        return -code error \\\$result
1620                    } else {
1621                        return 0
1622                    }
1623                \"
1624                proc do-$target {} { $origproc $target }
1625                makeuserproc userproc-${ident}-${target}-\${proc_index} \$args
1626            "
1627        }
1628        proc pre-$target {args} "
1629            variable proc_index
1630            set proc_index \[llength \[ditem_key $ditem pre\]\]
1631            ditem_append $ditem pre proc-pre-${ident}-${target}-\${proc_index}
1632            proc proc-pre-${ident}-${target}-\${proc_index} {name} \"
1633                if {\\\[catch userproc-pre-${ident}-${target}-\${proc_index} result\\\]} {
1634                    return -code error \\\$result
1635                } else {
1636                    return 0
1637                }
1638            \"
1639            makeuserproc userproc-pre-${ident}-${target}-\${proc_index} \$args
1640        "
1641        proc post-$target {args} "
1642            variable proc_index
1643            set proc_index \[llength \[ditem_key $ditem post\]\]
1644            ditem_append $ditem post proc-post-${ident}-${target}-\${proc_index}
1645            proc proc-post-${ident}-${target}-\${proc_index} {name} \"
1646                if {\\\[catch userproc-post-${ident}-${target}-\${proc_index} result\\\]} {
1647                    return -code error \\\$result
1648                } else {
1649                    return 0
1650                }
1651            \"
1652            makeuserproc userproc-post-${ident}-${target}-\${proc_index} \$args
1653        "
1654    }
1655    eval ditem_append $ditem provides $args
1656}
1657
1658proc target_requires {ditem args} {
1659    eval ditem_append $ditem requires $args
1660}
1661
1662proc target_uses {ditem args} {
1663    eval ditem_append $ditem uses $args
1664}
1665
1666proc target_deplist {ditem args} {
1667    eval ditem_append $ditem deplist $args
1668}
1669
1670proc target_prerun {ditem args} {
1671    eval ditem_append $ditem prerun $args
1672}
1673
1674proc target_postrun {ditem args} {
1675    eval ditem_append $ditem postrun $args
1676}
1677
1678proc target_runtype {ditem args} {
1679    eval ditem_append $ditem runtype $args
1680}
1681
1682proc target_state {ditem args} {
1683    eval ditem_append $ditem state $args
1684}
1685
1686proc target_init {ditem args} {
1687    eval ditem_append $ditem init $args
1688}
1689
1690##### variant class #####
1691
1692# constructor for variant objects
1693proc variant_new {name} {
1694    set ditem [ditem_create]
1695    ditem_key $ditem name $name
1696    return $ditem
1697}
1698
1699proc handle_default_variants {option action {value ""}} {
1700    global variations
1701    switch -regex $action {
1702        set|append {
1703            foreach v $value {
1704                if {[regexp {([-+])([-A-Za-z0-9_]+)} $v whole val variant]} {
1705                    if {![info exists variations($variant)]} {
1706                        set variations($variant) $val
1707                    }
1708                }
1709            }
1710        }
1711        delete {
1712            # xxx
1713        }
1714    }
1715}
1716
1717
1718# builds the specified port (looked up in the index) to the specified target
1719# doesn't yet support options or variants...
1720# newworkpath defines the port's workpath - useful for when one port relies
1721# on the source, etc, of another
1722proc portexec_int {portname target {newworkpath ""}} {
1723    ui_debug "Executing $target ($portname)"
1724    set variations [list]
1725    if {$newworkpath == ""} {
1726        array set options [list]
1727    } else {
1728        set options(workpath) ${newworkpath}
1729    }
1730    # Escape regex special characters
1731    regsub -all "(\\(){1}|(\\)){1}|(\\{1}){1}|(\\+){1}|(\\{1}){1}|(\\{){1}|(\\}){1}|(\\^){1}|(\\$){1}|(\\.){1}|(\\\\){1}" $portname "\\\\&" search_string
1732   
1733    set res [mport_search ^$search_string\$]
1734    if {[llength $res] < 2} {
1735        ui_error "Dependency $portname not found"
1736        return -1
1737    }
1738   
1739    array set portinfo [lindex $res 1]
1740    set porturl $portinfo(porturl)
1741    if {[catch {set worker [mport_open $porturl [array get options] $variations]} result]} {
1742                global errorInfo
1743                ui_debug "$errorInfo"
1744        ui_error "Opening $portname $target failed: $result"
1745        return -1
1746    }
1747    if {[catch {mport_exec $worker $target} result] || $result != 0} {
1748                global errorInfo
1749                ui_debug "$errorInfo"
1750        ui_error "Execution $portname $target failed: $result"
1751        mport_close $worker
1752        return -1
1753    }
1754    mport_close $worker
1755   
1756    return 0
1757}
1758
1759# portfile primitive that calls portexec_int with newworkpath == ${workpath}
1760proc portexec {portname target} {
1761    global workpath
1762    return [portexec_int $portname $target $workpath]
1763}
1764
1765proc adduser {name args} {
1766    global os.platform
1767    set passwd {*}
1768    set uid [nextuid]
1769    set gid [existsgroup nogroup]
1770    set realname ${name}
1771    set home /dev/null
1772    set shell /dev/null
1773   
1774    foreach arg $args {
1775        if {[regexp {([a-z]*)=(.*)} $arg match key val]} {
1776            regsub -all " " ${val} "\\ " val
1777            set $key $val
1778        }
1779    }
1780   
1781    if {[existsuser ${name}] != 0 || [existsuser ${uid}] != 0} {
1782        return
1783    }
1784   
1785    if {${os.platform} eq "darwin"} {
1786        exec dscl . -create /Users/${name} Password ${passwd}
1787        exec dscl . -create /Users/${name} UniqueID ${uid}
1788        exec dscl . -create /Users/${name} PrimaryGroupID ${gid}
1789        exec dscl . -create /Users/${name} RealName ${realname}
1790        exec dscl . -create /Users/${name} NFSHomeDirectory ${home}
1791        exec dscl . -create /Users/${name} UserShell ${shell}
1792    } else {
1793        # XXX adduser is only available for darwin, add more support here
1794        ui_warn "WARNING: adduser is not implemented on ${os.platform}."
1795        ui_warn "The requested user was not created."
1796    }
1797}
1798
1799proc addgroup {name args} {
1800    global os.platform
1801    set gid [nextgid]
1802    set realname ${name}
1803    set passwd {*}
1804    set users ""
1805   
1806    foreach arg $args {
1807        if {[regexp {([a-z]*)=(.*)} $arg match key val]} {
1808            regsub -all " " ${val} "\\ " val
1809            set $key $val
1810        }
1811    }
1812   
1813    if {[existsgroup ${name}] != 0 || [existsgroup ${gid}] != 0} {
1814        return
1815    }
1816   
1817    if {${os.platform} eq "darwin"} {
1818        exec dscl . -create /Groups/${name} Password ${passwd}
1819        exec dscl . -create /Groups/${name} RealName ${realname}
1820        exec dscl . -create /Groups/${name} PrimaryGroupID ${gid}
1821        if {${users} ne ""} {
1822            exec dscl . -create /Groups/${name} GroupMembership ${users}
1823        }
1824    } else {
1825        # XXX addgroup is only available for darwin, add more support here
1826        ui_warn "WARNING: addgroup is not implemented on ${os.platform}."
1827        ui_warn "The requested group was not created."
1828    }
1829}
1830
1831# proc to calculate size of a directory
1832# moved here from portpkg.tcl
1833proc dirSize {dir} {
1834    set size    0;
1835    foreach file [readdir $dir] {
1836        if {[file type [file join $dir $file]] == "link" } {
1837            continue
1838        }
1839        if {[file isdirectory [file join $dir $file]]} {
1840            incr size [dirSize [file join $dir $file]]
1841        } else {
1842            incr size [file size [file join $dir $file]];
1843        }
1844    }
1845    return $size;
1846}
1847
1848# check for a binary in the path
1849# returns an error code if it can not be found
1850proc binaryInPath {binary} {
1851    global env
1852    foreach dir [split $env(PATH) :] { 
1853        if {[file executable [file join $dir $binary]]} {
1854            return [file join $dir $binary]
1855        }
1856    }
1857   
1858    return -code error [format [msgcat::mc "Failed to locate '%s' in path: '%s'"] $binary $env(PATH)];
1859}
1860
1861# Set the UI prefix to something standard (so it can be grepped for in output)
1862proc set_ui_prefix {} {
1863        global UI_PREFIX env
1864        if {[info exists env(UI_PREFIX)]} {
1865                set UI_PREFIX $env(UI_PREFIX)
1866        } else {
1867                set UI_PREFIX "---> "
1868        }
1869}
1870
1871# Use a specified group/version.
1872proc PortGroup {group version} {
1873        global portresourcepath
1874
1875        set groupFile ${portresourcepath}/group/${group}-${version}.tcl
1876
1877        if {[file exists $groupFile]} {
1878                uplevel "source $groupFile"
1879        } else {
1880                ui_warn "Group file could not be located."
1881        }
1882}
1883
1884# check if archive type is supported by current system
1885# returns an error code if it is not
1886proc archiveTypeIsSupported {type} {
1887    global os.platform os.version
1888        set errmsg ""
1889        switch -regex $type {
1890                cp(io|gz) {
1891                        set pax "pax"
1892                        if {[catch {set pax [binaryInPath $pax]} errmsg] == 0} {
1893                                if {[regexp {z$} $type]} {
1894                                        set gzip "gzip"
1895                                        if {[catch {set gzip [binaryInPath $gzip]} errmsg] == 0} {
1896                                                return 0
1897                                        }
1898                                } else {
1899                                        return 0
1900                                }
1901                        }
1902                }
1903                t(ar|bz|gz) {
1904                        set tar "tar"
1905                        if {[catch {set tar [binaryInPath $tar]} errmsg] == 0} {
1906                                if {[regexp {z2?$} $type]} {
1907                                        if {[regexp {bz2?$} $type]} {
1908                                                set gzip "bzip2"
1909                                        } else {
1910                                                set gzip "gzip"
1911                                        }
1912                                        if {[catch {set gzip [binaryInPath $gzip]} errmsg] == 0} {
1913                                                return 0
1914                                        }
1915                                } else {
1916                                        return 0
1917                                }
1918                        }
1919                }
1920                xar {
1921                        set xar "xar"
1922                        if {[catch {set xar [binaryInPath $xar]} errmsg] == 0} {
1923                                return 0
1924                        }
1925                }
1926                zip {
1927                        set zip "zip"
1928                        if {[catch {set zip [binaryInPath $zip]} errmsg] == 0} {
1929                                set unzip "unzip"
1930                                if {[catch {set unzip [binaryInPath $unzip]} errmsg] == 0} {
1931                                        return 0
1932                                }
1933                        }
1934                }
1935                default {
1936                        return -code error [format [msgcat::mc "Invalid port archive type '%s' specified!"] $type]
1937                }
1938        }
1939        return -code error [format [msgcat::mc "Unsupported port archive type '%s': %s"] $type $errmsg]
1940}
1941
1942
1943# simple wrapper for calling merge.rb - for creating universal binaries (etc.)
1944# this is intended to be called during destroot, e.g. 'merge i386 ppc'
1945# this will merge the directories $destroot/i386 & $destroot/ppc into $destroot
1946proc merge args {
1947        global workpath prefix destroot
1948        set all_args "-i ${destroot} -o ${destroot} -v debug"
1949        set architectures ""
1950
1951        # check existance of given architectures in $destroot
1952        foreach arg $args {
1953                if [file exists ${destroot}/${arg}] {
1954                        ui_debug "found architecture '${arg}'"
1955                        set architectures "${architectures} $arg"
1956                } else {
1957                        ui_error "could not find directory for architecture '${arg}'"
1958                }
1959        }
1960        set all_args "${all_args} ${architectures}"
1961
1962        # call merge.rb
1963        ui_debug "executing merge.rb with '${all_args}'"
1964        set fullcmdstring "${prefix}/bin/merge.rb $all_args"
1965        set code [catch {system $fullcmdstring} result]
1966        ui_debug "merge returned: '${result}'"
1967
1968        foreach arg ${architectures} {
1969                ui_debug "removing arch directory \"$arg\""
1970                file delete -force ${destroot}/${arg}
1971        }
1972
1973        return -code $code $result
1974}
1975
Note: See TracBrowser for help on using the repository browser.