source: branches/gsoc09-logging/base/src/port1.0/portutil.tcl @ 51384

Last change on this file since 51384 was 51384, checked in by enl@…, 11 years ago

Merge from trunk

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