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

Last change on this file since 41249 was 41249, checked in by pguyot@…, 9 years ago

Add support for +universal variants with the xcode portgroup

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 69.7 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 41249 2008-10-29 09:17:40Z pguyot@kallisys.net $
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    while 1 {
722        set arg [lindex $args 0]
723        if {[string index $arg 0] eq "-"} {
724            set args [lrange $args 1 end]
725            switch [string range $arg 1 end] {
726                E {
727                    set extended 1
728                }
729                - {
730                    break
731                }
732                default {
733                    error "reinplace: unknown flag '$arg'"
734                }
735            }
736        } else {
737            break
738        }
739    }
740    if {[llength $args] < 2} {
741        error "reinplace ?-E? pattern file ..."
742    }
743    set pattern [lindex $args 0]
744    set files [lrange $args 1 end]
745   
746    foreach file $files {
747        if {[catch {set tmpfile [mkstemp "/tmp/[file tail $file].sed.XXXXXXXX"]} error]} {
748            global errorInfo
749            ui_debug "$errorInfo"
750            ui_error "reinplace: $error"
751            return -code error "reinplace failed"
752        } else {
753            # Extract the Tcl Channel number
754            set tmpfd [lindex $tmpfile 0]
755            # Set tmpfile to only the file name
756            set tmpfile [lindex $tmpfile 1]
757        }
758   
759        set cmdline $portutil::autoconf::sed_command
760        if {$extended} {
761            if {$portutil::autoconf::sed_ext_flag == "N/A"} {
762                ui_debug "sed extended regexp not available"
763                return -code error "reinplace sed(1) too old"
764            }
765            lappend cmdline $portutil::autoconf::sed_ext_flag
766        }
767        set cmdline [concat $cmdline [list $pattern < $file >@ $tmpfd]]
768        if {[catch {eval exec $cmdline} error]} {
769            global errorInfo
770            ui_debug "$errorInfo"
771            ui_error "reinplace: $error"
772            file delete "$tmpfile"
773            close $tmpfd
774            return -code error "reinplace sed(1) failed"
775        }
776   
777        close $tmpfd
778   
779        set attributes [file attributes $file]
780        # We need to overwrite this file
781        if {[catch {file attributes $file -permissions u+w} error]} {
782            global errorInfo
783            ui_debug "$errorInfo"
784            ui_error "reinplace: $error"
785            file delete "$tmpfile"
786            return -code error "reinplace permissions failed"
787        }
788   
789        if {[catch {exec cp $tmpfile $file} error]} {
790            global errorInfo
791            ui_debug "$errorInfo"
792            ui_error "reinplace: $error"
793            file delete "$tmpfile"
794            return -code error "reinplace copy failed"
795        }
796   
797        for {set i 0} {$i < [llength attributes]} {incr i} {
798            set opt [lindex $attributes $i]
799            incr i
800            set arg [lindex $attributes $i]
801            file attributes $file $opt $arg
802        }
803       
804        file delete "$tmpfile"
805    }
806    return
807}
808
809# delete
810# file delete -force by itself doesn't handle directories properly
811# on systems older than Tiger. Lets recurse using fs-traverse instead
812proc delete {args} {
813    ui_debug "delete: $args"
814    fs-traverse -depth file $args {
815        file delete -force -- $file
816        continue
817    }
818}
819
820# touch
821# mimics the BSD touch command
822proc touch {args} {
823    while {[string match -* [lindex $args 0]]} {
824        set arg [string range [lindex $args 0] 1 end]
825        set args [lrange $args 1 end]
826        switch -- $arg {
827            a -
828            c -
829            m {set options($arg) yes}
830            r -
831            t {
832                set narg [lindex $args 0]
833                set args [lrange $args 1 end]
834                if {[string length $narg] == 0} {
835                    return -code error "touch: option requires an argument -- $arg"
836                }
837                set options($arg) $narg
838                set options(rt) $arg ;# later option overrides earlier
839            }
840            - break
841            default {return -code error "touch: illegal option -- $arg"}
842        }
843    }
844   
845    # parse the r/t options
846    if {[info exists options(rt)]} {
847        if {[string equal $options(rt) r]} {
848            # -r
849            # get atime/mtime from the file
850            if {[file exists $options(r)]} {
851                set atime [file atime $options(r)]
852                set mtime [file mtime $options(r)]
853            } else {
854                return -code error "touch: $options(r): No such file or directory"
855            }
856        } else {
857            # -t
858            # parse the time specification
859            # turn it into a CCyymmdd hhmmss
860            set timespec {^(?:(\d\d)?(\d\d))?(\d\d)(\d\d)(\d\d)(\d\d)(?:\.(\d\d))?$}
861            if {[regexp $timespec $options(t) {} CC YY MM DD hh mm SS]} {
862                if {[string length $YY] == 0} {
863                    set year [clock format [clock seconds] -format %Y]
864                } elseif {[string length $CC] == 0} {
865                    if {$YY >= 69 && $YY <= 99} {
866                        set year 19$YY
867                    } else {
868                        set year 20$YY
869                    }
870                } else {
871                    set year $CC$YY
872                }
873                if {[string length $SS] == 0} {
874                    set SS 00
875                }
876                set atime [clock scan "$year$MM$DD $hh$mm$SS"]
877                set mtime $atime
878            } else {
879                return -code error \
880                    {touch: out of range or illegal time specification: [[CC]YY]MMDDhhmm[.SS]}
881            }
882        }
883    } else {
884        set atime [clock seconds]
885        set mtime [clock seconds]
886    }
887   
888    # do we have any files to process?
889    if {[llength $args] == 0} {
890        # print usage
891        ui_msg {usage: touch [-a] [-c] [-m] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...}
892        return
893    }
894   
895    foreach file $args {
896        if {![file exists $file]} {
897            if {[info exists options(c)]} {
898                continue
899            } else {
900                close [open $file w]
901            }
902        }
903       
904        if {[info exists options(a)] || ![info exists options(m)]} {
905            file atime $file $atime
906        }
907        if {[info exists options(m)] || ![info exists options(a)]} {
908            file mtime $file $mtime
909        }
910    }
911    return
912}
913
914# copy
915proc copy {args} {
916    eval file copy $args
917}
918
919# move
920proc move {args} {
921    eval file rename $args
922}
923
924# ln
925# Mimics the BSD ln implementation
926# ln [-f] [-h] [-s] [-v] source_file [target_file]
927# ln [-f] [-h] [-s] [-v] source_file ... target_dir
928proc ln {args} {
929    while {[string match -* [lindex $args 0]]} {
930        set arg [string range [lindex $args 0] 1 end]
931        if {[string length $arg] > 1} {
932            set remainder -[string range $arg 1 end]
933            set arg [string range $arg 0 0]
934            set args [lreplace $args 0 0 $remainder]
935        } else {
936            set args [lreplace $args 0 0]
937        }
938        switch -- $arg {
939            f -
940            h -
941            s -
942            v {set options($arg) yes}
943            - break
944            default {return -code error "ln: illegal option -- $arg"}
945        }
946    }
947   
948    if {[llength $args] == 0} {
949        ui_msg {usage: ln [-f] [-h] [-s] [-v] source_file [target_file]}
950        ui_msg {       ln [-f] [-h] [-s] [-v] file ... directory}
951        return
952    } elseif {[llength $args] == 1} {
953        set files $args
954        set target ./
955    } else {
956        set files [lrange $args 0 [expr [llength $args] - 2]]
957        set target [lindex $args end]
958    }
959   
960    foreach file $files {
961        if {[file isdirectory $file] && ![info exists options(s)]} {
962            return -code error "ln: $file: Is a directory"
963        }
964       
965        if {[file isdirectory $target] && ([file type $target] ne "link" || ![info exists options(h)])} {
966            set linktarget [file join $target [file tail $file]]
967        } else {
968            set linktarget $target
969        }
970       
971        if {![catch {file type $linktarget}]} {
972            if {[info exists options(f)]} {
973                file delete $linktarget
974            } else {
975                return -code error "ln: $linktarget: File exists"
976            }
977        }
978       
979        if {[llength $files] > 2} {
980            if {![file exists $linktarget]} {
981                return -code error "ln: $linktarget: No such file or directory"
982            } elseif {![file isdirectory $target]} {
983                # this error isn't striclty what BSD ln gives, but I think it's more useful
984                return -code error "ln: $target: Not a directory"
985            }
986        }
987       
988        if {[info exists options(v)]} {
989            ui_msg "ln: $linktarget -> $file"
990        }
991        if {[info exists options(s)]} {
992            symlink $file $linktarget
993        } else {
994            file link -hard $linktarget $file
995        }
996    }
997    return
998}
999
1000# filefindbypath
1001# Provides searching of the standard path for included files
1002proc filefindbypath {fname} {
1003    global distpath filesdir worksrcdir portpath
1004   
1005    if {[file readable $portpath/$fname]} {
1006        return $portpath/$fname
1007    } elseif {[file readable $portpath/$filesdir/$fname]} {
1008        return $portpath/$filesdir/$fname
1009    } elseif {[file readable $distpath/$fname]} {
1010        return $distpath/$fname
1011    }
1012    return ""
1013}
1014
1015# include
1016# Source a file, looking for it along a standard search path.
1017proc include {fname} {
1018    set tgt [filefindbypath $fname]
1019    if {[string length $tgt]} {
1020        uplevel "source $tgt"
1021    } else {
1022        return -code error "Unable to find include file $fname"
1023    }
1024}
1025
1026# makeuserproc
1027# This procedure re-writes the user-defined custom target to include
1028# all the globals in its scope.  This is undeniably ugly, but I haven't
1029# thought of any other way to do this.
1030proc makeuserproc {name body} {
1031    regsub -- "^\{(.*?)" $body "\{ \n foreach g \[info globals\] \{ \n global \$g \n \} \n \\1" body
1032    eval "proc $name {} $body"
1033}
1034
1035# backup
1036# Operates on universal_filelist, creates universal_archlist
1037# Save single-architecture files, a temporary location, preserving the original
1038# directory structure.
1039
1040proc backup {arch} {
1041    global universal_archlist universal_filelist workpath
1042    lappend universal_archlist ${arch}
1043    foreach file ${universal_filelist} {
1044        set filedir [file dirname $file]
1045        xinstall -d ${workpath}/${arch}/${filedir}
1046        xinstall ${file} ${workpath}/${arch}/${filedir}
1047    }
1048}
1049
1050# lipo
1051# Operates on universal_filelist, universal_archlist.
1052# Run lipo(1) on a list of single-arch files.
1053
1054proc lipo {} {
1055    global universal_archlist universal_filelist workpath
1056    foreach file ${universal_filelist} {
1057        xinstall -d [file dirname $file]
1058        file delete ${file}
1059        set lipoSources ""
1060        foreach arch $universal_archlist {
1061            append lipoSources "-arch ${arch} ${workpath}/${arch}/${file} "
1062        }
1063        system "lipo ${lipoSources}-create -output ${file}"
1064    }
1065}
1066
1067
1068# unobscure maintainer addresses as used in Portfiles
1069# We allow two obscured forms:
1070#   (1) User name only with no domain:
1071#           foo implies foo@macports.org
1072#   (2) Mangled name:
1073#           subdomain.tld:username implies username@subdomain.tld
1074#
1075proc unobscure_maintainers { list } {
1076    set result {}
1077    foreach m $list {
1078        if {[string first "@" $m] < 0} {
1079            if {[string first ":" $m] >= 0} {
1080                set m [regsub -- "(.*):(.*)" $m "\\2@\\1"]
1081            } else {
1082                set m "$m@macports.org"
1083            }
1084        }
1085        lappend result $m
1086    }
1087    return $result
1088}
1089
1090
1091
1092
1093########### Internal Dependency Manipulation Procedures ###########
1094
1095proc target_run {ditem} {
1096    global target_state_fd portpath portname portversion portrevision portvariants ports_force variations workpath ports_trace PortInfo
1097    set result 0
1098    set skipped 0
1099    set procedure [ditem_key $ditem procedure]
1100           
1101    if {[ditem_key $ditem state] != "no"} {
1102        set target_state_fd [open_statefile]
1103    }
1104       
1105    if {$procedure != ""} {
1106        set name [ditem_key $ditem name]
1107   
1108        if {[ditem_contains $ditem init]} {
1109            set result [catch {[ditem_key $ditem init] $name} errstr]
1110        }
1111   
1112        if {$result == 0} {
1113            # Skip the step if required and explain why through ui_debug.
1114            # 1st case: the step was already done (as mentioned in the state file)
1115            if {[ditem_key $ditem state] != "no"
1116                    && [check_statefile target $name $target_state_fd]} {
1117                ui_debug "Skipping completed $name ($portname)"
1118                set skipped 1
1119            # 2nd case: the step is not to always be performed
1120            # and this exact port/version/revision/variants is already installed
1121            # and user didn't mention -f
1122            # and portfile didn't change since installation.
1123            } elseif {[ditem_key $ditem runtype] != "always"
1124              && [registry_exists $portname $portversion $portrevision $portvariants]
1125              && !([info exists ports_force] && $ports_force == "yes")} {
1126                       
1127                # Did the Portfile change since installation?
1128                set regref [registry_open $portname $portversion $portrevision $portvariants]
1129           
1130                set installdate [registry_prop_retr $regref date]
1131                if { $installdate != 0
1132                  && $installdate < [file mtime ${portpath}/Portfile]} {
1133                    ui_debug "Portfile changed since installation"
1134                } else {
1135                    # Say we're skipping.
1136                    set skipped 1
1137               
1138                    ui_debug "Skipping $name ($portname) since this port is already installed"
1139                }
1140           
1141                # Something to close the registry entry may be called here, if it existed.
1142                # 3rd case: the same port/version/revision/Variants is already active
1143                # and user didn't mention -f
1144            } elseif {$name == "org.macports.activate"
1145              && [registry_exists $portname $portversion $portrevision $portvariants]
1146              && !([info exists ports_force] && $ports_force == "yes")} {
1147           
1148                # Is port active?
1149                set regref [registry_open $portname $portversion $portrevision $portvariants]
1150           
1151                if { [registry_prop_retr $regref active] != 0 } {
1152                    # Say we're skipping.
1153                    set skipped 1
1154               
1155                    ui_msg "Skipping $name ($portname $portvariants) since this port is already active"
1156                }
1157               
1158            }
1159           
1160            # otherwise execute the task.
1161            if {$skipped == 0} {
1162                set target [ditem_key $ditem provides]
1163           
1164                # Execute pre-run procedure
1165                if {[ditem_contains $ditem prerun]} {
1166                    set result [catch {[ditem_key $ditem prerun] $name} errstr]
1167                }
1168           
1169                #start tracelib
1170                if {($result ==0
1171                  && [info exists ports_trace]
1172                  && $ports_trace == "yes"
1173                  && $target != "clean")} {
1174                    trace_start $workpath
1175
1176                    # Enable the fence to prevent any creation/modification
1177                    # outside the sandbox.
1178                    if {$target != "activate"
1179                      && $target != "archive"
1180                      && $target != "fetch"
1181                      && $target != "install"} {
1182                        trace_enable_fence
1183                    }
1184           
1185                    # collect deps
1186                   
1187                    # Don't check dependencies for extract (they're not honored
1188                    # anyway). This avoids warnings about bzip2.
1189                    if {$target != "extract"} {
1190                        set depends {}
1191                        set deptypes {}
1192                   
1193                        # Determine deptypes to look for based on target
1194                        switch $target {
1195                            configure   -
1196                            build       { set deptypes "depends_lib depends_build" }
1197                       
1198                            test        -
1199                            destroot    -
1200                            install     -
1201                            archive     -
1202                            dmg         -
1203                            pkg         -
1204                            mpkg        -
1205                            rpm         -
1206                            srpm        -
1207                            dpkg        -
1208                            mdmg        -
1209                            activate    -
1210                            ""          { set deptypes "depends_lib depends_build depends_run" }
1211                        }
1212                   
1213                        # Gather the dependencies for deptypes
1214                        foreach deptype $deptypes {
1215                            # Add to the list of dependencies if the option exists and isn't empty.
1216                            if {[info exists PortInfo($deptype)] && $PortInfo($deptype) != ""} {
1217                                set depends [concat $depends $PortInfo($deptype)]
1218                            }
1219                        }
1220   
1221                        # Dependencies are in the form verb:[param:]port
1222                        set depsPorts {}
1223                        foreach depspec $depends {
1224                            # grab the portname portion of the depspec
1225                            set dep_portname [lindex [split $depspec :] end]
1226                            lappend depsPorts $dep_portname
1227                        }
1228
1229                        # always allow gzip in destroot as it is used to compress man pages
1230                        if {$target == "destroot"} {
1231                            lappend depsPorts "gzip"
1232                        }
1233                   
1234                        set portlist $depsPorts
1235                        foreach depName $depsPorts {
1236                            set portlist [recursive_collect_deps $depName $deptypes $portlist]
1237                        }
1238                   
1239                        if {[llength $deptypes] > 0} {tracelib setdeps $portlist}
1240                    }
1241                }
1242           
1243                if {$result == 0} {
1244                    foreach pre [ditem_key $ditem pre] {
1245                        ui_debug "Executing $pre"
1246                        set result [catch {$pre $name} errstr]
1247                        if {$result != 0} { break }
1248                    }
1249                }
1250           
1251                if {$result == 0} {
1252                ui_debug "Executing $name ($portname)"
1253                set result [catch {$procedure $name} errstr]
1254                }
1255           
1256                if {$result == 0} {
1257                    foreach post [ditem_key $ditem post] {
1258                        ui_debug "Executing $post"
1259                        set result [catch {$post $name} errstr]
1260                        if {$result != 0} { break }
1261                    }
1262                }
1263                # Execute post-run procedure
1264                if {[ditem_contains $ditem postrun] && $result == 0} {
1265                    set postrun [ditem_key $ditem postrun]
1266                    ui_debug "Executing $postrun"
1267                    set result [catch {$postrun $name} errstr]
1268                }
1269
1270                # Check dependencies & file creations outside workpath.
1271                if {[info exists ports_trace]
1272                  && $ports_trace == "yes"
1273                  && $target!="clean"} {
1274               
1275                    tracelib closesocket
1276               
1277                    trace_check_violations
1278               
1279                    # End of trace.
1280                    trace_stop
1281                }
1282            }
1283        }
1284        if {$result == 0} {
1285            # Only write to state file if:
1286            # - we indeed performed this step.
1287            # - this step is not to always be performed
1288            # - this step must be written to file
1289            if {$skipped == 0
1290          && [ditem_key $ditem runtype] != "always"
1291          && [ditem_key $ditem state] != "no"} {
1292            write_statefile target $name $target_state_fd
1293            }
1294        } else {
1295            ui_error "Target $name returned: $errstr"
1296            set result 1
1297        }
1298   
1299    } else {
1300        ui_info "Warning: $name does not have a registered procedure"
1301        set result 1
1302    }
1303   
1304    if {[ditem_key $ditem state] != "no"} {
1305        close $target_state_fd
1306    }
1307
1308    return $result
1309}
1310
1311# recursive dependency search for portname
1312proc recursive_collect_deps {portname deptypes {depsfound {}}} \
1313{
1314    set res [mport_search ^$portname\$]
1315    if {[llength $res] < 2} \
1316    {
1317        return {}
1318    }
1319
1320    set depends {}
1321
1322    array set portinfo [lindex $res 1]
1323    foreach deptype $deptypes \
1324    {
1325        if {[info exists portinfo($deptype)] && $portinfo($deptype) != ""} \
1326        {
1327            set depends [concat $depends $portinfo($deptype)]
1328        }
1329    }
1330
1331    set portdeps $depsfound
1332    foreach depspec $depends \
1333    {
1334        set portname [lindex [split $depspec :] end]
1335        if {[lsearch -exact $portdeps $portname] == -1} {
1336            lappend portdeps $portname
1337            set portdeps [recursive_collect_deps $portname $deptypes $portdeps]
1338        }
1339    }
1340    return $portdeps
1341}
1342
1343
1344proc eval_targets {target} {
1345    global targets target_state_fd portname
1346    set dlist $targets
1347   
1348    # Select the subset of targets under $target
1349    if {$target != ""} {
1350        set matches [dlist_search $dlist provides $target]
1351   
1352        if {[llength $matches] > 0} {
1353            set dlist [dlist_append_dependents $dlist [lindex $matches 0] [list]]
1354            # Special-case 'all'
1355        } elseif {$target != "all"} {
1356            ui_error "unknown target: $target"
1357            return 1
1358        }
1359    }
1360   
1361    set dlist [dlist_eval $dlist "" target_run]
1362   
1363    if {[llength $dlist] > 0} {
1364        # somebody broke!
1365        set errstring "Warning: the following items did not execute (for $portname):"
1366        foreach ditem $dlist {
1367            append errstring " [ditem_key $ditem name]"
1368        }
1369        ui_info $errstring
1370        set result 1
1371    } else {
1372        set result 0
1373    }
1374   
1375    return $result
1376}
1377
1378# open_statefile
1379# open file to store name of completed targets
1380proc open_statefile {args} {
1381    global workpath worksymlink place_worksymlink portname portpath ports_ignore_older
1382   
1383    if {![file isdirectory $workpath]} {
1384        file mkdir $workpath
1385    }
1386    # flock Portfile
1387    set statefile [file join $workpath .macports.${portname}.state]
1388    if {[file exists $statefile]} {
1389        if {![file writable $statefile]} {
1390            return -code error "$statefile is not writable - check permission on port directory"
1391        }
1392        if {!([info exists ports_ignore_older] && $ports_ignore_older == "yes") && [file mtime $statefile] < [file mtime ${portpath}/Portfile]} {
1393            ui_msg "Portfile changed since last build; discarding previous state."
1394            #file delete $statefile
1395            exec rm -rf [file join $workpath]
1396            exec mkdir [file join $workpath]
1397        }
1398    }
1399
1400    # Create a symlink to the workpath for port authors
1401    if {[tbool place_worksymlink] && ![file isdirectory $worksymlink]} {
1402        exec ln -sf $workpath $worksymlink
1403    }
1404   
1405    set fd [open $statefile a+]
1406    if {[catch {flock $fd -exclusive -noblock} result]} {
1407        if {"$result" == "EAGAIN"} {
1408            ui_msg "Waiting for lock on $statefile"
1409    } elseif {"$result" == "EOPNOTSUPP"} {
1410        # Locking not supported, just return
1411        return $fd
1412        } else {
1413            return -code error "$result obtaining lock on $statefile"
1414        }
1415    }
1416    flock $fd -exclusive
1417    return $fd
1418}
1419
1420# check_statefile
1421# Check completed/selected state of target/variant $name
1422proc check_statefile {class name fd} {
1423    seek $fd 0
1424    while {[gets $fd line] >= 0} {
1425        if {$line == "$class: $name"} {
1426            return 1
1427        }
1428    }
1429    return 0
1430}
1431
1432# write_statefile
1433# Set target $name completed in the state file
1434proc write_statefile {class name fd} {
1435    if {[check_statefile $class $name $fd]} {
1436        return 0
1437    }
1438    seek $fd 0 end
1439    puts $fd "$class: $name"
1440    flush $fd
1441}
1442
1443# check_statefile_variants
1444# Check that recorded selection of variants match the current selection
1445proc check_statefile_variants {variations fd} {
1446    upvar $variations upvariations
1447   
1448    seek $fd 0
1449    while {[gets $fd line] >= 0} {
1450        if {[regexp "variant: (.*)" $line match name]} {
1451            set oldvariations([string range $name 1 end]) [string range $name 0 0]
1452        }
1453    }
1454   
1455    set mismatch 0
1456    if {[array size oldvariations] > 0} {
1457        if {[array size oldvariations] != [array size upvariations]} {
1458            set mismatch 1
1459        } else {
1460            foreach key [array names upvariations *] {
1461                if {![info exists oldvariations($key)] || $upvariations($key) != $oldvariations($key)} {
1462                set mismatch 1
1463                break
1464                }
1465            }
1466        }
1467    }
1468   
1469    return $mismatch
1470}
1471
1472########### Port Variants ###########
1473
1474# Each variant which provides a subset of the requested variations
1475# will be chosen.  Returns a list of the selected variants.
1476proc choose_variants {dlist variations} {
1477    upvar $variations upvariations
1478   
1479    set selected [list]
1480   
1481    foreach ditem $dlist {
1482        # Enumerate through the provides, tallying the pros and cons.
1483        set pros 0
1484        set cons 0
1485        set ignored 0
1486        foreach flavor [ditem_key $ditem provides] {
1487            if {[info exists upvariations($flavor)]} {
1488                if {$upvariations($flavor) == "+"} {
1489                    incr pros
1490                } elseif {$upvariations($flavor) == "-"} {
1491                    incr cons
1492                }
1493            } else {
1494                incr ignored
1495            }
1496        }
1497   
1498        if {$cons > 0} { continue }
1499   
1500        if {$pros > 0 && $ignored == 0} {
1501            lappend selected $ditem
1502        }
1503    }
1504    return $selected
1505}
1506
1507proc variant_run {ditem} {
1508    set name [ditem_key $ditem name]
1509    ui_debug "Executing variant $name provides [ditem_key $ditem provides]"
1510   
1511    # test for conflicting variants
1512    foreach v [ditem_key $ditem conflicts] {
1513        if {[variant_isset $v]} {
1514            ui_error "Variant $name conflicts with $v"
1515            return 1
1516        }
1517    }
1518   
1519    # execute proc with same name as variant.
1520    if {[catch "variant-${name}" result]} {
1521        global errorInfo
1522        ui_debug "$errorInfo"
1523        ui_error "Error executing $name: $result"
1524        return 1
1525    }
1526    return 0
1527}
1528
1529# Given a list of variant specifications, return a canonical string form
1530# for the registry.
1531    # The strategy is as follows: regardless of how some collection of variants
1532    # was turned on or off, a particular instance of the port is uniquely
1533    # characterized by the set of variants that are *on*. Thus, record those
1534    # variants in a string in a standard order as +var1+var2 etc.
1535    # We can skip the platform and architecture since those are always
1536    # requested.  XXX: Is that really true? What if the user explicitly
1537    # overrides the platform and architecture variants? Will the registry get
1538    # bollixed? It would seem safer to me to just leave in all the variants that
1539    # are on, but for now I'm just leaving the skipping code as it was in the
1540    # previous version.
1541proc canonicalize_variants {variants} {
1542    array set vara $variants
1543    set result ""
1544    set vlist [lsort -ascii [array names vara]]
1545    foreach v $vlist {
1546        if {$vara($v) == "+" && $v ne [option os.platform] && $v ne [option os.arch]} {
1547            append result +$v
1548        }
1549    }
1550    return $result
1551}
1552
1553proc eval_variants {variations} {
1554    global all_variants ports_force PortInfo portvariants
1555    set dlist $all_variants
1556    upvar $variations upvariations
1557    set chosen [choose_variants $dlist upvariations]
1558    set portname $PortInfo(name)
1559
1560    # Check to make sure the requested variations are available with this
1561    # port, if one is not, warn the user and remove the variant from the
1562    # array.
1563    foreach key [array names upvariations *] {
1564        if {![info exists PortInfo(variants)] ||
1565            [lsearch $PortInfo(variants) $key] == -1} {
1566            ui_debug "Requested variant $key is not provided by port $portname."
1567            array unset upvariations $key
1568        }
1569    }
1570
1571    # now that we've selected variants, change all provides [a b c] to [a-b-c]
1572    # this will eliminate ambiguity between item a, b, and a-b while fulfilling requirments.
1573    #foreach obj $dlist {
1574    #    $obj set provides [list [join [$obj get provides] -]]
1575    #}
1576   
1577    set newlist [list]
1578    foreach variant $chosen {
1579        set newlist [dlist_append_dependents $dlist $variant $newlist]
1580    }
1581   
1582    set dlist [dlist_eval $newlist "" variant_run]
1583    if {[llength $dlist] > 0} {
1584        return 1
1585    }
1586
1587    # Now compute the true active array of variants. Note we do not
1588    # change upvariations any further, since that represents the
1589    # requested list of variations; but the registry for consistency
1590    # must encode the actual list of variants evaluated, however that
1591    # came to pass (dependencies, defaults, etc.) While we're at it,
1592    # it's convenient to check for inconsistent requests for
1593    # variations, namely foo +requirer -required where the 'requirer'
1594    # variant requires the 'required' one.
1595    array set activevariants [list]
1596    foreach dvar $newlist {
1597        set thevar [ditem_key $dvar provides]
1598        if {[info exists upvariations($thevar)] && $upvariations($thevar) eq "-"} {
1599            set chosenlist ""
1600            foreach choice $chosen {
1601                lappend chosenlist +[ditem_key $choice provides]
1602            }
1603            ui_error "Inconsistent variant specification: $portname variant +$thevar is required by at least one of $chosenlist, but specified -$thevar"
1604            return 1
1605        }
1606        set activevariants($thevar) "+"
1607    }
1608
1609    # Record a canonical variant string, used e.g. in accessing the registry
1610    set portvariants [canonicalize_variants [array get activevariants]]
1611
1612    # XXX: I suspect it would actually work better in the following
1613    # block to record the activevariants in the statefile rather than
1614    # the upvariations, since as far as I can see different sets of
1615    # upvariations which amount to the same activevariants in the end
1616    # can share all aspects of the build. But I'm leaving this alone
1617    # for the time being, so that someone with more extensive
1618    # experience can examine the idea before putting it into
1619    # action. -- GlenWhitney
1620
1621    return 0
1622}
1623
1624proc check_variants {variations target} {
1625    global ports_force PortInfo
1626    upvar $variations upvariations
1627    set result 0
1628    set portname $PortInfo(name)
1629   
1630    # Make sure the variations match those stored in the statefile.
1631    # If they don't match, print an error indicating a 'port clean'
1632    # should be performed. 
1633    # - Skip this test if the statefile is empty.
1634    # - Skip this test if performing a clean or submit.
1635    # - Skip this test if ports_force was specified.
1636   
1637    # TODO: Don't hardcode this list of targets here,
1638    #       check for [ditem_key $mport state] == "no" somewhere else instead
1639    if { [lsearch "clean submit lint livecheck" $target] < 0 &&
1640        !([info exists ports_force] && $ports_force == "yes")} {
1641       
1642        set state_fd [open_statefile]
1643   
1644        if {[check_statefile_variants upvariations $state_fd]} {
1645            ui_error "Requested variants do not match original selection.\nPlease perform 'port clean $portname' or specify the force option."
1646            set result 1
1647        } else {
1648            # Write variations out to the statefile
1649            foreach key [array names upvariations *] {
1650            write_statefile variant $upvariations($key)$key $state_fd
1651            }
1652        }
1653       
1654        close $state_fd
1655    }
1656   
1657    return $result
1658}
1659
1660proc default_universal_variant_allowed {args} {
1661   
1662    if {[variant_exists universal]} {
1663        ui_debug "universal variant already exists, so not adding the default one"
1664        return no
1665    } elseif {[exists universal_variant] && ![option universal_variant]} {
1666        ui_debug "'universal_variant no' specified, so not adding the default universal variant"
1667        return no
1668    } elseif {[exists use_xmkmf] && [option use_xmkmf]} {
1669        ui_debug "using xmkmf, so not adding the default universal variant"
1670        return no
1671    } elseif {[exists use_configure] && ![option use_configure] && ![exists xcode.universal.settings]} {
1672        # Allow +universal if port uses xcode portgroup.
1673        ui_debug "not using configure, so not adding the default universal variant"
1674        return no
1675    } elseif {![exists os.universal_supported] || ![option os.universal_supported]} {
1676        ui_debug "OS doesn't support universal builds, so not adding the default universal variant"
1677        return no
1678    } else {
1679        ui_debug "adding the default universal variant"
1680        return yes
1681    }
1682}
1683
1684proc add_default_universal_variant {args} {
1685    # Declare default universal variant if universal SDK is installed
1686    variant universal description {Build for multiple architectures} {
1687        pre-fetch {
1688            if {![file exists ${configure.universal_sysroot}]} {
1689                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"
1690            }
1691        }
1692
1693        eval configure.args-append ${configure.universal_args}
1694        eval configure.cflags-append ${configure.universal_cflags}
1695        eval configure.cppflags-append ${configure.universal_cppflags}
1696        eval configure.cxxflags-append ${configure.universal_cxxflags}
1697        eval configure.ldflags-append ${configure.universal_ldflags}
1698    }
1699}
1700
1701# Target class definition.
1702
1703# constructor for target object
1704proc target_new {name procedure} {
1705    global targets
1706    set ditem [ditem_create]
1707   
1708    ditem_key $ditem name $name
1709    ditem_key $ditem procedure $procedure
1710   
1711    lappend targets $ditem
1712   
1713    return $ditem
1714}
1715
1716proc target_provides {ditem args} {
1717    global targets
1718    # Register the pre-/post- hooks for use in Portfile.
1719    # Portfile syntax: pre-fetch { puts "hello world" }
1720    # User-code exceptions are caught and returned as a result of the target.
1721    # Thus if the user code breaks, dependent targets will not execute.
1722    foreach target $args {
1723        set origproc [ditem_key $ditem procedure]
1724        set ident [ditem_key $ditem name]
1725        if {[info commands $target] != ""} {
1726            ui_debug "$ident registered provides '$target', a pre-existing procedure. Target override will not be provided"
1727        } else {
1728            proc $target {args} "
1729                variable proc_index
1730                set proc_index \[llength \[ditem_key $ditem proc\]\]
1731                ditem_key $ditem procedure proc-${ident}-${target}-\${proc_index}
1732                proc proc-${ident}-${target}-\${proc_index} {name} \"
1733                    if {\\\[catch userproc-${ident}-${target}-\${proc_index} result\\\]} {
1734                        return -code error \\\$result
1735                    } else {
1736                        return 0
1737                    }
1738                \"
1739                proc do-$target {} { $origproc $target }
1740                makeuserproc userproc-${ident}-${target}-\${proc_index} \$args
1741            "
1742        }
1743        proc pre-$target {args} "
1744            variable proc_index
1745            set proc_index \[llength \[ditem_key $ditem pre\]\]
1746            ditem_append $ditem pre proc-pre-${ident}-${target}-\${proc_index}
1747            proc proc-pre-${ident}-${target}-\${proc_index} {name} \"
1748                if {\\\[catch userproc-pre-${ident}-${target}-\${proc_index} result\\\]} {
1749                    return -code error \\\$result
1750                } else {
1751                    return 0
1752                }
1753            \"
1754            makeuserproc userproc-pre-${ident}-${target}-\${proc_index} \$args
1755        "
1756        proc post-$target {args} "
1757            variable proc_index
1758            set proc_index \[llength \[ditem_key $ditem post\]\]
1759            ditem_append $ditem post proc-post-${ident}-${target}-\${proc_index}
1760            proc proc-post-${ident}-${target}-\${proc_index} {name} \"
1761                if {\\\[catch userproc-post-${ident}-${target}-\${proc_index} result\\\]} {
1762                    return -code error \\\$result
1763                } else {
1764                    return 0
1765                }
1766            \"
1767            makeuserproc userproc-post-${ident}-${target}-\${proc_index} \$args
1768        "
1769    }
1770    eval ditem_append $ditem provides $args
1771}
1772
1773proc target_requires {ditem args} {
1774    eval ditem_append $ditem requires $args
1775}
1776
1777proc target_uses {ditem args} {
1778    eval ditem_append $ditem uses $args
1779}
1780
1781proc target_deplist {ditem args} {
1782    eval ditem_append $ditem deplist $args
1783}
1784
1785proc target_prerun {ditem args} {
1786    eval ditem_append $ditem prerun $args
1787}
1788
1789proc target_postrun {ditem args} {
1790    eval ditem_append $ditem postrun $args
1791}
1792
1793proc target_runtype {ditem args} {
1794    eval ditem_append $ditem runtype $args
1795}
1796
1797proc target_state {ditem args} {
1798    eval ditem_append $ditem state $args
1799}
1800
1801proc target_init {ditem args} {
1802    eval ditem_append $ditem init $args
1803}
1804
1805##### variant class #####
1806
1807# constructor for variant objects
1808proc variant_new {name} {
1809    set ditem [ditem_create]
1810    ditem_key $ditem name $name
1811    return $ditem
1812}
1813
1814proc handle_default_variants {option action {value ""}} {
1815    global variations
1816    switch -regex $action {
1817        set|append {
1818            foreach v $value {
1819                if {[regexp {([-+])([-A-Za-z0-9_]+)} $v whole val variant]} {
1820                    if {![info exists variations($variant)]} {
1821                    set variations($variant) $val
1822                    }
1823                }
1824            }
1825        }
1826        delete {
1827            # xxx
1828        }
1829    }
1830}
1831
1832
1833# builds the specified port (looked up in the index) to the specified target
1834# doesn't yet support options or variants...
1835# newworkpath defines the port's workpath - useful for when one port relies
1836# on the source, etc, of another
1837proc portexec_int {portname target {newworkpath ""}} {
1838    ui_debug "Executing $target ($portname)"
1839    set variations [list]
1840    if {$newworkpath == ""} {
1841        array set options [list]
1842    } else {
1843        set options(workpath) ${newworkpath}
1844    }
1845    # Escape regex special characters
1846    regsub -all "(\\(){1}|(\\)){1}|(\\{1}){1}|(\\+){1}|(\\{1}){1}|(\\{){1}|(\\}){1}|(\\^){1}|(\\$){1}|(\\.){1}|(\\\\){1}" $portname "\\\\&" search_string
1847   
1848    set res [mport_search ^$search_string\$]
1849    if {[llength $res] < 2} {
1850        ui_error "Dependency $portname not found"
1851        return -1
1852    }
1853   
1854    array set portinfo [lindex $res 1]
1855    set porturl $portinfo(porturl)
1856    if {[catch {set worker [mport_open $porturl [array get options] $variations]} result]} {
1857        global errorInfo
1858        ui_debug "$errorInfo"
1859        ui_error "Opening $portname $target failed: $result"
1860        return -1
1861    }
1862    if {[catch {mport_exec $worker $target} result] || $result != 0} {
1863        global errorInfo
1864        ui_debug "$errorInfo"
1865        ui_error "Execution $portname $target failed: $result"
1866        mport_close $worker
1867        return -1
1868    }
1869    mport_close $worker
1870   
1871    return 0
1872}
1873
1874# portfile primitive that calls portexec_int with newworkpath == ${workpath}
1875proc portexec {portname target} {
1876    global workpath
1877    return [portexec_int $portname $target $workpath]
1878}
1879
1880proc adduser {name args} {
1881    global os.platform
1882    set passwd {*}
1883    set uid [nextuid]
1884    set gid [existsgroup nogroup]
1885    set realname ${name}
1886    set home /dev/null
1887    set shell /dev/null
1888   
1889    foreach arg $args {
1890        if {[regexp {([a-z]*)=(.*)} $arg match key val]} {
1891            regsub -all " " ${val} "\\ " val
1892            set $key $val
1893        }
1894    }
1895   
1896    if {[existsuser ${name}] != 0 || [existsuser ${uid}] != 0} {
1897        return
1898    }
1899   
1900    if {${os.platform} eq "darwin"} {
1901        exec dscl . -create /Users/${name} Password ${passwd}
1902        exec dscl . -create /Users/${name} UniqueID ${uid}
1903        exec dscl . -create /Users/${name} PrimaryGroupID ${gid}
1904        exec dscl . -create /Users/${name} RealName ${realname}
1905        exec dscl . -create /Users/${name} NFSHomeDirectory ${home}
1906        exec dscl . -create /Users/${name} UserShell ${shell}
1907    } else {
1908        # XXX adduser is only available for darwin, add more support here
1909        ui_warn "WARNING: adduser is not implemented on ${os.platform}."
1910        ui_warn "The requested user was not created."
1911    }
1912}
1913
1914proc addgroup {name args} {
1915    global os.platform
1916    set gid [nextgid]
1917    set realname ${name}
1918    set passwd {*}
1919    set users ""
1920   
1921    foreach arg $args {
1922        if {[regexp {([a-z]*)=(.*)} $arg match key val]} {
1923            regsub -all " " ${val} "\\ " val
1924            set $key $val
1925        }
1926    }
1927   
1928    if {[existsgroup ${name}] != 0 || [existsgroup ${gid}] != 0} {
1929        return
1930    }
1931   
1932    if {${os.platform} eq "darwin"} {
1933        exec dscl . -create /Groups/${name} Password ${passwd}
1934        exec dscl . -create /Groups/${name} RealName ${realname}
1935        exec dscl . -create /Groups/${name} PrimaryGroupID ${gid}
1936        if {${users} ne ""} {
1937            exec dscl . -create /Groups/${name} GroupMembership ${users}
1938        }
1939    } else {
1940        # XXX addgroup is only available for darwin, add more support here
1941        ui_warn "WARNING: addgroup is not implemented on ${os.platform}."
1942        ui_warn "The requested group was not created."
1943    }
1944}
1945
1946# proc to calculate size of a directory
1947# moved here from portpkg.tcl
1948proc dirSize {dir} {
1949    set size    0;
1950    foreach file [readdir $dir] {
1951        if {[file type [file join $dir $file]] == "link" } {
1952            continue
1953        }
1954        if {[file isdirectory [file join $dir $file]]} {
1955            incr size [dirSize [file join $dir $file]]
1956        } else {
1957            incr size [file size [file join $dir $file]];
1958        }
1959    }
1960    return $size;
1961}
1962
1963# check for a binary in the path
1964# returns an error code if it can not be found
1965proc binaryInPath {binary} {
1966    global env
1967    foreach dir [split $env(PATH) :] { 
1968        if {[file executable [file join $dir $binary]]} {
1969            return [file join $dir $binary]
1970        }
1971    }
1972   
1973    return -code error [format [msgcat::mc "Failed to locate '%s' in path: '%s'"] $binary $env(PATH)];
1974}
1975
1976# Set the UI prefix to something standard (so it can be grepped for in output)
1977proc set_ui_prefix {} {
1978    global UI_PREFIX env
1979    if {[info exists env(UI_PREFIX)]} {
1980        set UI_PREFIX $env(UI_PREFIX)
1981    } else {
1982        set UI_PREFIX "---> "
1983    }
1984}
1985
1986# Use a specified group/version.
1987proc PortGroup {group version} {
1988    global portresourcepath
1989
1990    set groupFile ${portresourcepath}/group/${group}-${version}.tcl
1991
1992    if {[file exists $groupFile]} {
1993        uplevel "source $groupFile"
1994    } else {
1995        ui_warn "Group file could not be located."
1996    }
1997}
1998
1999# check if archive type is supported by current system
2000# returns an error code if it is not
2001proc archiveTypeIsSupported {type} {
2002    global os.platform os.version
2003    set errmsg ""
2004    switch -regex $type {
2005        cp(io|gz) {
2006            set pax "pax"
2007            if {[catch {set pax [binaryInPath $pax]} errmsg] == 0} {
2008                if {[regexp {z$} $type]} {
2009                    set gzip "gzip"
2010                    if {[catch {set gzip [binaryInPath $gzip]} errmsg] == 0} {
2011                        return 0
2012                    }
2013                } else {
2014                    return 0
2015                }
2016            }
2017        }
2018        t(ar|bz|lz|gz) {
2019            set tar "tar"
2020            if {[catch {set tar [binaryInPath $tar]} errmsg] == 0} {
2021                if {[regexp {z2?$} $type]} {
2022                    if {[regexp {bz2?$} $type]} {
2023                        set gzip "bzip2"
2024                    } elseif {[regexp {lz$} $type]} {
2025                        set gzip "lzma"
2026                    } else {
2027                        set gzip "gzip"
2028                    }
2029                    if {[catch {set gzip [binaryInPath $gzip]} errmsg] == 0} {
2030                        return 0
2031                    }
2032                } else {
2033                    return 0
2034                }
2035            }
2036        }
2037        xar {
2038            set xar "xar"
2039            if {[catch {set xar [binaryInPath $xar]} errmsg] == 0} {
2040                return 0
2041            }
2042        }
2043        zip {
2044            set zip "zip"
2045            if {[catch {set zip [binaryInPath $zip]} errmsg] == 0} {
2046                set unzip "unzip"
2047                if {[catch {set unzip [binaryInPath $unzip]} errmsg] == 0} {
2048                    return 0
2049                }
2050            }
2051        }
2052        default {
2053            return -code error [format [msgcat::mc "Invalid port archive type '%s' specified!"] $type]
2054        }
2055    }
2056    return -code error [format [msgcat::mc "Unsupported port archive type '%s': %s"] $type $errmsg]
2057}
2058
2059#
2060# merge function for universal builds
2061#
2062
2063# private function
2064# merge_lipo base-path target-path relative-path architectures
2065# e.g. 'merge_lipo ${workpath}/pre-dest ${destroot} ${prefix}/bin/pstree i386 ppc
2066# will merge binary files with lipo which have to be in the same (relative) path
2067proc merge_lipo {base target file archs} {
2068    set exec-lipo ""
2069    foreach arch ${archs} {
2070        set exec-lipo [concat ${exec-lipo} [list "-arch" "${arch}" "${base}/${arch}${file}"]]
2071    }
2072    set exec-lipo [concat ${exec-lipo}]
2073    system "/usr/bin/lipo ${exec-lipo} -create -output ${target}${file}"
2074}
2075
2076# private function
2077# merge C/C++/.. files
2078# either just copy (if equivalent) or add CPP directive for differences
2079# should work for C++, C, Obj-C, Obj-C++ files and headers
2080proc merge_cpp {base target file archs} {
2081    merge_file $base $target $file $archs
2082    # TODO -- instead of just calling merge_file:
2083    # check if different
2084    #   no: copy
2085    #   yes: merge with #elif defined(__i386__) (__x86_64__, __ppc__, __ppc64__)
2086}
2087
2088# private function
2089# merge_file base-path target-path relative-path architectures
2090# e.g. 'merge_file ${workpath}/pre-dest ${destroot} ${prefix}/share/man/man1/port.1 i386 ppc
2091# will test equivalence of files and copy them if they are the same (for the different architectures)
2092proc merge_file {base target file archs} {
2093    set basearch [lindex ${archs} 0]
2094    ui_debug "ba: '${basearch}' ('${archs}')"
2095    foreach arch [lrange ${archs} 1 end] {
2096        # checking for differences; TODO: error more gracefully on non-equal files
2097        exec "/usr/bin/diff" "-q" "${base}/${basearch}${file}" "${base}/${arch}${file}"
2098    }
2099    ui_debug "ba: '${basearch}'"
2100    file copy "${base}/${basearch}${file}" "${target}${file}"
2101}
2102
2103# merges multiple "single-arch" destroots into the final destroot
2104# 'base' is the path where the different directories (one for each arch) are
2105# e.g. call 'merge ${workpath}/pre-dest' with having a destroot in ${workpath}/pre-dest/i386 and ${workpath}/pre-dest/ppc64 -- single arch -- each
2106proc merge {base} {
2107    global destroot configure.universal_archs
2108
2109    # test which architectures are available, set one as base-architecture
2110    set archs ""
2111    set base_arch ""
2112    foreach arch ${configure.universal_archs} {
2113        if [file exists "${base}/${arch}"] {
2114            set archs [concat ${archs} ${arch}]
2115            set base_arch ${arch}
2116        }
2117    }
2118    ui_debug "merging architectures ${archs}, base_arch is ${base_arch}"
2119
2120    # traverse the base-architecture directory
2121    set basepath "${base}/${base_arch}"
2122    fs-traverse file "${basepath}" {
2123        set fpath [string range "${file}" [string length "${basepath}"] [string length "${file}"]]
2124        if {${fpath} != ""} {
2125            # determine the type (dir/file/link)
2126            set filetype [exec "/usr/bin/file" "-b" "${basepath}${fpath}"]
2127            switch -regexp ${filetype} {
2128                directory {
2129                    # just create directories
2130                    ui_debug "mrg: directory ${fpath}"
2131                    file mkdir "${destroot}${fpath}"
2132                }
2133                symbolic\ link.* {
2134                    # copy symlinks, TODO: check if targets match!
2135                    ui_debug "mrg: symlink ${fpath}"
2136                    file copy "${basepath}${fpath}" "${destroot}${fpath}"
2137                }
2138                Mach-O.* {
2139                    merge_lipo "${base}" "${destroot}" "${fpath}" "${archs}"
2140                }
2141                current\ ar\ archive {
2142                    merge_lipo "${base}" "${destroot}" "${fpath}" "${archs}"
2143                }
2144                ASCII\ C\ program\ text {
2145                    merge_cpp "${base}" "${destroot}" "${fpath}" "${archs}"
2146                }
2147                default {
2148                    ui_debug "unknown file type: ${filetype}"
2149                    merge_file "${base}" "${destroot}" "${fpath}" "${archs}"
2150                }
2151            }
2152        }
2153    }
2154}
2155
2156##
2157# Escape a string for safe use in regular expressions
2158#
2159# @param str the string to be quoted
2160# @return the escaped string
2161proc quotemeta {str} {
2162    regsub -all {(\W)} $str {\\\1} str
2163    return $str
2164}
2165
Note: See TracBrowser for help on using the repository browser.