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

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

ChangeLog: consolidate entries for Leopard environment variable issue

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