-
Notifications
You must be signed in to change notification settings - Fork 98
/
uri.rb
1379 lines (1268 loc) · 45.9 KB
/
uri.rb
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
# coding: utf-8
require 'cgi'
module RDF
##
# A Uniform Resource Identifier (URI).
# Also compatible with International Resource Identifier (IRI)
#
# @example Creating a URI reference (1)
# uri = RDF::URI.new("https://rubygems.org/gems/rdf")
#
# @example Creating a URI reference (2)
# uri = RDF::URI.new(scheme: 'http', host: 'rubygems.org', path: '/gems/rdf')
# #=> RDF::URI.new("https://rubygems.org/gems/rdf")
#
# @example Creating an interned URI reference
# uri = RDF::URI.intern("https://rubygems.org/gems/rdf")
#
# @example Getting the string representation of a URI
# uri.to_s #=> "https://rubygems.org/gems/rdf"
#
# @see https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier
# @see https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
# @see https://www.ietf.org/rfc/rfc3986.txt
# @see https://www.ietf.org/rfc/rfc3987.txt
# @see https://rubydoc.info/gems/addressable
class URI
include RDF::Resource
# IRI components
UCSCHAR = Regexp.compile(<<-EOS.gsub(/\s+/, ''))
[\\u00A0-\\uD7FF]|[\\uF900-\\uFDCF]|[\\uFDF0-\\uFFEF]|
[\\u{10000}-\\u{1FFFD}]|[\\u{20000}-\\u{2FFFD}]|[\\u{30000}-\\u{3FFFD}]|
[\\u{40000}-\\u{4FFFD}]|[\\u{50000}-\\u{5FFFD}]|[\\u{60000}-\\u{6FFFD}]|
[\\u{70000}-\\u{7FFFD}]|[\\u{80000}-\\u{8FFFD}]|[\\u{90000}-\\u{9FFFD}]|
[\\u{A0000}-\\u{AFFFD}]|[\\u{B0000}-\\u{BFFFD}]|[\\u{C0000}-\\u{CFFFD}]|
[\\u{D0000}-\\u{DFFFD}]|[\\u{E1000}-\\u{EFFFD}]
EOS
IPRIVATE = Regexp.compile("[\\uE000-\\uF8FF]|[\\u{F0000}-\\u{FFFFD}]|[\\u100000-\\u10FFFD]").freeze
SCHEME = Regexp.compile("[A-Za-z](?:[A-Za-z0-9+-\.])*").freeze
PORT = Regexp.compile("[0-9]*").freeze
IP_literal = Regexp.compile("\\[[0-9A-Fa-f:\\.]*\\]").freeze # Simplified, no IPvFuture
PCT_ENCODED = Regexp.compile("%[0-9A-Fa-f][0-9A-Fa-f]").freeze
GEN_DELIMS = Regexp.compile("[:/\\?\\#\\[\\]@]").freeze
SUB_DELIMS = Regexp.compile("[!\\$&'\\(\\)\\*\\+,;=]").freeze
RESERVED = Regexp.compile("(?:#{GEN_DELIMS}|#{SUB_DELIMS})").freeze
UNRESERVED = Regexp.compile("[A-Za-z0-9\._~-]").freeze
IUNRESERVED = Regexp.compile("[A-Za-z0-9\._~-]|#{UCSCHAR}").freeze
IPCHAR = Regexp.compile("(?:#{IUNRESERVED}|#{PCT_ENCODED}|#{SUB_DELIMS}|:|@)").freeze
IQUERY = Regexp.compile("(?:#{IPCHAR}|#{IPRIVATE}|/|\\?)*").freeze
IFRAGMENT = Regexp.compile("(?:#{IPCHAR}|/|\\?)*").freeze
ISEGMENT = Regexp.compile("(?:#{IPCHAR})*").freeze
ISEGMENT_NZ = Regexp.compile("(?:#{IPCHAR})+").freeze
ISEGMENT_NZ_NC = Regexp.compile("(?:(?:#{IUNRESERVED})|(?:#{PCT_ENCODED})|(?:#{SUB_DELIMS})|@)+").freeze
IPATH_ABEMPTY = Regexp.compile("(?:/#{ISEGMENT})*").freeze
IPATH_ABSOLUTE = Regexp.compile("/(?:(?:#{ISEGMENT_NZ})(/#{ISEGMENT})*)?").freeze
IPATH_NOSCHEME = Regexp.compile("(?:#{ISEGMENT_NZ_NC})(?:/#{ISEGMENT})*").freeze
IPATH_ROOTLESS = Regexp.compile("(?:#{ISEGMENT_NZ})(?:/#{ISEGMENT})*").freeze
IPATH_EMPTY = Regexp.compile("").freeze
IREG_NAME = Regexp.compile("(?:(?:#{IUNRESERVED})|(?:#{PCT_ENCODED})|(?:#{SUB_DELIMS}))*").freeze
IHOST = Regexp.compile("(?:#{IP_literal})|(?:#{IREG_NAME})").freeze
IUSERINFO = Regexp.compile("(?:(?:#{IUNRESERVED})|(?:#{PCT_ENCODED})|(?:#{SUB_DELIMS})|:)*").freeze
IAUTHORITY = Regexp.compile("(?:#{IUSERINFO}@)?#{IHOST}(?::#{PORT})?").freeze
IRELATIVE_PART = Regexp.compile("(?:(?://#{IAUTHORITY}(?:#{IPATH_ABEMPTY}))|(?:#{IPATH_ABSOLUTE})|(?:#{IPATH_NOSCHEME})|(?:#{IPATH_EMPTY}))").freeze
IRELATIVE_REF = Regexp.compile("^#{IRELATIVE_PART}(?:\\?#{IQUERY})?(?:\\##{IFRAGMENT})?$").freeze
IHIER_PART = Regexp.compile("(?:(?://#{IAUTHORITY}#{IPATH_ABEMPTY})|(?:#{IPATH_ABSOLUTE})|(?:#{IPATH_ROOTLESS})|(?:#{IPATH_EMPTY}))").freeze
IRI = Regexp.compile("^#{SCHEME}:(?:#{IHIER_PART})(?:\\?#{IQUERY})?(?:\\##{IFRAGMENT})?$").freeze
# Split an IRI into it's component parts
IRI_PARTS = /^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/.freeze
# Remove dot expressions regular expressions
RDS_2A = /^\.?\.\/(.*)$/.freeze
RDS_2B1 = /^\/\.$/.freeze
RDS_2B2 = /^(?:\/\.\/)(.*)$/.freeze
RDS_2C1 = /^\/\.\.$/.freeze
RDS_2C2 = /^(?:\/\.\.\/)(.*)$/.freeze
RDS_2D = /^\.\.?$/.freeze
RDS_2E = /^(\/?[^\/]*)(\/?.*)?$/.freeze
# Remove port, if it is standard for the scheme when normalizing
PORT_MAPPING = {
"http" => 80,
"https" => 443,
"ftp" => 21,
"tftp" => 69,
"sftp" => 22,
"ssh" => 22,
"svn+ssh" => 22,
"telnet" => 23,
"nntp" => 119,
"gopher" => 70,
"wais" => 210,
"ldap" => 389,
"prospero" => 1525
}
# List of schemes known not to be hierarchical
NON_HIER_SCHEMES = %w(
about acct bitcoin callto cid data fax geo gtalk h323 iax icon im jabber
jms magnet mailto maps news pres proxy session sip sips skype sms spotify stun stuns
tag tel turn turns tv urn javascript
).freeze
# Characters in a PName which must be escaped
# Note: not all reserved characters need to be escaped in SPARQL/Turtle, but they must be unescaped when encountered
PN_ESCAPE_CHARS = /[~\.!\$&'\(\)\*\+,;=\/\?\#@%]/.freeze
PN_ESCAPES = /\\#{Regexp.union(PN_ESCAPE_CHARS, /[\-_]/)}/.freeze
##
# Cache size may be set through {RDF.config} using `uri_cache_size`.
#
# @return [RDF::Util::Cache]
# @private
def self.cache
require 'rdf/util/cache' unless defined?(::RDF::Util::Cache)
@cache ||= RDF::Util::Cache.new(RDF.config.uri_cache_size)
end
##
# Returns an interned `RDF::URI` instance based on the given `uri`
# string.
#
# The maximum number of cached interned URI references is given by the
# `CACHE_SIZE` constant. This value is unlimited by default, in which
# case an interned URI object will be purged only when the last strong
# reference to it is garbage collected (i.e., when its finalizer runs).
#
# Excepting special memory-limited circumstances, it should always be
# safe and preferred to construct new URI references using
# `RDF::URI.intern` instead of `RDF::URI.new`, since if an interned
# object can't be returned for some reason, this method will fall back
# to returning a freshly-allocated one.
#
# (see #initialize)
# @return [RDF::URI] an immutable, frozen URI object
def self.intern(str, *args, **options)
(cache[(str = str.to_s).to_sym] ||= self.new(str, *args, **options)).freeze
end
##
# Creates a new `RDF::URI` instance based on the given `uri` string.
#
# This is just an alias for {RDF::URI#initialize} for compatibity
# with `Addressable::URI.parse`. Actual parsing is defered
# until {#object} is accessed.
#
# @param [String, #to_s] str
# @return [RDF::URI]
def self.parse(str)
self.new(str)
end
##
# Resolve paths to their simplest form.
#
# @todo This process is correct, but overly iterative. It could be better done with a single regexp which handled most of the segment collapses all at once. Parent segments would still require iteration.
#
# @param [String] path
# @return [String] normalized path
# @see http://tools.ietf.org/html/rfc3986#section-5.2.4
def self.normalize_path(path)
output, input = "", path.to_s
if input.encoding != Encoding::ASCII_8BIT
input = input.dup.force_encoding(Encoding::ASCII_8BIT)
end
until input.empty?
if input.match(RDS_2A)
# If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise,
input = $1
elsif input.match(RDS_2B1) || input.match(RDS_2B2)
# if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise,
input = "/#{$1}"
elsif input.match(RDS_2C1) || input.match(RDS_2C2)
# if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer
input = "/#{$1}"
# and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise,
output.sub!(/\/?[^\/]*$/, '')
elsif input.match(RDS_2D)
# if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise,
input = ""
elsif input.match(RDS_2E)
# move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer.end
seg, input = $1, $2
output << seg
end
end
output.force_encoding(Encoding::UTF_8)
end
##
# @overload initialize(uri, **options)
# @param [URI, String, #to_s] uri
#
# @overload initialize(**options)
# @param [Hash{Symbol => Object}] options
# @option [String, #to_s] :scheme The scheme component.
# @option [String, #to_s] :user The user component.
# @option [String, #to_s] :password The password component.
# @option [String, #to_s] :userinfo
# The userinfo component. If this is supplied, the user and password
# components must be omitted.
# @option [String, #to_s] :host The host component.
# @option [String, #to_s] :port The port component.
# @option [String, #to_s] :authority
# The authority component. If this is supplied, the user, password,
# userinfo, host, and port components must be omitted.
# @option [String, #to_s] :path The path component.
# @option [String, #to_s] :query The query component.
# @option [String, #to_s] :fragment The fragment component.
#
# @param [Boolean] validate (false)
# @param [Boolean] canonicalize (false)
def initialize(*args, validate: false, canonicalize: false, **options)
@value = @object = @hash = nil
@mutex = Mutex.new
uri = args.first
if uri
@value = uri.to_s.dup
@value.dup.force_encoding(Encoding::UTF_8) if @value.encoding != Encoding::UTF_8
@value.freeze
else
%i(
scheme
user password userinfo
host port authority
path query fragment
).each do |meth|
if options.key?(meth)
self.send("#{meth}=".to_sym, options[meth])
else
self.send(meth)
end
end
end
validate! if validate
canonicalize! if canonicalize
end
##
# Returns `true`.
#
# @return [Boolean] `true` or `false`
# @see http://en.wikipedia.org/wiki/Uniform_Resource_Identifier
def uri?
true
end
##
# Returns `true` if this URI is a URN.
#
# @example
# RDF::URI('http://example.org/').urn? #=> false
#
# @return [Boolean] `true` or `false`
# @see http://en.wikipedia.org/wiki/Uniform_Resource_Name
# @since 0.2.0
def urn?
@object ? @object[:scheme] == 'urn' : start_with?('urn:')
end
##
# Returns `true` if the URI scheme is hierarchical.
#
# @example
# RDF::URI('http://example.org/').hier? #=> true
# RDF::URI('urn:isbn:125235111').hier? #=> false
#
# @return [Boolean] `true` or `false`
# @see http://en.wikipedia.org/wiki/URI_scheme
# @see NON_HIER_SCHEMES
# @since 1.0.10
def hier?
!NON_HIER_SCHEMES.include?(scheme)
end
##
# Returns `true` if this URI is a URL.
#
# @example
# RDF::URI('http://example.org/').url? #=> true
#
# @return [Boolean] `true` or `false`
# @see http://en.wikipedia.org/wiki/Uniform_Resource_Locator
# @since 0.2.0
def url?
!urn?
end
##
# A URI is absolute when it has a scheme
# @return [Boolean] `true` or `false`
def absolute?; !scheme.nil?; end
##
# A URI is relative when it does not have a scheme
# @return [Boolean] `true` or `false`
def relative?; !absolute?; end
# Attempt to make this URI relative to the provided `base_uri`. If successful, returns a relative URI, otherwise the original URI
# @param [#to_s] base_uri
# @return [RDF::URI]
def relativize(base_uri)
if self.to_s.start_with?(base_uri.to_s) && %w(# ?).include?(self.to_s[base_uri.to_s.length, 1]) ||
base_uri.to_s.end_with?("/", "#") &&
self.to_s.start_with?(base_uri.to_s)
return RDF::URI(self.to_s[base_uri.to_s.length..-1])
else
# Create a list of parents, for which this IRI may be relative.
u = RDF::URI(base_uri)
iri_set = u.to_s.end_with?('/') ? [u.to_s] : []
iri_set << u.to_s while (u = u.parent)
iri_set.each_with_index do |bb, index|
next unless self.to_s.start_with?(bb)
rel = "../" * index + self.to_s[bb.length..-1]
return rel.empty? ? "./" : rel
end
end
self
end
##
# Returns the string length of this URI.
#
# @example
# RDF::URI('http://example.org/').length #=> 19
#
# @return [Integer]
# @since 0.3.0
def length
to_s.length
end
alias_method :size, :length
##
# Determine if the URI is a valid according to RFC3987
#
# Note that RDF URIs syntactically can contain Unicode escapes, which are unencoded in the internal representation. To validate, %-encode specifically excluded characters from IRIREF
#
# @return [Boolean] `true` or `false`
# @since 0.3.9
def valid?
RDF::URI::IRI.match(to_s) || false
end
##
# Validates this URI, raising an error if it is invalid.
#
# @return [RDF::URI] `self`
# @raise [ArgumentError] if the URI is invalid
# @since 0.3.0
def validate!
raise ArgumentError, "#{to_base.inspect} is not a valid IRI" if invalid?
self
end
##
# Returns a copy of this URI converted into its canonical lexical
# representation.
#
# @return [RDF::URI]
# @since 0.3.0
def canonicalize
self.dup.canonicalize!
end
alias_method :normalize, :canonicalize
##
# Converts this URI into its canonical lexical representation.
#
# @return [RDF::URI] `self`
# @since 0.3.0
def canonicalize!
@object = {
scheme: normalized_scheme,
authority: normalized_authority,
path: normalized_path.squeeze('/'),
query: normalized_query,
fragment: normalized_fragment
}
@value = nil
@hash = nil
self
end
alias_method :normalize!, :canonicalize!
##
# Joins several URIs together.
#
# This method conforms to join normalization semantics as per RFC3986,
# section 5.2. This method normalizes URIs, removes some duplicate path
# information, such as double slashes, and other behavior specified in the
# RFC.
#
# Other URI building methods are `#/` and `#+`.
#
# For an up-to-date list of edge case behavior, see the shared examples for
# RDF::URI in the rdf-spec project.
#
# @example Joining two URIs
# RDF::URI.new('http://example.org/foo/bar').join('/foo')
# #=> RDF::URI('http://example.org/foo')
# @see <https://github.com/ruby-rdf/rdf-spec/blob/master/lib/rdf/spec/uri.rb>
# @see <http://tools.ietf.org/html/rfc3986#section-5.2>
# @see RDF::URI#/
# @see RDF::URI#+
# @param [Array<String, RDF::URI, #to_s>] uris absolute or relative URIs.
# @return [RDF::URI]
# @see http://tools.ietf.org/html/rfc3986#section-5.2.2
# @see http://tools.ietf.org/html/rfc3986#section-5.2.3
def join(*uris)
joined_parts = object.dup.delete_if {|k, v| %i(user password host port).include?(k)}
uris.each do |uri|
uri = RDF::URI.new(uri) unless uri.is_a?(RDF::URI)
next if uri.to_s.empty? # Don't mess with base URI
case
when uri.scheme
joined_parts = uri.object.merge(path: self.class.normalize_path(uri.path))
when uri.authority
joined_parts[:authority] = uri.authority
joined_parts[:path] = self.class.normalize_path(uri.path)
joined_parts[:query] = uri.query
when uri.path.to_s.empty?
joined_parts[:query] = uri.query if uri.query
when uri.path[0,1] == '/'
joined_parts[:path] = self.class.normalize_path(uri.path)
joined_parts[:query] = uri.query
else
# Merge path segments from section 5.2.3
# Note that if the path includes no segments, the entire path is removed
# > return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
base_path = path.to_s.include?('/') ? path.to_s.sub(/\/[^\/]*$/, '/') : ''
joined_parts[:path] = self.class.normalize_path(base_path + uri.path)
joined_parts[:query] = uri.query
end
joined_parts[:fragment] = uri.fragment
end
# Return joined URI
RDF::URI.new(**joined_parts)
end
##
# 'Smart separator' URI builder
#
# This method attempts to use some understanding of the most common use
# cases for URLs and URNs to create a simple method for building new URIs
# from fragments. This means that it will always insert a separator of
# some sort, will remove duplicate seperators, will always assume that a
# fragment argument represents a relative and not absolute path, and throws
# an exception when an absolute URI is received for a fragment argument.
#
# This is separate from the semantics for `#join`, which are well-defined by
# RFC3986 section 5.2 as part of the merging and normalization process;
# this method does not perform any normalization, removal of spurious
# paths, or removal of parent directory references `(/../)`.
#
# When `fragment` is a path segment containing a colon, best practice is to prepend a `./` and use {#join}, which resolves dot-segments.
#
# See also `#+`, which concatenates the string forms of two URIs without
# any sort of checking or processing.
#
# For an up-to-date list of edge case behavior, see the shared examples for
# RDF::URI in the rdf-spec project.
#
# @param [Any] fragment A URI fragment to be appended to this URI
# @return [RDF::URI]
# @raise [ArgumentError] if the URI is invalid
# @see RDF::URI#+
# @see RDF::URI#join
# @see <http://tools.ietf.org/html/rfc3986#section-5.2>
# @see <https://github.com/ruby-rdf/rdf-spec/blob/master/lib/rdf/spec/uri.rb>
# @example Building a HTTP URL
# RDF::URI.new('http://example.org') / 'jhacker' / 'foaf.ttl'
# #=> RDF::URI('http://example.org/jhacker/foaf.ttl')
# @example Building a HTTP URL (absolute path components)
# RDF::URI.new('http://example.org/') / '/jhacker/' / '/foaf.ttl'
# #=> RDF::URI('http://example.org/jhacker/foaf.ttl')
# @example Using an anchored base URI
# RDF::URI.new('http://example.org/users#') / 'jhacker'
# #=> RDF::URI('http://example.org/users#jhacker')
# @example Building a URN
# RDF::URI.new('urn:isbn') / 125235111
# #=> RDF::URI('urn:isbn:125235111')
def /(fragment)
frag = fragment.respond_to?(:to_uri) ? fragment.to_uri : RDF::URI(fragment.to_s)
raise ArgumentError, "Non-absolute URI or string required, got #{frag}" unless frag.relative?
if urn?
RDF::URI.intern(to_s.sub(/:+$/,'') + ':' + fragment.to_s.sub(/^:+/,''))
else # !urn?
res = self.dup
if res.fragment
case fragment.to_s[0,1]
when '/'
# Base with a fragment, fragment beginning with '/'. The fragment wins, we use '/'.
path, frag = fragment.to_s.split('#', 2)
res.path = "#{res.path}/#{path.sub(/^\/*/,'')}"
res.fragment = frag
else
# Replace fragment
res.fragment = fragment.to_s.sub(/^#+/,'')
end
else
# Not a fragment. includes '/'. Results from bases ending in '/' are the same as if there were no trailing slash.
case fragment.to_s[0,1]
when '#'
# Base ending with '/', fragment beginning with '#'. The fragment wins, we use '#'.
res.path = res.path.to_s.sub(/\/*$/, '')
# Add fragment
res.fragment = fragment.to_s.sub(/^#+/,'')
else
# Add fragment as path component
path, frag = fragment.to_s.split('#', 2)
res.path = res.path.to_s.sub(/\/*$/,'/') + path.sub(/^\/*/,'')
res.fragment = frag
end
end
RDF::URI.intern(res.to_s)
end
end
##
# Simple concatenation operator. Returns a URI formed from concatenating
# the string form of two elements.
#
# For building URIs from fragments, you may want to use the smart
# separator, `#/`. `#join` implements another set of URI building
# semantics.
#
# @example Concatenating a string to a URI
# RDF::URI.new('http://example.org/test') + 'test'
# #=> RDF::URI('http://example.org/testtest')
# @example Concatenating two URIs
# RDF::URI.new('http://example.org/test') + RDF::URI.new('test')
# #=> RDF::URI('http://example.org/testtest')
# @see RDF::URI#/
# @see RDF::URI#join
# @param [Any] other
# @return [RDF::URI]
def +(other)
RDF::URI.intern(self.to_s + other.to_s)
end
##
# Returns `true` if this URI's scheme is not hierarchical,
# or its path component is equal to `/`.
# Protocols not using hierarchical components are always considered
# to be at the root.
#
# @example
# RDF::URI('http://example.org/').root? #=> true
# RDF::URI('http://example.org/path/').root? #=> false
# RDF::URI('urn:isbn').root? #=> true
#
# @return [Boolean] `true` or `false`
def root?
!self.hier? || self.path == '/' || self.path.to_s.empty?
end
##
# Returns a copy of this URI with the path component set to `/`.
#
# @example
# RDF::URI('http://example.org/').root #=> RDF::URI('http://example.org/')
# RDF::URI('http://example.org/path/').root #=> RDF::URI('http://example.org/')
#
# @return [RDF::URI]
def root
if root?
self
else
RDF::URI.new(
**object.merge(path: '/').
keep_if {|k, v| %i(scheme authority path).include?(k)})
end
end
##
# Returns `true` if this URI is hierarchical and it's path component isn't equal to `/`.
#
# @example
# RDF::URI('http://example.org/').parent? #=> false
# RDF::URI('http://example.org/path/').parent? #=> true
#
# @return [Boolean] `true` or `false`
def parent?
!root?
end
alias_method :has_parent?, :parent?
##
# Returns a copy of this URI with the path component ascended to the
# parent directory, if any.
#
# @example
# RDF::URI('http://example.org/').parent #=> nil
# RDF::URI('http://example.org/path/').parent #=> RDF::URI('http://example.org/')
#
# @return [RDF::URI]
def parent
case
when root? then nil
else
require 'pathname' unless defined?(Pathname)
if path = Pathname.new(self.path).parent
uri = self.dup
uri.path = path.to_s
uri.path << '/' unless uri.root?
uri
end
end
end
##
# Returns a qualified name (QName) as a tuple of `[prefix, suffix]` for this URI based on available vocabularies, if possible.
#
# @example
# RDF::URI('http://www.w3.org/2000/01/rdf-schema#').qname #=> [:rdfs, nil]
# RDF::URI('http://www.w3.org/2000/01/rdf-schema#label').qname #=> [:rdfs, :label]
# RDF::RDFS.label.qname #=> [:rdfs, :label]
# RDF::Vocab::DC.title.qname(
# prefixes: {dcterms: 'http://purl.org/dc/terms/'}) #=> [:dcterms, :title]
#
# @note within this software, the term QName is used to describe the tuple of prefix and suffix for a given IRI, where the prefix identifies some defined vocabulary. This somewhat contrasts with the notion of a [Qualified Name](https://www.w3.org/TR/2006/REC-xml-names11-20060816/#ns-qualnames) from XML, which are a subset of Prefixed Names.
#
# @param [Hash{Symbol => String}] prefixes
# Explicit set of prefixes to look for matches, defaults to loaded vocabularies.
# @return [Array(Symbol, Symbol)] or `nil` if no QName found. The suffix component will not have [reserved characters](https://www.w3.org/TR/turtle/#reserved) escaped.
def qname(prefixes: nil)
if prefixes
prefixes.each do |prefix, uri|
return [prefix, self.to_s[uri.length..-1].to_sym] if self.start_with?(uri)
end
elsif self.to_s =~ %r([:/#]([^:/#]*)$)
local_name = $1
vocab_uri = local_name.empty? ? self.to_s : self.to_s[0...-(local_name.length)]
Vocabulary.each do |vocab|
if vocab.to_uri == vocab_uri
prefix = vocab.equal?(RDF) ? :rdf : vocab.__prefix__
return [prefix, local_name.empty? ? nil : local_name.to_sym]
end
end
else
Vocabulary.each do |vocab|
vocab_uri = vocab.to_uri
if self.start_with?(vocab_uri)
prefix = vocab.equal?(RDF) ? :rdf : vocab.__prefix__
local_name = self.to_s[vocab_uri.length..-1]
return [prefix, local_name.empty? ? nil : local_name.to_sym]
end
end
end
return nil # no QName found
end
##
# Returns a Prefixed Name (PName) or the full IRI with any [reserved characters](https://www.w3.org/TR/turtle/#reserved) in the suffix escaped.
#
# @example Using a custom prefix for creating a PNname.
# RDF::URI('http://purl.org/dc/terms/creator').
# pname(prefixes: {dcterms: 'http://purl.org/dc/terms/'})
# #=> "dcterms:creator"
#
# @param [Hash{Symbol => String}] prefixes
# Explicit set of prefixes to look for matches, defaults to loaded vocabularies.
# @return [String] or `nil`
# @see #qname
# @see https://www.w3.org/TR/rdf-sparql-query/#prefNames
def pname(prefixes: nil)
q = self.qname(prefixes: prefixes)
return self.to_s unless q
prefix, suffix = q
suffix = suffix.to_s.gsub(PN_ESCAPE_CHARS) {|c| "\\#{c}"} if
suffix.to_s.match?(PN_ESCAPE_CHARS)
[prefix, suffix].join(":")
end
##
# Returns a duplicate copy of `self`.
#
# @return [RDF::URI]
def dup
self.class.new(@value, **(@object || {}))
end
##
# @private
def freeze
unless frozen?
@mutex.synchronize do
# Create derived components
authority; userinfo; user; password; host; port
@value = value.freeze
@object = object.freeze
@hash = hash.freeze
super
end
end
self
end
##
# Returns `true` if this URI ends with the given `string`.
#
# @example
# RDF::URI('http://example.org/').end_with?('/') #=> true
# RDF::URI('http://example.org/').end_with?('#') #=> false
#
# @param [String, #to_s] string
# @return [Boolean] `true` or `false`
# @see String#end_with?
# @since 0.3.0
def end_with?(string)
to_s.end_with?(string.to_s)
end
alias_method :ends_with?, :end_with?
##
# Checks whether this URI the same term as `other`.
#
# @example
# RDF::URI('http://t.co/').eql?(RDF::URI('http://t.co/')) #=> true
# RDF::URI('http://t.co/').eql?('http://t.co/') #=> false
# RDF::URI('http://www.w3.org/2000/01/rdf-schema#').eql?(RDF::RDFS) #=> false
#
# @param [RDF::URI] other
# @return [Boolean] `true` or `false`
def eql?(other)
other.is_a?(URI) && self.hash == other.hash && self == other
end
##
# Checks whether this URI is equal to `other` (type checking).
#
# Per SPARQL data-r2/expr-equal/eq-2-2, numeric can't be compared with other types
#
# @example
# RDF::URI('http://t.co/') == RDF::URI('http://t.co/') #=> true
# RDF::URI('http://t.co/') == 'http://t.co/' #=> true
# RDF::URI('http://www.w3.org/2000/01/rdf-schema#') == RDF::RDFS #=> true
#
# @param [Object] other
# @return [Boolean] `true` or `false`
# @see http://www.w3.org/TR/rdf-sparql-query/#func-RDFterm-equal
def ==(other)
case other
when Literal
# If other is a Literal, reverse test to consolodate complex type checking logic
other == self
when String then to_s == other
when URI then hash == other.hash && to_s == other.to_s
else other.respond_to?(:to_uri) && to_s == other.to_uri.to_s
end
end
##
# Checks for case equality to the given `other` object.
#
# @example
# RDF::URI('http://example.org/') === /example/ #=> true
# RDF::URI('http://example.org/') === /foobar/ #=> false
# RDF::URI('http://t.co/') === RDF::URI('http://t.co/') #=> true
# RDF::URI('http://t.co/') === 'http://t.co/' #=> true
# RDF::URI('http://www.w3.org/2000/01/rdf-schema#') === RDF::RDFS #=> true
#
# @param [Object] other
# @return [Boolean] `true` or `false`
# @since 0.3.0
def ===(other)
case other
when Regexp then other === to_s
else self == other
end
end
##
# Performs a pattern match using the given regular expression.
#
# @example
# RDF::URI('http://example.org/') =~ /example/ #=> 7
# RDF::URI('http://example.org/') =~ /foobar/ #=> nil
#
# @param [Regexp] pattern
# @return [Integer] the position the match starts
# @see String#=~
# @since 0.3.0
def =~(pattern)
case pattern
when Regexp then to_s =~ pattern
else super # `Object#=~` returns `false`
end
end
##
# Returns `self`.
#
# @return [RDF::URI] `self`
def to_uri
self
end
##
# Returns the string representation of this URI.
#
# @example
# RDF::URI('http://example.org/').to_str #=> 'http://example.org/'
#
# @return [String]
def to_str; value; end
alias_method :to_s, :to_str
##
# Returns a <code>String</code> representation of the URI object's state.
#
# @return [String] The URI object's state, as a <code>String</code>.
def inspect
sprintf("#<%s:%#0x URI:%s>", URI.to_s, self.object_id, self.to_s)
end
##
# lexical representation of URI, either absolute or relative
# @return [String]
def value
return @value if @value
@value = [
("#{scheme}:" if absolute?),
("//#{authority}" if authority),
path,
("?#{query}" if query),
("##{fragment}" if fragment)
].compact.join("").freeze
end
##
# Returns a hash code for this URI.
#
# @return [Integer]
def hash
@hash || @hash = (value.hash * -1)
end
##
# Returns object representation of this URI, broken into components
#
# @return [Hash{Symbol => String}]
def object
@object || @object = parse(@value)
end
alias_method :to_h, :object
##{
# Parse a URI into it's components
#
# @param [String, to_s] value
# @return [Object{Symbol => String}]
def parse(value)
value = value.to_s.dup.force_encoding(Encoding::ASCII_8BIT)
parts = {}
if matchdata = IRI_PARTS.match(value)
scheme, authority, path, query, fragment = matchdata[1..-1]
userinfo, hostport = authority.to_s.split('@', 2)
hostport, userinfo = userinfo, nil unless hostport
user, password = userinfo.to_s.split(':', 2)
host, port = hostport.to_s.split(':', 2)
parts[:scheme] = (scheme.dup.force_encoding(Encoding::UTF_8) if scheme)
parts[:authority] = (authority.dup.force_encoding(Encoding::UTF_8) if authority)
parts[:userinfo] = (userinfo.dup.force_encoding(Encoding::UTF_8) if userinfo)
parts[:user] = (user.dup.force_encoding(Encoding::UTF_8) if user)
parts[:password] = (password.dup.force_encoding(Encoding::UTF_8) if password)
parts[:host] = (host.dup.force_encoding(Encoding::UTF_8) if host)
parts[:port] = (CGI.unescape(port).to_i if port)
parts[:path] = (path.to_s.dup.force_encoding(Encoding::UTF_8) unless path.empty?)
parts[:query] = (query[1..-1].dup.force_encoding(Encoding::UTF_8) if query)
parts[:fragment] = (fragment[1..-1].dup.force_encoding(Encoding::UTF_8) if fragment)
end
parts
end
##
# @return [String]
def scheme
object.fetch(:scheme) do
nil
end
end
##
# @param [String, #to_s] value
# @return [RDF::URI] self
def scheme=(value)
object[:scheme] = (value.to_s.dup.force_encoding(Encoding::UTF_8) if value)
@value = nil
self
end
##
# Return normalized version of scheme, if any
# @return [String]
def normalized_scheme
normalize_segment(scheme.strip, SCHEME, true) if scheme
end
##
# @return [String]
def user
object.fetch(:user) do
@object[:user] = (userinfo.split(':', 2)[0] if userinfo)
end
end
##
# @param [String, #to_s] value
# @return [RDF::URI] self
def user=(value)
object[:user] = (value.to_s.dup.force_encoding(Encoding::UTF_8) if value)
@object[:userinfo] = format_userinfo("")
@object[:authority] = format_authority
@value = nil
self
end
##
# Normalized version of user
# @return [String]
def normalized_user
URI.encode(CGI.unescape(user), /[^#{IUNRESERVED}|#{SUB_DELIMS}]/).force_encoding(Encoding::UTF_8) if user
end
##
# @return [String]
def password
object.fetch(:password) do
@object[:password] = (userinfo.split(':', 2)[1] if userinfo)
end
end
##
# @param [String, #to_s] value
# @return [RDF::URI] self
def password=(value)
object[:password] = (value.to_s.dup.force_encoding(Encoding::UTF_8) if value)
@object[:userinfo] = format_userinfo("")
@object[:authority] = format_authority
@value = nil
self
end
##
# Normalized version of password
# @return [String]
def normalized_password
URI.encode(CGI.unescape(password), /[^#{IUNRESERVED}|#{SUB_DELIMS}]/).force_encoding(Encoding::UTF_8) if password
end
HOST_FROM_AUTHORITY_RE = /(?:[^@]+@)?([^:]+)(?::.*)?$/.freeze
##
# @return [String]
def host
object.fetch(:host) do
@object[:host] = ($1 if @object[:authority] && HOST_FROM_AUTHORITY_RE.match(@object[:authority]))
end
end
##
# @param [String, #to_s] value
# @return [RDF::URI] self
def host=(value)
object[:host] = (value.to_s.dup.force_encoding(Encoding::UTF_8) if value)
@object[:authority] = format_authority
@value = nil
self
end
##
# Normalized version of host
# @return [String]
def normalized_host
# Remove trailing '.' characters
normalize_segment(host, IHOST, true).chomp('.') if host
end
PORT_FROM_AUTHORITY_RE = /:(\d+)$/.freeze