golden hour
/tmp
⬆️ Go Up
Upload
File/Folder
Size
Actions
.s.PGSQL.5432
-
Del
OK
.wp_cron_private
111 B
Del
OK
error_log.txt
504 B
Del
OK
mysql.sock
-
Del
OK
php01mUcb
40 KB
Del
OK
php01tguP
8.5 KB
Del
OK
php09F8va
0 B
Del
OK
php09vT8o
40 KB
Del
OK
php0AtsaS
27.25 KB
Del
OK
php0CAHMv
40 KB
Del
OK
php0CiQjF
10.93 KB
Del
OK
php0EqtcF
281 B
Del
OK
php0Gj2Al
17.07 KB
Del
OK
php0JoXKr
32.5 KB
Del
OK
php0L6Yjx
1.5 KB
Del
OK
php0Ltb7h
216 KB
Del
OK
php0NMAye
80 KB
Del
OK
php0SZIUv
512 B
Del
OK
php0bx1RN
0 B
Del
OK
php0iUCyv
40 KB
Del
OK
php0k9T19
0 B
Del
OK
php0kdOR6
40 KB
Del
OK
php0l8ZU5
4.56 MB
Del
OK
php0n7cYe
40 KB
Del
OK
php0pN8J9
24.5 KB
Del
OK
php0pnuq5
60.92 KB
Del
OK
php0rVDsi
80 KB
Del
OK
php0yMZ80
937 B
Del
OK
php0yT8gX
8.5 KB
Del
OK
php1EcjtX
33.8 KB
Del
OK
php1EdFo1
10.02 KB
Del
OK
php1GJqBj
40 KB
Del
OK
php1LMnzi
5.5 KB
Del
OK
php1OU7Wa
0 B
Del
OK
php1PTBRu
25.19 KB
Del
OK
php1UKXp7
46.22 KB
Del
OK
php1UOKqT
40 KB
Del
OK
php1UicbS
23.23 KB
Del
OK
php1VwCzk
3.38 KB
Del
OK
php1e1a7w
1.05 MB
Del
OK
php1fxBfr
512 B
Del
OK
php1iXX1M
40 KB
Del
OK
php1k9TgO
40 KB
Del
OK
php1s2OVF
3.94 KB
Del
OK
php1xqKaI
96 KB
Del
OK
php28At3t
16 KB
Del
OK
php29MzXR
3.98 KB
Del
OK
php2CaVG0
19.32 KB
Del
OK
php2Ez5E8
40 KB
Del
OK
php2OIZAJ
16 KB
Del
OK
php2Q527a
6.53 MB
Del
OK
php2S2baW
40 KB
Del
OK
php2TcimF
15.66 KB
Del
OK
php2UIbfD
21.72 MB
Del
OK
php2XNrfC
4.99 KB
Del
OK
php2cOauz
24 KB
Del
OK
php2dQNRA
1.21 KB
Del
OK
php2eqZ0O
715.59 KB
Del
OK
php2gQIc6
8.24 KB
Del
OK
php2inYsi
40 KB
Del
OK
php2jjWxB
147.04 KB
Del
OK
php2lFD4k
2 KB
Del
OK
php2rCrQx
249.88 KB
Del
OK
php2wj4x2
35.27 KB
Del
OK
php2xi2b0
1.5 KB
Del
OK
php2zqVTM
8.5 KB
Del
OK
php32FDTG
16.5 KB
Del
OK
php330eAu
29.4 MB
Del
OK
php36Vliv
73.59 KB
Del
OK
php37voyY
15.59 KB
Del
OK
php3D0n82
67.95 KB
Del
OK
php3M1O9x
43.19 MB
Del
OK
php3ON19I
0 B
Del
OK
php3P2kvK
11.5 KB
Del
OK
php3QU2do
0 B
Del
OK
php3TN5za
0 B
Del
OK
php3UEFTY
1.5 KB
Del
OK
php3dIAUq
31.81 KB
Del
OK
php3fe19A
512 B
Del
OK
php3gltxA
60.17 KB
Del
OK
php3hFfO2
45.98 KB
Del
OK
php3ntMT9
39.45 KB
Del
OK
php3olRtr
1.5 KB
Del
OK
php3pOjZl
384.5 KB
Del
OK
php3rK5zV
32.5 KB
Del
OK
php3tprIC
550 B
Del
OK
php3xLip3
27.67 KB
Del
OK
php3zsXea
80 KB
Del
OK
php440adM
263.4 KB
Del
OK
php445aUf
9.89 KB
Del
OK
php45cCq0
32 KB
Del
OK
php4FVXp1
11.55 KB
Del
OK
php4KGY4d
2.76 MB
Del
OK
php4Lv7Ai
0 B
Del
OK
php4MCktH
16 KB
Del
OK
php4OlHNM
0 B
Del
OK
php4TKIy9
4 KB
Del
OK
php4UBY3r
405 B
Del
OK
php4X6RpD
24.5 KB
Del
OK
php4YGCsf
32 KB
Del
OK
php4a9qMI
0 B
Del
OK
php4dGaa9
40 KB
Del
OK
php4dXw4u
80 KB
Del
OK
php4ez48G
40 KB
Del
OK
php4h2PFX
40 KB
Del
OK
php4icfa3
40 KB
Del
OK
php4mLiVH
6.07 MB
Del
OK
php4mSNRQ
0 B
Del
OK
php4n70H7
75.75 KB
Del
OK
php4oUm5H
1.01 KB
Del
OK
php4zSFNk
1.75 MB
Del
OK
php59NDyk
49.74 KB
Del
OK
php5DLWJi
512 B
Del
OK
php5FaKuU
39.54 KB
Del
OK
php5KQZ86
33.54 KB
Del
OK
php5Pm4BY
1.73 KB
Del
OK
php5V1Sqo
40 KB
Del
OK
php5V4oH9
83 B
Del
OK
php5apmfN
20.87 KB
Del
OK
php5fde6q
8.5 KB
Del
OK
php5gKjFI
4.22 MB
Del
OK
php5jyjgk
68 B
Del
OK
php5lKVj0
32 KB
Del
OK
php5r4Y7O
10.53 MB
Del
OK
php5tm8Rp
1.94 KB
Del
OK
php5vJXmQ
80 KB
Del
OK
php5wNDen
2.73 MB
Del
OK
php5yYpKf
8.58 KB
Del
OK
php60anWj
1.24 MB
Del
OK
php68JiUr
0 B
Del
OK
php6CAWrS
53.56 MB
Del
OK
php6IKgfF
40.54 KB
Del
OK
php6Im3r4
40 KB
Del
OK
php6Iur8A
38.98 KB
Del
OK
php6JCsp9
32 KB
Del
OK
php6MWySe
40 KB
Del
OK
php6NE2eL
1.07 MB
Del
OK
php6OcA1z
24.02 KB
Del
OK
php6QEPJr
41.78 MB
Del
OK
php6Qd5EW
8 KB
Del
OK
php6UZIvM
0 B
Del
OK
php6azyWE
23.83 KB
Del
OK
php6h4ySy
40 KB
Del
OK
php6iexHc
40 KB
Del
OK
php6pnCiz
110.07 KB
Del
OK
php6xvuCl
16.86 MB
Del
OK
php6zIZFE
8 B
Del
OK
php77fFv0
25.72 KB
Del
OK
php77wybR
40 KB
Del
OK
php7CN70m
0 B
Del
OK
php7I1QXa
5.18 MB
Del
OK
php7J1Atw
234.4 KB
Del
OK
php7NA1aC
20.91 MB
Del
OK
php7U4leS
55.32 MB
Del
OK
php7UQrRj
2 KB
Del
OK
php7WGDuk
91.96 KB
Del
OK
php7XE0an
512 B
Del
OK
php7Yz1Rp
2.5 KB
Del
OK
php7br3tc
81.21 KB
Del
OK
php7dEGUi
3.9 KB
Del
OK
php7e7Qdz
40 KB
Del
OK
php7fwBx9
17.19 KB
Del
OK
php7grjXm
27.3 KB
Del
OK
php7h1JM4
16.32 KB
Del
OK
php7hiFHT
23.55 KB
Del
OK
php7mcTCL
1.29 MB
Del
OK
php7rUahT
8 KB
Del
OK
php7siU9s
1.5 KB
Del
OK
php7wbrip
40 KB
Del
OK
php7xs4PV
9.77 KB
Del
OK
php86YnmU
16.37 KB
Del
OK
php86tdZo
12.23 MB
Del
OK
php86yPmE
8.08 KB
Del
OK
php87oTpS
28.49 KB
Del
OK
php89UEat
1.45 MB
Del
OK
php8B4VlV
10.57 KB
Del
OK
php8Bg4Er
1.5 KB
Del
OK
php8GLz76
32 KB
Del
OK
php8Iz687
1013 B
Del
OK
php8TnD14
34.53 KB
Del
OK
php8XkkOb
40 KB
Del
OK
php8dpS39
32 KB
Del
OK
php8k5SY5
16 KB
Del
OK
php8kaGbK
40 KB
Del
OK
php8kpDuP
18.15 MB
Del
OK
php8wi06h
1.67 KB
Del
OK
php93xki0
26.23 KB
Del
OK
php99dbtt
39.42 KB
Del
OK
php9AUMAS
7.5 KB
Del
OK
php9AV7FX
1.86 MB
Del
OK
php9CI6Vp
32 KB
Del
OK
php9Ihzha
12.5 KB
Del
OK
php9Iutz4
11.82 KB
Del
OK
php9J7msk
78 B
Del
OK
php9MGgnV
512 B
Del
OK
php9Nt6zt
35.52 KB
Del
OK
php9Q1sbk
57.74 MB
Del
OK
php9RXD7v
1.5 KB
Del
OK
php9YP9iW
30.8 KB
Del
OK
php9boBk3
79.29 MB
Del
OK
php9c9Q3B
35.72 MB
Del
OK
php9ffHgn
89 B
Del
OK
php9jvV3c
0 B
Del
OK
php9kCQ36
0 B
Del
OK
php9qCwBF
40 KB
Del
OK
php9qqqw0
42.62 KB
Del
OK
php9rp8br
32.72 KB
Del
OK
php9xy7tX
40 KB
Del
OK
phpA1LgKO
72 KB
Del
OK
phpA26A7k
8.5 KB
Del
OK
phpA8wu0U
4.99 MB
Del
OK
phpA9RRRV
512 B
Del
OK
phpABmhXR
11.51 KB
Del
OK
phpADYWCn
410 KB
Del
OK
phpAEiDiG
24.61 KB
Del
OK
phpAG7dHD
40 KB
Del
OK
phpAH0EnE
1.39 MB
Del
OK
phpAJwgvE
0 B
Del
OK
phpAOOMwi
2 KB
Del
OK
phpAP9lfl
40 KB
Del
OK
phpAW1PF0
281.53 KB
Del
OK
phpAaQAcM
72.05 KB
Del
OK
phpAf6tCc
0 B
Del
OK
phpAfyDDb
40 KB
Del
OK
phpAiz6zw
512 B
Del
OK
phpAjRgLq
399 B
Del
OK
phpAzBMMM
35.38 KB
Del
OK
phpB2pERU
516 KB
Del
OK
phpB69IUu
32 KB
Del
OK
phpB6Q4EI
31.48 KB
Del
OK
phpBFxDtI
28.04 KB
Del
OK
phpBG4GP2
4.75 KB
Del
OK
phpBLLqMo
2.48 MB
Del
OK
phpBMomvl
15.82 KB
Del
OK
phpBR69HE
32 KB
Del
OK
phpBX8XAw
1.42 KB
Del
OK
phpBl0lUb
8.58 KB
Del
OK
phpBmh3Am
40 KB
Del
OK
phpBqTHDS
88.36 KB
Del
OK
phpC186oj
118 B
Del
OK
phpC6yCwB
17.19 KB
Del
OK
phpC8f5DM
4.67 KB
Del
OK
phpC9Ln41
160 KB
Del
OK
phpCIZwEh
13.91 KB
Del
OK
phpCLgq2B
178.49 KB
Del
OK
phpCMOzKd
601 B
Del
OK
phpCSLJxR
2.07 MB
Del
OK
phpCVICMp
3.66 MB
Del
OK
phpCa5SPg
23.79 KB
Del
OK
phpCaZD1D
79.37 MB
Del
OK
phpCfpkv6
184 KB
Del
OK
phpChE8Wc
40 KB
Del
OK
phpCsNp9n
76.95 KB
Del
OK
phpCt58ws
8.5 KB
Del
OK
phpCto6S7
0 B
Del
OK
phpCxUmSY
2.35 MB
Del
OK
phpD1qEbt
33.55 MB
Del
OK
phpD7nFJN
40 KB
Del
OK
phpDEPxNm
82.35 KB
Del
OK
phpDFKBdu
0 B
Del
OK
phpDFpZqI
24.44 KB
Del
OK
phpDI8V3J
32 KB
Del
OK
phpDKhp9b
2.72 MB
Del
OK
phpDRQ9DM
5.12 MB
Del
OK
phpDVvD2X
32 KB
Del
OK
phpDlCYxC
195.86 KB
Del
OK
phpDmBTuf
32 KB
Del
OK
phpDojSMG
14.83 KB
Del
OK
phpDp2bDV
48.33 KB
Del
OK
phpDqigbN
16 KB
Del
OK
phpDqnLKC
512 B
Del
OK
phpDrUtUX
151 KB
Del
OK
phpDwKcRO
171.86 KB
Del
OK
phpDyvWaQ
810 B
Del
OK
phpE0dfwd
12.57 KB
Del
OK
phpE1CLxk
24.08 KB
Del
OK
phpE85YQK
2.85 KB
Del
OK
phpECFWdn
40 KB
Del
OK
phpEF1nZd
40 KB
Del
OK
phpEHkFf0
1.56 KB
Del
OK
phpEIz6kY
4.9 KB
Del
OK
phpELlCkq
512 B
Del
OK
phpENBKKD
3.25 MB
Del
OK
phpEOZjEK
32 KB
Del
OK
phpEVPKWM
60.44 KB
Del
OK
phpEYy2WG
0 B
Del
OK
phpEbmrQr
8 KB
Del
OK
phpEhQ9AL
46 B
Del
OK
phpEoVbYr
40 KB
Del
OK
phpEpiP8R
0 B
Del
OK
phpEt6xl2
80 KB
Del
OK
phpEuKeZN
0 B
Del
OK
phpEvFWWO
2.64 MB
Del
OK
phpEx5vdu
220 B
Del
OK
phpF1db4V
40 KB
Del
OK
phpF27R7c
102.01 MB
Del
OK
phpF2UCNR
2.5 KB
Del
OK
phpF4Acbd
2.5 KB
Del
OK
phpF9Awve
45 B
Del
OK
phpFDw8BK
46 B
Del
OK
phpFGyMvE
40 KB
Del
OK
phpFJj1Z6
1.87 MB
Del
OK
phpFOc23l
2.89 MB
Del
OK
phpFPeK3A
25 KB
Del
OK
phpFPuFKK
2.75 MB
Del
OK
phpFUcPq9
1.31 MB
Del
OK
phpFbtsXw
0 B
Del
OK
phpFgy8Js
46 B
Del
OK
phpFgyuqy
192 KB
Del
OK
phpFjAsfz
1.5 KB
Del
OK
phpFkrmBz
78 B
Del
OK
phpFlgtL2
7.5 KB
Del
OK
phpFnjbmB
1.5 KB
Del
OK
phpG0pzF5
80 KB
Del
OK
phpG1rrPi
40 KB
Del
OK
phpG2E8tu
456.9 KB
Del
OK
phpG5SMWX
32 KB
Del
OK
phpG7MNVO
64.5 KB
Del
OK
phpGBYCWo
40 KB
Del
OK
phpGBt0R2
47.83 KB
Del
OK
phpGLA0Uh
20.68 KB
Del
OK
phpGMxv12
29.13 KB
Del
OK
phpGWoY85
416 KB
Del
OK
phpGZOiEG
32 KB
Del
OK
phpGe7TCG
40 KB
Del
OK
phpGhLaQ7
0 B
Del
OK
phpGiMBYZ
24 KB
Del
OK
phpGjzD7b
40 KB
Del
OK
phpGtENsj
0 B
Del
OK
phpGuLBMC
8 KB
Del
OK
phpH6JuyV
5.02 MB
Del
OK
phpH7O00N
32.5 KB
Del
OK
phpH808SC
40 KB
Del
OK
phpHAi6L2
79.35 MB
Del
OK
phpHBDBay
40 KB
Del
OK
phpHCqDBg
40 KB
Del
OK
phpHMeRe8
0 B
Del
OK
phpHUUrMT
2 KB
Del
OK
phpHYf6VD
36.14 KB
Del
OK
phpHggk41
0 B
Del
OK
phpHiczhe
392 KB
Del
OK
phpHmWPs9
69 B
Del
OK
phpHnFFCl
6.32 KB
Del
OK
phpHyQMqj
3.79 KB
Del
OK
phpHzp4Jd
11.08 KB
Del
OK
phpI9Vgpt
15.87 KB
Del
OK
phpI9vy8I
151.38 KB
Del
OK
phpIBPQcM
20.04 KB
Del
OK
phpID77wU
32 KB
Del
OK
phpIDAogY
51.38 KB
Del
OK
phpIEMNjF
17.56 KB
Del
OK
phpIIdfts
24.5 KB
Del
OK
phpIJndBV
13 KB
Del
OK
phpIK0bxI
23.09 KB
Del
OK
phpIMCR9F
29 KB
Del
OK
phpIMiWS7
1.5 KB
Del
OK
phpIQ2PCj
6 KB
Del
OK
phpIS5czG
2.46 KB
Del
OK
phpIYJfHn
10.79 KB
Del
OK
phpIZtbLn
0 B
Del
OK
phpIbtQ60
11.5 KB
Del
OK
phpIidNsc
0 B
Del
OK
phpIjl1uC
0 B
Del
OK
phpIlGZVA
23.63 MB
Del
OK
phpIpvF03
0 B
Del
OK
phpIrtyps
860.95 KB
Del
OK
phpIt6Ral
69.59 KB
Del
OK
phpIvmCNS
22.7 KB
Del
OK
phpIwICvp
171.86 KB
Del
OK
phpJ3YL59
2.83 MB
Del
OK
phpJ44BNU
14.41 KB
Del
OK
phpJ4rm1H
4.5 KB
Del
OK
phpJ5MxmL
164.98 KB
Del
OK
phpJCf7nV
8 KB
Del
OK
phpJCzlen
40 KB
Del
OK
phpJDGMzX
46.63 KB
Del
OK
phpJHWX0N
0 B
Del
OK
phpJIp4VW
0 B
Del
OK
phpJNFYHR
8 KB
Del
OK
phpJPFew6
152 KB
Del
OK
phpJQUNz0
7.5 KB
Del
OK
phpJTiGy0
35.27 KB
Del
OK
phpJWOZIT
32 KB
Del
OK
phpJY9Eww
354.33 KB
Del
OK
phpJdD5Wa
16.05 KB
Del
OK
phpJesLeK
27.85 MB
Del
OK
phpJidmJ7
8 KB
Del
OK
phpJm0QXa
512 B
Del
OK
phpJq1PDF
23.01 KB
Del
OK
phpJtfnkw
8.71 MB
Del
OK
phpJyb8in
63.08 MB
Del
OK
phpK3vTbB
5.52 MB
Del
OK
phpK4ZYOy
24.75 KB
Del
OK
phpKFGFiY
6.13 MB
Del
OK
phpKNXngO
35.41 KB
Del
OK
phpKOcA8K
40 KB
Del
OK
phpKQjzmP
40 KB
Del
OK
phpKRQ72Y
53.56 MB
Del
OK
phpKSh7Wl
6.5 KB
Del
OK
phpKTfsHK
17.65 MB
Del
OK
phpKUQ5m4
2.51 MB
Del
OK
phpKckQ0Q
3.5 KB
Del
OK
phpKhmkB0
79.44 MB
Del
OK
phpKkgYrf
51.8 KB
Del
OK
phpKmTe57
2.07 MB
Del
OK
phpKzTb28
80 KB
Del
OK
phpL0medW
40 KB
Del
OK
phpLAdePz
1.35 MB
Del
OK
phpLEHLuv
512 B
Del
OK
phpLIQ7pY
8.5 KB
Del
OK
phpLOEQEU
33 B
Del
OK
phpLS94cB
32 KB
Del
OK
phpLUa2Z0
40 KB
Del
OK
phpLXq4WM
512 B
Del
OK
phpLc9n7p
0 B
Del
OK
phpLo0sxn
35.39 KB
Del
OK
phpLoShi8
110.46 KB
Del
OK
phpLqH87l
1.5 KB
Del
OK
phpLsCHuH
16 KB
Del
OK
phpLu1mBs
472 KB
Del
OK
phpLzRO82
3 KB
Del
OK
phpM3QdQk
3.22 MB
Del
OK
phpMAPPyA
512 B
Del
OK
phpMIdygD
40 KB
Del
OK
phpMM9u4f
72.97 KB
Del
OK
phpMNbay9
56.5 KB
Del
OK
phpMO0Y2e
32 KB
Del
OK
phpMSCsq2
8.5 KB
Del
OK
phpMUs66Z
512 B
Del
OK
phpMXQo3Q
1.5 KB
Del
OK
phpMYWlzf
512 B
Del
OK
phpMbCf3a
0 B
Del
OK
phpMedvLo
55.45 MB
Del
OK
phpMfPjPF
794.44 KB
Del
OK
phpN3xc6o
1.66 KB
Del
OK
phpN8lxu6
40 KB
Del
OK
phpNAg5Cc
25.76 KB
Del
OK
phpNFqaBT
0 B
Del
OK
phpNIFs38
42.2 KB
Del
OK
phpNRjOLd
791.67 KB
Del
OK
phpNVc2ke
8.96 KB
Del
OK
phpNYyRsW
0 B
Del
OK
phpNdZcU6
40 KB
Del
OK
phpNgJx7w
40 KB
Del
OK
phpNje2eZ
32.05 KB
Del
OK
phpNjgLvm
1.5 KB
Del
OK
phpNpcqsI
14.5 KB
Del
OK
phpNvwCTh
0 B
Del
OK
phpNykVBj
512 B
Del
OK
phpNyoHY4
32.02 KB
Del
OK
phpO1mxEC
3.94 KB
Del
OK
phpO8gbMR
57.74 MB
Del
OK
phpOBnTO4
79.38 MB
Del
OK
phpOCRRXV
0 B
Del
OK
phpOCvs70
16 KB
Del
OK
phpOMiF5S
40 KB
Del
OK
phpOMoPtu
6.29 KB
Del
OK
phpONT9UL
19.16 KB
Del
OK
phpOOvmWo
181 B
Del
OK
phpORyiCd
2.25 MB
Del
OK
phpOSjz0x
0 B
Del
OK
phpOU8tJD
0 B
Del
OK
phpOYgGKi
1.5 KB
Del
OK
phpOavCwM
88 KB
Del
OK
phpOcAuaK
31.4 KB
Del
OK
phpOu3TUR
62 B
Del
OK
phpOzeA8r
151.97 KB
Del
OK
phpP4iJFE
32 KB
Del
OK
phpP67g9Y
384 KB
Del
OK
phpP74C3a
18 B
Del
OK
phpP9rT5q
40 KB
Del
OK
phpPBABeU
555.5 KB
Del
OK
phpPBqRGr
0 B
Del
OK
phpPEBtEj
7.98 MB
Del
OK
phpPFNbqU
40 KB
Del
OK
phpPFzKL4
19.34 KB
Del
OK
phpPJQ7BY
1.88 KB
Del
OK
phpPROmTq
1.76 KB
Del
OK
phpPVkJqO
0 B
Del
OK
phpPWQGIS
31.31 KB
Del
OK
phpPX9ony
40 KB
Del
OK
phpPXoGyE
1.08 MB
Del
OK
phpPY6Gh1
1.66 MB
Del
OK
phpPc5KZ4
731.95 KB
Del
OK
phpPcFz3V
40 KB
Del
OK
phpPkCo8y
80 KB
Del
OK
phpPqIzil
32.72 KB
Del
OK
phpPrMVYK
39.64 KB
Del
OK
phpPreqC5
15.11 KB
Del
OK
phpPw7LF8
2.22 MB
Del
OK
phpPyOJZ1
13.39 MB
Del
OK
phpPzOUDe
72.6 KB
Del
OK
phpQ6rrmq
1.5 KB
Del
OK
phpQ7sOCs
452.45 KB
Del
OK
phpQDwlth
299 KB
Del
OK
phpQFxsPq
40 KB
Del
OK
phpQHWsKh
30 B
Del
OK
phpQPvRj3
512 B
Del
OK
phpQSb6ju
62.04 KB
Del
OK
phpQSkEHm
8 KB
Del
OK
phpQWe5Ya
5 KB
Del
OK
phpQd2Jhh
34.44 KB
Del
OK
phpQhJ510
200.5 KB
Del
OK
phpQhoYIZ
18.39 KB
Del
OK
phpQkefGr
40 KB
Del
OK
phpQlBcyZ
80 KB
Del
OK
phpQsXTfJ
40 KB
Del
OK
phpQtQ4Tu
15.25 MB
Del
OK
phpQuilX4
20.18 KB
Del
OK
phpQvSBM3
1.78 MB
Del
OK
phpRC716h
16 KB
Del
OK
phpRHzJ6A
3.27 MB
Del
OK
phpRIWqF2
40 KB
Del
OK
phpRJmDti
34.87 KB
Del
OK
phpRLp9Hw
512 B
Del
OK
phpRX5HyJ
40 KB
Del
OK
phpRY6kxE
40 KB
Del
OK
phpRjO7z0
9.79 MB
Del
OK
phpRmG8Mp
457 B
Del
OK
phpRmRFOt
40 KB
Del
OK
phpRnnnh2
0 B
Del
OK
phpRqd13P
2.5 KB
Del
OK
phpRuVWSs
8 KB
Del
OK
phpRx3yOp
8 KB
Del
OK
phpRxU3oD
47.94 MB
Del
OK
phpRzmyJo
16 KB
Del
OK
phpS7fqzz
900 B
Del
OK
phpSFB9iK
1.5 KB
Del
OK
phpSHNTYt
512 B
Del
OK
phpSL5J24
16.5 MB
Del
OK
phpSNAxJm
512 B
Del
OK
phpSV3958
77.52 MB
Del
OK
phpSWorIb
15.6 KB
Del
OK
phpSgFaor
40 KB
Del
OK
phpSjEzWN
40 KB
Del
OK
phpSl3v8s
0 B
Del
OK
phpSlgcp1
52 B
Del
OK
phpSmFUiV
40 KB
Del
OK
phpSySmLg
10.7 KB
Del
OK
phpT677nX
3.88 KB
Del
OK
phpTHDzBe
15.15 KB
Del
OK
phpTKGUnd
25.02 KB
Del
OK
phpTKND41
80 KB
Del
OK
phpTKy2uD
324.17 KB
Del
OK
phpTQrfsd
2 KB
Del
OK
phpTWd9oN
40 B
Del
OK
phpTagKwn
0 B
Del
OK
phpTd0krH
22.61 MB
Del
OK
phpTgZCdG
40 KB
Del
OK
phpTlzK2m
65.68 KB
Del
OK
phpTnff7L
24.5 KB
Del
OK
phpToBTsi
57 B
Del
OK
phpToyPsW
512 B
Del
OK
phpTtaYa2
11.05 KB
Del
OK
phpU3uTFz
40 KB
Del
OK
phpU7Ym1p
1.08 MB
Del
OK
phpU7uz55
15.65 KB
Del
OK
phpUFTPl9
823 B
Del
OK
phpUIH7ix
0 B
Del
OK
phpUZ9X9f
639 KB
Del
OK
phpUaLNwx
40.11 KB
Del
OK
phpUbGApk
7.64 MB
Del
OK
phpUcd5Z9
999 B
Del
OK
phpUlmBSh
21.52 KB
Del
OK
phpUmI62w
0 B
Del
OK
phpUosLhV
40 KB
Del
OK
phpUpQY4f
0 B
Del
OK
phpUqH1om
128.5 KB
Del
OK
phpUrjHRo
27.75 KB
Del
OK
phpUwrqDO
0 B
Del
OK
phpVC6tdG
13.91 KB
Del
OK
phpVEenuw
33 B
Del
OK
phpVHnw3N
512 B
Del
OK
phpVN0t44
4.21 MB
Del
OK
phpVQ2Duo
400.45 KB
Del
OK
phpVRqvNP
11.12 MB
Del
OK
phpVVM36k
0 B
Del
OK
phpVWnn7O
15.69 KB
Del
OK
phpVZmSeK
8 KB
Del
OK
phpVhSI7T
46.39 MB
Del
OK
phpVlbocq
715.59 KB
Del
OK
phpVvtJcJ
0 B
Del
OK
phpVw1WYD
72.07 KB
Del
OK
phpVw457K
78.06 MB
Del
OK
phpVwbhnM
9.41 MB
Del
OK
phpVwyO1a
15.1 KB
Del
OK
phpVzPSj1
3.03 MB
Del
OK
phpW4hsSR
8.5 KB
Del
OK
phpW5J6zY
74.06 KB
Del
OK
phpW6TzcG
512 B
Del
OK
phpW6cVVE
131.55 KB
Del
OK
phpW7GQhR
67 B
Del
OK
phpW80yCr
40 KB
Del
OK
phpW8KwmC
0 B
Del
OK
phpW8nQzI
30.71 MB
Del
OK
phpWB9Vc4
941.23 KB
Del
OK
phpWBTw9T
3.29 KB
Del
OK
phpWCE1Th
79.3 MB
Del
OK
phpWEvKuZ
512 B
Del
OK
phpWTA2ar
35.4 KB
Del
OK
phpWTBjRR
32.5 KB
Del
OK
phpWUxphd
6.86 KB
Del
OK
phpWX3mlM
23.14 KB
Del
OK
phpWYTIsL
119 B
Del
OK
phpWZEs5j
0 B
Del
OK
phpWcxx3g
2.7 MB
Del
OK
phpWiNDHg
0 B
Del
OK
phpWlbinZ
40 KB
Del
OK
phpWyF18J
68.28 MB
Del
OK
phpX9NfYV
27.28 KB
Del
OK
phpXMHpwC
1.97 MB
Del
OK
phpXWrRLe
40 KB
Del
OK
phpXaI2yt
21 B
Del
OK
phpXbW5eW
192 KB
Del
OK
phpXeEKhc
8.5 KB
Del
OK
phpXkNHHE
8.5 KB
Del
OK
phpXm3YDI
80 KB
Del
OK
phpXmFMt6
1.42 KB
Del
OK
phpXrKKqo
0 B
Del
OK
phpXrrc3r
40 KB
Del
OK
phpXsx1rg
40 KB
Del
OK
phpY2xdEb
0 B
Del
OK
phpY4xYwf
3.64 MB
Del
OK
phpY5VqsO
19.74 KB
Del
OK
phpY5f6HV
53.9 MB
Del
OK
phpY8SyxK
32 KB
Del
OK
phpYBn5sb
16 KB
Del
OK
phpYHLLMf
538 B
Del
OK
phpYJU5Jw
399 B
Del
OK
phpYKU3Fs
26.43 KB
Del
OK
phpYP4gnz
512 B
Del
OK
phpYUzBlp
7 KB
Del
OK
phpYZ1XX0
91.88 KB
Del
OK
phpYaEzve
4.5 KB
Del
OK
phpYaotvU
0 B
Del
OK
phpYbDqNH
0 B
Del
OK
phpYbOaET
40 KB
Del
OK
phpYbqEHR
40 KB
Del
OK
phpYgpaav
80 KB
Del
OK
phpYk6ooC
16.5 KB
Del
OK
phpYonSjm
24 KB
Del
OK
phpZ645wl
13.16 KB
Del
OK
phpZ723P0
40 KB
Del
OK
phpZCjTJe
26 B
Del
OK
phpZFHdpP
13.66 KB
Del
OK
phpZLCmXV
200 B
Del
OK
phpZQVhL6
538 B
Del
OK
phpZS4m0k
40 KB
Del
OK
phpZUgl5F
79.41 MB
Del
OK
phpZXbJsG
16 KB
Del
OK
phpZYfgmo
40 KB
Del
OK
phpZcmVhj
66.55 KB
Del
OK
phpZgfSQk
1.66 KB
Del
OK
phpZp2HzV
9.89 KB
Del
OK
phpZrxJwW
512 B
Del
OK
phpZwB5Zb
32.5 KB
Del
OK
phpZxUjA9
24 KB
Del
OK
php_sessions
-
Del
OK
phpa38H6V
80 KB
Del
OK
phpaEtPG9
40 KB
Del
OK
phpaGnfek
79.33 MB
Del
OK
phpaQzsAw
40 KB
Del
OK
phpaTN3Qs
40 KB
Del
OK
phpaWuwqA
40 KB
Del
OK
phpagjUdS
40 KB
Del
OK
phpahKg5K
0 B
Del
OK
phpajvIvs
3.9 KB
Del
OK
phpanpoRm
40 KB
Del
OK
phpanxfLR
512 B
Del
OK
phpaoUy3u
5.53 KB
Del
OK
phpar1Lh2
40 KB
Del
OK
phparp6o3
552 B
Del
OK
phpasLy8J
27.75 KB
Del
OK
phpaxoWIX
170.49 KB
Del
OK
phpb39n4j
40 KB
Del
OK
phpb7FPuG
32 KB
Del
OK
phpbByw9Y
40 KB
Del
OK
phpbGQxDz
21.5 KB
Del
OK
phpbIpleT
17.41 KB
Del
OK
phpbLTYtQ
40 KB
Del
OK
phpbN9rea
67.73 MB
Del
OK
phpbUCFwB
319 B
Del
OK
phpbXXIj7
16 KB
Del
OK
phpbY0pAs
24.5 KB
Del
OK
phpbg18wT
40 KB
Del
OK
phpbhp5lJ
1.56 MB
Del
OK
phpbmCdwO
63.13 MB
Del
OK
phpbnDVY3
40 KB
Del
OK
phpbniljq
1.67 KB
Del
OK
phpbo1zqA
40 KB
Del
OK
phpbq87CB
35.48 KB
Del
OK
phpbvfLrC
80.5 KB
Del
OK
phpc58RO9
40 KB
Del
OK
phpc91PE3
283 B
Del
OK
phpcIVcoe
9.98 MB
Del
OK
phpcP8pJC
40 KB
Del
OK
phpcPHJRz
27.3 KB
Del
OK
phpcPMnuz
48.95 KB
Del
OK
phpcUnADS
32 KB
Del
OK
phpcUqt0w
39.62 KB
Del
OK
phpcVjrCW
40 KB
Del
OK
phpcYTUxC
43.68 KB
Del
OK
phpcasPiY
26.19 MB
Del
OK
phpccUwHE
42.4 KB
Del
OK
phpcj561o
40 KB
Del
OK
phpckDeiA
0 B
Del
OK
phpckXZib
512 B
Del
OK
phpcvxeey
11.45 MB
Del
OK
phpcxKKo2
76.87 KB
Del
OK
phpcyWMfS
412 B
Del
OK
phpd9yj4I
8.15 KB
Del
OK
phpdBX0YU
0 B
Del
OK
phpdBqH9G
1.5 KB
Del
OK
phpdJuguR
0 B
Del
OK
phpdL2pRD
40 KB
Del
OK
phpdMTIGo
6.87 MB
Del
OK
phpdQ9VZ7
35.35 KB
Del
OK
phpdQSqPV
8.86 KB
Del
OK
phpdWLuoM
30 B
Del
OK
phpdcx4o6
40 KB
Del
OK
phpdgO8xL
40 KB
Del
OK
phpdjlESG
1.61 MB
Del
OK
phpdo9ge4
584 KB
Del
OK
phpdoYQLo
2.5 KB
Del
OK
phpdq5XHF
27.3 KB
Del
OK
phpe7jybV
32 KB
Del
OK
phpeCgzPX
27.67 KB
Del
OK
phpeG6cJ8
24 KB
Del
OK
phpeNgMXr
0 B
Del
OK
phpeTjuGU
1.5 KB
Del
OK
phpeU9oDV
11.35 KB
Del
OK
phpeVzKao
1.8 MB
Del
OK
phpeXic8d
6 KB
Del
OK
phpeZIl0A
31.81 KB
Del
OK
phpeg8PRA
15.63 KB
Del
OK
phpeka3IH
40 KB
Del
OK
phpemJnWA
40 KB
Del
OK
phpeouNfI
8.5 KB
Del
OK
phpeuRJHW
5.49 MB
Del
OK
phpevMga9
32 KB
Del
OK
phpevbjlO
16 KB
Del
OK
phpexMJky
694.37 KB
Del
OK
phpf1xr4u
64.07 KB
Del
OK
phpf2daOx
3.93 KB
Del
OK
phpf3Wdwr
1.5 KB
Del
OK
phpf82doz
16.19 KB
Del
OK
phpfFqFv7
102.01 MB
Del
OK
phpfLEIaX
40 KB
Del
OK
phpfNwAFc
512 B
Del
OK
phpfcP9mX
12.32 KB
Del
OK
phpff8vTj
8.08 KB
Del
OK
phpffDKzS
40 KB
Del
OK
phpffmUMM
59 B
Del
OK
phpfq8oks
40 KB
Del
OK
phpfqWCYM
1.63 KB
Del
OK
phpfvp788
64.42 KB
Del
OK
phpg3qBsi
30.03 MB
Del
OK
phpg5NKSB
28 B
Del
OK
phpg9qLPE
512 B
Del
OK
phpgBX9ej
10.55 KB
Del
OK
phpgFW5Og
39.63 KB
Del
OK
phpgHrFki
512 B
Del
OK
phpgIdKtS
512 B
Del
OK
phpgPBX0K
5.53 MB
Del
OK
phpgVQqKn
0 B
Del
OK
phpgZZeXv
7.5 KB
Del
OK
phpgbX0cZ
0 B
Del
OK
phpghgCqD
62 B
Del
OK
phpgpaGUT
0 B
Del
OK
phpgrkDGo
50 B
Del
OK
phpgxG6r1
3.13 MB
Del
OK
phph0CZpN
80 KB
Del
OK
phph1Px6x
31.74 KB
Del
OK
phph4mi3p
40 KB
Del
OK
phphCXDud
27.28 KB
Del
OK
phphCsqSQ
512 B
Del
OK
phphQrS6j
38.8 KB
Del
OK
phphUX0pL
206 B
Del
OK
phphVOZp0
0 B
Del
OK
phphb4zJl
20.01 MB
Del
OK
phphdNjzt
44.42 KB
Del
OK
phphqixDP
1.5 KB
Del
OK
phpi278sg
0 B
Del
OK
phpi29fKx
40 KB
Del
OK
phpi3pXDu
32.32 MB
Del
OK
phpiA2LAd
32 KB
Del
OK
phpiFPIH1
1.43 KB
Del
OK
phpiION5P
28.67 KB
Del
OK
phpiO3vXE
141.71 KB
Del
OK
phpiORDZV
35.33 KB
Del
OK
phpiSoWUS
32 KB
Del
OK
phpiU8JRj
1.21 KB
Del
OK
phpiW5PPS
80 KB
Del
OK
phpidbwyM
21.13 KB
Del
OK
phpifmXJh
14.01 KB
Del
OK
phpihFVxi
1.5 KB
Del
OK
phpihWRZx
2.05 MB
Del
OK
phpii5l13
3.98 MB
Del
OK
phpiiW1Z0
0 B
Del
OK
phpimn9fZ
0 B
Del
OK
phpipJbfx
0 B
Del
OK
phpir3Fx7
16 KB
Del
OK
phpity2Px
32 KB
Del
OK
phpiuNze1
25 KB
Del
OK
phpiz0sfa
8.5 KB
Del
OK
phpizokim
335 B
Del
OK
phpj4mCEt
15.1 KB
Del
OK
phpj8Z2EY
8 KB
Del
OK
phpj9FQ75
40 KB
Del
OK
phpjA9Gr4
5.65 KB
Del
OK
phpjIGGD0
18.42 MB
Del
OK
phpjLJeSf
1 B
Del
OK
phpjUu8Kz
0 B
Del
OK
phpjWPMRD
4.58 MB
Del
OK
phpjYMbvq
15.14 KB
Del
OK
phpjbafu6
2.85 KB
Del
OK
phpjc0UlZ
40 KB
Del
OK
phpjlbXU6
8.94 KB
Del
OK
phpjpSyM6
16 KB
Del
OK
phpjqAENS
80 KB
Del
OK
phpjwTDLc
40 B
Del
OK
phpk0x4At
39.59 KB
Del
OK
phpk77sRo
74.51 KB
Del
OK
phpkCV4Bo
512 B
Del
OK
phpkH8TgW
32 KB
Del
OK
phpkRK4Dr
1.08 MB
Del
OK
phpkaBcDR
24.34 KB
Del
OK
phpkdhzEh
15.13 KB
Del
OK
phpkfnIlj
39.51 KB
Del
OK
phpkl3JOp
6 KB
Del
OK
phpknCWMB
16 KB
Del
OK
phpkz3Ol6
30 B
Del
OK
phpkzfJEF
0 B
Del
OK
phpl2Mwlm
63.07 MB
Del
OK
phpl4uRRG
0 B
Del
OK
phpl5x3fb
8 KB
Del
OK
phpl9QvWX
80 KB
Del
OK
phplI05xU
40 KB
Del
OK
phplJTM8Z
0 B
Del
OK
phplKIaVD
16 KB
Del
OK
phplKVp27
39.45 KB
Del
OK
phplMiTRR
40 KB
Del
OK
phplP8wqZ
8 KB
Del
OK
phplQiPyR
129 B
Del
OK
phplRnWV6
67 B
Del
OK
phplS2mOo
64 B
Del
OK
phplTUtFr
8 KB
Del
OK
phplUyKpI
512 B
Del
OK
phplalkBE
1.5 KB
Del
OK
phplciJTA
40 KB
Del
OK
phplhP5td
4 KB
Del
OK
phpljUoKz
0 B
Del
OK
phplr7kRE
0 B
Del
OK
phplt90Ff
5.36 MB
Del
OK
phplwetyi
1.5 KB
Del
OK
phpm3hQ8i
40 KB
Del
OK
phpm67AyA
0 B
Del
OK
phpm7sgqh
0 B
Del
OK
phpmKBeV3
61.87 KB
Del
OK
phpmPKW7t
15.16 KB
Del
OK
phpmRxoDq
6.74 KB
Del
OK
phpmXF0nI
8 KB
Del
OK
phpmii2Qv
266 B
Del
OK
phpmtNkhk
46 B
Del
OK
phpn0KERe
33.19 KB
Del
OK
phpnGhZTW
23.36 KB
Del
OK
phpnJxoB0
0 B
Del
OK
phpnLgdch
40 KB
Del
OK
phpnLqiuK
1.5 KB
Del
OK
phpnPRxAg
14.01 MB
Del
OK
phpnRlY1k
0 B
Del
OK
phpnWOYI3
40 KB
Del
OK
phpnXEcU7
40 KB
Del
OK
phpnYgZws
52.59 MB
Del
OK
phpnbGptv
16 KB
Del
OK
phpncQ2lW
0 B
Del
OK
phpnffb3O
9.69 KB
Del
OK
phpnkxTd4
7.53 MB
Del
OK
phpnpHj7c
79.37 MB
Del
OK
phpnvPx79
162 B
Del
OK
phpnzicFK
32 KB
Del
OK
phpnzqyBv
8.5 KB
Del
OK
phpo3OGCH
5.93 MB
Del
OK
phpoI2dNd
35.48 KB
Del
OK
phpoJp8Jr
7.83 MB
Del
OK
phpoLhlOX
52 B
Del
OK
phpoRy30v
8.5 KB
Del
OK
phpoSZgNd
0 B
Del
OK
phpoXKcu6
40 KB
Del
OK
phpoimKGx
8.5 KB
Del
OK
phpoj99Bi
79.36 MB
Del
OK
phpolwAOx
694.37 KB
Del
OK
phpono4UD
222 B
Del
OK
phposjthu
77 B
Del
OK
phpovOR2P
8 KB
Del
OK
phpoxb2nH
1.52 MB
Del
OK
phpoy6Ob9
56.59 MB
Del
OK
phpp39IOE
25 KB
Del
OK
phpp47nX4
54 B
Del
OK
phpp4gRCD
368.5 KB
Del
OK
phpp4iiSN
80 KB
Del
OK
phpp6jmCv
6.5 KB
Del
OK
phppB6r7a
0 B
Del
OK
phppDnHzK
135 B
Del
OK
phppSsywW
5.32 KB
Del
OK
phppUOCLf
4.5 KB
Del
OK
phppZzdTj
40 KB
Del
OK
phppaFlqz
80 KB
Del
OK
phppdTWhO
26.06 KB
Del
OK
phppg3B26
63.13 MB
Del
OK
phppgoRqc
40 KB
Del
OK
phpplyETU
0 B
Del
OK
phppm69I3
40 KB
Del
OK
phppoPat9
0 B
Del
OK
phpptqmD6
40 KB
Del
OK
phppxvaUX
40 KB
Del
OK
phpq19HYj
8.5 KB
Del
OK
phpq2kqG9
31.35 KB
Del
OK
phpq54Smx
32 KB
Del
OK
phpq9gYkv
55.45 MB
Del
OK
phpqCACNH
580 B
Del
OK
phpqD4T6N
24.5 KB
Del
OK
phpqFhFbL
32 KB
Del
OK
phpqNWHwo
40 KB
Del
OK
phpqROH9B
6.39 MB
Del
OK
phpqSlPp4
21 KB
Del
OK
phpqSn0xY
26.43 KB
Del
OK
phpqUsSUT
2.69 KB
Del
OK
phpqcQc53
165 B
Del
OK
phpqletcD
469.62 KB
Del
OK
phpqmG0L0
2.32 MB
Del
OK
phpqzlIJf
35.48 KB
Del
OK
phpr0P3XI
80 KB
Del
OK
phpr0neyA
40 KB
Del
OK
phpr1n3Lh
24 KB
Del
OK
phpr5SCZB
16 KB
Del
OK
phprCqXBR
80 KB
Del
OK
phprRKOPb
8.5 KB
Del
OK
phprS1dAg
15.6 KB
Del
OK
phprSgxPF
48.5 KB
Del
OK
phprb4Ry4
16 KB
Del
OK
phpre5pbg
1.15 KB
Del
OK
phpredY18
1.5 KB
Del
OK
phprevaHK
4.86 MB
Del
OK
phprgmaB1
31.22 KB
Del
OK
phprkPp3A
152.78 KB
Del
OK
phprl7Jmz
32 KB
Del
OK
phpruvaJy
0 B
Del
OK
phprywRTa
46.37 MB
Del
OK
phpsACbgB
51 B
Del
OK
phpsDoJoH
40 KB
Del
OK
phpsOofec
34.7 MB
Del
OK
phpsabB4B
4.98 MB
Del
OK
phpsb6vUN
40 KB
Del
OK
phpsePHI3
722 B
Del
OK
phpsnB3gT
48.5 KB
Del
OK
phpspweSN
40 KB
Del
OK
phpt5NAX5
27.9 KB
Del
OK
phpt5jKdZ
0 B
Del
OK
phpt8Pe3G
80 KB
Del
OK
phpt9a4Yp
16 KB
Del
OK
phptCMN6u
31.42 KB
Del
OK
phptFvC48
40 KB
Del
OK
phptGLQau
0 B
Del
OK
phptIKtPV
0 B
Del
OK
phptJjtkO
0 B
Del
OK
phptKNNfU
1.5 KB
Del
OK
phptM3Ewp
8 KB
Del
OK
phptM65gy
27.34 KB
Del
OK
phptO3Xkx
39.45 KB
Del
OK
phptP4mxd
27.86 KB
Del
OK
phptdEPU4
0 B
Del
OK
phptiwifh
5 KB
Del
OK
phptlWVMF
1.44 KB
Del
OK
phptm4uK2
40 KB
Del
OK
phptnH4s5
1011.37 KB
Del
OK
phpts8ooi
79.34 MB
Del
OK
phptt5q0h
40 KB
Del
OK
phptz5Vsv
15.61 KB
Del
OK
phptz9K14
65.68 KB
Del
OK
phptzo7sN
32 KB
Del
OK
phpu2JMGP
16.05 KB
Del
OK
phpu9iy3b
430 B
Del
OK
phpuBX1Jg
40 KB
Del
OK
phpuCHc7E
2.92 MB
Del
OK
phpuUcNRf
2.5 KB
Del
OK
phpuYE689
40 KB
Del
OK
phpugvt5l
832.5 KB
Del
OK
phpulCaOg
2.83 KB
Del
OK
phpuoi2eA
224 KB
Del
OK
phpuuunak
50 B
Del
OK
phpuwDW34
43.67 KB
Del
OK
phpv4O7T2
13 KB
Del
OK
phpvFJDCv
15.09 KB
Del
OK
phpvMqdFd
54.36 MB
Del
OK
phpvNfHa6
1.5 KB
Del
OK
phpvPT7Nq
16 KB
Del
OK
phpvQmG9E
71.57 KB
Del
OK
phpvRVIHc
11.24 KB
Del
OK
phpvT43gH
40 KB
Del
OK
phpvTfq4V
64 KB
Del
OK
phpvUbcmd
56 KB
Del
OK
phpvV0J0b
6.74 KB
Del
OK
phpvcPFS8
21.05 KB
Del
OK
phpvcXPH5
32 KB
Del
OK
phpvhAcXC
29.83 KB
Del
OK
phpvi3rcc
40 KB
Del
OK
phpvocBoC
210.23 KB
Del
OK
phpvpeSbE
24 KB
Del
OK
phpvxELdf
0 B
Del
OK
phpw1JqfM
8.21 MB
Del
OK
phpw1xogN
410 KB
Del
OK
phpw4naIK
1.92 MB
Del
OK
phpw5ibSY
40 KB
Del
OK
phpwEhgp5
823.55 KB
Del
OK
phpwJX3Gh
5.54 KB
Del
OK
phpwNvgTu
14 MB
Del
OK
phpwY4ZlH
4.03 KB
Del
OK
phpwaGX75
2.55 MB
Del
OK
phpwaMb08
1024 B
Del
OK
phpwehmf3
15.64 KB
Del
OK
phpwgMHS9
3.4 KB
Del
OK
phpwju2I5
17.19 KB
Del
OK
phpwkCma7
88.45 KB
Del
OK
phpwmbE67
512 B
Del
OK
phpwqd1ED
23.21 KB
Del
OK
phpwwzZK5
27.39 KB
Del
OK
phpwypbbE
4.28 MB
Del
OK
phpx4jyaG
32.05 KB
Del
OK
phpx5jBHz
40 KB
Del
OK
phpxExLkI
40 KB
Del
OK
phpxFdJMN
4.25 KB
Del
OK
phpxJK7C8
6.07 MB
Del
OK
phpxK3sCR
40 KB
Del
OK
phpxOoq6n
1.5 KB
Del
OK
phpxSKAat
216 KB
Del
OK
phpxTumNQ
891.16 KB
Del
OK
phpxXxlqt
54 B
Del
OK
phpxZUylL
40 KB
Del
OK
phpxagDhl
0 B
Del
OK
phpxcaeQ6
1.82 MB
Del
OK
phpxfnKDK
40 KB
Del
OK
phpxt02IE
16.41 KB
Del
OK
phpxvbXmn
16 KB
Del
OK
phpxwxlYr
40 KB
Del
OK
phpxz0f4k
53.95 KB
Del
OK
phpxzXqnd
4.03 MB
Del
OK
phpy1moZ2
39.58 KB
Del
OK
phpyBU4RH
3.08 MB
Del
OK
phpyD9NhX
19.16 KB
Del
OK
phpyJUNnX
78.07 MB
Del
OK
phpyKv2dV
1.5 KB
Del
OK
phpyOD5DC
32.04 KB
Del
OK
phpyTG8N1
80 KB
Del
OK
phpyXmuzz
40 KB
Del
OK
phpydox08
342.27 KB
Del
OK
phpyi2Wbr
0 B
Del
OK
phpyjqnUL
5.65 KB
Del
OK
phpykOCTi
7.33 MB
Del
OK
phpyoWBQ2
2.35 MB
Del
OK
phpytJwhd
31.47 KB
Del
OK
phpz1oBMs
39.45 KB
Del
OK
phpz2vOfd
1.5 KB
Del
OK
phpz32Tc7
0 B
Del
OK
phpz7GIMi
6.65 KB
Del
OK
phpz8iHJF
3.95 MB
Del
OK
phpzEFhj1
3 KB
Del
OK
phpzFuO8j
40 KB
Del
OK
phpzHAI5M
1.13 MB
Del
OK
phpzR182L
512 B
Del
OK
phpzSArE5
0 B
Del
OK
phpzTbpgh
40 KB
Del
OK
phpzVTEjg
5.5 KB
Del
OK
phpzgHEVL
44.13 KB
Del
OK
phpzi2xYj
40 KB
Del
OK
phpzn0Y1e
40 KB
Del
OK
phpznw4rp
8 KB
Del
OK
phpzokr9D
46 B
Del
OK
phpzpJJ6I
760 B
Del
OK
phpzqPqGK
20 KB
Del
OK
phpzqyFpM
4.07 KB
Del
OK
phpzzTHtu
0 B
Del
OK
phpzzaGsJ
111.09 KB
Del
OK
phpzzrYWF
0 B
Del
OK
system_log.txt
282 B
Del
OK
www.seshaasschool.com.588275.tmp
34.55 KB
Del
OK
Edit: phpqletcD
# frozen_string_literal: true require_relative 'psych/versions' case RUBY_ENGINE when 'jruby' require_relative 'psych_jars' if JRuby::Util.respond_to?(:load_ext) JRuby::Util.load_ext('org.jruby.ext.psych.PsychLibrary') else require 'java'; require 'jruby' org.jruby.ext.psych.PsychLibrary.new.load(JRuby.runtime, false) end else require 'psych.so' end require_relative 'psych/nodes' require_relative 'psych/streaming' require_relative 'psych/visitors' require_relative 'psych/handler' require_relative 'psych/tree_builder' require_relative 'psych/parser' require_relative 'psych/omap' require_relative 'psych/set' require_relative 'psych/coder' require_relative 'psych/core_ext' require_relative 'psych/stream' require_relative 'psych/json/tree_builder' require_relative 'psych/json/stream' require_relative 'psych/handlers/document_stream' require_relative 'psych/class_loader' ### # = Overview # # Psych is a YAML parser and emitter. # Psych leverages libyaml [Home page: https://pyyaml.org/wiki/LibYAML] # or [git repo: https://github.com/yaml/libyaml] for its YAML parsing # and emitting capabilities. In addition to wrapping libyaml, Psych also # knows how to serialize and de-serialize most Ruby objects to and from # the YAML format. # # = I NEED TO PARSE OR EMIT YAML RIGHT NOW! # # # Parse some YAML # Psych.load("--- foo") # => "foo" # # # Emit some YAML # Psych.dump("foo") # => "--- foo\n...\n" # { :a => 'b'}.to_yaml # => "---\n:a: b\n" # # Got more time on your hands? Keep on reading! # # == YAML Parsing # # Psych provides a range of interfaces for parsing a YAML document ranging from # low level to high level, depending on your parsing needs. At the lowest # level, is an event based parser. Mid level is access to the raw YAML AST, # and at the highest level is the ability to unmarshal YAML to Ruby objects. # # == YAML Emitting # # Psych provides a range of interfaces ranging from low to high level for # producing YAML documents. Very similar to the YAML parsing interfaces, Psych # provides at the lowest level, an event based system, mid-level is building # a YAML AST, and the highest level is converting a Ruby object straight to # a YAML document. # # == High-level API # # === Parsing # # The high level YAML parser provided by Psych simply takes YAML as input and # returns a Ruby data structure. For information on using the high level parser # see Psych.load # # ==== Reading from a string # # Psych.safe_load("--- a") # => 'a' # Psych.safe_load("---\n - a\n - b") # => ['a', 'b'] # # From a trusted string: # Psych.load("--- !ruby/range\nbegin: 0\nend: 42\nexcl: false\n") # => 0..42 # # ==== Reading from a file # # Psych.safe_load_file("data.yml", permitted_classes: [Date]) # Psych.load_file("trusted_database.yml") # # ==== Exception handling # # begin # # The second argument changes only the exception contents # Psych.parse("--- `", "file.txt") # rescue Psych::SyntaxError => ex # ex.file # => 'file.txt' # ex.message # => "(file.txt): found character that cannot start any token" # end # # === Emitting # # The high level emitter has the easiest interface. Psych simply takes a Ruby # data structure and converts it to a YAML document. See Psych.dump for more # information on dumping a Ruby data structure. # # ==== Writing to a string # # # Dump an array, get back a YAML string # Psych.dump(['a', 'b']) # => "---\n- a\n- b\n" # # # Dump an array to an IO object # Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890> # # # Dump an array with indentation set # Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n" # # # Dump an array to an IO with indentation set # Psych.dump(['a', ['b']], StringIO.new, :indentation => 3) # # ==== Writing to a file # # Currently there is no direct API for dumping Ruby structure to file: # # File.open('database.yml', 'w') do |file| # file.write(Psych.dump(['a', 'b'])) # end # # == Mid-level API # # === Parsing # # Psych provides access to an AST produced from parsing a YAML document. This # tree is built using the Psych::Parser and Psych::TreeBuilder. The AST can # be examined and manipulated freely. Please see Psych::parse_stream, # Psych::Nodes, and Psych::Nodes::Node for more information on dealing with # YAML syntax trees. # # ==== Reading from a string # # # Returns Psych::Nodes::Stream # Psych.parse_stream("---\n - a\n - b") # # # Returns Psych::Nodes::Document # Psych.parse("---\n - a\n - b") # # ==== Reading from a file # # # Returns Psych::Nodes::Stream # Psych.parse_stream(File.read('database.yml')) # # # Returns Psych::Nodes::Document # Psych.parse_file('database.yml') # # ==== Exception handling # # begin # # The second argument changes only the exception contents # Psych.parse("--- `", "file.txt") # rescue Psych::SyntaxError => ex # ex.file # => 'file.txt' # ex.message # => "(file.txt): found character that cannot start any token" # end # # === Emitting # # At the mid level is building an AST. This AST is exactly the same as the AST # used when parsing a YAML document. Users can build an AST by hand and the # AST knows how to emit itself as a YAML document. See Psych::Nodes, # Psych::Nodes::Node, and Psych::TreeBuilder for more information on building # a YAML AST. # # ==== Writing to a string # # # We need Psych::Nodes::Stream (not Psych::Nodes::Document) # stream = Psych.parse_stream("---\n - a\n - b") # # stream.to_yaml # => "---\n- a\n- b\n" # # ==== Writing to a file # # # We need Psych::Nodes::Stream (not Psych::Nodes::Document) # stream = Psych.parse_stream(File.read('database.yml')) # # File.open('database.yml', 'w') do |file| # file.write(stream.to_yaml) # end # # == Low-level API # # === Parsing # # The lowest level parser should be used when the YAML input is already known, # and the developer does not want to pay the price of building an AST or # automatic detection and conversion to Ruby objects. See Psych::Parser for # more information on using the event based parser. # # ==== Reading to Psych::Nodes::Stream structure # # parser = Psych::Parser.new(TreeBuilder.new) # => #<Psych::Parser> # parser = Psych.parser # it's an alias for the above # # parser.parse("---\n - a\n - b") # => #<Psych::Parser> # parser.handler # => #<Psych::TreeBuilder> # parser.handler.root # => #<Psych::Nodes::Stream> # # ==== Receiving an events stream # # recorder = Psych::Handlers::Recorder.new # parser = Psych::Parser.new(recorder) # # parser.parse("---\n - a\n - b") # recorder.events # => [list of [event, args] lists] # # event is one of: Psych::Handler::EVENTS # # args are the arguments passed to the event # # === Emitting # # The lowest level emitter is an event based system. Events are sent to a # Psych::Emitter object. That object knows how to convert the events to a YAML # document. This interface should be used when document format is known in # advance or speed is a concern. See Psych::Emitter for more information. # # ==== Writing to a Ruby structure # # Psych.parser.parse("--- a") # => #<Psych::Parser> # # parser.handler.first # => #<Psych::Nodes::Stream> # parser.handler.first.to_ruby # => ["a"] # # parser.handler.root.first # => #<Psych::Nodes::Document> # parser.handler.root.first.to_ruby # => "a" # # # You can instantiate an Emitter manually # Psych::Visitors::ToRuby.new.accept(parser.handler.root.first) # # => "a" module Psych # The version of libyaml Psych is using LIBYAML_VERSION = Psych.libyaml_version.join('.').freeze ### # Load +yaml+ in to a Ruby data structure. If multiple documents are # provided, the object contained in the first document will be returned. # +filename+ will be used in the exception message if any exception # is raised while parsing. If +yaml+ is empty, it returns # the specified +fallback+ return value, which defaults to +false+. # # Raises a Psych::SyntaxError when a YAML syntax error is detected. # # Example: # # Psych.unsafe_load("--- a") # => 'a' # Psych.unsafe_load("---\n - a\n - b") # => ['a', 'b'] # # begin # Psych.unsafe_load("--- `", filename: "file.txt") # rescue Psych::SyntaxError => ex # ex.file # => 'file.txt' # ex.message # => "(file.txt): found character that cannot start any token" # end # # When the optional +symbolize_names+ keyword argument is set to a # true value, returns symbols for keys in Hash objects (default: strings). # # Psych.unsafe_load("---\n foo: bar") # => {"foo"=>"bar"} # Psych.unsafe_load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"} # # Raises a TypeError when `yaml` parameter is NilClass # # NOTE: This method *should not* be used to parse untrusted documents, such as # YAML documents that are supplied via user input. Instead, please use the # load method or the safe_load method. # def self.unsafe_load yaml, filename: nil, fallback: false, symbolize_names: false, freeze: false, strict_integer: false result = parse(yaml, filename: filename) return fallback unless result result.to_ruby(symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer) end ### # Safely load the yaml string in +yaml+. By default, only the following # classes are allowed to be deserialized: # # * TrueClass # * FalseClass # * NilClass # * Integer # * Float # * String # * Array # * Hash # # Recursive data structures are not allowed by default. Arbitrary classes # can be allowed by adding those classes to the +permitted_classes+ keyword argument. They are # additive. For example, to allow Date deserialization: # # Psych.safe_load(yaml, permitted_classes: [Date]) # # Now the Date class can be loaded in addition to the classes listed above. # # Aliases can be explicitly allowed by changing the +aliases+ keyword argument. # For example: # # x = [] # x << x # yaml = Psych.dump x # Psych.safe_load yaml # => raises an exception # Psych.safe_load yaml, aliases: true # => loads the aliases # # A Psych::DisallowedClass exception will be raised if the yaml contains a # class that isn't in the +permitted_classes+ list. # # A Psych::AliasesNotEnabled exception will be raised if the yaml contains aliases # but the +aliases+ keyword argument is set to false. # # +filename+ will be used in the exception message if any exception is raised # while parsing. # # When the optional +symbolize_names+ keyword argument is set to a # true value, returns symbols for keys in Hash objects (default: strings). # # Psych.safe_load("---\n foo: bar") # => {"foo"=>"bar"} # Psych.safe_load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"} # def self.safe_load yaml, permitted_classes: [], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false, strict_integer: false result = parse(yaml, filename: filename) return fallback unless result class_loader = ClassLoader::Restricted.new(permitted_classes.map(&:to_s), permitted_symbols.map(&:to_s)) scanner = ScalarScanner.new class_loader, strict_integer: strict_integer visitor = if aliases Visitors::ToRuby.new scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze else Visitors::NoAliasRuby.new scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze end result = visitor.accept result result end ### # Load +yaml+ in to a Ruby data structure. If multiple documents are # provided, the object contained in the first document will be returned. # +filename+ will be used in the exception message if any exception # is raised while parsing. If +yaml+ is empty, it returns # the specified +fallback+ return value, which defaults to +false+. # # Raises a Psych::SyntaxError when a YAML syntax error is detected. # # Example: # # Psych.load("--- a") # => 'a' # Psych.load("---\n - a\n - b") # => ['a', 'b'] # # begin # Psych.load("--- `", filename: "file.txt") # rescue Psych::SyntaxError => ex # ex.file # => 'file.txt' # ex.message # => "(file.txt): found character that cannot start any token" # end # # When the optional +symbolize_names+ keyword argument is set to a # true value, returns symbols for keys in Hash objects (default: strings). # # Psych.load("---\n foo: bar") # => {"foo"=>"bar"} # Psych.load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"} # # Raises a TypeError when `yaml` parameter is NilClass. This method is # similar to `safe_load` except that `Symbol` objects are allowed by default. # def self.load yaml, permitted_classes: [Symbol], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false, strict_integer: false safe_load yaml, permitted_classes: permitted_classes, permitted_symbols: permitted_symbols, aliases: aliases, filename: filename, fallback: fallback, symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer end ### # Parse a YAML string in +yaml+. Returns the Psych::Nodes::Document. # +filename+ is used in the exception message if a Psych::SyntaxError is # raised. # # Raises a Psych::SyntaxError when a YAML syntax error is detected. # # Example: # # Psych.parse("---\n - a\n - b") # => #<Psych::Nodes::Document:0x00> # # begin # Psych.parse("--- `", filename: "file.txt") # rescue Psych::SyntaxError => ex # ex.file # => 'file.txt' # ex.message # => "(file.txt): found character that cannot start any token" # end # # See Psych::Nodes for more information about YAML AST. def self.parse yaml, filename: nil parse_stream(yaml, filename: filename) do |node| return node end false end ### # Parse a file at +filename+. Returns the Psych::Nodes::Document. # # Raises a Psych::SyntaxError when a YAML syntax error is detected. def self.parse_file filename, fallback: false result = File.open filename, 'r:bom|utf-8' do |f| parse f, filename: filename end result || fallback end ### # Returns a default parser def self.parser Psych::Parser.new(TreeBuilder.new) end ### # Parse a YAML string in +yaml+. Returns the Psych::Nodes::Stream. # This method can handle multiple YAML documents contained in +yaml+. # +filename+ is used in the exception message if a Psych::SyntaxError is # raised. # # If a block is given, a Psych::Nodes::Document node will be yielded to the # block as it's being parsed. # # Raises a Psych::SyntaxError when a YAML syntax error is detected. # # Example: # # Psych.parse_stream("---\n - a\n - b") # => #<Psych::Nodes::Stream:0x00> # # Psych.parse_stream("--- a\n--- b") do |node| # node # => #<Psych::Nodes::Document:0x00> # end # # begin # Psych.parse_stream("--- `", filename: "file.txt") # rescue Psych::SyntaxError => ex # ex.file # => 'file.txt' # ex.message # => "(file.txt): found character that cannot start any token" # end # # Raises a TypeError when NilClass is passed. # # See Psych::Nodes for more information about YAML AST. def self.parse_stream yaml, filename: nil, &block if block_given? parser = Psych::Parser.new(Handlers::DocumentStream.new(&block)) parser.parse yaml, filename else parser = self.parser parser.parse yaml, filename parser.handler.root end end ### # call-seq: # Psych.dump(o) -> string of yaml # Psych.dump(o, options) -> string of yaml # Psych.dump(o, io) -> io object passed in # Psych.dump(o, io, options) -> io object passed in # # Dump Ruby object +o+ to a YAML string. Optional +options+ may be passed in # to control the output format. If an IO object is passed in, the YAML will # be dumped to that IO object. # # Currently supported options are: # # [<tt>:indentation</tt>] Number of space characters used to indent. # Acceptable value should be in <tt>0..9</tt> range, # otherwise option is ignored. # # Default: <tt>2</tt>. # [<tt>:line_width</tt>] Max character to wrap line at. # # Default: <tt>0</tt> (meaning "wrap at 81"). # [<tt>:canonical</tt>] Write "canonical" YAML form (very verbose, yet # strictly formal). # # Default: <tt>false</tt>. # [<tt>:header</tt>] Write <tt>%YAML [version]</tt> at the beginning of document. # # Default: <tt>false</tt>. # # Example: # # # Dump an array, get back a YAML string # Psych.dump(['a', 'b']) # => "---\n- a\n- b\n" # # # Dump an array to an IO object # Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890> # # # Dump an array with indentation set # Psych.dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n" # # # Dump an array to an IO with indentation set # Psych.dump(['a', ['b']], StringIO.new, indentation: 3) def self.dump o, io = nil, options = {} if Hash === io options = io io = nil end visitor = Psych::Visitors::YAMLTree.create options visitor << o visitor.tree.yaml io, options end ### # call-seq: # Psych.safe_dump(o) -> string of yaml # Psych.safe_dump(o, options) -> string of yaml # Psych.safe_dump(o, io) -> io object passed in # Psych.safe_dump(o, io, options) -> io object passed in # # Safely dump Ruby object +o+ to a YAML string. Optional +options+ may be passed in # to control the output format. If an IO object is passed in, the YAML will # be dumped to that IO object. By default, only the following # classes are allowed to be serialized: # # * TrueClass # * FalseClass # * NilClass # * Integer # * Float # * String # * Array # * Hash # # Arbitrary classes can be allowed by adding those classes to the +permitted_classes+ # keyword argument. They are additive. For example, to allow Date serialization: # # Psych.safe_dump(yaml, permitted_classes: [Date]) # # Now the Date class can be dumped in addition to the classes listed above. # # A Psych::DisallowedClass exception will be raised if the object contains a # class that isn't in the +permitted_classes+ list. # # Currently supported options are: # # [<tt>:indentation</tt>] Number of space characters used to indent. # Acceptable value should be in <tt>0..9</tt> range, # otherwise option is ignored. # # Default: <tt>2</tt>. # [<tt>:line_width</tt>] Max character to wrap line at. # # Default: <tt>0</tt> (meaning "wrap at 81"). # [<tt>:canonical</tt>] Write "canonical" YAML form (very verbose, yet # strictly formal). # # Default: <tt>false</tt>. # [<tt>:header</tt>] Write <tt>%YAML [version]</tt> at the beginning of document. # # Default: <tt>false</tt>. # # Example: # # # Dump an array, get back a YAML string # Psych.safe_dump(['a', 'b']) # => "---\n- a\n- b\n" # # # Dump an array to an IO object # Psych.safe_dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890> # # # Dump an array with indentation set # Psych.safe_dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n" # # # Dump an array to an IO with indentation set # Psych.safe_dump(['a', ['b']], StringIO.new, indentation: 3) def self.safe_dump o, io = nil, options = {} if Hash === io options = io io = nil end visitor = Psych::Visitors::RestrictedYAMLTree.create options visitor << o visitor.tree.yaml io, options end ### # Dump a list of objects as separate documents to a document stream. # # Example: # # Psych.dump_stream("foo\n ", {}) # => "--- ! \"foo\\n \"\n--- {}\n" def self.dump_stream *objects visitor = Psych::Visitors::YAMLTree.create({}) objects.each do |o| visitor << o end visitor.tree.yaml end ### # Dump Ruby +object+ to a JSON string. def self.to_json object visitor = Psych::Visitors::JSONTree.create visitor << object visitor.tree.yaml end ### # Load multiple documents given in +yaml+. Returns the parsed documents # as a list. If a block is given, each document will be converted to Ruby # and passed to the block during parsing # # Example: # # Psych.load_stream("--- foo\n...\n--- bar\n...") # => ['foo', 'bar'] # # list = [] # Psych.load_stream("--- foo\n...\n--- bar\n...") do |ruby| # list << ruby # end # list # => ['foo', 'bar'] # def self.load_stream yaml, filename: nil, fallback: [], **kwargs result = if block_given? parse_stream(yaml, filename: filename) do |node| yield node.to_ruby(**kwargs) end else parse_stream(yaml, filename: filename).children.map { |node| node.to_ruby(**kwargs) } end return fallback if result.is_a?(Array) && result.empty? result end ### # Load the document contained in +filename+. Returns the yaml contained in # +filename+ as a Ruby object, or if the file is empty, it returns # the specified +fallback+ return value, which defaults to +false+. # # NOTE: This method *should not* be used to parse untrusted documents, such as # YAML documents that are supplied via user input. Instead, please use the # safe_load_file method. def self.unsafe_load_file filename, **kwargs File.open(filename, 'r:bom|utf-8') { |f| self.unsafe_load f, filename: filename, **kwargs } end ### # Safely loads the document contained in +filename+. Returns the yaml contained in # +filename+ as a Ruby object, or if the file is empty, it returns # the specified +fallback+ return value, which defaults to +false+. # See safe_load for options. def self.safe_load_file filename, **kwargs File.open(filename, 'r:bom|utf-8') { |f| self.safe_load f, filename: filename, **kwargs } end ### # Loads the document contained in +filename+. Returns the yaml contained in # +filename+ as a Ruby object, or if the file is empty, it returns # the specified +fallback+ return value, which defaults to +false+. # See load for options. def self.load_file filename, **kwargs File.open(filename, 'r:bom|utf-8') { |f| self.load f, filename: filename, **kwargs } end # :stopdoc: def self.add_domain_type domain, type_tag, &block key = ['tag', domain, type_tag].join ':' domain_types[key] = [key, block] domain_types["tag:#{type_tag}"] = [key, block] end def self.add_builtin_type type_tag, &block domain = 'yaml.org,2002' key = ['tag', domain, type_tag].join ':' domain_types[key] = [key, block] end def self.remove_type type_tag domain_types.delete type_tag end def self.add_tag tag, klass load_tags[tag] = klass.name dump_tags[klass] = tag end class << self if defined?(Ractor) class Config attr_accessor :load_tags, :dump_tags, :domain_types def initialize @load_tags = {} @dump_tags = {} @domain_types = {} end end def config Ractor.current[:PsychConfig] ||= Config.new end def load_tags config.load_tags end def dump_tags config.dump_tags end def domain_types config.domain_types end def load_tags=(value) config.load_tags = value end def dump_tags=(value) config.dump_tags = value end def domain_types=(value) config.domain_types = value end else attr_accessor :load_tags attr_accessor :dump_tags attr_accessor :domain_types end end self.load_tags = {} self.dump_tags = {} self.domain_types = {} # :startdoc: end # frozen_string_literal: true require_relative 'nodes/node' require_relative 'nodes/stream' require_relative 'nodes/document' require_relative 'nodes/sequence' require_relative 'nodes/scalar' require_relative 'nodes/mapping' require_relative 'nodes/alias' module Psych ### # = Overview # # When using Psych.load to deserialize a YAML document, the document is # translated to an intermediary AST. That intermediary AST is then # translated in to a Ruby object graph. # # In the opposite direction, when using Psych.dump, the Ruby object graph is # translated to an intermediary AST which is then converted to a YAML # document. # # Psych::Nodes contains all of the classes that make up the nodes of a YAML # AST. You can manually build an AST and use one of the visitors (see # Psych::Visitors) to convert that AST to either a YAML document or to a # Ruby object graph. # # Here is an example of building an AST that represents a list with one # scalar: # # # Create our nodes # stream = Psych::Nodes::Stream.new # doc = Psych::Nodes::Document.new # seq = Psych::Nodes::Sequence.new # scalar = Psych::Nodes::Scalar.new('foo') # # # Build up our tree # stream.children << doc # doc.children << seq # seq.children << scalar # # The stream is the root of the tree. We can then convert the tree to YAML: # # stream.to_yaml => "---\n- foo\n" # # Or convert it to Ruby: # # stream.to_ruby => [["foo"]] # # == YAML AST Requirements # # A valid YAML AST *must* have one Psych::Nodes::Stream at the root. A # Psych::Nodes::Stream node must have 1 or more Psych::Nodes::Document nodes # as children. # # Psych::Nodes::Document nodes must have one and *only* one child. That child # may be one of: # # * Psych::Nodes::Sequence # * Psych::Nodes::Mapping # * Psych::Nodes::Scalar # # Psych::Nodes::Sequence and Psych::Nodes::Mapping nodes may have many # children, but Psych::Nodes::Mapping nodes should have an even number of # children. # # All of these are valid children for Psych::Nodes::Sequence and # Psych::Nodes::Mapping nodes: # # * Psych::Nodes::Sequence # * Psych::Nodes::Mapping # * Psych::Nodes::Scalar # * Psych::Nodes::Alias # # Psych::Nodes::Scalar and Psych::Nodes::Alias are both terminal nodes and # should not have any children. module Nodes end end # frozen_string_literal: true module Psych ### # Scan scalars for built in types class ScalarScanner # Taken from http://yaml.org/type/timestamp.html TIME = /^-?\d{4}-\d{1,2}-\d{1,2}(?:[Tt]|\s+)\d{1,2}:\d\d:\d\d(?:\.\d*)?(?:\s*(?:Z|[-+]\d{1,2}:?(?:\d\d)?))?$/ # Taken from http://yaml.org/type/float.html # Base 60, [-+]inf and NaN are handled separately FLOAT = /^(?:[-+]?([0-9][0-9_,]*)?\.[0-9]*([eE][-+][0-9]+)?(?# base 10))$/x # Taken from http://yaml.org/type/int.html INTEGER_STRICT = /^(?:[-+]?0b[0-1_]+ (?# base 2) |[-+]?0[0-7_]+ (?# base 8) |[-+]?(0|[1-9][0-9_]*) (?# base 10) |[-+]?0x[0-9a-fA-F_]+ (?# base 16))$/x # Same as above, but allows commas. # Not to YML spec, but kept for backwards compatibility INTEGER_LEGACY = /^(?:[-+]?0b[0-1_,]+ (?# base 2) |[-+]?0[0-7_,]+ (?# base 8) |[-+]?(?:0|[1-9](?:[0-9]|,[0-9]|_[0-9])*) (?# base 10) |[-+]?0x[0-9a-fA-F_,]+ (?# base 16))$/x attr_reader :class_loader # Create a new scanner def initialize class_loader, strict_integer: false @symbol_cache = {} @class_loader = class_loader @strict_integer = strict_integer end # Tokenize +string+ returning the Ruby object def tokenize string return nil if string.empty? return @symbol_cache[string] if @symbol_cache.key?(string) integer_regex = @strict_integer ? INTEGER_STRICT : INTEGER_LEGACY # Check for a String type, being careful not to get caught by hash keys, hex values, and # special floats (e.g., -.inf). if string.match?(%r{^[^\d.:-]?[[:alpha:]_\s!@#$%\^&*(){}<>|/\\~;=]+}) || string.match?(/\n/) return string if string.length > 5 if string.match?(/^[^ytonf~]/i) string elsif string == '~' || string.match?(/^null$/i) nil elsif string.match?(/^(yes|true|on)$/i) true elsif string.match?(/^(no|false|off)$/i) false else string end elsif string.match?(TIME) begin parse_time string rescue ArgumentError string end elsif string.match?(/^\d{4}-(?:1[012]|0\d|\d)-(?:[12]\d|3[01]|0\d|\d)$/) require 'date' begin class_loader.date.strptime(string, '%F', Date::GREGORIAN) rescue ArgumentError string end elsif string.match?(/^\+?\.inf$/i) Float::INFINITY elsif string.match?(/^-\.inf$/i) -Float::INFINITY elsif string.match?(/^\.nan$/i) Float::NAN elsif string.match?(/^:./) if string =~ /^:(["'])(.*)\1/ @symbol_cache[string] = class_loader.symbolize($2.sub(/^:/, '')) else @symbol_cache[string] = class_loader.symbolize(string.sub(/^:/, '')) end elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}$/) i = 0 string.split(':').each_with_index do |n,e| i += (n.to_i * 60 ** (e - 2).abs) end i elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}\.[0-9_]*$/) i = 0 string.split(':').each_with_index do |n,e| i += (n.to_f * 60 ** (e - 2).abs) end i elsif string.match?(FLOAT) if string.match?(/\A[-+]?\.\Z/) string else Float(string.delete(',_').gsub(/\.([Ee]|$)/, '\1')) end elsif string.match?(integer_regex) parse_int string else string end end ### # Parse and return an int from +string+ def parse_int string Integer(string.delete(',_')) end ### # Parse and return a Time from +string+ def parse_time string klass = class_loader.load 'Time' date, time = *(string.split(/[ tT]/, 2)) (yy, m, dd) = date.match(/^(-?\d{4})-(\d{1,2})-(\d{1,2})/).captures.map { |x| x.to_i } md = time.match(/(\d+:\d+:\d+)(?:\.(\d*))?\s*(Z|[-+]\d+(:\d\d)?)?/) (hh, mm, ss) = md[1].split(':').map { |x| x.to_i } us = (md[2] ? Rational("0.#{md[2]}") : 0) * 1000000 time = klass.utc(yy, m, dd, hh, mm, ss, us) return time if 'Z' == md[3] return klass.at(time.to_i, us) unless md[3] tz = md[3].match(/^([+\-]?\d{1,2})\:?(\d{1,2})?$/)[1..-1].compact.map { |digit| Integer(digit, 10) } offset = tz.first * 3600 if offset < 0 offset -= ((tz[1] || 0) * 60) else offset += ((tz[1] || 0) * 60) end klass.new(yy, m, dd, hh, mm, ss+us/(1_000_000r), offset) end end end # frozen_string_literal: true module Psych class Set < ::Hash end end # frozen_string_literal: true require_relative 'omap' require_relative 'set' module Psych class ClassLoader # :nodoc: BIG_DECIMAL = 'BigDecimal' COMPLEX = 'Complex' DATE = 'Date' DATE_TIME = 'DateTime' EXCEPTION = 'Exception' OBJECT = 'Object' PSYCH_OMAP = 'Psych::Omap' PSYCH_SET = 'Psych::Set' RANGE = 'Range' RATIONAL = 'Rational' REGEXP = 'Regexp' STRUCT = 'Struct' SYMBOL = 'Symbol' def initialize @cache = CACHE.dup end def load klassname return nil if !klassname || klassname.empty? find klassname end def symbolize sym symbol sym.to_sym end constants.each do |const| konst = const_get const class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{const.to_s.downcase} load #{konst.inspect} end RUBY end private def find klassname @cache[klassname] ||= resolve(klassname) end def resolve klassname name = klassname retried = false begin path2class(name) rescue ArgumentError, NameError => ex unless retried name = "Struct::#{name}" retried = ex retry end raise retried end end CACHE = Hash[constants.map { |const| val = const_get const begin [val, ::Object.const_get(val)] rescue nil end }.compact].freeze class Restricted < ClassLoader def initialize classes, symbols @classes = classes @symbols = symbols super() end def symbolize sym return super if @symbols.empty? if @symbols.include? sym super else raise DisallowedClass.new('load', 'Symbol') end end private def find klassname if @classes.include? klassname super else raise DisallowedClass.new('load', klassname) end end end end end # frozen_string_literal: true require_relative 'handler' module Psych ### # This class works in conjunction with Psych::Parser to build an in-memory # parse tree that represents a YAML document. # # == Example # # parser = Psych::Parser.new Psych::TreeBuilder.new # parser.parse('--- foo') # tree = parser.handler.root # # See Psych::Handler for documentation on the event methods used in this # class. class TreeBuilder < Psych::Handler # Returns the root node for the built tree attr_reader :root # Create a new TreeBuilder instance def initialize @stack = [] @last = nil @root = nil @start_line = nil @start_column = nil @end_line = nil @end_column = nil end def event_location(start_line, start_column, end_line, end_column) @start_line = start_line @start_column = start_column @end_line = end_line @end_column = end_column end %w{ Sequence Mapping }.each do |node| class_eval <<~RUBY, __FILE__, __LINE__ + 1 def start_#{node.downcase}(anchor, tag, implicit, style) n = Nodes::#{node}.new(anchor, tag, implicit, style) set_start_location(n) @last.children << n push n end def end_#{node.downcase} n = pop set_end_location(n) n end RUBY end ### # Handles start_document events with +version+, +tag_directives+, # and +implicit+ styling. # # See Psych::Handler#start_document def start_document version, tag_directives, implicit n = Nodes::Document.new version, tag_directives, implicit set_start_location(n) @last.children << n push n end ### # Handles end_document events with +version+, +tag_directives+, # and +implicit+ styling. # # See Psych::Handler#start_document def end_document implicit_end = !streaming? @last.implicit_end = implicit_end n = pop set_end_location(n) n end def start_stream encoding @root = Nodes::Stream.new(encoding) set_start_location(@root) push @root end def end_stream n = pop set_end_location(n) n end def scalar value, anchor, tag, plain, quoted, style s = Nodes::Scalar.new(value,anchor,tag,plain,quoted,style) set_location(s) @last.children << s s end def alias anchor a = Nodes::Alias.new(anchor) set_location(a) @last.children << a a end private def push value @stack.push value @last = value end def pop x = @stack.pop @last = @stack.last x end def set_location(node) set_start_location(node) set_end_location(node) end def set_start_location(node) node.start_line = @start_line node.start_column = @start_column end def set_end_location(node) node.end_line = @end_line node.end_column = @end_column end end end # frozen_string_literal: true module Psych module Nodes ### # This class represents a {YAML Scalar}[http://yaml.org/spec/1.1/#id858081]. # # This node type is a terminal node and should not have any children. class Scalar < Psych::Nodes::Node # Any style scalar, the emitter chooses ANY = 0 # Plain scalar style PLAIN = 1 # Single quoted style SINGLE_QUOTED = 2 # Double quoted style DOUBLE_QUOTED = 3 # Literal style LITERAL = 4 # Folded style FOLDED = 5 # The scalar value attr_accessor :value # The anchor value (if there is one) attr_accessor :anchor # The tag value (if there is one) attr_accessor :tag # Is this a plain scalar? attr_accessor :plain # Is this scalar quoted? attr_accessor :quoted # The style of this scalar attr_accessor :style ### # Create a new Psych::Nodes::Scalar object. # # +value+ is the string value of the scalar # +anchor+ is an associated anchor or nil # +tag+ is an associated tag or nil # +plain+ is a boolean value # +quoted+ is a boolean value # +style+ is an integer indicating the string style # # == See Also # # See also Psych::Handler#scalar def initialize value, anchor = nil, tag = nil, plain = true, quoted = false, style = ANY @value = value @anchor = anchor @tag = tag @plain = plain @quoted = quoted @style = style end def scalar?; true; end end end end # frozen_string_literal: true module Psych module Nodes ### # This class represents a {YAML Alias}[http://yaml.org/spec/1.1/#alias]. # It points to an +anchor+. # # A Psych::Nodes::Alias is a terminal node and may have no children. class Alias < Psych::Nodes::Node # The anchor this alias links to attr_accessor :anchor # Create a new Alias that points to an +anchor+ def initialize anchor @anchor = anchor end def alias?; true; end end end end # frozen_string_literal: true module Psych module Nodes ### # This class represents a {YAML Mapping}[http://yaml.org/spec/1.1/#mapping]. # # A Psych::Nodes::Mapping node may have 0 or more children, but must have # an even number of children. Here are the valid children a # Psych::Nodes::Mapping node may have: # # * Psych::Nodes::Sequence # * Psych::Nodes::Mapping # * Psych::Nodes::Scalar # * Psych::Nodes::Alias class Mapping < Psych::Nodes::Node # Any Map Style ANY = 0 # Block Map Style BLOCK = 1 # Flow Map Style FLOW = 2 # The optional anchor for this mapping attr_accessor :anchor # The optional tag for this mapping attr_accessor :tag # Is this an implicit mapping? attr_accessor :implicit # The style of this mapping attr_accessor :style ### # Create a new Psych::Nodes::Mapping object. # # +anchor+ is the anchor associated with the map or +nil+. # +tag+ is the tag associated with the map or +nil+. # +implicit+ is a boolean indicating whether or not the map was implicitly # started. # +style+ is an integer indicating the mapping style. # # == See Also # See also Psych::Handler#start_mapping def initialize anchor = nil, tag = nil, implicit = true, style = BLOCK super() @anchor = anchor @tag = tag @implicit = implicit @style = style end def mapping?; true; end end end end # frozen_string_literal: true module Psych module Nodes ### # Represents a YAML stream. This is the root node for any YAML parse # tree. This node must have one or more child nodes. The only valid # child node for a Psych::Nodes::Stream node is Psych::Nodes::Document. class Stream < Psych::Nodes::Node # Encodings supported by Psych (and libyaml) # Any encoding ANY = Psych::Parser::ANY # UTF-8 encoding UTF8 = Psych::Parser::UTF8 # UTF-16LE encoding UTF16LE = Psych::Parser::UTF16LE # UTF-16BE encoding UTF16BE = Psych::Parser::UTF16BE # The encoding used for this stream attr_accessor :encoding ### # Create a new Psych::Nodes::Stream node with an +encoding+ that # defaults to Psych::Nodes::Stream::UTF8. # # See also Psych::Handler#start_stream def initialize encoding = UTF8 super() @encoding = encoding end def stream?; true; end end end end # frozen_string_literal: true require 'stringio' require_relative '../class_loader' require_relative '../scalar_scanner' module Psych module Nodes ### # The base class for any Node in a YAML parse tree. This class should # never be instantiated. class Node include Enumerable # The children of this node attr_reader :children # An associated tag attr_reader :tag # The line number where this node start attr_accessor :start_line # The column number where this node start attr_accessor :start_column # The line number where this node ends attr_accessor :end_line # The column number where this node ends attr_accessor :end_column # Create a new Psych::Nodes::Node def initialize @children = [] end ### # Iterate over each node in the tree. Yields each node to +block+ depth # first. def each &block return enum_for :each unless block_given? Visitors::DepthFirst.new(block).accept self end ### # Convert this node to Ruby. # # See also Psych::Visitors::ToRuby def to_ruby(symbolize_names: false, freeze: false, strict_integer: false) Visitors::ToRuby.create(symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer).accept(self) end alias :transform :to_ruby ### # Convert this node to YAML. # # See also Psych::Visitors::Emitter def yaml io = nil, options = {} real_io = io || StringIO.new(''.encode('utf-8')) Visitors::Emitter.new(real_io, options).accept self return real_io.string unless io io end alias :to_yaml :yaml def alias?; false; end def document?; false; end def mapping?; false; end def scalar?; false; end def sequence?; false; end def stream?; false; end end end end # frozen_string_literal: true module Psych module Nodes ### # This represents a YAML Document. This node must be a child of # Psych::Nodes::Stream. A Psych::Nodes::Document must have one child, # and that child may be one of the following: # # * Psych::Nodes::Sequence # * Psych::Nodes::Mapping # * Psych::Nodes::Scalar class Document < Psych::Nodes::Node # The version of the YAML document attr_accessor :version # A list of tag directives for this document attr_accessor :tag_directives # Was this document implicitly created? attr_accessor :implicit # Is the end of the document implicit? attr_accessor :implicit_end ### # Create a new Psych::Nodes::Document object. # # +version+ is a list indicating the YAML version. # +tags_directives+ is a list of tag directive declarations # +implicit+ is a flag indicating whether the document will be implicitly # started. # # == Example: # This creates a YAML document object that represents a YAML 1.1 document # with one tag directive, and has an implicit start: # # Psych::Nodes::Document.new( # [1,1], # [["!", "tag:tenderlovemaking.com,2009:"]], # true # ) # # == See Also # See also Psych::Handler#start_document def initialize version = [], tag_directives = [], implicit = false super() @version = version @tag_directives = tag_directives @implicit = implicit @implicit_end = true end ### # Returns the root node. A Document may only have one root node: # http://yaml.org/spec/1.1/#id898031 def root children.first end def document?; true; end end end end # frozen_string_literal: true module Psych module Nodes ### # This class represents a # {YAML sequence}[http://yaml.org/spec/1.1/#sequence/syntax]. # # A YAML sequence is basically a list, and looks like this: # # %YAML 1.1 # --- # - I am # - a Sequence # # A YAML sequence may have an anchor like this: # # %YAML 1.1 # --- # &A [ # "This sequence", # "has an anchor" # ] # # A YAML sequence may also have a tag like this: # # %YAML 1.1 # --- # !!seq [ # "This sequence", # "has a tag" # ] # # This class represents a sequence in a YAML document. A # Psych::Nodes::Sequence node may have 0 or more children. Valid children # for this node are: # # * Psych::Nodes::Sequence # * Psych::Nodes::Mapping # * Psych::Nodes::Scalar # * Psych::Nodes::Alias class Sequence < Psych::Nodes::Node # Any Styles, emitter chooses ANY = 0 # Block style sequence BLOCK = 1 # Flow style sequence FLOW = 2 # The anchor for this sequence (if any) attr_accessor :anchor # The tag name for this sequence (if any) attr_accessor :tag # Is this sequence started implicitly? attr_accessor :implicit # The sequence style used attr_accessor :style ### # Create a new object representing a YAML sequence. # # +anchor+ is the anchor associated with the sequence or nil. # +tag+ is the tag associated with the sequence or nil. # +implicit+ a boolean indicating whether or not the sequence was # implicitly started. # +style+ is an integer indicating the list style. # # See Psych::Handler#start_sequence def initialize anchor = nil, tag = nil, implicit = true, style = BLOCK super() @anchor = anchor @tag = tag @implicit = implicit @style = style end def sequence?; true; end end end end # frozen_string_literal: true module Psych module Streaming module ClassMethods ### # Create a new streaming emitter. Emitter will print to +io+. See # Psych::Stream for an example. def new io emitter = const_get(:Emitter).new(io) class_loader = ClassLoader.new ss = ScalarScanner.new class_loader super(emitter, ss, {}) end end ### # Start streaming using +encoding+ def start encoding = Nodes::Stream::UTF8 super.tap { yield self if block_given? } ensure finish if block_given? end private def register target, obj end end end # frozen_string_literal: true module Psych ### # YAML event parser class. This class parses a YAML document and calls # events on the handler that is passed to the constructor. The events can # be used for things such as constructing a YAML AST or deserializing YAML # documents. It can even be fed back to Psych::Emitter to emit the same # document that was parsed. # # See Psych::Handler for documentation on the events that Psych::Parser emits. # # Here is an example that prints out ever scalar found in a YAML document: # # # Handler for detecting scalar values # class ScalarHandler < Psych::Handler # def scalar value, anchor, tag, plain, quoted, style # puts value # end # end # # parser = Psych::Parser.new(ScalarHandler.new) # parser.parse(yaml_document) # # Here is an example that feeds the parser back in to Psych::Emitter. The # YAML document is read from STDIN and written back out to STDERR: # # parser = Psych::Parser.new(Psych::Emitter.new($stderr)) # parser.parse($stdin) # # Psych uses Psych::Parser in combination with Psych::TreeBuilder to # construct an AST of the parsed YAML document. class Parser class Mark < Struct.new(:index, :line, :column) end # The handler on which events will be called attr_accessor :handler # Set the encoding for this parser to +encoding+ attr_writer :external_encoding ### # Creates a new Psych::Parser instance with +handler+. YAML events will # be called on +handler+. See Psych::Parser for more details. def initialize handler = Handler.new @handler = handler @external_encoding = ANY end ### # call-seq: # parser.parse(yaml) # # Parse the YAML document contained in +yaml+. Events will be called on # the handler set on the parser instance. # # See Psych::Parser and Psych::Parser#handler def parse yaml, path = yaml.respond_to?(:path) ? yaml.path : "<unknown>" _native_parse @handler, yaml, path end end end # frozen_string_literal: true module Psych ### # If an object defines +encode_with+, then an instance of Psych::Coder will # be passed to the method when the object is being serialized. The Coder # automatically assumes a Psych::Nodes::Mapping is being emitted. Other # objects like Sequence and Scalar may be emitted if +seq=+ or +scalar=+ are # called, respectively. class Coder attr_accessor :tag, :style, :implicit, :object attr_reader :type, :seq def initialize tag @map = {} @seq = [] @implicit = false @type = :map @tag = tag @style = Psych::Nodes::Mapping::BLOCK @scalar = nil @object = nil end def scalar *args if args.length > 0 warn "#{caller[0]}: Coder#scalar(a,b,c) is deprecated" if $VERBOSE @tag, @scalar, _ = args @type = :scalar end @scalar end # Emit a map. The coder will be yielded to the block. def map tag = @tag, style = @style @tag = tag @style = style yield self if block_given? @map end # Emit a scalar with +value+ and +tag+ def represent_scalar tag, value self.tag = tag self.scalar = value end # Emit a sequence with +list+ and +tag+ def represent_seq tag, list @tag = tag self.seq = list end # Emit a sequence with +map+ and +tag+ def represent_map tag, map @tag = tag self.map = map end # Emit an arbitrary object +obj+ and +tag+ def represent_object tag, obj @tag = tag @type = :object @object = obj end # Emit a scalar with +value+ def scalar= value @type = :scalar @scalar = value end # Emit a map with +value+ def map= map @type = :map @map = map end def []= k, v @type = :map @map[k] = v end alias :add :[]= def [] k @type = :map @map[k] end # Emit a sequence of +list+ def seq= list @type = :seq @seq = list end end end # frozen_string_literal: true require_relative 'visitors/visitor' require_relative 'visitors/to_ruby' require_relative 'visitors/emitter' require_relative 'visitors/yaml_tree' require_relative 'visitors/json_tree' require_relative 'visitors/depth_first' # frozen_string_literal: true module Psych ### # Psych::Stream is a streaming YAML emitter. It will not buffer your YAML, # but send it straight to an IO. # # Here is an example use: # # stream = Psych::Stream.new($stdout) # stream.start # stream.push({:foo => 'bar'}) # stream.finish # # YAML will be immediately emitted to $stdout with no buffering. # # Psych::Stream#start will take a block and ensure that Psych::Stream#finish # is called, so you can do this form: # # stream = Psych::Stream.new($stdout) # stream.start do |em| # em.push(:foo => 'bar') # end # class Stream < Psych::Visitors::YAMLTree class Emitter < Psych::Emitter # :nodoc: def end_document implicit_end = !streaming? super end def streaming? true end end include Psych::Streaming extend Psych::Streaming::ClassMethods end end # frozen_string_literal: true module Psych class Omap < ::Hash end end # frozen_string_literal: true module Psych class Exception < RuntimeError end class BadAlias < Exception end # Subclasses `BadAlias` for backwards compatibility class AliasesNotEnabled < BadAlias def initialize super "Alias parsing was not enabled. To enable it, pass `aliases: true` to `Psych::load` or `Psych::safe_load`." end end # Subclasses `BadAlias` for backwards compatibility class AnchorNotDefined < BadAlias def initialize anchor_name super "An alias referenced an unknown anchor: #{anchor_name}" end end class DisallowedClass < Exception def initialize action, klass_name super "Tried to #{action} unspecified class: #{klass_name}" end end end # frozen_string_literal: true require_relative '../handler' module Psych module Handlers ### # This handler will capture an event and record the event. Recorder events # are available vial Psych::Handlers::Recorder#events. # # For example: # # recorder = Psych::Handlers::Recorder.new # parser = Psych::Parser.new recorder # parser.parse '--- foo' # # recorder.events # => [list of events] # # # Replay the events # # emitter = Psych::Emitter.new $stdout # recorder.events.each do |m, args| # emitter.send m, *args # end class Recorder < Psych::Handler attr_reader :events def initialize @events = [] super end EVENTS.each do |event| define_method event do |*args| @events << [event, args] end end end end end # frozen_string_literal: true require_relative '../tree_builder' module Psych module Handlers class DocumentStream < Psych::TreeBuilder # :nodoc: def initialize &block super @block = block end def start_document version, tag_directives, implicit n = Nodes::Document.new version, tag_directives, implicit push n end def end_document implicit_end = !streaming? @last.implicit_end = implicit_end @block.call pop end end end end # frozen_string_literal: true require_relative 'exception' module Psych class SyntaxError < Psych::Exception attr_reader :file, :line, :column, :offset, :problem, :context def initialize file, line, col, offset, problem, context err = [problem, context].compact.join ' ' filename = file || '<unknown>' message = "(%s): %s at line %d column %d" % [filename, err, line, col] @file = file @line = line @column = col @offset = offset @problem = problem @context = context super(message) end end end # frozen_string_literal: true module Psych module JSON module RubyEvents # :nodoc: def visit_Time o formatted = format_time o @emitter.scalar formatted, nil, nil, false, true, Nodes::Scalar::DOUBLE_QUOTED end def visit_DateTime o visit_Time o.to_time end def visit_String o @emitter.scalar o.to_s, nil, nil, false, true, Nodes::Scalar::DOUBLE_QUOTED end alias :visit_Symbol :visit_String end end end # frozen_string_literal: true module Psych module JSON module YAMLEvents # :nodoc: def start_document version, tag_directives, implicit super(version, tag_directives, !streaming?) end def end_document implicit_end = !streaming? super(implicit_end) end def start_mapping anchor, tag, implicit, style super(anchor, nil, true, Nodes::Mapping::FLOW) end def start_sequence anchor, tag, implicit, style super(anchor, nil, true, Nodes::Sequence::FLOW) end def scalar value, anchor, tag, plain, quoted, style if "tag:yaml.org,2002:null" == tag super('null', nil, nil, true, false, Nodes::Scalar::PLAIN) else super end end end end end # frozen_string_literal: true require_relative 'yaml_events' module Psych module JSON ### # Psych::JSON::TreeBuilder is an event based AST builder. Events are sent # to an instance of Psych::JSON::TreeBuilder and a JSON AST is constructed. class TreeBuilder < Psych::TreeBuilder include Psych::JSON::YAMLEvents end end end # frozen_string_literal: true require_relative 'ruby_events' require_relative 'yaml_events' module Psych module JSON class Stream < Psych::Visitors::JSONTree include Psych::JSON::RubyEvents include Psych::Streaming extend Psych::Streaming::ClassMethods class Emitter < Psych::Stream::Emitter # :nodoc: include Psych::JSON::YAMLEvents end end end end # frozen_string_literal: true module Psych ### # Psych::Handler is an abstract base class that defines the events used # when dealing with Psych::Parser. Clients who want to use Psych::Parser # should implement a class that inherits from Psych::Handler and define # events that they can handle. # # Psych::Handler defines all events that Psych::Parser can possibly send to # event handlers. # # See Psych::Parser for more details class Handler ### # Configuration options for dumping YAML. class DumperOptions attr_accessor :line_width, :indentation, :canonical def initialize @line_width = 0 @indentation = 2 @canonical = false end end # Default dumping options OPTIONS = DumperOptions.new # Events that a Handler should respond to. EVENTS = [ :alias, :empty, :end_document, :end_mapping, :end_sequence, :end_stream, :scalar, :start_document, :start_mapping, :start_sequence, :start_stream ] ### # Called with +encoding+ when the YAML stream starts. This method is # called once per stream. A stream may contain multiple documents. # # See the constants in Psych::Parser for the possible values of +encoding+. def start_stream encoding end ### # Called when the document starts with the declared +version+, # +tag_directives+, if the document is +implicit+. # # +version+ will be an array of integers indicating the YAML version being # dealt with, +tag_directives+ is a list of tuples indicating the prefix # and suffix of each tag, and +implicit+ is a boolean indicating whether # the document is started implicitly. # # === Example # # Given the following YAML: # # %YAML 1.1 # %TAG ! tag:tenderlovemaking.com,2009: # --- !squee # # The parameters for start_document must be this: # # version # => [1, 1] # tag_directives # => [["!", "tag:tenderlovemaking.com,2009:"]] # implicit # => false def start_document version, tag_directives, implicit end ### # Called with the document ends. +implicit+ is a boolean value indicating # whether or not the document has an implicit ending. # # === Example # # Given the following YAML: # # --- # hello world # # +implicit+ will be true. Given this YAML: # # --- # hello world # ... # # +implicit+ will be false. def end_document implicit end ### # Called when an alias is found to +anchor+. +anchor+ will be the name # of the anchor found. # # === Example # # Here we have an example of an array that references itself in YAML: # # --- &ponies # - first element # - *ponies # # &ponies is the anchor, *ponies is the alias. In this case, alias is # called with "ponies". def alias anchor end ### # Called when a scalar +value+ is found. The scalar may have an # +anchor+, a +tag+, be implicitly +plain+ or implicitly +quoted+ # # +value+ is the string value of the scalar # +anchor+ is an associated anchor or nil # +tag+ is an associated tag or nil # +plain+ is a boolean value # +quoted+ is a boolean value # +style+ is an integer indicating the string style # # See the constants in Psych::Nodes::Scalar for the possible values of # +style+ # # === Example # # Here is a YAML document that exercises most of the possible ways this # method can be called: # # --- # - !str "foo" # - &anchor fun # - many # lines # - | # many # newlines # # The above YAML document contains a list with four strings. Here are # the parameters sent to this method in the same order: # # # value anchor tag plain quoted style # ["foo", nil, "!str", false, false, 3 ] # ["fun", "anchor", nil, true, false, 1 ] # ["many lines", nil, nil, true, false, 1 ] # ["many\nnewlines\n", nil, nil, false, true, 4 ] # def scalar value, anchor, tag, plain, quoted, style end ### # Called when a sequence is started. # # +anchor+ is the anchor associated with the sequence or nil. # +tag+ is the tag associated with the sequence or nil. # +implicit+ a boolean indicating whether or not the sequence was implicitly # started. # +style+ is an integer indicating the list style. # # See the constants in Psych::Nodes::Sequence for the possible values of # +style+. # # === Example # # Here is a YAML document that exercises most of the possible ways this # method can be called: # # --- # - !!seq [ # a # ] # - &pewpew # - b # # The above YAML document consists of three lists, an outer list that # contains two inner lists. Here is a matrix of the parameters sent # to represent these lists: # # # anchor tag implicit style # [nil, nil, true, 1 ] # [nil, "tag:yaml.org,2002:seq", false, 2 ] # ["pewpew", nil, true, 1 ] def start_sequence anchor, tag, implicit, style end ### # Called when a sequence ends. def end_sequence end ### # Called when a map starts. # # +anchor+ is the anchor associated with the map or +nil+. # +tag+ is the tag associated with the map or +nil+. # +implicit+ is a boolean indicating whether or not the map was implicitly # started. # +style+ is an integer indicating the mapping style. # # See the constants in Psych::Nodes::Mapping for the possible values of # +style+. # # === Example # # Here is a YAML document that exercises most of the possible ways this # method can be called: # # --- # k: !!map { hello: world } # v: &pewpew # hello: world # # The above YAML document consists of three maps, an outer map that contains # two inner maps. Below is a matrix of the parameters sent in order to # represent these three maps: # # # anchor tag implicit style # [nil, nil, true, 1 ] # [nil, "tag:yaml.org,2002:map", false, 2 ] # ["pewpew", nil, true, 1 ] def start_mapping anchor, tag, implicit, style end ### # Called when a map ends def end_mapping end ### # Called when an empty event happens. (Which, as far as I can tell, is # never). def empty end ### # Called when the YAML stream ends def end_stream end ### # Called before each event with line/column information. def event_location(start_line, start_column, end_line, end_column) end ### # Is this handler a streaming handler? def streaming? false end end end # frozen_string_literal: true class Object def self.yaml_tag url Psych.add_tag(url, self) end ### # call-seq: to_yaml(options = {}) # # Convert an object to YAML. See Psych.dump for more information on the # available +options+. def to_yaml options = {} Psych.dump self, options end end if defined?(::IRB) require_relative 'y' end # frozen_string_literal: true module Kernel ### # An alias for Psych.dump_stream meant to be used with IRB. def y *objects puts Psych.dump_stream(*objects) end private :y end # frozen_string_literal: true module Psych # The version of Psych you are using VERSION = '5.1.2' if RUBY_ENGINE == 'jruby' DEFAULT_SNAKEYAML_VERSION = '2.7'.freeze end end # frozen_string_literal: true module Psych module Visitors class DepthFirst < Psych::Visitors::Visitor def initialize block @block = block end private def nary o o.children.each { |x| visit x } @block.call o end alias :visit_Psych_Nodes_Stream :nary alias :visit_Psych_Nodes_Document :nary alias :visit_Psych_Nodes_Sequence :nary alias :visit_Psych_Nodes_Mapping :nary def terminal o @block.call o end alias :visit_Psych_Nodes_Scalar :terminal alias :visit_Psych_Nodes_Alias :terminal end end end # frozen_string_literal: true module Psych module Visitors class Emitter < Psych::Visitors::Visitor def initialize io, options = {} opts = [:indentation, :canonical, :line_width].find_all { |opt| options.key?(opt) } if opts.empty? @handler = Psych::Emitter.new io else du = Handler::DumperOptions.new opts.each { |option| du.send :"#{option}=", options[option] } @handler = Psych::Emitter.new io, du end end def visit_Psych_Nodes_Stream o @handler.start_stream o.encoding o.children.each { |c| accept c } @handler.end_stream end def visit_Psych_Nodes_Document o @handler.start_document o.version, o.tag_directives, o.implicit o.children.each { |c| accept c } @handler.end_document o.implicit_end end def visit_Psych_Nodes_Scalar o @handler.scalar o.value, o.anchor, o.tag, o.plain, o.quoted, o.style end def visit_Psych_Nodes_Sequence o @handler.start_sequence o.anchor, o.tag, o.implicit, o.style o.children.each { |c| accept c } @handler.end_sequence end def visit_Psych_Nodes_Mapping o @handler.start_mapping o.anchor, o.tag, o.implicit, o.style o.children.each { |c| accept c } @handler.end_mapping end def visit_Psych_Nodes_Alias o @handler.alias o.anchor end end end end # frozen_string_literal: true require_relative '../scalar_scanner' require_relative '../class_loader' require_relative '../exception' unless defined?(Regexp::NOENCODING) Regexp::NOENCODING = 32 end module Psych module Visitors ### # This class walks a YAML AST, converting each node to Ruby class ToRuby < Psych::Visitors::Visitor def self.create(symbolize_names: false, freeze: false, strict_integer: false) class_loader = ClassLoader.new scanner = ScalarScanner.new class_loader, strict_integer: strict_integer new(scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze) end attr_reader :class_loader def initialize ss, class_loader, symbolize_names: false, freeze: false super() @st = {} @ss = ss @load_tags = Psych.load_tags @domain_types = Psych.domain_types @class_loader = class_loader @symbolize_names = symbolize_names @freeze = freeze end def accept target result = super unless @domain_types.empty? || !target.tag key = target.tag.sub(/^[!\/]*/, '').sub(/(,\d+)\//, '\1:') key = "tag:#{key}" unless key =~ /^(?:tag:|x-private)/ if @domain_types.key? key value, block = @domain_types[key] result = block.call value, result end end result = deduplicate(result).freeze if @freeze result end def deserialize o if klass = resolve_class(@load_tags[o.tag]) instance = klass.allocate if instance.respond_to?(:init_with) coder = Psych::Coder.new(o.tag) coder.scalar = o.value instance.init_with coder end return instance end return o.value if o.quoted return @ss.tokenize(o.value) unless o.tag case o.tag when '!binary', 'tag:yaml.org,2002:binary' o.value.unpack('m').first when /^!(?:str|ruby\/string)(?::(.*))?$/, 'tag:yaml.org,2002:str' klass = resolve_class($1) if klass klass.allocate.replace o.value else o.value end when '!ruby/object:BigDecimal' require 'bigdecimal' unless defined? BigDecimal class_loader.big_decimal._load o.value when "!ruby/object:DateTime" class_loader.date_time require 'date' unless defined? DateTime t = @ss.parse_time(o.value) DateTime.civil(*t.to_a[0, 6].reverse, Rational(t.utc_offset, 86400)) + (t.subsec/86400) when '!ruby/encoding' ::Encoding.find o.value when "!ruby/object:Complex" class_loader.complex Complex(o.value) when "!ruby/object:Rational" class_loader.rational Rational(o.value) when "!ruby/class", "!ruby/module" resolve_class o.value when "tag:yaml.org,2002:float", "!float" Float(@ss.tokenize(o.value)) when "!ruby/regexp" klass = class_loader.regexp o.value =~ /^\/(.*)\/([mixn]*)$/m source = $1 options = 0 lang = nil $2&.each_char do |option| case option when 'x' then options |= Regexp::EXTENDED when 'i' then options |= Regexp::IGNORECASE when 'm' then options |= Regexp::MULTILINE when 'n' then options |= Regexp::NOENCODING else lang = option end end klass.new(*[source, options, lang].compact) when "!ruby/range" klass = class_loader.range args = o.value.split(/([.]{2,3})/, 2).map { |s| accept Nodes::Scalar.new(s) } args.push(args.delete_at(1) == '...') klass.new(*args) when /^!ruby\/sym(bol)?:?(.*)?$/ class_loader.symbolize o.value else @ss.tokenize o.value end end private :deserialize def visit_Psych_Nodes_Scalar o register o, deserialize(o) end def visit_Psych_Nodes_Sequence o if klass = resolve_class(@load_tags[o.tag]) instance = klass.allocate if instance.respond_to?(:init_with) coder = Psych::Coder.new(o.tag) coder.seq = o.children.map { |c| accept c } instance.init_with coder end return instance end case o.tag when nil register_empty(o) when '!omap', 'tag:yaml.org,2002:omap' map = register(o, Psych::Omap.new) o.children.each { |a| map[accept(a.children.first)] = accept a.children.last } map when /^!(?:seq|ruby\/array):(.*)$/ klass = resolve_class($1) list = register(o, klass.allocate) o.children.each { |c| list.push accept c } list else register_empty(o) end end def visit_Psych_Nodes_Mapping o if @load_tags[o.tag] return revive(resolve_class(@load_tags[o.tag]), o) end return revive_hash(register(o, {}), o) unless o.tag case o.tag when /^!ruby\/struct:?(.*)?$/ klass = resolve_class($1) if $1 if klass s = register(o, klass.allocate) members = {} struct_members = s.members.map { |x| class_loader.symbolize x } o.children.each_slice(2) do |k,v| member = accept(k) value = accept(v) if struct_members.include?(class_loader.symbolize(member)) s.send("#{member}=", value) else members[member.to_s.sub(/^@/, '')] = value end end init_with(s, members, o) else klass = class_loader.struct members = o.children.map { |c| accept c } h = Hash[*members] s = klass.new(*h.map { |k,v| class_loader.symbolize k }).new(*h.map { |k,v| v }) register(o, s) s end when /^!ruby\/object:?(.*)?$/ name = $1 || 'Object' if name == 'Complex' class_loader.complex h = Hash[*o.children.map { |c| accept c }] register o, Complex(h['real'], h['image']) elsif name == 'Rational' class_loader.rational h = Hash[*o.children.map { |c| accept c }] register o, Rational(h['numerator'], h['denominator']) elsif name == 'Hash' revive_hash(register(o, {}), o) else obj = revive((resolve_class(name) || class_loader.object), o) obj end when /^!(?:str|ruby\/string)(?::(.*))?$/, 'tag:yaml.org,2002:str' klass = resolve_class($1) members = {} string = nil o.children.each_slice(2) do |k,v| key = accept k value = accept v if key == 'str' if klass string = klass.allocate.replace value else string = value end register(o, string) else members[key] = value end end init_with(string, members.map { |k,v| [k.to_s.sub(/^@/, ''),v] }, o) when /^!ruby\/array:(.*)$/ klass = resolve_class($1) list = register(o, klass.allocate) members = Hash[o.children.map { |c| accept c }.each_slice(2).to_a] list.replace members['internal'] members['ivars'].each do |ivar, v| list.instance_variable_set ivar, v end list when '!ruby/range' klass = class_loader.range h = Hash[*o.children.map { |c| accept c }] register o, klass.new(h['begin'], h['end'], h['excl']) when /^!ruby\/exception:?(.*)?$/ h = Hash[*o.children.map { |c| accept c }] e = build_exception((resolve_class($1) || class_loader.exception), h.delete('message')) e.set_backtrace h.delete('backtrace') if h.key? 'backtrace' init_with(e, h, o) when '!set', 'tag:yaml.org,2002:set' set = class_loader.psych_set.new @st[o.anchor] = set if o.anchor o.children.each_slice(2) do |k,v| set[accept(k)] = accept(v) end set when /^!ruby\/hash-with-ivars(?::(.*))?$/ hash = $1 ? resolve_class($1).allocate : {} register o, hash o.children.each_slice(2) do |key, value| case key.value when 'elements' revive_hash hash, value when 'ivars' value.children.each_slice(2) do |k,v| hash.instance_variable_set accept(k), accept(v) end end end hash when /^!map:(.*)$/, /^!ruby\/hash:(.*)$/ revive_hash register(o, resolve_class($1).allocate), o when '!omap', 'tag:yaml.org,2002:omap' map = register(o, class_loader.psych_omap.new) o.children.each_slice(2) do |l,r| map[accept(l)] = accept r end map when /^!ruby\/marshalable:(.*)$/ name = $1 klass = resolve_class(name) obj = register(o, klass.allocate) if obj.respond_to?(:init_with) init_with(obj, revive_hash({}, o), o) elsif obj.respond_to?(:marshal_load) marshal_data = o.children.map(&method(:accept)) obj.marshal_load(marshal_data) obj else raise ArgumentError, "Cannot deserialize #{name}" end else revive_hash(register(o, {}), o) end end def visit_Psych_Nodes_Document o accept o.root end def visit_Psych_Nodes_Stream o o.children.map { |c| accept c } end def visit_Psych_Nodes_Alias o @st.fetch(o.anchor) { raise AnchorNotDefined, o.anchor } end private def register node, object @st[node.anchor] = object if node.anchor object end def register_empty object list = register(object, []) object.children.each { |c| list.push accept c } list end def revive_hash hash, o, tagged= false o.children.each_slice(2) { |k,v| key = accept(k) val = accept(v) if key == '<<' && k.tag != "tag:yaml.org,2002:str" case v when Nodes::Alias, Nodes::Mapping begin hash.merge! val rescue TypeError hash[key] = val end when Nodes::Sequence begin h = {} val.reverse_each do |value| h.merge! value end hash.merge! h rescue TypeError hash[key] = val end else hash[key] = val end else if !tagged && @symbolize_names && key.is_a?(String) key = key.to_sym elsif !@freeze key = deduplicate(key) end hash[key] = val end } hash end if RUBY_VERSION < '2.7' def deduplicate key if key.is_a?(String) # It is important to untaint the string, otherwise it won't # be deduplicated into an fstring, but simply frozen. -(key.untaint) else key end end else def deduplicate key if key.is_a?(String) -key else key end end end def merge_key hash, key, val end def revive klass, node s = register(node, klass.allocate) init_with(s, revive_hash({}, node, true), node) end def init_with o, h, node c = Psych::Coder.new(node.tag) c.map = h if o.respond_to?(:init_with) o.init_with c else h.each { |k,v| o.instance_variable_set(:"@#{k}", v) } end o end # Convert +klassname+ to a Class def resolve_class klassname class_loader.load klassname end end class NoAliasRuby < ToRuby def visit_Psych_Nodes_Alias o raise AliasesNotEnabled end end end end # frozen_string_literal: true require_relative '../json/ruby_events' module Psych module Visitors class JSONTree < YAMLTree include Psych::JSON::RubyEvents def self.create options = {} emitter = Psych::JSON::TreeBuilder.new class_loader = ClassLoader.new ss = ScalarScanner.new class_loader new(emitter, ss, options) end def accept target if target.respond_to?(:encode_with) dump_coder target else send(@dispatch_cache[target.class], target) end end end end end # frozen_string_literal: true module Psych module Visitors class Visitor def accept target visit target end private # @api private def self.dispatch_cache Hash.new do |hash, klass| hash[klass] = :"visit_#{klass.name.gsub('::', '_')}" end.compare_by_identity end if defined?(Ractor) def dispatch @dispatch_cache ||= (Ractor.current[:Psych_Visitors_Visitor] ||= Visitor.dispatch_cache) end else DISPATCH = dispatch_cache def dispatch DISPATCH end end def visit target send dispatch[target.class], target end end end end # frozen_string_literal: true require_relative '../tree_builder' require_relative '../scalar_scanner' require_relative '../class_loader' module Psych module Visitors ### # YAMLTree builds a YAML ast given a Ruby object. For example: # # builder = Psych::Visitors::YAMLTree.new # builder << { :foo => 'bar' } # builder.tree # => #<Psych::Nodes::Stream .. } # class YAMLTree < Psych::Visitors::Visitor class Registrar # :nodoc: def initialize @obj_to_id = {}.compare_by_identity @obj_to_node = {}.compare_by_identity @targets = [] @counter = 0 end def register target, node @targets << target @obj_to_node[target] = node end def key? target @obj_to_node.key? target rescue NoMethodError false end def id_for target @obj_to_id[target] ||= (@counter += 1) end def node_for target @obj_to_node[target] end end attr_reader :started, :finished alias :finished? :finished alias :started? :started def self.create options = {}, emitter = nil emitter ||= TreeBuilder.new class_loader = ClassLoader.new ss = ScalarScanner.new class_loader new(emitter, ss, options) end def initialize emitter, ss, options super() @started = false @finished = false @emitter = emitter @st = Registrar.new @ss = ss @options = options @line_width = options[:line_width] if @line_width && @line_width < 0 if @line_width == -1 # Treat -1 as unlimited line-width, same as libyaml does. @line_width = nil else fail(ArgumentError, "Invalid line_width #{@line_width}, must be non-negative or -1 for unlimited.") end end @coders = [] @dispatch_cache = Hash.new do |h,klass| method = "visit_#{(klass.name || '').split('::').join('_')}" method = respond_to?(method) ? method : h[klass.superclass] raise(TypeError, "Can't dump #{target.class}") unless method h[klass] = method end.compare_by_identity end def start encoding = Nodes::Stream::UTF8 @emitter.start_stream(encoding).tap do @started = true end end def finish @emitter.end_stream.tap do @finished = true end end def tree finish unless finished? @emitter.root end def push object start unless started? version = [] version = [1,1] if @options[:header] case @options[:version] when Array version = @options[:version] when String version = @options[:version].split('.').map { |x| x.to_i } else version = [1,1] end if @options.key? :version @emitter.start_document version, [], false accept object @emitter.end_document !@emitter.streaming? end alias :<< :push def accept target # return any aliases we find if @st.key? target oid = @st.id_for target node = @st.node_for target anchor = oid.to_s node.anchor = anchor return @emitter.alias anchor end if target.respond_to?(:encode_with) dump_coder target else send(@dispatch_cache[target.class], target) end end def visit_Psych_Omap o seq = @emitter.start_sequence(nil, 'tag:yaml.org,2002:omap', false, Nodes::Sequence::BLOCK) register(o, seq) o.each { |k,v| visit_Hash k => v } @emitter.end_sequence end def visit_Encoding o tag = "!ruby/encoding" @emitter.scalar o.name, nil, tag, false, false, Nodes::Scalar::ANY end def visit_Object o tag = Psych.dump_tags[o.class] unless tag klass = o.class == Object ? nil : o.class.name tag = ['!ruby/object', klass].compact.join(':') end map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK) register(o, map) dump_ivars o @emitter.end_mapping end alias :visit_Delegator :visit_Object def visit_Struct o tag = ['!ruby/struct', o.class.name].compact.join(':') register o, @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK) o.members.each do |member| @emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY accept o[member] end dump_ivars o @emitter.end_mapping end def visit_Exception o dump_exception o, o.message.to_s end def visit_NameError o dump_exception o, o.message.to_s end def visit_Regexp o register o, @emitter.scalar(o.inspect, nil, '!ruby/regexp', false, false, Nodes::Scalar::ANY) end def visit_Date o register o, visit_Integer(o.gregorian) end def visit_DateTime o t = o.italy formatted = format_time t, t.offset.zero? tag = '!ruby/object:DateTime' register o, @emitter.scalar(formatted, nil, tag, false, false, Nodes::Scalar::ANY) end def visit_Time o formatted = format_time o register o, @emitter.scalar(formatted, nil, nil, true, false, Nodes::Scalar::ANY) end def visit_Rational o register o, @emitter.start_mapping(nil, '!ruby/object:Rational', false, Nodes::Mapping::BLOCK) [ 'denominator', o.denominator.to_s, 'numerator', o.numerator.to_s ].each do |m| @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY end @emitter.end_mapping end def visit_Complex o register o, @emitter.start_mapping(nil, '!ruby/object:Complex', false, Nodes::Mapping::BLOCK) ['real', o.real.to_s, 'image', o.imag.to_s].each do |m| @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY end @emitter.end_mapping end def visit_Integer o @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY end alias :visit_TrueClass :visit_Integer alias :visit_FalseClass :visit_Integer def visit_Float o if o.nan? @emitter.scalar '.nan', nil, nil, true, false, Nodes::Scalar::ANY elsif o.infinite? @emitter.scalar((o.infinite? > 0 ? '.inf' : '-.inf'), nil, nil, true, false, Nodes::Scalar::ANY) else @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY end end def visit_BigDecimal o @emitter.scalar o._dump, nil, '!ruby/object:BigDecimal', false, false, Nodes::Scalar::ANY end def visit_String o plain = true quote = true style = Nodes::Scalar::PLAIN tag = nil if binary?(o) o = [o].pack('m0') tag = '!binary' # FIXME: change to below when syck is removed #tag = 'tag:yaml.org,2002:binary' style = Nodes::Scalar::LITERAL plain = false quote = false elsif o =~ /\n(?!\Z)/ # match \n except blank line at the end of string style = Nodes::Scalar::LITERAL elsif o == '<<' style = Nodes::Scalar::SINGLE_QUOTED tag = 'tag:yaml.org,2002:str' plain = false quote = false elsif o == 'y' || o == 'n' style = Nodes::Scalar::DOUBLE_QUOTED elsif @line_width && o.length > @line_width style = Nodes::Scalar::FOLDED elsif o =~ /^[^[:word:]][^"]*$/ style = Nodes::Scalar::DOUBLE_QUOTED elsif not String === @ss.tokenize(o) or /\A0[0-7]*[89]/ =~ o style = Nodes::Scalar::SINGLE_QUOTED end is_primitive = o.class == ::String ivars = is_primitive ? [] : o.instance_variables if ivars.empty? unless is_primitive tag = "!ruby/string:#{o.class}" plain = false quote = false end @emitter.scalar o, nil, tag, plain, quote, style else maptag = '!ruby/string'.dup maptag << ":#{o.class}" unless o.class == ::String register o, @emitter.start_mapping(nil, maptag, false, Nodes::Mapping::BLOCK) @emitter.scalar 'str', nil, nil, true, false, Nodes::Scalar::ANY @emitter.scalar o, nil, tag, plain, quote, style dump_ivars o @emitter.end_mapping end end def visit_Module o raise TypeError, "can't dump anonymous module: #{o}" unless o.name register o, @emitter.scalar(o.name, nil, '!ruby/module', false, false, Nodes::Scalar::SINGLE_QUOTED) end def visit_Class o raise TypeError, "can't dump anonymous class: #{o}" unless o.name register o, @emitter.scalar(o.name, nil, '!ruby/class', false, false, Nodes::Scalar::SINGLE_QUOTED) end def visit_Range o register o, @emitter.start_mapping(nil, '!ruby/range', false, Nodes::Mapping::BLOCK) ['begin', o.begin, 'end', o.end, 'excl', o.exclude_end?].each do |m| accept m end @emitter.end_mapping end def visit_Hash o if o.class == ::Hash register(o, @emitter.start_mapping(nil, nil, true, Psych::Nodes::Mapping::BLOCK)) o.each do |k,v| accept k accept v end @emitter.end_mapping else visit_hash_subclass o end end def visit_Psych_Set o register(o, @emitter.start_mapping(nil, '!set', false, Psych::Nodes::Mapping::BLOCK)) o.each do |k,v| accept k accept v end @emitter.end_mapping end def visit_Array o if o.class == ::Array visit_Enumerator o else visit_array_subclass o end end def visit_Enumerator o register o, @emitter.start_sequence(nil, nil, true, Nodes::Sequence::BLOCK) o.each { |c| accept c } @emitter.end_sequence end def visit_NilClass o @emitter.scalar('', nil, 'tag:yaml.org,2002:null', true, false, Nodes::Scalar::ANY) end def visit_Symbol o if o.empty? @emitter.scalar "", nil, '!ruby/symbol', false, false, Nodes::Scalar::ANY else @emitter.scalar ":#{o}", nil, nil, true, false, Nodes::Scalar::ANY end end def visit_BasicObject o tag = Psych.dump_tags[o.class] tag ||= "!ruby/marshalable:#{o.class.name}" map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK) register(o, map) o.marshal_dump.each(&method(:accept)) @emitter.end_mapping end private def binary? string string.encoding == Encoding::ASCII_8BIT && !string.ascii_only? end def visit_array_subclass o tag = "!ruby/array:#{o.class}" ivars = o.instance_variables if ivars.empty? node = @emitter.start_sequence(nil, tag, false, Nodes::Sequence::BLOCK) register o, node o.each { |c| accept c } @emitter.end_sequence else node = @emitter.start_mapping(nil, tag, false, Nodes::Sequence::BLOCK) register o, node # Dump the internal list accept 'internal' @emitter.start_sequence(nil, nil, true, Nodes::Sequence::BLOCK) o.each { |c| accept c } @emitter.end_sequence # Dump the ivars accept 'ivars' @emitter.start_mapping(nil, nil, true, Nodes::Sequence::BLOCK) ivars.each do |ivar| accept ivar accept o.instance_variable_get ivar end @emitter.end_mapping @emitter.end_mapping end end def visit_hash_subclass o ivars = o.instance_variables if ivars.any? tag = "!ruby/hash-with-ivars:#{o.class}" node = @emitter.start_mapping(nil, tag, false, Psych::Nodes::Mapping::BLOCK) register(o, node) # Dump the ivars accept 'ivars' @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK o.instance_variables.each do |ivar| accept ivar accept o.instance_variable_get ivar end @emitter.end_mapping # Dump the elements accept 'elements' @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK o.each do |k,v| accept k accept v end @emitter.end_mapping @emitter.end_mapping else tag = "!ruby/hash:#{o.class}" node = @emitter.start_mapping(nil, tag, false, Psych::Nodes::Mapping::BLOCK) register(o, node) o.each do |k,v| accept k accept v end @emitter.end_mapping end end def dump_list o end def dump_exception o, msg tag = ['!ruby/exception', o.class.name].join ':' @emitter.start_mapping nil, tag, false, Nodes::Mapping::BLOCK if msg @emitter.scalar 'message', nil, nil, true, false, Nodes::Scalar::ANY accept msg end @emitter.scalar 'backtrace', nil, nil, true, false, Nodes::Scalar::ANY accept o.backtrace dump_ivars o @emitter.end_mapping end def format_time time, utc = time.utc? if utc time.strftime("%Y-%m-%d %H:%M:%S.%9N Z") else time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z") end end def register target, yaml_obj @st.register target, yaml_obj yaml_obj end def dump_coder o @coders << o tag = Psych.dump_tags[o.class] unless tag klass = o.class == Object ? nil : o.class.name tag = ['!ruby/object', klass].compact.join(':') end c = Psych::Coder.new(tag) o.encode_with(c) emit_coder c, o end def emit_coder c, o case c.type when :scalar @emitter.scalar c.scalar, nil, c.tag, c.tag.nil?, false, c.style when :seq @emitter.start_sequence nil, c.tag, c.tag.nil?, c.style c.seq.each do |thing| accept thing end @emitter.end_sequence when :map register o, @emitter.start_mapping(nil, c.tag, c.implicit, c.style) c.map.each do |k,v| accept k accept v end @emitter.end_mapping when :object accept c.object end end def dump_ivars target target.instance_variables.each do |iv| @emitter.scalar("#{iv.to_s.sub(/^@/, '')}", nil, nil, true, false, Nodes::Scalar::ANY) accept target.instance_variable_get(iv) end end end class RestrictedYAMLTree < YAMLTree DEFAULT_PERMITTED_CLASSES = { TrueClass => true, FalseClass => true, NilClass => true, Integer => true, Float => true, String => true, Array => true, Hash => true, }.compare_by_identity.freeze def initialize emitter, ss, options super @permitted_classes = DEFAULT_PERMITTED_CLASSES.dup Array(options[:permitted_classes]).each do |klass| @permitted_classes[klass] = true end @permitted_symbols = {}.compare_by_identity Array(options[:permitted_symbols]).each do |symbol| @permitted_symbols[symbol] = true end @aliases = options.fetch(:aliases, false) end def accept target if !@aliases && @st.key?(target) raise BadAlias, "Tried to dump an aliased object" end unless Symbol === target || @permitted_classes[target.class] raise DisallowedClass.new('dump', target.class.name || target.class.inspect) end super end def visit_Symbol sym unless @permitted_classes[Symbol] || @permitted_symbols[sym] raise DisallowedClass.new('dump', "Symbol(#{sym.inspect})") end super end end end end # Rackup `rackup` provides a command line interface for running a Rack-compatible application. [](https://github.com/rack/rackup/actions?workflow=Test) ## Installation ``` bash $ gem install rackup ``` ## Usage In a directory with your `config.ru` simply run the command: ``` bash $ rackup ``` Your application should now be available locally, typically `http://localhost:9292`. ## Contributing We welcome contributions to this project. 1. Fork it. 2. Create your feature branch (`git checkout -b my-new-feature`). 3. Commit your changes (`git commit -am 'Add some feature'`). 4. Push to the branch (`git push origin my-new-feature`). 5. Create new Pull Request. # frozen_string_literal: true # Released under the MIT License. # Copyright, 2019-2022, by Samuel Williams. module Rackup # The input stream is an IO-like object which contains the raw HTTP POST data. When applicable, its external encoding must be “ASCII-8BIT” and it must be opened in binary mode, for Ruby 1.9 compatibility. The input stream must respond to gets, each, read and rewind. class Stream def initialize(input = nil, output = Buffered.new) @input = input @output = output raise ArgumentError, "Non-writable output!" unless output.respond_to?(:write) # Will hold remaining data in `#read`. @buffer = nil @closed = false end attr :input attr :output # This provides a read-only interface for data, which is surprisingly tricky to implement correctly. module Reader # rack.hijack_io must respond to: # read, write, read_nonblock, write_nonblock, flush, close, close_read, close_write, closed? # read behaves like IO#read. Its signature is read([length, [buffer]]). If given, length must be a non-negative Integer (>= 0) or nil, and buffer must be a String and may not be nil. If length is given and not nil, then this method reads at most length bytes from the input stream. If length is not given or nil, then this method reads all data until EOF. When EOF is reached, this method returns nil if length is given and not nil, or “” if length is not given or is nil. If buffer is given, then the read data will be placed into buffer instead of a newly created String object. # @param length [Integer] the amount of data to read # @param buffer [String] the buffer which will receive the data # @return a buffer containing the data def read(length = nil, buffer = nil) return '' if length == 0 buffer ||= String.new.force_encoding(Encoding::BINARY) # Take any previously buffered data and replace it into the given buffer. if @buffer buffer.replace(@buffer) @buffer = nil else buffer.clear end if length while buffer.bytesize < length and chunk = read_next buffer << chunk end # This ensures the subsequent `slice!` works correctly. buffer.force_encoding(Encoding::BINARY) # This will be at least one copy: @buffer = buffer.byteslice(length, buffer.bytesize) # This should be zero-copy: buffer.slice!(length, buffer.bytesize) if buffer.empty? return nil else return buffer end else while chunk = read_next buffer << chunk end return buffer end end # Read at most `length` bytes from the stream. Will avoid reading from the underlying stream if possible. def read_partial(length = nil) if @buffer buffer = @buffer @buffer = nil else buffer = read_next end if buffer and length if buffer.bytesize > length # This ensures the subsequent `slice!` works correctly. buffer.force_encoding(Encoding::BINARY) @buffer = buffer.byteslice(length, buffer.bytesize) buffer.slice!(length, buffer.bytesize) end end return buffer end def gets read_partial end def each while chunk = read_partial yield chunk end end def read_nonblock(length, buffer = nil) @buffer ||= read_next chunk = nil unless @buffer buffer&.clear return end if @buffer.bytesize > length chunk = @buffer.byteslice(0, length) @buffer = @buffer.byteslice(length, @buffer.bytesize) else chunk = @buffer @buffer = nil end if buffer buffer.replace(chunk) else buffer = chunk end return buffer end end include Reader def write(buffer) if @output @output.write(buffer) return buffer.bytesize else raise IOError, "Stream is not writable, output has been closed!" end end def write_nonblock(buffer) write(buffer) end def <<(buffer) write(buffer) end def flush end def close_read @input&.close @input = nil end # close must never be called on the input stream. huh? def close_write if @output.respond_to?(:close) @output&.close end @output = nil end # Close the input and output bodies. def close(error = nil) self.close_read self.close_write return nil ensure @closed = true end # Whether the stream has been closed. def closed? @closed end # Whether there are any output chunks remaining? def empty? @output.empty? end private def read_next if @input return @input.read else @input = nil raise IOError, "Stream is not readable, input has been closed!" end end end end # frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. # Copyright, 2022, by Jeremy Evans. require 'webrick' require 'stringio' require 'rack/constants' require_relative '../handler' require_relative '../version' require_relative '../stream' module Rackup module Handler class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet def self.run(app, **options) environment = ENV['RACK_ENV'] || 'development' default_host = environment == 'development' ? 'localhost' : nil if !options[:BindAddress] || options[:Host] options[:BindAddress] = options.delete(:Host) || default_host end options[:Port] ||= 8080 if options[:SSLEnable] require 'webrick/https' end @server = ::WEBrick::HTTPServer.new(options) @server.mount "/", Rackup::Handler::WEBrick, app yield @server if block_given? @server.start end def self.valid_options environment = ENV['RACK_ENV'] || 'development' default_host = environment == 'development' ? 'localhost' : '0.0.0.0' { "Host=HOST" => "Hostname to listen on (default: #{default_host})", "Port=PORT" => "Port to listen on (default: 8080)", } end def self.shutdown if @server @server.shutdown @server = nil end end def initialize(server, app) super server @app = app end # This handles mapping the WEBrick request to a Rack input stream. class Input include Stream::Reader def initialize(request) @request = request @reader = Fiber.new do @request.body do |chunk| Fiber.yield(chunk) end Fiber.yield(nil) # End of stream: @reader = nil end end def close @request = nil @reader = nil end private # Read one chunk from the request body. def read_next @reader&.resume end end def service(req, res) env = req.meta_vars env.delete_if { |k, v| v.nil? } input = Input.new(req) env.update( ::Rack::RACK_INPUT => input, ::Rack::RACK_ERRORS => $stderr, ::Rack::RACK_URL_SCHEME => ["yes", "on", "1"].include?(env[::Rack::HTTPS]) ? "https" : "http", ::Rack::RACK_IS_HIJACK => true, ) env[::Rack::QUERY_STRING] ||= "" unless env[::Rack::PATH_INFO] == "" path, n = req.request_uri.path, env[::Rack::SCRIPT_NAME].length env[::Rack::PATH_INFO] = path[n, path.length - n] end env[::Rack::REQUEST_PATH] ||= [env[::Rack::SCRIPT_NAME], env[::Rack::PATH_INFO]].join status, headers, body = @app.call(env) begin res.status = status if value = headers[::Rack::RACK_HIJACK] io_lambda = value body = nil elsif !body.respond_to?(:to_path) && !body.respond_to?(:each) io_lambda = body body = nil end if value = headers.delete('set-cookie') res.cookies.concat(Array(value)) end headers.each do |key, value| # Skip keys starting with rack., per Rack SPEC next if key.start_with?('rack.') # Since WEBrick won't accept repeated headers, # merge the values per RFC 1945 section 4.2. value = value.join(", ") if Array === value res[key] = value end if io_lambda protocol = headers['rack.protocol'] || headers['upgrade'] if protocol # Set all the headers correctly for an upgrade response: res.upgrade!(protocol) end res.body = io_lambda elsif body.respond_to?(:to_path) res.body = ::File.open(body.to_path, 'rb') else buffer = String.new body.each do |part| buffer << part end res.body = buffer end ensure body.close if body.respond_to?(:close) end end end register :webrick, WEBrick end end # frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. module Rackup module Handler class CGI include Rack def self.run(app, **options) $stdin.binmode serve app end def self.serve(app) env = ENV.to_hash env.delete "HTTP_CONTENT_LENGTH" env[SCRIPT_NAME] = "" if env[SCRIPT_NAME] == "/" env.update( RACK_INPUT => $stdin, RACK_ERRORS => $stderr, RACK_URL_SCHEME => ["yes", "on", "1"].include?(ENV[HTTPS]) ? "https" : "http" ) env[QUERY_STRING] ||= "" env[REQUEST_PATH] ||= "/" status, headers, body = app.call(env) begin send_headers status, headers send_body body ensure body.close if body.respond_to? :close end end def self.send_headers(status, headers) $stdout.print "Status: #{status}\r\n" headers.each { |k, vs| vs.split("\n").each { |v| $stdout.print "#{k}: #{v}\r\n" } } $stdout.print "\r\n" $stdout.flush end def self.send_body(body) body.each { |part| $stdout.print part $stdout.flush } end end register :cgi, CGI end end # frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. require 'optparse' require 'fileutils' require 'rack/builder' require 'rack/common_logger' require 'rack/content_length' require 'rack/show_exceptions' require 'rack/lint' require 'rack/tempfile_reaper' require 'rack/version' require_relative 'version' require_relative 'handler' module Rackup class Server class Options def parse!(args) options = {} opt_parser = OptionParser.new("", 24, ' ') do |opts| opts.banner = "Usage: rackup [ruby options] [rack options] [rackup config]" opts.separator "" opts.separator "Ruby options:" lineno = 1 opts.on("-e", "--eval LINE", "evaluate a LINE of code") { |line| eval line, TOPLEVEL_BINDING, "-e", lineno lineno += 1 } opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") { options[:debug] = true } opts.on("-w", "--warn", "turn warnings on for your script") { options[:warn] = true } opts.on("-q", "--quiet", "turn off logging") { options[:quiet] = true } opts.on("-I", "--include PATH", "specify $LOAD_PATH (may be used more than once)") { |path| (options[:include] ||= []).concat(path.split(":")) } opts.on("-r", "--require LIBRARY", "require the library, before executing your script") { |library| (options[:require] ||= []) << library } opts.separator "" opts.separator "Rack options:" opts.on("-b", "--builder BUILDER_LINE", "evaluate a BUILDER_LINE of code as a builder script") { |line| options[:builder] = line } opts.on("-s", "--server SERVER", "serve using SERVER (thin/puma/webrick)") { |s| options[:server] = s } opts.on("-o", "--host HOST", "listen on HOST (default: localhost)") { |host| options[:Host] = host } opts.on("-p", "--port PORT", "use PORT (default: 9292)") { |port| options[:Port] = port } opts.on("-O", "--option NAME[=VALUE]", "pass VALUE to the server as option NAME. If no VALUE, sets it to true. Run '#{$0} -s SERVER -h' to get a list of options for SERVER") { |name| name, value = name.split('=', 2) value = true if value.nil? options[name.to_sym] = value } opts.on("-E", "--env ENVIRONMENT", "use ENVIRONMENT for defaults (default: development)") { |e| options[:environment] = e } opts.on("-D", "--daemonize", "run daemonized in the background") { |d| options[:daemonize] ||= true } opts.on("--daemonize-noclose", "run daemonized in the background without closing stdout/stderr") { options[:daemonize] = :noclose } opts.on("-P", "--pid FILE", "file to store PID") { |f| options[:pid] = ::File.expand_path(f) } opts.separator "" opts.separator "Profiling options:" opts.on("--heap HEAPFILE", "Build the application, then dump the heap to HEAPFILE") do |e| options[:heapfile] = e end opts.on("--profile PROFILE", "Dump CPU or Memory profile to PROFILE (defaults to a tempfile)") do |e| options[:profile_file] = e end opts.on("--profile-mode MODE", "Profile mode (cpu|wall|object)") do |e| unless %w[cpu wall object].include?(e) raise OptionParser::InvalidOption, "unknown profile mode: #{e}" end options[:profile_mode] = e.to_sym end opts.separator "" opts.separator "Common options:" opts.on_tail("-h", "-?", "--help", "Show this message") do puts opts puts handler_opts(options) exit end opts.on_tail("--version", "Show version") do puts "Rack #{Rack::RELEASE}" exit end end begin opt_parser.parse! args rescue OptionParser::InvalidOption => e warn e.message abort opt_parser.to_s end options[:config] = args.last if args.last && !args.last.empty? options end def handler_opts(options) info = [] server = Rackup::Handler.get(options[:server]) || Rackup::Handler.default if server && server.respond_to?(:valid_options) info << "" info << "Server-specific options for #{server.name}:" has_options = false server.valid_options.each do |name, description| next if /^(Host|Port)[^a-zA-Z]/.match?(name.to_s) # ignore handler's host and port options, we do our own. info << sprintf(" -O %-21s %s", name, description) has_options = true end return "" if !has_options end info.join("\n") rescue NameError, LoadError return "Warning: Could not find handler specified (#{options[:server] || 'default'}) to determine handler-specific options" end end # Start a new rack server (like running rackup). This will parse ARGV and # provide standard ARGV rackup options, defaulting to load 'config.ru'. # # Providing an options hash will prevent ARGV parsing and will not include # any default options. # # This method can be used to very easily launch a CGI application, for # example: # # Rack::Server.start( # :app => lambda do |e| # [200, {'content-type' => 'text/html'}, ['hello world']] # end, # :server => 'cgi' # ) # # Further options available here are documented on Rack::Server#initialize def self.start(options = nil) new(options).start end attr_writer :options # Options may include: # * :app # a rack application to run (overrides :config and :builder) # * :builder # a string to evaluate a Rack::Builder from # * :config # a rackup configuration file path to load (.ru) # * :environment # this selects the middleware that will be wrapped around # your application. Default options available are: # - development: CommonLogger, ShowExceptions, and Lint # - deployment: CommonLogger # - none: no extra middleware # note: when the server is a cgi server, CommonLogger is not included. # * :server # choose a specific Rackup::Handler, e.g. cgi, fcgi, webrick # * :daemonize # if truthy, the server will daemonize itself (fork, detach, etc) # if :noclose, the server will not close STDOUT/STDERR # * :pid # path to write a pid file after daemonize # * :Host # the host address to bind to (used by supporting Rackup::Handler) # * :Port # the port to bind to (used by supporting Rackup::Handler) # * :AccessLog # webrick access log options (or supporting Rackup::Handler) # * :debug # turn on debug output ($DEBUG = true) # * :warn # turn on warnings ($-w = true) # * :include # add given paths to $LOAD_PATH # * :require # require the given libraries # # Additional options for profiling app initialization include: # * :heapfile # location for ObjectSpace.dump_all to write the output to # * :profile_file # location for CPU/Memory (StackProf) profile output (defaults to a tempfile) # * :profile_mode # StackProf profile mode (cpu|wall|object) def initialize(options = nil) @ignore_options = [] if options @use_default_options = false @options = options @app = options[:app] if options[:app] else @use_default_options = true @options = parse_options(ARGV) end end def options merged_options = @use_default_options ? default_options.merge(@options) : @options merged_options.reject { |k, v| @ignore_options.include?(k) } end def default_options environment = ENV['RACK_ENV'] || 'development' default_host = environment == 'development' ? 'localhost' : '0.0.0.0' { environment: environment, pid: nil, Port: 9292, Host: default_host, AccessLog: [], config: "config.ru" } end def app @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config end class << self def logging_middleware lambda { |server| /CGI/.match?(server.server.name) || server.options[:quiet] ? nil : [Rack::CommonLogger, $stderr] } end def default_middleware_by_environment m = Hash.new {|h, k| h[k] = []} m["deployment"] = [ [Rack::ContentLength], logging_middleware, [Rack::TempfileReaper] ] m["development"] = [ [Rack::ContentLength], logging_middleware, [Rack::ShowExceptions], [Rack::Lint], [Rack::TempfileReaper] ] m end def middleware default_middleware_by_environment end end def middleware self.class.middleware end def start(&block) if options[:warn] $-w = true end if includes = options[:include] $LOAD_PATH.unshift(*includes) end Array(options[:require]).each do |library| require library end if options[:debug] $DEBUG = true require 'pp' p options[:server] pp wrapped_app pp app end check_pid! if options[:pid] # Touch the wrapped app, so that the config.ru is loaded before # daemonization (i.e. before chdir, etc). handle_profiling(options[:heapfile], options[:profile_mode], options[:profile_file]) do wrapped_app end daemonize_app if options[:daemonize] write_pid if options[:pid] trap(:INT) do if server.respond_to?(:shutdown) server.shutdown else exit end end server.run(wrapped_app, **options, &block) end def server @_server ||= Handler.get(options[:server]) || Handler.default end private def build_app_and_options_from_config if !::File.exist? options[:config] abort "configuration #{options[:config]} not found" end return Rack::Builder.parse_file(self.options[:config]) end def handle_profiling(heapfile, profile_mode, filename) if heapfile require "objspace" ObjectSpace.trace_object_allocations_start yield GC.start ::File.open(heapfile, "w") { |f| ObjectSpace.dump_all(output: f) } exit end if profile_mode require "stackprof" require "tempfile" make_profile_name(filename) do |filename| ::File.open(filename, "w") do |f| StackProf.run(mode: profile_mode, out: f) do yield end puts "Profile written to: #{filename}" end end exit end yield end def make_profile_name(filename) if filename yield filename else ::Dir::Tmpname.create("profile.dump") do |tmpname, _, _| yield tmpname end end end def build_app_from_string Rack::Builder.new_from_string(self.options[:builder]) end def parse_options(args) # Don't evaluate CGI ISINDEX parameters. args.clear if ENV.include?(Rack::REQUEST_METHOD) @options = opt_parser.parse!(args) @options[:config] = ::File.expand_path(options[:config]) ENV["RACK_ENV"] = options[:environment] @options end def opt_parser Options.new end def build_app(app) middleware[options[:environment]].reverse_each do |middleware| middleware = middleware.call(self) if middleware.respond_to?(:call) next unless middleware klass, *args = middleware app = klass.new(app, *args) end app end def wrapped_app @wrapped_app ||= build_app app end def daemonize_app # Cannot be covered as it forks # :nocov: Process.daemon(true, options[:daemonize] == :noclose) # :nocov: end def write_pid ::File.open(options[:pid], ::File::CREAT | ::File::EXCL | ::File::WRONLY ){ |f| f.write("#{Process.pid}") } at_exit { ::FileUtils.rm_f(options[:pid]) } rescue Errno::EEXIST check_pid! retry end def check_pid! return unless ::File.exist?(options[:pid]) pid = ::File.read(options[:pid]).to_i raise Errno::ESRCH if pid == 0 Process.kill(0, pid) exit_with_pid(pid) rescue Errno::ESRCH ::File.delete(options[:pid]) rescue Errno::EPERM exit_with_pid(pid) end def exit_with_pid(pid) $stderr.puts "A server is already running (pid: #{pid}, file: #{options[:pid]})." exit(1) end end end # frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. require 'zlib' require 'rack/constants' require 'rack/request' require 'rack/response' module Rackup # Paste has a Pony, Rack has a Lobster! class Lobster include Rack LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2 P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0 t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0]) LambdaLobster = lambda { |env| if env[QUERY_STRING].include?("flip") lobster = LobsterString.split("\n"). map { |line| line.ljust(42).reverse }. join("\n") href = "?" else lobster = LobsterString href = "?flip" end content = ["<title>Lobstericious!</title>", "<pre>", lobster, "</pre>", "<a href='#{href}'>flip!</a>"] length = content.inject(0) { |a, e| a + e.size }.to_s [200, { CONTENT_TYPE => "text/html", CONTENT_LENGTH => length }, content] } def call(env) req = Request.new(env) if req.GET["flip"] == "left" lobster = LobsterString.split("\n").map do |line| line.ljust(42).reverse. gsub('\\', 'TEMP'). gsub('/', '\\'). gsub('TEMP', '/'). gsub('{', '}'). gsub('(', ')') end.join("\n") href = "?flip=right" elsif req.GET["flip"] == "crash" raise "Lobster crashed" else lobster = LobsterString href = "?flip=left" end res = Response.new res.write "<title>Lobstericious!</title>" res.write "<pre>" res.write lobster res.write "</pre>" res.write "<p><a href='#{href}'>flip!</a></p>" res.write "<p><a href='?flip=crash'>crash!</a></p>" res.finish end end end if $0 == __FILE__ # :nocov: require_relative 'server' require_relative 'show_exceptions' require_relative 'lint' Rackup::Server.start( app: Rack::ShowExceptions.new(Rack::Lint.new(Rackup::Lobster.new)), Port: 9292 ) # :nocov: end # frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. module Rackup VERSION = "2.1.0" end # frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. module Rackup # *Handlers* connect web servers with Rack. # # Rackup includes Handlers for WEBrick and CGI. # # Handlers usually are activated by calling <tt>MyHandler.run(myapp)</tt>. # A second optional hash can be passed to include server-specific # configuration. module Handler @handlers = {} # Register a named handler class. def self.register(name, klass) if klass.is_a?(String) warn "Calling Rackup::Handler.register with a string is deprecated, use the class/module itself.", uplevel: 1 klass = self.const_get(klass, false) end name = name.to_sym @handlers[name] = klass end def self.[](name) name = name.to_sym begin @handlers[name] || self.const_get(name, false) rescue NameError # Ignore. end end def self.get(name) return nil unless name name = name.to_sym if server = self[name] return server end begin require_handler("rackup/handler", name) rescue LoadError require_handler("rack/handler", name) end return self[name] end RACK_HANDLER = 'RACK_HANDLER' RACKUP_HANDLER = 'RACKUP_HANDLER' SERVER_NAMES = %i(puma falcon webrick).freeze private_constant :SERVER_NAMES # Select first available Rack handler given an `Array` of server names. # Raises `LoadError` if no handler was found. # # > pick ['puma', 'webrick'] # => Rackup::Handler::WEBrick def self.pick(server_names) server_names = Array(server_names) server_names.each do |server_name| begin server = self.get(server_name) return server if server rescue LoadError # Ignore. end end raise LoadError, "Couldn't find handler for: #{server_names.join(', ')}." end def self.default if rack_handler = ENV[RACKUP_HANDLER] self.get(rack_handler) elsif rack_handler = ENV[RACK_HANDLER] warn "RACK_HANDLER is deprecated, use RACKUP_HANDLER." self.get(rack_handler) else pick SERVER_NAMES end end # Transforms server-name constants to their canonical form as filenames, # then tries to require them but silences the LoadError if not found # # Naming convention: # # Foo # => 'foo' # FooBar # => 'foo_bar.rb' # FooBAR # => 'foobar.rb' # FOObar # => 'foobar.rb' # FOOBAR # => 'foobar.rb' # FooBarBaz # => 'foo_bar_baz.rb' def self.require_handler(prefix, const_name) file = const_name.to_s.gsub(/^[A-Z]+/) { |pre| pre.downcase }. gsub(/[A-Z]+[^A-Z]/, '_\&').downcase require(::File.join(prefix, file)) end end end # frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. require_relative 'rackup/handler' require_relative 'rackup/server' require_relative 'rackup/version' require_relative 'rackup/handler/webrick' require_relative 'rackup/handler/cgi' # MIT License Copyright, 2007-2009, by Leah Neukirchen. Copyright, 2008, by Marc-André Cournoyer. Copyright, 2009, by Aaron Pfeifer. Copyright, 2009-2010, by Megan Batty. Copyright, 2009-2010, by Michael Fellinger. Copyright, 2009, by Genki Takiuchi. Copyright, 2009, by Joshua Peek. Copyright, 2009, by Yehuda Katz + Carl Lerche. Copyright, 2009, by Carl Lerche. Copyright, 2010, by Julik Tarkhanov. Copyright, 2010-2016, by James Tucker. Copyright, 2010, by Timur Batyrshin. Copyright, 2010, by Loren Segal. Copyright, 2010, by Andrew Bortz. Copyright, 2010, by John Barnette. Copyright, 2010, by John Sumsion. Copyright, 2011-2018, by Aaron Patterson. Copyright, 2011, by Konstantin Haase. Copyright, 2011, by Blake Mizerany. Copyright, 2011, by Tsutomu Kuroda. Copyright, 2012, by Jean Boussier. Copyright, 2012, by Trevor Wennblom. Copyright, 2012, by Anurag Priyam. Copyright, 2012, by Hrvoje Šimić. Copyright, 2013, by Uchio KONDO. Copyright, 2013, by Tim Moore. Copyright, 2013, by Postmodern. Copyright, 2013, by Bas Vodde. Copyright, 2013, by Joe Fiorini. Copyright, 2014, by Wyatt Pan. Copyright, 2014, by Lenny Marks. Copyright, 2014, by Igor Bochkariov. Copyright, 2014, by Max Cantor. Copyright, 2014, by David Celis. Copyright, 2014, by Rafael Mendonça França. Copyright, 2014, by Jeremy Kemper. Copyright, 2014, by Richard Schneeman. Copyright, 2015, by Peter Wilmott. Copyright, 2015, by Sean McGivern. Copyright, 2015, by Tadashi Saito. Copyright, 2015, by deepj. Copyright, 2015, by Zachary Scott. Copyright, 2016, by Sophie Deziel. Copyright, 2016, by Kazuya Hotta. Copyright, 2017, by Ryunosuke Sato. Copyright, 2017-2023, by Samuel Williams. Copyright, 2018, by Dillon Welch. Copyright, 2018, by Yoshiyuki Hirano. Copyright, 2018, by Nick LaMuro. Copyright, 2019, by Rafael França. Copyright, 2019, by Krzysztof Rybka. Copyright, 2019, by Misaki Shioi. Copyright, 2020-2022, by Jeremy Evans. Copyright, 2021, by Katsuhiko YOSHIDA. Copyright, 2021, by KS. Copyright, 2021, by Stephen Paul Weber. Copyright, 2022, by Akira Matsuda. Copyright, 2022, by Andrew Hoglund. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #!/usr/bin/env ruby # frozen_string_literal: true require_relative "../lib/rackup" Rackup::Server.start # Security Policy Please see our main security policy: https://github.com/rack/rack/security/policy # frozen_string_literal: false # #-- # bigdecimal/util extends various native classes to provide the #to_d method, # and provides BigDecimal#to_d and BigDecimal#to_digits. #++ require 'bigdecimal' class Integer < Numeric # call-seq: # int.to_d -> bigdecimal # # Returns the value of +int+ as a BigDecimal. # # require 'bigdecimal' # require 'bigdecimal/util' # # 42.to_d # => 0.42e2 # # See also Kernel.BigDecimal. # def to_d BigDecimal(self) end end class Float < Numeric # call-seq: # float.to_d -> bigdecimal # float.to_d(precision) -> bigdecimal # # Returns the value of +float+ as a BigDecimal. # The +precision+ parameter is used to determine the number of # significant digits for the result. When +precision+ is set to +0+, # the number of digits to represent the float being converted is determined # automatically. # The default +precision+ is +0+. # # require 'bigdecimal' # require 'bigdecimal/util' # # 0.5.to_d # => 0.5e0 # 1.234.to_d # => 0.1234e1 # 1.234.to_d(2) # => 0.12e1 # # See also Kernel.BigDecimal. # def to_d(precision=0) BigDecimal(self, precision) end end class String # call-seq: # str.to_d -> bigdecimal # # Returns the result of interpreting leading characters in +str+ # as a BigDecimal. # # require 'bigdecimal' # require 'bigdecimal/util' # # "0.5".to_d # => 0.5e0 # "123.45e1".to_d # => 0.12345e4 # "45.67 degrees".to_d # => 0.4567e2 # # See also Kernel.BigDecimal. # def to_d BigDecimal.interpret_loosely(self) end end class BigDecimal < Numeric # call-seq: # a.to_digits -> string # # Converts a BigDecimal to a String of the form "nnnnnn.mmm". # This method is deprecated; use BigDecimal#to_s("F") instead. # # require 'bigdecimal/util' # # d = BigDecimal("3.14") # d.to_digits # => "3.14" # def to_digits if self.nan? || self.infinite? || self.zero? self.to_s else i = self.to_i.to_s _,f,_,z = self.frac.split i + "." + ("0"*(-z)) + f end end # call-seq: # a.to_d -> bigdecimal # # Returns self. # # require 'bigdecimal/util' # # d = BigDecimal("3.14") # d.to_d # => 0.314e1 # def to_d self end end class Rational < Numeric # call-seq: # rat.to_d(precision) -> bigdecimal # # Returns the value as a BigDecimal. # # The required +precision+ parameter is used to determine the number of # significant digits for the result. # # require 'bigdecimal' # require 'bigdecimal/util' # # Rational(22, 7).to_d(3) # => 0.314e1 # # See also Kernel.BigDecimal. # def to_d(precision) BigDecimal(self, precision) end end class Complex < Numeric # call-seq: # cmp.to_d -> bigdecimal # cmp.to_d(precision) -> bigdecimal # # Returns the value as a BigDecimal. # # The +precision+ parameter is required for a rational complex number. # This parameter is used to determine the number of significant digits # for the result. # # require 'bigdecimal' # require 'bigdecimal/util' # # Complex(0.1234567, 0).to_d(4) # => 0.1235e0 # Complex(Rational(22, 7), 0).to_d(3) # => 0.314e1 # # See also Kernel.BigDecimal. # def to_d(*args) BigDecimal(self) unless self.imag.zero? # to raise eerror if args.length == 0 case self.real when Rational BigDecimal(self.real) # to raise error end end self.real.to_d(*args) end end class NilClass # call-seq: # nil.to_d -> bigdecimal # # Returns nil represented as a BigDecimal. # # require 'bigdecimal' # require 'bigdecimal/util' # # nil.to_d # => 0.0 # def to_d BigDecimal(0) end end # frozen_string_literal: false require 'bigdecimal' # # Solves a*x = b for x, using LU decomposition. # module LUSolve module_function # Performs LU decomposition of the n by n matrix a. def ludecomp(a,n,zero=0,one=1) prec = BigDecimal.limit(nil) ps = [] scales = [] for i in 0...n do # pick up largest(abs. val.) element in each row. ps <<= i nrmrow = zero ixn = i*n for j in 0...n do biggst = a[ixn+j].abs nrmrow = biggst if biggst>nrmrow end if nrmrow>zero then scales <<= one.div(nrmrow,prec) else raise "Singular matrix" end end n1 = n - 1 for k in 0...n1 do # Gaussian elimination with partial pivoting. biggst = zero; for i in k...n do size = a[ps[i]*n+k].abs*scales[ps[i]] if size>biggst then biggst = size pividx = i end end raise "Singular matrix" if biggst<=zero if pividx!=k then j = ps[k] ps[k] = ps[pividx] ps[pividx] = j end pivot = a[ps[k]*n+k] for i in (k+1)...n do psin = ps[i]*n a[psin+k] = mult = a[psin+k].div(pivot,prec) if mult!=zero then pskn = ps[k]*n for j in (k+1)...n do a[psin+j] -= mult.mult(a[pskn+j],prec) end end end end raise "Singular matrix" if a[ps[n1]*n+n1] == zero ps end # Solves a*x = b for x, using LU decomposition. # # a is a matrix, b is a constant vector, x is the solution vector. # # ps is the pivot, a vector which indicates the permutation of rows performed # during LU decomposition. def lusolve(a,b,ps,zero=0.0) prec = BigDecimal.limit(nil) n = ps.size x = [] for i in 0...n do dot = zero psin = ps[i]*n for j in 0...i do dot = a[psin+j].mult(x[j],prec) + dot end x <<= b[ps[i]] - dot end (n-1).downto(0) do |i| dot = zero psin = ps[i]*n for j in (i+1)...n do dot = a[psin+j].mult(x[j],prec) + dot end x[i] = (x[i]-dot).div(a[psin+i],prec) end x end end # frozen_string_literal: false require "bigdecimal/ludcmp" require "bigdecimal/jacobian" # # newton.rb # # Solves the nonlinear algebraic equation system f = 0 by Newton's method. # This program is not dependent on BigDecimal. # # To call: # n = nlsolve(f,x) # where n is the number of iterations required, # x is the initial value vector # f is an Object which is used to compute the values of the equations to be solved. # It must provide the following methods: # # f.values(x):: returns the values of all functions at x # # f.zero:: returns 0.0 # f.one:: returns 1.0 # f.two:: returns 2.0 # f.ten:: returns 10.0 # # f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal. # # On exit, x is the solution vector. # module Newton include LUSolve include Jacobian module_function def norm(fv,zero=0.0) # :nodoc: s = zero n = fv.size for i in 0...n do s += fv[i]*fv[i] end s end # See also Newton def nlsolve(f,x) nRetry = 0 n = x.size f0 = f.values(x) zero = f.zero one = f.one two = f.two p5 = one/two d = norm(f0,zero) minfact = f.ten*f.ten*f.ten minfact = one/minfact e = f.eps while d >= e do nRetry += 1 # Not yet converged. => Compute Jacobian matrix dfdx = jacobian(f,f0,x) # Solve dfdx*dx = -f0 to estimate dx dx = lusolve(dfdx,f0,ludecomp(dfdx,n,zero,one),zero) fact = two xs = x.dup begin fact *= p5 if fact < minfact then raise "Failed to reduce function values." end for i in 0...n do x[i] = xs[i] - dx[i]*fact end f0 = f.values(x) dn = norm(f0,zero) end while(dn>=d) d = dn end nRetry end end # frozen_string_literal: false require 'bigdecimal' # require 'bigdecimal/jacobian' # # Provides methods to compute the Jacobian matrix of a set of equations at a # point x. In the methods below: # # f is an Object which is used to compute the Jacobian matrix of the equations. # It must provide the following methods: # # f.values(x):: returns the values of all functions at x # # f.zero:: returns 0.0 # f.one:: returns 1.0 # f.two:: returns 2.0 # f.ten:: returns 10.0 # # f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal. # # x is the point at which to compute the Jacobian. # # fx is f.values(x). # module Jacobian module_function # Determines the equality of two numbers by comparing to zero, or using the epsilon value def isEqual(a,b,zero=0.0,e=1.0e-8) aa = a.abs bb = b.abs if aa == zero && bb == zero then true else if ((a-b)/(aa+bb)).abs < e then true else false end end end # Computes the derivative of +f[i]+ at +x[i]+. # +fx+ is the value of +f+ at +x+. def dfdxi(f,fx,x,i) nRetry = 0 n = x.size xSave = x[i] ok = 0 ratio = f.ten*f.ten*f.ten dx = x[i].abs/ratio dx = fx[i].abs/ratio if isEqual(dx,f.zero,f.zero,f.eps) dx = f.one/f.ten if isEqual(dx,f.zero,f.zero,f.eps) until ok>0 do deriv = [] nRetry += 1 if nRetry > 100 raise "Singular Jacobian matrix. No change at x[" + i.to_s + "]" end dx = dx*f.two x[i] += dx fxNew = f.values(x) for j in 0...n do if !isEqual(fxNew[j],fx[j],f.zero,f.eps) then ok += 1 deriv <<= (fxNew[j]-fx[j])/dx else deriv <<= f.zero end end x[i] = xSave end deriv end # Computes the Jacobian of +f+ at +x+. +fx+ is the value of +f+ at +x+. def jacobian(f,fx,x) n = x.size dfdx = Array.new(n*n) for i in 0...n do df = dfdxi(f,fx,x,i) for j in 0...n do dfdx[j*n+i] = df[j] end end dfdx end end # frozen_string_literal: false require 'bigdecimal' # #-- # Contents: # sqrt(x, prec) # sin (x, prec) # cos (x, prec) # atan(x, prec) Note: |x|<1, x=0.9999 may not converge. # PI (prec) # E (prec) == exp(1.0,prec) # # where: # x ... BigDecimal number to be computed. # |x| must be small enough to get convergence. # prec ... Number of digits to be obtained. #++ # # Provides mathematical functions. # # Example: # # require "bigdecimal/math" # # include BigMath # # a = BigDecimal((PI(100)/2).to_s) # puts sin(a,100) # => 0.99999999999999999999......e0 # module BigMath module_function # call-seq: # sqrt(decimal, numeric) -> BigDecimal # # Computes the square root of +decimal+ to the specified number of digits of # precision, +numeric+. # # BigMath.sqrt(BigDecimal('2'), 16).to_s # #=> "0.1414213562373095048801688724e1" # def sqrt(x, prec) x.sqrt(prec) end # call-seq: # sin(decimal, numeric) -> BigDecimal # # Computes the sine of +decimal+ to the specified number of digits of # precision, +numeric+. # # If +decimal+ is Infinity or NaN, returns NaN. # # BigMath.sin(BigMath.PI(5)/4, 5).to_s # #=> "0.70710678118654752440082036563292800375e0" # def sin(x, prec) raise ArgumentError, "Zero or negative precision for sin" if prec <= 0 return BigDecimal("NaN") if x.infinite? || x.nan? n = prec + BigDecimal.double_fig one = BigDecimal("1") two = BigDecimal("2") x = -x if neg = x < 0 if x > (twopi = two * BigMath.PI(prec)) if x > 30 x %= twopi else x -= twopi while x > twopi end end x1 = x x2 = x.mult(x,n) sign = 1 y = x d = y i = one z = one while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0) m = BigDecimal.double_fig if m < BigDecimal.double_fig sign = -sign x1 = x2.mult(x1,n) i += two z *= (i-one) * i d = sign * x1.div(z,m) y += d end neg ? -y : y end # call-seq: # cos(decimal, numeric) -> BigDecimal # # Computes the cosine of +decimal+ to the specified number of digits of # precision, +numeric+. # # If +decimal+ is Infinity or NaN, returns NaN. # # BigMath.cos(BigMath.PI(4), 16).to_s # #=> "-0.999999999999999999999999999999856613163740061349e0" # def cos(x, prec) raise ArgumentError, "Zero or negative precision for cos" if prec <= 0 return BigDecimal("NaN") if x.infinite? || x.nan? n = prec + BigDecimal.double_fig one = BigDecimal("1") two = BigDecimal("2") x = -x if x < 0 if x > (twopi = two * BigMath.PI(prec)) if x > 30 x %= twopi else x -= twopi while x > twopi end end x1 = one x2 = x.mult(x,n) sign = 1 y = one d = y i = BigDecimal("0") z = one while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0) m = BigDecimal.double_fig if m < BigDecimal.double_fig sign = -sign x1 = x2.mult(x1,n) i += two z *= (i-one) * i d = sign * x1.div(z,m) y += d end y end # call-seq: # atan(decimal, numeric) -> BigDecimal # # Computes the arctangent of +decimal+ to the specified number of digits of # precision, +numeric+. # # If +decimal+ is NaN, returns NaN. # # BigMath.atan(BigDecimal('-1'), 16).to_s # #=> "-0.785398163397448309615660845819878471907514682065e0" # def atan(x, prec) raise ArgumentError, "Zero or negative precision for atan" if prec <= 0 return BigDecimal("NaN") if x.nan? pi = PI(prec) x = -x if neg = x < 0 return pi.div(neg ? -2 : 2, prec) if x.infinite? return pi / (neg ? -4 : 4) if x.round(prec) == 1 x = BigDecimal("1").div(x, prec) if inv = x > 1 x = (-1 + sqrt(1 + x**2, prec))/x if dbl = x > 0.5 n = prec + BigDecimal.double_fig y = x d = y t = x r = BigDecimal("3") x2 = x.mult(x,n) while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0) m = BigDecimal.double_fig if m < BigDecimal.double_fig t = -t.mult(x2,n) d = t.div(r,m) y += d r += 2 end y *= 2 if dbl y = pi / 2 - y if inv y = -y if neg y end # call-seq: # PI(numeric) -> BigDecimal # # Computes the value of pi to the specified number of digits of precision, # +numeric+. # # BigMath.PI(10).to_s # #=> "0.3141592653589793238462643388813853786957412e1" # def PI(prec) raise ArgumentError, "Zero or negative precision for PI" if prec <= 0 n = prec + BigDecimal.double_fig zero = BigDecimal("0") one = BigDecimal("1") two = BigDecimal("2") m25 = BigDecimal("-0.04") m57121 = BigDecimal("-57121") pi = zero d = one k = one t = BigDecimal("-80") while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0) m = BigDecimal.double_fig if m < BigDecimal.double_fig t = t*m25 d = t.div(k,m) k = k+two pi = pi + d end d = one k = one t = BigDecimal("956") while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0) m = BigDecimal.double_fig if m < BigDecimal.double_fig t = t.div(m57121,n) d = t.div(k,m) pi = pi + d k = k+two end pi end # call-seq: # E(numeric) -> BigDecimal # # Computes e (the base of natural logarithms) to the specified number of # digits of precision, +numeric+. # # BigMath.E(10).to_s # #=> "0.271828182845904523536028752390026306410273e1" # def E(prec) raise ArgumentError, "Zero or negative precision for E" if prec <= 0 BigMath.exp(1, prec) end end = RAKE -- Ruby Make home :: https://github.com/ruby/rake bugs :: https://github.com/ruby/rake/issues docs :: https://ruby.github.io/rake == Description Rake is a Make-like program implemented in Ruby. Tasks and dependencies are specified in standard Ruby syntax. Rake has the following features: * Rakefiles (rake's version of Makefiles) are completely defined in standard Ruby syntax. No XML files to edit. No quirky Makefile syntax to worry about (is that a tab or a space?) * Users can specify tasks with prerequisites. * Rake supports rule patterns to synthesize implicit tasks. * Flexible FileLists that act like arrays but know about manipulating file names and paths. * A library of prepackaged tasks to make building rakefiles easier. For example, tasks for building tarballs. (Formerly tasks for building RDoc, Gems, and publishing to FTP were included in rake but they're now available in RDoc, RubyGems, and rake-contrib respectively.) * Supports parallel execution of tasks. == Installation === Gem Installation Download and install rake with the following. gem install rake == Usage === Simple Example First, you must write a "Rakefile" file which contains the build rules. Here's a simple example: task default: %w[test] task :test do ruby "test/unittest.rb" end This Rakefile has two tasks: * A task named "test", which -- upon invocation -- will run a unit test file in Ruby. * A task named "default". This task does nothing by itself, but it has exactly one dependency, namely the "test" task. Invoking the "default" task will cause Rake to invoke the "test" task as well. Running the "rake" command without any options will cause it to run the "default" task in the Rakefile: % ls Rakefile test/ % rake (in /home/some_user/Projects/rake) ruby test/unittest.rb ....unit test output here... Type "rake --help" for all available options. == Resources === Rake Information * {Rake command-line}[link:doc/command_line_usage.rdoc] * {Writing Rakefiles}[link:doc/rakefile.rdoc] * The original {Rake announcement}[link:doc/rational.rdoc] * Rake {glossary}[link:doc/glossary.rdoc] === Presentations and Articles about Rake * Avdi Grimm's rake series: 1. {Rake Basics}[https://avdi.codes/rake-part-1-basics/] 2. {Rake File Lists}[https://avdi.codes/rake-part-2-file-lists-2/] 3. {Rake Rules}[https://avdi.codes/rake-part-3-rules/] 4. {Rake Pathmap}[https://avdi.codes/rake-part-4-pathmap/] 5. {File Operations}[https://avdi.codes/rake-part-5-file-operations/] 6. {Clean and Clobber}[https://avdi.codes/rake-part-6-clean-and-clobber/] 7. {MultiTask}[https://avdi.codes/rake-part-7-multitask/] * {Jim Weirich's 2003 RubyConf presentation}[https://web.archive.org/web/20140221123354/http://onestepback.org/articles/buildingwithrake/] * Martin Fowler's article on Rake: https://martinfowler.com/articles/rake.html == Other Make Re-envisionings ... Rake is a late entry in the make replacement field. Here are links to other projects with similar (and not so similar) goals. * https://directory.fsf.org/wiki/Bras -- Bras, one of earliest implementations of "make in a scripting language". * http://www.a-a-p.org -- Make in Python * https://ant.apache.org -- The Ant project * https://search.cpan.org/search?query=PerlBuildSystem -- The Perl Build System * https://www.rubydoc.info/gems/rant/0.5.7/frames -- Rant, another Ruby make tool. == Credits [<b>Jim Weirich</b>] Who originally created Rake. [<b>Ryan Dlugosz</b>] For the initial conversation that sparked Rake. [<b>Nobuyoshi Nakada <nobu@ruby-lang.org></b>] For the initial patch for rule support. [<b>Tilman Sauerbeck <tilman@code-monkey.de></b>] For the recursive rule patch. [<b>Eric Hodel</b>] For aid in maintaining rake. [<b>Hiroshi SHIBATA</b>] Maintainer of Rake 10 and later == License Rake is available under an MIT-style license. :include: MIT-LICENSE --- = Other stuff Author:: Jim Weirich <jim.weirich@gmail.com> Requires:: Ruby 2.0.0 or later License:: Copyright Jim Weirich. Released under an MIT-style license. See the MIT-LICENSE file included in the distribution. == Warranty This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. == Historical Rake was originally created by Jim Weirich, who unfortunately passed away in February 2014. This repository was originally hosted at {github.com/jimweirich/rake}[https://github.com/jimweirich/rake/], however with his passing, has been moved to {ruby/rake}[https://github.com/ruby/rake]. You can view Jim's last commit here: https://github.com/jimweirich/rake/tree/336559f28f55bce418e2ebcc0a57548dcbac4025 You can {read more about Jim}[https://en.wikipedia.org/wiki/Jim_Weirich] at Wikipedia. Thank you for this great tool, Jim. We'll remember you. # frozen_string_literal: true #-- # Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. #++ module Rake; end require "rake/version" require "rbconfig" require "fileutils" require "singleton" require "monitor" require "optparse" require "ostruct" require "rake/ext/string" require "rake/win32" require "rake/linked_list" require "rake/cpu_counter" require "rake/scope" require "rake/task_argument_error" require "rake/rule_recursion_overflow_error" require "rake/rake_module" require "rake/trace_output" require "rake/pseudo_status" require "rake/task_arguments" require "rake/invocation_chain" require "rake/task" require "rake/file_task" require "rake/file_creation_task" require "rake/multi_task" require "rake/dsl_definition" require "rake/file_utils_ext" require "rake/file_list" require "rake/default_loader" require "rake/early_time" require "rake/late_time" require "rake/name_space" require "rake/task_manager" require "rake/application" require "rake/backtrace" $trace = false # :stopdoc: # # Some top level Constants. FileList = Rake::FileList RakeFileUtils = Rake::FileUtilsExt # frozen_string_literal: true module Rake # The TaskManager module is a mixin for managing tasks. module TaskManager # Track the last comment made in the Rakefile. attr_accessor :last_description def initialize # :nodoc: super @tasks = Hash.new @rules = Array.new @scope = Scope.make @last_description = nil end def create_rule(*args, &block) # :nodoc: pattern, args, deps, order_only = resolve_args(args) pattern = Regexp.new(Regexp.quote(pattern) + "$") if String === pattern @rules << [pattern, args, deps, order_only, block] end def define_task(task_class, *args, &block) # :nodoc: task_name, arg_names, deps, order_only = resolve_args(args) original_scope = @scope if String === task_name and not task_class.ancestors.include? Rake::FileTask task_name, *definition_scope = *(task_name.split(":").reverse) @scope = Scope.make(*(definition_scope + @scope.to_a)) end task_name = task_class.scope_name(@scope, task_name) task = intern(task_class, task_name) task.set_arg_names(arg_names) unless arg_names.empty? if Rake::TaskManager.record_task_metadata add_location(task) task.add_description(get_description(task)) end task.enhance(Task.format_deps(deps), &block) task | order_only unless order_only.nil? task ensure @scope = original_scope end # Lookup a task. Return an existing task if found, otherwise # create a task of the current type. def intern(task_class, task_name) @tasks[task_name.to_s] ||= task_class.new(task_name, self) end # Find a matching task for +task_name+. def [](task_name, scopes=nil) task_name = task_name.to_s self.lookup(task_name, scopes) or enhance_with_matching_rule(task_name) or synthesize_file_task(task_name) or fail generate_message_for_undefined_task(task_name) end def generate_message_for_undefined_task(task_name) message = "Don't know how to build task '#{task_name}' "\ "(See the list of available tasks with `#{Rake.application.name} --tasks`)" message + generate_did_you_mean_suggestions(task_name) end def generate_did_you_mean_suggestions(task_name) return "" unless defined?(::DidYouMean::SpellChecker) suggestions = ::DidYouMean::SpellChecker.new(dictionary: @tasks.keys).correct(task_name.to_s) if ::DidYouMean.respond_to?(:formatter)# did_you_mean v1.2.0 or later ::DidYouMean.formatter.message_for(suggestions) elsif defined?(::DidYouMean::Formatter) # before did_you_mean v1.2.0 ::DidYouMean::Formatter.new(suggestions).to_s else "" end end def synthesize_file_task(task_name) # :nodoc: return nil unless File.exist?(task_name) define_task(Rake::FileTask, task_name) end # Resolve the arguments for a task/rule. Returns a tuple of # [task_name, arg_name_list, prerequisites, order_only_prerequisites]. def resolve_args(args) if args.last.is_a?(Hash) deps = args.pop resolve_args_with_dependencies(args, deps) else resolve_args_without_dependencies(args) end end # Resolve task arguments for a task or rule when there are no # dependencies declared. # # The patterns recognized by this argument resolving function are: # # task :t # task :t, [:a] # def resolve_args_without_dependencies(args) task_name = args.shift if args.size == 1 && args.first.respond_to?(:to_ary) arg_names = args.first.to_ary else arg_names = args end [task_name, arg_names, [], nil] end private :resolve_args_without_dependencies # Resolve task arguments for a task or rule when there are # dependencies declared. # # The patterns recognized by this argument resolving function are: # # task :t, order_only: [:e] # task :t => [:d] # task :t => [:d], order_only: [:e] # task :t, [a] => [:d] # task :t, [a] => [:d], order_only: [:e] # def resolve_args_with_dependencies(args, hash) # :nodoc: fail "Task Argument Error" if hash.size != 1 && (hash.size != 2 || !hash.key?(:order_only)) order_only = hash.delete(:order_only) key, value = hash.map { |k, v| [k, v] }.first if args.empty? task_name = key arg_names = [] deps = value || [] else task_name = args.shift arg_names = key || args.shift|| [] deps = value || [] end deps = [deps] unless deps.respond_to?(:to_ary) [task_name, arg_names, deps, order_only] end private :resolve_args_with_dependencies # If a rule can be found that matches the task name, enhance the # task with the prerequisites and actions from the rule. Set the # source attribute of the task appropriately for the rule. Return # the enhanced task or nil of no rule was found. def enhance_with_matching_rule(task_name, level=0) fail Rake::RuleRecursionOverflowError, "Rule Recursion Too Deep" if level >= 16 @rules.each do |pattern, args, extensions, order_only, block| if pattern && pattern.match(task_name) task = attempt_rule(task_name, pattern, args, extensions, block, level) task | order_only unless order_only.nil? return task if task end end nil rescue Rake::RuleRecursionOverflowError => ex ex.add_target(task_name) fail ex end # List of all defined tasks in this application. def tasks @tasks.values.sort_by { |t| t.name } end # List of all the tasks defined in the given scope (and its # sub-scopes). def tasks_in_scope(scope) prefix = scope.path tasks.select { |t| /^#{prefix}:/ =~ t.name } end # Clear all tasks in this application. def clear @tasks.clear @rules.clear end # Lookup a task, using scope and the scope hints in the task name. # This method performs straight lookups without trying to # synthesize file tasks or rules. Special scope names (e.g. '^') # are recognized. If no scope argument is supplied, use the # current scope. Return nil if the task cannot be found. def lookup(task_name, initial_scope=nil) initial_scope ||= @scope task_name = task_name.to_s if task_name =~ /^rake:/ scopes = Scope.make task_name = task_name.sub(/^rake:/, "") elsif task_name =~ /^(\^+)/ scopes = initial_scope.trim($1.size) task_name = task_name.sub(/^(\^+)/, "") else scopes = initial_scope end lookup_in_scope(task_name, scopes) end # Lookup the task name def lookup_in_scope(name, scope) loop do tn = scope.path_with_task_name(name) task = @tasks[tn] return task if task break if scope.empty? scope = scope.tail end nil end private :lookup_in_scope # Return the list of scope names currently active in the task # manager. def current_scope @scope end # Evaluate the block in a nested namespace named +name+. Create # an anonymous namespace if +name+ is nil. def in_namespace(name) name ||= generate_name @scope = Scope.new(name, @scope) ns = NameSpace.new(self, @scope) yield(ns) ns ensure @scope = @scope.tail end private # Add a location to the locations field of the given task. def add_location(task) loc = find_location task.locations << loc if loc task end # Find the location that called into the dsl layer. def find_location locations = caller i = 0 while locations[i] return locations[i + 1] if locations[i] =~ /rake\/dsl_definition.rb/ i += 1 end nil end # Generate an anonymous namespace name. def generate_name @seed ||= 0 @seed += 1 "_anon_#{@seed}" end def trace_rule(level, message) # :nodoc: options.trace_output.puts "#{" " * level}#{message}" if Rake.application.options.trace_rules end # Attempt to create a rule given the list of prerequisites. def attempt_rule(task_name, task_pattern, args, extensions, block, level) sources = make_sources(task_name, task_pattern, extensions) prereqs = sources.map { |source| trace_rule level, "Attempting Rule #{task_name} => #{source}" if File.exist?(source) || Rake::Task.task_defined?(source) trace_rule level, "(#{task_name} => #{source} ... EXIST)" source elsif parent = enhance_with_matching_rule(source, level + 1) trace_rule level, "(#{task_name} => #{source} ... ENHANCE)" parent.name else trace_rule level, "(#{task_name} => #{source} ... FAIL)" return nil end } task = FileTask.define_task(task_name, { args => prereqs }, &block) task.sources = prereqs task end # Make a list of sources from the list of file name extensions / # translation procs. def make_sources(task_name, task_pattern, extensions) result = extensions.map { |ext| case ext when /%/ task_name.pathmap(ext) when %r{/} ext when /^\./ source = task_name.sub(task_pattern, ext) source == ext ? task_name.ext(ext) : source when String, Symbol ext.to_s when Proc, Method if ext.arity == 1 ext.call(task_name) else ext.call end else fail "Don't know how to handle rule dependent: #{ext.inspect}" end } result.flatten end # Return the current description, clearing it in the process. def get_description(task) desc = @last_description @last_description = nil desc end class << self attr_accessor :record_task_metadata # :nodoc: TaskManager.record_task_metadata = false end end end # frozen_string_literal: true require "rake/private_reader" module Rake class ThreadHistoryDisplay # :nodoc: all include Rake::PrivateReader private_reader :stats, :items, :threads def initialize(stats) @stats = stats @items = { _seq_: 1 } @threads = { _seq_: "A" } end def show puts "Job History:" stats.each do |stat| stat[:data] ||= {} rename(stat, :thread, threads) rename(stat[:data], :item_id, items) rename(stat[:data], :new_thread, threads) rename(stat[:data], :deleted_thread, threads) printf("%8d %2s %-20s %s\n", (stat[:time] * 1_000_000).round, stat[:thread], stat[:event], stat[:data].map do |k, v| "#{k}:#{v}" end.join(" ")) end end private def rename(hash, key, renames) if hash && hash[key] original = hash[key] value = renames[original] unless value value = renames[:_seq_] renames[:_seq_] = renames[:_seq_].succ renames[original] = value end hash[key] = value end end end end # frozen_string_literal: true # Define a package task library to aid in the definition of # redistributable package files. require "rake" require "rake/tasklib" module Rake # Create a packaging task that will package the project into # distributable files (e.g zip archive or tar files). # # The PackageTask will create the following targets: # # +:package+ :: # Create all the requested package files. # # +:clobber_package+ :: # Delete all the package files. This target is automatically # added to the main clobber target. # # +:repackage+ :: # Rebuild the package files from scratch, even if they are not out # of date. # # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tgz"</tt> :: # Create a gzipped tar package (if <em>need_tar</em> is true). # # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.gz"</tt> :: # Create a gzipped tar package (if <em>need_tar_gz</em> is true). # # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.bz2"</tt> :: # Create a bzip2'd tar package (if <em>need_tar_bz2</em> is true). # # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.zip"</tt> :: # Create a zip package archive (if <em>need_zip</em> is true). # # Example: # # Rake::PackageTask.new("rake", "1.2.3") do |p| # p.need_tar = true # p.package_files.include("lib/**/*.rb") # end # class PackageTask < TaskLib # Name of the package (from the GEM Spec). attr_accessor :name # Version of the package (e.g. '1.3.2'). attr_accessor :version # Directory used to store the package files (default is 'pkg'). attr_accessor :package_dir # True if a gzipped tar file (tgz) should be produced (default is # false). attr_accessor :need_tar # True if a gzipped tar file (tar.gz) should be produced (default # is false). attr_accessor :need_tar_gz # True if a bzip2'd tar file (tar.bz2) should be produced (default # is false). attr_accessor :need_tar_bz2 # True if a xz'd tar file (tar.xz) should be produced (default is false) attr_accessor :need_tar_xz # True if a zip file should be produced (default is false) attr_accessor :need_zip # List of files to be included in the package. attr_accessor :package_files # Tar command for gzipped or bzip2ed archives. The default is 'tar'. attr_accessor :tar_command # Zip command for zipped archives. The default is 'zip'. attr_accessor :zip_command # True if parent directory should be omitted (default is false) attr_accessor :without_parent_dir # Create a Package Task with the given name and version. Use +:noversion+ # as the version to build a package without a version or to provide a # fully-versioned package name. def initialize(name=nil, version=nil) init(name, version) yield self if block_given? define unless name.nil? end # Initialization that bypasses the "yield self" and "define" step. def init(name, version) @name = name @version = version @package_files = Rake::FileList.new @package_dir = "pkg" @need_tar = false @need_tar_gz = false @need_tar_bz2 = false @need_tar_xz = false @need_zip = false @tar_command = "tar" @zip_command = "zip" @without_parent_dir = false end # Create the tasks defined by this task library. def define fail "Version required (or :noversion)" if @version.nil? @version = nil if :noversion == @version desc "Build all the packages" task :package desc "Force a rebuild of the package files" task repackage: [:clobber_package, :package] desc "Remove package products" task :clobber_package do rm_r package_dir rescue nil end task clobber: [:clobber_package] [ [need_tar, tgz_file, "z"], [need_tar_gz, tar_gz_file, "z"], [need_tar_bz2, tar_bz2_file, "j"], [need_tar_xz, tar_xz_file, "J"] ].each do |need, file, flag| if need task package: ["#{package_dir}/#{file}"] file "#{package_dir}/#{file}" => [package_dir_path] + package_files do chdir(working_dir) { sh @tar_command, "#{flag}cvf", file, target_dir } mv "#{package_dir_path}/#{target_dir}", package_dir if without_parent_dir end end end if need_zip task package: ["#{package_dir}/#{zip_file}"] file "#{package_dir}/#{zip_file}" => [package_dir_path] + package_files do chdir(working_dir) { sh @zip_command, "-r", zip_file, target_dir } mv "#{package_dir_path}/#{zip_file}", package_dir if without_parent_dir end end directory package_dir_path => @package_files do @package_files.each do |fn| f = File.join(package_dir_path, fn) fdir = File.dirname(f) mkdir_p(fdir) unless File.exist?(fdir) if File.directory?(fn) mkdir_p(f) else rm_f f safe_ln(fn, f) end end end self end # The name of this package def package_name @version ? "#{@name}-#{@version}" : @name end # The directory this package will be built in def package_dir_path "#{package_dir}/#{package_name}" end # The package name with .tgz added def tgz_file "#{package_name}.tgz" end # The package name with .tar.gz added def tar_gz_file "#{package_name}.tar.gz" end # The package name with .tar.bz2 added def tar_bz2_file "#{package_name}.tar.bz2" end # The package name with .tar.xz added def tar_xz_file "#{package_name}.tar.xz" end # The package name with .zip added def zip_file "#{package_name}.zip" end def working_dir without_parent_dir ? package_dir_path : package_dir end # target directory relative to working_dir def target_dir without_parent_dir ? "." : package_name end end end # frozen_string_literal: true module Rake module TraceOutput # :nodoc: all # Write trace output to output stream +out+. # # The write is done as a single IO call (to print) to lessen the # chance that the trace output is interrupted by other tasks also # producing output. def trace_on(out, *strings) sep = $\ || "\n" if strings.empty? output = sep else output = strings.map { |s| next if s.nil? s.end_with?(sep) ? s : s + sep }.join end out.print(output) end end end # frozen_string_literal: true require "optparse" require "rake/task_manager" require "rake/file_list" require "rake/thread_pool" require "rake/thread_history_display" require "rake/trace_output" require "rake/win32" module Rake CommandLineOptionError = Class.new(StandardError) ## # Rake main application object. When invoking +rake+ from the # command line, a Rake::Application object is created and run. class Application include TaskManager include TraceOutput # The name of the application (typically 'rake') attr_reader :name # The original directory where rake was invoked. attr_reader :original_dir # Name of the actual rakefile used. attr_reader :rakefile # Number of columns on the terminal attr_accessor :terminal_columns # List of the top level task names (task names from the command line). attr_reader :top_level_tasks # Override the detected TTY output state (mostly for testing) attr_writer :tty_output DEFAULT_RAKEFILES = [ "rakefile", "Rakefile", "rakefile.rb", "Rakefile.rb" ].freeze # Initialize a Rake::Application object. def initialize super @name = "rake" @rakefiles = DEFAULT_RAKEFILES.dup @rakefile = nil @pending_imports = [] @imported = [] @loaders = {} @default_loader = Rake::DefaultLoader.new @original_dir = Dir.pwd @top_level_tasks = [] add_loader("rb", DefaultLoader.new) add_loader("rf", DefaultLoader.new) add_loader("rake", DefaultLoader.new) @tty_output = STDOUT.tty? @terminal_columns = ENV["RAKE_COLUMNS"].to_i set_default_options end # Run the Rake application. The run method performs the following # three steps: # # * Initialize the command line options (+init+). # * Define the tasks (+load_rakefile+). # * Run the top level tasks (+top_level+). # # If you wish to build a custom rake command, you should call # +init+ on your application. Then define any tasks. Finally, # call +top_level+ to run your top level tasks. def run(argv = ARGV) standard_exception_handling do init "rake", argv load_rakefile top_level end end # Initialize the command line parameters and app name. def init(app_name="rake", argv = ARGV) standard_exception_handling do @name = app_name begin args = handle_options argv rescue ArgumentError # Backward compatibility for capistrano args = handle_options end load_debug_at_stop_feature collect_command_line_tasks(args) end end def load_debug_at_stop_feature return unless ENV["RAKE_DEBUG"] require "debug/session" DEBUGGER__::start no_sigint_hook: true, nonstop: true Rake::Task.prepend Module.new { def execute(*) exception = DEBUGGER__::SESSION.capture_exception_frames(/(exe|bin|lib)\/rake/) do super end if exception STDERR.puts exception.message DEBUGGER__::SESSION.enter_postmortem_session exception raise exception end end } rescue LoadError end private :load_debug_at_stop_feature # Find the rakefile and then load it and any pending imports. def load_rakefile standard_exception_handling do raw_load_rakefile end end # Run the top level tasks of a Rake application. def top_level run_with_threads do if options.show_tasks display_tasks_and_comments elsif options.show_prereqs display_prerequisites else top_level_tasks.each { |task_name| invoke_task(task_name) } end end end # Run the given block with the thread startup and shutdown. def run_with_threads thread_pool.gather_history if options.job_stats == :history yield thread_pool.join if defined?(@thread_pool) if options.job_stats stats = thread_pool.statistics puts "Maximum active threads: #{stats[:max_active_threads]} + main" puts "Total threads in play: #{stats[:total_threads_in_play]} + main" end ThreadHistoryDisplay.new(thread_pool.history).show if options.job_stats == :history end # Add a loader to handle imported files ending in the extension # +ext+. def add_loader(ext, loader) ext = ".#{ext}" unless ext =~ /^\./ @loaders[ext] = loader end # Application options from the command line def options @options ||= OpenStruct.new end # Return the thread pool used for multithreaded processing. def thread_pool # :nodoc: @thread_pool ||= ThreadPool.new(options.thread_pool_size || Rake.suggested_thread_count-1) end # internal ---------------------------------------------------------------- # Invokes a task with arguments that are extracted from +task_string+ def invoke_task(task_string) # :nodoc: name, args = parse_task_string(task_string) t = self[name] t.invoke(*args) end def parse_task_string(string) # :nodoc: /^([^\[]+)(?:\[(.*)\])$/ =~ string.to_s name = $1 remaining_args = $2 return string, [] unless name return name, [] if remaining_args.empty? args = [] begin /\s*((?:[^\\,]|\\.)*?)\s*(?:,\s*(.*))?$/ =~ remaining_args remaining_args = $2 args << $1.gsub(/\\(.)/, '\1') end while remaining_args return name, args end # Provide standard exception handling for the given block. def standard_exception_handling # :nodoc: yield rescue SystemExit # Exit silently with current status raise rescue OptionParser::InvalidOption => ex $stderr.puts ex.message exit(false) rescue Exception => ex # Exit with error message display_error_message(ex) exit_because_of_exception(ex) end # Exit the program because of an unhandled exception. # (may be overridden by subclasses) def exit_because_of_exception(ex) # :nodoc: exit(false) end # Display the error message that caused the exception. def display_error_message(ex) # :nodoc: trace "#{name} aborted!" display_exception_details(ex) trace "Tasks: #{ex.chain}" if has_chain?(ex) trace "(See full trace by running task with --trace)" unless options.backtrace end def display_exception_details(ex) # :nodoc: display_exception_details_seen << ex display_exception_message_details(ex) display_exception_backtrace(ex) display_cause_details(ex.cause) if has_cause?(ex) end def display_cause_details(ex) # :nodoc: return if display_exception_details_seen.include? ex trace "\nCaused by:" display_exception_details(ex) end def display_exception_details_seen # :nodoc: Thread.current[:rake_display_exception_details_seen] ||= [] end def has_cause?(ex) # :nodoc: ex.respond_to?(:cause) && ex.cause end def display_exception_message_details(ex) # :nodoc: if ex.instance_of?(RuntimeError) trace ex.message elsif ex.respond_to?(:detailed_message) trace "#{ex.class.name}: #{ex.detailed_message(highlight: false)}" else trace "#{ex.class.name}: #{ex.message}" end end def display_exception_backtrace(ex) # :nodoc: if options.backtrace trace ex.backtrace.join("\n") else trace Backtrace.collapse(ex.backtrace).join("\n") end end # Warn about deprecated usage. # # Example: # Rake.application.deprecate("import", "Rake.import", caller.first) # def deprecate(old_usage, new_usage, call_site) # :nodoc: unless options.ignore_deprecate $stderr.puts "WARNING: '#{old_usage}' is deprecated. " + "Please use '#{new_usage}' instead.\n" + " at #{call_site}" end end # Does the exception have a task invocation chain? def has_chain?(exception) # :nodoc: exception.respond_to?(:chain) && exception.chain end private :has_chain? # True if one of the files in RAKEFILES is in the current directory. # If a match is found, it is copied into @rakefile. def have_rakefile # :nodoc: @rakefiles.each do |fn| if File.exist?(fn) others = FileList.glob(fn, File::FNM_CASEFOLD) return others.size == 1 ? others.first : fn elsif fn == "" return fn end end return nil end # True if we are outputting to TTY, false otherwise def tty_output? # :nodoc: @tty_output end # We will truncate output if we are outputting to a TTY or if we've been # given an explicit column width to honor def truncate_output? # :nodoc: tty_output? || @terminal_columns.nonzero? end # Display the tasks and comments. def display_tasks_and_comments # :nodoc: displayable_tasks = tasks.select { |t| (options.show_all_tasks || t.comment) && t.name =~ options.show_task_pattern } case options.show_tasks when :tasks width = displayable_tasks.map { |t| t.name_with_args.length }.max || 10 if truncate_output? max_column = terminal_width - name.size - width - 7 else max_column = nil end displayable_tasks.each do |t| printf("#{name} %-#{width}s # %s\n", t.name_with_args, max_column ? truncate(t.comment, max_column) : t.comment) end when :describe displayable_tasks.each do |t| puts "#{name} #{t.name_with_args}" comment = t.full_comment || "" comment.split("\n").each do |line| puts " #{line}" end puts end when :lines displayable_tasks.each do |t| t.locations.each do |loc| printf "#{name} %-30s %s\n", t.name_with_args, loc end end else fail "Unknown show task mode: '#{options.show_tasks}'" end end def terminal_width # :nodoc: if @terminal_columns.nonzero? result = @terminal_columns else result = unix? ? dynamic_width : 80 end (result < 10) ? 80 : result rescue 80 end # Calculate the dynamic width of the def dynamic_width # :nodoc: @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput) end def dynamic_width_stty # :nodoc: %x{stty size 2>/dev/null}.split[1].to_i end def dynamic_width_tput # :nodoc: %x{tput cols 2>/dev/null}.to_i end def unix? # :nodoc: RbConfig::CONFIG["host_os"] =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i end def windows? # :nodoc: Win32.windows? end def truncate(string, width) # :nodoc: if string.nil? "" elsif string.length <= width string else (string[0, width - 3] || "") + "..." end end # Display the tasks and prerequisites def display_prerequisites # :nodoc: tasks.each do |t| puts "#{name} #{t.name}" t.prerequisites.each { |pre| puts " #{pre}" } end end def trace(*strings) # :nodoc: options.trace_output ||= $stderr trace_on(options.trace_output, *strings) end def sort_options(options) # :nodoc: options.sort_by { |opt| opt.select { |o| o.is_a?(String) && o =~ /^-/ }.map(&:downcase).sort.reverse } end private :sort_options # A list of all the standard options used in rake, suitable for # passing to OptionParser. def standard_rake_options # :nodoc: sort_options( [ ["--all", "-A", "Show all tasks, even uncommented ones (in combination with -T or -D)", lambda { |value| options.show_all_tasks = value } ], ["--backtrace=[OUT]", "Enable full backtrace. OUT can be stderr (default) or stdout.", lambda { |value| options.backtrace = true select_trace_output(options, "backtrace", value) } ], ["--build-all", "-B", "Build all prerequisites, including those which are up-to-date.", lambda { |value| options.build_all = true } ], ["--comments", "Show commented tasks only", lambda { |value| options.show_all_tasks = !value } ], ["--describe", "-D [PATTERN]", "Describe the tasks (matching optional PATTERN), then exit.", lambda { |value| select_tasks_to_show(options, :describe, value) } ], ["--directory", "-C [DIRECTORY]", "Change to DIRECTORY before doing anything.", lambda { |value| Dir.chdir value @original_dir = Dir.pwd } ], ["--dry-run", "-n", "Do a dry run without executing actions.", lambda { |value| Rake.verbose(true) Rake.nowrite(true) options.dryrun = true options.trace = true } ], ["--execute", "-e CODE", "Execute some Ruby code and exit.", lambda { |value| eval(value) exit } ], ["--execute-print", "-p CODE", "Execute some Ruby code, print the result, then exit.", lambda { |value| puts eval(value) exit } ], ["--execute-continue", "-E CODE", "Execute some Ruby code, " + "then continue with normal task processing.", lambda { |value| eval(value) } ], ["--jobs", "-j [NUMBER]", "Specifies the maximum number of tasks to execute in parallel. " + "(default is number of CPU cores + 4)", lambda { |value| if value.nil? || value == "" value = Float::INFINITY elsif value =~ /^\d+$/ value = value.to_i else value = Rake.suggested_thread_count end value = 1 if value < 1 options.thread_pool_size = value - 1 } ], ["--job-stats [LEVEL]", "Display job statistics. " + "LEVEL=history displays a complete job list", lambda { |value| if value =~ /^history/i options.job_stats = :history else options.job_stats = true end } ], ["--libdir", "-I LIBDIR", "Include LIBDIR in the search path for required modules.", lambda { |value| $:.push(value) } ], ["--multitask", "-m", "Treat all tasks as multitasks.", lambda { |value| options.always_multitask = true } ], ["--no-search", "--nosearch", "-N", "Do not search parent directories for the Rakefile.", lambda { |value| options.nosearch = true } ], ["--prereqs", "-P", "Display the tasks and dependencies, then exit.", lambda { |value| options.show_prereqs = true } ], ["--quiet", "-q", "Do not log messages to standard output.", lambda { |value| Rake.verbose(false) } ], ["--rakefile", "-f [FILENAME]", "Use FILENAME as the rakefile to search for.", lambda { |value| value ||= "" @rakefiles.clear @rakefiles << value } ], ["--rakelibdir", "--rakelib", "-R RAKELIBDIR", "Auto-import any .rake files in RAKELIBDIR. " + "(default is 'rakelib')", lambda { |value| options.rakelib = value.split(File::PATH_SEPARATOR) } ], ["--require", "-r MODULE", "Require MODULE before executing rakefile.", lambda { |value| begin require value rescue LoadError => ex begin rake_require value rescue LoadError raise ex end end } ], ["--rules", "Trace the rules resolution.", lambda { |value| options.trace_rules = true } ], ["--silent", "-s", "Like --quiet, but also suppresses the " + "'in directory' announcement.", lambda { |value| Rake.verbose(false) options.silent = true } ], ["--suppress-backtrace PATTERN", "Suppress backtrace lines matching regexp PATTERN. " + "Ignored if --trace is on.", lambda { |value| options.suppress_backtrace_pattern = Regexp.new(value) } ], ["--system", "-g", "Using system wide (global) rakefiles " + "(usually '~/.rake/*.rake').", lambda { |value| options.load_system = true } ], ["--no-system", "--nosystem", "-G", "Use standard project Rakefile search paths, " + "ignore system wide rakefiles.", lambda { |value| options.ignore_system = true } ], ["--tasks", "-T [PATTERN]", "Display the tasks (matching optional PATTERN) " + "with descriptions, then exit. " + "-AT combination displays all the tasks, including those without descriptions.", lambda { |value| select_tasks_to_show(options, :tasks, value) } ], ["--trace=[OUT]", "-t", "Turn on invoke/execute tracing, enable full backtrace. " + "OUT can be stderr (default) or stdout.", lambda { |value| options.trace = true options.backtrace = true select_trace_output(options, "trace", value) Rake.verbose(true) } ], ["--verbose", "-v", "Log message to standard output.", lambda { |value| Rake.verbose(true) } ], ["--version", "-V", "Display the program version.", lambda { |value| puts "rake, version #{Rake::VERSION}" exit } ], ["--where", "-W [PATTERN]", "Describe the tasks (matching optional PATTERN), then exit.", lambda { |value| select_tasks_to_show(options, :lines, value) options.show_all_tasks = true } ], ["--no-deprecation-warnings", "-X", "Disable the deprecation warnings.", lambda { |value| options.ignore_deprecate = true } ], ]) end def select_tasks_to_show(options, show_tasks, value) # :nodoc: options.show_tasks = show_tasks options.show_task_pattern = Regexp.new(value || "") Rake::TaskManager.record_task_metadata = true end private :select_tasks_to_show def select_trace_output(options, trace_option, value) # :nodoc: value = value.strip unless value.nil? case value when "stdout" options.trace_output = $stdout when "stderr", nil options.trace_output = $stderr else fail CommandLineOptionError, "Unrecognized --#{trace_option} option '#{value}'" end end private :select_trace_output # Read and handle the command line options. Returns the command line # arguments that we didn't understand, which should (in theory) be just # task names and env vars. def handle_options(argv) # :nodoc: set_default_options OptionParser.new do |opts| opts.banner = "#{Rake.application.name} [-f rakefile] {options} targets..." opts.separator "" opts.separator "Options are ..." opts.on_tail("-h", "--help", "-H", "Display this help message.") do puts opts exit end standard_rake_options.each { |args| opts.on(*args) } opts.environment("RAKEOPT") end.parse(argv) end # Similar to the regular Ruby +require+ command, but will check # for *.rake files in addition to *.rb files. def rake_require(file_name, paths=$LOAD_PATH, loaded=$") # :nodoc: fn = file_name + ".rake" return false if loaded.include?(fn) paths.each do |path| full_path = File.join(path, fn) if File.exist?(full_path) Rake.load_rakefile(full_path) loaded << fn return true end end fail LoadError, "Can't find #{file_name}" end def find_rakefile_location # :nodoc: here = Dir.pwd until (fn = have_rakefile) Dir.chdir("..") return nil if Dir.pwd == here || options.nosearch here = Dir.pwd end [fn, here] ensure Dir.chdir(Rake.original_dir) end def print_rakefile_directory(location) # :nodoc: $stderr.puts "(in #{Dir.pwd})" unless options.silent or original_dir == location end def raw_load_rakefile # :nodoc: rakefile, location = find_rakefile_location if (!options.ignore_system) && (options.load_system || rakefile.nil?) && system_dir && File.directory?(system_dir) print_rakefile_directory(location) glob("#{system_dir}/*.rake") do |name| add_import name end else fail "No Rakefile found (looking for: #{@rakefiles.join(', ')})" if rakefile.nil? @rakefile = rakefile Dir.chdir(location) print_rakefile_directory(location) Rake.load_rakefile(File.expand_path(@rakefile)) if @rakefile && @rakefile != "" options.rakelib.each do |rlib| glob("#{rlib}/*.rake") do |name| add_import name end end end load_imports end def glob(path, &block) # :nodoc: FileList.glob(path.tr("\\", "/")).each(&block) end private :glob # The directory path containing the system wide rakefiles. def system_dir # :nodoc: @system_dir ||= begin if ENV["RAKE_SYSTEM"] ENV["RAKE_SYSTEM"] else standard_system_dir end end end # The standard directory containing system wide rake files. if Win32.windows? def standard_system_dir #:nodoc: Win32.win32_system_dir end else def standard_system_dir #:nodoc: File.join(File.expand_path("~"), ".rake") end end private :standard_system_dir # Collect the list of tasks on the command line. If no tasks are # given, return a list containing only the default task. # Environmental assignments are processed at this time as well. # # `args` is the list of arguments to peruse to get the list of tasks. # It should be the command line that was given to rake, less any # recognised command-line options, which OptionParser.parse will # have taken care of already. def collect_command_line_tasks(args) # :nodoc: @top_level_tasks = [] args.each do |arg| if arg =~ /^(\w+)=(.*)$/m ENV[$1] = $2 else @top_level_tasks << arg unless arg =~ /^-/ end end @top_level_tasks.push(default_task_name) if @top_level_tasks.empty? end # Default task name ("default"). # (May be overridden by subclasses) def default_task_name # :nodoc: "default" end # Add a file to the list of files to be imported. def add_import(fn) # :nodoc: @pending_imports << fn end # Load the pending list of imported files. def load_imports # :nodoc: while fn = @pending_imports.shift next if @imported.member?(fn) fn_task = lookup(fn) and fn_task.invoke ext = File.extname(fn) loader = @loaders[ext] || @default_loader loader.load(fn) if fn_task = lookup(fn) and fn_task.needed? fn_task.reenable fn_task.invoke loader.load(fn) end @imported << fn end end def rakefile_location(backtrace=caller) # :nodoc: backtrace.map { |t| t[/([^:]+):/, 1] } re = /^#{@rakefile}$/ re = /#{re.source}/i if windows? backtrace.find { |str| str =~ re } || "" end def set_default_options # :nodoc: options.always_multitask = false options.backtrace = false options.build_all = false options.dryrun = false options.ignore_deprecate = false options.ignore_system = false options.job_stats = false options.load_system = false options.nosearch = false options.rakelib = %w[rakelib] options.show_all_tasks = false options.show_prereqs = false options.show_task_pattern = nil options.show_tasks = nil options.silent = false options.suppress_backtrace_pattern = nil options.thread_pool_size = Rake.suggested_thread_count options.trace = false options.trace_output = $stderr options.trace_rules = false end end end # frozen_string_literal: true module Rake # Same as a regular task, but the immediate prerequisites are done in # parallel using Ruby threads. # class MultiTask < Task private def invoke_prerequisites(task_args, invocation_chain) # :nodoc: invoke_prerequisites_concurrently(task_args, invocation_chain) end end end # frozen_string_literal: true # Defines a :phony task that you can use as a dependency. This allows # file-based tasks to use non-file-based tasks as prerequisites # without forcing them to rebuild. # # See FileTask#out_of_date? and Task#timestamp for more info. require "rake" task :phony Rake::Task[:phony].tap do |task| def task.timestamp # :nodoc: Time.at 0 end end # frozen_string_literal: true module Rake # Makefile loader to be used with the import file loader. Use this to # import dependencies from make dependency tools: # # require 'rake/loaders/makefile' # # file ".depends.mf" => [SRC_LIST] do |t| # sh "makedepend -f- -- #{CFLAGS} -- #{t.prerequisites} > #{t.name}" # end # # import ".depends.mf" # # See {Importing Dependencies}[link:doc/rakefile_rdoc.html#label-Importing+Dependencies] # for further details. class MakefileLoader include Rake::DSL SPACE_MARK = "\0" # :nodoc: # Load the makefile dependencies in +fn+. def load(fn) # :nodoc: lines = File.read fn lines.gsub!(/\\ /, SPACE_MARK) lines.gsub!(/#[^\n]*\n/m, "") lines.gsub!(/\\\n/, " ") lines.each_line do |line| process_line(line) end end private # Process one logical line of makefile data. def process_line(line) # :nodoc: file_tasks, args = line.split(":", 2) return if args.nil? dependents = args.split.map { |d| respace(d) } file_tasks.scan(/\S+/) do |file_task| file_task = respace(file_task) file file_task => dependents end end def respace(str) # :nodoc: str.tr SPACE_MARK, " " end end # Install the handler Rake.application.add_loader("mf", MakefileLoader.new) end # frozen_string_literal: true module Rake module Backtrace # :nodoc: all SYS_KEYS = RbConfig::CONFIG.keys.grep(/(?:[a-z]prefix|libdir)\z/) SYS_PATHS = RbConfig::CONFIG.values_at(*SYS_KEYS).uniq + [ File.join(File.dirname(__FILE__), "..") ] SUPPRESSED_PATHS = SYS_PATHS. map { |s| s.tr("\\", "/") }. map { |f| File.expand_path(f) }. reject { |s| s.nil? || s =~ /^ *$/ } SUPPRESSED_PATHS_RE = SUPPRESSED_PATHS.map { |f| Regexp.quote(f) }.join("|") SUPPRESSED_PATHS_RE << "|^org\\/jruby\\/\\w+\\.java" if Object.const_defined?(:RUBY_ENGINE) and RUBY_ENGINE == "jruby" SUPPRESS_PATTERN = %r!(\A(#{SUPPRESSED_PATHS_RE})|bin/rake:\d+)!i def self.collapse(backtrace) pattern = Rake.application.options.suppress_backtrace_pattern || SUPPRESS_PATTERN backtrace.reject { |elem| elem =~ pattern } end end end # frozen_string_literal: true require "rake/promise" require "set" module Rake class ThreadPool # :nodoc: all # Creates a ThreadPool object. The +thread_count+ parameter is the size # of the pool. def initialize(thread_count) @max_active_threads = [thread_count, 0].max @threads = Set.new @threads_mon = Monitor.new @queue = Queue.new @join_cond = @threads_mon.new_cond @history_start_time = nil @history = [] @history_mon = Monitor.new @total_threads_in_play = 0 end # Creates a future executed by the +ThreadPool+. # # The args are passed to the block when executing (similarly to # Thread#new) The return value is an object representing # a future which has been created and added to the queue in the # pool. Sending #value to the object will sleep the # current thread until the future is finished and will return the # result (or raise an exception thrown from the future) def future(*args, &block) promise = Promise.new(args, &block) promise.recorder = lambda { |*stats| stat(*stats) } @queue.enq promise stat :queued, item_id: promise.object_id start_thread promise end # Waits until the queue of futures is empty and all threads have exited. def join @threads_mon.synchronize do begin stat :joining @join_cond.wait unless @threads.empty? stat :joined rescue Exception => e stat :joined $stderr.puts e $stderr.print "Queue contains #{@queue.size} items. " + "Thread pool contains #{@threads.count} threads\n" $stderr.print "Current Thread #{Thread.current} status = " + "#{Thread.current.status}\n" $stderr.puts e.backtrace.join("\n") @threads.each do |t| $stderr.print "Thread #{t} status = #{t.status}\n" $stderr.puts t.backtrace.join("\n") end raise e end end end # Enable the gathering of history events. def gather_history #:nodoc: @history_start_time = Time.now if @history_start_time.nil? end # Return a array of history events for the thread pool. # # History gathering must be enabled to be able to see the events # (see #gather_history). Best to call this when the job is # complete (i.e. after ThreadPool#join is called). def history # :nodoc: @history_mon.synchronize { @history.dup }. sort_by { |i| i[:time] }. each { |i| i[:time] -= @history_start_time } end # Return a hash of always collected statistics for the thread pool. def statistics # :nodoc: { total_threads_in_play: @total_threads_in_play, max_active_threads: @max_active_threads, } end private # processes one item on the queue. Returns true if there was an # item to process, false if there was no item def process_queue_item #:nodoc: return false if @queue.empty? # Even though we just asked if the queue was empty, it # still could have had an item which by this statement # is now gone. For this reason we pass true to Queue#deq # because we will sleep indefinitely if it is empty. promise = @queue.deq(true) stat :dequeued, item_id: promise.object_id promise.work return true rescue ThreadError # this means the queue is empty false end def safe_thread_count @threads_mon.synchronize do @threads.count end end def start_thread # :nodoc: @threads_mon.synchronize do next unless @threads.count < @max_active_threads t = Thread.new do begin while safe_thread_count <= @max_active_threads break unless process_queue_item end ensure @threads_mon.synchronize do @threads.delete Thread.current stat :ended, thread_count: @threads.count @join_cond.broadcast if @threads.empty? end end end @threads << t stat( :spawned, new_thread: t.object_id, thread_count: @threads.count) @total_threads_in_play = @threads.count if @threads.count > @total_threads_in_play end end def stat(event, data=nil) # :nodoc: return if @history_start_time.nil? info = { event: event, data: data, time: Time.now, thread: Thread.current.object_id, } @history_mon.synchronize { @history << info } end # for testing only def __queue__ # :nodoc: @queue end end end # frozen_string_literal: true module Rake # EarlyTime is a fake timestamp that occurs _before_ any other time value. class EarlyTime include Comparable include Singleton ## # The EarlyTime always comes before +other+! def <=>(other) -1 end def to_s # :nodoc: "<EARLY TIME>" end end EARLY = EarlyTime.instance end # frozen_string_literal: true module Rake # Based on a script at: # http://stackoverflow.com/questions/891537/ruby-detect-number-of-cpus-installed class CpuCounter # :nodoc: all def self.count new.count_with_default end def count_with_default(default=4) count || default rescue StandardError default end begin require "etc" rescue LoadError else if Etc.respond_to?(:nprocessors) def count return Etc.nprocessors end end end end end unless Rake::CpuCounter.method_defined?(:count) Rake::CpuCounter.class_eval <<-'end;', __FILE__, __LINE__+1 require 'rbconfig' def count if RUBY_PLATFORM == 'java' count_via_java_runtime else case RbConfig::CONFIG['host_os'] when /linux/ count_via_cpuinfo when /darwin|bsd/ count_via_sysctl when /mswin|mingw/ count_via_win32 else # Try everything count_via_win32 || count_via_sysctl || count_via_cpuinfo end end end def count_via_java_runtime Java::Java.lang.Runtime.getRuntime.availableProcessors rescue StandardError nil end def count_via_win32 require 'win32ole' wmi = WIN32OLE.connect("winmgmts://") cpu = wmi.ExecQuery("select NumberOfCores from Win32_Processor") # TODO count hyper-threaded in this cpu.to_enum.first.NumberOfCores rescue StandardError, LoadError nil end def count_via_cpuinfo open('/proc/cpuinfo') { |f| f.readlines }.grep(/processor/).size rescue StandardError nil end def count_via_sysctl run 'sysctl', '-n', 'hw.ncpu' end def run(command, *args) cmd = resolve_command(command) if cmd IO.popen [cmd, *args] do |io| io.read.to_i end else nil end end def resolve_command(command) look_for_command("/usr/sbin", command) || look_for_command("/sbin", command) || in_path_command(command) end def look_for_command(dir, command) path = File.join(dir, command) File.exist?(path) ? path : nil end def in_path_command(command) IO.popen ['which', command] do |io| io.eof? ? nil : command end end end; end # frozen_string_literal: true require "rake/ext/core" class String rake_extension("ext") do # Replace the file extension with +newext+. If there is no extension on # the string, append the new extension to the end. If the new extension # is not given, or is the empty string, remove any existing extension. # # +ext+ is a user added method for the String class. # # This String extension comes from Rake def ext(newext="") return self.dup if [".", ".."].include? self if newext != "" newext = "." + newext unless newext =~ /^\./ end self.chomp(File.extname(self)) << newext end end rake_extension("pathmap") do # Explode a path into individual components. Used by +pathmap+. # # This String extension comes from Rake def pathmap_explode head, tail = File.split(self) return [self] if head == self return [tail] if head == "." || tail == "/" return [head, tail] if head == "/" return head.pathmap_explode + [tail] end protected :pathmap_explode # Extract a partial path from the path. Include +n+ directories from the # front end (left hand side) if +n+ is positive. Include |+n+| # directories from the back end (right hand side) if +n+ is negative. # # This String extension comes from Rake def pathmap_partial(n) dirs = File.dirname(self).pathmap_explode partial_dirs = if n > 0 dirs[0...n] elsif n < 0 dirs.reverse[0...-n].reverse else "." end File.join(partial_dirs) end protected :pathmap_partial # Perform the pathmap replacement operations on the given path. The # patterns take the form 'pat1,rep1;pat2,rep2...'. # # This String extension comes from Rake def pathmap_replace(patterns, &block) result = self patterns.split(";").each do |pair| pattern, replacement = pair.split(",") pattern = Regexp.new(pattern) if replacement == "*" && block_given? result = result.sub(pattern, &block) elsif replacement result = result.sub(pattern, replacement) else result = result.sub(pattern, "") end end result end protected :pathmap_replace # Map the path according to the given specification. The specification # controls the details of the mapping. The following special patterns are # recognized: # # <tt>%p</tt> :: The complete path. # <tt>%f</tt> :: The base file name of the path, with its file extension, # but without any directories. # <tt>%n</tt> :: The file name of the path without its file extension. # <tt>%d</tt> :: The directory list of the path. # <tt>%x</tt> :: The file extension of the path. An empty string if there # is no extension. # <tt>%X</tt> :: Everything *but* the file extension. # <tt>%s</tt> :: The alternate file separator if defined, otherwise use # # the standard file separator. # <tt>%%</tt> :: A percent sign. # # The <tt>%d</tt> specifier can also have a numeric prefix (e.g. '%2d'). # If the number is positive, only return (up to) +n+ directories in the # path, starting from the left hand side. If +n+ is negative, return (up # to) +n+ directories from the right hand side of the path. # # Examples: # # 'a/b/c/d/file.txt'.pathmap("%2d") => 'a/b' # 'a/b/c/d/file.txt'.pathmap("%-2d") => 'c/d' # # Also the <tt>%d</tt>, <tt>%p</tt>, <tt>%f</tt>, <tt>%n</tt>, # <tt>%x</tt>, and <tt>%X</tt> operators can take a pattern/replacement # argument to perform simple string substitutions on a particular part of # the path. The pattern and replacement are separated by a comma and are # enclosed by curly braces. The replacement spec comes after the % # character but before the operator letter. (e.g. "%{old,new}d"). # Multiple replacement specs should be separated by semi-colons (e.g. # "%{old,new;src,bin}d"). # # Regular expressions may be used for the pattern, and back refs may be # used in the replacement text. Curly braces, commas and semi-colons are # excluded from both the pattern and replacement text (let's keep parsing # reasonable). # # For example: # # "src/org/onestepback/proj/A.java".pathmap("%{^src,class}X.class") # # returns: # # "class/org/onestepback/proj/A.class" # # If the replacement text is '*', then a block may be provided to perform # some arbitrary calculation for the replacement. # # For example: # # "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext| # ext.downcase # } # # Returns: # # "/path/to/file.txt" # # This String extension comes from Rake def pathmap(spec=nil, &block) return self if spec.nil? result = "".dup spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag| case frag when "%f" result << File.basename(self) when "%n" result << File.basename(self).ext when "%d" result << File.dirname(self) when "%x" result << File.extname(self) when "%X" result << self.ext when "%p" result << self when "%s" result << (File::ALT_SEPARATOR || File::SEPARATOR) when "%-" # do nothing when "%%" result << "%" when /%(-?\d+)d/ result << pathmap_partial($1.to_i) when /^%\{([^}]*)\}(\d*[dpfnxX])/ patterns, operator = $1, $2 result << pathmap("%" + operator).pathmap_replace(patterns, &block) when /^%/ fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'" else result << frag end end result end end end # frozen_string_literal: true class Module # Check for an existing method in the current class before extending. If # the method already exists, then a warning is printed and the extension is # not added. Otherwise the block is yielded and any definitions in the # block will take effect. # # Usage: # # class String # rake_extension("xyz") do # def xyz # ... # end # end # end # def rake_extension(method) # :nodoc: if method_defined?(method) $stderr.puts "WARNING: Possible conflict with Rake extension: " + "#{self}##{method} already exists" else yield end end end # frozen_string_literal: true require "rake/application" module Rake class << self # Current Rake Application def application @application ||= Rake::Application.new end # Set the current Rake application object. def application=(app) @application = app end def suggested_thread_count # :nodoc: @cpu_count ||= Rake::CpuCounter.count @cpu_count + 4 end # Return the original directory where the Rake application was started. def original_dir application.original_dir end # Load a rakefile. def load_rakefile(path) load(path) end # Add files to the rakelib list def add_rakelib(*files) application.options.rakelib ||= [] application.options.rakelib.concat(files) end # Make +block_application+ the default rake application inside a block so # you can load rakefiles into a different application. # # This is useful when you want to run rake tasks inside a library without # running rake in a sub-shell. # # Example: # # Dir.chdir 'other/directory' # # other_rake = Rake.with_application do |rake| # rake.load_rakefile # end # # puts other_rake.tasks def with_application(block_application = Rake::Application.new) orig_application = Rake.application Rake.application = block_application yield block_application block_application ensure Rake.application = orig_application end end end # frozen_string_literal: true module Rake # Error indicating a recursion overflow error in task selection. class RuleRecursionOverflowError < StandardError def initialize(*args) super @targets = [] end def add_target(target) @targets << target end def message super + ": [" + @targets.reverse.join(" => ") + "]" end end end # frozen_string_literal: true require "rake/invocation_exception_mixin" module Rake ## # A Task is the basic unit of work in a Rakefile. Tasks have associated # actions (possibly more than one) and a list of prerequisites. When # invoked, a task will first ensure that all of its prerequisites have an # opportunity to run and then it will execute its own actions. # # Tasks are not usually created directly using the new method, but rather # use the +file+ and +task+ convenience methods. # class Task # List of prerequisites for a task. attr_reader :prerequisites alias prereqs prerequisites # List of order only prerequisites for a task. attr_reader :order_only_prerequisites # List of actions attached to a task. attr_reader :actions # Application owning this task. attr_accessor :application # Array of nested namespaces names used for task lookup by this task. attr_reader :scope # File/Line locations of each of the task definitions for this # task (only valid if the task was defined with the detect # location option set). attr_reader :locations # Has this task already been invoked? Already invoked tasks # will be skipped unless you reenable them. attr_reader :already_invoked # Return task name def to_s name end def inspect # :nodoc: "<#{self.class} #{name} => [#{prerequisites.join(', ')}]>" end # List of sources for task. attr_writer :sources def sources if defined?(@sources) @sources else prerequisites end end # List of prerequisite tasks def prerequisite_tasks (prerequisites + order_only_prerequisites).map { |pre| lookup_prerequisite(pre) } end def lookup_prerequisite(prerequisite_name) # :nodoc: scoped_prerequisite_task = application[prerequisite_name, @scope] if scoped_prerequisite_task == self unscoped_prerequisite_task = application[prerequisite_name] end unscoped_prerequisite_task || scoped_prerequisite_task end private :lookup_prerequisite # List of all unique prerequisite tasks including prerequisite tasks' # prerequisites. # Includes self when cyclic dependencies are found. def all_prerequisite_tasks seen = {} collect_prerequisites(seen) seen.values end def collect_prerequisites(seen) # :nodoc: prerequisite_tasks.each do |pre| next if seen[pre.name] seen[pre.name] = pre pre.collect_prerequisites(seen) end end protected :collect_prerequisites # First source from a rule (nil if no sources) def source sources.first end # Create a task named +task_name+ with no actions or prerequisites. Use # +enhance+ to add actions and prerequisites. def initialize(task_name, app) @name = task_name.to_s @prerequisites = [] @actions = [] @already_invoked = false @comments = [] @lock = Monitor.new @application = app @scope = app.current_scope @arg_names = nil @locations = [] @invocation_exception = nil @order_only_prerequisites = [] end # Enhance a task with prerequisites or actions. Returns self. def enhance(deps=nil, &block) @prerequisites |= deps if deps @actions << block if block_given? self end # Name of the task, including any namespace qualifiers. def name @name.to_s end # Name of task with argument list description. def name_with_args # :nodoc: if arg_description "#{name}#{arg_description}" else name end end # Argument description (nil if none). def arg_description # :nodoc: @arg_names ? "[#{arg_names.join(',')}]" : nil end # Name of arguments for this task. def arg_names @arg_names || [] end # Reenable the task, allowing its tasks to be executed if the task # is invoked again. def reenable @already_invoked = false @invocation_exception = nil end # Clear the existing prerequisites, actions, comments, and arguments of a rake task. def clear clear_prerequisites clear_actions clear_comments clear_args self end # Clear the existing prerequisites of a rake task. def clear_prerequisites prerequisites.clear self end # Clear the existing actions on a rake task. def clear_actions actions.clear self end # Clear the existing comments on a rake task. def clear_comments @comments = [] self end # Clear the existing arguments on a rake task. def clear_args @arg_names = nil self end # Invoke the task if it is needed. Prerequisites are invoked first. def invoke(*args) task_args = TaskArguments.new(arg_names, args) invoke_with_call_chain(task_args, InvocationChain::EMPTY) end # Same as invoke, but explicitly pass a call chain to detect # circular dependencies. # # If multiple tasks depend on this # one in parallel, they will all fail if the first execution of # this task fails. def invoke_with_call_chain(task_args, invocation_chain) new_chain = Rake::InvocationChain.append(self, invocation_chain) @lock.synchronize do begin if application.options.trace application.trace "** Invoke #{name} #{format_trace_flags}" end if @already_invoked if @invocation_exception if application.options.trace application.trace "** Previous invocation of #{name} failed #{format_trace_flags}" end raise @invocation_exception else return end end @already_invoked = true invoke_prerequisites(task_args, new_chain) execute(task_args) if needed? rescue Exception => ex add_chain_to(ex, new_chain) @invocation_exception = ex raise ex end end end protected :invoke_with_call_chain def add_chain_to(exception, new_chain) # :nodoc: exception.extend(InvocationExceptionMixin) unless exception.respond_to?(:chain) exception.chain = new_chain if exception.chain.nil? end private :add_chain_to # Invoke all the prerequisites of a task. def invoke_prerequisites(task_args, invocation_chain) # :nodoc: if application.options.always_multitask invoke_prerequisites_concurrently(task_args, invocation_chain) else prerequisite_tasks.each { |p| prereq_args = task_args.new_scope(p.arg_names) p.invoke_with_call_chain(prereq_args, invocation_chain) } end end # Invoke all the prerequisites of a task in parallel. def invoke_prerequisites_concurrently(task_args, invocation_chain)# :nodoc: futures = prerequisite_tasks.map do |p| prereq_args = task_args.new_scope(p.arg_names) application.thread_pool.future(p) do |r| r.invoke_with_call_chain(prereq_args, invocation_chain) end end # Iterate in reverse to improve performance related to thread waiting and switching futures.reverse_each(&:value) end # Format the trace flags for display. def format_trace_flags flags = [] flags << "first_time" unless @already_invoked flags << "not_needed" unless needed? flags.empty? ? "" : "(" + flags.join(", ") + ")" end private :format_trace_flags # Execute the actions associated with this task. def execute(args=nil) args ||= EMPTY_TASK_ARGS if application.options.dryrun application.trace "** Execute (dry run) #{name}" return end application.trace "** Execute #{name}" if application.options.trace application.enhance_with_matching_rule(name) if @actions.empty? if opts = Hash.try_convert(args) and !opts.empty? @actions.each { |act| act.call(self, args, **opts) } else @actions.each { |act| act.call(self, args) } end end # Is this task needed? def needed? true end # Timestamp for this task. Basic tasks return the current time for their # time stamp. Other tasks can be more sophisticated. def timestamp Time.now end # Add a description to the task. The description can consist of an option # argument list (enclosed brackets) and an optional comment. def add_description(description) return unless description comment = description.strip add_comment(comment) if comment && !comment.empty? end def comment=(comment) # :nodoc: add_comment(comment) end def add_comment(comment) # :nodoc: return if comment.nil? @comments << comment unless @comments.include?(comment) end private :add_comment # Full collection of comments. Multiple comments are separated by # newlines. def full_comment transform_comments("\n") end # First line (or sentence) of all comments. Multiple comments are # separated by a "/". def comment transform_comments(" / ") { |c| first_sentence(c) } end # Transform the list of comments as specified by the block and # join with the separator. def transform_comments(separator, &block) if @comments.empty? nil else block ||= lambda { |c| c } @comments.map(&block).join(separator) end end private :transform_comments # Get the first sentence in a string. The sentence is terminated # by the first period, exclamation mark, or the end of the line. # Decimal points do not count as periods. def first_sentence(string) string.split(/(?<=\w)(\.|!)[ \t]|(\.$|!)|\n/).first end private :first_sentence # Set the names of the arguments for this task. +args+ should be # an array of symbols, one for each argument name. def set_arg_names(args) @arg_names = args.map(&:to_sym) end # Return a string describing the internal state of a task. Useful for # debugging. def investigation result = "------------------------------\n".dup result << "Investigating #{name}\n" result << "class: #{self.class}\n" result << "task needed: #{needed?}\n" result << "timestamp: #{timestamp}\n" result << "pre-requisites: \n" prereqs = prerequisite_tasks prereqs.sort! { |a, b| a.timestamp <=> b.timestamp } prereqs.each do |p| result << "--#{p.name} (#{p.timestamp})\n" end latest_prereq = prerequisite_tasks.map(&:timestamp).max result << "latest-prerequisite time: #{latest_prereq}\n" result << "................................\n\n" return result end # Format dependencies parameter to pass to task. def self.format_deps(deps) deps = [deps] unless deps.respond_to?(:to_ary) deps.map { |d| Rake.from_pathname(d).to_s } end # Add order only dependencies. def |(deps) @order_only_prerequisites |= Task.format_deps(deps) - @prerequisites self end # ---------------------------------------------------------------- # Rake Module Methods # class << self # Clear the task list. This cause rake to immediately forget all the # tasks that have been assigned. (Normally used in the unit tests.) def clear Rake.application.clear end # List of all defined tasks. def tasks Rake.application.tasks end # Return a task with the given name. If the task is not currently # known, try to synthesize one from the defined rules. If no rules are # found, but an existing file matches the task name, assume it is a file # task with no dependencies or actions. def [](task_name) Rake.application[task_name] end # TRUE if the task name is already defined. def task_defined?(task_name) Rake.application.lookup(task_name) != nil end # Define a task given +args+ and an option block. If a rule with the # given name already exists, the prerequisites and actions are added to # the existing task. Returns the defined task. def define_task(*args, &block) Rake.application.define_task(self, *args, &block) end # Define a rule for synthesizing tasks. def create_rule(*args, &block) Rake.application.create_rule(*args, &block) end # Apply the scope to the task name according to the rules for # this kind of task. Generic tasks will accept the scope as # part of the name. def scope_name(scope, task_name) scope.path_with_task_name(task_name) end end # class << Rake::Task end # class Rake::Task end # frozen_string_literal: true require "rake" require "rake/tasklib" module Rake # Create a task that runs a set of tests. # # Example: # require "rake/testtask" # # Rake::TestTask.new do |t| # t.libs << "test" # t.test_files = FileList['test/test*.rb'] # t.verbose = true # end # # If rake is invoked with a "TEST=filename" command line option, # then the list of test files will be overridden to include only the # filename specified on the command line. This provides an easy way # to run just one test. # # If rake is invoked with a "TESTOPTS=options" command line option, # then the given options are passed to the test process after a # '--'. This allows Test::Unit options to be passed to the test # suite. # # Examples: # # rake test # run tests normally # rake test TEST=just_one_file.rb # run just one test file. # rake test TESTOPTS="-v" # run in verbose mode # rake test TESTOPTS="--runner=fox" # use the fox test runner # class TestTask < TaskLib # Name of test task. (default is :test) attr_accessor :name # List of directories added to $LOAD_PATH before running the # tests. (default is 'lib') attr_accessor :libs # True if verbose test output desired. (default is false) attr_accessor :verbose # Test options passed to the test suite. An explicit # TESTOPTS=opts on the command line will override this. (default # is NONE) attr_accessor :options # Request that the tests be run with the warning flag set. # E.g. warning=true implies "ruby -w" used to run the tests. # (default is true) attr_accessor :warning # Glob pattern to match test files. (default is 'test/test*.rb') attr_accessor :pattern # Style of test loader to use. Options are: # # * :rake -- Rake provided test loading script (default). # * :testrb -- Ruby provided test loading script. # * :direct -- Load tests using command line loader. # attr_accessor :loader # Array of command line options to pass to ruby when running test loader. attr_accessor :ruby_opts # Description of the test task. (default is 'Run tests') attr_accessor :description # Task prerequisites. attr_accessor :deps # Explicitly define the list of test files to be included in a # test. +list+ is expected to be an array of file names (a # FileList is acceptable). If both +pattern+ and +test_files+ are # used, then the list of test files is the union of the two. def test_files=(list) @test_files = list end # Create a testing task. def initialize(name=:test) @name = name @libs = ["lib"] @pattern = nil @options = nil @test_files = nil @verbose = false @warning = true @loader = :rake @ruby_opts = [] @description = "Run tests" + (@name == :test ? "" : " for #{@name}") @deps = [] if @name.is_a?(Hash) @deps = @name.values.first @name = @name.keys.first end yield self if block_given? @pattern = "test/test*.rb" if @pattern.nil? && @test_files.nil? define end # Create the tasks defined by this task lib. def define desc @description task @name => Array(deps) do FileUtilsExt.verbose(@verbose) do puts "Use TESTOPTS=\"--verbose\" to pass --verbose" \ ", etc. to runners." if ARGV.include? "--verbose" args = "#{ruby_opts_string} #{run_code} " + "#{file_list_string} #{option_list}" ruby args do |ok, status| if !ok && status.respond_to?(:signaled?) && status.signaled? raise SignalException.new(status.termsig) elsif !ok status = "Command failed with status (#{status.exitstatus})" details = ": [ruby #{args}]" message = if Rake.application.options.trace or @verbose status + details else status end fail message end end end end self end def option_list # :nodoc: (ENV["TESTOPTS"] || ENV["TESTOPT"] || ENV["TEST_OPTS"] || ENV["TEST_OPT"] || @options || "") end def ruby_opts_string # :nodoc: opts = @ruby_opts.dup opts.unshift("-I\"#{lib_path}\"") unless @libs.empty? opts.unshift("-w") if @warning opts.join(" ") end def lib_path # :nodoc: @libs.join(File::PATH_SEPARATOR) end def file_list_string # :nodoc: file_list.map { |fn| "\"#{fn}\"" }.join(" ") end def file_list # :nodoc: if ENV["TEST"] FileList[ENV["TEST"]] else result = [] result += @test_files.to_a if @test_files result += FileList[@pattern].to_a if @pattern result end end def ruby_version # :nodoc: RUBY_VERSION end def run_code # :nodoc: case @loader when :direct "-e \"ARGV.each{|f| require f}\"" when :testrb "-S testrb" when :rake "#{__dir__}/rake_test_loader.rb" end end end end # frozen_string_literal: true module Rake ## # Mixin for creating easily cloned objects. module Cloneable # :nodoc: # The hook that is invoked by 'clone' and 'dup' methods. def initialize_copy(source) super source.instance_variables.each do |var| src_value = source.instance_variable_get(var) value = src_value.clone rescue src_value instance_variable_set(var, value) end end end end # frozen_string_literal: true require "rbconfig" module Rake # Win 32 interface methods for Rake. Windows specific functionality # will be placed here to collect that knowledge in one spot. module Win32 # :nodoc: all # Error indicating a problem in locating the home directory on a # Win32 system. class Win32HomeError < RuntimeError end class << self # True if running on a windows system. def windows? RbConfig::CONFIG["host_os"] =~ %r!(msdos|mswin|djgpp|mingw|[Ww]indows)! end # The standard directory containing system wide rake files on # Win 32 systems. Try the following environment variables (in # order): # # * HOME # * HOMEDRIVE + HOMEPATH # * APPDATA # * USERPROFILE # # If the above are not defined, the return nil. def win32_system_dir #:nodoc: win32_shared_path = ENV["HOME"] if win32_shared_path.nil? && ENV["HOMEDRIVE"] && ENV["HOMEPATH"] win32_shared_path = ENV["HOMEDRIVE"] + ENV["HOMEPATH"] end win32_shared_path ||= ENV["APPDATA"] win32_shared_path ||= ENV["USERPROFILE"] raise Win32HomeError, "Unable to determine home path environment variable." if win32_shared_path.nil? or win32_shared_path.empty? normalize(File.join(win32_shared_path, "Rake")) end # Normalize a win32 path so that the slashes are all forward slashes. def normalize(path) path.gsub(/\\/, "/") end end end end # frozen_string_literal: true module Rake ## # Exit status class for times the system just gives us a nil. class PseudoStatus # :nodoc: all attr_reader :exitstatus def initialize(code=0) @exitstatus = code end def to_i @exitstatus << 8 end def >>(n) to_i >> n end def stopped? false end def exited? true end end end # frozen_string_literal: true require "rake/task" require "rake/early_time" module Rake # A FileTask is a task that includes time based dependencies. If any of a # FileTask's prerequisites have a timestamp that is later than the file # represented by this task, then the file must be rebuilt (using the # supplied actions). # class FileTask < Task # Is this file task needed? Yes if it doesn't exist, or if its time stamp # is out of date. def needed? begin out_of_date?(File.mtime(name)) || @application.options.build_all rescue Errno::ENOENT true end end # Time stamp for file task. def timestamp begin File.mtime(name) rescue Errno::ENOENT Rake::LATE end end private # Are there any prerequisites with a later time than the given time stamp? def out_of_date?(stamp) all_prerequisite_tasks.any? { |prereq| prereq_task = application[prereq, @scope] if prereq_task.instance_of?(Rake::FileTask) prereq_task.timestamp > stamp || @application.options.build_all else prereq_task.timestamp > stamp end } end # ---------------------------------------------------------------- # Task class methods. # class << self # Apply the scope to the task name according to the rules for this kind # of task. File based tasks ignore the scope when creating the name. def scope_name(scope, task_name) Rake.from_pathname(task_name) end end end end # frozen_string_literal: true module Rake # InvocationChain tracks the chain of task invocations to detect # circular dependencies. class InvocationChain < LinkedList # Is the invocation already in the chain? def member?(invocation) head == invocation || tail.member?(invocation) end # Append an invocation to the chain of invocations. It is an error # if the invocation already listed. def append(invocation) if member?(invocation) fail RuntimeError, "Circular dependency detected: #{to_s} => #{invocation}" end conj(invocation) end # Convert to string, ie: TOP => invocation => invocation def to_s "#{prefix}#{head}" end # Class level append. def self.append(invocation, chain) chain.append(invocation) end private def prefix "#{tail} => " end # Null object for an empty chain. class EmptyInvocationChain < LinkedList::EmptyLinkedList @parent = InvocationChain def member?(obj) false end def append(invocation) conj(invocation) end def to_s "TOP" end end EMPTY = EmptyInvocationChain.new end end # frozen_string_literal: true module Rake # Error indicating an ill-formed task declaration. class TaskArgumentError < ArgumentError end end # frozen_string_literal: true # The 'rake/clean' file defines two file lists (CLEAN and CLOBBER) and # two rake tasks (:clean and :clobber). # # [:clean] Clean up the project by deleting scratch files and backup # files. Add files to the CLEAN file list to have the :clean # target handle them. # # [:clobber] Clobber all generated and non-source files in a project. # The task depends on :clean, so all the clean files will # be deleted as well as files in the CLOBBER file list. # The intent of this task is to return a project to its # pristine, just unpacked state. require "rake" # :stopdoc: module Rake module Cleaner extend FileUtils module_function def cleanup_files(file_names) file_names.each do |file_name| cleanup(file_name) end end def cleanup(file_name, **opts) begin opts = { verbose: Rake.application.options.trace }.merge(opts) rm_r file_name, **opts rescue StandardError => ex puts "Failed to remove #{file_name}: #{ex}" unless file_already_gone?(file_name) end end def file_already_gone?(file_name) return false if File.exist?(file_name) path = file_name prev = nil while path = File.dirname(path) return false if cant_be_deleted?(path) break if [prev, "."].include?(path) prev = path end true end private_class_method :file_already_gone? def cant_be_deleted?(path_name) File.exist?(path_name) && (!File.readable?(path_name) || !File.executable?(path_name)) end private_class_method :cant_be_deleted? end end CLEAN = ::Rake::FileList["**/*~", "**/*.bak", "**/core"] CLEAN.clear_exclude.exclude { |fn| fn.pathmap("%f").downcase == "core" && File.directory?(fn) } desc "Remove any temporary products." task :clean do Rake::Cleaner.cleanup_files(CLEAN) end CLOBBER = ::Rake::FileList.new desc "Remove any generated files." task clobber: [:clean] do Rake::Cleaner.cleanup_files(CLOBBER) end # frozen_string_literal: true # Rake DSL functions. require "rake/file_utils_ext" module Rake ## # DSL is a module that provides #task, #desc, #namespace, etc. Use this # when you'd like to use rake outside the top level scope. # # For a Rakefile you run from the command line this module is automatically # included. module DSL #-- # Include the FileUtils file manipulation functions in the top # level module, but mark them private so that they don't # unintentionally define methods on other objects. #++ include FileUtilsExt private(*FileUtils.instance_methods(false)) private(*FileUtilsExt.instance_methods(false)) private # :call-seq: # task(task_name) # task(task_name: dependencies) # task(task_name, arguments => dependencies) # # Declare a basic task. The +task_name+ is always the first argument. If # the task name contains a ":" it is defined in that namespace. # # The +dependencies+ may be a single task name or an Array of task names. # The +argument+ (a single name) or +arguments+ (an Array of names) define # the arguments provided to the task. # # The task, argument and dependency names may be either symbols or # strings. # # A task with a single dependency: # # task clobber: %w[clean] do # rm_rf "html" # end # # A task with an argument and a dependency: # # task :package, [:version] => :test do |t, args| # # ... # end # # To invoke this task from the command line: # # $ rake package[1.2.3] # def task(*args, &block) # :doc: Rake::Task.define_task(*args, &block) end # Declare a file task. # # Example: # file "config.cfg" => ["config.template"] do # open("config.cfg", "w") do |outfile| # open("config.template") do |infile| # while line = infile.gets # outfile.puts line # end # end # end # end # def file(*args, &block) # :doc: Rake::FileTask.define_task(*args, &block) end # Declare a file creation task. # (Mainly used for the directory command). def file_create(*args, &block) Rake::FileCreationTask.define_task(*args, &block) end # Declare a set of files tasks to create the given directories on # demand. # # Example: # directory "testdata/doc" # def directory(*args, &block) # :doc: result = file_create(*args, &block) dir, _ = *Rake.application.resolve_args(args) dir = Rake.from_pathname(dir) Rake.each_dir_parent(dir) do |d| file_create d do |t| mkdir_p t.name unless File.exist?(t.name) end end result end # Declare a task that performs its prerequisites in # parallel. Multitasks does *not* guarantee that its prerequisites # will execute in any given order (which is obvious when you think # about it) # # Example: # multitask deploy: %w[deploy_gem deploy_rdoc] # def multitask(*args, &block) # :doc: Rake::MultiTask.define_task(*args, &block) end # Create a new rake namespace and use it for evaluating the given # block. Returns a NameSpace object that can be used to lookup # tasks defined in the namespace. # # Example: # # ns = namespace "nested" do # # the "nested:run" task # task :run # end # task_run = ns[:run] # find :run in the given namespace. # # Tasks can also be defined in a namespace by using a ":" in the task # name: # # task "nested:test" do # # ... # end # def namespace(name=nil, &block) # :doc: name = name.to_s if name.kind_of?(Symbol) name = name.to_str if name.respond_to?(:to_str) unless name.kind_of?(String) || name.nil? raise ArgumentError, "Expected a String or Symbol for a namespace name" end Rake.application.in_namespace(name, &block) end # Declare a rule for auto-tasks. # # Example: # rule '.o' => '.c' do |t| # sh 'cc', '-o', t.name, t.source # end # def rule(*args, &block) # :doc: Rake::Task.create_rule(*args, &block) end # Describes the next rake task. Duplicate descriptions are discarded. # Descriptions are shown with <code>rake -T</code> (up to the first # sentence) and <code>rake -D</code> (the entire description). # # Example: # desc "Run the Unit Tests" # task test: [:build] do # # ... run tests # end # def desc(description) # :doc: Rake.application.last_description = description end # Import the partial Rakefiles +fn+. Imported files are loaded # _after_ the current file is completely loaded. This allows the # import statement to appear anywhere in the importing file, and yet # allowing the imported files to depend on objects defined in the # importing file. # # A common use of the import statement is to include files # containing dependency declarations. # # See also the --rakelibdir command line option. # # Example: # import ".depend", "my_rules" # def import(*fns) # :doc: fns.each do |fn| Rake.application.add_import(fn) end end end extend FileUtilsExt end # Extend the main object with the DSL commands. This allows top-level # calls to task, etc. to work from a Rakefile without polluting the # object inheritance tree. self.extend Rake::DSL # frozen_string_literal: true module Rake VERSION = "13.1.0" module Version # :nodoc: all MAJOR, MINOR, BUILD, *OTHER = Rake::VERSION.split "." NUMBERS = [MAJOR, MINOR, BUILD, *OTHER] end end # frozen_string_literal: true module Rake # Polylithic linked list structure used to implement several data # structures in Rake. class LinkedList include Enumerable attr_reader :head, :tail # Polymorphically add a new element to the head of a list. The # type of head node will be the same list type as the tail. def conj(item) self.class.cons(item, self) end # Is the list empty? # .make guards against a list being empty making any instantiated LinkedList # object not empty by default # You should consider overriding this method if you implement your own .make method def empty? false end # Lists are structurally equivalent. def ==(other) current = self while !current.empty? && !other.empty? return false if current.head != other.head current = current.tail other = other.tail end current.empty? && other.empty? end # Convert to string: LL(item, item...) def to_s items = map(&:to_s).join(", ") "LL(#{items})" end # Same as +to_s+, but with inspected items. def inspect items = map(&:inspect).join(", ") "LL(#{items})" end # For each item in the list. def each current = self while !current.empty? yield(current.head) current = current.tail end self end # Make a list out of the given arguments. This method is # polymorphic def self.make(*args) # return an EmptyLinkedList if there are no arguments return empty if !args || args.empty? # build a LinkedList by starting at the tail and iterating # through each argument # inject takes an EmptyLinkedList to start args.reverse.inject(empty) do |list, item| list = cons(item, list) list # return the newly created list for each item in the block end end # Cons a new head onto the tail list. def self.cons(head, tail) new(head, tail) end # The standard empty list class for the given LinkedList class. def self.empty self::EMPTY end protected def initialize(head, tail=EMPTY) @head = head @tail = tail end # Represent an empty list, using the Null Object Pattern. # # When inheriting from the LinkedList class, you should implement # a type specific Empty class as well. Make sure you set the class # instance variable @parent to the associated list class (this # allows conj, cons and make to work polymorphically). class EmptyLinkedList < LinkedList @parent = LinkedList def initialize end def empty? true end def self.cons(head, tail) @parent.cons(head, tail) end end EMPTY = EmptyLinkedList.new end end # frozen_string_literal: true module Rake # LateTime is a fake timestamp that occurs _after_ any other time value. class LateTime include Comparable include Singleton def <=>(other) 1 end def to_s "<LATE TIME>" end end LATE = LateTime.instance end # frozen_string_literal: true module Rake module InvocationExceptionMixin # Return the invocation chain (list of Rake tasks) that were in # effect when this exception was detected by rake. May be null if # no tasks were active. def chain @rake_invocation_chain ||= nil end # Set the invocation chain in effect when this exception was # detected. def chain=(value) @rake_invocation_chain = value end end end # frozen_string_literal: true module Rake # A Promise object represents a promise to do work (a chore) in the # future. The promise is created with a block and a list of # arguments for the block. Calling value will return the value of # the promised chore. # # Used by ThreadPool. # class Promise # :nodoc: all NOT_SET = Object.new.freeze # :nodoc: attr_accessor :recorder # Create a promise to do the chore specified by the block. def initialize(args, &block) @mutex = Mutex.new @result = NOT_SET @error = NOT_SET @args = args @block = block end # Return the value of this promise. # # If the promised chore is not yet complete, then do the work # synchronously. We will wait. def value unless complete? stat :sleeping_on, item_id: object_id @mutex.synchronize do stat :has_lock_on, item_id: object_id chore stat :releasing_lock_on, item_id: object_id end end error? ? raise(@error) : @result end # If no one else is working this promise, go ahead and do the chore. def work stat :attempting_lock_on, item_id: object_id if @mutex.try_lock stat :has_lock_on, item_id: object_id chore stat :releasing_lock_on, item_id: object_id @mutex.unlock else stat :bailed_on, item_id: object_id end end private # Perform the chore promised def chore if complete? stat :found_completed, item_id: object_id return end stat :will_execute, item_id: object_id begin @result = @block.call(*@args) rescue Exception => e @error = e end stat :did_execute, item_id: object_id discard end # Do we have a result for the promise def result? !@result.equal?(NOT_SET) end # Did the promise throw an error def error? !@error.equal?(NOT_SET) end # Are we done with the promise def complete? result? || error? end # free up these items for the GC def discard @args = nil @block = nil end # Record execution statistics if there is a recorder def stat(*args) @recorder.call(*args) if @recorder end end end # frozen_string_literal: true ## # The NameSpace class will lookup task names in the scope defined by a # +namespace+ command. class Rake::NameSpace ## # Create a namespace lookup object using the given task manager # and the list of scopes. def initialize(task_manager, scope_list) @task_manager = task_manager @scope = scope_list.dup end ## # Lookup a task named +name+ in the namespace. def [](name) @task_manager.lookup(name, @scope) end ## # The scope of the namespace (a LinkedList) def scope @scope.dup end ## # Return the list of tasks defined in this and nested namespaces. def tasks @task_manager.tasks_in_scope(@scope) end end # frozen_string_literal: true require "rake/file_utils" module Rake # # FileUtilsExt provides a custom version of the FileUtils methods # that respond to the <tt>verbose</tt> and <tt>nowrite</tt> # commands. # module FileUtilsExt include FileUtils class << self attr_accessor :verbose_flag, :nowrite_flag end DEFAULT = Object.new FileUtilsExt.verbose_flag = DEFAULT FileUtilsExt.nowrite_flag = false FileUtils.commands.each do |name| opts = FileUtils.options_of name default_options = [] if opts.include?("verbose") default_options << "verbose: FileUtilsExt.verbose_flag" end if opts.include?("noop") default_options << "noop: FileUtilsExt.nowrite_flag" end next if default_options.empty? module_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{name}(*args, **options, &block) super(*args, #{default_options.join(', ')}, **options, &block) end EOS end # Get/set the verbose flag controlling output from the FileUtils # utilities. If verbose is true, then the utility method is # echoed to standard output. # # Examples: # verbose # return the current value of the # # verbose flag # verbose(v) # set the verbose flag to _v_. # verbose(v) { code } # Execute code with the verbose flag set # # temporarily to _v_. Return to the # # original value when code is done. def verbose(value=nil) oldvalue = FileUtilsExt.verbose_flag FileUtilsExt.verbose_flag = value unless value.nil? if block_given? begin yield ensure FileUtilsExt.verbose_flag = oldvalue end end FileUtilsExt.verbose_flag end # Get/set the nowrite flag controlling output from the FileUtils # utilities. If verbose is true, then the utility method is # echoed to standard output. # # Examples: # nowrite # return the current value of the # # nowrite flag # nowrite(v) # set the nowrite flag to _v_. # nowrite(v) { code } # Execute code with the nowrite flag set # # temporarily to _v_. Return to the # # original value when code is done. def nowrite(value=nil) oldvalue = FileUtilsExt.nowrite_flag FileUtilsExt.nowrite_flag = value unless value.nil? if block_given? begin yield ensure FileUtilsExt.nowrite_flag = oldvalue end end oldvalue end # Use this function to prevent potentially destructive ruby code # from running when the :nowrite flag is set. # # Example: # # when_writing("Building Project") do # project.build # end # # The following code will build the project under normal # conditions. If the nowrite(true) flag is set, then the example # will print: # # DRYRUN: Building Project # # instead of actually building the project. # def when_writing(msg=nil) if FileUtilsExt.nowrite_flag $stderr.puts "DRYRUN: #{msg}" if msg else yield end end # Send the message to the default rake output (which is $stderr). def rake_output_message(message) $stderr.puts(message) end # Check that the options do not contain options not listed in # +optdecl+. An ArgumentError exception is thrown if non-declared # options are found. def rake_check_options(options, *optdecl) h = options.dup optdecl.each do |name| h.delete name end raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty? end extend self end end # frozen_string_literal: true module Rake class Scope < LinkedList # :nodoc: all # Path for the scope. def path map(&:to_s).reverse.join(":") end # Path for the scope + the named path. def path_with_task_name(task_name) "#{path}:#{task_name}" end # Trim +n+ innermost scope levels from the scope. In no case will # this trim beyond the toplevel scope. def trim(n) result = self while n > 0 && !result.empty? result = result.tail n -= 1 end result end # Scope lists always end with an EmptyScope object. See Null # Object Pattern) class EmptyScope < EmptyLinkedList @parent = Scope def path "" end def path_with_task_name(task_name) task_name end end # Singleton null object for an empty scope. EMPTY = EmptyScope.new end end # frozen_string_literal: true require "rake/file_list" # Load the test files from the command line. argv = ARGV.select do |argument| case argument when /^-/ then argument when /\*/ then Rake::FileList[argument].to_a.each do |file| require File.expand_path file end false else path = File.expand_path argument abort "\nFile does not exist: #{path}\n\n" unless File.exist?(path) require path false end end ARGV.replace argv # frozen_string_literal: true module Rake ## # TaskArguments manage the arguments passed to a task. # class TaskArguments include Enumerable # Argument names attr_reader :names # Create a TaskArgument object with a list of argument +names+ and a set # of associated +values+. +parent+ is the parent argument object. def initialize(names, values, parent=nil) @names = names @parent = parent @hash = {} @values = values names.each_with_index { |name, i| next if values[i].nil? || values[i] == "" @hash[name.to_sym] = values[i] } end # Retrieve the complete array of sequential values def to_a @values.dup end # Retrieve the list of values not associated with named arguments def extras @values[@names.length..-1] || [] end # Create a new argument scope using the prerequisite argument # names. def new_scope(names) values = names.map { |n| self[n] } self.class.new(names, values + extras, self) end # Find an argument value by name or index. def [](index) lookup(index.to_sym) end # Specify a hash of default values for task arguments. Use the # defaults only if there is no specific value for the given # argument. def with_defaults(defaults) @hash = defaults.merge(@hash) end # Enumerates the arguments and their values def each(&block) @hash.each(&block) end # Extracts the argument values at +keys+ def values_at(*keys) keys.map { |k| lookup(k) } end # Returns the value of the given argument via method_missing def method_missing(sym, *args) lookup(sym.to_sym) end # Returns a Hash of arguments and their values def to_hash @hash.dup end def to_s # :nodoc: inspect end def inspect # :nodoc: inspection = @hash.map do |k,v| "#{k.to_s}: #{v.to_s}" end.join(", ") "#<#{self.class} #{inspection}>" end # Returns true if +key+ is one of the arguments def has_key?(key) @hash.has_key?(key) end alias key? has_key? def fetch(*args, &block) @hash.fetch(*args, &block) end protected def lookup(name) # :nodoc: if @hash.has_key?(name) @hash[name] elsif @parent @parent.lookup(name) end end end EMPTY_TASK_ARGS = TaskArguments.new([], []) # :nodoc: end # frozen_string_literal: true require "rake/file_task" require "rake/early_time" module Rake # A FileCreationTask is a file task that when used as a dependency will be # needed if and only if the file has not been created. Once created, it is # not re-triggered if any of its dependencies are newer, nor does trigger # any rebuilds of tasks that depend on it whenever it is updated. # class FileCreationTask < FileTask # Is this file task needed? Yes if it doesn't exist. def needed? !File.exist?(name) end # Time stamp for file creation task. This time stamp is earlier # than any other time stamp. def timestamp Rake::EARLY end end end # frozen_string_literal: true module Rake # Default Rakefile loader used by +import+. class DefaultLoader ## # Loads a rakefile into the current application from +fn+ def load(fn) Rake.load_rakefile(File.expand_path(fn)) end end end # frozen_string_literal: true require "rake" module Rake # Base class for Task Libraries. class TaskLib include Cloneable include Rake::DSL end end # frozen_string_literal: true module Rake # Include PrivateReader to use +private_reader+. module PrivateReader # :nodoc: all def self.included(base) base.extend(ClassMethods) end module ClassMethods # Declare a list of private accessors def private_reader(*names) attr_reader(*names) private(*names) end end end end # frozen_string_literal: true require "rake/cloneable" require "rake/file_utils_ext" require "rake/ext/string" module Rake ## # A FileList is essentially an array with a few helper methods defined to # make file manipulation a bit easier. # # FileLists are lazy. When given a list of glob patterns for possible files # to be included in the file list, instead of searching the file structures # to find the files, a FileList holds the pattern for latter use. # # This allows us to define a number of FileList to match any number of # files, but only search out the actual files when then FileList itself is # actually used. The key is that the first time an element of the # FileList/Array is requested, the pending patterns are resolved into a real # list of file names. # class FileList include Cloneable # == Method Delegation # # The lazy evaluation magic of FileLists happens by implementing all the # array specific methods to call +resolve+ before delegating the heavy # lifting to an embedded array object (@items). # # In addition, there are two kinds of delegation calls. The regular kind # delegates to the @items array and returns the result directly. Well, # almost directly. It checks if the returned value is the @items object # itself, and if so will return the FileList object instead. # # The second kind of delegation call is used in methods that normally # return a new Array object. We want to capture the return value of these # methods and wrap them in a new FileList object. We enumerate these # methods in the +SPECIAL_RETURN+ list below. # List of array methods (that are not in +Object+) that need to be # delegated. ARRAY_METHODS = (Array.instance_methods - Object.instance_methods).map(&:to_s) # List of additional methods that must be delegated. MUST_DEFINE = %w[inspect <=>] # List of methods that should not be delegated here (we define special # versions of them explicitly below). MUST_NOT_DEFINE = %w[to_a to_ary partition * <<] # List of delegated methods that return new array values which need # wrapping. SPECIAL_RETURN = %w[ map collect sort sort_by select find_all reject grep compact flatten uniq values_at + - & | ] DELEGATING_METHODS = (ARRAY_METHODS + MUST_DEFINE - MUST_NOT_DEFINE).map(&:to_s).sort.uniq # Now do the delegation. DELEGATING_METHODS.each do |sym| if SPECIAL_RETURN.include?(sym) ln = __LINE__ + 1 class_eval %{ def #{sym}(*args, &block) resolve result = @items.send(:#{sym}, *args, &block) self.class.new.import(result) end }, __FILE__, ln else ln = __LINE__ + 1 class_eval %{ def #{sym}(*args, &block) resolve result = @items.send(:#{sym}, *args, &block) result.object_id == @items.object_id ? self : result end }, __FILE__, ln end end GLOB_PATTERN = %r{[*?\[\{]} # Create a file list from the globbable patterns given. If you wish to # perform multiple includes or excludes at object build time, use the # "yield self" pattern. # # Example: # file_list = FileList.new('lib/**/*.rb', 'test/test*.rb') # # pkg_files = FileList.new('lib/**/*') do |fl| # fl.exclude(/\bCVS\b/) # end # def initialize(*patterns) @pending_add = [] @pending = false @exclude_patterns = DEFAULT_IGNORE_PATTERNS.dup @exclude_procs = DEFAULT_IGNORE_PROCS.dup @items = [] patterns.each { |pattern| include(pattern) } yield self if block_given? end # Add file names defined by glob patterns to the file list. If an array # is given, add each element of the array. # # Example: # file_list.include("*.java", "*.cfg") # file_list.include %w( math.c lib.h *.o ) # def include(*filenames) # TODO: check for pending filenames.each do |fn| if fn.respond_to? :to_ary include(*fn.to_ary) else @pending_add << Rake.from_pathname(fn) end end @pending = true self end alias :add :include # Register a list of file name patterns that should be excluded from the # list. Patterns may be regular expressions, glob patterns or regular # strings. In addition, a block given to exclude will remove entries that # return true when given to the block. # # Note that glob patterns are expanded against the file system. If a file # is explicitly added to a file list, but does not exist in the file # system, then an glob pattern in the exclude list will not exclude the # file. # # Examples: # FileList['a.c', 'b.c'].exclude("a.c") => ['b.c'] # FileList['a.c', 'b.c'].exclude(/^a/) => ['b.c'] # # If "a.c" is a file, then ... # FileList['a.c', 'b.c'].exclude("a.*") => ['b.c'] # # If "a.c" is not a file, then ... # FileList['a.c', 'b.c'].exclude("a.*") => ['a.c', 'b.c'] # def exclude(*patterns, &block) patterns.each do |pat| if pat.respond_to? :to_ary exclude(*pat.to_ary) else @exclude_patterns << Rake.from_pathname(pat) end end @exclude_procs << block if block_given? resolve_exclude unless @pending self end # Clear all the exclude patterns so that we exclude nothing. def clear_exclude @exclude_patterns = [] @exclude_procs = [] self end # A FileList is equal through array equality. def ==(array) to_ary == array end # Return the internal array object. def to_a resolve @items end # Return the internal array object. def to_ary to_a end # Lie about our class. def is_a?(klass) klass == Array || super(klass) end alias kind_of? is_a? # Redefine * to return either a string or a new file list. def *(other) result = @items * other case result when Array self.class.new.import(result) else result end end def <<(obj) resolve @items << Rake.from_pathname(obj) self end # Resolve all the pending adds now. def resolve if @pending @pending = false @pending_add.each do |fn| resolve_add(fn) end @pending_add = [] resolve_exclude end self end def resolve_add(fn) # :nodoc: case fn when GLOB_PATTERN add_matching(fn) else self << fn end end private :resolve_add def resolve_exclude # :nodoc: reject! { |fn| excluded_from_list?(fn) } self end private :resolve_exclude # Return a new FileList with the results of running +sub+ against each # element of the original list. # # Example: # FileList['a.c', 'b.c'].sub(/\.c$/, '.o') => ['a.o', 'b.o'] # def sub(pat, rep) inject(self.class.new) { |res, fn| res << fn.sub(pat, rep) } end # Return a new FileList with the results of running +gsub+ against each # element of the original list. # # Example: # FileList['lib/test/file', 'x/y'].gsub(/\//, "\\") # => ['lib\\test\\file', 'x\\y'] # def gsub(pat, rep) inject(self.class.new) { |res, fn| res << fn.gsub(pat, rep) } end # Same as +sub+ except that the original file list is modified. def sub!(pat, rep) each_with_index { |fn, i| self[i] = fn.sub(pat, rep) } self end # Same as +gsub+ except that the original file list is modified. def gsub!(pat, rep) each_with_index { |fn, i| self[i] = fn.gsub(pat, rep) } self end # Apply the pathmap spec to each of the included file names, returning a # new file list with the modified paths. (See String#pathmap for # details.) def pathmap(spec=nil, &block) collect { |fn| fn.pathmap(spec, &block) } end # Return a new FileList with <tt>String#ext</tt> method applied to # each member of the array. # # This method is a shortcut for: # # array.collect { |item| item.ext(newext) } # # +ext+ is a user added method for the Array class. def ext(newext="") collect { |fn| fn.ext(newext) } end # Grep each of the files in the filelist using the given pattern. If a # block is given, call the block on each matching line, passing the file # name, line number, and the matching line of text. If no block is given, # a standard emacs style file:linenumber:line message will be printed to # standard out. Returns the number of matched items. def egrep(pattern, *options) matched = 0 each do |fn| begin File.open(fn, "r", *options) do |inf| count = 0 inf.each do |line| count += 1 if pattern.match(line) matched += 1 if block_given? yield fn, count, line else puts "#{fn}:#{count}:#{line}" end end end end rescue StandardError => ex $stderr.puts "Error while processing '#{fn}': #{ex}" end end matched end # Return a new file list that only contains file names from the current # file list that exist on the file system. def existing select { |fn| File.exist?(fn) }.uniq end # Modify the current file list so that it contains only file name that # exist on the file system. def existing! resolve @items = @items.select { |fn| File.exist?(fn) }.uniq self end # FileList version of partition. Needed because the nested arrays should # be FileLists in this version. def partition(&block) # :nodoc: resolve result = @items.partition(&block) [ self.class.new.import(result[0]), self.class.new.import(result[1]), ] end # Convert a FileList to a string by joining all elements with a space. def to_s resolve self.join(" ") end # Add matching glob patterns. def add_matching(pattern) self.class.glob(pattern).each do |fn| self << fn unless excluded_from_list?(fn) end end private :add_matching # Should the given file name be excluded from the list? # # NOTE: This method was formerly named "exclude?", but Rails # introduced an exclude? method as an array method and setup a # conflict with file list. We renamed the method to avoid # confusion. If you were using "FileList#exclude?" in your user # code, you will need to update. def excluded_from_list?(fn) return true if @exclude_patterns.any? do |pat| case pat when Regexp fn =~ pat when GLOB_PATTERN flags = File::FNM_PATHNAME # Ruby <= 1.9.3 does not support File::FNM_EXTGLOB flags |= File::FNM_EXTGLOB if defined? File::FNM_EXTGLOB File.fnmatch?(pat, fn, flags) else fn == pat end end @exclude_procs.any? { |p| p.call(fn) } end DEFAULT_IGNORE_PATTERNS = [ /(^|[\/\\])CVS([\/\\]|$)/, /(^|[\/\\])\.svn([\/\\]|$)/, /\.bak$/, /~$/ ] DEFAULT_IGNORE_PROCS = [ proc { |fn| fn =~ /(^|[\/\\])core$/ && !File.directory?(fn) } ] def import(array) # :nodoc: @items = array self end class << self # Create a new file list including the files listed. Similar to: # # FileList.new(*args) def [](*args) new(*args) end # Get a sorted list of files matching the pattern. This method # should be preferred to Dir[pattern] and Dir.glob(pattern) because # the files returned are guaranteed to be sorted. def glob(pattern, *args) Dir.glob(pattern, *args).sort end end end end module Rake class << self # Yield each file or directory component. def each_dir_parent(dir) # :nodoc: old_length = nil while dir != "." && dir.length != old_length yield(dir) old_length = dir.length dir = File.dirname(dir) end end # Convert Pathname and Pathname-like objects to strings; # leave everything else alone def from_pathname(path) # :nodoc: path = path.to_path if path.respond_to?(:to_path) path = path.to_str if path.respond_to?(:to_str) path end end end # module Rake # frozen_string_literal: true require "rbconfig" require "fileutils" #-- # This a FileUtils extension that defines several additional commands to be # added to the FileUtils utility functions. module FileUtils # Path to the currently running Ruby program RUBY = ENV["RUBY"] || File.join( RbConfig::CONFIG["bindir"], RbConfig::CONFIG["ruby_install_name"] + RbConfig::CONFIG["EXEEXT"]). sub(/.*\s.*/m, '"\&"') # Run the system command +cmd+. If multiple arguments are given the command # is run directly (without the shell, same semantics as Kernel::exec and # Kernel::system). # # It is recommended you use the multiple argument form over interpolating # user input for both usability and security reasons. With the multiple # argument form you can easily process files with spaces or other shell # reserved characters in them. With the multiple argument form your rake # tasks are not vulnerable to users providing an argument like # <code>; rm # -rf /</code>. # # If a block is given, upon command completion the block is called with an # OK flag (true on a zero exit status) and a Process::Status object. # Without a block a RuntimeError is raised when the command exits non-zero. # # Examples: # # sh 'ls -ltr' # # sh 'ls', 'file with spaces' # # # check exit status after command runs # sh %{grep pattern file} do |ok, res| # if !ok # puts "pattern not found (status = #{res.exitstatus})" # end # end # def sh(*cmd, &block) options = (Hash === cmd.last) ? cmd.pop : {} shell_runner = block_given? ? block : create_shell_runner(cmd) set_verbose_option(options) verbose = options.delete :verbose noop = options.delete(:noop) || Rake::FileUtilsExt.nowrite_flag Rake.rake_output_message sh_show_command cmd if verbose unless noop res = (Hash === cmd.last) ? system(*cmd) : system(*cmd, options) status = $? status = Rake::PseudoStatus.new(1) if !res && status.nil? shell_runner.call(res, status) end end def create_shell_runner(cmd) # :nodoc: show_command = sh_show_command cmd lambda do |ok, status| ok or fail "Command failed with status (#{status.exitstatus}): " + "[#{show_command}]" end end private :create_shell_runner def sh_show_command(cmd) # :nodoc: cmd = cmd.dup if Hash === cmd.first env = cmd.first env = env.map { |name, value| "#{name}=#{value}" }.join " " cmd[0] = env end cmd.join " " end private :sh_show_command def set_verbose_option(options) # :nodoc: unless options.key? :verbose options[:verbose] = (Rake::FileUtilsExt.verbose_flag == Rake::FileUtilsExt::DEFAULT) || Rake::FileUtilsExt.verbose_flag end end private :set_verbose_option # Run a Ruby interpreter with the given arguments. # # Example: # ruby %{-pe '$_.upcase!' <README} # def ruby(*args, **options, &block) if args.length > 1 sh(RUBY, *args, **options, &block) else sh("#{RUBY} #{args.first}", **options, &block) end end LN_SUPPORTED = [true] # Attempt to do a normal file link, but fall back to a copy if the link # fails. def safe_ln(*args, **options) if LN_SUPPORTED[0] begin return options.empty? ? ln(*args) : ln(*args, **options) rescue StandardError, NotImplementedError LN_SUPPORTED[0] = false end end options.empty? ? cp(*args) : cp(*args, **options) end # Split a file path into individual directory names. # # Example: # split_all("a/b/c") => ['a', 'b', 'c'] # def split_all(path) head, tail = File.split(path) return [tail] if head == "." || tail == "/" return [head, tail] if head == "/" return split_all(head) + [tail] end end = Rake Command Line Usage Rake is invoked from the command line using: % rake [options ...] [VAR=VALUE ...] [targets ...] Options are: [<tt><em>name</em>=<em>value</em></tt>] Set the environment variable <em>name</em> to <em>value</em> during the execution of the <b>rake</b> command. You can access the value by using ENV['<em>name</em>']. [<tt>--all</tt> (-A)] Used in combination with the -T and -D options, will force those options to show all the tasks, even the ones without comments. [<tt>--backtrace</tt>{=_output_} (-n)] Enable a full backtrace (i.e. like --trace, but without the task tracing details). The _output_ parameter is optional, but if specified it controls where the backtrace output is sent. If _output_ is <tt>stdout</tt>, then backtrace output is directed to standard output. If _output_ is <tt>stderr</tt>, or if it is missing, then the backtrace output is sent to standard error. [<tt>--comments</tt>] Used in combination with the -W options to force the output to contain commented options only. This is the reverse of <tt>--all</tt>. [<tt>--describe</tt> _pattern_ (-D)] Describe the tasks (matching optional PATTERN), then exit. [<tt>--dry-run</tt> (-n)] Do a dry run. Print the tasks invoked and executed, but do not actually execute any of the actions. [<tt>--execute</tt> _code_ (-e)] Execute some Ruby code and exit. [<tt>--execute-print</tt> _code_ (-p)] Execute some Ruby code, print the result, and exit. [<tt>--execute-continue</tt> _code_ (-E)] Execute some Ruby code, then continue with normal task processing. [<tt>--help</tt> (-H)] Display some help text and exit. [<tt>--jobs</tt> _number_ (-j)] Specifies the maximum number of concurrent threads allowed. Rake will allocate threads as needed up to this maximum number. If omitted, Rake will attempt to estimate the number of CPUs on the system and add 4 to that number. The concurrent threads are used to execute the <tt>multitask</tt> prerequisites. Also see the <tt>-m</tt> option which turns all tasks into multitasks. Sample values: (no -j) : Allow up to (# of CPUs + 4) number of threads --jobs : Allow unlimited number of threads --jobs=1 : Allow only one thread (the main thread) --jobs=16 : Allow up to 16 concurrent threads [<tt>--job-stats</tt> _level_] Display job statistics at the completion of the run. By default, this will display the requested number of active threads (from the -j options) and the maximum number of threads in play at any given time. If the optional _level_ is <tt>history</tt>, then a complete trace of task history will be displayed on standard output. [<tt>--libdir</tt> _directory_ (-I)] Add _directory_ to the list of directories searched for require. [<tt>--multitask</tt> (-m)] Treat all tasks as multitasks. ('make/drake' semantics) [<tt>--nosearch</tt> (-N)] Do not search for a Rakefile in parent directories. [<tt>--prereqs</tt> (-P)] Display a list of all tasks and their immediate prerequisites. [<tt>--quiet</tt> (-q)] Do not echo commands from FileUtils. [<tt>--rakefile</tt> _filename_ (-f)] Use _filename_ as the name of the rakefile. The default rakefile names are +rakefile+ and +Rakefile+ (with +rakefile+ taking precedence). If the rakefile is not found in the current directory, +rake+ will search parent directories for a match. The directory where the Rakefile is found will become the current directory for the actions executed in the Rakefile. [<tt>--rakelibdir</tt> _rakelibdir_ (-R)] Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib') [<tt>--require</tt> _name_ (-r)] Require _name_ before executing the Rakefile. [<tt>--rules</tt>] Trace the rules resolution. [<tt>--silent (-s)</tt>] Like --quiet, but also suppresses the 'in directory' announcement. [<tt>--suppress-backtrace _pattern_ </tt>] Line matching the regular expression _pattern_ will be removed from the backtrace output. Note that the --backtrace option is the full backtrace without these lines suppressed. [<tt>--system</tt> (-g)] Use the system wide (global) rakefiles. The project Rakefile is ignored. By default, the system wide rakefiles are used only if no project Rakefile is found. On Unix-like system, the system wide rake files are located in $HOME/.rake. On a windows system they are stored in $APPDATA/Rake. [<tt>--no-system</tt> (-G)] Use the project level Rakefile, ignoring the system-wide (global) rakefiles. [<tt>--tasks</tt> <em>pattern</em> (-T)] Display a list of the major tasks and their comments. Comments are defined using the "desc" command. If a pattern is given, then only tasks matching the pattern are displayed. [<tt>--trace</tt>{=_output_} (-t)] Turn on invoke/execute tracing. Also enable full backtrace on errors. The _output_ parameter is optional, but if specified it controls where the trace output is sent. If _output_ is <tt>stdout</tt>, then trace output is directed to standard output. If _output_ is <tt>stderr</tt>, or if it is missing, then trace output is sent to standard error. [<tt>--verbose</tt> (-v)] Echo the Sys commands to standard output. [<tt>--version</tt> (-V)] Display the program version and exit. [<tt>--where</tt> <em>pattern</em> (-W)] Display tasks that match <em>pattern</em> and the file and line number where the task is defined. By default this option will display all tasks, not just the tasks that have descriptions. [<tt>--no-deprecation-warnings</tt> (-X)] Do not display the deprecation warnings. In addition, any command line option of the form <em>VAR</em>=<em>VALUE</em> will be added to the environment hash <tt>ENV</tt> and may be tested in the Rakefile. = Original Prototype Rake This is the original 100 line prototype rake program. --- #!/opt/alt/ruby33/bin/ruby require 'ftools' class Task TASKS = Hash.new attr_reader :prerequisites def initialize(task_name) @name = task_name @prerequisites = [] @actions = [] end def enhance(deps=nil, &block) @prerequisites |= deps if deps @actions << block if block_given? self end def name @name.to_s end def invoke @prerequisites.each { |n| Task[n].invoke } execute if needed? end def execute return if @triggered @triggered = true @actions.collect { |act| result = act.call(self) }.last end def needed? true end def timestamp Time.now end class << self def [](task_name) TASKS[intern(task_name)] or fail "Don't know how to rake #{task_name}" end def define_task(args, &block) case args when Hash fail "Too Many Target Names: #{args.keys.join(' ')}" if args.size > 1 fail "No Task Name Given" if args.size < 1 task_name = args.keys[0] deps = args[task_name] else task_name = args deps = [] end deps = deps.collect {|d| intern(d) } get(task_name).enhance(deps, &block) end def get(task_name) name = intern(task_name) TASKS[name] ||= self.new(name) end def intern(task_name) (Symbol === task_name) ? task_name : task_name.intern end end end class FileTask < Task def needed? return true unless File.exist?(name) latest_prereq = @prerequisites.collect{|n| Task[n].timestamp}.max return false if latest_prereq.nil? timestamp < latest_prereq end def timestamp File.new(name.to_s).mtime end end def task(args, &block) Task.define_task(args, &block) end def file(args, &block) FileTask.define_task(args, &block) end def sys(cmd) puts cmd system(cmd) or fail "Command Failed: [#{cmd}]" end def rake begin here = Dir.pwd while ! File.exist?("Rakefile") Dir.chdir("..") fail "No Rakefile found" if Dir.pwd == here here = Dir.pwd end puts "(in #{Dir.pwd})" load "./Rakefile" ARGV.push("default") if ARGV.size == 0 ARGV.each { |task_name| Task[task_name].invoke } rescue Exception => ex puts "rake aborted ... #{ex.message}" puts ex.backtrace.find {|str| str =~ /Rakefile/ } || "" end end if __FILE__ == $0 then rake end = Glossary action :: Code to be executed in order to perform a task. Actions in a Rakefile are specified in a code block. (Usually delimited by +do+/+end+ pairs.) execute :: When a task is executed, all of its actions are performed in the order they were defined. Note that, unlike <tt>invoke</tt>, <tt>execute</tt> always executes the actions (without invoking or executing the prerequisites). file task (Rake::FileTask) :: A file task is a task whose purpose is to create a file (which has the same name as the task). When invoked, a file task will only execute if one or more of the following conditions are true. 1. The associated file does not exist. 2. A prerequisite has a later time stamp than the existing file. Because normal Tasks always have the current time as timestamp, a FileTask that has a normal Task prerequisite will always execute. invoke :: When a task is invoked, first we check to see if it has been invoked before. If it has been, then nothing else is done. If this is the first time it has been invoked, then we invoke each of its prerequisites. Finally, we check to see if we need to execute the actions of this task by calling Rake::Task#needed?. If the task is needed, we execute its actions. NOTE: Prerequisites are still invoked even if the task is not needed. prerequisites :: Every task has a (possibly empty) set of prerequisites. A prerequisite P to Task T is itself a task that must be invoked before Task T. rule :: A rule is a recipe for synthesizing a task when no task is explicitly defined. Rules generally synthesize file tasks. task (Rake::Task) :: The basic unit of work in a Rakefile. A task has a name, a set of prerequisites, and a list of actions to be performed. = Why rake? Ok, let me state from the beginning that I never intended to write this code. I'm not convinced it is useful, and I'm not convinced anyone would even be interested in it. All I can say is that Why's onion truck must by been passing through the Ohio valley. What am I talking about? ... A Ruby version of Make. See, I can sense you cringing already, and I agree. The world certainly doesn't need yet another reworking of the "make" program. I mean, we already have "ant". Isn't that enough? It started yesterday. I was helping a coworker fix a problem in one of the Makefiles we use in our project. Not a particularly tough problem, but during the course of the conversation I began lamenting some of the shortcomings of make. In particular, in one of my makefiles I wanted to determine the name of a file dynamically and had to resort to some simple scripting (in Ruby) to make it work. "Wouldn't it be nice if you could just use Ruby inside a Makefile" I said. My coworker (a recent convert to Ruby) agreed, but wondered what it would look like. So I sketched the following on the whiteboard... "What if you could specify the make tasks in Ruby, like this ..." task "build" do java_compile(...args, etc ...) end "The task function would register "build" as a target to be made, and the block would be the action executed whenever the build system determined that it was time to do the build target." We agreed that would be cool, but writing make from scratch would be WAY too much work. And that was the end of that! ... Except I couldn't get the thought out of my head. What exactly would be needed to make the about syntax work as a make file? Hmmm, you would need to register the tasks, you need some way of specifying dependencies between tasks, and some way of kicking off the process. Hey! What if we did ... and fifteen minutes later I had a working prototype of Ruby make, complete with dependencies and actions. I showed the code to my coworker and we had a good laugh. It was just about a page worth of code that reproduced an amazing amount of the functionality of make. We were both truly stunned with the power of Ruby. But it didn't do everything make did. In particular, it didn't have timestamp based file dependencies (where a file is rebuilt if any of its prerequisite files have a later timestamp). Obviously THAT would be a pain to add and so Ruby Make would remain an interesting experiment. ... Except as I walked back to my desk, I started thinking about what file based dependencies would really need. Rats! I was hooked again, and by adding a new class and two new methods, file/timestamp dependencies were implemented. Ok, now I was really hooked. Last night (during CSI!) I massaged the code and cleaned it up a bit. The result is a bare-bones replacement for make in exactly 100 lines of code. For the curious, you can see it at ... * doc/proto_rake.rdoc Oh, about the name. When I wrote the example Ruby Make task on my whiteboard, my coworker exclaimed "Oh! I have the perfect name: Rake ... Get it? Ruby-Make. Rake!" He said he envisioned the tasks as leaves and Rake would clean them up ... or something like that. Anyways, the name stuck. Some quick examples ... A simple task to delete backup files ... task :clean do Dir['*~'].each {|fn| rm fn rescue nil} end Note that task names are symbols (they are slightly easier to type than quoted strings ... but you may use quoted string if you would rather). Rake makes the methods of the FileUtils module directly available, so we take advantage of the <tt>rm</tt> command. Also note the use of "rescue nil" to trap and ignore errors in the <tt>rm</tt> command. To run it, just type "rake clean". Rake will automatically find a Rakefile in the current directory (or above!) and will invoke the targets named on the command line. If there are no targets explicitly named, rake will invoke the task "default". Here's another task with dependencies ... task :clobber => [:clean] do rm_r "tempdir" end Task :clobber depends upon task :clean, so :clean will be run before :clobber is executed. Files are specified by using the "file" command. It is similar to the task command, except that the task name represents a file, and the task will be run only if the file doesn't exist, or if its modification time is earlier than any of its prerequisites. Here is a file based dependency that will compile "hello.cc" to "hello.o". file "hello.cc" file "hello.o" => ["hello.cc"] do |t| srcfile = t.name.sub(/\.o$/, ".cc") sh %{g++ #{srcfile} -c -o #{t.name}} end I normally specify file tasks with string (rather than symbols). Some file names can't be represented by symbols. Plus it makes the distinction between them more clear to the casual reader. Currently writing a task for each and every file in the project would be tedious at best. I envision a set of libraries to make this job easier. For instance, perhaps something like this ... require 'rake/ctools' Dir['*.c'].each do |fn| c_source_file(fn) end where "c_source_file" will create all the tasks need to compile all the C source files in a directory. Any number of useful libraries could be created for rake. That's it. There's no documentation (other than whats in this message). Does this sound interesting to anyone? If so, I'll continue to clean it up and write it up and publish it on RAA. Otherwise, I'll leave it as an interesting exercise and a tribute to the power of Ruby. Why /might/ rake be interesting to Ruby programmers. I don't know, perhaps ... * No weird make syntax (only weird Ruby syntax :-) * No need to edit or read XML (a la ant) * Platform independent build scripts. * Will run anywhere Ruby exists, so no need to have "make" installed. If you stay away from the "sys" command and use things like 'ftools', you can have a perfectly platform independent build script. Also rake is only 100 lines of code, so it can easily be packaged along with the rest of your code. So ... Sorry for the long rambling message. Like I said, I never intended to write this code at all. # Example Rakefile -*- ruby -*- task :default => [:main] file "a.o" => ["a.c"] do |t| src = t.name.sub(/\.o$/, '.c') sh "gcc #{src} -c -o #{t.name}" end file "b.o" => ["b.c"] do |t| src = t.name.sub(/\.o$/, '.c') sh "gcc #{src} -c -o #{t.name}" end file "main.o" => ["main.c"] do |t| src = t.name.sub(/\.o$/, '.c') sh "gcc #{src} -c -o #{t.name}" end OBJFILES = ["a.o", "b.o", "main.o"] task :obj => OBJFILES file "main" => OBJFILES do |t| sh "gcc -o #{t.name} main.o a.o b.o" end task :clean do rm_f FileList['*.o'] Dir['*~'].each { |fn| rm_f fn } end task :clobber => [:clean] do rm_f "main" end task :run => ["main"] do sh "./main" end #include <stdio.h> extern void a(); extern void b(); int main () { a(); b(); return 0; } #include <stdio.h> void a() { printf ("In function a\n"); } # Example Rakefile -*- ruby -*- # Using the power of Ruby task :default => [:main] def ext(fn, newext) fn.sub(/\.[^.]+$/, newext) end SRCFILES = Dir['*.c'] OBJFILES = SRCFILES.collect { |fn| ext(fn,".o") } OBJFILES.each do |objfile| srcfile = ext(objfile, ".c") file objfile => [srcfile] do |t| sh "gcc #{srcfile} -c -o #{t.name}" end end file "main" => OBJFILES do |t| sh "gcc -o #{t.name} main.o a.o b.o" end task :clean do rm_f FileList['*.o'] Dir['*~'].each { |fn| rm_f fn } end task :clobber => [:clean] do rm_f "main" end task :run => ["main"] do sh "./main" end #include <stdio.h> void b() { printf ("In function b\n"); } = Rakefile Format First of all, there is no special format for a Rakefile. A Rakefile contains executable Ruby code. Anything legal in a ruby script is allowed in a Rakefile. Now that we understand there is no special syntax in a Rakefile, there are some conventions that are used in a Rakefile that are a little unusual in a typical Ruby program. Since a Rakefile is tailored to specifying tasks and actions, the idioms used in a Rakefile are designed to support that. So, what goes into a Rakefile? == Tasks Tasks are the main unit of work in a Rakefile. Tasks have a name (usually given as a symbol or a string), a list of prerequisites (more symbols or strings) and a list of actions (given as a block). === Simple Tasks A task is declared by using the +task+ method. +task+ takes a single parameter that is the name of the task. task :name === Tasks with Prerequisites Any prerequisites are given as a list (enclosed in square brackets) following the name and an arrow (=>). task name: [:prereq1, :prereq2] *NOTE:* Although this syntax looks a little funky, it is legal Ruby. We are constructing a hash where the key is :name and the value for that key is the list of prerequisites. It is equivalent to the following ... hash = Hash.new hash[:name] = [:prereq1, :prereq2] task(hash) You can also use strings for task names and prerequisites, rake doesn't care. This is the same task definition: task 'name' => %w[prereq1 prereq2] As is this: task name: %w[prereq1 prereq2] We'll prefer this style for regular tasks with prerequisites throughout the rest of the document. Using an array of strings for the prerequisites means you will need to make fewer changes if you need to move tasks into namespaces or perform other refactorings. === Tasks with Actions Actions are defined by passing a block to the +task+ method. Any Ruby code can be placed in the block. The block may reference the task object via the block parameter. task name: [:prereq1, :prereq2] do |t| # actions (may reference t) end === Multiple Definitions A task may be specified more than once. Each specification adds its prerequisites and actions to the existing definition. This allows one part of a rakefile to specify the actions and a different rakefile (perhaps separately generated) to specify the dependencies. For example, the following is equivalent to the single task specification given above. task :name task name: :prereq1 task name: %w[prereq2] task :name do |t| # actions end == File Tasks Some tasks are designed to create a file from one or more other files. Tasks that generate these files may be skipped if the file already exists. File tasks are used to specify file creation tasks. File tasks are declared using the +file+ method (instead of the +task+ method). In addition, file tasks are usually named with a string rather than a symbol. The following file task creates a executable program (named +prog+) given two object files named +a.o+ and +b.o+. The tasks for creating +a.o+ and +b.o+ are not shown. file "prog" => ["a.o", "b.o"] do |t| sh "cc -o #{t.name} #{t.prerequisites.join(' ')}" end == Directory Tasks It is common to need to create directories upon demand. The +directory+ convenience method is a short-hand for creating a FileTask that creates the directory. For example, the following declaration ... directory "testdata/examples/doc" is equivalent to ... file "testdata" do |t| mkdir t.name end file "testdata/examples" => ["testdata"] do |t| mkdir t.name end file "testdata/examples/doc" => ["testdata/examples"] do |t| mkdir t.name end The +directory+ method does not accept prerequisites or actions, but both prerequisites and actions can be added later. For example ... directory "testdata" file "testdata" => ["otherdata"] file "testdata" do cp Dir["standard_data/*.data"], "testdata" end == Tasks with Parallel Prerequisites Rake allows parallel execution of prerequisites using the following syntax: multitask copy_files: %w[copy_src copy_doc copy_bin] do puts "All Copies Complete" end In this example, +copy_files+ is a normal rake task. Its actions are executed whenever all of its prerequisites are done. The big difference is that the prerequisites (+copy_src+, +copy_bin+ and +copy_doc+) are executed in parallel. Each of the prerequisites are run in their own Ruby thread, possibly allowing faster overall runtime. === Secondary Prerequisites If any of the primary prerequisites of a multitask have common secondary prerequisites, all of the primary/parallel prerequisites will wait until the common prerequisites have been run. For example, if the <tt>copy_<em>xxx</em></tt> tasks have the following prerequisites: task copy_src: :prep_for_copy task copy_bin: :prep_for_copy task copy_doc: :prep_for_copy Then the +prep_for_copy+ task is run before starting all the copies in parallel. Once +prep_for_copy+ is complete, +copy_src+, +copy_bin+, and +copy_doc+ are all run in parallel. Note that +prep_for_copy+ is run only once, even though it is referenced in multiple threads. === Thread Safety The Rake internal data structures are thread-safe with respect to the multitask parallel execution, so there is no need for the user to do extra synchronization for Rake's benefit. However, if there are user data structures shared between the parallel prerequisites, the user must do whatever is necessary to prevent race conditions. == Tasks with Arguments Prior to version 0.8.0, rake was only able to handle command line arguments of the form NAME=VALUE that were passed into Rake via the ENV hash. Many folks had asked for some kind of simple command line arguments, perhaps using "--" to separate regular task names from argument values on the command line. The problem is that there was no easy way to associate positional arguments on the command line with different tasks. Suppose both tasks :a and :b expect a command line argument: does the first value go with :a? What if :b is run first? Should it then get the first command line argument. Rake 0.8.0 solves this problem by explicitly passing values directly to the tasks that need them. For example, if I had a release task that required a version number, I could say: rake release[0.8.2] And the string "0.8.2" will be passed to the :release task. Multiple arguments can be passed by separating them with a comma, for example: rake name[john,doe] Just a few words of caution. The rake task name and its arguments need to be a single command line argument to rake. This generally means no spaces. If spaces are needed, then the entire name + argument string should be quoted. Something like this: rake "name[billy bob, smith]" (Quoting rules vary between operating systems and shells, so make sure you consult the proper docs for your OS/shell). === Tasks that Expect Parameters Parameters are only given to tasks that are setup to expect them. In order to handle named parameters, the task declaration syntax for tasks has been extended slightly. For example, a task that needs a first name and last name might be declared as: task :name, [:first_name, :last_name] The first argument is still the name of the task (:name in this case). The next two arguments are the names of the parameters expected by :name in an array (:first_name and :last_name in the example). To access the values of the parameters, the block defining the task behaviour can now accept a second parameter: task :name, [:first_name, :last_name] do |t, args| puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end The first argument of the block "t" is always bound to the current task object. The second argument "args" is an open-struct like object that allows access to the task arguments. Extra command line arguments to a task are ignored. If you wish to specify default values for the arguments, you can use the with_defaults method in the task body. Here is the above example where we specify default values for the first and last names: task :name, [:first_name, :last_name] do |t, args| args.with_defaults(:first_name => "John", :last_name => "Dough") puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end === Tasks that Expect Parameters and Have Prerequisites Tasks that use parameters have a slightly different format for prerequisites. Use the arrow notation to indicate the prerequisites for tasks with arguments. For example: task :name, [:first_name, :last_name] => [:pre_name] do |t, args| args.with_defaults(:first_name => "John", :last_name => "Dough") puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end === Tasks that take Variable-length Parameters Tasks that need to handle a list of values as a parameter can use the extras method of the args variable. This allows for tasks that can loop over a variable number of values, and its compatible with named parameters as well: task :email, [:message] do |t, args| mail = Mail.new(args.message) recipients = args.extras recipients.each do |target| mail.send_to(target) end end There is also the convenience method to_a that returns all parameters in the sequential order they were given, including those associated with named parameters. === Deprecated Task Parameters Format There is an older format for declaring task parameters that omitted the task argument array and used the :needs keyword to introduce the dependencies. That format is still supported for compatibility, but is not recommended for use. The older format may be dropped in future versions of rake. == Accessing Task Programmatically Sometimes it is useful to manipulate tasks programmatically in a Rakefile. To find a task object use Rake::Task.[]. === Programmatic Task Example For example, the following Rakefile defines two tasks. The :doit task simply prints a simple "DONE" message. The :dont class will lookup the doit class and remove (clear) all of its prerequisites and actions. task :doit do puts "DONE" end task :dont do Rake::Task[:doit].clear end Running this example: $ rake doit (in /Users/jim/working/git/rake/x) DONE $ rake dont doit (in /Users/jim/working/git/rake/x) $ The ability to programmatically manipulate tasks gives rake very powerful meta-programming capabilities w.r.t. task execution, but should be used with caution. == Rules When a file is named as a prerequisite, but does not have a file task defined for it, Rake will attempt to synthesize a task by looking at a list of rules supplied in the Rakefile. Suppose we were trying to invoke task "mycode.o", but no task is defined for it. But the rakefile has a rule that look like this ... rule '.o' => ['.c'] do |t| sh "cc #{t.source} -c -o #{t.name}" end This rule will synthesize any task that ends in ".o". It has a prerequisite a source file with an extension of ".c" must exist. If Rake is able to find a file named "mycode.c", it will automatically create a task that builds "mycode.o" from "mycode.c". If the file "mycode.c" does not exist, rake will attempt to recursively synthesize a rule for it. When a task is synthesized from a rule, the +source+ attribute of the task is set to the matching source file. This allows us to write rules with actions that reference the source file. === Advanced Rules Any regular expression may be used as the rule pattern. Additionally, a proc may be used to calculate the name of the source file. This allows for complex patterns and sources. The following rule is equivalent to the example above. rule( /\.o$/ => [ proc {|task_name| task_name.sub(/\.[^.]+$/, '.c') } ]) do |t| sh "cc #{t.source} -c -o #{t.name}" end *NOTE:* Because of a _quirk_ in Ruby syntax, parenthesis are required on *rule* when the first argument is a regular expression. The following rule might be used for Java files ... rule '.class' => [ proc { |tn| tn.sub(/\.class$/, '.java').sub(/^classes\//, 'src/') } ] do |t| java_compile(t.source, t.name) end *NOTE:* +java_compile+ is a hypothetical method that invokes the java compiler. == Importing Dependencies Any ruby file (including other rakefiles) can be included with a standard Ruby +require+ command. The rules and declarations in the required file are just added to the definitions already accumulated. Because the files are loaded _before_ the rake targets are evaluated, the loaded files must be "ready to go" when the rake command is invoked. This makes generated dependency files difficult to use. By the time rake gets around to updating the dependencies file, it is too late to load it. The +import+ command addresses this by specifying a file to be loaded _after_ the main rakefile is loaded, but _before_ any targets on the command line are invoked. In addition, if the file name matches an explicit task, that task is invoked before loading the file. This allows dependency files to be generated and used in a single rake command invocation. Example: require 'rake/loaders/makefile' file ".depends.mf" => [SRC_LIST] do |t| sh "makedepend -f- -- #{CFLAGS} -- #{t.prerequisites} > #{t.name}" end import ".depends.mf" If ".depends" does not exist, or is out of date w.r.t. the source files, a new ".depends" file is generated using +makedepend+ before loading. == Comments Standard Ruby comments (beginning with "#") can be used anywhere it is legal in Ruby source code, including comments for tasks and rules. However, if you wish a task to be described using the "-T" switch, then you need to use the +desc+ command to describe the task. Example: desc "Create a distribution package" task package: %w[ ... ] do ... end The "-T" switch (or "--tasks" if you like to spell things out) will display a list of tasks that have a description. If you use +desc+ to describe your major tasks, you have a semi-automatic way of generating a summary of your Rake file. $ rake -T (in /home/.../rake) rake clean # Remove any temporary products. rake clobber # Remove any generated file. rake clobber_rdoc # Remove rdoc products rake contrib_test # Run tests for contrib_test rake default # Default Task rake install # Install the application rake lines # Count lines in the main rake file rake rdoc # Build the rdoc HTML Files rake rerdoc # Force a rebuild of the RDOC files rake test # Run tests rake testall # Run all test targets Only tasks with descriptions will be displayed with the "-T" switch. Use "-P" (or "--prereqs") to get a list of all tasks and their prerequisites. == Namespaces As projects grow (and along with it, the number of tasks), it is common for task names to begin to clash. For example, if you might have a main program and a set of sample programs built by a single Rakefile. By placing the tasks related to the main program in one namespace, and the tasks for building the sample programs in a different namespace, the task names will not interfere with each other. For example: namespace "main" do task :build do # Build the main program end end namespace "samples" do task :build do # Build the sample programs end end task build: %w[main:build samples:build] Referencing a task in a separate namespace can be achieved by prefixing the task name with the namespace and a colon (e.g. "main:build" refers to the :build task in the +main+ namespace). Nested namespaces are supported. Note that the name given in the +task+ command is always the unadorned task name without any namespace prefixes. The +task+ command always defines a task in the current namespace. === FileTasks File task names are not scoped by the namespace command. Since the name of a file task is the name of an actual file in the file system, it makes little sense to include file task names in name space. Directory tasks (created by the +directory+ command) are a type of file task and are also not affected by namespaces. === Name Resolution When looking up a task name, rake will start with the current namespace and attempt to find the name there. If it fails to find a name in the current namespace, it will search the parent namespaces until a match is found (or an error occurs if there is no match). The "rake" namespace is a special implicit namespace that refers to the toplevel names. If a task name begins with a "^" character, the name resolution will start in the parent namespace. Multiple "^" characters are allowed. Here is an example file with multiple :run tasks and how various names resolve in different locations. task :run namespace "one" do task :run namespace "two" do task :run # :run => "one:two:run" # "two:run" => "one:two:run" # "one:two:run" => "one:two:run" # "one:run" => "one:run" # "^run" => "one:run" # "^^run" => "rake:run" (the top level task) # "rake:run" => "rake:run" (the top level task) end # :run => "one:run" # "two:run" => "one:two:run" # "^run" => "rake:run" end # :run => "rake:run" # "one:run" => "one:run" # "one:two:run" => "one:two:run" == FileLists FileLists are the way Rake manages lists of files. You can treat a FileList as an array of strings for the most part, but FileLists support some additional operations. === Creating a FileList Creating a file list is easy. Just give it the list of file names: fl = FileList['file1.rb', file2.rb'] Or give it a glob pattern: fl = FileList['*.rb'] == Odds and Ends === do/end versus { } Blocks may be specified with either a +do+/+end+ pair, or with curly braces in Ruby. We _strongly_ recommend using +do+/+end+ to specify the actions for tasks and rules. Because the rakefile idiom tends to leave off parentheses on the task/file/rule methods, unusual ambiguities can arise when using curly braces. For example, suppose that the method +object_files+ returns a list of object files in a project. Now we use +object_files+ as the prerequisites in a rule specified with actions in curly braces. # DON'T DO THIS! file "prog" => object_files { # Actions are expected here (but it doesn't work)! } Because curly braces have a higher precedence than +do+/+end+, the block is associated with the +object_files+ method rather than the +file+ method. This is the proper way to specify the task ... # THIS IS FINE file "prog" => object_files do # Actions go here end == Rakefile Path When issuing the +rake+ command in a terminal, Rake will look for a Rakefile in the current directory. If a Rakefile is not found, it will search parent directories until one is found. For example, if a Rakefile resides in the +project/+ directory, moving deeper into the project's directory tree will not have an adverse effect on rake tasks: $ pwd /home/user/project $ cd lib/foo/bar $ pwd /home/user/project/lib/foo/bar $ rake run_pwd /home/user/project As far as rake is concerned, all tasks are run from the directory in which the Rakefile resides. === Multiple Rake Files Not all tasks need to be included in a single Rakefile. Additional rake files (with the file extension "+.rake+") may be placed in +rakelib+ directory located at the top level of a project (i.e. the same directory that contains the main +Rakefile+). Also, rails projects may include additional rake files in the +lib/tasks+ directory. === Clean and Clobber Tasks Through <tt>require 'rake/clean'</tt> Rake provides +clean+ and +clobber+ tasks: +clean+ :: Clean up the project by deleting scratch files and backup files. Add files to the +CLEAN+ FileList to have the +clean+ target handle them. +clobber+ :: Clobber all generated and non-source files in a project. The task depends on +clean+, so all the +CLEAN+ files will be deleted as well as files in the +CLOBBER+ FileList. The intent of this task is to return a project to its pristine, just unpacked state. You can add file names or glob patterns to both the +CLEAN+ and +CLOBBER+ lists. === Phony Task The phony task can be used as a dependency to allow file-based tasks to use non-file-based-tasks as prerequisites without forcing them to rebuild. You can <tt>require 'rake/phony'</tt> to add the +phony+ task. ---- == See * README.rdoc -- Main documentation for Rake. # frozen_string_literal: true module RDoc module Page FONTS = "\"Bitstream Vera Sans\", Verdana, Arial, Helvetica, sans-serif" STYLE = <<CSS a { color: #00F; text-decoration: none; } a:hover { color: #77F; text-decoration: underline; } body, td, p { font-family: %fonts%; background: #FFF; color: #000; margin: 0px; font-size: small; } #content { margin: 2em; } #description p { margin-bottom: 0.5em; } .sectiontitle { margin-top: 1em; margin-bottom: 1em; padding: 0.5em; padding-left: 2em; background: #005; color: #FFF; font-weight: bold; border: 1px dotted black; } .attr-rw { padding-left: 1em; padding-right: 1em; text-align: center; color: #055; } .attr-name { font-weight: bold; } .attr-desc { } .attr-value { font-family: monospace; } .file-title-prefix { font-size: large; } .file-title { font-size: large; font-weight: bold; background: #005; color: #FFF; } .banner { background: #005; color: #FFF; border: 1px solid black; padding: 1em; } .banner td { background: transparent; color: #FFF; } h1 a, h2 a, .sectiontitle a, .banner a { color: #FF0; } h1 a:hover, h2 a:hover, .sectiontitle a:hover, .banner a:hover { color: #FF7; } .dyn-source { display: none; background: #FFE; color: #000; border: 1px dotted black; margin: 0.5em 2em 0.5em 2em; padding: 0.5em; } .dyn-source .cmt { color: #00F; font-style: italic; } .dyn-source .kw { color: #070; font-weight: bold; } .method { margin-left: 1em; margin-right: 1em; margin-bottom: 1em; } .description pre { padding: 0.5em; border: 1px dotted black; background: #FFE; } .method .title { font-family: monospace; font-size: large; border-bottom: 1px dashed black; margin-bottom: 0.3em; padding-bottom: 0.1em; } .method .description, .method .sourcecode { margin-left: 1em; } .description p, .sourcecode p { margin-bottom: 0.5em; } .method .sourcecode p.source-link { text-indent: 0em; margin-top: 0.5em; } .method .aka { margin-top: 0.3em; margin-left: 1em; font-style: italic; text-indent: 2em; } h1 { padding: 1em; border: 1px solid black; font-size: x-large; font-weight: bold; color: #FFF; background: #007; } h2 { padding: 0.5em 1em 0.5em 1em; border: 1px solid black; font-size: large; font-weight: bold; color: #FFF; background: #009; } h3, h4, h5, h6 { padding: 0.2em 1em 0.2em 1em; border: 1px dashed black; color: #000; background: #AAF; } .sourcecode > pre { padding: 0.5em; border: 1px dotted black; background: #FFE; } CSS XHTML_PREAMBLE = %{<?xml version="1.0" encoding="%charset%"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> } HEADER = XHTML_PREAMBLE + <<ENDHEADER <html> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" /> <script language="JavaScript" type="text/javascript"> // <![CDATA[ function toggleSource( id ) { var elem var link if( document.getElementById ) { elem = document.getElementById( id ) link = document.getElementById( "l_" + id ) } else if ( document.all ) { elem = eval( "document.all." + id ) link = eval( "document.all.l_" + id ) } else return false; if( elem.style.display == "block" ) { elem.style.display = "none" link.innerHTML = "show source" } else { elem.style.display = "block" link.innerHTML = "hide source" } } function openCode( url ) { window.open( url, "SOURCE_CODE", "width=400,height=400,scrollbars=yes" ) } // ]]> </script> </head> <body> ENDHEADER FILE_PAGE = <<HTML <table border='0' cellpadding='0' cellspacing='0' width="100%" class='banner'> <tr><td> <table width="100%" border='0' cellpadding='0' cellspacing='0'><tr> <td class="file-title" colspan="2"><span class="file-title-prefix">File</span><br />%short_name%</td> <td align="right"> <table border='0' cellspacing="0" cellpadding="2"> <tr> <td>Path:</td> <td>%full_path% IF:cvsurl (<a href="%cvsurl%">CVS</a>) ENDIF:cvsurl </td> </tr> <tr> <td>Modified:</td> <td>%dtm_modified%</td> </tr> </table> </td></tr> </table> </td></tr> </table><br> HTML ################################################################### CLASS_PAGE = <<HTML <table width="100%" border='0' cellpadding='0' cellspacing='0' class='banner'><tr> <td class="file-title"><span class="file-title-prefix">%classmod%</span><br />%full_name%</td> <td align="right"> <table cellspacing=0 cellpadding=2> <tr valign="top"> <td>In:</td> <td> START:infiles HREF:full_path_url:full_path: IF:cvsurl (<a href="%cvsurl%">CVS</a>) ENDIF:cvsurl END:infiles </td> </tr> IF:parent <tr> <td>Parent:</td> <td> IF:par_url <a href="%par_url%"> ENDIF:par_url %parent% IF:par_url </a> ENDIF:par_url </td> </tr> ENDIF:parent </table> </td> </tr> </table> HTML ################################################################### METHOD_LIST = <<HTML <div id="content"> IF:diagram <table cellpadding='0' cellspacing='0' border='0' width="100%"><tr><td align="center"> %diagram% </td></tr></table> ENDIF:diagram IF:description <div class="description">%description%</div> ENDIF:description IF:requires <div class="sectiontitle">Required Files</div> <ul> START:requires <li>HREF:aref:name:</li> END:requires </ul> ENDIF:requires IF:toc <div class="sectiontitle">Contents</div> <ul> START:toc <li><a href="#%href%">%secname%</a></li> END:toc </ul> ENDIF:toc IF:methods <div class="sectiontitle">Methods</div> <ul> START:methods <li>HREF:aref:name:</li> END:methods </ul> ENDIF:methods IF:includes <div class="sectiontitle">Included Modules</div> <ul> START:includes <li>HREF:aref:name:</li> END:includes </ul> ENDIF:includes START:sections IF:sectitle <div class="sectiontitle"><a nem="%secsequence%">%sectitle%</a></div> IF:seccomment <div class="description"> %seccomment% </div> ENDIF:seccomment ENDIF:sectitle IF:classlist <div class="sectiontitle">Classes and Modules</div> %classlist% ENDIF:classlist IF:constants <div class="sectiontitle">Constants</div> <table border='0' cellpadding='5'> START:constants <tr valign='top'> <td class="attr-name">%name%</td> <td>=</td> <td class="attr-value">%value%</td> </tr> IF:desc <tr valign='top'> <td> </td> <td colspan="2" class="attr-desc">%desc%</td> </tr> ENDIF:desc END:constants </table> ENDIF:constants IF:attributes <div class="sectiontitle">Attributes</div> <table border='0' cellpadding='5'> START:attributes <tr valign='top'> <td class='attr-rw'> IF:rw [%rw%] ENDIF:rw </td> <td class='attr-name'>%name%</td> <td class='attr-desc'>%a_desc%</td> </tr> END:attributes </table> ENDIF:attributes IF:method_list START:method_list IF:methods <div class="sectiontitle">%type% %category% methods</div> START:methods <div class="method"> <div class="title"> IF:callseq <a name="%aref%"></a><b>%callseq%</b> ENDIF:callseq IFNOT:callseq <a name="%aref%"></a><b>%name%</b>%params% ENDIF:callseq IF:codeurl [ <a href="javascript:openCode('%codeurl%')">source</a> ] ENDIF:codeurl </div> IF:m_desc <div class="description"> %m_desc% </div> ENDIF:m_desc IF:aka <div class="aka"> This method is also aliased as START:aka <a href="%aref%">%name%</a> END:aka </div> ENDIF:aka IF:sourcecode <div class="sourcecode"> <p class="source-link">[ <a href="javascript:toggleSource('%aref%_source')" id="l_%aref%_source">show source</a> ]</p> <div id="%aref%_source" class="dyn-source"> <pre> %sourcecode% </pre> </div> </div> ENDIF:sourcecode </div> END:methods ENDIF:methods END:method_list ENDIF:method_list END:sections </div> HTML FOOTER = <<ENDFOOTER </body> </html> ENDFOOTER BODY = HEADER + <<ENDBODY !INCLUDE! <!-- banner header --> <div id="bodyContent"> #{METHOD_LIST} </div> #{FOOTER} ENDBODY ########################## Source code ########################## SRC_PAGE = XHTML_PREAMBLE + <<HTML <html> <head><title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style> .ruby-comment { color: green; font-style: italic } .ruby-constant { color: #4433aa; font-weight: bold; } .ruby-identifier { color: #222222; } .ruby-ivar { color: #2233dd; } .ruby-keyword { color: #3333FF; font-weight: bold } .ruby-node { color: #777777; } .ruby-operator { color: #111111; } .ruby-regexp { color: #662222; } .ruby-value { color: #662222; font-style: italic } .kw { color: #3333FF; font-weight: bold } .cmt { color: green; font-style: italic } .str { color: #662222; font-style: italic } .re { color: #662222; } </style> </head> <body bgcolor="white"> <pre>%code%</pre> </body> </html> HTML ########################## Index ################################ FR_INDEX_BODY = <<HTML !INCLUDE! HTML FILE_INDEX = XHTML_PREAMBLE + <<HTML <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style> <!-- body { background-color: #EEE; font-family: #{FONTS}; color: #000; margin: 0px; } .banner { background: #005; color: #FFF; padding: 0.2em; font-size: small; font-weight: bold; text-align: center; } .entries { margin: 0.25em 1em 0 1em; font-size: x-small; } a { color: #00F; text-decoration: none; white-space: nowrap; } a:hover { color: #77F; text-decoration: underline; } --> </style> <base target="docwin"> </head> <body> <div class="banner">%list_title%</div> <div class="entries"> START:entries <a href="%href%">%name%</a><br> END:entries </div> </body></html> HTML CLASS_INDEX = FILE_INDEX METHOD_INDEX = FILE_INDEX INDEX = XHTML_PREAMBLE + <<HTML <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> </head> <frameset cols="20%,*"> <frameset rows="15%,35%,50%"> <frame src="fr_file_index.html" title="Files" name="Files" /> <frame src="fr_class_index.html" name="Classes" /> <frame src="fr_method_index.html" name="Methods" /> </frameset> IF:inline_source <frame src="%initial_page%" name="docwin"> ENDIF:inline_source IFNOT:inline_source <frameset rows="80%,20%"> <frame src="%initial_page%" name="docwin"> <frame src="blank.html" name="source"> </frameset> ENDIF:inline_source <noframes> <body bgcolor="white"> Click <a href="html/index.html">here</a> for a non-frames version of this page. </body> </noframes> </frameset> </html> HTML end end #!/opt/alt/ruby33/bin/ruby #-- # Copyright (c) 2003, 2004, 2005, 2006, 2007 Jim Weirich # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. #++ require "rake" Rake.application.run Copyright (c) Jim Weirich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. === 13.0.6 * Additional fix for #389 Pull request #390 by hsbt === 13.0.5 * Fixed the regression of #388 Pull request #389 by hsbt === 13.0.4 * Fix rake test loader swallowing useful error information. Pull request #367 by deivid-rodriguez * Add -C/--directory option the same as GNU make. Pull request #376 by nobu === 13.0.3 * Fix breaking change of execution order on TestTask. Pull request #368 by ysakasin === 13.0.2 ==== Enhancements * Fix tests to work with current FileUtils Pull Request #358 by jeremyevans * Simplify default rake test loader Pull Request #357 by deivid-rodriguez * Update rdoc Pull Request #366 by bahasalien * Update broken links to rake articles from Avdi in README Pull Request #360 by svl7 === 13.0.1 ==== Bug fixes * Fixed bug: Reenabled task raises previous exception on second invokation Pull Request #271 by thorsteneckel * Fix an incorrectly resolved arg pattern Pull Request #327 by mjbellantoni === 13.0.0 ==== Enhancements * Follows recent changes on keyword arguments in ruby 2.7. Pull Request #326 by nobu * Make `PackageTask` be able to omit parent directory while packing files Pull Request #310 by tonytonyjan * Add order only dependency Pull Request #269 by take-cheeze ==== Compatibility changes * Drop old ruby versions(< 2.2) === 12.3.3 ==== Bug fixes * Use the application's name in error message if a task is not found. Pull Request #303 by tmatilai ==== Enhancements: * Use File.open explicitly. === 12.3.2 ==== Bug fixes * Fixed test fails caused by 2.6 warnings. Pull Request #297 by hsbt ==== Enhancements: * Rdoc improvements. Pull Request #293 by colby-swandale * Improve multitask performance. Pull Request #273 by jsm * Add alias `prereqs`. Pull Request #268 by take-cheeze === 12.3.1 ==== Bug fixes * Support did_you_mean >= v1.2.0 which has a breaking change on formatters. Pull request #262 by FUJI Goro. ==== Enhancements: * Don't run task if it depends on already invoked but failed task. Pull request #252 by Gonzalo Rodriguez. * Make space trimming consistent for all task arguments. Pull request #259 by Gonzalo Rodriguez. * Removes duplicated inclusion of Rake::DSL in tests. Pull request #254 by Gonzalo Rodriguez. * Re-raise a LoadError that didn't come from require in the test loader. Pull request #250 by Dylan Thacker-Smith. === 12.3.0 ==== Compatibility Changes * Bump `required_ruby_version` to Ruby 2.0.0. Rake has already removed support for Ruby 1.9.x. ==== Enhancements: * Support `test-bundled-gems` task on ruby core. === 12.2.1 ==== Bug fixes * Fixed to break Capistrano::Application on capistrano3. === 12.2.0 ==== Enhancements: * Make rake easier to use as a library Pull request #211 by @drbrain * Fix quadratic performance in FileTask#out_of_date? Pull request #224 by @doudou * Clarify output when printing nested exception traces Pull request #232 by @urbanautomaton ==== Bug fixes * Account for a file that match 2 or more patterns. Pull request #231 by @styd === 12.1.0 ==== Enhancements: * Added did_you_mean feature for invalid rake task. Pull request #221 by @xtina-starr * Enabled to dependency chained by extensions. Pull request #39 by Petr Skocik. * Make all of string literals to frozen objects on Ruby 2.4 or later. ==== Bug fixes * Typo fixes in rakefile.rdoc. Pull request #180 by Yuta Kurotaki. * Fix unexpected behavior of file task with dryrun option. Pull request #183 by @aycabta. * Make LoadError from running tests more obvious. Pull request #195 by Eric Hodel. * Fix unexpected TypeError with hash style option. Pull request #202 by Kuniaki IGARASHI. === 12.0.0 ==== Compatibility Changes * Removed arguments on clear #157 by Jesse Bowes * Removed `rake/contrib` packages. These are extracted to `rake-contrib` gem. * Removed deprecated method named `last\_comment`. ==== Enhancements: * Re-use trace option on `cleanup` task. #164 by Brian Henderson * Actions adore keyword arguments #174 by Josh Cheek * Rake::TaskArguments#key? alias of #has_key? #175 by Paul Annesley === 11.3.0 / 2016-09-20 ==== Enhancements: * Remove to reference `Fixnum` constant. Pull request #160 by nobu === 11.2.2 / 2016-06-12 ==== Bug fixes * Fix unexpected behavior with multiple dependencies on Rake::TestTask === 11.2.1 / 2016-06-12 ==== Bug fixes * Fix regression of dependencies handling on Rake::TestTask. Report #139 === 11.2.0 / 2016-06-11 ==== Bug fixes * Fix unexpected cut-out behavior on task description using triple dots and exclamation. Report #106 from Stephan Kämper and Pull request #134 by Lee * Fix empty argument assignment with `with_defaults` option. Pull request #135 by bakunyo * Ignore to use `hwprefs` on Darwin platform. Use sysctl now. Report #128 ==== Enhancements * Spawn options for sh Pull equest #138 by Eric Hodel. * Allow to specify dependencies(prerequisites) for Rake::TestTask Pull request #117 by Tim Maslyuchenko * Use Bundler task instead of hoe for gem release. * Remove explicitly load to rubygems for Ruby 1.8. * Unify to declare `Rake::VERSION`. * Support xz format for PackageTask. === 11.1.2 / 2016-03-28 ==== Bug fixes * Remove `-W` option when Rake::TestTask#verbose enabled. It's misunderstanding specification change with Rake 11. Partly revert #67 === 11.1.1 / 2016-03-14 ==== Bug fixes * Use `-W` instead of `--verbose` when Rake::TestTask#verbose enabled. JRuby doesn't have `--verbose` option. === 11.1.0 / 2016-03-11 ==== Compatibility Changes * Revert to remove `last\_comment`. It will remove Rake 12. === 11.0.1 / 2016-03-09 ==== Bug fixes * Fixed packaging manifest. === 11.0.0 / 2016-03-09 ==== Bug fixes * Correctly handle bad encoding in exception messages. Pull request #113 by Tomer Brisker * Fix verbose option at TestTask. Pull request #67 by Mike Blumtritt ==== Enhancements * Make FileList#exclude more analogous to FileList#include. * Use IO.open instead of Open3.popen3 for CPU counter. * Make Rake::Task#already_invoked publicly accessible. Pull request #93 by Joe Rafaniello * Lookup prerequisites with same name outside of scope instead of matching self. Pull request #96 by Sandy Vanderbleek * Make FileList#pathmap behave like String#pathmap. Pull request #61 by Daniel Tamai * Add fetch method to task arguments. Pull request #12 by Chris Keathley * Use ruby warnings by default. Pull request #97 by Harold Giménez ==== Compatibility Changes * Removed to support Ruby 1.8.x * Removed constant named `RAKEVERSION` * Removed Rake::AltSystem * Removed Rake::RubyForgePublisher * Removed Rake::TaskManager#last\_comment. Use last\_description. * Removed Rake::TaskLib#paste * Removed Top-level SshDirPublisher, SshFreshDirPublisher, SshFilePublisher and CompositePublisher from lib/rake/contrib/publisher.rb * Removed "rake/runtest.rb" === 10.5.0 / 2016-01-13 ==== Enhancements * Removed monkey patching for Ruby 1.8. Pull request #46 by Pablo Herrero. * Inheritance class of Rake::FileList returns always self class. Pull request #74 by Thomas Scholz === 10.4.2 / 2014-12-02 ==== Bug fixes * Rake no longer edits ARGV. This allows you to re-exec rake from a rake task. Pull requset #9 by Matt Palmer. * Documented how Rake::DSL#desc handles sentences in task descriptions. Issue #7 by Raza Sayed. * Fixed test error on 1.9.3 with legacy RubyGems. Issue #8 by Matt Palmer. * Deleted duplicated History entry. Pull request #10 by Yuji Yamamoto. === 10.4.1 / 2014-12-01 ==== Bug fixes * Reverted fix for #277 as it caused numerous issues for rake users. rails/spring issue #366 by Gustavo Dutra. === 10.4.0 / 2014-11-22 ==== Enhancements * Upgraded to minitest 5. Pull request #292 by Teo Ljungberg. * Added support for Pathname in rake tasks. Pull request #271 by Randy Coulman. * Rake now ignores falsy dependencies which allows for easier programmatic creation of tasks. Pull request #273 by Manav. * Rake no longer edits ARGV. This allows you to re-exec rake from a rake task. Issue #277 by Matt Palmer. * Etc.nprocessors is used for counting the number of CPUs. ==== Bug fixes * Updated rake manpage. Issue #283 by Nathan Long, pull request #291 by skittleys. * Add Rake::LATE to allow rebuilding of files that depend on deleted files. Bug #286, pull request #287 by David Grayson. * Fix relinking of files when repackaging. Bug #276 by Muenze. * Fixed some typos. Pull request #280 by Jed Northridge. * Try counting CPUs via cpuinfo if host_os was not matched. Pull request #282 by Edouard B. === 10.3.2 / 2014-05-15 ==== Bug fixes * Rake no longer infinitely loops when showing exception causes that refer to each other. Bug #272 by Chris Bandy. * Fixed documentation typos. Bug #275 by Jake Worth. === 10.3.1 / 2014-04-17 ==== Bug fixes * Really stop reporting an error when cleaning already-deleted files. Pull request #269 by Randy Coulman * Fixed infinite loop when cleaning already-deleted files on windows. === 10.3 / 2014-04-15 ==== Enhancements * Added --build-all option to rake which treats all file prerequisites as out-of-date. Pull request #254 by Andrew Gilbert. * Added Rake::NameSpace#scope. Issue #263 by Jon San Miguel. ==== Bug fixes * Suppress org.jruby package files in rake error messages for JRuby users. Issue #213 by Charles Nutter. * Fixed typo, removed extra "h". Pull request #267 by Hsing-Hui Hsu. * Rake no longer reports an error when cleaning already-deleted files. Pull request #266 by Randy Coulman. * Consume stderr while determining CPU count to avoid hang. Issue #268 by Albert Sun. === 10.2.2 / 2014-03-27 ==== Bug fixes * Restored Ruby 1.8.7 compatibility === 10.2.1 / 2014-03-25 ==== Bug fixes * File tasks including a ':' are now top-level tasks again. Issue #262 by Josh Holtrop. * Use sysctl for CPU count for all BSDs. Pull request #261 by Joshua Stein. * Fixed CPU detection for unknown platforms. === 10.2.0 / 2014-03-24 ==== Enhancements * Rake now requires Ruby 1.9 or newer. For me, this is a breaking change, but it seems that Jim planned to release it with Rake 10.2. See also pull request #247 by Philip Arndt. * Rake now allows you to declare tasks under a namespace like: task 'a:b' do ... end Pull request #232 by Judson Lester. * Task#source defaults to the first prerequisite in non-rule tasks. Pull request #215 by Avdi Grimm. * Rake now automatically rebuilds and reloads imported files. Pull request #209 by Randy Coulman. * The rake task arguments can contain escaped commas. Pull request #214 by Filip Hrbek. * Rake now prints the exception class on errors. Patch #251 by David Cornu. ==== Bug fixes * Fixed typos. Pull request #256 by Valera Rozuvan, #250 via Jake Worth, #260 by Zachary Scott. * Fixed documentation for calling tasks with arguments. Pull request #235 by John Varghese. * Clarified `rake -f` usage message. Pull request #252 by Marco Pfatschbacher. * Fixed a test failure on windows. Pull request #231 by Hiroshi Shirosaki. * Fixed corrupted rake.1.gz. Pull request #225 by Michel Boaventura. * Fixed bug in can\_detect\_signals? in test. Patch from #243 by Alexey Borzenkov. === 10.1.1 * Use http://github.com/jimweirich/rake instead of http://rake.rubyforge.org for canonical project url. === 10.1.0 ==== Changes ===== New Features * Add support for variable length task argument lists. If more actual arguments are supplied than named arguments, then the extra arguments values will be in args.extras. * Application name is not displayed in the help banner. (Previously "rake" was hardcoded, now rake-based applications can display their own names). ===== Bug Fixes Bug fixes include: * Fix backtrace suppression issues. * Rules now explicit get task arguments passed to them. * Rename FileList#exclude? to FileList#exclude\_from\_list? to avoid conflict with new Rails method. * Clean / Clobber tasks now report failure to remove files. * Plus heaps of internal code cleanup. ==== Thanks As usual, it was input from users that drove a lot of these changes. The following people contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Michael Nikitochkin (general code cleanup) * Vipul A M (general code cleanup) * Dennis Bell (variable length task argument lists) * Jacob Swanner (rules arguments) * Rafael Rosa Fu (documentation typo) * Stuart Nelson (install.rb fixes) * Lee Hambley (application name in help banner) -- Jim Weirich === 10.0.3 "Jim, when will Rake reach version 1.0?" Over the past several years I've been asked that question at conferences, panels and over twitter. Due to historical reasons (or maybe just plain laziness) Rake has (incorrectly) been treating the second digit of the version as the major release number. So in my head Rake was already at version 9. Well, it's time to fix things. This next version of Rake drops old, crufty, backwards compatibility hacks such as top level constants, DSL methods defined in Object and numerous other features that are just no longer desired. It's also time to drop the leading zero from the version number as well and call this new version of rake what it really is: Version 10. So, welcome to Rake 10.0! Rake 10 is actually feature identical to the latest version of Rake 9 (that would be the version spelled 0.9.3), *except* that Rake 10 drops all the sundry deprecated features that have accumulated over the years. If your Rakefile is up to date and current with all the new features of Rake 10, you are ready to go. If your Rakefile still uses a few deprecated feeatures, feel free to use Rake 9 (0.9.3) with the same feature set. Just be aware that future features will be in Rake 10 family line. ==== Changes As mentioned above, there are no new features in Rake 10. However, there are a number of features missing: * Classic namespaces are now gone. Rake is no longer able to reflect the options settings in the global variables ($rakefile, $show\_tasks, $show\_prereqs, $trace, $dryrun and $silent). The <tt>--classic-namespace</tt> option is no longer supported. * Global constants are no longer supported. This includes <tt>Task</tt>, <tt>FileTask</tt>, <tt>FileCreationTask</tt> and <tt>RakeApp</tt>). The constant missing hook to warn about using global rake constants has been removed. * The Rake DSL methods (task, file, directory, etc) are in their own module (Rake::DSL). The stub versions of these methods (that printed warnings) in Object have been removed. However, the DSL methods are added to the top-level <tt>main</tt> object. Since <tt>main</tt> is not in the inheritance tree, the presence of the DSL methods in main should be low impact on other libraries. If you want to use the Rake DSL commands from your own code, just include <tt>Rake::DSL</tt> into your own classes and modules. * The deprecated syntax for task arguments (the one using <tt>:needs</tt>) has been removed. * The <tt>--reduce-compat</tt> flag has been removed (it's not needed anymore). * The deprecated <tt>rake/sys.rb</tt> library has been removed. * The deprecated <tt>rake/rdoctask.rb</tt> library has been removed. RDoc supplies its own rake task now. * The deprecated <tt>rake/gempackagetask.rb</tt> library has been removed. Gem supplies its own package task now. There is one small behavioral change: * Non-file tasks now always report the current time as their time stamp. This is different from the previous behavior where non-file tasks reported current time only if there were no prerequisites, and the max prerequisite timestamp otherwise. This lead to inconsistent and surprising behavior when adding prerequisites to tasks that in turn were prequisites to file tasks. The new behavior is more consistent and predictable. ==== Changes (from 0.9.3, 0.9.4, 0.9.5) Since Rake 10 includes the changes from the last version of Rake 9, we'll repeat the changes for versions 0.9.3 through 0.9.5 here. ===== New Features (in 0.9.3) * Multitask tasks now use a thread pool. Use -j to limit the number of available threads. * Use -m to turn regular tasks into multitasks (use at your own risk). * You can now do "Rake.add_rakelib 'dir'" in your Rakefile to programatically add rake task libraries. * You can specific backtrace suppression patterns (see --suppress-backtrace) * Directory tasks can now take prerequisites and actions * Use --backtrace to request a full backtrace without the task trace. * You can say "--backtrace=stdout" and "--trace=stdout" to route trace output to standard output rather than standard error. * Optional 'phony' target (enable with 'require 'rake/phony'") for special purpose builds. * Task#clear now clears task comments as well as actions and prerequisites. Task#clear_comment will specifically target comments. * The --all option will force -T and -D to consider all the tasks, with and without descriptions. ===== Bug Fixes (in 0.9.3) * Semi-colons in windows rakefile paths now work. * Improved Control-C support when invoking multiple test suites. * egrep method now reads files in text mode (better support for Windows) * Better deprecation line number reporting. * The -W option now works with all tasks, whether they have a description or not. * File globs in rake should not be sorted alphabetically, independent of file system and platform. * Numerous internal improvements. * Documentation typos and fixes. ===== Bug Fixes (in 0.9.4) * Exit status with failing tests is not correctly set to non-zero. * Simplified syntax for phony task (for older versions of RDoc). * Stand alone FileList usage gets glob function (without loading in extra dependencies) ===== Bug Fixes (in 0.9.5) * --trace and --backtrace no longer swallow following task names. ==== Thanks As usual, it was input from users that drove a lot of these changes. The following people contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === 10.0.2 ==== Changes ===== Bug Fixes * --trace and --backtrace no longer swallow following task names. ==== Thanks As usual, it was input from users that drove a lot of these changes. The following people contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === 10.0.1 ==== Changes ===== Bug Fixes * Exit status with failing tests is not correctly set to non-zero. * Simplified syntax for phony task (for older versions of RDoc). * Stand alone FileList usage gets glob function (without loading in extra dependencies) ==== Thanks As usual, it was input from users that drove a lot of these changes. The following people contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === 10.0.0 "Jim, when will Rake reach version 1.0?" Over the past several years I've been asked that question at conferences, panels and over twitter. Due to historical reasons (or maybe just plain laziness) Rake has (incorrectly) been treating the second digit of the version as the major release number. So in my head Rake was already at version 9. Well, it's time to fix things. This next version of Rake drops old, crufty, backwards compatibility hacks such as top level constants, DSL methods defined in Object and numerous other features that are just no longer desired. It's also time to drop the leading zero from the version number as well and call this new version of rake what it really is: Version 10. So, welcome to Rake 10.0! Rake 10 is actually feature identical to the latest version of Rake 9 (that would be the version spelled 0.9.3), *except* that Rake 10 drops all the sundry deprecated features that have accumulated over the years. If your Rakefile is up to date and current with all the new features of Rake 10, you are ready to go. If your Rakefile still uses a few deprecated feeatures, feel free to use Rake 9 (0.9.3) with the same feature set. Just be aware that future features will be in Rake 10 family line. ==== Changes in 10.0 As mentioned above, there are no new features in Rake 10. However, there are a number of features missing: * Classic namespaces are now gone. Rake is no longer able to reflect the options settings in the global variables ($rakefile, $show\_tasks, $show\_prereqs, $trace, $dryrun and $silent). The <tt>--classic-namespace</tt> option is no longer supported. * Global constants are no longer supported. This includes <tt>Task</tt>, <tt>FileTask</tt>, <tt>FileCreationTask</tt> and <tt>RakeApp</tt>). The constant missing hook to warn about using global rake constants has been removed. * The Rake DSL methods (task, file, directory, etc) are in their own module (Rake::DSL). The stub versions of these methods (that printed warnings) in Object have been removed. However, the DSL methods are added to the top-level <tt>main</tt> object. Since <tt>main</tt> is not in the inheritance tree, the presence of the DSL methods in main should be low impact on other libraries. If you want to use the Rake DSL commands from your own code, just include <tt>Rake::DSL</tt> into your own classes and modules. * The deprecated syntax for task arguments (the one using <tt>:needs</tt>) has been removed. * The <tt>--reduce-compat</tt> flag has been removed (it's not needed anymore). * The deprecated <tt>rake/sys.rb</tt> library has been removed. * The deprecated <tt>rake/rdoctask.rb</tt> library has been removed. RDoc supplies its own rake task now. * The deprecated <tt>rake/gempackagetask.rb</tt> library has been removed. Gem supplies its own package task now. There is one small behavioral change: * Non-file tasks now always report the current time as their time stamp. This is different from the previous behavior where non-file tasks reported current time only if there were no prerequisites, and the max prerequisite timestamp otherwise. This lead to inconsistent and surprising behavior when adding prerequisites to tasks that in turn were prequisites to file tasks. The new behavior is more consistent and predictable. ==== Changes (from 0.9.3) Since Rake 10 includes the changes from the last version of Rake 9, we'll repeat the changes for version 0.9.3 here. ===== New Features * Multitask tasks now use a thread pool. Use -j to limit the number of available threads. * Use -m to turn regular tasks into multitasks (use at your own risk). * You can now do "Rake.add_rakelib 'dir'" in your Rakefile to programatically add rake task libraries. * You can specific backtrace suppression patterns (see --suppress-backtrace) * Directory tasks can now take prerequisites and actions * Use --backtrace to request a full backtrace without the task trace. * You can say "--backtrace=stdout" and "--trace=stdout" to route trace output to standard output rather than standard error. * Optional 'phony' target (enable with 'require 'rake/phony'") for special purpose builds. * Task#clear now clears task comments as well as actions and prerequisites. Task#clear_comment will specifically target comments. * The --all option will force -T and -D to consider all the tasks, with and without descriptions. ===== Bug Fixes * Semi-colons in windows rakefile paths now work. * Improved Control-C support when invoking multiple test suites. * egrep method now reads files in text mode (better support for Windows) * Better deprecation line number reporting. * The -W option now works with all tasks, whether they have a description or not. * File globs in rake should not be sorted alphabetically, independent of file system and platform. * Numerous internal improvements. * Documentation typos and fixes. ==== Thanks As usual, it was input from users that drove a lot of these changes. The following people contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === 0.9.6 Rake version 0.9.6 contains a number of fixes mainly for merging Rake into the Ruby source tree and fixing tests. ==== Changes ===== Bug Fixes (0.9.6) * Better trace output when using a multi-threaded Rakefile. * Arg parsing is now consistent for tasks and multitasks. * Skip exit code test in versions of Ruby that don't support it well. Changes for better integration with the Ruby source tree: * Fix version literal for Ruby source tree build. * Better loading of libraries for testing in Ruby build. * Use the ruby version provided by Ruby's tests. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === 0.9.5 Rake version 0.9.5 contains a number of bug fixes. ==== Changes ===== Bug Fixes (0.9.5) * --trace and --backtrace no longer swallow following task names. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === 0.9.4 Rake version 0.9.4 contains a number of bug fixes. ==== Changes ===== Bug Fixes (0.9.4) * Exit status with failing tests is not correctly set to non-zero. * Simplified syntax for phony task (for older versions of RDoc). * Stand alone FileList usage gets glob function (without loading in extra dependencies) ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === 0.9.3 Rake version 0.9.3 contains some new, backwards compatible features and a number of bug fixes. ==== Changes ===== New Features * Multitask tasks now use a thread pool. Use -j to limit the number of available threads. * Use -m to turn regular tasks into multitasks (use at your own risk). * You can now do "Rake.add_rakelib 'dir'" in your Rakefile to programatically add rake task libraries. * You can specific backtrace suppression patterns (see --suppress-backtrace) * Directory tasks can now take prerequisites and actions * Use --backtrace to request a full backtrace without the task trace. * You can say "--backtrace=stdout" and "--trace=stdout" to route trace output to standard output rather than standard error. * Optional 'phony' target (enable with 'require 'rake/phony'") for special purpose builds. * Task#clear now clears task comments as well as actions and prerequisites. Task#clear_comment will specifically target comments. * The --all option will force -T and -D to consider all the tasks, with and without descriptions. ===== Bug Fixes * Semi-colons in windows rakefile paths now work. * Improved Control-C support when invoking multiple test suites. * egrep method now reads files in text mode (better support for Windows) * Better deprecation line number reporting. * The -W option now works with all tasks, whether they have a description or not. * File globs in rake should not be sorted alphabetically, independent of file system and platform. * Numerous internal improvements. * Documentation typos and fixes. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Aaron Patterson * Dylan Smith * Jo Liss * Jonas Pfenniger * Kazuki Tsujimoto * Michael Bishop * Michael Elufimov * NAKAMURA Usaku * Ryan Davis * Sam Grönblom * Sam Phippen * Sergio Wong * Tay Ray Chuan * grosser * quix Also, many thanks to Eric Hodel for assisting with getting this release out the door. -- Jim Weirich === Rake 0.9.2.2 Rake version 0.9.2.2 is mainly bug fixes. ==== Changes * The rake test loader now removes arguments it has processed. Issue #51 * Rake::TaskArguments now responds to #values\_at * RakeFileUtils.verbose_flag = nil silences output the same as 0.8.7 * Rake tests are now directory-independent * Rake tests are no longer require flexmock * Commands constant is no longer polluting top level namespace. * Show only the interesting portion of the backtrace by default (James M. Lawrence). * Added --reduce-compat option to remove backward compatible DSL hacks (James M. Lawrence). ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James M. Lawrence (quix) * Roger Pack * Cezary Baginski * Sean Scot August Moon * R.T. Lechow * Alex Chaffee * James Tucker * Matthias Lüdtke * Santiago Pastorino Also, bit thanks to Eric Hodel for assisting with getting this release out the door (where "assisting" includes, but is not by any means limited to, "pushing" me to get it done). -- Jim Weirich === 0.9.2 Rake version 0.9.2 has a few small fixes. See below for details. ==== Changes * Support for Ruby 1.8.6 was fixed. * Global DSL warnings now honor --no-deprecate ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James M. Lawrence (quix) * Roger Pack * Cezary Baginski * Sean Scot August Moon * R.T. Lechow * Alex Chaffee * James Tucker * Matthias Lüdtke * Santiago Pastorino Also, bit thanks to Eric Hodel for assisting with getting this release out the door (where "assisting" includes, but is not by any means limited to, "pushing" me to get it done). -- Jim Weirich === 0.9.1 Rake version 0.9.1 has a number of bug fixes and enhancments (see below for more details). Additionally, the internals have be slightly restructured and improved. ==== Changes Rake 0.9.1 adds back the global DSL methods, but with deprecation messages. This allows Rake 0.9.1 to be used with older rakefiles with warning messages. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James M. Lawrence (quix) * Roger Pack * Cezary Baginski * Sean Scot August Moon * R.T. Lechow * Alex Chaffee * James Tucker * Matthias Lüdtke * Santiago Pastorino Also, bit thanks to Eric Hodel for assisting with getting this release out the door (where "assisting" includes, but is not by any means limited to, "pushing" me to get it done). -- Jim Weirich === 0.9.0 Rake version 0.9.0 has a number of bug fixes and enhancments (see below for more details). Additionally, the internals have be slightly restructured and improved. ==== Changes ===== New Features / Enhancements / Bug Fixes in Version 0.9.0 * Rake now warns when the deprecated :needs syntax used (and suggests the proper syntax in the warning). * Moved Rake DSL commands to top level ruby object 'main'. Rake DSL commands are no longer private methods in Object. (Suggested by James M. Lawrence/quix) * Rake now uses case-insensitive comparisons to find the Rakefile on Windows. Based on patch by Roger Pack. * Rake now requires (instead of loads) files in the test task. Patch by Cezary Baginski. * Fixed typos. Patches by Sean Scot August Moon and R.T. Lechow. * Rake now prints the Rakefile directory only when it's different from the current directory. Patch by Alex Chaffee. * Improved rakefile_location discovery on Windows. Patch by James Tucker. * Rake now recognizes "Windows Server" as a windows system. Patch by Matthias Lüdtke * Rake::RDocTask is deprecated. Use RDoc::Task from RDoc 2.4.2+ (require 'rdoc/task') * Rake::GemPackageTask is deprecated. Use Gem::PackageTask (require 'rubygems/package\_task') * Rake now outputs various messages to $stderr instead of $stdout. * Rake no longer emits warnings for Config. Patch by Santiago Pastorino. * Removed Rake's DSL methods from the top level scope. If you need to call 'task :xzy' in your code, include Rake::DSL into your class, or put the code in a Rake::DSL.environment do ... end block. * Split rake.rb into individual files. * Support for the --where (-W) flag for showing where a task is defined. * Fixed quoting in test task. (http://onestepback.org/redmine/issues/show/44, http://www.pivotaltracker.com/story/show/1223138) * Fixed the silent option parsing problem. (http://onestepback.org/redmine/issues/show/47) * Fixed :verbose=>false flag on sh and ruby commands. * Rake command line options may be given by default in a RAKEOPT environment variable. * Errors in Rake will now display the task invocation chain in effect at the time of the error. * Accepted change by warnickr to not expand test patterns in shell (allowing more files in the test suite). * Fixed that file tasks did not perform prereq lookups in scope (Redmine #57). ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James M. Lawrence (quix) * Roger Pack * Cezary Baginski * Sean Scot August Moon * R.T. Lechow * Alex Chaffee * James Tucker * Matthias Lüdtke * Santiago Pastorino Also, bit thanks to Eric Hodel for assisting with getting this release out the door (where "assisting" includes, but is not by any means limited to, "pushing" me to get it done). -- Jim Weirich === 0.8.7 Rake version 0.8.5 introduced greatly improved support for executing commands on Windows. The "sh" command now has the same semantics on Windows that it has on Unix based platforms. Rake version 0.8.6 includes minor fixes the the RDoc generation. Rake version 0.8.7 includes a minor fix for JRuby running on windows. ==== Changes ===== New Features / Enhancements in Version 0.8.5 * Improved implementation of the Rake system command for Windows. (patch from James M. Lawrence/quix) * Support for Ruby 1.9's improved system command. (patch from James M. Lawrence/quix) * Rake now includes the configured extension when invoking an executable (Config::CONFIG['EXEEXT]) ===== Bug Fixes in Version 0.8.5 * Environment variable keys are now correctly cased (it matters in some implementations). ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Charles Nutter -- Jim Weirich === 0.8.6 Rake version 0.8.5 introduced greatly improved support for executing commands on Windows. The "sh" command now has the same semantics on Windows that it has on Unix based platforms. Rake version 0.8.5 includes minor fixes the the RDoc generation. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James M. Lawrence/quix * Luis Lavena -- Jim Weirich === 0.8.5 Rake version 0.8.5 is a new release of Rake with greatly improved support for executing commands on Windows. The "sh" command now has the same semantics on Windows that it has on Unix based platforms. ==== Changes ===== New Features / Enhancements in Version 0.8.5 * Improved implementation of the Rake system command for Windows. (patch from James M. Lawrence/quix) * Support for Ruby 1.9's improved system command. (patch from James M. Lawrence/quix) * Rake now includes the configured extension when invoking an executable (Config::CONFIG['EXEEXT]) ===== Bug Fixes in Version 0.8.5 * Environment variable keys are now correctly cased (it matters in some implementations). ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James M. Lawrence/quix * Luis Lavena -- Jim Weirich === 0.8.4 Rake version 0.8.4 is a bug-fix release of rake. NOTE: The version of Rake that comes with Ruby 1.9 has diverged slightly from the core Rake code base. Rake 0.8.4 will work with Ruby 1.9, but is not a strict upgrade for the Rake that comes with Ruby 1.9. A (near) future release of Rake will unify those two codebases. ==== Letter Writing Campaign Thanks to Aaron Patterson (@tenderlove) and Eric Hodel (@drbrain) for their encouraging support in organizing a letter writing campaign to lobby for the "Warning Free" release of rake 0.8.4. A special callout goes to Jonathan D. Lord, Sr (Dr. Wingnut) whose postcard was the first to actually reach me. (see http://tenderlovemaking.com/2009/02/26/we-need-a-new-version-of-rake/ for details) ==== Changes ===== New Features / Enhancements in Version 0.8.4 * Case is preserved on rakefile names. (patch from James M. Lawrence/quix) * Improved Rakefile case insensitivity testing (patch from Luis Lavena). * Windows system dir search order is now: HOME, HOMEDRIVE + HOMEPATH, APPDATA, USERPROFILE (patch from Luis Lavena) * MingGW is now recognized as a windows platform. (patch from Luis Lavena) ===== Bug Fixes in Version 0.8.4 * Removed reference to manage_gem to fix the warning produced by the gem package task. * Fixed stray ARGV option problem that was interfering with Test::Unit::Runner. (patch from Pivotal Labs) ===== Infrastructure Improvements in Version 0.8.4 * Numerous fixes to the windows test suite (patch from Luis Lavena). * Improved Rakefile case insensitivity testing (patch from Luis Lavena). * Better support for windows paths in the test task (patch from Simon Chiang/bahuvrihi) ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James M. Lawrence/quix * Luis Lavena * Pivotal Labs * Simon Chiang/bahuvrihi -- Jim Weirich === 0.8.3 Rake version 0.8.3 is a bug-fix release of rake. ==== Changes ===== Bug Fixes in Version 0.8.3 * Enhanced the system directory detection in windows. We now check HOMEDRIVE/HOMEPATH and USERPROFILE if APPDATA isn't found. (Patch supplied by James Tucker). Rake no long aborts if it can't find the directory. * Added fix to handle ruby installations in directories with spaces in their name. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Edwin Pratomo * Gavin Stark * Adam Q. Salter * Adam Majer * Emanuel Indermühle * Ittay Dror * Bheeshmar Redheendran (for spending an afternoon with me debugging windows issues) -- Jim Weirich === 0.8.2 Rake version 0.8.2 is a new release of rake that includes a number of new features and numerous bug fixes. ==== Changes ===== New Features in Version 0.8.2 * Switched from getoptlong to optparse (patches supplied by Edwin Pratomo). * The -T option will now attempt to dynamically sense the size of the terminal. The -T output will only self-truncate if the output is a tty. However, if RAKE_COLUMNS is explicitly set, it will be honored in any case. (Patch provided by Gavin Stark). * The following public methods have been added to rake task objects: * task.clear -- Clear both the prerequisites and actions of the target rake task. * task.clear_prerequisites -- Clear all the existing prerequisites from the target rake task. * task.clear_actions -- Clear all the existing actions from the target rake task. * task.reenable -- Re-enable a task, allowing its actions to be executed again if the task is invoked. * Changed RDoc test task to have no default template. This makes it easier for the tempate to pick up the template from the environment. * Default values for task arguments can easily be specified with the :with_defaults method. (Idea for default argument merging supplied by (Adam Q. Salter) ===== Bug Fixes in Version 0.8.2 * Fixed bug in package task so that it will include the subdir directory in the package for testing. (Bug found by Adam Majer) * Fixed filename dependency order bug in test\_inspect\_pending and test\_to\_s\_pending. (Bug found by Adam Majer) * Fixed check for file utils options to make them immune to the symbol/string differences. (Patch supplied by Edwin Pratomo) * Fixed bug with rules involving multiple source, where only the first dependency of a rule has any effect (Patch supplied by Emanuel Indermühle) * FileList#clone and FileList#dup have better sematics w.r.t. taint and freeze. * Changed from using Mutex to Monitor. Evidently Mutex causes thread join errors when Ruby is compiled with -disable-pthreads. (Patch supplied by Ittay Dror) * Fixed bug in makefile parser that had problems with extra spaces in file task names. (Patch supplied by Ittay Dror) ==== Other changes in Version 0.8.2 * Added ENV var to rake's own Rakefile to prevent OS X from including extended attribute junk in the rake package tar file. (Bug found by Adam Majer) * Added a performance patch for reading large makefile dependency files. (Patch supplied by Ittay Dror) ==== Task Argument Examples Prior to version 0.8.0, rake was only able to handle command line arguments of the form NAME=VALUE that were passed into Rake via the ENV hash. Many folks had asked for some kind of simple command line arguments, perhaps using "--" to separate regular task names from argument values on the command line. The problem is that there was no easy way to associate positional arguments on the command line with different tasks. Suppose both tasks :a and :b expect a command line argument: does the first value go with :a? What if :b is run first? Should it then get the first command line argument. Rake 0.8.0 solves this problem by explicitly passing values directly to the tasks that need them. For example, if I had a release task that required a version number, I could say: rake release[0.8.2] And the string "0.8.2" will be passed to the :release task. Multiple arguments can be passed by separating them with a comma, for example: rake name[john,doe] Just a few words of caution. The rake task name and its arguments need to be a single command line argument to rake. This generally means no spaces. If spaces are needed, then the entire rake + argument string should be quoted. Something like this: rake "name[billy bob, smith]" (Quoting rules vary between operating systems and shells, so make sure you consult the proper docs for your OS/shell). ===== Tasks that Expect Parameters Parameters are only given to tasks that are setup to expect them. In order to handle named parameters, the task declaration syntax for tasks has been extended slightly. For example, a task that needs a first name and last name might be declared as: task :name, :first_name, :last_name The first argument is still the name of the task (:name in this case). The next to argumements are the names of the parameters expected by :name (:first_name and :last_name in the example). To access the values of the parameters, the block defining the task behaviour can now accept a second parameter: task :name, :first_name, :last_name do |t, args| puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end The first argument of the block "t" is always bound to the current task object. The second argument "args" is an open-struct like object that allows access to the task arguments. Extra command line arguments to a task are ignored. Missing command line arguments are given the nil value. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Edwin Pratomo * Gavin Stark * Adam Q. Salter * Adam Majer * Emanuel Indermühle * Ittay Dror * Bheeshmar Redheendran (for spending an afternoon with me debugging windows issues) -- Jim Weirich === 0.8.0/0.8.1 Rake version 0.8.0 is a new release of rake that includes serveral new features. ==== Changes ===== New Features in Version 0.8.0 * Tasks can now receive command line parameters. See the examples below for more details. * Comments are limited to 80 columns on output, but full comments can be seen by using the -D parameter. (feature suggested by Jamis Buck). * Explicit exit(n) calls will now set the exit status to n. (patch provided by Stephen Touset). * Rake is now compatible with Ruby 1.9. Version 0.8.1 is a minor update that includes additional Ruby 1.9 compatibility fixes. ==== Task Argument Examples Prior to version 0.8.0, rake was only able to handle command line arguments of the form NAME=VALUE that were passed into Rake via the ENV hash. Many folks had asked for some kind of simple command line arguments, perhaps using "--" to separate regular task names from argument values on the command line. The problem is that there was no easy way to associate positional arguments on the command line with different tasks. Suppose both tasks :a and :b expect a command line argument: does the first value go with :a? What if :b is run first? Should it then get the first command line argument. Rake 0.8.0 solves this problem by explicitly passing values directly to the tasks that need them. For example, if I had a release task that required a version number, I could say: rake release[0.8.0] And the string "0.8.0" will be passed to the :release task. Multiple arguments can be passed by separating them with a comma, for example: rake name[john,doe] Just a few words of caution. The rake task name and its arguments need to be a single command line argument to rake. This generally means no spaces. If spaces are needed, then the entire rake + argument string should be quoted. Something like this: rake "name[billy bob, smith]" (Quoting rules vary between operating systems and shells, so make sure you consult the proper docs for your OS/shell). ===== Tasks that Expect Parameters Parameters are only given to tasks that are setup to expect them. In order to handle named parameters, the task declaration syntax for tasks has been extended slightly. For example, a task that needs a first name and last name might be declared as: task :name, :first_name, :last_name The first argument is still the name of the task (:name in this case). The next to argumements are the names of the parameters expected by :name (:first_name and :last_name in the example). To access the values of the parameters, the block defining the task behaviour can now accept a second parameter: task :name, :first_name, :last_name do |t, args| puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end The first argument of the block "t" is always bound to the current task object. The second argument "args" is an open-struct like object that allows access to the task arguments. Extra command line arguments to a task are ignored. Missing command line arguments are given the nil value. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Jamis Buck (for comment formatting suggestions) * Stephen Touset (for exit status patch). -- Jim Weirich === 0.7.3 Rake version 0.7.3 is a minor release that includes some refactoring to better support custom Rake applications. ==== Changes ===== New Features in Version 0.7.3 * Added the +init+ and +top_level+ methods to make the creation of custom Rake applications a bit easier. E.g. gem 'rake', ">= 0.7.3" require 'rake' Rake.application.init('myrake') task :default do something_interesting end Rake.application.top_level ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... -- Jim Weirich === 0.7.2 Version 0.7.2 supplies a bug fix and a few minor enhancements. In particular, the new version fixes an incompatibility with the soon to be released Ruby 1.8.6. We strongly recommend upgrading to Rake 0.7.2 in order to be compatible with the new version of Ruby. ==== Changes ===== Bug Fixes in 0.7.2 There are quite a number of bug fixes in the new 0.7.2 version of Rake: * Removed dependency on internal fu_xxx functions from FileUtils. * Error messages are now send to stderr rather than stdout (from Payton Quackenbush). * Better error handling on invalid command line arguments (from Payton Quackenbush). * Fixed some bugs where the application object was going to the global appliation instead of using its own data. * Fixed the method name leak from FileUtils (bug found by Glenn Vanderburg). * Added test for noop, bad_option and verbose flags to sh command. * Added a description to the gem task in GemPackageTask. * Fixed a bug when rules have multiple prerequisites (patch by Joel VanderWerf) * Added the handful of RakeFileUtils to the private method as well. ===== New Features in 0.7.2 The following new features are available in Rake version 0.7.2: * Added square and curly bracket patterns to FileList#include (Tilman Sauerbeck). * FileLists can now pass a block to FileList#exclude to exclude files based on calculated values. * Added plain filename support to rule dependents (suggested by Nobu Nakada). * Added pathmap support to rule dependents. In other words, if a pathmap format (beginning with a '%') is given as a Rake rule dependent, then the name of the depend will be the name of the target with the pathmap format applied. * Added a 'tasks' method to a namespace to get a list of tasks associated with the namespace. * Added tar_command and zip_command options to the Package task. * The clean task will no longer delete 'core' if it is a directory. ===== Internal Rake Improvements The following changes will are mainly internal improvements and refactorings and have little effect on the end user. But they may be of interest to the general public. * Added rcov task and updated unit testing for better code coverage. * Added a 'shame' task to the Rakefile. * Added rake_extension to handle detection of extension collisions. * Added a protected 'require "rubygems"' to test/test_application to unbreak cruisecontrol.rb. * Removed rake\_dup. Now we just simply rescue a bad dup. * Refactored the FileList reject logic to remove duplication. * Removed if \_\_FILE\_\_ at the end of the rake.rb file. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Payton Quackenbush -- For several error handling improvements. * Glenn Vanderburg -- For finding and fixing the method name leak from FileUtils. * Joel VanderWerf -- for finding and fixing a bug in the handling of multiple prerequisites. * Tilman Sauerbeck -- For some enhancing FileList to support more advanced file globbing. * Nobu Nakada -- For suggesting plain file name support to rule dependents. -- Jim Weirich === 0.7.1 Version 0.7.1 supplies a bug fix and a few minor enhancements. ==== Changes ===== Bug Fixes in 0.7.1 * Changes in the exception reported for the FileUtils.ln caused safe_ln to fail with a NotImplementedError. Rake 0.7.1 will now catch that error or any StandardError and properly fall back to using +cp+. ===== New Features in 0.7.1 * You can filter the results of the --task option by supplying an optional regular expression. This allows the user to easily find a particular task name in a long list of possible names. * Transforming procs in a rule may now return a list of prerequisites. This allows more flexible rule formation. * FileList and String now support a +pathmap+ melthod that makes the transforming paths a bit easier. See the API docs for +pathmap+ for details. * The -f option without a value will disable the search for a Rakefile. This allows the Rakefile to be defined entirely in a library (and loaded with the -r option). The current working directory is not changed when this is done. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * James Britt and Assaph Mehr for reporting and helping to debug the safe_ln issue. -- Jim Weirich === 0.7.0 These changes for Rake have been brewing for a long time. Here they are, I hope you enjoy them. ==== Changes ===== New Features * Name space support for task names (see below). * Prerequisites can be executed in parallel (see below). * Added safe_ln support for openAFS (via Ludvig Omholt). * RDoc defaults to internal (in-process) invocation. The old behavior is still available by setting the +external+ flag to true. * Rakefiles are now loaded with the expanded path to prevent accidental pollution from the Ruby load path. * Task objects my now be used in prerequisite lists directly. * Task objects (in addition to task names) may now be included in the prerequisite list of a task. * Internals cleanup and refactoring. ===== Bug Fixes * Compatibility fixes for Ruby 1.8.4 FileUtils changes. ===== Namespaces Tasks can now be nested inside their own namespaces. Tasks within one namespace will not accidentally interfer with tasks named in a different namespace. For example: namespace "main" do task :build do # Build the main program end end namespace "samples" do task :build do # Build the sample programs end end task :build_all => ["main:build", "samples:build"] Even though both tasks are named :build, they are separate tasks in their own namespaces. The :build_all task (defined in the toplevel namespace) references both build tasks in its prerequisites. You may invoke each of the individual build tasks with the following commands: rake main:build rake samples:build Or invoke both via the :build_all command: rake build_all Namespaces may be nested arbitrarily. Since the name of file tasks correspond to the name of a file in the external file system, FileTasks are not affected by the namespaces. See the Rakefile format documentation (in the Rake API documents) for more information. ===== Parallel Tasks Sometimes you have several tasks that can be executed in parallel. By specifying these tasks as prerequisites to a +multitask+ task. In the following example the tasks copy\_src, copy\_doc and copy\_bin will all execute in parallel in their own thread. multitask :copy_files => [:copy_src, :copy_doc, :copy_bin] do puts "All Copies Complete" end ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Doug Young (inspiration for the parallel task) * David Heinemeier Hansson (for --trace message enhancement and for pushing for namespace support). * Ludvig Omholt (for the openAFS fix) -- Jim Weirich === 0.6.1 * Rebuilt 0.6.0 gem without signing. === 0.6.0 Its time for some long requested enhancements and lots of bug fixes ... And a whole new web page. ==== New Web Page The primary documentation for rake has moved from the RubyForge based wiki to its own Hieraki based web site. Constant spam on the wiki made it a difficult to keep clean. The new site will be easier to update and organize. Check out the new documentation at: http://docs.rubyrake.org We will be adding new documentation to the site as time goes on. In addition to the new docs page, make sure you check out Martin Fowlers article on rake at http://martinfowler.com/articles/rake.html ==== Changes ===== New Features * Multiple prerequisites on Rake rules now allowed. However, keep the following in mind: 1. All the prerequisites of a rule must be available before a rule is triggered, where "enabled" means (a) an existing file, (b) a defined rule, or (c) another rule which also must be trigger-able. 2. Rules are checked in order of definition, so it is important to order your rules properly. If a file can be created by two different rules, put the more specific rule first (otherwise the more general rule will trigger first and the specific one will never be triggered). 3. The <tt>source</tt> method now returns the name of the first prerequisite listed in the rule. <tt>sources</tt> returns the names of all the rule prerequisites, ordered as they are defined in the rule. If the task has other prerequisites not defined in the rule (but defined in an explicit task definition), then they will _not_ be included in the sources list. * FileLists may now use the egrep command. This popular enhancement is now a core part of the FileList object. If you want to get a list of all your to-dos, fixmes and TBD comments, add the following to your Rakefile. desc "Look for TODO and FIXME tags in the code" task :todo do FileList['**/*.rb'].egrep /#.*(FIXME|TODO|TBD)/ end * The <tt>investigation</tt> method was added to task object to dump out some important values. This makes it a bit easier to debug Rake tasks. For example, if you are having problems with a particular task, just print it out: task :huh do puts Rake::Task['huh'].investigation end * The Rake::TestTask class now supports a "ruby\_opts" option to pass arbitrary ruby options to a test subprocess. ===== Some Incompatibilities * When using the <tt>ruby</tt> command to start a Ruby subprocess, the Ruby interpreter that is currently running rake is used by default. This makes it easier to use rake in an environment with multiple ruby installation. (Previously, the first ruby command found in the PATH was used). If you wish to chose a different Ruby interpreter, you can explicitly choose the interpreter via the <tt>sh</tt> command. * The major rake classes (Task, FileTask, FileCreationTask, RakeApp) have been moved out of the toplevel scope and are now accessible as Rake::Task, Rake::FileTask, Rake::FileCreationTask and Rake::Application. If your Rakefile directly references any one of these tasks, you may: 1. Update your Rakefile to use the new classnames 2. Use the --classic-namespace option on the rake command to get the old behavior, 3. Add <code>require 'rake/classic_namespace'</code> to the Rakefile to get the old behavior. <tt>rake</tt> will print a rather annoying warning whenever a deprecated class name is referenced without enabling classic namespace. ===== Bug Fixes * Several unit tests and functional tests were fixed to run better under windows. * Directory tasks are now a specialized version of a File task. A directory task will only be triggered if it doesn't exist. It will not be triggered if it is out of date w.r.t. any of its prerequisites. * Fixed a bug in the Rake::GemPackageTask class so that the gem now properly contains the platform name. * Fixed a bug where a prerequisite on a <tt>file</tt> task would cause an exception if the prerequisite did not exist. ==== Thanks As usual, it was input from users that drove a alot of these changes. The following people either contributed patches, made suggestions or made otherwise helpful comments. Thanks to ... * Greg Fast (better ruby_opt test options) * Kelly Felkins (requested by better namespace support) * Martin Fowler (suggested Task.investigation) * Stuart Jansen (send initial patch for multiple prerequisites). * Masao Mutch (better support for non-ruby Gem platforms) * Philipp Neubeck (patch for file task exception fix) -- Jim Weirich === 0.5.4 Time for some minor bug fixes and small enhancements ==== Changes Here are the changes for version 0.5.4 ... * Added double quotes to the test runner. This allows the location of the tests (and runner) to be in a directory path that contains spaces (e.g. "C:/Program Files/ruby/bin"). * Added .svn to default ignore list. Now subversion project metadata is automatically ignored by Rake's FileList. * Updated FileList#include to support nested arrays and filelists. FileLists are flat lists of file names. Using a FileList in an include will flatten out the nested file names. == Thanks As usual, it was input from users that drove a alot of these changes. Thanks to ... * Tilman Sauerbeck for the nested FileList suggestion. * Josh Knowles for pointing out the spaces in directory name problem. -- Jim Weirich === 0.5.3 Although it has only been two weeks since the last release, we have enough updates to the Rake program to make it time for another release. ==== Changes Here are the changes for version 0.5.3 ... * FileLists have been extensively changed so that they mimic the behavior of real arrays even more closely. In particular, operations on FileLists that return a new collection (e.g. collect, reject) will now return a FileList rather than an array. In addition, several places where FileLists were not properly expanded before use have been fixed. * A method (+ext+) to simplify the handling of file extensions was added to String and to Array. * The 'testrb' script in test/unit tends to silently swallow syntax errors in test suites. Because of that, the default test loader is now a rake-provided script. You can still use 'testrb' by setting the loader flag in the test task to :testrb. (See the API documents for TestTask for all the loader flag values). * FileUtil methods (e.g. cp, mv, install) are now declared to be private. This will cut down on the interference with user defined methods of the same name. * Fixed the verbose flag in the TestTask so that the test code is controlled by the flag. Also shortened up some failure messages. (Thanks to Tobias Luetke for the suggestion). * Rules will now properly detect a task that can generate a source file. Previously rules would only consider source files that were already present. * Added an +import+ command that allows Rake to dynamically import dependendencies into a running Rake session. The +import+ command can run tasks to update the dependency file before loading them. Dependency files can be in rake or make format, allowing rake to work with tools designed to generate dependencies for make. ==== Thanks As usual, it was input from users that drove a alot of these changes. Thanks to ... * Brian Gernhardt for the rules fix (especially for the patience to explain the problem to me until I got what he was talking about). * Stefan Lang for pointing out problems in the dark corners of the FileList implementation. * Alexey Verkhovsky pointing out the silently swallows syntax errors in tests. * Tobias Luetke for beautifying the test task output. * Sam Roberts for some of the ideas behind dependency loading. -- Jim Weirich === 0.5.0 It has been a long time in coming, but we finally have a new version of Rake available. ==== Changes * Fixed documentation that was lacking the Rake module name (Tilman Sauerbeck). * Added tar.gz and tar.bz2 support to package task (Tilman Sauerbeck). * Recursive rules are now supported (Tilman Sauerbeck). * Added warning option for the Test Task (requested by Eric Hodel). * The jamis rdoc template is only used if it exists. * Added fix for Ruby 1.8.2 test/unit and rails problem. * Added contributed rake man file (Jani Monoses). * Added Brian Candler's fix for problems in --trace and --dry-run mode. ==== Thanks Lots of people provided input to this release. Thanks to Tilman Sauerbeck for numerous patches, documentation fixes and suggestions. And for also pushing me to get this release out. Also, thanks to Brian Candler for the finding and fixing --trace/dry-run fix. That was an obscure bug. Also to Eric Hodel for some good suggestions. -- Jim Weirich === 0.4.15 ==== Changes Version 0.4.15 is a bug fix update for the Ruby 1.8.2 compatibility changes. This release includes: * Fixed a bug that prevented the TESTOPTS flag from working with the revised for 1.8.2 test task. * Updated the docs on --trace to indicate that it also enables a full backtrace on errors. * Several fixes for new warnings generated. ==== Mini-Roadmap I will continue to issue Rake updates in the 0.4.xx series as new Ruby-1.8.2 issues become manifest. Once the codebase stabilizes, I will release a 0.5.0 version incorporating all the changes. If you are not using Ruby-1.8.2 and wish to avoid version churn, I recommend staying with a release prior to Rake-0.4.14. === 0.4.14 Version 0.4.14 is a compatibility fix to allow Rake's test task to work under Ruby 1.8.2. A change in the Test::Unit autorun feature prevented Rake from running any tests. This release fixes the problem. Rake 0.4.14 is the recommended release for anyone using Ruby 1.8.2. === 0.4.13 * Fixed the dry-run flag so it is operating again. * Multiple arguments to sh and ruby commands will not be interpreted by the shell (patch provided by Jonathan Paisley). === 0.4.12 * Added --silent (-s) to suppress the (in directory) rake message. === 0.4.11 * Changed the "don't know how to rake" message (finally) * Changes references to a literal "Rakefile" to reference the global variable $rakefile (which contains the actual name of the rakefile). === 0.4.10 * Added block support to the "sh" command, allowing users to take special actions on the result of the system call. E.g. sh "shell_command" do |ok, res| puts "Program returned #{res.exitstatus}" if ! ok end === 0.4.9 * Switched to Jamis Buck's RDoc template. * Removed autorequire from Rake's gem spec. This prevents the Rake libraries from loading while using rails. === 0.4.8 * Added support for .rb versions of Rakefile. * Removed \\\n's from test task. * Fixed Ruby 1.9 compatibility issue with FileList. === 0.4.7 * Fixed problem in FileList that caused Ruby 1.9 to go into infinite recursion. Since to_a was removed from Object, it does not need to added back into the list of methods to rewrite in FileList. (Thanks to Kent Sibilev for pointing this out). === 0.4.6 * Removed test version of ln in FileUtils that prevented safe_ln from using ln. === 0.4.5 * Upgraded comments in TestTask. * FileList to_s and inspect now automatically resolve pending changes. * FileList#exclude properly returns the FileList. === 0.4.4 * Fixed initialization problem with @comment. * Now using multi -r technique in TestTask. Switch Rakefile back to using the built-in test task macros because the rake runtime is no longer needed. * Added 'TEST=filename' and 'TESTOPTS=options' to the Test Task macros. * Allow a +test_files+ attribute in test tasks. This allows more flexibility in specifying test files. === 0.4.3 * Fixed Comment leakage. === 0.4.2 * Added safe_ln that falls back to a copy if a file link is not supported. * Package builder now uses safe\_ln. === 0.4.1 * Task comments are now additive, combined with "/". * Works with (soon to be released) rubygems 0.6.2 (or 0.7.0) === 0.4.0 * FileList now uses deferred loading. The file system is not searched until the first call that needs the file names. * VAR=VALUE options are now accepted on the command line and are treated like environment variables. The values may be tested in a Rakefile by referencing ENV['VAR']. * File.mtime is now used (instead of File.new().mtime). === 0.3.2.x * Removed some hidden dependencies on rubygems. Tests now will test gems only if they are installed. * Removed Sys from some example files. I believe that is that last reference to Sys outside of the contrib area. * Updated all copyright notices to include 2004. === 0.3.2 * GEM Installation now works with the application stub. === 0.3.1 * FileLists now automatically ignore CVS, .bak, ! * GEM Installation now works. === 0.3.0 Promoted 0.2.10. === 0.2.10 General * Added title to Rake's rdocs * Contrib packages are no longer included in the documentation. RDoc Issues * Removed default for the '--main' option * Fixed rendering of the rdoc options * Fixed clean/clobber confusion with rerdoc * 'title' attribute added Package Task Library Issues * Version (or explicit :noversion) is required. * +package_file+ attribute is now writable FileList Issues * Dropped bang version of exclude. Now using ant-like include/exclude semantics. * Enabled the "yield self" idiom in FileList#initialize. === 0.2.9 This version contains numerous changes as the RubyConf.new(2003) presentation was being prepared. The changes include: * The monolithic rubyapp task library is in the process of being dropped in favor of lighter weight task libraries. === 0.2.7 * Added "desc" for task descriptions. * -T will now display tasks with descriptions. * -P will display tasks and prerequisites. * Dropped the Sys module in favor of the 1.8.x FileUtils module. Sys is still supported in the contrib area. === 0.2.6 * Moved to RubyForge === 0.2.5 * Switched to standard ruby app builder. * Added no_match option to file matcher. === 0.2.4 * Fixed indir, which neglected to actually change directories. === 0.2.3 * Added rake module for a help target * Added 'for\_files' to Sys * Added a $rakefile constant * Added test for selecting proper rule with multiple targets. #!/opt/alt/ruby33/bin/ruby # Tiny eRuby --- ERB2 # Copyright (c) 1999-2000,2002 Masatoshi SEKI # You can redistribute it and/or modify it under the same terms as Ruby. require 'erb' class ERB module Main def ARGV.switch return nil if self.empty? arg = self.shift return nil if arg == '--' case arg when /\A-(.)(.*)/ if $1 == '-' arg, @maybe_arg = arg.split(/=/, 2) return arg end raise 'unknown switch "-"' if $2[0] == ?- and $1 != 'T' if $2.size > 0 self.unshift "-#{$2}" @maybe_arg = $2 else @maybe_arg = nil end "-#{$1}" when /\A(\w+)=/ arg else self.unshift arg nil end end def ARGV.req_arg (@maybe_arg || self.shift || raise('missing argument')).tap { @maybe_arg = nil } end def trim_mode_opt(trim_mode, disable_percent) return trim_mode if disable_percent case trim_mode when 0 return '%' when 1 return '%>' when 2 return '%<>' when '-' return '%-' end end module_function :trim_mode_opt def run(factory=ERB) trim_mode = 0 disable_percent = false variables = {} begin while switch = ARGV.switch case switch when '-x' # ruby source output = true when '-n' # line number number = true when '-v' # verbose $VERBOSE = true when '--version' # version STDERR.puts factory.version exit when '-d', '--debug' # debug $DEBUG = true when '-r' # require require ARGV.req_arg when '-T' # trim mode arg = ARGV.req_arg if arg == '-' trim_mode = arg next end raise "invalid trim mode #{arg.dump}" unless arg =~ /\A[0-2]\z/ trim_mode = arg.to_i when '-E', '--encoding' arg = ARGV.req_arg set_encoding(*arg.split(/:/, 2)) when '-U' set_encoding(Encoding::UTF_8, Encoding::UTF_8) when '-P' disable_percent = true when '--help' raise "print this help" when /\A-/ raise "unknown switch #{switch.dump}" else var, val = *switch.split('=', 2) (variables ||= {})[var] = val end end rescue # usage STDERR.puts $!.to_s STDERR.puts File.basename($0) + " [switches] [var=value...] [inputfile]" STDERR.puts <<EOU -x print ruby script -n print ruby script with line number -v enable verbose mode -d set $DEBUG to true -r library load a library -E ex[:in] set default external/internal encodings -U set default encoding to UTF-8 -T trim_mode specify trim_mode (0..2, -) -P disable ruby code evaluation for lines beginning with % var=value set variable EOU exit 1 end $<.set_encoding(Encoding::UTF_8, nil) src = $<.read filename = $FILENAME exit 2 unless src trim = trim_mode_opt(trim_mode, disable_percent) erb = factory.new(src, trim_mode: trim) erb.filename = filename if output if number erb.src.each_line.with_index do |line, l| puts "%3d %s"%[l+1, line] end else puts erb.src end else bind = TOPLEVEL_BINDING if variables enc = erb.encoding for var, val in variables do val = val.encode(enc) if val bind.local_variable_set(var, val) end end erb.run(bind) end end module_function :run def set_encoding(extern, intern = nil) verbose, $VERBOSE = $VERBOSE, nil Encoding.default_external = extern unless extern.nil? || extern == "" Encoding.default_internal = intern unless intern.nil? || intern == "" [$stdin, $stdout, $stderr].each do |io| io.set_encoding(extern, intern) end ensure $VERBOSE = verbose end module_function :set_encoding class << self; private :set_encoding; end end end ERB::Main.run # frozen_string_literal: true require_relative "bundler/vendored_fileutils" require "pathname" require "rbconfig" require_relative "bundler/errors" require_relative "bundler/environment_preserver" require_relative "bundler/plugin" require_relative "bundler/rubygems_ext" require_relative "bundler/rubygems_integration" require_relative "bundler/version" require_relative "bundler/constants" require_relative "bundler/current_ruby" require_relative "bundler/build_metadata" # Bundler provides a consistent environment for Ruby projects by # tracking and installing the exact gems and versions that are needed. # # Bundler is a part of Ruby's standard library. # # Bundler is used by creating _gemfiles_ listing all the project dependencies # and (optionally) their versions and then using # # require 'bundler/setup' # # or Bundler.setup to setup environment where only specified gems and their # specified versions could be used. # # See {Bundler website}[https://bundler.io/docs.html] for extensive documentation # on gemfiles creation and Bundler usage. # # As a standard library inside project, Bundler could be used for introspection # of loaded and required modules. # module Bundler environment_preserver = EnvironmentPreserver.from_env ORIGINAL_ENV = environment_preserver.restore environment_preserver.replace_with_backup SUDO_MUTEX = Thread::Mutex.new autoload :Checksum, File.expand_path("bundler/checksum", __dir__) autoload :CLI, File.expand_path("bundler/cli", __dir__) autoload :CIDetector, File.expand_path("bundler/ci_detector", __dir__) autoload :CompactIndexClient, File.expand_path("bundler/compact_index_client", __dir__) autoload :Definition, File.expand_path("bundler/definition", __dir__) autoload :Dependency, File.expand_path("bundler/dependency", __dir__) autoload :Deprecate, File.expand_path("bundler/deprecate", __dir__) autoload :Digest, File.expand_path("bundler/digest", __dir__) autoload :Dsl, File.expand_path("bundler/dsl", __dir__) autoload :EndpointSpecification, File.expand_path("bundler/endpoint_specification", __dir__) autoload :Env, File.expand_path("bundler/env", __dir__) autoload :Fetcher, File.expand_path("bundler/fetcher", __dir__) autoload :FeatureFlag, File.expand_path("bundler/feature_flag", __dir__) autoload :GemHelper, File.expand_path("bundler/gem_helper", __dir__) autoload :GemHelpers, File.expand_path("bundler/gem_helpers", __dir__) autoload :GemVersionPromoter, File.expand_path("bundler/gem_version_promoter", __dir__) autoload :Graph, File.expand_path("bundler/graph", __dir__) autoload :Index, File.expand_path("bundler/index", __dir__) autoload :Injector, File.expand_path("bundler/injector", __dir__) autoload :Installer, File.expand_path("bundler/installer", __dir__) autoload :LazySpecification, File.expand_path("bundler/lazy_specification", __dir__) autoload :LockfileParser, File.expand_path("bundler/lockfile_parser", __dir__) autoload :MatchRemoteMetadata, File.expand_path("bundler/match_remote_metadata", __dir__) autoload :ProcessLock, File.expand_path("bundler/process_lock", __dir__) autoload :RemoteSpecification, File.expand_path("bundler/remote_specification", __dir__) autoload :Resolver, File.expand_path("bundler/resolver", __dir__) autoload :Retry, File.expand_path("bundler/retry", __dir__) autoload :RubyDsl, File.expand_path("bundler/ruby_dsl", __dir__) autoload :RubyVersion, File.expand_path("bundler/ruby_version", __dir__) autoload :Runtime, File.expand_path("bundler/runtime", __dir__) autoload :SelfManager, File.expand_path("bundler/self_manager", __dir__) autoload :Settings, File.expand_path("bundler/settings", __dir__) autoload :SharedHelpers, File.expand_path("bundler/shared_helpers", __dir__) autoload :Source, File.expand_path("bundler/source", __dir__) autoload :SourceList, File.expand_path("bundler/source_list", __dir__) autoload :SourceMap, File.expand_path("bundler/source_map", __dir__) autoload :SpecSet, File.expand_path("bundler/spec_set", __dir__) autoload :StubSpecification, File.expand_path("bundler/stub_specification", __dir__) autoload :UI, File.expand_path("bundler/ui", __dir__) autoload :URICredentialsFilter, File.expand_path("bundler/uri_credentials_filter", __dir__) autoload :URINormalizer, File.expand_path("bundler/uri_normalizer", __dir__) autoload :SafeMarshal, File.expand_path("bundler/safe_marshal", __dir__) class << self def configure @configure ||= configure_gem_home_and_path end def ui (defined?(@ui) && @ui) || (self.ui = UI::Shell.new) end def ui=(ui) Bundler.rubygems.ui = UI::RGProxy.new(ui) @ui = ui end # Returns absolute path of where gems are installed on the filesystem. def bundle_path @bundle_path ||= Pathname.new(configured_bundle_path.path).expand_path(root) end def create_bundle_path mkdir_p(bundle_path) unless bundle_path.exist? @bundle_path = bundle_path.realpath rescue Errno::EEXIST raise PathError, "Could not install to path `#{bundle_path}` " \ "because a file already exists at that path. Either remove or rename the file so the directory can be created." end def configured_bundle_path @configured_bundle_path ||= settings.path.tap(&:validate!) end # Returns absolute location of where binstubs are installed to. def bin_path @bin_path ||= begin path = settings[:bin] || "bin" path = Pathname.new(path).expand_path(root).expand_path mkdir_p(path) path end end # Turns on the Bundler runtime. After +Bundler.setup+ call, all +load+ or # +require+ of the gems would be allowed only if they are part of # the Gemfile or Ruby's standard library. If the versions specified # in Gemfile, only those versions would be loaded. # # Assuming Gemfile # # gem 'first_gem', '= 1.0' # group :test do # gem 'second_gem', '= 1.0' # end # # The code using Bundler.setup works as follows: # # require 'third_gem' # allowed, required from global gems # require 'first_gem' # allowed, loads the last installed version # Bundler.setup # require 'fourth_gem' # fails with LoadError # require 'second_gem' # loads exactly version 1.0 # # +Bundler.setup+ can be called only once, all subsequent calls are no-op. # # If _groups_ list is provided, only gems from specified groups would # be allowed (gems specified outside groups belong to special +:default+ group). # # To require all gems from Gemfile (or only some groups), see Bundler.require. # def setup(*groups) # Return if all groups are already loaded return @setup if defined?(@setup) && @setup definition.validate_runtime! SharedHelpers.print_major_deprecations! if groups.empty? # Load all groups, but only once @setup = load.setup else load.setup(*groups) end end def auto_switch self_manager.restart_with_locked_bundler_if_needed end # Automatically install dependencies if Bundler.settings[:auto_install] exists. # This is set through config cmd `bundle config set --global auto_install 1`. # # Note that this method `nil`s out the global Definition object, so it # should be called first, before you instantiate anything like an # `Installer` that'll keep a reference to the old one instead. def auto_install return unless settings[:auto_install] begin definition.specs rescue GemNotFound, GitError ui.info "Automatically installing missing gems." reset! CLI::Install.new({}).run reset! end end # Setups Bundler environment (see Bundler.setup) if it is not already set, # and loads all gems from groups specified. Unlike ::setup, can be called # multiple times with different groups (if they were allowed by setup). # # Assuming Gemfile # # gem 'first_gem', '= 1.0' # group :test do # gem 'second_gem', '= 1.0' # end # # The code will work as follows: # # Bundler.setup # allow all groups # Bundler.require(:default) # requires only first_gem # # ...later # Bundler.require(:test) # requires second_gem # def require(*groups) setup(*groups).require(*groups) end def load @load ||= Runtime.new(root, definition) end def environment SharedHelpers.major_deprecation 2, "Bundler.environment has been removed in favor of Bundler.load", print_caller_location: true load end # Returns an instance of Bundler::Definition for given Gemfile and lockfile # # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @param lockfile [Pathname] Path to Gemfile.lock # @return [Bundler::Definition] def definition(unlock = nil, lockfile = default_lockfile) @definition = nil if unlock @definition ||= begin configure Definition.build(default_gemfile, lockfile, unlock) end end def frozen_bundle? frozen = settings[:frozen] return frozen unless frozen.nil? settings[:deployment] end def locked_gems @locked_gems ||= if defined?(@definition) && @definition definition.locked_gems elsif Bundler.default_lockfile.file? lock = Bundler.read_file(Bundler.default_lockfile) LockfileParser.new(lock) end end def most_specific_locked_platform?(platform) return false unless defined?(@definition) && @definition definition.most_specific_locked_platform == platform end def ruby_scope "#{Bundler.rubygems.ruby_engine}/#{RbConfig::CONFIG["ruby_version"]}" end def user_home @user_home ||= begin home = Bundler.rubygems.user_home bundle_home = home ? File.join(home, ".bundle") : nil warning = if home.nil? "Your home directory is not set." elsif !File.directory?(home) "`#{home}` is not a directory." elsif !File.writable?(home) && (!File.directory?(bundle_home) || !File.writable?(bundle_home)) "`#{home}` is not writable." end if warning Bundler.ui.warn "#{warning}\n" user_home = tmp_home_path Bundler.ui.warn "Bundler will use `#{user_home}' as your home directory temporarily.\n" user_home else Pathname.new(home) end end end def user_bundle_path(dir = "home") env_var, fallback = case dir when "home" ["BUNDLE_USER_HOME", proc { Pathname.new(user_home).join(".bundle") }] when "cache" ["BUNDLE_USER_CACHE", proc { user_bundle_path.join("cache") }] when "config" ["BUNDLE_USER_CONFIG", proc { user_bundle_path.join("config") }] when "plugin" ["BUNDLE_USER_PLUGIN", proc { user_bundle_path.join("plugin") }] else raise BundlerError, "Unknown user path requested: #{dir}" end # `fallback` will already be a Pathname, but Pathname.new() is # idempotent so it's OK Pathname.new(ENV.fetch(env_var, &fallback)) end def user_cache user_bundle_path("cache") end def home bundle_path.join("bundler") end def install_path home.join("gems") end def specs_path bundle_path.join("specifications") end def root @root ||= begin SharedHelpers.root rescue GemfileNotFound bundle_dir = default_bundle_dir raise GemfileNotFound, "Could not locate Gemfile or .bundle/ directory" unless bundle_dir Pathname.new(File.expand_path("..", bundle_dir)) end end def app_config_path if app_config = ENV["BUNDLE_APP_CONFIG"] app_config_pathname = Pathname.new(app_config) if app_config_pathname.absolute? app_config_pathname else app_config_pathname.expand_path(root) end else root.join(".bundle") end end def app_cache(custom_path = nil) path = custom_path || root Pathname.new(path).join(settings.app_cache_path) end def tmp(name = Process.pid.to_s) Kernel.send(:require, "tmpdir") Pathname.new(Dir.mktmpdir(["bundler", name])) end def rm_rf(path) FileUtils.remove_entry_secure(path) if path && File.exist?(path) end def settings @settings ||= Settings.new(app_config_path) rescue GemfileNotFound @settings = Settings.new end # @return [Hash] Environment present before Bundler was activated def original_env ORIGINAL_ENV.clone end # @deprecated Use `unbundled_env` instead def clean_env message = "`Bundler.clean_env` has been deprecated in favor of `Bundler.unbundled_env`. " \ "If you instead want the environment before bundler was originally loaded, use `Bundler.original_env`" removed_message = "`Bundler.clean_env` has been removed in favor of `Bundler.unbundled_env`. " \ "If you instead want the environment before bundler was originally loaded, use `Bundler.original_env`" Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true) unbundled_env end # @return [Hash] Environment with all bundler-related variables removed def unbundled_env unbundle_env(original_env) end # Remove all bundler-related variables from ENV def unbundle_env! ENV.replace(unbundle_env(ENV)) end # Run block with environment present before Bundler was activated def with_original_env with_env(original_env) { yield } end # @deprecated Use `with_unbundled_env` instead def with_clean_env message = "`Bundler.with_clean_env` has been deprecated in favor of `Bundler.with_unbundled_env`. " \ "If you instead want the environment before bundler was originally loaded, use `Bundler.with_original_env`" removed_message = "`Bundler.with_clean_env` has been removed in favor of `Bundler.with_unbundled_env`. " \ "If you instead want the environment before bundler was originally loaded, use `Bundler.with_original_env`" Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true) with_env(unbundled_env) { yield } end # Run block with all bundler-related variables removed def with_unbundled_env with_env(unbundled_env) { yield } end # Run subcommand with the environment present before Bundler was activated def original_system(*args) with_original_env { Kernel.system(*args) } end # @deprecated Use `unbundled_system` instead def clean_system(*args) message = "`Bundler.clean_system` has been deprecated in favor of `Bundler.unbundled_system`. " \ "If you instead want to run the command in the environment before bundler was originally loaded, use `Bundler.original_system`" removed_message = "`Bundler.clean_system` has been removed in favor of `Bundler.unbundled_system`. " \ "If you instead want to run the command in the environment before bundler was originally loaded, use `Bundler.original_system`" Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true) with_env(unbundled_env) { Kernel.system(*args) } end # Run subcommand in an environment with all bundler related variables removed def unbundled_system(*args) with_unbundled_env { Kernel.system(*args) } end # Run a `Kernel.exec` to a subcommand with the environment present before Bundler was activated def original_exec(*args) with_original_env { Kernel.exec(*args) } end # @deprecated Use `unbundled_exec` instead def clean_exec(*args) message = "`Bundler.clean_exec` has been deprecated in favor of `Bundler.unbundled_exec`. " \ "If you instead want to exec to a command in the environment before bundler was originally loaded, use `Bundler.original_exec`" removed_message = "`Bundler.clean_exec` has been removed in favor of `Bundler.unbundled_exec`. " \ "If you instead want to exec to a command in the environment before bundler was originally loaded, use `Bundler.original_exec`" Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true) with_env(unbundled_env) { Kernel.exec(*args) } end # Run a `Kernel.exec` to a subcommand in an environment with all bundler related variables removed def unbundled_exec(*args) with_env(unbundled_env) { Kernel.exec(*args) } end def local_platform return Gem::Platform::RUBY if settings[:force_ruby_platform] Gem::Platform.local end def default_gemfile SharedHelpers.default_gemfile end def default_lockfile SharedHelpers.default_lockfile end def default_bundle_dir SharedHelpers.default_bundle_dir end def system_bindir # Gem.bindir doesn't always return the location that RubyGems will install # system binaries. If you put '-n foo' in your .gemrc, RubyGems will # install binstubs there instead. Unfortunately, RubyGems doesn't expose # that directory at all, so rather than parse .gemrc ourselves, we allow # the directory to be set as well, via `bundle config set --local bindir foo`. Bundler.settings[:system_bindir] || Bundler.rubygems.gem_bindir end def preferred_gemfile_name Bundler.settings[:init_gems_rb] ? "gems.rb" : "Gemfile" end def use_system_gems? configured_bundle_path.use_system_gems? end def mkdir_p(path) SharedHelpers.filesystem_access(path, :write) do |p| FileUtils.mkdir_p(p) end end def which(executable) if File.file?(executable) && File.executable?(executable) executable elsif paths = ENV["PATH"] quote = '"' paths.split(File::PATH_SEPARATOR).find do |path| path = path[1..-2] if path.start_with?(quote) && path.end_with?(quote) executable_path = File.expand_path(executable, path) return executable_path if File.file?(executable_path) && File.executable?(executable_path) end end end def read_file(file) SharedHelpers.filesystem_access(file, :read) do File.open(file, "r:UTF-8", &:read) end end def safe_load_marshal(data) if Gem.respond_to?(:load_safe_marshal) Gem.load_safe_marshal begin Gem::SafeMarshal.safe_load(data) rescue Gem::SafeMarshal::Reader::Error, Gem::SafeMarshal::Visitors::ToRuby::Error => e raise MarshalError, "#{e.class}: #{e.message}" end else load_marshal(data, marshal_proc: SafeMarshal.proc) end end def load_gemspec(file, validate = false) @gemspec_cache ||= {} key = File.expand_path(file) @gemspec_cache[key] ||= load_gemspec_uncached(file, validate) # Protect against caching side-effected gemspecs by returning a # new instance each time. @gemspec_cache[key]&.dup end def load_gemspec_uncached(file, validate = false) path = Pathname.new(file) contents = read_file(file) spec = if contents.start_with?("---") # YAML header eval_yaml_gemspec(path, contents) else # Eval the gemspec from its parent directory, because some gemspecs # depend on "./" relative paths. SharedHelpers.chdir(path.dirname.to_s) do eval_gemspec(path, contents) end end return unless spec spec.loaded_from = path.expand_path.to_s Bundler.rubygems.validate(spec) if validate spec end def clear_gemspec_cache @gemspec_cache = {} end def git_present? return @git_present if defined?(@git_present) @git_present = Bundler.which("git#{RbConfig::CONFIG["EXEEXT"]}") end def feature_flag @feature_flag ||= FeatureFlag.new(VERSION) end def reset! reset_paths! Plugin.reset! reset_rubygems! end def reset_settings_and_root! @settings = nil @root = nil end def reset_paths! @bin_path = nil @bundler_major_version = nil @bundle_path = nil @configure = nil @configured_bundle_path = nil @definition = nil @load = nil @locked_gems = nil @root = nil @settings = nil @setup = nil @user_home = nil end def reset_rubygems! return unless defined?(@rubygems) && @rubygems rubygems.undo_replacements rubygems.reset @rubygems = nil end def configure_gem_home_and_path(path = bundle_path) configure_gem_path configure_gem_home(path) Bundler.rubygems.clear_paths end def self_manager @self_manager ||= begin require_relative "bundler/self_manager" Bundler::SelfManager.new end end private def unbundle_env(env) if env.key?("BUNDLER_ORIG_MANPATH") env["MANPATH"] = env["BUNDLER_ORIG_MANPATH"] end env.delete_if {|k, _| k[0, 7] == "BUNDLE_" } env.delete("BUNDLER_SETUP") if env.key?("RUBYOPT") rubyopt = env["RUBYOPT"].split(" ") rubyopt.delete("-r#{File.expand_path("bundler/setup", __dir__)}") rubyopt.delete("-rbundler/setup") env["RUBYOPT"] = rubyopt.join(" ") end if env.key?("RUBYLIB") rubylib = env["RUBYLIB"].split(File::PATH_SEPARATOR) rubylib.delete(__dir__) env["RUBYLIB"] = rubylib.join(File::PATH_SEPARATOR) end env end def load_marshal(data, marshal_proc: nil) Marshal.load(data, marshal_proc) rescue TypeError => e raise MarshalError, "#{e.class}: #{e.message}" end def eval_yaml_gemspec(path, contents) Kernel.require "psych" Gem::Specification.from_yaml(contents) rescue ::Psych::SyntaxError, ArgumentError, Gem::EndOfYAMLException, Gem::Exception eval_gemspec(path, contents) end def eval_gemspec(path, contents) eval(contents, TOPLEVEL_BINDING.dup, path.expand_path.to_s) rescue ScriptError, StandardError => e msg = "There was an error while loading `#{path.basename}`: #{e.message}" raise GemspecError, Dsl::DSLError.new(msg, path.to_s, e.backtrace, contents) end def configure_gem_path unless use_system_gems? # this needs to be empty string to cause # PathSupport.split_gem_path to only load up the # Bundler --path setting as the GEM_PATH. Bundler::SharedHelpers.set_env "GEM_PATH", "" end end def configure_gem_home(path) Bundler::SharedHelpers.set_env "GEM_HOME", path.to_s end def tmp_home_path Kernel.send(:require, "tmpdir") SharedHelpers.filesystem_access(Dir.tmpdir) do path = Bundler.tmp at_exit { Bundler.rm_rf(path) } path end end # @param env [Hash] def with_env(env) backup = ENV.to_hash ENV.replace(env) yield ensure ENV.replace(backup) end end end # frozen_string_literal: true require_relative "base" module Bundler class Fetcher class Index < Base def specs(_gem_names) Bundler.rubygems.fetch_all_remote_specs(remote, gem_remote_fetcher) rescue Gem::RemoteFetcher::FetchError => e case e.message when /certificate verify failed/ raise CertificateFailureError.new(display_uri) when /401/ raise BadAuthenticationError, remote_uri if remote_uri.userinfo raise AuthenticationRequiredError, remote_uri when /403/ raise AuthenticationForbiddenError, remote_uri else raise HTTPError, "Could not fetch specs from #{display_uri} due to underlying error <#{e.message}>" end end end end end # frozen_string_literal: true module Bundler class Fetcher class Downloader attr_reader :connection attr_reader :redirect_limit def initialize(connection, redirect_limit) @connection = connection @redirect_limit = redirect_limit end def fetch(uri, headers = {}, counter = 0) raise HTTPError, "Too many redirects" if counter >= redirect_limit filtered_uri = URICredentialsFilter.credential_filtered_uri(uri) response = request(uri, headers) Bundler.ui.debug("HTTP #{response.code} #{response.message} #{filtered_uri}") case response when Gem::Net::HTTPSuccess, Gem::Net::HTTPNotModified response when Gem::Net::HTTPRedirection new_uri = Gem::URI.parse(response["location"]) if new_uri.host == uri.host new_uri.user = uri.user new_uri.password = uri.password end fetch(new_uri, headers, counter + 1) when Gem::Net::HTTPRequestedRangeNotSatisfiable new_headers = headers.dup new_headers.delete("Range") new_headers["Accept-Encoding"] = "gzip" fetch(uri, new_headers) when Gem::Net::HTTPRequestEntityTooLarge raise FallbackError, response.body when Gem::Net::HTTPTooManyRequests raise TooManyRequestsError, response.body when Gem::Net::HTTPUnauthorized raise BadAuthenticationError, uri.host if uri.userinfo raise AuthenticationRequiredError, uri.host when Gem::Net::HTTPForbidden raise AuthenticationForbiddenError, uri.host when Gem::Net::HTTPNotFound raise FallbackError, "Gem::Net::HTTPNotFound: #{filtered_uri}" else message = "Gem::#{response.class.name.gsub(/\AGem::/, "")}" message += ": #{response.body}" unless response.body.empty? raise HTTPError, message end end def request(uri, headers) validate_uri_scheme!(uri) filtered_uri = URICredentialsFilter.credential_filtered_uri(uri) Bundler.ui.debug "HTTP GET #{filtered_uri}" req = Gem::Net::HTTP::Get.new uri.request_uri, headers if uri.user user = CGI.unescape(uri.user) password = uri.password ? CGI.unescape(uri.password) : nil req.basic_auth(user, password) end connection.request(uri, req) rescue OpenSSL::SSL::SSLError raise CertificateFailureError.new(uri) rescue *HTTP_ERRORS => e Bundler.ui.trace e if e.is_a?(SocketError) || e.message.to_s.include?("host down:") raise NetworkDownError, "Could not reach host #{uri.host}. Check your network " \ "connection and try again." else raise HTTPError, "Network error while fetching #{filtered_uri}" \ " (#{e})" end end private def validate_uri_scheme!(uri) return if /\Ahttps?\z/.match?(uri.scheme) raise InvalidOption, "The request uri `#{uri}` has an invalid scheme (`#{uri.scheme}`). " \ "Did you mean `http` or `https`?" end end end end # frozen_string_literal: true require_relative "base" require_relative "../worker" module Bundler class Fetcher class CompactIndex < Base def self.compact_index_request(method_name) method = instance_method(method_name) undef_method(method_name) define_method(method_name) do |*args, &blk| method.bind(self).call(*args, &blk) rescue NetworkDownError, CompactIndexClient::Updater::MismatchedChecksumError => e raise HTTPError, e.message rescue AuthenticationRequiredError, BadAuthenticationError # Fail since we got a 401 from the server. raise rescue HTTPError => e Bundler.ui.trace(e) nil end end def specs(gem_names) specs_for_names(gem_names) end compact_index_request :specs def specs_for_names(gem_names) gem_info = [] complete_gems = [] remaining_gems = gem_names.dup until remaining_gems.empty? log_specs { "Looking up gems #{remaining_gems.inspect}" } deps = fetch_gem_infos(remaining_gems).flatten(1) next_gems = deps.flat_map {|d| d[CompactIndexClient::INFO_DEPS].flat_map(&:first) }.uniq deps.each {|dep| gem_info << dep } complete_gems.concat(deps.map(&:first)).uniq! remaining_gems = next_gems - complete_gems end @bundle_worker&.stop @bundle_worker = nil # reset it. Not sure if necessary gem_info end def available? unless SharedHelpers.md5_available? Bundler.ui.debug("FIPS mode is enabled, bundler can't use the CompactIndex API") return nil end # Read info file checksums out of /versions, so we can know if gems are up to date compact_index_client.available? rescue CompactIndexClient::Updater::MismatchedChecksumError => e Bundler.ui.debug(e.message) nil end compact_index_request :available? def api_fetcher? true end private def compact_index_client @compact_index_client ||= SharedHelpers.filesystem_access(cache_path) do CompactIndexClient.new(cache_path, client_fetcher) end end def fetch_gem_infos(names) in_parallel(names) {|name| compact_index_client.info(name) } rescue TooManyRequestsError # rubygems.org is rate limiting us, slow down. @bundle_worker&.stop @bundle_worker = nil # reset it. Not sure if necessary compact_index_client.reset! names.map {|name| compact_index_client.info(name) } end def in_parallel(inputs, &blk) func = lambda {|object, _index| blk.call(object) } worker = bundle_worker(func) inputs.each {|input| worker.enq(input) } inputs.map { worker.deq } end def bundle_worker(func = nil) @bundle_worker ||= begin worker_name = "Compact Index (#{display_uri.host})" Bundler::Worker.new(Bundler.settings.processor_count, worker_name, func) end @bundle_worker.tap do |worker| worker.instance_variable_set(:@func, func) if func end end def cache_path Bundler.user_cache.join("compact_index", remote.cache_slug) end def client_fetcher ClientFetcher.new(self, Bundler.ui) end ClientFetcher = Struct.new(:fetcher, :ui) do def call(path, headers) fetcher.downloader.fetch(fetcher.fetch_uri + path, headers) rescue NetworkDownError => e raise unless Bundler.feature_flag.allow_offline_install? && headers["If-None-Match"] ui.warn "Using the cached data for the new index because of a network error: #{e}" Gem::Net::HTTPNotModified.new(nil, nil, nil) end end end end end # frozen_string_literal: true require_relative "base" require "cgi" module Bundler class Fetcher class Dependency < Base def available? @available ||= fetch_uri.scheme != "file" && downloader.fetch(dependency_api_uri) rescue NetworkDownError => e raise HTTPError, e.message rescue AuthenticationRequiredError # Fail since we got a 401 from the server. raise rescue HTTPError false end def api_fetcher? true end def specs(gem_names, full_dependency_list = [], last_spec_list = []) query_list = gem_names.uniq - full_dependency_list log_specs { "Query List: #{query_list.inspect}" } return last_spec_list if query_list.empty? spec_list, deps_list = Bundler::Retry.new("dependency api", FAIL_ERRORS).attempts do dependency_specs(query_list) end returned_gems = spec_list.map(&:first).uniq specs(deps_list, full_dependency_list + returned_gems, spec_list + last_spec_list) rescue MarshalError, HTTPError, GemspecError Bundler.ui.info "" unless Bundler.ui.debug? # new line now that the dots are over Bundler.ui.debug "could not fetch from the dependency API, trying the full index" nil end def dependency_specs(gem_names) Bundler.ui.debug "Query Gemcutter Dependency Endpoint API: #{gem_names.join(",")}" gem_list = unmarshalled_dep_gems(gem_names) get_formatted_specs_and_deps(gem_list) end def unmarshalled_dep_gems(gem_names) gem_list = [] gem_names.each_slice(Source::Rubygems::API_REQUEST_SIZE) do |names| marshalled_deps = downloader.fetch(dependency_api_uri(names)).body gem_list.concat(Bundler.safe_load_marshal(marshalled_deps)) end gem_list end def get_formatted_specs_and_deps(gem_list) deps_list = [] spec_list = [] gem_list.each do |s| deps_list.concat(s[:dependencies].map(&:first)) deps = s[:dependencies].map {|n, d| [n, d.split(", ")] } spec_list.push([s[:name], s[:number], s[:platform], deps]) end [spec_list, deps_list] end def dependency_api_uri(gem_names = []) uri = fetch_uri + "api/v1/dependencies" uri.query = "gems=#{CGI.escape(gem_names.sort.join(","))}" if gem_names.any? uri end end end end # frozen_string_literal: true module Bundler class Fetcher class Base attr_reader :downloader attr_reader :display_uri attr_reader :remote attr_reader :gem_remote_fetcher def initialize(downloader, remote, display_uri, gem_remote_fetcher) raise "Abstract class" if self.class == Base @downloader = downloader @remote = remote @display_uri = display_uri @gem_remote_fetcher = gem_remote_fetcher end def remote_uri @remote.uri end def fetch_uri @fetch_uri ||= if remote_uri.host == "rubygems.org" uri = remote_uri.dup uri.host = "index.rubygems.org" uri else remote_uri end end def available? true end def api_fetcher? false end private def log_specs(&block) if Bundler.ui.debug? Bundler.ui.debug yield else Bundler.ui.info ".", false end end end end end # frozen_string_literal: true require "rubygems/remote_fetcher" module Bundler class Fetcher class GemRemoteFetcher < Gem::RemoteFetcher def request(*args) super do |req| req.delete("User-Agent") if headers["User-Agent"] yield req if block_given? end end end end end # frozen_string_literal: true require_relative "version" require_relative "rubygems_integration" require_relative "current_ruby" autoload :Pathname, "pathname" module Bundler autoload :WINDOWS, File.expand_path("constants", __dir__) autoload :FREEBSD, File.expand_path("constants", __dir__) autoload :NULL, File.expand_path("constants", __dir__) module SharedHelpers def root gemfile = find_gemfile raise GemfileNotFound, "Could not locate Gemfile" unless gemfile Pathname.new(gemfile).expand_path.parent end def default_gemfile gemfile = find_gemfile raise GemfileNotFound, "Could not locate Gemfile" unless gemfile Pathname.new(gemfile).expand_path end def default_lockfile gemfile = default_gemfile case gemfile.basename.to_s when "gems.rb" then Pathname.new(gemfile.sub(/.rb$/, ".locked")) else Pathname.new("#{gemfile}.lock") end end def default_bundle_dir bundle_dir = find_directory(".bundle") return nil unless bundle_dir bundle_dir = Pathname.new(bundle_dir) global_bundle_dir = Bundler.user_home.join(".bundle") return nil if bundle_dir == global_bundle_dir bundle_dir end def in_bundle? find_gemfile end def chdir(dir, &blk) Bundler.rubygems.ext_lock.synchronize do Dir.chdir dir, &blk end end def pwd Bundler.rubygems.ext_lock.synchronize do Pathname.pwd end end def with_clean_git_env(&block) keys = %w[GIT_DIR GIT_WORK_TREE] old_env = keys.inject({}) do |h, k| h.update(k => ENV[k]) end keys.each {|key| ENV.delete(key) } block.call ensure keys.each {|key| ENV[key] = old_env[key] } end def set_bundle_environment set_bundle_variables set_path set_rubyopt set_rubylib end # Rescues permissions errors raised by file system operations # (ie. Errno:EACCESS, Errno::EAGAIN) and raises more friendly errors instead. # # @param path [String] the path that the action will be attempted to # @param action [Symbol, #to_s] the type of operation that will be # performed. For example: :write, :read, :exec # # @yield path # # @raise [Bundler::PermissionError] if Errno:EACCES is raised in the # given block # @raise [Bundler::TemporaryResourceError] if Errno:EAGAIN is raised in the # given block # # @example # filesystem_access("vendor/cache", :write) do # FileUtils.mkdir_p("vendor/cache") # end # # @see {Bundler::PermissionError} def filesystem_access(path, action = :write, &block) yield(path.dup) rescue Errno::EACCES raise PermissionError.new(path, action) rescue Errno::EAGAIN raise TemporaryResourceError.new(path, action) rescue Errno::EPROTO raise VirtualProtocolError.new rescue Errno::ENOSPC raise NoSpaceOnDeviceError.new(path, action) rescue Errno::ENOTSUP raise OperationNotSupportedError.new(path, action) rescue Errno::EEXIST, Errno::ENOENT raise rescue SystemCallError => e raise GenericSystemCallError.new(e, "There was an error accessing `#{path}`.") end def major_deprecation(major_version, message, removed_message: nil, print_caller_location: false) if print_caller_location caller_location = caller_locations(2, 2).first suffix = " (called at #{caller_location.path}:#{caller_location.lineno})" message += suffix removed_message += suffix if removed_message end bundler_major_version = Bundler.bundler_major_version if bundler_major_version > major_version require_relative "errors" raise DeprecatedError, "[REMOVED] #{removed_message || message}" end return unless bundler_major_version >= major_version && prints_major_deprecations? Bundler.ui.warn("[DEPRECATED] #{message}") end def print_major_deprecations! multiple_gemfiles = search_up(".") do |dir| gemfiles = gemfile_names.select {|gf| File.file? File.expand_path(gf, dir) } next if gemfiles.empty? break gemfiles.size != 1 end return unless multiple_gemfiles message = "Multiple gemfiles (gems.rb and Gemfile) detected. " \ "Make sure you remove Gemfile and Gemfile.lock since bundler is ignoring them in favor of gems.rb and gems.locked." Bundler.ui.warn message end def ensure_same_dependencies(spec, old_deps, new_deps) new_deps = new_deps.reject {|d| d.type == :development } old_deps = old_deps.reject {|d| d.type == :development } without_type = proc {|d| Gem::Dependency.new(d.name, d.requirements_list.sort) } new_deps.map!(&without_type) old_deps.map!(&without_type) extra_deps = new_deps - old_deps return if extra_deps.empty? Bundler.ui.debug "#{spec.full_name} from #{spec.remote} has either corrupted API or lockfile dependencies" \ " (was expecting #{old_deps.map(&:to_s)}, but the real spec has #{new_deps.map(&:to_s)})" raise APIResponseMismatchError, "Downloading #{spec.full_name} revealed dependencies not in the API or the lockfile (#{extra_deps.join(", ")})." \ "\nRunning `bundle update #{spec.name}` should fix the problem." end def pretty_dependency(dep) msg = String.new(dep.name) msg << " (#{dep.requirement})" unless dep.requirement == Gem::Requirement.default if dep.is_a?(Bundler::Dependency) platform_string = dep.platforms.join(", ") msg << " " << platform_string if !platform_string.empty? && platform_string != Gem::Platform::RUBY end msg end def md5_available? return @md5_available if defined?(@md5_available) @md5_available = begin require "openssl" ::OpenSSL::Digest.digest("MD5", "") true rescue LoadError true rescue ::OpenSSL::Digest::DigestError false end end def digest(name) require "digest" Digest(name) end def checksum_for_file(path, digest) return unless path.file? # This must use File.read instead of Digest.file().hexdigest # because we need to preserve \n line endings on windows when calculating # the checksum SharedHelpers.filesystem_access(path, :read) do File.open(path, "rb") do |f| digest = SharedHelpers.digest(digest).new buf = String.new(capacity: 16_384, encoding: Encoding::BINARY) digest << buf while f.read(16_384, buf) digest.hexdigest end end end def write_to_gemfile(gemfile_path, contents) filesystem_access(gemfile_path) {|g| File.open(g, "w") {|file| file.puts contents } } end def relative_gemfile_path relative_path_to(Bundler.default_gemfile) end def relative_lockfile_path relative_path_to(Bundler.default_lockfile) end def relative_path_to(destination, from: pwd) Pathname.new(destination).relative_path_from(from).to_s rescue ArgumentError # on Windows, if source and destination are on different drivers, there's no relative path from one to the other destination end private def validate_bundle_path path_separator = Bundler.rubygems.path_separator return unless Bundler.bundle_path.to_s.split(path_separator).size > 1 message = "Your bundle path contains text matching #{path_separator.inspect}, " \ "which is the path separator for your system. Bundler cannot " \ "function correctly when the Bundle path contains the " \ "system's PATH separator. Please change your " \ "bundle path to not match #{path_separator.inspect}." \ "\nYour current bundle path is '#{Bundler.bundle_path}'." raise Bundler::PathError, message end def find_gemfile given = ENV["BUNDLE_GEMFILE"] return given if given && !given.empty? find_file(*gemfile_names) end def gemfile_names ["gems.rb", "Gemfile"] end def find_file(*names) search_up(*names) do |filename| return filename if File.file?(filename) end end def find_directory(*names) search_up(*names) do |dirname| return dirname if File.directory?(dirname) end end def search_up(*names) previous = nil current = File.expand_path(SharedHelpers.pwd) until !File.directory?(current) || current == previous if ENV["BUNDLER_SPEC_RUN"] # avoid stepping above the tmp directory when testing gemspec = if ENV["GEM_COMMAND"] # for Ruby Core "lib/bundler/bundler.gemspec" else "bundler.gemspec" end # avoid stepping above the tmp directory when testing return nil if File.file?(File.join(current, gemspec)) end names.each do |name| filename = File.join(current, name) yield filename end previous = current current = File.expand_path("..", current) end end def set_env(key, value) raise ArgumentError, "new key #{key}" unless EnvironmentPreserver::BUNDLER_KEYS.include?(key) orig_key = "#{EnvironmentPreserver::BUNDLER_PREFIX}#{key}" orig = ENV[key] orig ||= EnvironmentPreserver::INTENTIONALLY_NIL ENV[orig_key] ||= orig ENV[key] = value end public :set_env def set_bundle_variables Bundler::SharedHelpers.set_env "BUNDLE_BIN_PATH", bundle_bin_path Bundler::SharedHelpers.set_env "BUNDLE_GEMFILE", find_gemfile.to_s Bundler::SharedHelpers.set_env "BUNDLER_VERSION", Bundler::VERSION Bundler::SharedHelpers.set_env "BUNDLER_SETUP", File.expand_path("setup", __dir__) end def bundle_bin_path # bundler exe & lib folders have same root folder, typical gem installation exe_file = File.expand_path("../../exe/bundle", __dir__) # for Ruby core repository testing exe_file = File.expand_path("../../libexec/bundle", __dir__) unless File.exist?(exe_file) # bundler is a default gem, exe path is separate exe_file = Bundler.rubygems.bin_path("bundler", "bundle", VERSION) unless File.exist?(exe_file) exe_file end public :bundle_bin_path def set_path validate_bundle_path paths = (ENV["PATH"] || "").split(File::PATH_SEPARATOR) paths.unshift "#{Bundler.bundle_path}/bin" Bundler::SharedHelpers.set_env "PATH", paths.uniq.join(File::PATH_SEPARATOR) end def set_rubyopt rubyopt = [ENV["RUBYOPT"]].compact setup_require = "-r#{File.expand_path("setup", __dir__)}" return if !rubyopt.empty? && rubyopt.first.include?(setup_require) rubyopt.unshift setup_require Bundler::SharedHelpers.set_env "RUBYOPT", rubyopt.join(" ") end def set_rubylib rubylib = (ENV["RUBYLIB"] || "").split(File::PATH_SEPARATOR) rubylib.unshift bundler_ruby_lib unless RbConfig::CONFIG["rubylibdir"] == bundler_ruby_lib Bundler::SharedHelpers.set_env "RUBYLIB", rubylib.uniq.join(File::PATH_SEPARATOR) end def bundler_ruby_lib File.expand_path("..", __dir__) end def clean_load_path loaded_gem_paths = Bundler.rubygems.loaded_gem_paths $LOAD_PATH.reject! do |p| resolved_path = resolve_path(p) next if $LOADED_FEATURES.any? {|lf| lf.start_with?(resolved_path) } loaded_gem_paths.delete(p) end $LOAD_PATH.uniq! end def resolve_path(path) expanded = File.expand_path(path) return expanded unless File.exist?(expanded) File.realpath(expanded) end def prints_major_deprecations? require_relative "../bundler" return false if Bundler.settings[:silence_deprecations] require_relative "deprecate" return false if Bundler::Deprecate.skip true end extend self end end # frozen_string_literal: true module Bundler; end require_relative "vendor/pub_grub/lib/pub_grub" # frozen_string_literal: true module Bundler module URICredentialsFilter module_function def credential_filtered_uri(uri_to_anonymize) return uri_to_anonymize if uri_to_anonymize.nil? uri = uri_to_anonymize.dup if uri.is_a?(String) return uri if File.exist?(uri) require_relative "vendored_uri" uri = Gem::URI(uri) end if uri.userinfo # oauth authentication if uri.password == "x-oauth-basic" || uri.password == "x" # URI as string does not display with password if no user is set oauth_designation = uri.password uri.user = oauth_designation end uri.password = nil end return uri.to_s if uri_to_anonymize.is_a?(String) uri rescue Gem::URI::InvalidURIError # uri is not canonical uri scheme uri end def credential_filtered_string(str_to_filter, uri) return str_to_filter if uri.nil? || str_to_filter.nil? str_with_no_credentials = str_to_filter.dup anonymous_uri_str = credential_filtered_uri(uri).to_s uri_str = uri.to_s if anonymous_uri_str != uri_str str_with_no_credentials = str_with_no_credentials.gsub(uri_str, anonymous_uri_str) end str_with_no_credentials end end end # frozen_string_literal: true module Bundler module FetchMetadata # A fallback is included because the original version of the specification # API didn't include that field, so some marshalled specs in the index have it # set to +nil+. def matches_current_ruby? @required_ruby_version ||= _remote_specification.required_ruby_version || Gem::Requirement.default super end def matches_current_rubygems? # A fallback is included because the original version of the specification # API didn't include that field, so some marshalled specs in the index have it # set to +nil+. @required_rubygems_version ||= _remote_specification.required_rubygems_version || Gem::Requirement.default super end end module MatchRemoteMetadata include MatchMetadata prepend FetchMetadata end end # frozen_string_literal: true require_relative "vendored_persistent" require_relative "vendored_timeout" require "cgi" require_relative "vendored_securerandom" require "zlib" module Bundler # Handles all the fetching with the rubygems server class Fetcher autoload :Base, File.expand_path("fetcher/base", __dir__) autoload :CompactIndex, File.expand_path("fetcher/compact_index", __dir__) autoload :Downloader, File.expand_path("fetcher/downloader", __dir__) autoload :Dependency, File.expand_path("fetcher/dependency", __dir__) autoload :Index, File.expand_path("fetcher/index", __dir__) # This error is raised when it looks like the network is down class NetworkDownError < HTTPError; end # This error is raised if we should rate limit our requests to the API class TooManyRequestsError < HTTPError; end # This error is raised if the API returns a 413 (only printed in verbose) class FallbackError < HTTPError; end # This is the error raised if OpenSSL fails the cert verification class CertificateFailureError < HTTPError def initialize(remote_uri) remote_uri = filter_uri(remote_uri) super "Could not verify the SSL certificate for #{remote_uri}.\nThere" \ " is a chance you are experiencing a man-in-the-middle attack, but" \ " most likely your system doesn't have the CA certificates needed" \ " for verification. For information about OpenSSL certificates, see" \ " https://railsapps.github.io/openssl-certificate-verify-failed.html." end end # This is the error raised when a source is HTTPS and OpenSSL didn't load class SSLError < HTTPError def initialize(msg = nil) super msg || "Could not load OpenSSL.\n" \ "You must recompile Ruby with OpenSSL support." end end # This error is raised if HTTP authentication is required, but not provided. class AuthenticationRequiredError < HTTPError def initialize(remote_uri) remote_uri = filter_uri(remote_uri) super "Authentication is required for #{remote_uri}.\n" \ "Please supply credentials for this source. You can do this by running:\n" \ "`bundle config set --global #{remote_uri} username:password`\n" \ "or by storing the credentials in the `#{Settings.key_for(remote_uri)}` environment variable" end end # This error is raised if HTTP authentication is provided, but incorrect. class BadAuthenticationError < HTTPError def initialize(remote_uri) remote_uri = filter_uri(remote_uri) super "Bad username or password for #{remote_uri}.\n" \ "Please double-check your credentials and correct them." end end # This error is raised if HTTP authentication is correct, but lacks # necessary permissions. class AuthenticationForbiddenError < HTTPError def initialize(remote_uri) remote_uri = filter_uri(remote_uri) super "Access token could not be authenticated for #{remote_uri}.\n" \ "Make sure it's valid and has the necessary scopes configured." end end # Exceptions classes that should bypass retry attempts. If your password didn't work the # first time, it's not going to the third time. NET_ERRORS = [:HTTPBadGateway, :HTTPBadRequest, :HTTPFailedDependency, :HTTPForbidden, :HTTPInsufficientStorage, :HTTPMethodNotAllowed, :HTTPMovedPermanently, :HTTPNoContent, :HTTPNotFound, :HTTPNotImplemented, :HTTPPreconditionFailed, :HTTPRequestEntityTooLarge, :HTTPRequestURITooLong, :HTTPUnauthorized, :HTTPUnprocessableEntity, :HTTPUnsupportedMediaType, :HTTPVersionNotSupported].freeze FAIL_ERRORS = begin fail_errors = [AuthenticationRequiredError, BadAuthenticationError, AuthenticationForbiddenError, FallbackError, SecurityError] fail_errors << Gem::Requirement::BadRequirementError fail_errors.concat(NET_ERRORS.map {|e| Gem::Net.const_get(e) }) end.freeze class << self attr_accessor :disable_endpoint, :api_timeout, :redirect_limit, :max_retries end self.redirect_limit = Bundler.settings[:redirect] # How many redirects to allow in one request self.api_timeout = Bundler.settings[:timeout] # How long to wait for each API call self.max_retries = Bundler.settings[:retry] # How many retries for the API call def initialize(remote) @cis = nil @remote = remote Socket.do_not_reverse_lookup = true connection # create persistent connection end def uri @remote.anonymized_uri end # fetch a gem specification def fetch_spec(spec) spec -= [nil, "ruby", ""] spec_file_name = "#{spec.join "-"}.gemspec" uri = Gem::URI.parse("#{remote_uri}#{Gem::MARSHAL_SPEC_DIR}#{spec_file_name}.rz") spec = if uri.scheme == "file" path = Gem::Util.correct_for_windows_path(uri.path) Bundler.safe_load_marshal Bundler.rubygems.inflate(Gem.read_binary(path)) elsif cached_spec_path = gemspec_cached_path(spec_file_name) Bundler.load_gemspec(cached_spec_path) else Bundler.safe_load_marshal Bundler.rubygems.inflate(downloader.fetch(uri).body) end raise MarshalError, "is #{spec.inspect}" unless spec.is_a?(Gem::Specification) spec rescue MarshalError raise HTTPError, "Gemspec #{spec} contained invalid data.\n" \ "Your network or your gem server is probably having issues right now." end # return the specs in the bundler format as an index with retries def specs_with_retry(gem_names, source) Bundler::Retry.new("fetcher", FAIL_ERRORS).attempts do specs(gem_names, source) end end # return the specs in the bundler format as an index def specs(gem_names, source) index = Bundler::Index.new fetch_specs(gem_names).each do |name, version, platform, dependencies, metadata| spec = if dependencies EndpointSpecification.new(name, version, platform, self, dependencies, metadata).tap do |es| source.checksum_store.replace(es, es.checksum) end else RemoteSpecification.new(name, version, platform, self) end spec.source = source spec.remote = @remote index << spec end index rescue CertificateFailureError Bundler.ui.info "" if gem_names && api_fetcher? # newline after dots raise end def user_agent @user_agent ||= begin ruby = Bundler::RubyVersion.system agent = String.new("bundler/#{Bundler::VERSION}") agent << " rubygems/#{Gem::VERSION}" agent << " ruby/#{ruby.versions_string(ruby.versions)}" agent << " (#{ruby.host})" agent << " command/#{ARGV.first}" if ruby.engine != "ruby" # engine_version raises on unknown engines engine_version = begin ruby.engine_versions rescue RuntimeError "???" end agent << " #{ruby.engine}/#{ruby.versions_string(engine_version)}" end agent << " options/#{Bundler.settings.all.join(",")}" agent << " ci/#{cis.join(",")}" if cis.any? # add a random ID so we can consolidate runs server-side agent << " " << Gem::SecureRandom.hex(8) # add any user agent strings set in the config extra_ua = Bundler.settings[:user_agent] agent << " " << extra_ua if extra_ua agent end end def http_proxy return unless uri = connection.proxy_uri uri.to_s end def inspect "#<#{self.class}:0x#{object_id} uri=#{uri}>" end def api_fetcher? fetchers.first.api_fetcher? end def gem_remote_fetcher @gem_remote_fetcher ||= begin require_relative "fetcher/gem_remote_fetcher" fetcher = GemRemoteFetcher.new Gem.configuration[:http_proxy] fetcher.headers["User-Agent"] = user_agent fetcher.headers["X-Gemfile-Source"] = @remote.original_uri.to_s if @remote.original_uri fetcher end end private def available_fetchers if Bundler::Fetcher.disable_endpoint [Index] elsif remote_uri.scheme == "file" Bundler.ui.debug("Using a local server, bundler won't use the CompactIndex API") [Index] else [CompactIndex, Dependency, Index] end end def fetchers @fetchers ||= available_fetchers.map {|f| f.new(downloader, @remote, uri, gem_remote_fetcher) }.drop_while {|f| !f.available? } end def fetch_specs(gem_names) fetchers.reject!(&:api_fetcher?) unless gem_names fetchers.reject! do |f| specs = f.specs(gem_names) return specs if specs true end [] end def cis @cis ||= Bundler::CIDetector.ci_strings end def connection @connection ||= begin needs_ssl = remote_uri.scheme == "https" || Bundler.settings[:ssl_verify_mode] || Bundler.settings[:ssl_client_cert] raise SSLError if needs_ssl && !defined?(OpenSSL::SSL) con = Gem::Net::HTTP::Persistent.new name: "bundler", proxy: :ENV if gem_proxy = Gem.configuration[:http_proxy] con.proxy = Gem::URI.parse(gem_proxy) if gem_proxy != :no_proxy end if remote_uri.scheme == "https" con.verify_mode = (Bundler.settings[:ssl_verify_mode] || OpenSSL::SSL::VERIFY_PEER) con.cert_store = bundler_cert_store end ssl_client_cert = Bundler.settings[:ssl_client_cert] || (Gem.configuration.ssl_client_cert if Gem.configuration.respond_to?(:ssl_client_cert)) if ssl_client_cert pem = File.read(ssl_client_cert) con.cert = OpenSSL::X509::Certificate.new(pem) con.key = OpenSSL::PKey::RSA.new(pem) end con.read_timeout = Fetcher.api_timeout con.open_timeout = Fetcher.api_timeout con.override_headers["User-Agent"] = user_agent con.override_headers["X-Gemfile-Source"] = @remote.original_uri.to_s if @remote.original_uri con end end # cached gem specification path, if one exists def gemspec_cached_path(spec_file_name) paths = Bundler.rubygems.spec_cache_dirs.map {|dir| File.join(dir, spec_file_name) } paths.find {|path| File.file? path } end HTTP_ERRORS = [ Gem::Timeout::Error, EOFError, SocketError, Errno::ENETDOWN, Errno::ENETUNREACH, Errno::EINVAL, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EAGAIN, Gem::Net::HTTPBadResponse, Gem::Net::HTTPHeaderSyntaxError, Gem::Net::ProtocolError, Gem::Net::HTTP::Persistent::Error, Zlib::BufError, Errno::EHOSTUNREACH ].freeze def bundler_cert_store store = OpenSSL::X509::Store.new ssl_ca_cert = Bundler.settings[:ssl_ca_cert] || (Gem.configuration.ssl_ca_cert if Gem.configuration.respond_to?(:ssl_ca_cert)) if ssl_ca_cert if File.directory? ssl_ca_cert store.add_path ssl_ca_cert else store.add_file ssl_ca_cert end else store.set_default_paths require "rubygems/request" Gem::Request.get_cert_files.each {|c| store.add_file c } end store end def remote_uri @remote.uri end def downloader @downloader ||= Downloader.new(connection, self.class.redirect_limit) end end end # frozen_string_literal: true module Bundler module RubyDsl def ruby(*ruby_version) options = ruby_version.pop if ruby_version.last.is_a?(Hash) ruby_version.flatten! if options patchlevel = options[:patchlevel] engine = options[:engine] engine_version = options[:engine_version] raise GemfileError, "Please define :engine_version" if engine && engine_version.nil? raise GemfileError, "Please define :engine" if engine_version && engine.nil? if options[:file] raise GemfileError, "Do not pass version argument when using :file option" unless ruby_version.empty? ruby_version << normalize_ruby_file(options[:file]) end if engine == "ruby" && engine_version && ruby_version != Array(engine_version) raise GemfileEvalError, "ruby_version must match the :engine_version for MRI" end end @ruby_version = RubyVersion.new(ruby_version, patchlevel, engine, engine_version) end # Support the various file formats found in .ruby-version files. # # 3.2.2 # ruby-3.2.2 # # Also supports .tool-versions files for asdf. Lines not starting with "ruby" are ignored. # # ruby 2.5.1 # comment is ignored # ruby 2.5.1# close comment and extra spaces doesn't confuse # # Intentionally does not support `3.2.1@gemset` since rvm recommends using .ruby-gemset instead # # Loads the file relative to the dirname of the Gemfile itself. def normalize_ruby_file(filename) file_content = Bundler.read_file(gemfile.dirname.join(filename)) # match "ruby-3.2.2" or "ruby 3.2.2" capturing version string up to the first space or comment if /^ruby(-|\s+)([^\s#]+)/.match(file_content) $2 else file_content.strip end end end end require_relative 'assignment' module Bundler::PubGrub class PartialSolution attr_reader :assignments, :decisions attr_reader :attempted_solutions def initialize reset! @attempted_solutions = 1 @backtracking = false end def decision_level @decisions.length end def relation(term) package = term.package return :overlap if !@terms.key?(package) @relation_cache[package][term] ||= @terms[package].relation(term) end def satisfies?(term) relation(term) == :subset end def derive(term, cause) add_assignment(Assignment.new(term, cause, decision_level, assignments.length)) end def satisfier(term) assignment = @assignments_by[term.package].bsearch do |assignment_by| @cumulative_assignments[assignment_by].satisfies?(term) end assignment || raise("#{term} unsatisfied") end # A list of unsatisfied terms def unsatisfied @required.keys.reject do |package| @decisions.key?(package) end.map do |package| @terms[package] end end def decide(package, version) @attempted_solutions += 1 if @backtracking @backtracking = false; decisions[package] = version assignment = Assignment.decision(package, version, decision_level, assignments.length) add_assignment(assignment) end def backtrack(previous_level) @backtracking = true new_assignments = assignments.select do |assignment| assignment.decision_level <= previous_level end new_decisions = Hash[decisions.first(previous_level)] reset! @decisions = new_decisions new_assignments.each do |assignment| add_assignment(assignment) end end private def reset! # { Array<Assignment> } @assignments = [] # { Package => Array<Assignment> } @assignments_by = Hash.new { |h,k| h[k] = [] } @cumulative_assignments = {}.compare_by_identity # { Package => Package::Version } @decisions = {} # { Package => Term } @terms = {} @relation_cache = Hash.new { |h,k| h[k] = {} } # { Package => Boolean } @required = {} end def add_assignment(assignment) term = assignment.term package = term.package @assignments << assignment @assignments_by[package] << assignment @required[package] = true if term.positive? if @terms.key?(package) old_term = @terms[package] @terms[package] = old_term.intersect(term) else @terms[package] = term end @relation_cache[package].clear @cumulative_assignments[assignment] = @terms[package] end end end module Bundler::PubGrub module RubyGems extend self def requirement_to_range(requirement) ranges = requirement.requirements.map do |(op, ver)| case op when "~>" name = "~> #{ver}" bump = ver.class.new(ver.bump.to_s + ".A") VersionRange.new(name: name, min: ver, max: bump, include_min: true) when ">" VersionRange.new(min: ver) when ">=" VersionRange.new(min: ver, include_min: true) when "<" VersionRange.new(max: ver) when "<=" VersionRange.new(max: ver, include_max: true) when "=" VersionRange.new(min: ver, max: ver, include_min: true, include_max: true) when "!=" VersionRange.new(min: ver, max: ver, include_min: true, include_max: true).invert else raise "bad version specifier: #{op}" end end ranges.inject(&:intersect) end def requirement_to_constraint(package, requirement) Bundler::PubGrub::VersionConstraint.new(package, range: requirement_to_range(requirement)) end def parse_range(dep) requirement_to_range(Gem::Requirement.new(dep)) end def parse_constraint(package, dep) range = parse_range(dep) Bundler::PubGrub::VersionConstraint.new(package, range: range) end end end
Save