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

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

port1.0/portutil.tcl:
Put checks for universal SDK in the default +universal variant into a pre-fetch
block to avoid breaking commands like port info +universal.

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