File: setup.py

package info (click to toggle)
python-kinterbasdb 3.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,432 kB
  • ctags: 1,830
  • sloc: ansic: 16,803; python: 3,514; makefile: 63; sh: 22
file content (1398 lines) | stat: -rw-r--r-- 58,405 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
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
# This horrible tangle of code will soon be blown away and replaced with
# something more respectable.  Yep, RSN.

import re, struct, sys, time
from StringIO import StringIO

# Exclude old versions of Python:
if not hasattr(sys, 'version_info') or sys.version_info < (2,3):
    raise NotImplementedError('This version of kinterbasdb requires Python 2.3'
        ' or later.'
      )

import ConfigParser, os, os.path, re, shutil
import distutils.core
import distutils.ccompiler
import distutils.sysconfig
import distutils.util

class BuildError(Exception): pass

def doCommand(cmd, header='COMMAND EXECUTION ERROR'):
    print '\t' + cmd
    taskOutStream = os.popen(cmd)
    taskOutput = taskOutStream.read()
    taskRetCode = taskOutStream.close()
    if taskRetCode is not None:
        raise BuildError('\n%s\n  Command [%s] died with error:\n[%s]\n'
            % (header, cmd, taskOutput)
          )
    return taskOutput

def doLibConvCmd(cmd):
    return doCommand(cmd, LIBCONVERSION_ERROR_HEADER)

def determineWindowsSystemDir():
    if sys.platform.lower() == 'cygwin':
        return doCommand('cygpath --sysdir')[:-1] # Trailing newline.
    else:
        # (normal win32)
        # If I were willing to introduce a win32all dependency into this build
        # script, this function would be replaced by win32api.GetSystemDirectory.
        winDir = os.environ.get('SYSTEMROOT', os.environ.get('WINDIR', 'C:\\Windows'))
        winSysDir = os.path.join(winDir, 'system32')
        if not os.path.isdir(winSysDir):
            winSysDir = os.path.join(winDir, 'system')
        return winSysDir

# Be careful about changing these messages; the build documentation refers to them.
PYTHON_SYSTEM_ERROR_HEADER = 'PYTHON SYSTEM ERROR:'
COMPILER_CONFIGURATION_ERROR_HEADER = 'COMPILER CONFIGURATION ERROR:'
KIDB_DISTRIBUTION_ERROR_HEADER = 'KINTERBASDB DISTRIBUTION ERROR:'
LIBCONVERSION_ERROR_HEADER = 'LIBRARY CONVERSION ERROR:'
AUTODETECTION_ERROR_HEADER = 'LIBRARY AUTODETECTION ERROR:'
MANUAL_SPECIFICATION_ERROR_HEADER = 'LIBRARY MANUAL SPECIFICATION ERROR:'

DISTUTILS_URL = 'http://www.python.org/sigs/distutils-sig/distutils.html'

VERSION_FILE = 'version.txt'
CONFIG_FILE = 'setup.cfg'

DEBUG = int(os.environ.get('KINTERBASDB_DEBUG', 0))

# Module name and version number:
kinterbasdb_name = 'kinterbasdb'
# Retrive the kinterbasdb version number from a central text file for the sake
# of maintainability:
try:
    kinterbasdb_version = open(VERSION_FILE).read().strip()
except IOError:
    raise BuildError(
        "\n%s\n"
        " File 'version.txt' is missing; cannot determine kinterbasdb"
        " version."
        % KIDB_DISTRIBUTION_ERROR_HEADER
      )

argJam = ' '.join(sys.argv[1:]).lower()
shouldSkipBuild = argJam.find('--skip-build') != -1
platformIsWindows = sys.platform.lower().startswith('win')


def isConfigValTrue(v):
    return str(v).strip().lower() in ('1', 'true', 'yes')


# These config parameters are user-specifiable via setup.cfg:
CHECKED_BUILD = 0
VERBOSE_DEBUGGING = 0

ENABLE_CONCURRENCY = 1
ENABLE_FREE_CONNECTION_AND_DISCONNECTION = 0

ENABLE_DB_EVENT_SUPPORT = 1
ENABLE_CONNECTION_TIMEOUT = 1
ENABLE_FIELD_PRECISION_DETERMINATION = 1
ENABLE_DB_ARRAY_SUPPORT = 1
ENABLE_DB_SERVICES_API = 1

DATABASE_IS_FIREBIRD = None
DATABASE_HOME_DIR = None
DATABASE_INCLUDE_DIR = None
DATABASE_LIB_DIR = None
DATABASE_LIB_NAME = None

# These config parameters are not drawn from setup.cfg:
CUSTOM_PREPROCESSOR_DEFS = []
PLATFORM_SPECIFIC_INCLUDE_DIRS = []
PLATFORM_SPECIFIC_LIB_DIRS = []
PLATFORM_SPECIFIC_LIB_NAMES = []
PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS = []
PLATFORM_SPECIFIC_EXTRA_LINKER_ARGS = []

# Create a list of all macro definitions that must be passed to distutils.
allMacroDefs = []

# Create a list of all extra options to pass to the compiler, linker.
allExtraCompilerArgs = []
extraCompilerArgsForExtension__kinterbasdb = []
extraCompilerArgsForExtension__kiservices = []

if not shouldSkipBuild:
    # Update the timestamp in kinterbasdb's __init__.py to reflect the time
    # (UTC zone) when this build script was run:
    initModule = file('__init__.py', 'rb')
    try:
        initModuleCode = initModule.read()
    finally:
        initModule.close()

    reTimestamp = re.compile(r"^(__timestamp__\s+=\s+')(.*?)(')$", re.MULTILINE)
    initModuleCode = reTimestamp.sub(
        r'\g<1>%s\g<3>' % time.strftime('%Y.%m.%d.%H.%M.%S.UTC', time.gmtime()),
        initModuleCode
      )

    initModule = file('__init__.py', 'wb')
    try:
        initModule.write(initModuleCode)
    finally:
        initModule.close()

    # See if the user manually specified various build options in the setup config
    # file.  If so, skip autodetection for the options that the user has specified.
    config = ConfigParser.ConfigParser()
    config.read(CONFIG_FILE)

    if config.has_section('manual_config'):
        def _boolConfOpt(name):
            if config.has_option('manual_config', name):
                return config.getboolean('manual_config', name)
            else:
                return False

        CHECKED_BUILD = _boolConfOpt('checked_build')
        VERBOSE_DEBUGGING = _boolConfOpt('verbose_debugging')

        ENABLE_CONCURRENCY = _boolConfOpt('enable_concurrency')
        if ENABLE_CONCURRENCY:
            try:
                import thread
            except ImportError:
                print ('Warning:  This Python interpreter was built with threading'
                    ' disabled, so kinterbasdb\'s concurrency support has been'
                    ' disabled.'
                  )
                ENABLE_CONCURRENCY = False

        ENABLE_FREE_CONNECTION_AND_DISCONNECTION = _boolConfOpt(
            'enable_free_connection_and_disconnection'
          )
        if ENABLE_FREE_CONNECTION_AND_DISCONNECTION and not ENABLE_CONCURRENCY:
            print ('Warning:  Free connection and disconnection support has been'
                ' disabled because concurrency is disabled.  (See setup.cfg'
                ' settings enable_concurrency and'
                ' enable_free_connection_and_disconnection.)'
              )
            ENABLE_FREE_CONNECTION_AND_DISCONNECTION = False

        ENABLE_DB_EVENT_SUPPORT = _boolConfOpt('enable_db_event_support')
        if ENABLE_DB_EVENT_SUPPORT and not ENABLE_CONCURRENCY:
            print ('Warning:  Database event support has been disabled because'
                ' concurrency is disabled.  (See setup.cfg settings'
                ' enable_concurrency and enable_db_event_support.)'
              )
            ENABLE_DB_EVENT_SUPPORT = False

        ENABLE_CONNECTION_TIMEOUT = _boolConfOpt('enable_connection_timeout')
        if ENABLE_CONNECTION_TIMEOUT and not ENABLE_CONCURRENCY:
            print ('Warning:  Connection timeout support has been disabled because'
                ' concurrency is disabled.  (See setup.cfg settings'
                ' enable_concurrency and enable_connection_timeout.)'
              )
            ENABLE_CONNECTION_TIMEOUT = False

        ENABLE_FIELD_PRECISION_DETERMINATION = _boolConfOpt('enable_field_precision_determination')
        ENABLE_DB_ARRAY_SUPPORT = _boolConfOpt('enable_db_array_support')
        ENABLE_DB_SERVICES_API = _boolConfOpt('enable_db_services_api')

        if config.has_option('manual_config', 'database_is_firebird'):
            DATABASE_IS_FIREBIRD = config.get('manual_config', 'database_is_firebird')
        if config.has_option('manual_config', 'database_home_dir'):
            DATABASE_HOME_DIR = config.get('manual_config', 'database_home_dir')
        if config.has_option('manual_config', 'database_include_dir'):
            DATABASE_INCLUDE_DIR = config.get('manual_config', 'database_include_dir')
        if config.has_option('manual_config', 'database_lib_dir'):
            DATABASE_LIB_DIR = config.get('manual_config', 'database_lib_dir')
        if config.has_option('manual_config', 'database_lib_name'):
            DATABASE_LIB_NAME = config.get('manual_config', 'database_lib_name')

        if DATABASE_HOME_DIR and not (DATABASE_INCLUDE_DIR or DATABASE_LIB_DIR):
            DATABASE_INCLUDE_DIR = os.path.join(DATABASE_HOME_DIR, 'include')
            DATABASE_LIB_DIR = os.path.join(DATABASE_HOME_DIR, 'lib')

        if DATABASE_INCLUDE_DIR is not None:
            fbHeaderPath = os.path.join(DATABASE_INCLUDE_DIR, 'ibase.h')
            if os.path.exists(fbHeaderPath):
                if 'FB_API_VER' in file(fbHeaderPath, 'rb').read():
                    if not DATABASE_IS_FIREBIRD:
                        DATABASE_IS_FIREBIRD = True

    if DEBUG:
        print "*** CONFIG OPTIONS SPECIFIED IN %s SECTION 'manual_config' ***" % CONFIG_FILE
        for key in config.options('manual_config'):
            print '%s:' % (key)
            print '    %s' % (config.get('manual_config', key))

    ALL_AUTODETECT_OPTIONS_MANUALLY_SPECIFIED = (
            DATABASE_IS_FIREBIRD is not None
        and DATABASE_HOME_DIR
        and DATABASE_INCLUDE_DIR
        and DATABASE_LIB_DIR
        and DATABASE_LIB_NAME
      )


    def verifyAutodetectedDatabaseIncludeDir():
        if not os.path.exists(DATABASE_INCLUDE_DIR):
            sys.stderr.write(
                "%s\n"
                "  Cannot autodetect the database header file directory.\n"
                "  (Tried %s)\n"
                "  Try specifying the 'database_include_dir' option in\n"
                "  the 'manual_config' section of the setup config file (%s).\n"
                % (AUTODETECTION_ERROR_HEADER, DATABASE_INCLUDE_DIR, CONFIG_FILE)
              )
            sys.exit(1)

    def verifyUserSpecifiedDatabaseIncludeDir():
        if not os.path.exists(DATABASE_INCLUDE_DIR):
            sys.stderr.write(
                "%s\n"
                "  The user-specified database header file directory\n"
                "    %s\n"
                "  does not exist.\n"
                "  Try modifying the 'database_include_dir' option in\n"
                "  the 'manual_config' section of the setup config file (%s),\n"
                "  or comment out that option to force this script to\n"
                "  to autodetect it.\n"
                % (MANUAL_SPECIFICATION_ERROR_HEADER, DATABASE_INCLUDE_DIR, CONFIG_FILE)
              )
            sys.exit(1)

    def verifyAutodetectedDatabaseLibraryDir():
        if not os.path.exists(DATABASE_LIB_DIR):
            sys.stderr.write(
                "%s\n"
                "  Cannot autodetect the database lib directory.\n"
                "  (Tried %s)\n"
                "  Try specifying the 'database_include_dir' option in\n"
                "  the 'manual_config' section of the setup config file (%s).\n"
                % (AUTODETECTION_ERROR_HEADER, DATABASE_LIB_DIR, CONFIG_FILE)
              )
            sys.exit(1)

    def verifyUserSpecifiedDatabaseLibraryDir():
        if not os.path.exists(DATABASE_LIB_DIR):
            sys.stderr.write(
                "%s\n"
                "  The user-specified database lib directory\n"
                "    %s\n"
                "  does not exist.\n"
                "  Try modifying the 'database_lib_dir' option in\n"
                "  the 'manual_config' section of the setup config file (%s),\n"
                "  or comment out that option to force this script to\n"
                "  to autodetect it.\n"
                % (MANUAL_SPECIFICATION_ERROR_HEADER, DATABASE_LIB_DIR, CONFIG_FILE)
              )
            sys.exit(1)

    def findSpacelessDirName(d):
        # On Windows, try to find the spaceless version of the provided directory
        # name.
        # This function was added on 2002.03.14 as part of an ugly hack to
        # surmount a bug in the distutils package.

        # Sometime distutils causes None to be fed to this function.
        if not d:
            return d
        d = os.path.normpath(os.path.abspath(d))
        if ' ' not in d:
            return d

        # If d doesn't exist, its short equivalent can't be determined.
        # However, for the purposes of this program (which is solely for
        # convenience anyway) it's better just to risk feeding the
        # compiler/linker a path with a space in it than it is to raise
        # an exception when there's still a *chance* of success.
        if not os.path.isdir(d):
            return d

        try:
            import win32api
            return os.path.normcase(win32api.GetShortPathName(d))
        except ImportError:
            # Since win32api is not available, we'll revert to a lame,
            # manual approximation of GetShortPathName.
            pass

        ds = d.split(os.sep) # Split into components.
        if DEBUG: print 'ds is', ds
        ds[0] = ds[0] + '\\' # Add slash back onto drive designation so that
                             # it's like c:\ rather than just c:

        dsNoSpaces = [] # Will contain a version of the directory components
                        # with all spaces removed.
        for x in range(len(ds)):
            dir = ds[x]
            if DEBUG: print 'dir is', dir

            if ' ' not in dir:
                shortDir = dir
            else:
                fullDir = apply(os.path.join, ds[:x + 1])
                if DEBUG: print 'fullDir is', fullDir

                # Must deal with names like 'abc de' that have their space
                # before the sixth character.
                dirNoSpaces = dir.replace(' ', '')
                if len(dirNoSpaces) < 6:
                    shortDirBase = dirNoSpaces
                else:
                    shortDirBase = dirNoSpaces[:6]

                # Search for shortDirBase~i until we find it.
                shortDir = None
                i = 1
                while i < 9: # This code doesn't handle situations where there are
                             # more than nine directories with the same prefix.
                    maybeShortDir = '%s~%d' % (shortDirBase, i)
                    fullMaybeShortDir = os.path.join(
                        os.path.dirname(fullDir), maybeShortDir)
                    if not os.path.isdir(fullMaybeShortDir):
                        continue

                    # There follows a *really* lame approximation of
                    # os.path.samefile, which is not available on Windows.
                    if os.listdir(fullMaybeShortDir) == os.listdir(fullDir):
                        shortDir = maybeShortDir
                        break

                    i = i + 1

                if shortDir is None:
                    raise Exception('Unable to find shortened version of'
                        ' directory named %s' % d
                      )

            dsNoSpaces.append(shortDir)

        if DEBUG:
            print 'dsNoSpaces is', dsNoSpaces

        return os.path.normcase(apply(os.path.join, dsNoSpaces))


    # Perform generic compilation parameter setup, then switch to platform-
    # specific.

    origWorkingDir = os.path.abspath(os.curdir)

    # Autodetect Python directory info.
    if DEBUG:
        print '*** PYTHON SETTINGS ***'

    pythonHomeDir = sys.exec_prefix
    pythonPkgDir = distutils.sysconfig.get_python_lib()

    if DEBUG:
        print '\tPython home dir:', pythonHomeDir
        print '\tPython package dir:', pythonPkgDir


    # Begin platform-specific compilation parameter setup:
    compilerIsMSVC = 0
    compilerIsMinGW = 0
    compilerIsGCC = 0

    if platformIsWindows:
        ALL_AUTODETECT_WINDOWS_REGISTRY_OPTIONS_MANUALLY_SPECIFIED = (
                DATABASE_HOME_DIR
            and DATABASE_INCLUDE_DIR
            and DATABASE_LIB_DIR
            and DATABASE_LIB_NAME
          )

        CUSTOM_PREPROCESSOR_DEFS.append( ('WIN32', None) )

        pyVersionSuffix = ''.join( [str(n) for n in sys.version_info[:2]] )
        pyLibName = 'python%s.lib' % pyVersionSuffix

        # 2003.03.28: Accomodate source dists of Python on Windows (give the
        # PCBuild\pythonVV.lib file (if any) precedence over the
        # libs\pythonVV.lib file (if any)):
        pyLibsDir = os.path.join(pythonHomeDir, 'PCbuild')
        if not os.path.exists(os.path.join(pyLibsDir, pyLibName)):
            pyLibsDir = os.path.join(pythonHomeDir, 'libs')

        pyConventionalLibPath = os.path.join(pyLibsDir, pyLibName)

        # If this is a source distribution of Python, add a couple of necessary
        # include and lib directories.
        pcbuildDir = os.path.join(
            os.path.dirname(distutils.sysconfig.get_python_inc()), 'PCBuild'
          )
        if os.path.exists(pcbuildDir):
            PLATFORM_SPECIFIC_LIB_DIRS.append(pcbuildDir)

            pySrcDistExtraIncludeDir = os.path.join(
                os.path.dirname(distutils.sysconfig.get_python_inc()), 'PC'
              )
            PLATFORM_SPECIFIC_INCLUDE_DIRS.append(pySrcDistExtraIncludeDir)

        # Verify the various directories (such as include and library dirs) that
        # will be used during compilation.

        # Open the registry in preparation for reading various installation
        # directories from it.
        try:
            import _winreg
        except ImportError:
            # If the user has manually specified all of the options that would
            # require registry access to autodetect, we can proceed despite the
            # lack of _winreg.
            if not ALL_AUTODETECT_WINDOWS_REGISTRY_OPTIONS_MANUALLY_SPECIFIED:
                sys.stderr.write(
                    "%s\n"
                    "  Cannot import the standard package '_winreg'.\n"
                    "  _winreg did not join the standard library until\n"
                    "  Python 2.0.  If you are using a source distribution\n"
                    "  of Python 2.0 or later, you may have simply forgotten\n"
                    "  to compile the _winreg C extension.\n"
                    "  You can get around the lack of _winreg by manually\n"
                    "  specifying all of the configuration options in the\n"
                    "  'manual_config' section of the setup config file (%s)."
                    % (AUTODETECTION_ERROR_HEADER, CONFIG_FILE)
                  )
                sys.exit(1)

        if not ALL_AUTODETECT_WINDOWS_REGISTRY_OPTIONS_MANUALLY_SPECIFIED:
            try:
                r = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
            except WindowsError, e:
                sys.stderr.write(
                    "%s\n"
                    "  Unable to connect to the HKEY_LOCAL_MACHINE section of\n"
                    "  the Windows registry.\n"
                    "  The specific error encountered is:\n"
                    "  %s"
                    % (AUTODETECTION_ERROR_HEADER, str(e))
                  )
                sys.exit(1)

        if DEBUG:
            print '*** DATABASE SETTINGS ***'

        # Autodetect database directory info if the user did not specify it.
        if not DATABASE_HOME_DIR:
            def findDatabaseHomeDir(databaseInfoKey, databaseHomeValueName):
                databaseCurrentVersionKey = _winreg.OpenKey(r, databaseInfoKey)
                try:
                    return _winreg.QueryValueEx(
                        databaseCurrentVersionKey,
                        databaseHomeValueName
                      )[0]
                finally:
                    _winreg.CloseKey(databaseCurrentVersionKey)

            # Try to find Firebird first; revert to Interbase only if necessary.
            try:
                try:
                    # 2003.11.10: Firebird 1.5 RC7 changed the registry structure.
                    DATABASE_HOME_DIR = findDatabaseHomeDir(
                        r'SOFTWARE\Firebird Project\Firebird Server\Instances',
                        'DefaultInstance'
                      )
                    DATABASE_IS_FIREBIRD = 1
                except WindowsError:
                    try:
                        # Firebird 1.0-Firebird 1.5 RC6:
                        DATABASE_HOME_DIR = findDatabaseHomeDir(
                            r'SOFTWARE\FirebirdSQL\Firebird\CurrentVersion',
                            'RootDirectory'
                          )
                        DATABASE_IS_FIREBIRD = 1
                    except WindowsError:
                        # Revert to Interbase.
                        DATABASE_IS_FIREBIRD = 0
                        DATABASE_HOME_DIR = findDatabaseHomeDir(
                            r'SOFTWARE\Borland\InterBase\CurrentVersion',
                            'RootDirectory'
                          )
            except WindowsError, e:
                sys.stderr.write(
                    "%s\n"
                    "  Unable to retrieve database directory from the Windows"
                    " registry.\n"
                    "  Try specifying the 'database_home_dir' option in the\n"
                    "  'manual_config' section of the setup config file (%s).\n"
                    "  The specific error encountered is:\n"
                    "  %s"
                    % (AUTODETECTION_ERROR_HEADER, CONFIG_FILE, str(e))
                  )
                sys.exit(1)

        if DATABASE_INCLUDE_DIR:
            verifyUserSpecifiedDatabaseIncludeDir()
            databaseSDKDir = os.path.dirname(DATABASE_INCLUDE_DIR)
        else:
            databaseSDKDir = os.path.join(DATABASE_HOME_DIR, 'SDK')
            if DATABASE_IS_FIREBIRD or not os.path.exists(databaseSDKDir):
                databaseSDKDir = DATABASE_HOME_DIR

            DATABASE_INCLUDE_DIR = os.path.join(databaseSDKDir, 'include')

            if DEBUG:
                print (
                    '\tDATABASE_INCLUDE_DIR exists at\n\t  %s: %d'
                    % (DATABASE_INCLUDE_DIR, os.path.exists(DATABASE_INCLUDE_DIR))
                  )

            verifyAutodetectedDatabaseIncludeDir()

        if DATABASE_LIB_DIR:
            verifyUserSpecifiedDatabaseLibraryDir()
        else:
            DATABASE_LIB_DIR = os.path.join(databaseSDKDir, 'lib')

            verifyAutodetectedDatabaseLibraryDir()

        # Try to "autodetect" library.
        if not DATABASE_LIB_NAME:
            if os.path.exists(os.path.join(DATABASE_LIB_DIR, 'firebird.lib')):
                DATABASE_LIB_NAME = 'firebird' # Vulcan
            elif os.path.exists(os.path.join(DATABASE_LIB_DIR, 'fbclient_ms.lib')):
                DATABASE_LIB_NAME = 'fbclient_ms' # FB 1.5 or 2.0
            else:
                DATABASE_LIB_NAME = 'gds32' # Default (IB5.5/IB6/FB1)

        # Perform compiler-specific setup.

        # I should discover a way to ask distutils what compiler it's
        # configured to use--the current code would only detect a compiler
        # change via the command line.  I've looked at the compiler subpackage
        # of distutils, and can't find any such facility (though it can be
        # queried for the system's default compiler).
        customCompilerName = 'msvc'

        match = re.search(r'--compiler=(?P<cname>\S+)', argJam)
        if match:
            customCompilerName = match.group('cname')
        else:
            match = re.search(r'-c\s*(?P<cname>\S+)', argJam)
            if match:
                customCompilerName = match.group('cname')

        compilerIsMSVC = customCompilerName.lower().startswith('msvc')
        compilerIsMinGW = customCompilerName.lower().startswith('mingw')

        if customCompilerName == 'msvc':
        # 2008.11.25: commented this part since it cause problem with VS2003 and newer
        # running vcvars32.bat before the build is enough
        # Philippe Makowski
        #    # 2004.11.05: SF 1056684:
        #    # If MSVC is assumed to be the compiler (which it is, on Windows,
        #    # unless the user explicitly indicates otherwise), but we're not
        #    # actually compiling (as when this script is invoked with
        #    # 'setup.py install --skip-build'), skip the registry lookups that'll
        #    # break if MSVC is not installed.
        #    if not shouldSkipBuild:
        #        # 2004.10.24:
        #        # Autodetect support files for "Microsoft Visual C++ Toolkit 2003":
        #        if sys.version_info[:2] >= (2,4):
        #            directoriesKey = _winreg.OpenKey(r,
        #                r'SOFTWARE\Microsoft\MicrosoftSDK\Directories'
        #              )
        #            try:
        #                windowsSDKDir = _winreg.QueryValueEx(
        #                    directoriesKey,
        #                    'Install Dir'
        #                  )[0]
        #            finally:
        #                _winreg.CloseKey(directoriesKey)
        #
        #            windowsSDKLibDir = os.path.join(windowsSDKDir, 'Lib')
        #            PLATFORM_SPECIFIC_LIB_DIRS.append(windowsSDKLibDir)
        #        # End "Microsoft Visual C++ Toolkit 2003" support code.
        #        else:
        #            # 2004.10.28: Better support for building with VStudio 6 when
        #            # "Register Environment Variables" was not selected during the
        #            # installation process (vcvars32.bat doesn't quite paper over
        #            # all of the differences).
        #            vcKey = _winreg.OpenKey(r,
        #                r'SOFTWARE\Microsoft\DevStudio\6.0\Products\Microsoft Visual C++'
        #              )
        #            try:
        #                vcDir = _winreg.QueryValueEx(vcKey, 'ProductDir')[0]
        #            finally:
        #                _winreg.CloseKey(vcKey)
        #
        #            PLATFORM_SPECIFIC_INCLUDE_DIRS.append(os.path.join(vcDir, 'Include'))
        #            PLATFORM_SPECIFIC_LIB_DIRS.append(os.path.join(vcDir, 'Lib'))


            if not DATABASE_IS_FIREBIRD:
                DATABASE_LIB_DIR = os.path.join(databaseSDKDir, r'lib_ms')
                if not os.path.exists(DATABASE_LIB_DIR):
                    DATABASE_LIB_DIR = os.path.join(databaseSDKDir, r'lib')

            if not DATABASE_LIB_NAME or DATABASE_LIB_NAME == 'gds32':
                DATABASE_LIB_NAME = 'gds32_ms'
        elif customCompilerName == 'bcpp':
            print '  *** BCPP LIBRARY GENERATION : begin ***'
            COMPILER_EXE_NAME = 'bcc32.exe'

            # Try to find the home directory of the Borland compiler by searching
            # each directory listed in the PATH.
            # If I were willing to depend on win32all, win32api.FindExecutable
            # would replace this code.
            osPath = os.environ['PATH'].split(os.pathsep)
            bccHome = None
            for dir in osPath:
                if os.path.exists(os.path.join(dir, COMPILER_EXE_NAME)):
                    bccHome = os.path.split(dir)[0]
                    break
            else:
                # Couldn't find it.
                sys.stderr.write(
                    "%s\n"
                    "  Unable to find the home directory of the Borland"
                    " compiler.\n"
                    "  You must add the 'bin' subdirectory of the"
                    " compiler's\n"
                    "  home directory to your PATH.\n"
                    "  One way to do this is to type a command of the"
                    " format\n"
                    "    SET PATH=%%PATH%%;c:\\EXAMPLE_DIR\\bin\n"
                    "  in the same command prompt you use to run the"
                    " kinterbasdb setup script."
                    % (COMPILER_CONFIGURATION_ERROR_HEADER,)
                  )
                sys.exit(1)

            # Override the default behavior of distutils.bcppcompiler.BCPPCompiler
            # in order to force it to issue the correct command.
            from distutils.bcppcompiler import BCPPCompiler
            def _makeDirNameSpacless(kwargs, argName):
                x = kwargs.get(argName, None)
                if x is None:
                    return
                elif isinstance(x, str):
                    kwargs[argName] = findSpacelessDirName(x)
                else: # sequence of strings
                    kwargs[argName] = [ findSpacelessDirName(d) for d in x ]

            class BCPP_UGLY_Hack(BCPPCompiler):
                def compile (self, *args, **kwargs):
                    bccIncludePreargDir = findSpacelessDirName(r'%s\include' % bccHome)
                    bccLibPreargDir = findSpacelessDirName(r'%s\lib' % bccHome)
                    bccLibPSDKPreargDir = findSpacelessDirName(r'%s\lib\psdk' % bccHome)

                    kwargs['extra_preargs'] = (
                        [
                          r'-I"%s"' % bccIncludePreargDir,
                          r'-L"%s"' % bccLibPreargDir,
                          r'-L"%s"' % bccLibPSDKPreargDir
                        ]
                        + kwargs.get('extra_preargs', [])
                      )
                    for argName in ('output_dir', 'include_dirs'):
                        _makeDirNameSpacless(kwargs, argName)

                    return BCPPCompiler.compile(self, *args, **kwargs)


                def link (self, *args, **kwargs):
                    ilinkLibPreargDir = findSpacelessDirName(r'%s\lib' % bccHome)
                    ilinkLibPSDKPreargDir = findSpacelessDirName(r'%s\lib\psdk' % bccHome)

                    myPreArgs = [
                        r'/L"%s"' % ilinkLibPreargDir,
                        r'/L"%s"' % ilinkLibPSDKPreargDir
                      ]
                    if 'extra_preargs' not in kwargs:
                        argsAsList = list(args)
                        argsAsList[9] = myPreArgs # see distuils.ccompiler.py
                        args = tuple(argsAsList)
                    else:
                        kwargs['extra_preargs'] = myPreArgs + kwargs.get['extra_preargs']

                    for argName in (
                        'output_dir', 'library_dirs',
                        'runtime_library_dirs', 'build_temp'
                      ):
                        _makeDirNameSpacless(kwargs, argName)

                    return BCPPCompiler.link(self, *args, **kwargs)


            # Force distutils to use our BCPP_UGLY_Hack class rather than the
            # default BCPPCompiler class.
            compilerSetupTuple = distutils.ccompiler.compiler_class['bcpp']
            import distutils.bcppcompiler
            distutils.bcppcompiler.BCPP_UGLY_Hack = BCPP_UGLY_Hack
            distutils.ccompiler.compiler_class['bcpp'] = (
                compilerSetupTuple[0], 'BCPP_UGLY_Hack', compilerSetupTuple[2]
              )

            # Use the Borland command-line library conversion tool coff2omf to
            # create a Borland-compiler-compatible library file,
            # "pythonVV_bcpp.lib", from the standard "pythonVV.lib".
            libName = os.path.join(pyLibsDir, 'python%s_bcpp.lib' % pyVersionSuffix)
            if not os.path.exists(libName):
                print 'setup.py is trying to create %s' % libName
                coff2omfCommand = ('coff2omf %s %s' % (pyConventionalLibPath, libName))

                os.system(coff2omfCommand)
                # Do this test instead of checking the return value of
                # os.system, which will not reliably indicate an error
                # condition on Win9x.
                if not os.path.exists(libName):
                    sys.stderr.write(
                        "%s\n"
                        "  Unable to create a Borland-compatible Python"
                        " library file using the\n"
                        "  coff2omf utility.\n"
                        "  Tried command:\n"
                        "    %s"
                        % (COMPILER_CONFIGURATION_ERROR_HEADER, coff2omfCommand)
                      )
                    sys.exit(1)
            assert os.path.isfile(libName)
            print '  *** BCPP LIBRARY GENERATION : end ***'
        elif compilerIsMinGW: # 2003.08.05:
            print '  *** MINGW LIBRARY GENERATION : begin ***'
            # Use the MinGW tools pexports and dlltool to create a GCC-compatible
            # library file for Python.
            # Firebird 1.5 already includes a suitable library file
            # (fbclient_ms.lib).  Versions earlier than FB 1.5 don't work with
            # MinGW, so override IB6/FB1-like lib names.
            if DATABASE_LIB_NAME in ('gds32', 'gds32_ms'):
                if DATABASE_LIB_NAME is not None:
                    print (
                        '\tIgnoring your "%s" library name setting in favor\n'
                        '\tof "fbclient_ms", which is the proper choice for\n'
                        '\tMinGW.'
                        % DATABASE_LIB_NAME
                      )
                DATABASE_LIB_NAME = 'fbclient_ms'

            winSysDir = determineWindowsSystemDir()

            # Python (pythonVV.lib -> libpythonVV.a):
            pyDLL = 'python%s.dll' % pyVersionSuffix
            pyDLLPathPossibilies = [os.path.join(d, pyDLL) for d in
                (pythonHomeDir, pcbuildDir, winSysDir)
              ]
            for pyDLLPath in pyDLLPathPossibilies:
                if os.path.isfile(pyDLLPath):
                    break
            else:
                raise BuildError("""\n%s\n  Can't find Python DLL "%s"."""
                    % (LIBCONVERSION_ERROR_HEADER, pyDLL)
                  )

            libName = 'libpython%s.a' % pyVersionSuffix
            libUltimateDest = os.path.join(pyLibsDir, libName)
            defFilename = 'python%s.def' % pyVersionSuffix
            if os.path.isfile(libUltimateDest):
                print ('\tMinGW-compatible Python library already exists at:\n\t  %s'
                    % libUltimateDest
                  )
            else:
                print (
                    '\n\tsetup.py is trying to create MinGW-compatible Python'
                    ' library at:\n'
                    '\t  "%s"'
                    % libUltimateDest
                  )
                os.chdir(os.path.dirname(pyDLLPath))
                try:
                    doLibConvCmd('pexports %s > %s' % (pyDLL, defFilename))
                    doLibConvCmd(
                        'dlltool --dllname %s --def %s --output-lib %s'
                        % (pyDLL, defFilename, libName)
                      )
                    os.remove(defFilename)
                    # With source builds of some versions of Python, the Python DLL
                    # is located in the same directory that distutils declares to
                    # be the "library directory", so the generated library file
                    # shouldn't be moved.
                    if os.path.dirname(libUltimateDest).lower() != os.path.abspath(os.curdir).lower():
                        shutil.copyfile(libName, libUltimateDest)
                        os.remove(libName)
                finally:
                    os.chdir(origWorkingDir)

            assert os.path.isfile(libUltimateDest)
            print '  *** MINGW LIBRARY GENERATION : end ***\n'

        if DEBUG:
            print '\tDATABASE_LIB_DIR exists at\n\t  %s: %d' \
                % (DATABASE_LIB_DIR, os.path.exists(DATABASE_LIB_DIR))
            print '\tDATABASE_LIB_NAME is\n\t  %s' % DATABASE_LIB_NAME

    elif sys.platform.lower() == 'cygwin': # 2003.08.05:
        print '  *** CYGWIN LIBRARY GENERATION : begin ***'
        if DATABASE_LIB_NAME != 'fbclient':
            if DATABASE_LIB_NAME is not None:
                print (
                    '\tIgnoring your "%s" library name setting in favor of\n'
                    '\t  "fbclient", which is the proper choice for Cygwin.'
                    % DATABASE_LIB_NAME
                  )
            DATABASE_LIB_NAME = 'fbclient'

        winSysDir = determineWindowsSystemDir()

        # 2003.11.10: Switched to FB 1.5 RC7+ reg structure.
        # baseRegLoc = '/proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/FirebirdSQL/Firebird/CurrentVersion'
        regInstLoc = (
            '/proc/registry/HKEY_LOCAL_MACHINE/SOFTWARE/Firebird Project'
            '/Firebird Server/Instances/DefaultInstance'
          )
        # Read the location of Firebird from the Windows registry.
        try:
            fbDir = doLibConvCmd('cat "%s"' % regInstLoc)[:-1] # Trailing null byte.
        except BuildError:
            raise BuildError("\n%s\n  Windows registry settings for Firebird 1.5"
                " were not found.  Try running Firebird's instreg.exe utility."
                " (Firebird 1.5 before RC7, Firebird 1.0, and Interbase are not"
                " supported.)"
                % AUTODETECTION_ERROR_HEADER
              )

        if fbDir.endswith('\\'):
            fbDir = fbDir[:-1] # Trailing backslash.
        fbDir = fbDir.replace('\\', '/')
        fbDir = doLibConvCmd('cygpath --unix %s' % fbDir)[:-1] # Trailing null byte.

        if DATABASE_INCLUDE_DIR:
            verifyUserSpecifiedDatabaseIncludeDir()
        else:
            DATABASE_INCLUDE_DIR = os.path.join(fbDir, 'include')
            verifyAutodetectedDatabaseIncludeDir()

        libUltimateDest = '/usr/lib/libfbclient.a'
        libUltimateDir, libName = os.path.split(libUltimateDest)
        if os.path.isfile(libUltimateDest):
            print ('\tCygwin-compatible Firebird library already exists at:\n\t  %s'
                % libUltimateDest
              )
        else:
            print (
                '\n\tsetup.py is trying to create cygwin-compatible Firebird'
                ' library at:\n'
                '\t  "%s"'
                % libUltimateDest
              )

            fbClientLibFilename = os.path.join(fbDir, 'lib', 'fbclient_ms.lib')

            origCurDir = os.path.abspath(os.curdir)
            os.chdir(winSysDir)
            try:
                # Create def file containing symbols from fbclient_ms.lib.
                doLibConvCmd(
                    '''(echo EXPORTS; nm %s  | grep " T _"'''
                    ''' | sed 's/.* T _//g' | sed 's/@.*$//g')'''
                    ''' > fbclient.def'''
                    % fbClientLibFilename
                  )
                # End lame pexports substitute.

                # Create lib file from DLL and the just-generated def file.
                doLibConvCmd(
                    'dlltool --dllname fbclient.dll --def fbclient.def --output-lib %s'
                    % libName
                  )
                os.remove('fbclient.def')
                # Move the lib file to a location where cygwin-GCC's linker will
                # find it.
                shutil.copyfile(libName, libUltimateDest)
                os.remove(libName)
            finally:
                os.chdir(origCurDir)

        assert os.path.isfile(libUltimateDest)
        print '  *** CYGWIN LIBRARY GENERATION : end ***\n'

    elif sys.platform.lower() == 'darwin': # Based on Patch 909886 (Piet van oostrum)
        PLATFORM_SPECIFIC_EXTRA_LINKER_ARGS.extend(['-framework', 'Firebird'])
        # Don't override the include dir specified in setup.cfg, if any:
        if not DATABASE_INCLUDE_DIR:
            DATABASE_INCLUDE_DIR = '/Library/Frameworks/Firebird.framework/Headers'

    else: # not win32, cygwin, or darwin
        # If the platform isn't Linux, issue a warning.
        if not sys.platform.lower().startswith('linux'):
            sys.stderr.write("Warning:  The kinterbasdb setup code was not"
                " specifically written to support your platform (%s), and"
                " may not work properly.\n"
                % sys.platform
              )

        # Is libcrypt necessary on all POSIX OSes, or just Linux?
        # Until someone informs me otherwise, I'll assume all.
        if os.name == 'posix':
            PLATFORM_SPECIFIC_LIB_NAMES.append('crypt')

        # Verify the various directories (such as include and library dirs) that
        # will be used during compilation.

        # Assumption:
        # This is a Unix-like OS, where a proper installation routine would have
        # placed the database [header, library] files in system-wide dirs.
        # We have no way of knowing beyond the shadow of a doubt whether that
        # has happened (as opposed to the situation on Windows, where we can
        # consult the registry to determine where a binary installer placed its
        # files), so we'll just let the compiler complain if it can't find the
        # [header, library] files.
        # If, on the other hand, the user manually specified the directories, we
        # verify that they exist before invoking the compiler.

        if DATABASE_INCLUDE_DIR: # the user manually specified it
            verifyUserSpecifiedDatabaseIncludeDir()

        if DATABASE_LIB_DIR: # the user manually specified it
            verifyUserSpecifiedDatabaseLibraryDir()

        # 2003.04.12:
        # On FreeBSD 4, the header and library files apparently are not made
        # visible by default.
        # This script attempts to "autodetect" an installation at the default
        # location, but only if:
        # - no DATABASE_HOME_DIR has been manually specified
        # - the default installation directory actually exists
        #
        # This "autodetection" will probably work for some other Unixes as well.
        if not DATABASE_HOME_DIR:
            DEFAULT_FREEBSD_HOME_DIR = '/usr/local/firebird'
            if os.path.isdir(DEFAULT_FREEBSD_HOME_DIR):
                DATABASE_HOME_DIR = DEFAULT_FREEBSD_HOME_DIR
                if not DATABASE_INCLUDE_DIR:
                    DATABASE_INCLUDE_DIR = os.path.join(DATABASE_HOME_DIR, 'include')
                if not DATABASE_LIB_DIR:
                    DATABASE_LIB_DIR = os.path.join(DATABASE_HOME_DIR, 'lib')

        if not DATABASE_LIB_NAME:
            # 2003.07.29:  If the user hasn't specified the name of the database
            # library, this script will now guess its way from the most recent
            # known library back to the oldest, most conservative option.
            # The goal of this smarter probing is to allow kinterbasdb to build out
            # of the box with Firebird 1.5, without *requiring* the user to modify
            # setup.cfg to specify the correct library name.
            #
            # YYY: This isn't the most proper way to probe for libraries using
            # distutils, but I must admit that propriety isn't my highest priority
            # in this setup script.
            import distutils.command.config as cmd_conf
            import distutils.dist as dist_dist

            class _ConfigUglyHack(cmd_conf.config):
                # _ConfigUglyHack circumvents a distutils problem brought to light
                # on Unix by this script's abuse of the distutils.
                def try_link(self, *args, **kwargs):
                    self.compiler.exe_extension = '' # ('' rather than None)
                    return cmd_conf.config.try_link(self, *args, **kwargs)

            cfg = _ConfigUglyHack(dist_dist.Distribution())
            for possibleLib in ('fbclient', 'fbembed'):
                if cfg.check_lib(possibleLib):
                    DATABASE_LIB_NAME = possibleLib
                    break
            else:
                DATABASE_LIB_NAME = 'gds'

    # On any non-Windows platform, assume that GCC is the compiler:
    compilerIsGCC = ((compilerIsMinGW or not platformIsWindows) and 1) or 0

    if compilerIsMSVC:
        # MSVC's /Wall generates warnings for just about everything one could
        # imagine (even just to indicate that it has inlined a function).  Some of
        # these are useful, but most aren't, so it's off by default.
        #PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('/Wall')

        # Generate warnings for potential 64-bit portability problems (this option
        # is not available in MSVC 6):
        if not (sys.version_info < (2,4) or 'MSC V.1200 ' in sys.version.upper()):
            PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('/Wp64')

        # Enable the pooling of read-only strings (reduces executable size
        # considerably, esp. when checked_build=1):
        PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('/GF')

        if CHECKED_BUILD:
            # Generate debugging symbol files (.pdb):
            PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('/Zi')
            buildDir = os.path.abspath(os.path.join(
                os.path.dirname(__file__), 'build'
              ))
            libDir = 'lib.%s-%s' % (
                distutils.util.get_platform(),
                '.'.join( [str(n) for n in sys.version_info[:2]] )
              )
            libPath = os.path.join(buildDir, libDir)
            for extensionName in ('_kinterbasdb', '_kiservices'):
                extraCompilerArgsForExt = globals()[
                    'extraCompilerArgsForExtension_' + extensionName
                  ]
                extraCompilerArgsForExt.append(
                    r'/Fd"%s\kinterbasdb\%s.pdb"' % (libPath, extensionName)
                  )
    elif compilerIsGCC:
        if CHECKED_BUILD:
            PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('-pedantic')
            # Include debugging symbols:
            PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('-g')

        # Prevent GCC from complaining about various things that are perfectly
        # legitimate, but not part of the C90 standard:
        PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('-std=c99')

        # By default, distutils includes the -fno-strict-aliasing flag on
        # *nix-GCC, but not on MinGW-GCC.
        PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('-fno-strict-aliasing')

        if not platformIsWindows:
            # Python's distutils infrastructure should already include this
            # argument if Python itself was compiled with threading enabled,
            # but make sure:
            PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('-pthread')

        PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS.append('-O3')

# Now finished with platform-specific compilation parameter setup.

# Create a list of all INCLUDE dirs to be passed to setup():
allIncludeDirs = []

# Add Python include directory:
allIncludeDirs.append(distutils.sysconfig.get_python_inc())

if len(PLATFORM_SPECIFIC_INCLUDE_DIRS) > 0:
    allIncludeDirs.extend(PLATFORM_SPECIFIC_INCLUDE_DIRS)

if DATABASE_INCLUDE_DIR:
    allIncludeDirs.append(DATABASE_INCLUDE_DIR)

# Create a list of all LIB names to be passed to setup():
allLibNames = []
if DATABASE_LIB_NAME:
    allLibNames.append(DATABASE_LIB_NAME)
allLibNames.extend(PLATFORM_SPECIFIC_LIB_NAMES)

# Create a list of all LIB directories to be passed to setup():
allLibDirs = []
if len(PLATFORM_SPECIFIC_LIB_DIRS) > 0:
    allLibDirs.extend(PLATFORM_SPECIFIC_LIB_DIRS)

if DATABASE_LIB_DIR:
    allLibDirs.append(DATABASE_LIB_DIR)

if len(CUSTOM_PREPROCESSOR_DEFS) > 0:
    allMacroDefs.extend(CUSTOM_PREPROCESSOR_DEFS)

if CHECKED_BUILD:
    # Activate assertions.
    # (Lack of a second tuple element is the distutils conventions for
    # "undefine this macro".)
    allMacroDefs.append(('NDEBUG',))
else:
    allMacroDefs.append(('NDEBUG', 1))

preprocConfigFile = file('__ki_platform_config.h', 'wb')
def defineConfigItem(name, value=None):
    print >> preprocConfigFile, '#define %s%s' % (
        name, (value and ' %s' % value) or ''
      )

for sizeOfName, sizeOfVal in (
    ('SIZEOF_POINTER', struct.calcsize('P')),
    ('SIZEOF_INT', struct.calcsize('i')),
    ('SIZEOF_LONG', struct.calcsize('l')),
  ):
    defineConfigItem(sizeOfName, sizeOfVal)

for boolOptName in (
    'VERBOSE_DEBUGGING',
    'ENABLE_CONCURRENCY',
    'ENABLE_FREE_CONNECTION_AND_DISCONNECTION',
    'ENABLE_DB_EVENT_SUPPORT',
    'ENABLE_CONNECTION_TIMEOUT',
    'ENABLE_FIELD_PRECISION_DETERMINATION',
    'ENABLE_DB_ARRAY_SUPPORT',
    'ENABLE_DB_SERVICES_API',
  ):
    if eval(boolOptName):
        defineConfigItem(boolOptName)


if len(PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS) > 0:
    allExtraCompilerArgs.extend(PLATFORM_SPECIFIC_EXTRA_COMPILER_ARGS)

allExtraLinkerArgs = [] # MSVC will produce .pdbs with '/DEBUG'.
if len(PLATFORM_SPECIFIC_EXTRA_LINKER_ARGS) > 0:
    allExtraLinkerArgs.extend(PLATFORM_SPECIFIC_EXTRA_LINKER_ARGS)

# Work around the quirks in compiling against an uninstalled build of the FB
# server on POSIX:
if (    DATABASE_LIB_DIR is not None
    and os.path.split(os.path.dirname(os.path.dirname(DATABASE_LIB_DIR)))[1]
        == 'gen'
  ):
    if 'gds' in allLibNames:
        allLibNames.remove('gds')
    allLibNames.append('fbclient')
    allLibDirs.append(os.path.join(DATABASE_LIB_DIR, 'lib'))

extensionModules = [
    distutils.core.Extension( "kinterbasdb._kinterbasdb",
        sources=["_kinterbasdb.c"],
        libraries=allLibNames,
        include_dirs=allIncludeDirs,
        library_dirs=allLibDirs,
        define_macros=allMacroDefs,
        extra_compile_args=allExtraCompilerArgs
          + extraCompilerArgsForExtension__kinterbasdb,
        extra_link_args=allExtraLinkerArgs
      ),
  ]


allPythonModules = [
    'kinterbasdb.__init__',
    'kinterbasdb.k_exceptions',

    'kinterbasdb.typeconv_naked',
    'kinterbasdb.typeconv_backcompat',
    'kinterbasdb.typeconv_23plus',

    'kinterbasdb.typeconv_fixed_stdlib',
    'kinterbasdb.typeconv_fixed_fixedpoint',

    'kinterbasdb.typeconv_datetime_naked',
    'kinterbasdb.typeconv_datetime_stdlib',
    'kinterbasdb.typeconv_datetime_mx',

    'kinterbasdb.typeconv_text_unicode',

    'kinterbasdb._array_descriptor',
    'kinterbasdb._connection_timeout',
    'kinterbasdb._request_buffer_builder', # 2006.02.16
  ]

if kinterbasdb_version >= '3.2':
    allPythonModules.extend([
        'kinterbasdb.typeconv_23plus_lowmem', # 2005.11.28
        'kinterbasdb.typeconv_24plus',
        'kinterbasdb.typeconv_fixed_decimal',
      ])

# 2003.02.18:
# Build somewhat differently if we're dealing with an IB version before 6.0.
# (Innocent until proven guilty.)
isIBLessThan_6_0 = 0
for incDir in allIncludeDirs:
    headerFilename = os.path.join(incDir, 'ibase.h')
    if os.path.exists(headerFilename):
        # Using the isc_decode_sql_time symbol as the detector is kinda arbitrary.
        if 'isc_decode_sql_time' not in open(headerFilename).read():
            isIBLessThan_6_0 = 1
            break

# Only include the services module if dealing with >= IB 6.0.
if isIBLessThan_6_0:
    print >> sys.stderr, \
        'WARNING:  Not building the kinterbasdb._services module because' \
        ' IB < 6.0 does not support it.'
else:
    if ENABLE_DB_SERVICES_API:
        allPythonModules.append('kinterbasdb.services')
        extensionModules.append(
            distutils.core.Extension( "kinterbasdb._kiservices",
                sources=["_kiservices.c"],
                libraries=allLibNames,
                include_dirs=allIncludeDirs,
                library_dirs=allLibDirs,
                define_macros=allMacroDefs,
                extra_compile_args=allExtraCompilerArgs
                  + extraCompilerArgsForExtension__kiservices,
                extra_link_args=allExtraLinkerArgs
              )
          )

# Now we've detected and verified all compilation parameters, and are ready to
# compile.

if DEBUG:
    print '*** SETTINGS DETECTION PHASE COMPLETE; READY FOR BUILD ***'
    print ("\tThe DEBUG flag is enabled, so the setup script stops\n"
           "\t  before actually invoking the distutils setup procedure."
        )
    sys.exit(0)


from distutils.command.config import config as DefaultConfigCommand
from distutils.command.build_ext import build_ext as DefaultBuildExtCommand
class ConfigCommand(DefaultConfigCommand):
    def run(self):
        print '-' * 79
        print 'WILL NOW PROBE DATABASE API FOR FEATURES.'
        print 'COMPILER ERRORS THAT ARISE DURING THIS PHASE ARE NOT A PROBLEM.'
        print '-' * 79

        # Suppress the probe-compilation output:
        origStdOut = sys.stdout
        origStdErr = sys.stderr
        sys.stdout = sys.stderr = StringIO()
        try:
            self._run()
        finally:
            sys.stdout = origStdOut
            sys.stderr = origStdErr

        print '-' * 79
        print 'FINISHED PROBING DATABASE API FOR FEATURES.'
        print '-' * 79


    def _run(self):
        if ENABLE_DB_EVENT_SUPPORT:
            # Sometime after FB 2.0b1, FPTR_EVENT_CALLBACK was renamed to
            # ISC_EVENT_CALLBACK.  This code allows kinterbasdb to compile
            # properly either way.
            if not self.try_compile(
                body='/* THIS IS PROBE CODE; THE ERRORS ARE NOT A PROBLEM! */\n'
                     'void dummy_callback(void *x, ISC_USHORT y, const ISC_UCHAR *z) {\n'
                     '}\n'
                     'int main() {\n'
                     '  ISC_EVENT_CALLBACK x = dummy_callback;\n'
                     '  return 0;\n'
                     '}\n'
                     '/* THIS IS PROBE CODE; THE ERRORS ARE NOT A PROBLEM! */\n',
                headers=['ibase.h'],
                include_dirs=allIncludeDirs
              ):
                defineConfigItem('ISC_EVENT_CALLBACK', 'FPTR_EVENT_CALLBACK')

        # This HAVE__? silliness is necessary because ibase.h is increasingly
        # not using the preprocessor for constant definitions, so setup.py has
        # to test for the presence of the constants, then use the preprocessor
        # to indicate the result.
        def probeIntConst(name):
            if self.try_compile(
                body='/* THIS IS PROBE CODE; THE ERRORS ARE NOT A PROBLEM! */\n'
                     'int main(void) {\n'
                     '  /* The cast is present because we are testing for the'
                     '   * presence of the constant; its type and value do not'
                     '   * matter. */'
                     '  const int x = (int) %s;\n'
                     '  return 0;\n'
                     '}\n'
                     '/* THIS IS PROBE CODE; THE ERRORS ARE NOT A PROBLEM! */\n'
                     % name,
                headers=['ibase.h'],
                include_dirs=allIncludeDirs
              ):
                defineConfigItem('HAVE__%s' % name)

        for intConstName in '''
            isc_tpb_lock_timeout

            isc_info_active_tran_count
            isc_info_creation_date

            isc_info_tra_oldest_interesting
            isc_info_tra_oldest_snapshot
            isc_info_tra_oldest_active
            isc_info_tra_isolation
            isc_info_tra_access
            isc_info_tra_lock_timeout
            isc_info_tra_consistency
            isc_info_tra_concurrency
            isc_info_tra_read_committed
            isc_info_tra_no_rec_version
            isc_info_tra_rec_version
            isc_info_tra_readonly
            isc_info_tra_readwrite
          '''.split():
            probeIntConst(intConstName)

        def probeCType(cTypeName, includeFiles=()):
            probeCTypeBody = (
                '/* THIS IS PROBE CODE; THE ERRORS ARE NOT A PROBLEM! */\n'
                 '%s\n'
                 'int main(void) {\n'
                 '  %s x;\n'
                 '  return 0;\n'
                 '}\n'
                 '/* THIS IS PROBE CODE; THE ERRORS ARE NOT A PROBLEM! */\n'
                 % ('\n'.join(['#include %s' % f for f in includeFiles]),
                    cTypeName
                   )
              )
            shavedIncludeFiles = [
                f[1:-1] for f in includeFiles
                if f.startswith('<') or f.startswith('"')
              ]
            if self.try_compile(
                body=probeCTypeBody,
                headers=['ibase.h'] + shavedIncludeFiles,
                include_dirs=allIncludeDirs
              ):
                defineConfigItem('HAVE__%s' % cTypeName)

        for cTypeName, includeFiles in (
            # Linux distributions in the Red Hat family define useconds_t in
            # sys/types.h, but some distributions don't:
            ('useconds_t', ['<sys/types.h>']),
          ):
            probeCType(cTypeName, includeFiles=includeFiles)

        preprocConfigFile.close()

        DefaultConfigCommand.run(self)


class BuildExtCommand(DefaultBuildExtCommand):
    def finalize_options(self):
        # Notice that the finalize_options method of the 'build' command is
        # called before the config command is called, so as to ensure that
        # self.compiler will have been computed by the time we need it.
        DefaultBuildExtCommand.finalize_options(self)

        configCommand = self.get_finalized_command('config')
        if not configCommand.compiler:
            configCommand.compiler = self.compiler

        self.run_command('config')


# The MEAT:
distutils.core.setup(
    name=kinterbasdb_name,
    version=kinterbasdb_version,
    author='''Originally by Alexander Kuznetsov ;
                   rewritten and expanded by David S. Rushby
                   with contributions from several others
                   (see docs/license.txt for details).''',
    author_email='woodsplitter@rocketmail.com',
    url='http://kinterbasdb.sourceforge.net',
    description='Python DB API 2.0 extension for Firebird and Interbase',
    long_description=
        'KInterbasDB implements Python Database API 2.0-compliant support\n'
        'for the open source relational database Firebird and some versions\n'
        'of its proprietary cousin Borland Interbase(R).\n\n'
        'In addition to the minimal feature set of the standard Python DB API,\n'
        'KInterbasDB also exposes nearly the entire native client API of the\n'
        'database engine.',
        # 'kinterbasdb allows Python to access the Firebird and Interbase\n'
        # 'relational databases according to the interface defined by the\n'
        # 'Python Database API Specification version 2.0.',
    license='see docs/license.txt',

    packages=['kinterbasdb'],
    package_dir={'kinterbasdb': os.curdir},
    package_data = {'kinterbasdb': ['docs/*.html','docs/_static/*','docs/_sources/*']},

    py_modules=allPythonModules,

    # 2005.12.08:
    cmdclass={'config': ConfigCommand, 'build_ext': BuildExtCommand,},

    ext_modules=extensionModules,
  )


print '\nSucceeded:\n ', sys.executable, ' '.join(sys.argv)