-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcfg-cruby
executable file
·626 lines (501 loc) · 15 KB
/
cfg-cruby
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
#! /usr/bin/env perl
use warnings;
use strict;
use constant VERSION => "2.1.0";
# cfg-cruby
#
# CRuby configuration script.
# Distributed under the MIT license.
#
# script to generate following files:
#
# Package.swift
# include, or don't include, some pkgconfig reference
#
# Sources/CRuby/module.modulemap
# include workaround headers on Linux
# include ruby_headers.h
# use the actual library soname
#
# Sources/CRuby/ruby_headers.h
# include all Ruby headers
# special paths syntax for Xcode mode to work with framework
#
# CRuby.pc
# compile + link flags/dirs to resolve ruby_headers.h + soname
#
# CRuby.xcconfig
# compile + link flags and paths to resolve ruby_headers.h + soname
# Problems
# --------
# Paths with spaces will almost certainly break at some point on some paths.
=head1 NAME
cfg-cruby - Configure the CRuby libruby wrapper for SwiftPM
=head1 SYNOPSIS
cfg-cruby --mode <mode> [options]
Options:
--name <name> The name of a managed version of Ruby to use
--path <path> The full path to the install dir of the custom Ruby
Modes:
xcode Use the macOS system Ruby with Xcode dev parts.
pkgconfig Use a Ruby known to pkg-config(1).
Requires --name, the package to use, eg. 'ruby-2.5'.
rbenv Use a Ruby known to rbenv.
Requires --name, the Ruby version to use, eg. '2.2.2'.
rvm Use a Ruby known to rvm.
Requires --name, the Ruby to use, eg. 'ruby-2.4.1'.
custom Use an arbitrary Ruby installation.
Requires --path.
Output files are produced in the same directory as the cfg-cruby script.
=cut
use Getopt::Long;
use Pod::Usage;
use Cwd qw(abs_path);
use File::Basename;
use POSIX qw(uname);
#
# OS utils, setup
#
my (undef, $script_dir, undef) = fileparse(__FILE__);
my $output_dir = abs_path($script_dir);
my ($system_arch, undef) = uname();
sub is_macos {
return $system_arch eq "Darwin";
}
sub is_linux {
return $system_arch eq "Linux";
}
sub stop_usage {
my $msg = shift;
pod2usage(-message => $msg, -exitval => 2);
}
sub stop {
my $msg = shift;
print("$msg\n");
exit(3);
}
# Return command results, intercept fail status
sub run_and_check {
my $command = shift;
my $result = `$command`;
unless (defined $result) {
print("Can't run '$command'.\n");
} elsif ($? != 0) {
print("Running '$command' failed: " . ($?>>8) . "\n");
return undef;
}
chomp $result;
return $result;
}
# Same but handling multi-line output
sub run_and_check_list {
my $lines = run_and_check(@_) or return 0;
my @result;
foreach my $line (split /^/, $lines) {
chomp($line);
push @result, $line;
}
return @result;
}
#
# CLI validation + main
#
my $mode;
my $ruby_name;
my $ruby_path;
sub confirm_noflags {
stop_usage("--name and --path do not apply to $mode mode.")
if $ruby_name or $ruby_path;
}
sub confirm_name {
stop_usage("Only --name must be set for $mode mode.")
if !$ruby_name or $ruby_path;
}
sub confirm_path {
stop_usage("Only --path must be set for $mode mode.")
if $ruby_name or !$ruby_path;
}
GetOptions('mode=s' => \$mode,
'name=s' => \$ruby_name,
'path=s' => \$ruby_path) or stop_usage();
unless ($mode) {
stop_usage("--mode not set.");
} elsif ($mode eq 'xcode') {
confirm_noflags();
validate_xcode(1) && do_xcode()
or stop("Could not configure for Xcode.");
} elsif ($mode eq 'pkgconfig' || $mode eq 'pkg-config') {
confirm_name();
validate_pkgconfig(1) && validate_pkgconfig_args() && do_pkgconfig()
or stop("Could not configure for pkg-config.");
} elsif ($mode eq 'rbenv') {
confirm_name();
validate_rbenv(1) && validate_rbenv_args() && do_rbenv()
or stop("Could not configure for rbenv.");
} elsif ($mode eq 'rvm') {
confirm_name();
validate_rvm(1) && validate_rvm_args() && do_rvm()
or stop("Could not configure for rvm.");
} elsif ($mode eq 'custom') {
confirm_path();
validate_custom(1) && validate_custom_args() && do_custom()
or stop("Could not configure for custom path.");
} else {
stop_usage("Bad mode.")
}
exit(0);
#
# File writing
#
sub write_file {
my ($filename, $content) = @_;
my $pathname = "$output_dir/$filename";
open FILE, ">$pathname"
or stop("Couldn't open $pathname for writing: $!");
print FILE $content;
print "Wrote $filename\n";
}
sub clear_file {
my $filename = shift;
my $pathname = "$output_dir/$filename";
if (-r $pathname) {
unlink($pathname) or stop("Can't delete $pathname: $!");
print("Deleted $filename\n");
}
}
sub write_target_file {
my ($filename, $content) = @_;
write_file("Sources/CRuby/$filename", $content);
}
sub write_modulemap {
my $libname = shift;
my $extraheaders_line = "";
if (is_linux()) {
$extraheaders_line = "\n header \"linux_headers.h\"";
}
my $content = <<"EOF";
// CRuby module-map generated by cfg-cruby @{[VERSION]}
module CRuby [system] {$extraheaders_line
header "ruby_headers.h"
link \"$libname\"
export *
}
EOF
write_target_file("module.modulemap", $content);
}
sub write_package {
my $pkgconfig = shift;
my $pkgconfig_line = "";
if ($pkgconfig) {
$pkgconfig_line = ", pkgConfig: \"$pkgconfig\"";
}
my $content = <<"EOF";
// swift-tools-version:5.4
// Generated by cfg-cruby @{[VERSION]}
import PackageDescription
let package = Package(
name: "CRuby",
products: [
.library(name: "CRuby", targets: ["CRuby"]),
],
targets: [
.systemLibrary(name: "CRuby"$pkgconfig_line),
]
)
EOF
write_file("Package.swift", $content);
}
sub write_ruby_headers {
my $xcode = shift;
my $prefix = $xcode ? "ruby/" : "";
my $content = <<"EOF";
/* Generated by cfg-cruby @{[VERSION]} */
#include "${prefix}ruby.h"
#include "${prefix}ruby/debug.h"
/* We have to knock these next three out because the Ruby regex implementation
duplicates an identifier (re_pattern_buffer) with /usr/include/regex.h.
And on Linux, the SwiftGlibC module pulls in every header known
to man so the clash is unavoidable. Could make this !__linux__ but
probably better to keep CRuby API the same.
Will try and fix for Ruby 2.6
*/
#if 0
#include "${prefix}ruby/encoding.h"
#include "${prefix}ruby/io.h"
#include "${prefix}ruby/re.h"
#endif
#include "${prefix}ruby/thread.h"
#include "${prefix}ruby/version.h"
#include "${prefix}ruby/vm.h"
EOF
write_target_file("ruby_headers.h", $content);
}
# Shonky arg filterer, duplicating SPM 'whitelist' 'functionality' to
# get an 'acceptable' list of flags.
sub spm_filter_flags {
my @flags = split ' ', shift;
my @filtered = ();
while (my $next = shift @flags) {
if ($next =~ m/^-([IFLl]|framework)/) {
push @filtered, $next;
while ($flags[0] && $flags[0] !~ m/^-/) {
push @filtered, (shift @flags);
}
}
}
return join ' ', @filtered;
}
sub write_pkgconfig {
my ($cflags, $ldflags) = @_;
my $filtered_cflags = spm_filter_flags($cflags);
my $filtered_ldflags = spm_filter_flags($ldflags);
my $content = <<"EOF";
# Generated by cfg-cruby @{[VERSION]}
Cflags: $filtered_cflags
Libs: $filtered_ldflags
EOF
write_file("CRuby.pc", $content);
print(
"SwiftPM must be able to find the directory containing 'CRuby.pc' when
it builds an executable depending on CRuby. For example:
PKG_CONFIG_PATH=\$(pwd)/Packages/CRuby:\$PKG_CONFIG_PATH swift build\n");
}
sub clear_pkgconfig {
clear_file("CRuby.pc");
}
sub write_xcconfig {
my ($hdrdirs, $libdir) = @_;
my $content = <<"EOF";
// Generated by cfg-cruby @{[VERSION]}
HEADER_SEARCH_PATHS = \$(inherited) $hdrdirs
LIBRARY_SEARCH_PATHS = \$(inherited) $libdir
EOF
write_file("CRuby.xcconfig", $content);
}
sub clear_xcconfig {
clear_file("CRuby.xcconfig");
}
# Phases
# Validate - Does it make sense to use the mode.
# Do not check if args are consistent.
# - Used as first step of mode validate
# ValidateArgs - Are entered args consistent with mode.
# - Used as second step of mode validate.
# Do - Create files for mode.
#
# Return 0 on failure, 1 on success.
#
# Xcode
#
my $xcode_dev_dir;
my $xcode_ruby_lib;
sub validate_xcode {
unless (is_macos()) {
print("Not macOS.\n");
return 0;
}
$xcode_dev_dir = run_and_check("xcode-select -p")
or return 0;
my $xcode_ruby_header = $xcode_dev_dir .
"/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/".
"System/Library/Frameworks/Ruby.framework/Headers/ruby.h";
unless (-r $xcode_ruby_header) {
print("Don't understand Xcode SDK layout.\n");
return 0;
}
# Handy symlink vanished around macOS 11
$xcode_ruby_lib =
readlink("/usr/lib/libruby.dylib") ||
readlink("/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/lib/libruby.dylib");
unless ($xcode_ruby_lib) {
print("Don't understand system Ruby setup, $?\n");
return 0;
}
1;
}
sub do_xcode {
print("Configuring for Xcode in $output_dir:\n");
print(" Xcode: $xcode_dev_dir\n");
print(" Ruby: /usr/lib/$xcode_ruby_lib\n");
write_modulemap("ruby");
write_ruby_headers(1); # Xcode
write_package(); # no pkgconfig ref
clear_pkgconfig();
clear_xcconfig();
1;
}
#
# Generic list-of-ruby-options helpers
#
my @ruby_versions;
sub validate_candidate_list {
my $cmd = shift;
if (scalar @ruby_versions == 0) {
print("No Ruby found in '$cmd'.\n");
return 0;
}
1;
}
sub validate_ruby_in_list {
unless (grep( /^$ruby_name$/, @ruby_versions)) {
print("Ruby '$ruby_name' not a candidate, choices:\n");
foreach my $ver (@ruby_versions) {
print(" $ver\n");
}
return 0;
}
1;
}
#
# pkg-config
#
sub validate_pkgconfig {
my $cmd = "pkg-config --list-all";
my @pkg_lines = run_and_check_list($cmd)
or return 0;
@ruby_versions = map { (split ' ')[0] } grep(/^ruby-/, @pkg_lines);
return validate_candidate_list($cmd);
}
sub validate_pkgconfig_args {
validate_ruby_in_list();
}
sub do_pkgconfig {
print("Configuring for pkg-config in $output_dir:\n");
print(" Ruby: $ruby_name\n");
my $ruby_soname =
run_and_check("pkg-config --variable RUBY_SO_NAME $ruby_name", 1);
my $ruby_hdr_dir =
run_and_check("pkg-config --variable rubyhdrdir $ruby_name", 1);
my $ruby_arch_hdr_dir =
run_and_check("pkg-config --variable rubyarchhdrdir $ruby_name", 1);
my $libdir =
run_and_check("pkg-config --variable libdir $ruby_name", 1);
my $cflags =
run_and_check("pkg-config --cflags $ruby_name", 1);
my $ldflags =
run_and_check("pkg-config --libs $ruby_name", 1);
unless ($ruby_soname && $ruby_hdr_dir && $cflags && $ldflags) {
print("Can't understand .pc format.");
return 0;
}
# Good old Homebrew seems to not get this quite right :(
if (is_macos()) {
$ldflags .= " -L$libdir"
}
write_modulemap($ruby_soname);
write_ruby_headers(0); # !Xcode
write_package("CRuby");
write_pkgconfig($cflags, $ldflags);
write_xcconfig("$ruby_arch_hdr_dir $ruby_hdr_dir", $libdir);
1;
}
#
# Rbenv etc.
#
my $rbenv_root;
sub validate_rbenv {
my $cmd = "rbenv versions --bare";
$rbenv_root = run_and_check("rbenv root")
or return 0;
@ruby_versions = run_and_check_list($cmd)
or return 0;
return validate_candidate_list(@ruby_versions);
}
sub validate_rbenv_args { validate_ruby_in_list() }
sub do_rbenv { do_managed("$rbenv_root/versions/$ruby_name", "rbenv"); }
sub do_managed { $ruby_path = shift; do_custom2(shift); }
my $rvm_home;
sub validate_rvm {
my $cmd = "rvm list strings";
my $rvm_info = run_and_check("rvm info | grep ' path'")
or return 0;
$rvm_info =~ m/\"(.*)\"/;
$rvm_home = $1;
@ruby_versions = run_and_check_list($cmd)
or return 0;
return validate_candidate_list(@ruby_versions);
}
sub validate_rvm_args { validate_ruby_in_list() }
sub do_rvm { do_managed("$rvm_home/rubies/$ruby_name", "rvm"); }
#
# Custom
#
sub validate_custom {
1;
}
sub validate_custom_args {
unless (-d $ruby_path) {
print("Custom path is not a directory.\n");
return 0;
}
unless (-d "$ruby_path/lib" && -d "$ruby_path/include") {
print("Custom path does not look like Ruby.\n");
return 0;
}
# just for consistency
$ruby_path =~ s/\/$//;
1;
}
sub do_custom { do_custom2("custom"); }
# Assemble the bits to use an arbitrary Ruby installation.
# Sadly there may be no pkg-config installed on the system.
sub do_custom2 {
my $manager = shift;
print("Configuring for $manager in $output_dir:\n");
print(" Ruby: $ruby_path\n");
# Top include dir - maybe different name (fix ver)
my $ruby_hdr_dir = (glob "$ruby_path/include/ruby*")[0];
# Find the arch dir - experience shows rbenv in particular will
# leave old ones lying around post reinstall, so check the pkgconfig file
# for the correct one.
my $pc = glob "$ruby_path/lib/pkgconfig/ruby*pc";
my $arch = run_and_check("grep ^arch= $pc|sed -e s/^.*=//", 1);
unless ($arch) {
print("Error: Can't find 'arch' in the .pc file.\n");
return 0;
}
# Only cflags are the includes search paths
my $hdrdirs = "$ruby_hdr_dir/$arch $ruby_hdr_dir";
my $cflags = "-I$ruby_hdr_dir/$arch -I$ruby_hdr_dir";
# Find the lib. Older Rubies don't have SOEXT in their .pc.
my $libdir = "$ruby_path/lib";
my @libpaths = glob "$libdir/*";
my $ruby_soname;
my $ldflags = "";
foreach my $path (@libpaths) {
my $file = basename($path);
if ($file =~ m/^lib(ruby.*)\.(so|dylib)$/) {
$ruby_soname = $1;
last;
}
}
# If no shared lib then try for a static one...
unless ($ruby_soname) {
foreach my $path (@libpaths) {
my $file = basename($path);
# (older rbenv use libruby-static with no version part)
if ($file =~ m/^lib(ruby.*static)\.a$/) {
$ruby_soname = $1;
if (is_macos()) {
$ldflags = "-framework CoreFoundation";
}
print("Note: Can't find a shared library. Using static.\n");
print("Note: You may see warnings from 'ld' when linking.\n");
print("Note: If so, do not be alarmed: everything is fine.\n");
last;
}
}
}
# Flags from the pc file
my $pkglibs = run_and_check("grep ^LIBS= $pc|sed -e s/^.*=//", 1);
unless (defined $pkglibs) {
print("Error: Can't find 'LIBS' in the .pc file.\n");
return 0;
}
write_modulemap($ruby_soname);
write_ruby_headers(0); # !Xcode
write_package("CRuby");
write_pkgconfig($cflags, "-L$libdir $pkglibs $ldflags");
write_xcconfig($hdrdirs, $libdir);
1;
}