summaryrefslogtreecommitdiff
path: root/swift/Rakefile
blob: a29cffca0cf36ad8271117353ff6febab5108cc6 (plain)
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
#!/usr/bin/env ruby

require 'xcodeproj'

$tests = [
    "Ice/acm",
    "Ice/adapterDeactivation",
    "Ice/admin",
    "Ice/ami",
    "Ice/binding",
    "Ice/defaultServant",
    "Ice/defaultValue",
    "Ice/enums",
    "Ice/exceptions",
    "Ice/facets",
    "Ice/hold",
    "Ice/info",
    "Ice/inheritance",
    "Ice/interceptor",
    "Ice/invoke",
    "Ice/location",
    "Ice/objects",
    "Ice/operations",
    "Ice/optional",
    "Ice/properties",
    "Ice/proxy",
    "Ice/retry",
    "Ice/scope",
    "Ice/servantLocator",
    "Ice/slicing/exceptions",
    "Ice/slicing/objects",
    "Ice/stream",
    "Ice/timeout",
    "Ice/udp",
    "IceSSL/configuration",
    "Slice/escape"
]

$test_variants = ["Client", "Server", "ServerAMD", "Collocated"]

#
# Default sources for each test variant
#
$test_default_sources = {
    "Client" => ["Client.swift", "AllTests.swift", "*Test.ice", "Client.ice"],
    "Server" => ["Server.swift", "TestI.swift", "*Test.ice", "Server.ice"],
    "ServerAMD" => ["ServerAMD.swift", "TestAMDI.swift", "*TestAMD.ice"],
    "Collocated" => ["Collocated.swift"]
}

#
# Extra test sources if any
#
$test_extra_sources = {
    "Ice/objects" => ["Forward.ice"],
    "Ice/operations/Client" => ["BatchOneways.swift",
                                "BatchOnewaysAMI.swift",
                                "Oneways.swift",
                                "OnewaysAMI.swift",
                                "Twoways.swift",
                                "TwowaysAMI.swift"],

    "Ice/servantLocator" => ["ServantLocatorI.swift"],
    "Ice/slicing/exceptions/Client" => ["ClientPrivate.ice"],
    "Ice/slicing/exceptions/Server" => ["ServerPrivate.ice"],
    "Ice/slicing/exceptions/ServerAMD" => ["ServerPrivateAMD.ice"],

    "Ice/slicing/objects/Client" => ["ClientPrivate.ice"],
    "Ice/slicing/objects/Server" => ["ServerPrivate.ice"],
    "Ice/slicing/objects/ServerAMD" => ["ServerPrivateAMD.ice"],
    "Slice/escape" => ["Clash.ice", "Key.ice"]
}

$test_resources = {
    "IceSSL/configuration" => ["../../../../cpp/test/IceSSL/certs"]
}

desc "Generate Xcode projects required to build Ice for Swift"
task :iceproj do
    project = Xcodeproj::Project.new("ice.xcodeproj")

    [:osx, :ios].each do |platform|
        create_platform_targets(project, platform)
    end

    attributes = project.root_object.attributes
    attributes["TargetAttributes"] ||= {}
    project.targets.each do |target|
        attributes["TargetAttributes"][target.uuid] ||= {}
        attributes["TargetAttributes"][target.uuid]["ProvisioningStyle"] = "Automatic"
    end
    project.root_object.development_region = "en"
    project.root_object.known_regions = ["Base", "en"]

    #
    # Sort the project and save it
    #
    project.sort({:groups_position => :above})
    project.save()
end

task :default => [:iceproj]

def create_platform_targets(project, platform)

    platform_name = platform == :osx ? "macOS" : "iOS"

    #
    # Ice for C++11 static libraries
    #
    cpp_components = ["Ice", "IceSSL", "IceDiscovery", "IceLocatorDiscovery"]
    cpp_source_dirs = { "Ice" => ["IceUtil", "Ice"] }
    if platform == :ios then
        cpp_components << "IceIAP"
        cpp_source_dirs["Ice"] << "Ice/ios"
    end

    excludes = {
        "Ice" => ["Application.cpp",
                  "AsyncResult.cpp",
                  "AsyncResult.cpp",
                  "ConvertUTF.cpp",
                  "DLLMain.cpp",
                  "GCObject.cpp",
                  "ResponseHandler.cpp",
                  "SystemdJournal.cpp",
                  "Unicode.cpp"],
        "IceSSL" => ["OpenSSL*", "SChannel*", "UWP*"]
    }

    cpp_targets = []
    ice_cpp_target = nil

    cpp_components.each do | component |
        target = project.new_target(:static_library, "#{component} C++11 #{platform_name}", platform)
        cpp_targets << target

        group = project_group(project, "slice/#{component}")
        target_add_files(target, group, "../slice/#{component}", ["*.ice"])
        target_add_slice2cpp_build_rule(project, target, component)

        target.build_configurations.each { |config|
            config.build_settings["HEADER_SEARCH_PATHS"] = [
                "$(SRCROOT)/../cpp/include/",
                "$(SYMROOT)/$(PLATFORM_NAME)/include/",
                "$(SRCROOT)/../cpp/src/"
            ]
            config.build_settings["GCC_PREPROCESSOR_DEFINITIONS"] = [
                "ICE_CPP11_MAPPING",
                "ICE_BUILDING_SRC",
                "ICE_STATIC_LIBS",
                "ICE_SWIFT"
            ]
            if config.name == "Release" then
                config.build_settings["GCC_PREPROCESSOR_DEFINITIONS"] << "NDEBUG"
            end
            config.build_settings["CLANG_ENABLE_OBJC_ARC"] = "NO"

            if component == "Ice" then
                ice_cpp_target = target
            else
                target.add_dependency(ice_cpp_target)
            end
        }
        target_set_common_build_settings(target, "#{component}++11#{platform_name}")

        source_dirs = cpp_source_dirs[component] || [component]
        source_dirs.each do |d|
            group = project_group(project, "cpp/src/#{d}")
            target_add_files(target, group, "../cpp/src/#{d}", ["*.cpp", "*.mm"], excludes[component] || [])
        end
    end

    #
    # IceImpl framework
    #
    iceimpl_target = project.new_target(:framework, "IceImpl", platform)
    iceimpl_target.name = "IceImpl #{platform_name}"

    target = iceimpl_target
    target.frameworks_build_phases.clear()

    group = project_group(project, "src/IceImpl")
    target_add_files(target, group, "src/IceImpl", ["*.mm"])
    target_add_headers(target, group, "src/IceImpl", ["*.h"],
                       excludes: ["Convert.h", "LoggerWrapperI.h"],
                       attributes: ["Public"])

    target_set_common_build_settings(target, "IceImpl", plist: "src/IceImpl/Info.plist")

    #
    # IceImpl depends on Ice for C++ frameworks
    #
    target.frameworks_build_phases.clear()
    cpp_targets.each do |t|
        target.frameworks_build_phases.add_file_reference(t.product_reference, true)
    end
    target.build_configurations.each { |config|
        config.build_settings["HEADER_SEARCH_PATHS"] = [
            "$(SRCROOT)/../cpp/include/",
            "$(SYMROOT)/$(PLATFORM_NAME)/include/",
            "$(SRCROOT)/../cpp/src/"
        ]
        config.build_settings["DEFINES_MODULE"] = "YES"
        config.build_settings["OTHER_LDFLAGS"] = [
            "-lbz2",
            "-liconv"
        ]
        config.build_settings["GCC_PREPROCESSOR_DEFINITIONS"] = [
            "ICE_CPP11_MAPPING",
            "ICE_STATIC_LIBS",
            "ICE_SWIFT"
        ]

        if config.name == "Release" then
            config.build_settings["GCC_PREPROCESSOR_DEFINITIONS"] << "NDEBUG"
        end
    }
    target_set_framework_build_settings(target)
    target.add_system_framework("Security")
    if platform == :ios then
        target.add_system_framework("ExternalAccessory")
        target.add_system_framework("CFNetwork")
        target.add_system_framework("Foundation")
        target.add_system_framework("UIKit")
    end

    #
    # Ice for Swift framework
    #
    ice_target = project.new_target(:framework, "Ice", platform)
    ice_target.name = "Ice #{platform_name}"

    target = ice_target
    target.frameworks_build_phases.clear()
    target.frameworks_build_phases.add_file_reference(iceimpl_target.product_reference, true)

    target_set_common_build_settings(target, "Ice", plist: "src/Ice/Info.plist", swift: true)

    target.build_configurations.each { |config|
        config.build_settings["DEFINES_MODULE"] = "YES"
    }
    target_set_framework_build_settings(target)
    target_add_carthage_framework(target, platform, "PromiseKit.framework")

    group = project_group(project, "src/Ice")
    group_add_files(group, "src/Ice", ["*.plist"])
    target_add_headers(target, group, "src/Ice", ["*.h"])
    target_add_files(target, group, "src/Ice", ["*.swift"])

    slices = ["Ice", "IceSSL"]
    if platform == :ios then
        slices << "IceIAP"
    end

    slices.each do |item|
        group = project_group(project, "slice/#{item}")
        target_add_files(target, group, "../slice/#{item}", ["*.ice"], excludes[item] || [])
        target_add_slice2swift_build_rule(project, target, item)
    end

    target_add_swiftlint_build_phase(target, "src/Ice")

    #
    # Glacier2, IceStorm and IceGrid Frameworks
    #
    glacier2_target = project.new_target(:framework, "Glacier2", platform)
    icestorm_target = project.new_target(:framework, "IceStorm", platform)
    icegrid_target = project.new_target(:framework, "IceGrid", platform)

    [glacier2_target, icestorm_target, icegrid_target].each do | t |
        target = t
        framework = target.name
        target.name = "#{target.name} #{platform_name}"

        target.frameworks_build_phases.clear()

        target_set_common_build_settings(target, framework, plist: "src/#{framework}/Info.plist", swift: true)

        target.build_configurations.each { |config|
            config.build_settings["DEFINES_MODULE"] = "YES"
        }
        target_set_framework_build_settings(target)
        target_add_carthage_framework(target, platform, "PromiseKit.framework")

        group = project_group(project, "src/#{framework}")
        group_add_files(group, "src/#{framework}", ["*.plist"])
        target_add_headers(target, group, "src/#{framework}", ["*.h"])
        target_add_files(target, group, "src/#{framework}", ["*.swift"])

        group = project_group(project, "slice/#{framework}")
        target_add_files(target, group, "../slice/#{framework}", ["*.ice"])
        target_add_slice2swift_build_rule(project, target, framework)
        target.frameworks_build_phases.add_file_reference(ice_target.product_reference)
        target.add_dependency(ice_target)
    end

    #
    # IceGrid requires Glacier2
    #
    icegrid_target.frameworks_build_phases.add_file_reference(glacier2_target.product_reference)
    icegrid_target.add_dependency(glacier2_target)

    #
    # TestCommon framework
    #
    target = project.new_target(:framework, "TestCommon", platform)
    target.name = "#{target.name} #{platform_name}"
    target.frameworks_build_phases.add_file_reference(ice_target.product_reference, true)
    target_set_framework_build_settings(target)
    target_add_carthage_framework(target, platform, "PromiseKit.framework")
    target_add_slice2swift_build_rule(project, target)
    target_add_swiftlint_build_phase(target, "test/TestCommon")
    test_common_target = target

    #
    # Add .ice and .swift files to the target
    #
    group = project_group(project, "test/TestCommon")
    group_add_files(group, "test/TestCommon", ["*.plist"])
    target_add_files(target, group, "test/TestCommon", ["*.ice", "*.swift"])
    target_set_common_build_settings(target, "TestCommon",
                                     plist: "test/TestCommon/Info.plist",
                                     swift: true)

    target = project.new_target(:application, "TestDriver", platform)
    target.name = "#{target.name} #{platform_name}"
    target_set_common_build_settings(target, "TestDriver",
                                     plist: "test/TestDriver/#{platform_name}/Info.plist",
                                     swift: true)
    target_add_slice2swift_build_rule(project, target)
    target_add_swiftlint_build_phase(target, "test/TestDriver")

    group = project_group(project, "test/TestDriver")
    target_add_files(target, group, "test/TestDriver", ["*.ice", "*.swift"])

    group = project_group(project, "test/TestDriver/#{platform_name}")
    target_add_files(target, group, "test/TestDriver/#{platform_name}", ["*.ice", "*.swift"])
    if platform == :ios then
        target_add_files(target, group, "../scripts", ["*.ice"])
        target_add_files(target, group, "test/TestDriver/#{platform_name}", ["*.xcassets"])
        target_add_files(target, group, "test/TestDriver/#{platform_name}/Base.lproj", ["*.storyboard"])
        target.add_resources(group_add_files(group, "..", ["certs"]))
    end

    #
    # Copy IceImpl, Ice and TestCommon frameworks to the test driver
    #
    copy_phase = target.new_copy_files_build_phase("Copy Frameworks")
    copy_phase.dst_subfolder_spec = Xcodeproj::Constants::COPY_FILES_BUILD_PHASE_DESTINATIONS[:frameworks]

    [iceimpl_target, ice_target, test_common_target].each do |t|
        file = copy_phase.add_file_reference(t.product_reference)
        file.settings = { 'ATTRIBUTES' => ['CodeSignOnCopy'] }
        target.frameworks_build_phases.add_file_reference(t.product_reference)
    end

    target_set_framework_build_settings(target)
    target_add_carthage_framework(target, platform, "PromiseKit.framework", true)

    target.build_configurations.each { |config|
        config.build_settings["CODE_SIGN_IDENTITY"] = "-"
    }
    test_driver_target = target

    #
    # For each test create a bundle target
    #
    $tests.each do |test|
        target = project.new_target(:bundle, target_name("#{test}"), platform)
        target.name = "#{target.name} #{platform_name}"

        [test_common_target, ice_target].each do |t|
            target.frameworks_build_phases.add_file_reference(t.product_reference, true)
        end

        target_set_framework_build_settings(target)
        target.build_configurations.each { |config|
            config.build_settings["ENABLE_BITCODE"] = "NO"
        }

        target_add_carthage_framework(target, platform, "PromiseKit.framework")
        target_add_slice2swift_build_rule(project, target)
        target_add_swiftlint_build_phase(target, "test/#{test}")

        #
        # Add .ice and .swift files to the target
        #
        group = project_group(project, "test/#{test}")
        group_add_files(group, "test/#{test}", ["*.plist"])

        $test_variants.reject{ |item| item == "ServerAMD" }.each do |variant|
            unless test_has_variant(test, variant)
                next
            end
            target_add_files(target, group, "test/#{test}", test_variant_sources(test, variant))
        end

        if $test_resources.include? test then
            target.add_resources(group_add_files(group, "test/#{test}", $test_resources[test]))
        end

        target_set_common_build_settings(target, target_name("#{test}"), swift: true)
        test_driver_target.add_dependency(target)

        #
        # Add the bundle to test driver copy phase
        #
        file = copy_phase.add_file_reference(target.product_reference)
        file.settings = { 'ATTRIBUTES' => ['CodeSignOnCopy'] }
    end

    #
    # Create a separate bundle for AMD test if there is an AMD test variant
    #
    $tests.each do |test|
        if test_has_variant(test, "ServerAMD")
            target = project.new_target(:bundle, target_name("#{test}AMD"), platform)
            target.name = "#{target.name} #{platform_name}"

            [test_common_target, ice_target].each do |t|
                target.frameworks_build_phases.add_file_reference(t.product_reference, true)
            end

            target_set_framework_build_settings(target)
            target.build_configurations.each { |config|
                config.build_settings["ENABLE_BITCODE"] = "NO"
            }

            target_add_carthage_framework(target, platform, "PromiseKit.framework")
            target_add_slice2swift_build_rule(project, target)
            target_add_swiftlint_build_phase(target, "test/#{test}")

            #
            # Add .ice and .swift files to the target
            #
            group = project_group(project, "test/#{test}")
            group_add_files(group, "test/#{test}", ["*.plist"])

            target_add_files(target, group, "test/#{test}", test_variant_sources(test, "ServerAMD"),
                             ["Test.ice", "Client*.ice"])
            target_set_common_build_settings(target, target_name("#{test}AMD"), swift: true)
            test_driver_target.add_dependency(target)

            #
            # Add the bundle to test driver copy phase
            #
            file = copy_phase.add_file_reference(target.product_reference)
            file.settings = { 'ATTRIBUTES' => ['CodeSignOnCopy'] }
        end
    end

    #
    # Ensure there is a shared scheme to build the frameworks distributed with Carthage builds
    #
    scheme = Xcodeproj::XCScheme.new
    scheme.add_build_target(iceimpl_target)
    scheme.add_build_target(ice_target)
    scheme.add_build_target(glacier2_target)
    scheme.add_build_target(icestorm_target)
    scheme.add_build_target(icegrid_target)
    scheme.save_as("ice.xcodeproj", "Ice #{platform_name}", true)
end

def project_group(project, name)
    group = project.main_group
    name.split("/").each { |item|
        new_group = group[item]
        unless new_group
            new_group = group.new_group(item)
        end
        group = new_group
    }
    group
end

def target_name(basename, suffix = nil)
    name = basename.split("/").map{ |item| item[0].upcase + item[1..-1]}.join()
    suffix ? "#{name} #{suffix}" : name
end

def target_add_slice2swift_build_rule(project, target, prefix = nil)
    #
    # Add Slice Compiler build rule to the target
    #
    rule = project.new(Xcodeproj::Project::PBXBuildRule)
    rule.compiler_spec = "com.apple.compilers.proxy.script"
    rule.file_type = "pattern.proxy"

    slic2swift = <<~EOF
        if [ -f "$ICE_HOME/cpp/bin/slice2swift" ]; then
            SLICE2SWIFT="$ICE_HOME/cpp/bin/slice2swift"
        elif [ -f "$SRCROOT/../cpp/bin/slice2swift" ]; then
            SLICE2SWIFT="$SRCROOT/../cpp/bin/slice2swift"
        elif [ -f /usr/local/bin/slice2swift ]; then
            SLICE2SWIFT=/usr/local/bin/slice2swift
        else
            echo "Failed to locate slice2swift compiler"
            exit 1
        fi
    EOF

    if prefix then
        rule.name = "Slice Compiler for #{prefix}/*.ice"
        rule.file_patterns = "*/#{prefix}/*.ice"
        rule.script = <<~EOF
            #{slic2swift}
            BASENAME=$(basename -- "$INPUT_FILE_PATH")
            BASENAME="${BASENAME%.*}"
            mkdir -p "$DERIVED_FILE_DIR/#{prefix}"
            "$SLICE2SWIFT" -I"$SRCROOT/../slice" -I"$INPUT_FILE_DIR" --output-dir "$DERIVED_FILE_DIR/#{prefix}" "$INPUT_FILE_PATH"
            mv "$DERIVED_FILE_DIR/#{prefix}/$BASENAME.swift" "$DERIVED_FILE_DIR/#{prefix}_$BASENAME.swift"
        EOF
        rule.output_files = ["$(DERIVED_FILE_DIR)/#{prefix}_$(INPUT_FILE_BASE).swift"]
    else
        rule.name = "Slice Compiler"
        rule.file_patterns = "*.ice"
        rule.script = <<~EOF
            #{slic2swift}
            "$SLICE2SWIFT" -I"$SRCROOT/../slice" -I"$INPUT_FILE_DIR" --output-dir "$DERIVED_FILE_DIR" "$INPUT_FILE_PATH"
        EOF
        rule.output_files = ["$(DERIVED_FILE_DIR)/$(INPUT_FILE_BASE).swift"]
    end
    target.build_rules << rule
end

def target_add_slice2cpp_build_rule(project, target, prefix)
    #
    # Add Slice Compiler build rule to the target
    #
    rule = project.new(Xcodeproj::Project::PBXBuildRule)
    rule.compiler_spec = "com.apple.compilers.proxy.script"
    rule.file_type = "pattern.proxy"
    rule.name = "Slice2Cpp Compiler for #{prefix}/*.ice"
    rule.file_patterns = "*/#{prefix}/*.ice"
    rule.script = <<~EOF
        if [ -f "$ICE_HOME/cpp/bin/slice2cpp" ]; then
            SLICE2CPP="$ICE_HOME/cpp/bin/slice2cpp"
        elif [ -f "$SRCROOT/../cpp/bin/slice2cpp" ]; then
            SLICE2CPP="$SRCROOT/../cpp/bin/slice2cpp"
        elif [ -f /usr/local/opt/slice2swift/libexec/bin/slice2cpp ]; then
            SLICE2CPP=/usr/local/opt/slice2swift/libexec/bin/slice2cpp
        elif [ -f /usr/local/bin/slice2cpp ]; then
            SLICE2CPP=/usr/local/bin/slice2cpp
        else
            echo "Failed to locate slice2cpp compiler"
            exit 1
        fi

        BASENAME=$(basename -- "$INPUT_FILE_PATH")
        BASENAME="${BASENAME%.*}"
        mkdir -p "$DERIVED_FILE_DIR/#{prefix}"
        $SLICE2CPP -I"$SRCROOT/../slice" -D ICE_SWIFT --include-dir #{prefix} --output-dir "$DERIVED_FILE_DIR/#{prefix}" "$INPUT_FILE_PATH"
        mkdir -p "$SYMROOT/$PLATFORM_NAME/include/#{prefix}"
        mv "$DERIVED_FILE_DIR/#{prefix}/$BASENAME.h" "$SYMROOT/$PLATFORM_NAME/include/#{prefix}/$BASENAME.h"
    EOF
    rule.output_files = ["$(DERIVED_FILE_DIR)/#{prefix}/$(INPUT_FILE_BASE).cpp",
                         "$(SYMROOT)/$(PLATFORM_NAME)/include/#{prefix}/$(INPUT_FILE_BASE).h"]
    target.build_rules << rule
end

def target_add_swiftlint_build_phase(target, basedir)
    phase = target.new_shell_script_build_phase("Swiftformat & Swiftlint")
    phase.shell_script = <<~EOF
        if which swiftlint >/dev/null; then
            swiftlint --path "$SRCROOT/#{basedir}" --config "$SRCROOT/.swiftlint.yml"
        else
            echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
        fi
    EOF
end

def group_add_files(group, basedir, patterns, exclude = [])
    files = []
    Dir.chdir(basedir) do
        patterns.each do |p|
            Dir.glob(p) do |file|
                files << file
            end
        end
    end
    files = files.reject { |item| exclude.any? { |pattern| item.match(pattern) } }
    files = files.uniq
    files.map { |file|  group.find_subpath(File.basename(file)) ||  group.new_file("#{basedir}/#{file}") }
end

def target_add_files(target, group, basedir, patterns, excludes = [])
    target.add_file_references(group_add_files(group, basedir, patterns, excludes))
end

def target_add_headers(target, group, basedir, patterns, excludes: [], attributes: ["Public"])
    files = group_add_files(group, basedir, patterns, excludes)
    if attributes.include? "Public" then
        files.each do |file|
            header = target.headers_build_phase.add_file_reference(file)
            header.settings = { "ATTRIBUTES" => attributes }
        end
    end
end

def target_set_common_build_settings(target, product, plist: nil, swift: false)
    target.build_configurations.each { |config|
        config.build_settings["GCC_SYMBOLS_PRIVATE_EXTERN"] = "YES"
        config.build_settings["ENABLE_TESTABILITY"] = "NO"
        config.build_settings["CODE_SIGN_STYLE"] = "Automatic"
        config.build_settings["CURRENT_PROJECT_VERSION"] = "3.7.62"
        config.build_settings["DYLIB_CURRENT_VERSION"] = "3.7.62"
        config.build_settings["DYLIB_COMPATIBILITY_VERSION"] = "0"

        if plist then
            config.build_settings["INFOPLIST_FILE"] = plist
        end
        config.build_settings["PRODUCT_NAME"] = product
        config.build_settings["PRODUCT_BUNDLE_IDENTIFIER"] = "com.zeroc.#{product}"

        if swift then
            config.build_settings["SWIFT_VERSION"] = "5.0"
        end

        config.build_settings["SUPPORTED_PLATFORMS"] =
            (target.name.include? "macOS") ? "macosx" : "iphoneos iphonesimulator"

        config.build_settings["AVAILABLE_PLATFORMS"] =
            (target.name.include? "macOS") ? "macosx" : "iphoneos iphonesimulator"
    }
end

def target_set_framework_build_settings(target)
    carthage_prefix = (target.name.include? "macOS") ? "Mac" : "iOS"
    target.build_configurations.each { |config|
        config.build_settings["FRAMEWORK_SEARCH_PATHS"] = "$(SRCROOT)/../Carthage/Build/#{carthage_prefix}"
    }
end

def target_add_carthage_framework(target, platform, framework, copy=false)
    group = target.project.frameworks_group[(platform == :osx ? "OS X" : "iOS")]
    carthage_prefix = (platform == :osx) ? "Mac" : "iOS"
    group_add_files(group, "../Carthage/Build/#{carthage_prefix}", [framework]).each do |ref|
        target.frameworks_build_phases.add_file_reference(ref, true)
        if copy then
            file = target.copy_files_build_phases[0].add_file_reference(ref)
            file.settings = { 'ATTRIBUTES' => ['CodeSignOnCopy'] }
        end
    end
end

#
# Check if the test include the given variant
#
def test_has_variant(test, variant)
    return File.file?("test/#{test}/#{variant}.swift")
end

def test_variant_sources(test, variant)
    sources = $test_default_sources[variant]

    if variant == "Collocated"
        sources += $test_default_sources["Server"].reject { |s| s == "Server.swift" }
        sources += $test_default_sources["Client"].reject { |s| s == "Client.swift" }

        sources += $test_extra_sources["#{test}/Server"] || []
        sources += $test_extra_sources["#{test}/Client"] || []
    end

    sources += $test_extra_sources[test] || []
    sources += $test_extra_sources["#{test}/#{variant}"] || []

    return sources
end