File: RecPython.py

package info (click to toggle)
aap 1.072-1.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 4,976 kB
  • ctags: 2,160
  • sloc: python: 15,113; makefile: 62; sh: 13
file content (1218 lines) | stat: -rw-r--r-- 40,924 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
# Part of the A-A-P recipe executive: Python functions used in a recipe

# Copyright (C) 2002-2003 Stichting NLnet Labs
# Permission to copy and use this file is specified in the file COPYING.
# If this file is missing you can find it here: http://www.a-a-p.org/COPYING

#
# These are Python functions available to the recipe.
# This means the arguments cannot be changed without causing incompatibilities!
#
# It's OK to do "from RecPython import *", these things are supposed to be
# global.
#

import os
import os.path
import sys

import import_re        # import the re module in a special way

import string
import tempfile

import Action
from Dictlist import str2dictlist, list2str, dictlist2str, listitem2str
from Dictlist import dictlist_expand, parse_attr
from Error import *
import Global
from Process import recipe_error
from Util import *
from Work import getwork
import Cache
from Message import *


#
################## Python functions used in Process() #####################
#

def expr2str(item):
    """Used to turn the result of a Python expression into a string.
       For a list the elements are separated with a space.
       "None" is changed to an empty string.
       Dollars are doubled to avoid them being recognized as variables."""
    s = var2string(item)

    # Replace items that could be misinterpreted by ":print".
    # TODO: Is this really the right place to do this, or should the user take
    # care of it when needed?
    s = string.replace(s, '$', '$$')
    s = string.replace(s, '#', '$#')
    s = string.replace(s, '>', '$(gt)')
    s = string.replace(s, '<', '$(lt)')
    s = string.replace(s, '|', '$(bar)')
    return s


def flush_cache(recdict):
    """Called just before setting $CACHEPATH."""
    # It's here so that only this module has to be imported in Process.py.
    Cache.dump_cache(recdict)

#
#################### Python functions for recipes #####################
#

def skipbuild():
    """Return True when skipping build commands."""
    return skip_commands()


def suffix(name):
    """Return the file suffix, empty string when there isn't one."""
    # Remove attributes
    while 1:
        s = string.find(name, "{")
        if s < 0:
            break
        try:
            n, v, e = parse_attr([], name, s)
        except UserError, e:
            # Error in attribute, only give a warning here.
            msg_warning(Global.globals, _("Warning: error in suffix() argument: %s") % str(e))
            e = len(name)
        if e >= len(name):
            name = name[:s]
            break
        else:
            name = name[:s] + ' ' + name[e:]

    # Find last dot.
    i = string.rfind(name, ".")
    if i < 0:
        return ''
    suf = name[i + 1:]

    # Reject suffix if it contains a path separator.
    if string.find(suf, "/") >= 0 or string.find(suf, "\\") >= 0:
        return ''

    # Remove trailing whitespace.
    while suf[-1] == ' ' or suf[-1] == '\t':
        suf = suf[:-1]
    return suf


def aap_sufreplace(suffrom, sufto, var):
    """Obsolete name for sufreplace."""
    return sufreplace(suffrom, sufto, var)

def sufreplace(suffrom, sufto, var):
    """
    Replace suffixes in "var" from "suffrom" to "sufto".
    When "suffrom" is None also add "sufto" if there is no suffix yet.
    When "suffrom" is empty accept any suffix.
    When "sufto" is empty the suffix is removed.
    """
    # Check that the from suffix starts with a dot.
    if suffrom and suffrom[0] != ".":
        recipe_error([], _('first sufreplace() argument must start with a dot'))

    try:
        if suffrom:
            rex = re.compile(string.replace(suffrom, ".", "\\.") + "$")
        else:
            rex = re.compile("\\.[^. \t/\\\\]+$")

        dl = var2dictlist(var)
        for n in dl:
            if (suffrom == None
                        and string.find(os.path.basename(n["name"]), '.') < 0):
                n["name"] = n["name"] + sufto
            else:
                n["name"] = rex.sub(sufto, n["name"])
        return dictlist2str(dl)

    except (StandardError, re.error), e:
        recipe_error([], _('sufreplace() failed: ') + str(e))
        return None     # not reached


def sufadd(suf, var, always = 0):
    """
    Add suffix "suf" to items in "var" that do not have a suffix.
    When "always" is non-zero add "suf" to all items.
    """
    # Check that the from suffix starts with a dot.
    if not suf or suf[0] != ".":
        recipe_error([], _('first sufadd() argument must start with a dot'))

    try:
        dl = var2dictlist(var)
        for n in dl:
            if always or string.find(os.path.basename(n["name"]), '.') < 0:
                n["name"] = n["name"] + suf
        return dictlist2str(dl)

    except (StandardError, re.error), e:
        recipe_error([], _('sufadd() failed: ') + str(e))
        return None     # not reached


def aap_abspath(var):
    """Obsolete name for var_abspath()."""
    return var_abspath(var)

def var_abspath(var):
    """Makes file names in "var" absolute."""
    # TODO: make this more robust.
    dl = str2dictlist([], var2string(var))
    for k in dl:
        n = k["name"]
        if not os.path.isabs(n):
            k["name"] = os.path.abspath(n)
    return dictlist2str(dl)


def aap_expand(var):
    """
    Obsolete name for var2string().
    """
    return var2string(var)


def childdir(arg):
    """
    Return the argument expanded to be relative to the directory of the parent
    recipe.
    """
    recdict = Global.globals
    if not recdict.has_key("CHILDDIR"):
        msg_error(recdict, _("Using childdir() at the top level"))
        return ''
    return relativedir(arg, "CHILDDIR")

def parentdir(arg):
    """
    Return the argument expanded to be relative to the current recipe
    directory, assuming it is relative to the parent recipe.
    """
    recdict = Global.globals
    if not recdict.has_key("PARENTDIR"):
        msg_error(recdict, _("Using parentdir() at the top level"))
        return ''
    return relativedir(arg, "PARENTDIR")

def topdir(arg):
    """
    Return the argument expanded to be relative to the directory of the
    toplevel recipe.
    """
    return relativedir(arg, "TOPDIR")

def basedir(arg):
    """
    Return the argument expanded to be relative to the current recipe
    directory, assuming it is relative to the toplevel recipe.
    """
    return relativedir(arg, "BASEDIR")

def relativedir(arg, varname):
    """
    Implementation of childdir() and topdir()
    """
    recdict = Global.globals
    dirname = recdict[varname]
    if not dirname:     # parent/top is in same directory.
        return arg

    dl = str2dictlist([], var2string(arg))
    for i in dl:
        i["name"] = os.path.join(dirname, i["name"])

    return dictlist2str(dl)


def src2obj(arg1, arg2 = None, sufname = "OBJSUF", auto = 1):
    """Turn a string (list of file names) to their respective object files."""
    # Allow passing two arguments for backwards compatibility.
    # But never use a string for recdict.
    import types
    if type(arg1) is types.DictType:
        recdict = arg1
        source = arg2
    else:
        recdict = Global.globals
        source = arg1
    source = var2string(source)

    dictlist = var2list(source)
    res = ''
    for name in dictlist:
        n = srcitem2obj(recdict, name, sufname = sufname, auto = auto)
        if res:
            res = res + ' '
        res = res + listitem2str(n)
    return res


def srcitem2obj(recdict, name, attrdict = {}, sufname = "OBJSUF", auto = 1):
    """
    Turn one file name to its object file name: Prepend $BDIR and add
    "sufname".  If "attrdict" is specified, use "var_" attributes for the
    variables.
    """
    node = getwork(recdict).find_node(name)
    if attrdict.has_key("var_BDIR"):
        bdir = attrdict["var_BDIR"]
    elif node and node.attributes.has_key("var_BDIR"):
        bdir = node.attributes["var_BDIR"]
    else:
        bdir = get_var_val_int(recdict, "BDIR")

    # When "name" starts with "../" replace it with "_/".  It's not a perfect
    # solution but should work nearly always.
    i = 0
    while (i < len(name)
            and name[i:i+2] == ".."
            and (name[i+2] == '/'
                or (os.name != "posix"
                    and name[i+2] == '\\'))):
        name = name[:i] + "_" + name[i+2:]
        i = i + 2

    name = os.path.join(bdir, name)

    if attrdict.has_key("suffix"):
        # Use the suffix attribute if it exists.
        objsuf = attrdict["suffix"]
    elif sufname:
        # Use the "sufname" argument.
        if not auto:
            ft = None
        else:
            # Use a language-specific suffix name $FT_OBJSUF if it exists.
            if node:
                ft = node.get_ftype(recdict)
            else:
                ft = attrdict.get("filetype")
                if not ft:
                    # A ":program" command adds a lower priority filetype
                    # attribute.
                    ft = attrdict.get("filetypehint")
                    if not ft:
                        from Filetype import ft_detect
                        ft = ft_detect(name, recdict = recdict)

        # If a filetype is known, find $FT_OBJSUF before $OBJSUF.
        if ft:
            l = [ string.upper(ft) + '_' + sufname, sufname ]
        else:
            l = [ sufname ]
        for sn in l:
            if attrdict.has_key("var_" + sn):
                objsuf = attrdict["var_" + sn]
                break
            if node and node.attributes.has_key("var_" + sn):
                objsuf = node.attributes["var_" + sn]
                break
            objsuf = get_var_val_int(recdict, sn)
            if objsuf:
                break
        if objsuf is None:
            recipe_error([], _('srcitem2obj(): $%s not set') % sufname)
    else:
        objsuf = ''

    i = string.rfind(name, '.')
    if i > 0 and i > string.rfind(name, '/') and i > string.rfind(name, '\\'):
        n = name[:i] + objsuf
    else:
        n = name + objsuf

    if attrdict.has_key("prefix"):
        n = os.path.join(os.path.dirname(n),
                                      attrdict["prefix"] + os.path.basename(n))
    return n


def get_attr(fname):
    """Obtain the attribute dictionary for a file name.
       Only works in a recipe, because it uses Global.globals."""
    node = getwork(Global.globals).find_node(fname)
    if node:
        return node.attributes
    return {}


def get_var_attr(var, attr):
    """
    Get the value of attribute "attr" from variable value "var".
    It's an error if two items in "var" have a different attribute value.
    """
    action = ''
    for item in var2dictlist(var):
	a = item.get(attr)
        if not a:
            a = get_attr(item["name"]).get(attr)
	if a:
	    if action and a != action:
                # TODO: mention recipe location!
                recipe_error([], _('get_var_attr(): Two different "%s" attributes specified: "%s" and "%s".') % (attr, action, a))
	    action = a
    return action


def program_path(name, path = None, pathext = None, skip = None):
    """Return the full name of a program "name" if it can be found in the
       search path.  None otherwise.
       If "path" is given, use it as the search path (string of items separated
       with os.pathsep).
       If "pathext" is given, try these suffixes (string of items separated
       with os.pathsep).
       If "skip" is given, skip this directory."""
    # Decide on the list of directories to examine.
    if not path is None:
        envpath = path
    elif os.environ.has_key('PATH'):
        envpath = os.environ['PATH']
    else:
        envpath = os.defpath
    if not type(envpath) is types.ListType:
        dirlist = string.split(envpath, os.pathsep)
    # When using a default path also include our own directory and its "bin"
    # subdirectory.
    if path is None and Global.aap_rootdir:
        dirlist = [ Global.aap_rootdir, Global.aap_bindir ] + dirlist

    # Decide on the list of suffixes to use.
    if not pathext is None:
        if pathext:
            if type(pathext) is types.ListType:
                extlist = pathext
            else:
                extlist = string.split(pathext, os.pathsep)
        else:
            extlist = [ '' ]    # empty pathext means not using a suffix
    elif os.environ.get('PATHEXT'):
        # Cygwin has os.pathsep set to ':' but PATHEXT does use ';' for
        # separator.  Since there should be no ';' in an extension it's
        # relatively safe to assume the separator is ';' if it's there.
        if ';' in os.environ['PATHEXT']:
            sep = ';'
        else:
            sep = os.pathsep
        extlist = string.split(os.environ['PATHEXT'], sep)
    elif os.name in [ 'dos', 'os2', 'nt' ]:
        extlist = [ '', '.exe', '.com', '.bat', '.cmd' ]
    else:
        extlist = [ '' ]
    # If the file name already includes an extention, don't try adding another
    # one.
    if string.find(os.path.basename(name), '.') > 0:
        extlist = [ '' ]

    for dir in dirlist:
        if skip and os.path.abspath(dir) == os.path.abspath(skip):
            continue
        for ext in extlist:
            fullname = os.path.join(dir, name) + ext
            if os.path.isfile(fullname):
                try:
                    # If os.access() is available we can check if the file is
                    # executable.
                    x_ok = os.access(fullname, os.X_OK)
                except:
                    # Couldn't execute os.access() (not supported on all
                    # systems), assume the file is executable.
                    x_ok = 1
                if not x_ok:
                    continue
                return fullname

    return None


def redir_system(arg1, arg2 = 1, arg3 = None):
    """Execute "cmd" with the shell and catch the output.
       Calls redir_system_int() to do the real work, passing the global
       variable dictionary."""
    # A previous version used "recdict" as the first argument.  Work backwards
    # compatible.
    import types
    if arg3 or type(arg1) is types.DictType:
        recdict = arg1
        cmd = arg2
        if arg3:
            use_tee = arg3
        else:
            use_tee = 1
    else:
        recdict = Global.globals
        cmd = arg1
        use_tee = arg2
    return redir_system_int(recdict, cmd, use_tee)


def sort_list(l):
    """Sort a list and return the result.  The sorting is done in-place, thus
       the original list is changed.  It's just a workaround for the Python
       sort method on lists returning None instead of the list."""
    l.sort()
    return l


def var2string(val):
    """
    Expand a variable when it is of ExpandVar class.
    To be used in Python code in a recipe.
    """
    if isinstance(val, ExpandVar):
        # Reduce an ExpandVar object to its value.
        from Commands import expand
        s = expand(0, Global.globals, val.getVal(), Expand(1, Expand.quote_aap))
    else:
        # Convert the value to a string.
        import types
        if type(val) == types.ListType:
            s = list2str(val)
        elif val is None:
            s = ''
        else:
            s = str(val)

    return s

def expandvar(l):
    """Obsolete name for expand2string()."""
    return expand2string(l)

def expand2string(l):
    """Expand wildcards and return a string."""
    return dictlist2str(dictlist_expand(str2dictlist([], var2string(l))))


def var2list(l):
    """Turn a variable with a string value into a list."""
    from Dictlist import str2list
    return str2list([], l)

def expand2list(l):
    """Like var2list() but also expand wildcards."""
    return map(lambda x: x["name"], dictlist_expand(str2dictlist([],
                                                               var2string(l))))


def var2dictlist(l):
    """Turn a variable with a string value into a dictlist."""
    return str2dictlist([], var2string(l))

def expand2dictlist(l):
    """Like var2dictlist() but also expand wildcards."""
    return dictlist_expand(str2dictlist([], var2string(l)))


def wildescape(l):
    """Escape wildcard characters in "l" so that they are not expanded."""
    res = ''
    for c in l:
        if c in ['*', '?', '[']:
            res = res + '[' + c + ']'
        else:
            res = res + c
    return res

def file2string(fname, recdict = None):
    """
    Read a file, remove comment lines and turn the result into one line.
    """
    res = ''
    # open the file, handle errors
    try:
        f = open(os.path.expanduser(fname))
    except StandardError, e:
        msg_error(recdict, (_('Cannot open "%s": ') % fname) + str(e))
    else:
        # read the file, handle errors
        lines = []
        try:
            lines = f.readlines()
        except StandardError, e:
            msg_error(recdict, (_('Error reading "%s": ') % fname) + str(e))
        f.close()

        # concatenate the lines, removing comment lines and white space
        for l in lines:
            l = string.strip(l)
            if l and l[0] != '#':
                res = res + ' ' + l

    res = string.lstrip(res)        # strip leading space
    return res


def has_target(arg1, arg2 = None):
    """Return zero if target "arg1" has no dependencies, one if it has and
       two if it also has build commands."""
    # This function used to have two arguments, first one the recdict used.
    # Figure out how it was called for backwards compatibility.
    if arg2:
        recdict = arg1
        target = arg2
    else:
        recdict = Global.globals
        target = arg1

    work = getwork(recdict)
    node = work.find_node(target)
    if node:
        if node.get_build_dependencies():
            return 2
        if node.get_dependencies():
            return 1
    return 0


def has_targetarg(targets):
    """
    Return non-zero if an entry in "targetlist" is one of the targets Aap was
    started with.
    """
    recdict = Global.globals
    l = var2list(get_var_val(0, recdict, "_no", "TARGETARG"))

    # Using filter() here causes warning messages...
    tlist = var2list(targets)
    for x in l:
        if x in tlist:
            return 1

    return 0


def has_build_target():
    """
    Return non-zero if there is a build target.
    Return zero if there are only fetch or cleanup targets, no need to run
    configure.
    """
    l = Global.cmd_args.targets
    if len(l) == 0:
        return 1        # The default target should build something
    for i in l:
        if not i in ["clean", "cleanmore", "cleanALL", "fetch"]:
            return 1
    return 0


def tempfname():
    """Return the name of a temporary file which is for private use."""
    # TODO: create a directory with 0700 permissions, so that it's private
    return tempfile.mktemp()


def aap_has(arg):
    """
    Return non-zero if "arg" is a supported feature.
    """
    # aap_has(":command")
    if len(arg) > 1 and arg[0] == ':':
        from Process import aap_cmd_names
        return arg[1:] in aap_cmd_names

    return 0


def define_action(action, primary, commands, attr = {},
                            intypes = [], outtypes = [],
                            defer_var_names = [],
                            outfilename = ''):
    """
    Define an action.
    """
    from RecPos import RecPos

    # TODO: is there a way to put a line number in rpstack?
    recdict = Global.globals
    str = "define_action(%s)" % action
    if intypes:
        str = str + " from %s" % reduce(lambda x, y: x + "," + y, intypes)
    if outtypes:
        str = str + " to %s" % reduce(lambda x, y: x + "," + y, outtypes)
    act = Action.Action([RecPos(str)], recdict, attr, commands,
                                    intypes = intypes, outtypes = outtypes,
                                             defer_var_names = defer_var_names,
                                             outfilename = outfilename)
    Action.action_add_to_dict(action, act)
    act.primary = primary
    return act


def action_in_types(name, outtype = None):
    """
    Find action object(s) by name and return a list of the supported input
    types.  Restrict to actions that support "outtype".
    """
    return Action.get_ftypes(name, 1, outtype = outtype)

def action_out_types(name, intype = None):
    """
    Find action object(s) by name and return a list of the supported output
    types.  Restrict to actions that support "intype".
    """
    return Action.get_ftypes(name, 0, intype = intype)

# Remember the last installed port to avoid asking the user twice about using
# it.
lastportname = None

def do_BSD_port(name, target):
    """
    Try using the BSD port system for the package "name".
    "target" is "install" to install and "all" to build only.
    Will ask the user when root permissions are required.
    Returns non-zero for success.
    """
    global lastportname

    recdict = Global.globals

    dirname = "/usr/ports/%s" % name
    try:
        if not os.access(dirname, os.R_OK):
            # Doesn't appear to exist.
            return 0
    except:
        # Can't use os.access().
        return 0

    if lastportname != name and not os.access(dirname, os.W_OK):
        r = raw_input(("\nThe %s port appears to exist.\n" % dirname) +
                        "Do you want to become root and use the port? (y/n) ")
        if not r or (r[0] != 'y' and r[0] != 'Y'):
            # User doesn't want this.
            lastportname = None
            return 0

    lastportname = None

    cwd = os.getcwd()
    try:
        os.chdir(dirname)
    except StandardError, e:
        msg_error(recdict, (_("Cannot cd to %s") % dirname) + str(e))
        return 0

    cmd = "make %s" % target
    try:
        if os.access("/", os.W_OK):
            from Commands import aap_system
            aap_system(0, recdict, cmd)
        else:
            res = do_as_root(recdict, [], cmd)
            if not res:
                raise UserError, _("%s failed") % cmd
    finally:
        os.chdir(cwd)

    lastportname = name

    return 1


# Remember the last installed package to avoid asking the user twice about
# using it.
lastpkgname = None

def do_Debian_pkg(name, target):
    """
    Try using the Debian apt-get command for the package "name".
    "target" is "install" to install and "all" to, eh, do nothing.
    Will ask the user when root permissions are required.
    Returns non-zero for success.
    """
    global lastpkgname

    recdict = Global.globals

    # Safety check: don't allow non-printable and non-ASCII characters in the
    # package name, since we are feeding it to a shell.
    for c in name:
        if ord(c) <= 32 or ord(c) >= 127:
            print _("Illegal character '%s' in package name '%s'") % (c, name)
            return 0

    try:
        if not os.path.isfile("/etc/debian_version"):
            return 0    # Not a Debian system.
        if not program_path("apt-get"):
            return 0    # apt-get is not available (or $PATH wrong)
    except:
        # Can't use os.access().
        return 0

    if lastpkgname != name and not os.access("/", os.W_OK):
        r = raw_input(("\nThis appears to be a Debian system and apt-get is found.\n") +
                        "Do you want to become root and install the %s package? (y/n) " % name)
        if not r or (r[0] != 'y' and r[0] != 'Y'):
            # User doesn't want this.
            lastpkgname = None
            return 0

    lastpkgname = None

    # Only do the work when actually installing.
    if target == "install":
        cmd = "apt-get install %s" % name
        if os.access("/", os.W_OK):
            from Commands import aap_system
            aap_system(0, recdict, cmd)
        else:
            do_as_root(recdict, [], cmd)
        print "apt-get finished"

    lastpkgname = name

    return 1


def ask_prefix(name):
    """
    Ask the user where to install package "name".
    Return a boolean, indicating whether ":asroot" is to be used, and the
    prefix to be used.
    """
    # If the user already is root silently install in /usr/local.
    if os.access("/", os.W_OK):
        return 1, "/usr/local/"

    home = home_dir()
    if home:
        home = os.path.dirname(home)
    r = raw_input((_('\nSelect where to install %s:\n') % name)
            + _('1. become root and install in "/usr/local"\n')
            + _('2. become root and install in a specified location\n')
            + (_('3. install in your home directory "%s"\n') % home)
            + _('4. install in a specified location\n')
            + _('q. quit\n')
            + _('choice: '))
    if r:
        if r[0] == 'q' or r[0] == 'Q':
            recipe_error([], _('ask_prefix() aborted'))
        if r[0] == '2' or r[0] == '4':
            dir = raw_input(_("Enter directory name: "))
            while dir and (dir[-1] == '\n' or dir[-1] == '\r'):
                dir = dir[:-1]
            dir = os.path.expanduser(dir)
        elif r[0] == '1':
            dir = "/usr/local/"
        elif r[0] == '3':
            dir = home
        else:
            return 0, ''

        # Make sure the directory ends in a slash (or backslash).
        if dir[-1] != '/' and dir[-1] != '\\':
            dir = dir + '/'

        if r[0] == '1' or r[0] == '2':
            return 1, dir
        return 0, dir

    # invalid answer
    return 0, ''


# This must be here instead of inside get_html_images() for Python 1.5.
import htmllib

def get_html_images(files, add_dir = 1):
    """
    Function to extract a list of image file names from HTML files.
    Only relative file names are supported, because a relative file name means
    the file can be found when testing locally.
    """
    class ImgHTMLParser(htmllib.HTMLParser):
        def __init__(self, formatter, verbose=0):
            htmllib.HTMLParser.__init__(self, formatter, verbose)
            self.img_list = []      # list of images so far
        def set_dir(self, dir):
            self.img_dir = dir      # dir of image file
        # Overrule handle_image(): append the file name to self.img_list[].
        def handle_image(self, src, alt, *args):
            if src:
                from Remote import url_split3
                scheme, mach, path = url_split3(src)
                if scheme == '' and not os.path.isabs(src):
                    # img file name is relative to html file dir.
                    # Remove things like "../" and "./".
                    n = os.path.normpath(os.path.join(self.img_dir, src))
                    if not n in self.img_list:
                        self.img_list.append(n)
        def get_img_list(self):
            return self.img_list


    import formatter
    parser = ImgHTMLParser(formatter.NullFormatter())

    if not type(files) is types.ListType:
        from Dictlist import str2list
        files = str2list([], files)

    for fname in files:
        try:
            f = open(fname)
        except StandardError, e:
            recipe_error([], _('get_html_images(): Cannot open file "%s": %s')
                                                             % (fname, str(e)))
        try:
            if add_dir:
                parser.set_dir(os.path.dirname(fname))
            parser.feed(f.read())
            parser.close()
            parser.reset()
        except StandardError, e:
            recipe_error([], _('get_html_images(): Error parsing file "%s": %s')
                                                             % (fname, str(e)))
        f.close()

    return parser.get_img_list()


#
#################### Python functions for internal things ###################
#

def aap_depend_c(recdict, sourcestr, targetstr, local = 1, flags = None):
    """
    Check for included files in C or C++ file "source", write a dependency line
    in "target".
    When "local" is non-zero skip files included with <file>.
    When "flags" is given use this instead of $CFLAGS.  Use $CXXFLAGS for C++.
    """
    dl = str2dictlist([], sourcestr)
    source = dl[0]["name"]
    dl = str2dictlist([], targetstr)
    target = dl[0]["name"]
    msg_info(recdict, _('Scanning "%s" for dependencies') % source)

    # "scanned" is a list of files that have been encountered.  The key is an
    # absolute file name.  The value is zero when the file is to be scanned,
    # one if it has been scanned.
    scanned = {full_fname(source) : 0}

    # Make the local pathlist from "-Idir" arguments.
    # Should we include the current directory?  Probably not.  We do look in
    # the directory of the source file when double quotes are used.
    localpathlist = [ ]
    if flags is None:
        flags = get_var_val_int(recdict, "CFLAGS")
    for n in [get_var_val_int(recdict, "CPPFLAGS"),
             get_var_val_int(recdict, "INCLUDE"), flags]:
        dl = str2dictlist([], n)
        for al in dl:
            a = al["name"]
            if len(a) > 2 and a[:2] == "-I":
                localpathlist.append(a[2:])

    globalpathlist = [ "/usr/local/include", "/usr/include" ]

    # Loop until there are no more files to be scanned.
    found = 1
    while found:
        found = 0
        for fname in scanned.keys():
            if scanned[fname] == 0:
                found = 1
                scanned[fname] = 1

                _scan_c_file(recdict, fname, scanned, local,
                                                 localpathlist, globalpathlist)
                break

    try:
        f = open(target, "w")
    except IOError, e:
        msg_error(recdict, (_('Cannot create dependency file "%s": ')
                                                            % target) + str(e))
    else:
        try:
            f.write("%s : " % fname_fold(source))
            for k in scanned.keys():
                f.write(listitem2str(shorten_name(k)) + " ")
            f.close()
        except IOError, e:
            msg_error(recdict, (_('Cannot write to dependency file "%s": ')
                                                            % target) + str(e))


def _scan_c_file(recdict, fname, scanned, local, localpathlist, globalpathlist):
    """
    Add included files in "fname" to dictionary "scanned".
    When "local" is True don't add files included in <>.
    Use the paths in "localpathlist" and "globalpathlist" to find included
    files.
    """
    def search_path(pathlist, fname):
        """Search for included file "fname" in list of dirs "pathlist"."""
        if os.path.isabs(fname):
            return fname
        for dir in pathlist:
            f = os.path.join(dir, fname)
            if os.path.exists(f):
                return full_fname(f)
        return None     # include file not found

    def search_target(work, pathlist, fname):
        """
        Search for included file "fname" in the list of nodes.
        Accept a node only if it has a "fetch" attribute or dependencies.
        Use "pathlist" if necessary.
        """
        n = work.find_node(fname)
        if n and (n.attributes.get("fetch") or n.get_dependencies()):
            return fname
        for dir in pathlist:
            f = os.path.join(dir, fname)
            n = work.find_node(f)
            if n and (n.attributes.get("fetch") or n.get_dependencies()):
                return full_fname(f)
        return None     # include file not found

    try:
        # Scan file "fname".
        if not os.path.exists(fname):
            # The file doesn't exist.
            # Fetch and/or update it.  If this fails just skip it.
            from Commands import aap_update
            try:
                aap_update(0, recdict, fname)
            except:
                msg_extra(recdict, _('Cannot find included file "%s"' % fname))
                return

        mypath = os.path.dirname(fname)
        if mypath == '':
            mypath = '.'

        f = open(fname)
        msg_extra(recdict, _('Scanning "%s" for dependencies') % fname)

        while 1:
            # Read each line of the file.  Quickly check if it
            # starts with "\s*#\s*include".
            line = f.readline()
            if not line:
                break
            i = 0
            min_len = len(line) - 10 # at least need include"f"
            while (i < min_len
                    and (line[i] == ' ' or line[i] == '\t')):
                i = i + 1
            if i < min_len and line[i] == '#':
                i = i + 1
                while (i < min_len
                        and (line[i] == ' ' or line[i] == '\t')):
                    i = i + 1
                if line[i:i+7] == "include":
                    i = skip_white(line, i + 7)
                    line_len = len(line)
                    if i < line_len:
                        quote = line[i]
                        if (quote == '"'
                                or (quote == '<' and not local)):
                            if quote == '<':
                                quote = '>'
                            i = i + 1
                            s = i
                            while i < line_len and line[i] != quote:
                                i = i + 1
                            if i < line_len and line[i] == quote:
                                # Make file name uniform (forward slashes).
                                name = fname_fold(line[s:i])

                                # Search for the file in the specified path for
                                # include files.
                                if quote == '"':
                                    pathlist = [ mypath ] + localpathlist + globalpathlist
                                else:
                                    pathlist = globalpathlist + localpathlist
                                fn = search_path(pathlist, name)

                                # If the file is not found search for a target
                                # that can produce it or fetch it.
                                if not fn:
                                    fn = search_target(getwork(recdict),
                                                                pathlist, name)
                                if fn and not scanned.has_key(fn):
                                    scanned[fn] = not local

    except IOError:
        # ignore errors while scanning a file, always close the
        # file
        try:
            f.close()
        except:
            pass


def get_md5(fname):
    """Get the md5 checksum as a hexdigest for file "file".
       Used in the recipe generated with ":mkdownload".
       Returns "unknown" when the file can't be read."""
    from Sign import check_md5

    return check_md5(globals(), fname, msg = 0)


#
# INSTALL stuff.
#

def install_files(desttail, source, modestr, strip = 0, mandir = 0,
                                                                uninstall = 0):
    """
    Called from the default actions to install files "source" into directory
    $DESTDIR/$PREFIX/"desttail" with mode "modestr".
    When "strip" is non-zero run $STRIP on the executables.
    When "mandir" is non-zero, use the file name extension for the directory
    name, as usual for manpages
    Also used for uninstall with "uninstall" set to 1.
    """
    from CopyMove import remote_copy_move
    from RecPos import RecPos
    from Remote import url_split3

    recdict = Global.globals
    # TODO: get better stack info!
    if uninstall:
        rpstack = [RecPos("uninstall_files()")]
    else:
        rpstack = [RecPos("install_files()")]

        if strip:
            stripprog = get_var_val(0, recdict, "_no", "STRIP")
            if not stripprog:
                msg_warning(recdict, _("$STRIP is empty, stripping skipped"))

    # Prepend $DESTDIR and $PREFIX.  $DESTDIR is optional.  $PREFIX is not used
    # when "desttail" starts with a slash.
    prefix = get_var_val(0, recdict, "_no", "PREFIX")
    if not prefix:
        prefix = "/usr/local"
    destlist = str2dictlist(recdict, desttail)
    if len(destlist) != 1:
        recipe_error([], _('destination directory must be one item: "%s"')
                                                                    % desttail)
    dest = os.path.join(os.path.expanduser(prefix), destlist[0]["name"])
    destdir = get_var_val(0, recdict, "_no", "DESTDIR")
    if destdir:
        while dest[0] in "/\\":
            dest = dest[1:]     # remove leading slashes before joining
        dest = os.path.join(os.path.expanduser(destdir), dest)

    for item in str2dictlist(recdict, source):
        name = item["name"]

        # Install "foo.2" in "man2" directory.
        if mandir and len(name) > 2 and name[-2] == '.':
            destloc = os.path.join(dest, "man%s" % name[-1])
        else:
            destloc = dest

        if item.get("installdir"):
            destloc = os.path.join(destloc, item.get("installdir"))
            if item.get("keepdir"):
                msg_warning(recdict, _('"%s" has both "keepdir" and "installdir"; using "installdir"') % name)
        # with {keepdir} append the directory of the source.
        elif item.get("keepdir"):
            destloc = os.path.join(destloc, os.path.dirname(name))

        destname = os.path.join(destloc, os.path.basename(name))
        scheme, mach, path = url_split3(destname)

        if uninstall:
            if scheme != '':
                msg_warning(recdict, _('Cannot delete remotely yet: "%s"')
                                                                    % destname)
            elif os.path.exists(destname):
                if skip_commands():
                    msg_info(recdict, _('Skip delete "%s"') % destname)
                else:
                    # Delete the file.
                    try:
                        msg_info(recdict, _('Deleting "%s"') % destname)
                        os.remove(destname)
                    except EnvironmentError, e:
                        msg_warning(recdict, (_('Could not delete "%s": ')
                                                          % destname) + str(e))

        else:

            # Create directories.
            if scheme == '' and destloc and not os.path.exists(destloc):
                if skip_commands():
                    msg_info(recdict, _('Skip create directory "%s"') % destloc)
                else:
                    msg_info(recdict, _('Creating directory "%s"') % destloc)
                    try:
                        os.makedirs(destloc)
                    except EnvironmentError, e:
                        recipe_error([], _('Could not create directory: %s') % e)

            if item.get("keepmode"):
                newmode = -1
            else:
                if item.get("mode"):
                    newmode = oct2int(item.get("mode"))
                else:
                    newmode = oct2int(modestr)
            dostrip = strip and stripprog and not item.get("nostrip")

            if skip_commands():
                msg_info(recdict, _('Skip copy "%s" to "%s"')
                                                            % (name, destname))
                if dostrip:
                    msg_info(recdict, _('Skip strip "%s"') % destname)
                if newmode >= 0:
                    msg_info(recdict, _('Skip chmod 0%o "%s"')
                                                         % (newmode, destname))
            else:
                if (newmode >= 0 or dostrip) and scheme != '':
                    # strip a remote program before copying, first make a copy.
                    tmpname = tempfname()
                    remote_copy_move(rpstack, recdict, 1,
                                [ {"name" : name} ], {"name" : tmpname},
                                {"force": 1}, 0, errmsg = 1)
                    if dostrip:
                        logged_system(recdict, "%s '%s'" % (stripprog, tmpname))
                    if newmode >= 0:
                        os.chmod(tmpname, newmode)
                    name = tmpname
                    copy = 0
                else:
                    copy = 1

                # Copy the file.
                remote_copy_move(rpstack, recdict, copy,
                            [ {"name" : name} ], {"name" : destname},
                            {"force": 1}, 0, errmsg = 1)

                # If stripping is requested and there is a strip program, strip.
                if dostrip and scheme == '':
                    logged_system(recdict, "%s '%s'" % (stripprog, destname))

                if newmode >= 0 and scheme == '':
                    os.chmod(destname, newmode)


def uninstall_files(desttail, source, mandir = 0):
    """
    Called by uninstall actions to remove files.
    """
    install_files(desttail, source, 0, mandir = mandir, uninstall = 1)


# vim: set sw=4 et sts=4 tw=79 fo+=l: