├── .all_images.yml ├── .gitignore ├── .travis.yml ├── CHANGES.md ├── COPYING ├── Gemfile ├── README.md ├── Rakefile ├── VERSION ├── bin └── rtail ├── examples ├── pager.rb └── tail.rb ├── file-tail.gemspec ├── lib ├── file-tail.rb └── file │ ├── tail.rb │ └── tail │ ├── group.rb │ ├── line_extension.rb │ ├── logfile.rb │ ├── tailer.rb │ └── version.rb └── tests ├── file_tail_group_test.rb ├── file_tail_test.rb └── test_helper.rb /.all_images.yml: -------------------------------------------------------------------------------- 1 | dockerfile: |- 2 | RUN apk add --no-cache build-base git bash 3 | 4 | fail_fast: true 5 | 6 | script: &script |- 7 | echo -e "\e[1m" 8 | ruby -v 9 | echo -e "\e[0m" 10 | bundle install 11 | rake test 12 | 13 | images: 14 | ruby:3.4-alpine: *script 15 | ruby:3.3-alpine: *script 16 | ruby:3.2-alpine: *script 17 | ruby:3.1-alpine: *script 18 | ruby:3.0-alpine: *script 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.rbc 2 | .*.sw[pon] 3 | .AppleDouble 4 | .bundle 5 | .rbx 6 | .utilsrc 7 | Gemfile.lock 8 | coverage 9 | errors.lst 10 | pkg 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | rvm: 2 | - 2.1 3 | - 2.2 4 | - 2.3 5 | - 2.4 6 | - 2.5 7 | - 2.6 8 | - ruby-head 9 | - jruby-head 10 | sudo: false 11 | matrix: 12 | allow_failures: 13 | - rvm: ruby-head 14 | - rvm: jruby-head 15 | -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | # Changes 2 | 3 | ## 2024-09-13 v1.3.0 4 | 5 | ### Significant Changes 6 | 7 | * **Improved waiting for log output by counting lines** 8 | + Increased timeout from 2 seconds to 10 seconds in multiple places 9 | * **Added Ruby version check in Dockerfile** 10 | + Update `gem update --system` and installation to be conditional on Ruby version 11 | + Replace `bundle` with `bundle install` in script section 12 | * **Convert CHANGES file to CHANGES\.md** 13 | 14 | ### Bug Fixes 15 | 16 | * **Add exit handler to delete temporary file** 17 | - Added at_exit block to delete test file created in setup method. 18 | * **Refactor File class for debugging** 19 | - Remove hardcoded `$DEBUG` variable usage in reopen_file and output_debug_information methods 20 | - Introduce debug? method to check if `FILE_TAIL_DEBUG` environment variable is set to 1. 21 | 22 | ### Dependency Updates 23 | 24 | * **Update Ruby dependencies and add new development dependencies** 25 | + Added `.all_images.yml` file with Dockerfile configuration 26 | + Updated Gemfile to use Ruby **3.5.18** instead of **2.7.8** 27 | + Updated Rakefile to ignore additional files 28 | + Updated `file-tail.gemspec` to include `.all_images.yml` in the list of files 29 | + Updated `tests/file_tail_test.rb` to use absolute path for test file 30 | + Added new development dependencies: `all_images`, `simplecov`, and `debug` 31 | + Updated dependency versions: `gem_hadar` to **1.17.1**, `test-unit` to 32 | **3.0**, and `tins` to **1.0** 33 | 34 | ## 2016-04-19 v1.2.0 35 | 36 | * Make line separator configurable 37 | 38 | ## 2016-04-19 v1.1.1 39 | 40 | * Fix tests on Ruby 2.3.0 41 | 42 | ## 2014-09-26 v1.1.0 43 | 44 | * Depend on tins ~ 1.0 45 | 46 | ## 2012-05-31 v1.0.10 47 | 48 | * Use rewind to force IO#lineno to be reset. 49 | 50 | ## 2012-05-31 v1.0.9 51 | 52 | * Reopen file in :top mode at the beginning. 53 | 54 | ## 2011-12-24 v1.0.8 55 | 56 | * Support simplecov. 57 | 58 | ## 2011-07-15 v1.0.7 59 | 60 | * Use gem_hadar to shorten Rakefile. 61 | 62 | ## 2011-06-25 v1.0.6 63 | 64 | * Create a gem spec file again. 65 | * Added a File::Tail::Group to tail multiple files more easily. 66 | 67 | ## 2010-03-25 v1.0.5 68 | 69 | * Added rtail executable, a nice app to supervise logfiles and logdirs. 70 | * Disabled creation of gem spec file. 71 | * Cleaned up documentation a bit. 72 | 73 | ## 2009-08-21 v1.0.4 74 | 75 | * Fixed the threaded tests for Ruby 1.9. 76 | * Create a gem spec file. 77 | * Some cleanup. 78 | 79 | ## 2008-04-07 v1.0.3 80 | 81 | * Danny Colligan reported a memory leak in long 82 | running scripts using file-tail. I changed file-ta il to only use block.call, 83 | which seems to improve the memory behaviour. I am still not sure, where the 84 | problem actually stems f rom, though. 85 | 86 | ## 2007-04-19 v1.0.2 87 | 88 | * make_doc.rb was missing from the source archive. Thanks to Rick Ohnemus 89 | for reporting it. 90 | 91 | ## 2007-04-19 v1.0.1 92 | 93 | * Bugfix: File::Tail::Logfile#open with block, now closes the file like 94 | File#open does. Found by Alex Doan , 95 | ruby-talk:248383. 96 | 97 | ## 2007-03-30 v1.0.0 98 | 99 | * Bugfix: David.Barzilay@swisscom.com reported, that file tails may skip some 100 | log file lines, after rotating it. I think, that I fixed that problem. 101 | * Added a after_reopen callback as well, that is called after reopening of the 102 | tailed file has occured. 103 | * Removed rewind/wind methods even earlier than planned: I placed the 104 | deprecation warning for rewind method in File instead of File::Tail, which 105 | caused rewind to stop working completely after loading file/tail. Duh! I 106 | blame vim's matchit, because it jump ed to the wrong end keyword. 107 | 108 | ## 2007-02-08 v0.1.4 109 | 110 | * Renamed rewind method to backward, and wind method to forward, because 111 | someone already had the good idea to name a method IO# rewind, which was 112 | overwritten by the mixed in File::Tail methods. The old methods are now 113 | deprecated and will be removed in a n ew 0.2.x version of the library. 114 | * Added a bit more of documentation. 115 | 116 | ## 2005-08-20 v0.1.3 117 | 118 | * Applied LOAD_PATH patch by Daniel Berger, binary mode changes were already in 119 | the CVS. Seemed to be like cheating to me, thou gh. ;) 120 | * Skipping one windows test for the moment, too. Sigh! 121 | 122 | ## 2004-09-30 v0.1.2 123 | 124 | * First Rubyforge release 125 | * Added Rakefile 126 | * Supports gem build now. 127 | 128 | ## 2004-09-01 v0.1.1 129 | 130 | * Josh Endries found a bug that caused File::Tail to 131 | malfunction on FreeBSD. Hotfix: Use a side effect of se ek to clearerr the 132 | tailed file handle after EOFError has been raised. 133 | 134 | ## 2004-04-13 v0.1.0 135 | 136 | * API documentation with rdoc. 137 | * return_if_eof attribute added. 138 | * Added array return mode for finite tail call without block given. 139 | * install.rb now uses ruby version site_dir. 140 | * Some code and directory structure cleanup. 141 | 142 | ## 2002-08-02 v0.0.2 143 | 144 | * Heavy refactoring, more and smaller methods and expception handling 145 | * Added check for inode and device equality of files as suggested by James 146 | F.Hranicky and Curt Sampson to cover 147 | remove rotation 148 | * If filesize shrinks suddenly, File::Tail assumes that copy and truncate 149 | rotation has happend: The file is reopened and every new line is handled. 150 | * NFS-Fix: Errno::ESTALE is caught. 151 | * wind added to skip the first n lines, as James F.Hranicky's suggested and 152 | changed name of last-method to rewind, because I li ked his method names 153 | better than mine ;) 154 | * Renamed next to tail either. 155 | * The API has changed - but I think very few people care at the moment. 156 | * Lots of tests added. 157 | 158 | ## 2002-07-30 v0.0.1 159 | 160 | * Initial Release 161 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [2017] [Florian Frank] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # vim: set filetype=ruby et sw=2 ts=2: 2 | 3 | source 'https://rubygems.org' 4 | 5 | gemspec 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # File::Tail for Ruby 2 | 3 | ## Description 4 | 5 | This is a small ruby library that allows it to "tail" files in Ruby, including 6 | following a file, that still is growing like the unix command 'tail -f' can. 7 | 8 | ## Download 9 | 10 | The latest version of *File::Tail* (file-tail) can be found at 11 | 12 | 13 | http://flori.github.com/file-tail 14 | 15 | ## Installation 16 | 17 | To install file-tail via its gem type: 18 | 19 | # gem install file-tail 20 | 21 | ## Usage 22 | 23 | File::Tail is a module in the File class. A lightweight class interface for 24 | logfiles can be seen under File::Tail::Logfile. 25 | 26 | Direct extension of File objects with File::Tail works like that: 27 | 28 | File.open(filename) do |log| 29 | log.extend(File::Tail) 30 | log.interval # 10 31 | log.backward(10) 32 | log.tail { |line| puts line } 33 | end 34 | 35 | It's also possible to mix File::Tail in your own File classes 36 | (see also File::Tail::Logfile): 37 | 38 | class MyFile < File 39 | include File::Tail 40 | end 41 | log # MyFile.new("myfile") 42 | log.interval # 10 43 | log.backward(10) 44 | log.tail { |line| print line } 45 | 46 | The forward/backward method returns self, so it's possible to chain 47 | methods together like that: 48 | 49 | log.backward(10).tail { |line| puts line } 50 | 51 | A command line utility named rtail, that uses File::Tail is provided as well. 52 | 53 | ## Documentation 54 | 55 | To create the documentation of this module, type 56 | 57 | ``` 58 | $ rake doc 59 | ``` 60 | 61 | and the API documentation is generated. 62 | 63 | In the examples directory is a small example of tail and 64 | pager program that use this module. You also may want look 65 | at the end of examples/tail.rb for a little example. 66 | 67 | ## Author 68 | 69 | Florian Frank mailto:flori@ping.de 70 | 71 | ## License 72 | 73 | Apache License, Version 2.0 – See the COPYING file in the source archive. 74 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # vim: set filetype=ruby et sw=2 ts=2: 2 | 3 | require 'gem_hadar' 4 | 5 | GemHadar do 6 | name 'file-tail' 7 | path_name 'file/tail' 8 | author 'Florian Frank' 9 | email 'flori@ping.de' 10 | homepage "http://github.com/flori/#{name}" 11 | summary "#{path_name.camelize} for Ruby" 12 | description 'Library to tail files in Ruby' 13 | test_dir 'tests' 14 | ignore '.*.sw[pon]', 'pkg', 'Gemfile.lock', 'coverage', '*.rbc', '.rbx', 15 | '.AppleDouble', '.bundle', 'errors.lst', '.utilsrc' 16 | readme 'README.md' 17 | licenses << 'Apache-2.0' 18 | 19 | dependency 'tins', '~>1.0' 20 | 21 | development_dependency 'test-unit', '~>3.0' 22 | development_dependency 'all_images' 23 | development_dependency 'simplecov' 24 | development_dependency 'debug' 25 | end 26 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 1.3.0 2 | -------------------------------------------------------------------------------- /bin/rtail: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'file/tail' 4 | require 'tins/go' 5 | include Tins::GO 6 | require 'thread' 7 | Thread.abort_on_exception = true 8 | 9 | $opt = go 'n:m:Mh' 10 | if $opt['h'] 11 | puts < true) do |log| 10 | begin 11 | log.tail(height) { |line| puts line } 12 | print "Press return key to continue!" ; gets 13 | print " " 14 | redo 15 | rescue File::Tail::BreakException 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /examples/tail.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'file/tail' 4 | 5 | filename = ARGV.pop or fail "Usage: #$0 number filename" 6 | number = (ARGV.pop || 0).to_i.abs 7 | 8 | File::Tail::Logfile.open(filename) do |log| 9 | log.backward(number).tail { |line| puts line } 10 | end 11 | -------------------------------------------------------------------------------- /file-tail.gemspec: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | # stub: file-tail 1.3.0 ruby lib 3 | 4 | Gem::Specification.new do |s| 5 | s.name = "file-tail".freeze 6 | s.version = "1.3.0".freeze 7 | 8 | s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= 9 | s.require_paths = ["lib".freeze] 10 | s.authors = ["Florian Frank".freeze] 11 | s.date = "2024-09-13" 12 | s.description = "Library to tail files in Ruby".freeze 13 | s.email = "flori@ping.de".freeze 14 | s.extra_rdoc_files = ["README.md".freeze, "lib/file-tail.rb".freeze, "lib/file/tail.rb".freeze, "lib/file/tail/group.rb".freeze, "lib/file/tail/line_extension.rb".freeze, "lib/file/tail/logfile.rb".freeze, "lib/file/tail/tailer.rb".freeze, "lib/file/tail/version.rb".freeze] 15 | s.files = [".all_images.yml".freeze, ".gitignore".freeze, ".travis.yml".freeze, "CHANGES.md".freeze, "COPYING".freeze, "Gemfile".freeze, "README.md".freeze, "Rakefile".freeze, "VERSION".freeze, "bin/rtail".freeze, "examples/pager.rb".freeze, "examples/tail.rb".freeze, "file-tail.gemspec".freeze, "lib/file-tail.rb".freeze, "lib/file/tail.rb".freeze, "lib/file/tail/group.rb".freeze, "lib/file/tail/line_extension.rb".freeze, "lib/file/tail/logfile.rb".freeze, "lib/file/tail/tailer.rb".freeze, "lib/file/tail/version.rb".freeze, "tests/file_tail_group_test.rb".freeze, "tests/file_tail_test.rb".freeze, "tests/test_helper.rb".freeze] 16 | s.homepage = "http://github.com/flori/file-tail".freeze 17 | s.licenses = ["Apache-2.0".freeze] 18 | s.rdoc_options = ["--title".freeze, "File-tail - File::Tail for Ruby".freeze, "--main".freeze, "README.md".freeze] 19 | s.rubygems_version = "3.5.18".freeze 20 | s.summary = "File::Tail for Ruby".freeze 21 | s.test_files = ["tests/file_tail_group_test.rb".freeze, "tests/file_tail_test.rb".freeze, "tests/test_helper.rb".freeze] 22 | 23 | s.specification_version = 4 24 | 25 | s.add_development_dependency(%q.freeze, ["~> 1.17.1".freeze]) 26 | s.add_development_dependency(%q.freeze, ["~> 3.0".freeze]) 27 | s.add_development_dependency(%q.freeze, [">= 0".freeze]) 28 | s.add_development_dependency(%q.freeze, [">= 0".freeze]) 29 | s.add_development_dependency(%q.freeze, [">= 0".freeze]) 30 | s.add_runtime_dependency(%q.freeze, ["~> 1.0".freeze]) 31 | end 32 | -------------------------------------------------------------------------------- /lib/file-tail.rb: -------------------------------------------------------------------------------- 1 | require 'file/tail' 2 | -------------------------------------------------------------------------------- /lib/file/tail.rb: -------------------------------------------------------------------------------- 1 | class File 2 | # This module can be included in your own File subclasses or used to extend 3 | # files you want to tail. 4 | module Tail 5 | require 'file/tail/version' 6 | require 'file/tail/logfile' 7 | require 'file/tail/group' 8 | require 'file/tail/tailer' 9 | require 'file/tail/line_extension' 10 | 11 | # This is the base class of all exceptions that are raised 12 | # in File::Tail. 13 | class TailException < Exception; end 14 | 15 | # The DeletedException is raised if a file is 16 | # deleted while tailing it. 17 | class DeletedException < TailException; end 18 | 19 | # The ReturnException is raised and caught 20 | # internally to implement "tail -10" behavior. 21 | class ReturnException < TailException; end 22 | 23 | # The BreakException is raised if the break_if_eof 24 | # attribute is set to a true value and the end of tailed file 25 | # is reached. 26 | class BreakException < TailException; end 27 | 28 | # The ReopenException is raised internally if File::Tail 29 | # gets suspicious something unusual has happened to 30 | # the tailed file, e. g., it was rotated away. The exception 31 | # is caught and an attempt to reopen it is made. 32 | class ReopenException < TailException 33 | attr_reader :mode 34 | 35 | # Creates an ReopenException object. The mode defaults to 36 | # :bottom which indicates that the file 37 | # should be tailed beginning from the end. :top 38 | # indicates, that it should be tailed from the beginning from the 39 | # start. 40 | def initialize(mode = :bottom) 41 | super(self.class.name) 42 | @mode = mode 43 | end 44 | end 45 | 46 | # The maximum interval File::Tail sleeps, before it tries 47 | # to take some action like reading the next few lines 48 | # or reopening the file. 49 | attr_accessor :max_interval 50 | 51 | # The start value of the sleep interval. This value 52 | # goes against max_interval if the tailed 53 | # file is silent for a sufficient time. 54 | attr_accessor :interval 55 | 56 | # If this attribute is set to a true value, File::Tail persists 57 | # on reopening a deleted file waiting max_interval seconds 58 | # between the attempts. This is useful if logfiles are 59 | # moved away while rotation occurs but are recreated at 60 | # the same place after a while. It defaults to true. 61 | attr_accessor :reopen_deleted 62 | 63 | # If this attribute is set to a true value, File::Tail 64 | # attempts to reopen it's tailed file after 65 | # suspicious_interval seconds of silence. 66 | attr_accessor :reopen_suspicious 67 | 68 | # The callback is called with _self_ as an argument after a reopen has 69 | # occurred. This allows a tailing script to find out, if a logfile has 70 | # been rotated. 71 | def after_reopen(&block) 72 | @after_reopen = block 73 | end 74 | 75 | # This attribute is the interval in seconds before File::Tail 76 | # gets suspicious that something has happened to it's tailed file 77 | # and an attempt to reopen it is made. 78 | # 79 | # If the attribute reopen_suspicious is 80 | # set to a non true value, suspicious_interval is 81 | # meaningless. It defaults to 60 seconds. 82 | attr_accessor :suspicious_interval 83 | 84 | # If this attribute is set to a true value, File::Fail's tail method 85 | # raises a BreakException if the end of the file is reached. 86 | attr_accessor :break_if_eof 87 | 88 | # If this attribute is set to a true value, File::Fail's tail method 89 | # just returns if the end of the file is reached. 90 | attr_accessor :return_if_eof 91 | 92 | # Default buffer size, that is used while going backward from a file's end. 93 | # This defaults to nil, which means that File::Tail attempts to derive this 94 | # value from the filesystem block size. 95 | attr_accessor :default_bufsize 96 | 97 | # Override the default line separator 98 | attr_accessor :line_separator 99 | 100 | # Skip the first n lines of this file. The default is to don't 101 | # skip any lines at all and start at the beginning of this file. 102 | def forward(n = 0) 103 | preset_attributes unless defined? @lines 104 | rewind 105 | while n > 0 and not eof? 106 | readline(@line_separator) 107 | n -= 1 108 | end 109 | self 110 | end 111 | 112 | # Rewind the last n lines of this file, starting 113 | # from the end. The default is to start tailing directly from the 114 | # end of the file. 115 | # 116 | # The additional argument bufsize is 117 | # used to determine the buffer size that is used to step through 118 | # the file backwards. It defaults to the block size of the 119 | # filesystem this file belongs to or 8192 bytes if this cannot 120 | # be determined. 121 | def backward(n = 0, bufsize = nil) 122 | preset_attributes unless defined? @lines 123 | if n <= 0 124 | seek(0, File::SEEK_END) 125 | return self 126 | end 127 | bufsize ||= default_bufsize || stat.blksize || 8192 128 | size = stat.size 129 | begin 130 | if bufsize < size 131 | seek(0, File::SEEK_END) 132 | while n > 0 and tell > 0 do 133 | seek(-bufsize, File::SEEK_CUR) 134 | buffer = read(bufsize) 135 | n -= buffer.count(@line_separator) 136 | seek(-bufsize, File::SEEK_CUR) 137 | end 138 | else 139 | rewind 140 | buffer = read(size) 141 | n -= buffer.count(@line_separator) 142 | rewind 143 | end 144 | rescue Errno::EINVAL 145 | size = tell 146 | retry 147 | end 148 | pos = -1 149 | while n < 0 # forward if we are too far back 150 | pos = buffer.index(@line_separator, pos + 1) 151 | n += 1 152 | end 153 | seek(pos + 1, File::SEEK_CUR) 154 | self 155 | end 156 | 157 | # This method tails this file and yields to the given block for 158 | # every new line that is read. 159 | # If no block is given an array of those lines is 160 | # returned instead. (In this case it's better to use a 161 | # reasonable value for n or set the 162 | # return_if_eof or break_if_eof 163 | # attribute to a true value to stop the method call from blocking.) 164 | # 165 | # If the argument n is given, only the next n 166 | # lines are read and the method call returns. Otherwise this method 167 | # call doesn't return, but yields to block for every new line read from 168 | # this file for ever. 169 | def tail(n = nil, &block) # :yields: line 170 | @n = n 171 | result = [] 172 | array_result = false 173 | unless block 174 | block = lambda { |line| result << line } 175 | array_result = true 176 | end 177 | preset_attributes unless defined? @lines 178 | loop do 179 | begin 180 | restat 181 | read_line(&block) 182 | redo 183 | rescue ReopenException => e 184 | until eof? || @n == 0 185 | block.call readline(@line_separator) 186 | @n -= 1 if @n 187 | end 188 | reopen_file(e.mode) 189 | @after_reopen.call self if defined? @after_reopen 190 | rescue ReturnException 191 | return array_result ? result : nil 192 | end 193 | end 194 | end 195 | 196 | private 197 | 198 | def read_line(&block) 199 | if @n 200 | until @n == 0 201 | block.call readline(@line_separator) 202 | @lines += 1 203 | @no_read = 0 204 | @n -= 1 205 | output_debug_information 206 | end 207 | raise ReturnException 208 | else 209 | block.call readline(@line_separator) 210 | @lines += 1 211 | @no_read = 0 212 | output_debug_information 213 | end 214 | rescue EOFError 215 | seek(0, File::SEEK_CUR) 216 | raise ReopenException if @reopen_suspicious and 217 | @no_read > @suspicious_interval 218 | raise BreakException if @break_if_eof 219 | raise ReturnException if @return_if_eof 220 | sleep_interval 221 | rescue Errno::ENOENT, Errno::ESTALE, Errno::EBADF 222 | raise ReopenException 223 | end 224 | 225 | def preset_attributes 226 | @reopen_deleted = true unless defined? @reopen_deleted 227 | @reopen_suspicious = true unless defined? @reopen_suspicious 228 | @break_if_eof = false unless defined? @break_if_eof 229 | @return_if_eof = false unless defined? @return_if_eof 230 | @max_interval ||= 10 231 | @line_separator ||= $/ 232 | @interval ||= @max_interval 233 | @suspicious_interval ||= 60 234 | @lines = 0 235 | @no_read = 0 236 | @stat = nil 237 | end 238 | 239 | def restat 240 | stat = File.stat(path) 241 | if @stat 242 | if stat.ino != @stat.ino or stat.dev != @stat.dev 243 | @stat = nil 244 | raise ReopenException.new(:top) 245 | end 246 | if stat.size < @stat.size 247 | @stat = nil 248 | raise ReopenException.new(:top) 249 | end 250 | end 251 | @stat = stat 252 | rescue Errno::ENOENT, Errno::ESTALE 253 | raise ReopenException 254 | end 255 | 256 | def sleep_interval 257 | if @lines > 0 258 | # estimate how much time we will spend on waiting for next line 259 | @interval = (@interval.to_f / @lines) 260 | @lines = 0 261 | else 262 | # exponential backoff if logfile is quiet 263 | @interval *= 2 264 | end 265 | if @interval > @max_interval 266 | # max. wait @max_interval 267 | @interval = @max_interval 268 | end 269 | output_debug_information 270 | sleep @interval 271 | @no_read += @interval 272 | end 273 | 274 | def reopen_file(mode) 275 | debug? and $stdout.print "Reopening '#{path}', mode = #{mode}.\n" 276 | @no_read = 0 277 | reopen(path) 278 | if mode == :bottom 279 | backward 280 | elsif mode == :top 281 | forward 282 | end 283 | rescue Errno::ESTALE, Errno::ENOENT 284 | if @reopen_deleted 285 | sleep @max_interval 286 | retry 287 | else 288 | raise DeletedException 289 | end 290 | end 291 | 292 | def output_debug_information 293 | debug? or return 294 | STDERR.puts({ 295 | :path => path, 296 | :lines => @lines, 297 | :interval => @interval, 298 | :no_read => @no_read, 299 | :n => @n, 300 | }.inspect) 301 | self 302 | end 303 | 304 | def debug? 305 | ENV['FILE_TAIL_DEBUG'].to_i == 1 306 | end 307 | end 308 | end 309 | 310 | if $0 == __FILE__ 311 | filename = ARGV.shift or fail "Usage: #$0 filename [number]" 312 | number = (ARGV.shift || 0).to_i 313 | File.open(filename) do |log| 314 | log.extend(File::Tail) 315 | # Some settings to make watching tail.rb with "ruby -d" fun 316 | log.interval = 1 317 | log.max_interval = 5 318 | log.reopen_deleted = true # is default 319 | log.reopen_suspicious = true # is default 320 | log.suspicious_interval = 20 321 | number >= 0 ? log.backward(number, 8192) : log.forward(-number) 322 | #loop do # grab 5 lines at a time and return 323 | # log.tail(5) { |line| puts line } 324 | # print "Got 5!\n" 325 | #end 326 | log.tail { |line| puts line } 327 | end 328 | end 329 | -------------------------------------------------------------------------------- /lib/file/tail/group.rb: -------------------------------------------------------------------------------- 1 | require 'thread' 2 | 3 | class File 4 | module Tail 5 | # This class can be used to coordinate tailing of many files, which have 6 | # been added to the group. 7 | class Group 8 | # Creates a new File::Tail::Group instance. 9 | # 10 | # The following options can be given as arguments: 11 | # :files:: an array of files (or filenames to open) that are placed into 12 | # the group. 13 | def initialize(opts = {}) 14 | @tailers = ThreadGroup.new 15 | if files = opts[:files] 16 | Array(files).each { |file| add file } 17 | end 18 | end 19 | 20 | # Creates a group for +files+ (IO instances or filename strings). 21 | def self.[](*files) 22 | new(:files => files) 23 | end 24 | 25 | # Add a file (IO instance) or filename (responding to to_str) to this 26 | # group. 27 | def add(file_or_filename) 28 | if file_or_filename.respond_to?(:to_io) 29 | add_file file_or_filename.to_io 30 | elsif file_or_filename.respond_to?(:to_str) 31 | add_filename file_or_filename 32 | end 33 | end 34 | 35 | alias << add 36 | 37 | # Add the IO instance +file+ to this group. 38 | def add_file(file) 39 | setup_file_tailer file 40 | self 41 | end 42 | 43 | # Add a file created by opening +filename+ to this group after stepping 44 | # +n+ lines backwards from the end of it. 45 | def add_filename(filename, n = 0) 46 | file = Logfile.open(filename.to_str, :backward => n) 47 | file.backward n 48 | setup_file_tailer file 49 | self 50 | end 51 | 52 | # Iterate over all files contained in this group yielding to +block+ for 53 | # each of them. 54 | def each_file(&block) 55 | each_tailer { |t| t.file }.map(&block) 56 | end 57 | 58 | # Iterate over all tailers in this group yielding to +block+ for each of 59 | # them. 60 | def each_tailer(&block) 61 | @tailers.list.map(&block) 62 | end 63 | 64 | # Stop all tailers in this group at once. 65 | def stop 66 | each_tailer { |t| t.stop } 67 | each_tailer { |t| t.join } 68 | self 69 | end 70 | 71 | # Tail all the lines of all the files in the Tail::Group instance, that 72 | # is yield to each of them. 73 | # 74 | # Every line is extended with the LineExtension module, that adds some 75 | # methods to the line string. To get the path of the file this line was 76 | # received from call line.file.path. 77 | def tail 78 | wait_for_activity do |tailer| 79 | tailer.pending_lines.each do |line| 80 | line.extend LineExtension 81 | line.instance_variable_set :@tailer, tailer 82 | yield line 83 | end 84 | end 85 | end 86 | 87 | private 88 | 89 | def setup_file_tailer(file) 90 | file.extend File::Tail 91 | setup = ConditionVariable.new 92 | mutex = Mutex.new 93 | ft = nil 94 | mutex.synchronize do 95 | ft = Tailer.new do 96 | t = Thread.current 97 | t[:queue] = Queue.new 98 | t[:file] = file 99 | mutex.synchronize do 100 | setup.signal 101 | end 102 | file.tail { |line| t[:queue] << line } 103 | end 104 | setup.wait mutex 105 | end 106 | @tailers.add ft 107 | nil 108 | end 109 | 110 | # Wait until new input is receіved on any of the tailers in the group. If 111 | # so call +block+ with all of these trailers as an argument. 112 | def wait_for_activity(&block) 113 | loop do 114 | pending = each_tailer.select(&:pending_lines?) 115 | if pending.empty? 116 | interval = each_file.map { |t| t.interval }.compact.min || 0.1 117 | sleep interval 118 | else 119 | pending.each(&block) 120 | end 121 | end 122 | end 123 | end 124 | end 125 | end 126 | -------------------------------------------------------------------------------- /lib/file/tail/line_extension.rb: -------------------------------------------------------------------------------- 1 | class File 2 | module Tail 3 | # This module is used to extend all lines received via one of the tailers 4 | # of a File::Tail::Group. 5 | module LineExtension 6 | # The file as a File instance this line was read from. 7 | def file 8 | tailer.file 9 | end 10 | 11 | # This is the tailer this line was received from. 12 | attr_reader :tailer 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /lib/file/tail/logfile.rb: -------------------------------------------------------------------------------- 1 | class File 2 | module Tail 3 | # This is an easy to use Logfile class that includes 4 | # the File::Tail module. 5 | # 6 | # === Usage 7 | # The unix command "tail -10f filename" can be emulated like that: 8 | # File::Tail::Logfile.open(filename, :backward => 10) do |log| 9 | # log.tail { |line| puts line } 10 | # end 11 | # 12 | # Or a bit shorter: 13 | # File::Tail::Logfile.tail(filename, :backward => 10) do |line| 14 | # puts line 15 | # end 16 | # 17 | # To skip the first 10 lines of the file do that: 18 | # File::Tail::Logfile.open(filename, :forward => 10) do |log| 19 | # log.tail { |line| puts line } 20 | # end 21 | # 22 | # The unix command "head -10 filename" can be emulated like that: 23 | # File::Tail::Logfile.open(filename, :return_if_eof => true) do |log| 24 | # log.tail(10) { |line| puts line } 25 | # end 26 | class Logfile < File 27 | include File::Tail 28 | 29 | # This method creates an File::Tail::Logfile object and 30 | # yields to it, and closes it, if a block is given, otherwise it just 31 | # returns it. The opts hash takes an option like 32 | # * :backward => 10 to go backwards 33 | # * :forward => 10 to go forwards 34 | # in the logfile for 10 lines at the start. The buffersize 35 | # for going backwards can be set with the 36 | # * :bufsiz => 8192 option. 37 | # To define a callback, that will be called after a reopening occurs, use: 38 | # * :after_reopen => lambda { |file| p file } 39 | # 40 | # Every attribute of File::Tail can be set with a :attributename => 41 | # value option. 42 | def self.open(filename, opts = {}, &block) # :yields: file 43 | file = new filename 44 | opts.each do |o, v| 45 | writer = o.to_s + "=" 46 | file.__send__(writer, v) if file.respond_to? writer 47 | end 48 | if opts.key?(:wind) or opts.key?(:rewind) 49 | warn ":wind and :rewind options are deprecated, "\ 50 | "use :forward and :backward instead!" 51 | end 52 | if backward = opts[:backward] || opts[:rewind] 53 | (args = []) << backward 54 | args << opt[:bufsiz] if opts[:bufsiz] 55 | file.backward(*args) 56 | elsif forward = opts[:forward] || opts[:wind] 57 | file.forward(forward) 58 | end 59 | if opts[:after_reopen] 60 | file.after_reopen(&opts[:after_reopen]) 61 | end 62 | if block_given? 63 | begin 64 | block.call file 65 | ensure 66 | file.close 67 | nil 68 | end 69 | else 70 | file 71 | end 72 | end 73 | 74 | # Like open, but yields to every new line encountered in the logfile in 75 | # +block+. 76 | def self.tail(filename, opts = {}, &block) 77 | if ([ :forward, :backward ] & opts.keys).empty? 78 | opts[:backward] = 0 79 | end 80 | open(filename, opts) do |log| 81 | log.tail { |line| block.call line } 82 | end 83 | end 84 | end 85 | end 86 | end 87 | -------------------------------------------------------------------------------- /lib/file/tail/tailer.rb: -------------------------------------------------------------------------------- 1 | class File 2 | module Tail 3 | # This class supervises activity on a tailed fail and collects newly read 4 | # lines until the Tail::Group fetches and processes them. 5 | class Tailer < ::Thread 6 | 7 | # True if there are any lines pending on this Tailer, false otherwise. 8 | def pending_lines? 9 | !queue.empty? 10 | end 11 | 12 | # Fetch all the pending lines from this Tailer and thereby remove them 13 | # from the Tailer's queue. 14 | def pending_lines 15 | Array.new(queue.size) { queue.deq(true) } 16 | end 17 | 18 | alias stop exit # Stop tailing this file and remove it from its File::Tail::Group. 19 | 20 | # Return true if the thread local variable +id+ is defined or if this 21 | # object responds to the method +id+. 22 | def respond_to?(id) 23 | !self[id].nil? || super 24 | end 25 | 26 | # Return the thread local variable +id+ if it is defined. 27 | def method_missing(id, *args, &block) 28 | if args.empty? && !(value = self[id]).nil? 29 | value 30 | else 31 | super 32 | end 33 | end 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /lib/file/tail/version.rb: -------------------------------------------------------------------------------- 1 | module File::Tail 2 | # File::Tail version 3 | VERSION = '1.3.0' 4 | VERSION_ARRAY = VERSION.split('.').map(&:to_i) # :nodoc: 5 | VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc: 6 | VERSION_MINOR = VERSION_ARRAY[1] # :nodoc: 7 | VERSION_BUILD = VERSION_ARRAY[2] # :nodoc: 8 | end 9 | -------------------------------------------------------------------------------- /tests/file_tail_group_test.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'test_helper' 4 | require 'file/tail' 5 | require 'timeout' 6 | require 'thread' 7 | require 'tempfile' 8 | Thread.abort_on_exception = true 9 | 10 | class FileTailGroupTest < Test::Unit::TestCase 11 | include File::Tail 12 | 13 | def test_create_group 14 | t, = make_file 15 | g = Group[t] 16 | assert_equal t.path, g.each_tailer.first.file.path 17 | assert_equal t.path, g.each_file.first.path 18 | end 19 | 20 | def test_stop_group 21 | t, = make_file 22 | g = Group[t] 23 | assert_equal t.path, g.each_tailer.first.file.path 24 | assert_equal t.path, g.each_file.first.path 25 | g.stop 26 | assert_nil g.each_file.first 27 | end 28 | 29 | def test_add_file_to_group 30 | g = Group.new 31 | t, = make_file 32 | g.add_file t 33 | assert_equal t.path, g.each_tailer.first.file.path 34 | assert_equal t.path, g.each_file.first.path 35 | end 36 | 37 | def test_add_filename_to_group 38 | g = Group.new 39 | t, name = make_file 40 | t.close 41 | g.add_filename name 42 | assert_equal name, g.each_tailer.first.file.path 43 | assert_equal t.path, g.each_file.first.path 44 | end 45 | 46 | def test_add_generic_to_group 47 | g = Group.new 48 | t1, n1 = make_file 49 | t1.close 50 | t2, n1 = make_file 51 | g << n1 52 | g << t2 53 | assert g.each_tailer.any? { |t| t.file.path == n1 } 54 | assert g.each_tailer.any? { |t| t.file.path == t2.path } 55 | assert g.each_file.any? { |t| t.path == n1 } 56 | assert g.each_file.any? { |t| t.path == t2.path } 57 | end 58 | 59 | def test_tail_multiple_files 60 | t1, = make_file 61 | t1.max_interval = 0.1 62 | t2, = make_file 63 | t2.max_interval = 0.1 64 | g = Group[t1, t2] 65 | q = Queue.new 66 | t = Thread.new do 67 | g.tail { |l| q << l } 68 | end 69 | t1.puts "foo" 70 | assert_equal "foo\n", q.pop 71 | t2.puts "bar" 72 | assert_equal "bar\n", q.pop 73 | ensure 74 | t and t.exit 75 | end 76 | 77 | private 78 | 79 | def make_file 80 | name = File.expand_path(File.join(Dir.tmpdir, "tmp.#$$")) 81 | file = File.open(name, 'w+') 82 | file.extend File::Tail 83 | return file, name 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /tests/file_tail_test.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'test_helper' 4 | require 'file/tail' 5 | require 'timeout' 6 | require 'thread' 7 | require 'fileutils' 8 | Thread.abort_on_exception = true 9 | 10 | class FileTailTest < Test::Unit::TestCase 11 | include File::Tail 12 | include FileUtils 13 | 14 | def setup 15 | @out = File.new(File.join(__dir__, "test.#$$"), "wb") 16 | at_exit { rm_f File.expand_path(@out.path) } 17 | append(@out, 100) 18 | @in = File.new(@out.path, "rb") 19 | @in.extend(File::Tail) 20 | @in.interval = 0.4 21 | @in.max_interval = 0.8 22 | @in.reopen_deleted = true # is default 23 | @in.reopen_suspicious = true # is default 24 | @in.suspicious_interval = 60 25 | end 26 | 27 | def test_forward 28 | [ 0, 1, 2, 10, 100 ].each do |lines| 29 | @in.forward(lines) 30 | assert_equal(100 - lines, count(@in)) 31 | end 32 | @in.forward(101) 33 | assert_equal(0, count(@in)) 34 | end 35 | 36 | def test_backward 37 | [ 0, 1, 2, 10, 100 ].each do |lines| 38 | @in.backward(lines) 39 | assert_equal(lines, count(@in)) 40 | end 41 | @in.backward(101) 42 | assert_equal(100, count(@in)) 43 | end 44 | 45 | def test_backward_small_buffer 46 | [ 0, 1, 2, 10, 100 ].each do |lines| 47 | @in.backward(lines, 100) 48 | assert_equal(lines, count(@in)) 49 | end 50 | @in.backward(101, 100) 51 | assert_equal(100, count(@in)) 52 | end 53 | 54 | def test_backward_small_buffer2 55 | @in.default_bufsize = 100 56 | [ 0, 1, 2, 10, 100 ].each do |lines| 57 | @in.backward(lines) 58 | assert_equal(lines, count(@in)) 59 | end 60 | @in.backward(101) 61 | assert_equal(100, count(@in)) 62 | end 63 | 64 | def test_tail_with_block_without_n 65 | Timeout::timeout(10) do 66 | lines = [] 67 | @in.backward(1) 68 | assert_raises(Timeout::Error) do 69 | Timeout::timeout(1) { @in.tail { |l| lines << l } } 70 | end 71 | assert_equal(1, lines.size) 72 | # 73 | lines = [] 74 | @in.backward(10) 75 | assert_raises(Timeout::Error) do 76 | Timeout::timeout(1) { @in.tail { |l| lines << l } } 77 | end 78 | assert_equal(10, lines.size) 79 | # 80 | lines = [] 81 | @in.backward(100) 82 | assert_raises(Timeout::Error) do 83 | Timeout::timeout(1) { @in.tail { |l| lines << l } } 84 | end 85 | assert_equal(100, lines.size) 86 | # 87 | lines = [] 88 | @in.backward(101) 89 | assert_raises(Timeout::Error) do 90 | Timeout::timeout(1) { @in.tail { |l| lines << l } } 91 | end 92 | end 93 | end 94 | 95 | def test_tail_with_block_with_n 96 | Timeout::timeout(10) do 97 | @in.backward(1) 98 | lines = [] 99 | Timeout::timeout(1) { @in.tail(0) { |l| lines << l } } 100 | assert_equal(0, lines.size) 101 | # 102 | @in.backward(1) 103 | lines = [] 104 | Timeout::timeout(1) { @in.tail(1) { |l| lines << l } } 105 | assert_equal(1, lines.size) 106 | # 107 | @in.backward(10) 108 | lines = [] 109 | Timeout::timeout(1) { @in.tail(10) { |l| lines << l } } 110 | assert_equal(10, lines.size) 111 | # 112 | @in.backward(100) 113 | lines = [] 114 | @in.backward(1) 115 | assert_raises(Timeout::Error) do 116 | Timeout::timeout(1) { @in.tail(2) { |l| lines << l } } 117 | end 118 | assert_equal(1, lines.size) 119 | # 120 | end 121 | end 122 | 123 | def test_tail_without_block_with_n 124 | Timeout::timeout(10) do 125 | @in.backward(1) 126 | lines = [] 127 | Timeout::timeout(1) { lines += @in.tail(0) } 128 | assert_equal(0, lines.size) 129 | # 130 | @in.backward(1) 131 | lines = [] 132 | Timeout::timeout(1) { lines += @in.tail(1) } 133 | assert_equal(1, lines.size) 134 | # 135 | @in.backward(10) 136 | lines = [] 137 | Timeout::timeout(1) { lines += @in.tail(10) } 138 | assert_equal(10, lines.size) 139 | # 140 | @in.backward(100) 141 | lines = [] 142 | @in.backward(1) 143 | assert_raises(Timeout::Error) do 144 | Timeout::timeout(1) { lines += @in.tail(2) } 145 | end 146 | assert_equal(0, lines.size) 147 | end 148 | end 149 | 150 | def test_tail_withappend 151 | @in.backward 152 | lines = [] 153 | logger = Thread.new do 154 | begin 155 | Timeout::timeout(1) { @in.tail { |l| lines << l } } 156 | rescue Timeout::Error 157 | end 158 | end 159 | appender = Thread.new { append(@out, 10) } 160 | appender.join 161 | logger.join 162 | assert_equal(10, lines.size) 163 | end 164 | 165 | def test_tail_truncated 166 | @in.backward 167 | lines = [] 168 | logger = Thread.new do 169 | begin 170 | Timeout::timeout(10) do 171 | @in.tail do |l| 172 | lines << l 173 | end 174 | end 175 | rescue Timeout::Error 176 | end 177 | end 178 | appender = Thread.new do 179 | until logger.stop? 180 | sleep 0.1 181 | end 182 | @out.close 183 | File.truncate(@out.path, 0) 184 | @out = File.new(@in.path, "ab") 185 | append(@out, 10) 186 | end 187 | appender.join 188 | logger.join 189 | assert_equal(10, lines.size) 190 | end 191 | 192 | def test_tail_remove 193 | return if File::PATH_SEPARATOR == ';' # Grmpf! Windows... 194 | @in.backward 195 | reopened = false 196 | @in.after_reopen { |f| reopened = true } 197 | lines = [] 198 | logger = Thread.new do 199 | begin 200 | Timeout::timeout(10) do 201 | @in.tail do |l| 202 | lines << l 203 | end 204 | end 205 | rescue Timeout::Error 206 | end 207 | end 208 | appender = Thread.new do 209 | until logger.stop? 210 | sleep 0.1 211 | end 212 | @out.close 213 | File.unlink(@out.path) 214 | @out = File.new(@in.path, "wb") 215 | append(@out, 10) 216 | end 217 | appender.join 218 | logger.join 219 | assert_equal(10, lines.size) 220 | assert reopened 221 | end 222 | 223 | def test_tail_remove2 224 | return if File::PATH_SEPARATOR == ';' # Grmpf! Windows... 225 | @in.backward 226 | reopened = false 227 | @in.after_reopen { |f| reopened = true } 228 | lines = [] 229 | logger = Thread.new do 230 | begin 231 | Timeout::timeout(10) do 232 | @in.tail do |l| 233 | lines << l 234 | end 235 | end 236 | rescue Timeout::Error 237 | end 238 | end 239 | appender = Thread.new do 240 | until logger.stop? 241 | sleep 0.1 242 | end 243 | @out.close 244 | File.unlink(@out.path) 245 | @out = File.new(@in.path, "wb") 246 | append(@out, 10) 247 | sleep 1 248 | append(@out, 10) 249 | File.unlink(@out.path) 250 | @out = File.new(@in.path, "wb") 251 | append(@out, 10) 252 | end 253 | appender.join 254 | logger.join 255 | assert_equal(30, lines.size) 256 | assert reopened 257 | end 258 | 259 | def test_tail_remove3 260 | return if File::PATH_SEPARATOR == ';' # Grmpf! Windows... 261 | @in.backward 262 | reopened = false 263 | @in.after_reopen { |f| reopened = true } 264 | lines = [] 265 | logger = Thread.new do 266 | begin 267 | Timeout::timeout(10) do 268 | @in.tail(15) do |l| 269 | lines << l 270 | end 271 | end 272 | rescue Timeout::Error 273 | end 274 | end 275 | appender = Thread.new do 276 | until logger.stop? 277 | sleep 0.1 278 | end 279 | @out.close 280 | File.unlink(@out.path) 281 | @out = File.new(@in.path, "wb") 282 | append(@out, 10) 283 | sleep 1 284 | append(@out, 10) 285 | File.unlink(@out.path) 286 | @out = File.new(@in.path, "wb") 287 | append(@out, 10) 288 | end 289 | appender.join 290 | logger.join 291 | assert_equal(15, lines.size) 292 | assert reopened 293 | end 294 | 295 | def test_tail_change 296 | return if File::PATH_SEPARATOR == ';' # Grmpf! Windows... 297 | @in.forward 298 | reopened = false 299 | assert_equal 0, @in.lineno 300 | @in.after_reopen { |f| reopened = true } 301 | lines = [] 302 | logger = Thread.new do 303 | begin 304 | Timeout::timeout(10) do 305 | @in.tail(110) do |l| 306 | lines << l 307 | end 308 | end 309 | rescue Timeout::Error 310 | end 311 | end 312 | appender = Thread.new do 313 | Timeout::timeout(10) do 314 | until lines.size == 100 315 | sleep 0.1 316 | end 317 | end 318 | @out.close 319 | File.unlink(@out.path) 320 | @out = File.new(@in.path, "wb") 321 | append(@out, 10) 322 | end 323 | appender.join 324 | logger.join 325 | assert_equal(110, lines.size) 326 | assert reopened 327 | assert_equal 10, @in.lineno 328 | end 329 | 330 | def test_tail_change2 331 | return if File::PATH_SEPARATOR == ';' # Grmpf! Windows... 332 | @in.forward 333 | reopened = false 334 | assert_equal 0, @in.lineno 335 | @in.after_reopen { |f| reopened = true } 336 | lines = [] 337 | logger = Thread.new do 338 | begin 339 | Timeout::timeout(10) do 340 | @in.tail(110) do |l| 341 | lines << l 342 | end 343 | end 344 | rescue Timeout::Error 345 | end 346 | end 347 | appender = Thread.new do 348 | Timeout::timeout(10) do 349 | until lines.size == 100 350 | sleep 0.1 351 | end 352 | end 353 | @out.truncate 0 354 | @out.close 355 | @out = File.new(@in.path, "wb") 356 | append(@out, 10) 357 | end 358 | appender.join 359 | logger.join 360 | assert_equal(110, lines.size) 361 | assert reopened 362 | assert_equal 10, @in.lineno 363 | end 364 | 365 | def teardown 366 | @in.close 367 | @out.close 368 | File.unlink(@out.path) 369 | end 370 | 371 | private 372 | 373 | def count(file) 374 | n = 0 375 | until file.eof? 376 | file.readline 377 | n += 1 378 | end 379 | return n 380 | end 381 | 382 | def append(file, n, size = 70) 383 | (1..n).each { |x| file << "#{x} #{"A" * size}\n" } 384 | file.flush 385 | end 386 | end 387 | -------------------------------------------------------------------------------- /tests/test_helper.rb: -------------------------------------------------------------------------------- 1 | if ENV['START_SIMPLECOV'].to_i == 1 2 | require 'simplecov' 3 | SimpleCov.start do 4 | add_filter "#{File.basename(File.dirname(__FILE__))}/" 5 | end 6 | end 7 | require 'test/unit' 8 | --------------------------------------------------------------------------------