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

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

Commit patch for #12224 - provide ${os.major} variable

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