├── test.txt ├── .github ├── PULL_REQUEST_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── Support_question.md │ ├── Feature_request.md │ └── Bug_report.md ├── workflows │ ├── dependencies.yml │ ├── docs.yml │ ├── deploy.yml │ └── ci.yml ├── CONTRIBUTING.md └── CODE_OF_CONDUCT.md ├── LICENSE.spdx ├── .gitignore ├── test ├── The Ants and the Grasshopper.txt ├── The Cat and the Mice.txt ├── The Goose With the Golden Eggs.txt ├── The Man and His Two Wives.txt ├── The Hare and the Tortoise.txt └── multigrep │ └── core_test.clj ├── pbr.clj ├── deps.edn ├── README.md ├── src └── multigrep │ └── core.clj └── LICENSE /test.txt: -------------------------------------------------------------------------------- 1 | This is a test. 2 | This is a test of the Outdoor Public Warning System. 3 | This is only a test. 4 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Addresses issue # 2 | 3 | Summary of changes: 4 | 5 | * 6 | * 7 | * 8 | 9 | Head's up @pmonks! -------------------------------------------------------------------------------- /LICENSE.spdx: -------------------------------------------------------------------------------- 1 | SPDXVersion: SPDX-2.1 2 | DataLicense: CC0-1.0 3 | Creator: Peter Monks 4 | PackageName: multigrep 5 | PackageOriginator: Peter Monks 6 | PackageHomePage: https://github.com/pmonks/multigrep 7 | PackageLicenseDeclared: Apache-2.0 8 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Support_question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🤗 Support Question 3 | about: If you have a question about configuration, usage, etc. 💬 4 | 5 | --- 6 | 7 | ## Support Question 8 | 9 | ...ask your question here. 10 | 11 | ...be sure to search existing issues since someone might have already asked something similar. 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | pom.xml 4 | pom.xml.asc 5 | *jar 6 | /lib/ 7 | /classes/ 8 | /targets/ 9 | /target/ 10 | .cpcache/ 11 | .nrepl-port 12 | .shell_history 13 | *.log 14 | uberjar/ 15 | /config.edn 16 | .rebel_readline_history 17 | .eastwood 18 | attic 19 | resources/logback-test.xml 20 | .clj-kondo/.cache 21 | .lein-failures 22 | greplace-test-*.txt 23 | -------------------------------------------------------------------------------- /.github/workflows/dependencies.yml: -------------------------------------------------------------------------------- 1 | name: dependencies 2 | on: 3 | push: 4 | schedule: 5 | - cron: '0 21 * * *' 6 | 7 | jobs: 8 | antq: 9 | runs-on: ubuntu-latest 10 | container: 11 | image: uochan/antq 12 | steps: 13 | - uses: actions/checkout@v2 14 | - run: java -jar /tmp/antq/antq.jar --skip=pom --error-format="::error file={{file}}::{{message}}" 15 | -------------------------------------------------------------------------------- /test/The Ants and the Grasshopper.txt: -------------------------------------------------------------------------------- 1 | The Ants and the Grasshopper 2 | 3 | 4 | THE ANTS were spending a fine winter's day drying grain collected 5 | in the summertime. A Grasshopper, perishing with famine, passed 6 | by and earnestly begged for a little food. The Ants inquired of 7 | him, "Why did you not treasure up food during the summer?' He 8 | replied, "I had not leisure enough. I passed the days in 9 | singing." They then said in derision: "If you were foolish enough 10 | to sing all the summer, you must dance supperless to bed in the 11 | winter." 12 | 13 | 14 | It is thrifty to prepare today for the wants of tomorrow -------------------------------------------------------------------------------- /test/The Cat and the Mice.txt: -------------------------------------------------------------------------------- 1 | The Cat and the Mice 2 | 3 | 4 | A CERTAIN HOUSE was overrun with Mice. A Cat, discovering this, 5 | made her way into it and began to catch and eat them one by one. 6 | Fearing for their lives, the Mice kept themselves close in their 7 | holes. The Cat was no longer able to get at them and perceived 8 | that she must tempt them forth by some device. For this purpose 9 | she jumped upon a peg, and suspending herself from it, pretended 10 | to be dead. One of the Mice, peeping stealthily out, saw her and 11 | said, "Ah, my good madam, even though you should turn into a 12 | meal-bag, we will not come near you." 13 | 14 | 15 | He who is once deceived is doubly cautious -------------------------------------------------------------------------------- /test/The Goose With the Golden Eggs.txt: -------------------------------------------------------------------------------- 1 | The Goose With the Golden Eggs 2 | 3 | 4 | One day a countryman going to the nest of his Goose found 5 | there an egg all yellow and glittering. When he took it up it was 6 | as heavy as lead and he was going to throw it away, because he 7 | thought a trick had been played upon him. But he took it home on 8 | second thoughts, and soon found to his delight that it was an egg 9 | of pure gold. Every morning the same thing occurred, and he soon 10 | became rich by selling his eggs. As he grew rich he grew greedy; 11 | and thinking to get at once all the gold the Goose could give, he 12 | killed it and opened it only to find nothing. 13 | 14 | 15 | Greed oft o'er reaches itself. -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature Request 3 | about: I have a suggestion (and may want to implement it 🙂)! 4 | 5 | --- 6 | 7 | ## Feature Request 8 | 9 | ### Description of Problem: 10 | ...what *problem* are you trying to solve that the project doesn't currently solve? 11 | 12 | ...please resist the temptation to describe your request in terms of a solution. Job Story form ("When [triggering condition], I want to [motivation/goal], so I can [outcome].") can help ensure you're expressing a problem statement. 13 | 14 | ### Potential Solutions: 15 | ...clearly and concisely describe what you want to happen. Add any considered drawbacks. 16 | 17 | ... if you've considered alternatives, clearly and concisely describe those too. 18 | -------------------------------------------------------------------------------- /test/The Man and His Two Wives.txt: -------------------------------------------------------------------------------- 1 | The Man and His Two Wives 2 | 3 | 4 | In the old days, when men were allowed to have many wives, a 5 | middle-aged Man had one wife that was old and one that was young; 6 | each loved him very much, and desired to see him like herself. 7 | Now the Man's hair was turning grey, which the young Wife did not 8 | like, as it made him look too old for her husband. So every night 9 | she used to comb his hair and pick out the white ones. But the 10 | elder Wife saw her husband growing grey with great pleasure, for 11 | she did not like to be mistaken for his mother. So every morning 12 | she used to arrange his hair and pick out as many of the black 13 | ones as she could. The consequence was the Man soon found himself 14 | entirely bald. 15 | 16 | 17 | Yield to all and you will soon have nothing to yield. -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug Report 3 | about: If something isn't working as expected 🤔. 4 | 5 | --- 6 | 7 | ## Bug Report 8 | 9 | ### Steps to Reproduce: 10 | 1. ...step 1 description... 11 | 2. ...step 2 description... 12 | 3. ...step 3 description... 13 | 14 | ### Expected Result: 15 | ...description of what you expected to see... 16 | 17 | ### Actual Result: 18 | ...what actually happened, including full exceptions (please include the entire stack trace, including "caused by" entries), log entries, screen shots etc. where appropriate... 19 | 20 | ### Environment: 21 | ...version and build of the project, OS, Java and Clojure versions, virtualised environment (if any), etc. ... 22 | 23 | ### Additional Context: 24 | ...add any other context about the problem here. If applicable, add screenshots to help explain... 25 | -------------------------------------------------------------------------------- /test/The Hare and the Tortoise.txt: -------------------------------------------------------------------------------- 1 | The Hare and the Tortoise 2 | 3 | 4 | A HARE one day ridiculed the short feet and slow pace of the 5 | Tortoise, who replied, laughing: "Though you be swift as the 6 | wind, I will beat you in a race." The Hare, believing her 7 | assertion to be simply impossible, assented to the proposal; and 8 | they agreed that the Fox should choose the course and fix the 9 | goal. On the day appointed for the race the two started 10 | together. The Tortoise never for a moment stopped, but went on 11 | with a slow but steady pace straight to the end of the course. 12 | The Hare, lying down by the wayside, fell fast asleep. At last 13 | waking up, and moving as fast as he could, he saw the Tortoise 14 | had reached the goal, and was comfortably dozing after her 15 | fatigue. 16 | 17 | 18 | Slow but steady wins the race. -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: docs 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | docs: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-java@v2 14 | with: 15 | distribution: 'temurin' 16 | java-version: 17 17 | - uses: DeLaGuardo/setup-clojure@3.7 18 | with: 19 | tools-deps: latest 20 | - uses: actions/cache@v2 21 | with: 22 | path: | 23 | ~/.m2/repository 24 | ~/.gitlibs 25 | ~/.clojure 26 | ~/.cpcache 27 | key: ${{ runner.os }}-${{ hashFiles('**/deps.edn') }} 28 | 29 | - name: Generate docs 30 | run: clojure -Srepro -J-Dclojure.main.report=stderr -T:build docs 31 | 32 | - name: Deploy docs 33 | uses: peaceiris/actions-gh-pages@v3 34 | with: 35 | github_token: ${{ secrets.GITHUB_TOKEN }} 36 | publish_dir: ./target/doc 37 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: deploy 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | environment: clojars 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | with: 15 | fetch-depth: 0 # Make sure we get the full history, or else the version number gets screwed up 16 | - uses: actions/setup-java@v2 17 | with: 18 | distribution: 'temurin' 19 | java-version: 17 20 | - uses: DeLaGuardo/setup-clojure@3.7 21 | with: 22 | tools-deps: latest 23 | - uses: actions/cache@v2 24 | with: 25 | path: | 26 | ~/.m2/repository 27 | ~/.gitlibs 28 | ~/.clojure 29 | ~/.cpcache 30 | key: ${{ runner.os }}-${{ hashFiles('**/deps.edn') }} 31 | 32 | - name: Build JAR and deploy to Clojars 33 | env: 34 | CLOJARS_USERNAME: ${{ secrets.CLOJARS_USERNAME }} 35 | CLOJARS_PASSWORD: ${{ secrets.CLOJARS_PASSWORD }} 36 | run: clojure -Srepro -J-Dclojure.main.report=stderr -T:build deploy 37 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | skip_check: 7 | runs-on: ubuntu-latest 8 | outputs: 9 | should_skip: ${{ steps.skip_check.outputs.should_skip }} 10 | steps: 11 | - id: skip_check 12 | uses: fkirc/skip-duplicate-actions@master 13 | 14 | CI: 15 | needs: skip_check 16 | if: ${{ needs.skip_check.outputs.should_skip != 'true' }} 17 | runs-on: ubuntu-latest 18 | 19 | strategy: 20 | matrix: 21 | java-version: [ 8, 11, 17 ] 22 | 23 | steps: 24 | - uses: actions/checkout@v2 25 | - uses: actions/setup-java@v2 26 | with: 27 | distribution: 'temurin' 28 | java-version: ${{ matrix.java-version }} 29 | - uses: DeLaGuardo/setup-clojure@3.7 30 | with: 31 | tools-deps: latest 32 | - uses: actions/cache@v2 33 | with: 34 | path: | 35 | ~/.m2/repository 36 | ~/.gitlibs 37 | ~/.clojure 38 | ~/.cpcache 39 | key: ${{ runner.os }}-${{ hashFiles('**/deps.edn') }} 40 | 41 | - name: Run CI checks 42 | run: clojure -Srepro -J-Dclojure.main.report=stderr -T:build ci 43 | -------------------------------------------------------------------------------- /pbr.clj: -------------------------------------------------------------------------------- 1 | ; 2 | ; Copyright © 2021 Peter Monks 3 | ; 4 | ; Licensed under the Apache License, Version 2.0 (the "License"); 5 | ; you may not use this file except in compliance with the License. 6 | ; You may obtain a copy of the License at 7 | ; 8 | ; http://www.apache.org/licenses/LICENSE-2.0 9 | ; 10 | ; Unless required by applicable law or agreed to in writing, software 11 | ; distributed under the License is distributed on an "AS IS" BASIS, 12 | ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | ; See the License for the specific language governing permissions and 14 | ; limitations under the License. 15 | ; 16 | ; SPDX-License-Identifier: Apache-2.0 17 | ; 18 | 19 | (def lib 'com.github.pmonks/multigrep) 20 | 21 | #_{:clj-kondo/ignore [:unresolved-namespace]} 22 | (def version (format "1.0.%s" (b/git-count-revs nil))) 23 | 24 | (defn set-opts 25 | [opts] 26 | (assoc opts 27 | :lib lib 28 | :version version 29 | :write-pom true 30 | :validate-pom true 31 | :pom {:description "A little Clojure library that provides regex-based file grepping and/or text substitution." 32 | :url "https://github.com/pmonks/multigrep" 33 | :licenses [:license {:name "Apache License 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html"}] 34 | :developers [:developer {:id "pmonks" :name "Peter Monks" :email "pmonks+multigrep@gmail.com"}] 35 | :scm {:url "https://github.com/pmonks/multigrep" :connection "scm:git:git://github.com/pmonks/multigrep.git" :developer-connection "scm:git:ssh://git@github.com/pmonks/multigrep.git"} 36 | :issue-management {:system "github" :url "https://github.com/pmonks/multigrep/issues"}})) 37 | -------------------------------------------------------------------------------- /deps.edn: -------------------------------------------------------------------------------- 1 | ; 2 | ; Copyright © 2021 Peter Monks 3 | ; 4 | ; Licensed under the Apache License, Version 2.0 (the "License"); 5 | ; you may not use this file except in compliance with the License. 6 | ; You may obtain a copy of the License at 7 | ; 8 | ; http://www.apache.org/licenses/LICENSE-2.0 9 | ; 10 | ; Unless required by applicable law or agreed to in writing, software 11 | ; distributed under the License is distributed on an "AS IS" BASIS, 12 | ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | ; See the License for the specific language governing permissions and 14 | ; limitations under the License. 15 | ; 16 | ; SPDX-License-Identifier: Apache-2.0 17 | ; 18 | 19 | {:deps 20 | {org.clojure/clojure {:mvn/version "1.10.3"}} 21 | :aliases 22 | {; ---- TOOL ALIASES ---- 23 | 24 | ; clj -T:build 25 | :build 26 | {:deps {io.github.seancorfield/build-clj {:git/tag "v0.6.5" :git/sha "972031a"} 27 | com.github.pmonks/pbr {:mvn/version "2.0.133"}} 28 | :ns-default build} 29 | 30 | 31 | ; ---- OTHER ALIASES ---- 32 | ; clj -M:check 33 | :check 34 | {:extra-deps {com.github.athos/clj-check {:git/sha "518d5a1cbfcd7c952f548e6dbfcb9a4a5faf9062"}} 35 | :main-opts ["-m" "clj-check.check"]} 36 | 37 | ; clj -X:test 38 | :test 39 | {:extra-paths ["test"] 40 | :extra-deps {org.clojure/test.check {:mvn/version "1.1.1"} 41 | io.github.cognitect-labs/test-runner {:git/tag "v0.5.0" :git/sha "48c3c67"}} 42 | :exec-fn cognitect.test-runner.api/test} 43 | 44 | ; clj -M:kondo 45 | :kondo 46 | {:extra-deps {clj-kondo/clj-kondo {:mvn/version "2021.12.19"}} 47 | :main-opts ["-m" "clj-kondo.main" "--lint" "src"]} 48 | 49 | ; clj -M:eastwood 50 | :eastwood 51 | {:extra-deps {jonase/eastwood {:mvn/version "1.0.0"}} 52 | :main-opts ["-m" "eastwood.lint" "{:source-paths,[\"src\"]}"]} 53 | 54 | ; clj -M:outdated 55 | :outdated 56 | {:extra-deps {com.github.liquidz/antq {:mvn/version "1.3.1"}} 57 | :main-opts ["-m" "antq.core" "--skip=pom"]} 58 | 59 | ; clj -X:codox 60 | :codox 61 | {:extra-deps {codox/codox {:mvn/version "0.10.8"}} 62 | :exec-fn codox.main/generate-docs 63 | :exec-args {:source-paths ["src"] 64 | :source-uri "https://github.com/pmonks/multigrep/blob/main/{filepath}#L{line}"}} 65 | }} 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | | | | | 2 | |---:|:---:|:---:| 3 | | [**main**](https://github.com/pmonks/multigrep/tree/main) | [![CI](https://github.com/pmonks/multigrep/workflows/CI/badge.svg?branch=main)](https://github.com/pmonks/multigrep/actions?query=workflow%3Alint) | [![Dependencies](https://github.com/pmonks/multigrep/workflows/dependencies/badge.svg?branch=main)](https://github.com/pmonks/multigrep/actions?query=workflow%3Adependencies) | 4 | | [**dev**](https://github.com/pmonks/multigrep/tree/dev) | [![CI](https://github.com/pmonks/multigrep/workflows/CI/badge.svg?branch=dev)](https://github.com/pmonks/multigrep/actions?query=workflow%3Alint) | [![Dependencies](https://github.com/pmonks/multigrep/workflows/dependencies/badge.svg?branch=dev)](https://github.com/pmonks/multigrep/actions?query=workflow%3Adependencies) | 5 | 6 | [![Latest Version](https://img.shields.io/clojars/v/com.github.pmonks/multigrep)](https://clojars.org/com.github.pmonks/multigrep/) [![Open Issues](https://img.shields.io/github/issues/pmonks/multigrep.svg)](https://github.com/pmonks/multigrep/issues) [![License](https://img.shields.io/github/license/pmonks/multigrep.svg)](https://github.com/pmonks/multigrep/blob/main/LICENSE) 7 | 8 | # multigrep 9 | 10 | A little Clojure library that provides regex-based file grepping and/or text substitution. 11 | 12 | ## Installation 13 | 14 | `multigrep` is available as a Maven artifact from [Clojars](https://clojars.org/com.github.pmonks/multigrep). 15 | 16 | ### Trying it Out 17 | 18 | #### Clojure CLI 19 | 20 | ```shell 21 | $ clj -Sdeps '{:deps {com.github.pmonks/multigrep {:mvn/version "#.#.#"}}}' # Where #.#.# is replaced with an actual version number (see badge above) 22 | ``` 23 | 24 | #### Leiningen 25 | 26 | ```shell 27 | $ lein try com.github.pmonks/spinner 28 | ``` 29 | 30 | ## Usage 31 | 32 | The multigrep functionality is provided by the `multigrep.core` namespace. 33 | 34 | Require it in the REPL: 35 | 36 | ```clojure 37 | (require '[multigrep.core :as mg]) 38 | ``` 39 | 40 | Require it in your application: 41 | 42 | ```clojure 43 | (ns my-app.core 44 | (:require [multigrep.core :as mg])) 45 | ``` 46 | 47 | The library provides two functions - `grep` (for searching for text within files) and `greplace!` (for searching and replacing text within files). 48 | [The API documentation](https://pmonks.github.io/multigrep/) has full details, and [the unit tests](https://github.com/pmonks/multigrep/blob/main/test/multigrep/core_test.clj) contain comprehensive usage examples. 49 | 50 | ### API Documentation 51 | 52 | [API documentation is available here](https://pmonks.github.io/multigrep/). 53 | 54 | ## Contributor Information 55 | 56 | [Contributing Guidelines](https://github.com/pmonks/multigrep/blob/main/.github/CONTRIBUTING.md) 57 | 58 | [Bug Tracker](https://github.com/pmonks/multigrep/issues) 59 | 60 | [Code of Conduct](https://github.com/pmonks/multigrep/blob/main/.github/CODE_OF_CONDUCT.md) 61 | 62 | ### Developer Workflow 63 | 64 | The repository has two permanent branches: `main` and `dev`. **All development must occur either in branch `dev`, or (preferably) in feature branches off of `dev`.** All PRs must also be submitted against `dev`; the `main` branch is **only** updated from `dev` via PRs created by the core development team. All other changes submitted to `main` will be rejected. 65 | 66 | This model allows otherwise unrelated changes to be batched up in the `dev` branch, integration tested there, and then released en masse to the `main` branch, which will trigger automated generation and deployment of the release (Codox docs to GitHub Pages, JARs to Clojars, etc.). 67 | 68 | ### Why are there so many different groupIds on Clojars for this project? 69 | 70 | The project was originally developed under my personal GitHub account. In early 2018 it was transferred to the `clj-commons` GitHub organisation, but then, as that group refined their scope and mission, it was determined that it no longer belonged there, and the project were transferred back in late 2021. During this time the build tooling for the project also changed from Leiningen to tools.build, which created further groupId churn (tools.build introduced special, useful semantics for `com.github.username` groupIds that don't exist with Leiningen or Clojars). 71 | 72 | ## License 73 | 74 | Copyright © 2014 Peter Monks 75 | 76 | Distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). 77 | 78 | SPDX-License-Identifier: [Apache-2.0](https://spdx.org/licenses/Apache-2.0) 79 | -------------------------------------------------------------------------------- /src/multigrep/core.clj: -------------------------------------------------------------------------------- 1 | ; 2 | ; Copyright © 2014 Peter Monks 3 | ; 4 | ; Licensed under the Apache License, Version 2.0 (the "License"); 5 | ; you may not use this file except in compliance with the License. 6 | ; You may obtain a copy of the License at 7 | ; 8 | ; http://www.apache.org/licenses/LICENSE-2.0 9 | ; 10 | ; Unless required by applicable law or agreed to in writing, software 11 | ; distributed under the License is distributed on an "AS IS" BASIS, 12 | ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | ; See the License for the specific language governing permissions and 14 | ; limitations under the License. 15 | ; 16 | ; SPDX-License-Identifier: Apache-2.0 17 | ; 18 | 19 | (ns multigrep.core 20 | (:require [clojure.java.io :as io] 21 | [clojure.string :as s])) 22 | 23 | (defn- grep-line 24 | "Greps a single line with multiple regexes, returning a sequence of matches." 25 | [file regexes line-number line] 26 | (remove nil? (map #(let [matches (re-seq % line)] 27 | (when (not-empty matches) 28 | { 29 | :file file 30 | :line line 31 | :line-number line-number 32 | :regex % 33 | :re-seq matches 34 | })) 35 | regexes))) 36 | 37 | (defmulti grep 38 | "Returns a sequence of maps representing each of the matches of r (one or more regexes) in f (one or more things that can be read by clojure.io/reader). 39 | 40 | Each map in the sequence has these keys: 41 | { 42 | :file ; the entry in f that matched 43 | :line ; text of the line that matched 44 | :line-number ; line-number of that line (note: 1 based) 45 | :regex ; the entry in r that matched 46 | :re-seq ; the output from re-seq for this line and this regex 47 | }" 48 | {:arglists '([r f])} 49 | (fn [r f] [(sequential? r) (sequential? f)])) 50 | 51 | (defmethod grep [false false] 52 | [regex file] 53 | (grep [regex] file)) 54 | 55 | (defmethod grep [false true] 56 | [regex files] 57 | (flatten (map (partial grep [regex]) files))) 58 | 59 | (defmethod grep [true false] 60 | [regexes file] 61 | (with-open [reader (io/reader file)] 62 | (let [lines (line-seq reader)] 63 | (doall (flatten (map-indexed #(grep-line file regexes (inc %1) %2) lines)))))) 64 | 65 | (defmethod grep [true true] 66 | [regexes files] 67 | (flatten (map (partial grep regexes) files))) 68 | 69 | 70 | (defmulti greplace! 71 | "Applies r (a single regex) to f (one or more things that can be read by clojure.io/reader), substituting s (a string, or a function of one parameter (the match(es) from the regex) returning a string). 72 | 73 | Returns a sequence of maps representing each of the substitutions. Each map in the sequence has these keys: 74 | { 75 | :file ; the entry in f that matched 76 | :line-number ; line-number of the line that had one or more substitutions (note: 1 based) 77 | } 78 | 79 | The optional fourth parameter specifies at what file size processing should switch from in-memory to on-disk. It defaults to 1MB." 80 | {:arglists '([r s f] 81 | [r s f in-memory-threshold])} 82 | (fn 83 | ([_ _ _] :add-default-threshold) 84 | ([_ _ f _] (sequential? f)))) 85 | 86 | (def ^:private default-in-memory-greplace-threshold (* 1024 1024)) ; 1MB 87 | 88 | (defn- greplace-and-write-line 89 | [^java.io.Writer out regex substitution line file line-number] 90 | (let [replaced-line (s/replace line regex substitution)] 91 | (.write out (str replaced-line "\n")) 92 | (when-not (= line replaced-line) 93 | { 94 | :file file 95 | :line-number line-number 96 | }))) 97 | 98 | (defn- greplace-and-write-file 99 | [regex substitution lines file] 100 | (with-open [out (io/writer file :append false)] 101 | (doall (remove nil? 102 | (flatten (map-indexed #(greplace-and-write-line out regex substitution %2 file (inc %1)) 103 | lines)))))) 104 | 105 | (defn- in-memory-greplace 106 | "Performs a greplace in memory." 107 | [regex substitution file] 108 | (let [lines (with-open [r (io/reader file)] 109 | (doall (line-seq r)))] 110 | (greplace-and-write-file regex substitution lines file))) 111 | 112 | (defn- on-disk-greplace 113 | "Performs a greplace on disk, a line at a time." 114 | [regex substitution file] 115 | (let [result (atom '()) 116 | temp-file (java.io.File/createTempFile "greplace_" ".tmp")] 117 | (try 118 | (io/copy (io/file file) temp-file) 119 | (with-open [temp-r (io/reader temp-file)] 120 | (reset! result (greplace-and-write-file regex substitution (line-seq temp-r) file))) 121 | (finally 122 | (io/delete-file temp-file))) 123 | @result)) 124 | 125 | (defmethod greplace! :add-default-threshold 126 | [regex substitution file] 127 | (greplace! regex substitution file default-in-memory-greplace-threshold)) 128 | 129 | (defmethod greplace! false 130 | [regex substitution file in-memory-threshold] 131 | (if (< (.length (io/file file)) in-memory-threshold) 132 | (in-memory-greplace regex substitution file) 133 | (on-disk-greplace regex substitution file))) 134 | 135 | (defmethod greplace! true 136 | [regex substitution files in-memory-threshold] 137 | (flatten (map #(greplace! regex substitution % in-memory-threshold) files))) 138 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to multigrep 2 | 3 | :+1: First off, thanks for taking the time to contribute! :+1: 4 | 5 | # Contributor License Agreement (CLA) 6 | 7 | A CLA is a document that specifies how a project is allowed to use your contribution. We want a CLA that is simple and as clear as possible so that it doesn't impede contributions to the project. 8 | 9 | When you make a contribution to the project, you agree: 10 | 11 | 1. Your contribution is your original work (you own the copyright) or you otherwise have the right to submit the work. 12 | 2. You grant the project a nonexclusive, irrevocable license to use your submitted contribution in any way. 13 | 3. You are capable of granting these rights for the contribution. 14 | 15 | **By submitting a contribution to the project you agree to the above statements.** 16 | 17 | # Contributing Issues 18 | 19 | ## Prerequisites 20 | 21 | * [ ] Have you [searched for duplicates](https://github.com/pmonks/multigrep/issues?utf8=%E2%9C%93&q=)? A simple search for exception error messages or a summary of the unexpected behaviour should suffice. 22 | * [ ] Are you sure this is a bug or missing capability? 23 | 24 | ## Raising an Issue 25 | 26 | * Create your issue [here](https://github.com/pmonks/multigrep/issues/new). 27 | * New issues contain two templates in the description: bug report and enhancement request. Please pick the most appropriate for your issue. 28 | * Please use [Markdown formatting](https://help.github.com/categories/writing-on-github/) liberally to assist in readability. 29 | * [Code fences](https://help.github.com/articles/creating-and-highlighting-code-blocks/) for exception stack traces and log entries, for example, massively improve readability. 30 | 31 | # Contributing Pull Requests (Code & Docs) 32 | 33 | To make review of PRs easier, please: 34 | 35 | * Reference an issue from your PR. If there isn't an existing issue for your PR, please create an issue first before submitting the PR. 36 | * This helps expedite review by keeping the problem statement (the issue) explicitly separate from one of potentially many solutions (the PR). 37 | * Make sure your PRs will merge cleanly - PRs that don't are unlikely to be accepted. 38 | * For code contributions, follow the existing coding style. 39 | * For documentation contributions, follow the general structure, language, and tone of the existing docs. 40 | * Keep PRs small and cohesive - if you have multiple independent contributions, please submit them as independent PRs. 41 | * Minimise "spurious" changes (e.g. whitespace shenanigans). 42 | * Ensure all updated files include your copyright information at the top. 43 | * Ensure all new files include a header comment block containing the [Apache 2.0 license header and your copyright information](https://infra.apache.org/apply-license.html). 44 | 45 | ## Commit and PR Messages 46 | 47 | * **Reference issues, wiki pages, and pull requests liberally!** 48 | * Use the present tense ("Add feature" not "Added feature") 49 | * Use the imperative mood ("Move button left..." not "Moves button left...") 50 | * Limit the first line to 72 characters or less 51 | * Please start the commit message with one or more applicable emoji: 52 | 53 | | Emoji | Raw Emoji Code | Description | 54 | |:---:|:---:|---| 55 | | :tada: | `:tada:` | **initial** commit | 56 | | :construction: | `:construction:` | **WIP** (Work In Progress) commits | 57 | | :ambulance: | `:ambulance:` | when fixing a **bug** | 58 | | :bug: | `:bug:` | when **identifying a bug**, via an inline comment (please use the `@FIXME` tag in the comment) | 59 | | :new: | `:new:` | when introducing **new** features | 60 | | :art: | `:art:` | when improving the **format** / structure of the code | 61 | | :pencil: | `:pencil:` | when **performing minor changes / fixing** the code or language | 62 | | :ballot_box_with_check: | `:ballot_box_with_check:` | when completing a task | 63 | | :arrow_up: | `:arrow_up:` | when upgrading **dependencies** | 64 | | :arrow_down: | `:arrow_down:` | when downgrading **dependencies** | 65 | | :racehorse: | `:racehorse:` | when improving **performance** | 66 | | :fire: | `:fire:` | when **removing code** or files | 67 | | :speaker: | `:speaker:` | when adding **logging** | 68 | | :mute: | `:mute:` | when reducing **logging** | 69 | | :books: | `:books:` | when writing **docs** | 70 | | :bookmark: | `:bookmark:` | when adding a **tag** | 71 | | :gem: | `:gem:` | new **release** | 72 | | :zap: | `:zap:` | when introducing **backward incompatible** changes or **removing functionality** | 73 | | :bulb: | `:bulb:` | new **idea** identified in the code, via an inline comment (please use the `@IDEA` tag in the comment) | 74 | | :snowflake: | `:snowflake:` | changing **configuration** | 75 | | :lipstick: | `:lipstick:` | when improving **UI** / cosmetic | 76 | | :umbrella: | `:umbrella:` | when adding **tests** | 77 | | :green_heart: | `:green_heart:` | when fixing the **CI** build | 78 | | :lock: | `:lock:` | when dealing with **security** | 79 | | :shirt: | `:shirt:` | when removing **linter** / strict / deprecation / reflection warnings | 80 | | :fast_forward: | `:fast_forward:` | when **forward-porting features** from an older version/branch | 81 | | :rewind: | `:rewind:` | when **backporting features** from a newer version/branch | 82 | | :wheelchair: | `:wheelchair:` | when improving **accessibility** | 83 | | :globe_with_meridians: | `:globe_with_meridians:` | when dealing with **globalisation** / internationalisation | 84 | | :rocket: | `:rocket:` | anything related to deployments / **DevOps** | 85 | | :non-potable_water: | `:non-potable_water:` | when plugging memory leaks 86 | | :balance_scale: | `:balance_scale:` | when making legal changes (e.g. licensing) | 87 | | :penguin: | `:penguin:` | when fixing something on **Linux** | 88 | | :apple: | `:apple:` | when fixing something on **Mac OS** | 89 | | :checkered_flag: | `:checkered_flag:` | when fixing something on **Windows** | 90 | | :handbag: | `:handbag:` | when a commit contains multiple unrelated changes that don't fit into any one category (but please try not to do this!) | 91 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | [pmonks+conduct@gmail.com](mailto:pmonks+conduct@gmail.com?subject=Code%20of%20Conduct%20Report). 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series of 87 | actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or permanent 94 | ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within the 114 | community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.1, available at 120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 121 | 122 | Community Impact Guidelines were inspired by 123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 127 | [https://www.contributor-covenant.org/translations][translations]. 128 | 129 | [homepage]: https://www.contributor-covenant.org 130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 131 | [Mozilla CoC]: https://github.com/mozilla/diversity 132 | [FAQ]: https://www.contributor-covenant.org/faq 133 | [translations]: https://www.contributor-covenant.org/translations 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /test/multigrep/core_test.clj: -------------------------------------------------------------------------------- 1 | ; 2 | ; Copyright © 2014 Peter Monks 3 | ; 4 | ; Licensed under the Apache License, Version 2.0 (the "License"); 5 | ; you may not use this file except in compliance with the License. 6 | ; You may obtain a copy of the License at 7 | ; 8 | ; http://www.apache.org/licenses/LICENSE-2.0 9 | ; 10 | ; Unless required by applicable law or agreed to in writing, software 11 | ; distributed under the License is distributed on an "AS IS" BASIS, 12 | ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | ; See the License for the specific language governing permissions and 14 | ; limitations under the License. 15 | ; 16 | ; SPDX-License-Identifier: Apache-2.0 17 | ; 18 | 19 | (ns multigrep.core-test 20 | (:require [clojure.java.io :as io] 21 | [clojure.string :as s] 22 | [clojure.test :refer :all] 23 | [multigrep.core :refer :all])) 24 | 25 | (println "\n☔️ Running tests on Clojure" (clojure-version) "/ JVM" (System/getProperty "java.version") (str "(" (System/getProperty "java.vm.name") " v" (System/getProperty "java.vm.version") ")")) 26 | 27 | (def aesop1 (io/resource "The Ants and the Grasshopper.txt")) 28 | (def aesop2 (io/resource "The Cat and the Mice.txt")) 29 | (def aesop3 (io/resource "The Goose With the Golden Eggs.txt")) 30 | (def aesop4 (io/resource "The Hare and the Tortoise.txt")) 31 | (def aesop5 (io/resource "The Man and His Two Wives.txt")) 32 | 33 | (def aesops [aesop1 aesop2 aesop3 aesop4 aesop5]) 34 | 35 | (defmulti ^:private file-name type) 36 | 37 | (defmethod ^:private file-name nil 38 | [file] 39 | nil) 40 | 41 | (defmethod ^:private file-name java.lang.String 42 | [file] 43 | file) 44 | 45 | (defmethod ^:private file-name java.net.URL 46 | [file] 47 | (if (nil? file) 48 | nil 49 | (.getName (io/file (.getPath (.toURI file)))))) 50 | 51 | (defmethod ^:private file-name java.io.File 52 | [file] 53 | (if (nil? file) 54 | nil? 55 | (.getName file))) 56 | 57 | (defn- file-name-line-number 58 | [grep-result-map] 59 | [(file-name (:file grep-result-map)) (:line-number grep-result-map)]) 60 | 61 | (defn- file-name-line-number-regex 62 | [grep-result-map] 63 | [(file-name (:file grep-result-map)) 64 | (:line-number grep-result-map) 65 | (str (:regex grep-result-map))]) ; Convert regexes to strings since they don't appear to respect equality... 66 | 67 | (deftest grep-tests 68 | (testing "grep" 69 | ; Simple (non-regex) greps 70 | (testing "one non-regex grep, one file, no matches" (is (= (map :line-number (grep #"Cats" aesop1)) 71 | '()))) 72 | (testing "one non-regex grep, one file, multiple matches" (is (= (map :line-number (grep #"Ants" aesop1)) 73 | '(1 6)))) 74 | (testing "one non-regex grep, multiple files, multiple matches" (is (= (map file-name-line-number (grep #"Ants" aesops)) 75 | '(["The Ants and the Grasshopper.txt" 1] 76 | ["The Ants and the Grasshopper.txt" 6])))) 77 | (testing "multiple non-regex greps, one file, multiple matches" (is (= (map :line-number (grep [#"Goose" #"egg"] aesop3)) 78 | '(1 4 5 8 10 11)))) 79 | (testing "multiple non-regex greps, multiple files, multiple matches" (is (= (map file-name-line-number (grep [#"Mice" #"Man"] aesops)) 80 | '(["The Cat and the Mice.txt" 1] 81 | ["The Cat and the Mice.txt" 4] 82 | ["The Cat and the Mice.txt" 6] 83 | ["The Cat and the Mice.txt" 10] 84 | ["The Man and His Two Wives.txt" 1] 85 | ["The Man and His Two Wives.txt" 5] 86 | ["The Man and His Two Wives.txt" 7] 87 | ["The Man and His Two Wives.txt" 13])))) 88 | ; Complex (regex) greps 89 | (testing "single regex grep, single file, multiple matches" (is (= (map :line-number (grep #"(ing)|(ed)" aesop4)) 90 | '(4 5 6 7 8 9 10 12 13 14)))) 91 | (testing "single regex grep, multiple files, multiple matches" (is (= (map file-name-line-number (grep #"l(ei)|(ie)" aesops)) 92 | '(["The Ants and the Grasshopper.txt" 8] 93 | ["The Hare and the Tortoise.txt" 5] 94 | ["The Hare and the Tortoise.txt" 6] 95 | ["The Man and His Two Wives.txt" 17])))) 96 | (testing "multiple regex greps, multiple files, multiple matches" (is (= (map file-name-line-number-regex (grep [#"ei" #"ie" #"\s[Gg]rass"] aesops)) 97 | '(["The Ants and the Grasshopper.txt" 1 "\\s[Gg]rass"] 98 | ["The Ants and the Grasshopper.txt" 5 "\\s[Gg]rass"] 99 | ["The Ants and the Grasshopper.txt" 8 "ei"] 100 | ["The Ants and the Grasshopper.txt" 8 "ie"] 101 | ["The Cat and the Mice.txt" 6 "ei"] 102 | ["The Cat and the Mice.txt" 7 "ei"] 103 | ["The Cat and the Mice.txt" 15 "ei"] 104 | ["The Hare and the Tortoise.txt" 5 "ie"] 105 | ["The Hare and the Tortoise.txt" 6 "ie"] 106 | ["The Man and His Two Wives.txt" 17 "ie"])))))) 107 | 108 | (deftest greplace!-tests 109 | (testing "greplace!" 110 | (testing "in-memory" 111 | (testing "single file" 112 | (let [test-file "greplace-test-aesop1.txt"] 113 | (io/copy (io/file aesop1) (io/file test-file)) 114 | 115 | (testing "non-regex grep, string substitute, no substitutions" (is (= (map :line-number (greplace! #"PANTS" "pants" test-file)) 116 | '()))) 117 | (testing "non-regex grep, string substitute, one substitution" (is (= (map :line-number (greplace! #"THE ANTS" "The Ants" test-file)) 118 | '(4)))) 119 | (testing "regex grep, string substitute, many substitutions" (is (= (map :line-number (greplace! #"(?i)ants" "ANTS" test-file)) 120 | '(1 4 6 14)))) 121 | (testing "regex grep, function substitute, many substitutions" (is (= (map :line-number (greplace! #"(?i)grasshopper" (fn [m] (str (java.util.UUID/randomUUID))) test-file)) 122 | '(1 5)))))) 123 | (testing "multiple files" 124 | (let [test-files ["greplace-test-aesop1.txt" 125 | "greplace-test-aesop2.txt" 126 | "greplace-test-aesop3.txt" 127 | "greplace-test-aesop4.txt" 128 | "greplace-test-aesop5.txt"]] 129 | (io/copy (io/file aesop1) (io/file "greplace-test-aesop1.txt")) 130 | (io/copy (io/file aesop2) (io/file "greplace-test-aesop2.txt")) 131 | (io/copy (io/file aesop3) (io/file "greplace-test-aesop3.txt")) 132 | (io/copy (io/file aesop4) (io/file "greplace-test-aesop4.txt")) 133 | (io/copy (io/file aesop5) (io/file "greplace-test-aesop5.txt")) 134 | 135 | (testing "non-regex grep, string substitute, no substitutions" (is (= (map file-name-line-number (greplace! #"PANTS" "pants" test-files)) 136 | '()))) 137 | (testing "non-regex grep, string substitute, many substitutions" (is (= (map file-name-line-number (greplace! #"and the" "AND THE" test-files)) 138 | '(["greplace-test-aesop1.txt" 1] 139 | ["greplace-test-aesop2.txt" 1] 140 | ["greplace-test-aesop4.txt" 1])))) 141 | (testing "regex grep, string substitute, many substitutions" (is (= (map file-name-line-number (greplace! #"(?i)(and|with) the" "and the" test-files)) 142 | '(["greplace-test-aesop1.txt" 1] 143 | ["greplace-test-aesop2.txt" 1] 144 | ["greplace-test-aesop3.txt" 1] 145 | ["greplace-test-aesop4.txt" 1])))) 146 | (testing "regex grep, function substitute, many substitutions" (is (= (map file-name-line-number (greplace! #"(?i)(and|with) the" (fn [m] (str (java.util.UUID/randomUUID))) test-files)) 147 | '(["greplace-test-aesop1.txt" 1] 148 | ["greplace-test-aesop2.txt" 1] 149 | ["greplace-test-aesop3.txt" 1] 150 | ["greplace-test-aesop4.txt" 1]))))))) 151 | (testing "on-disk" 152 | (let [in-memory-threshold 0] ; Force on-disk greplace 153 | (testing "single file" 154 | (let [test-file "greplace-test-aesop1.txt"] 155 | (io/copy (io/file aesop1) (io/file test-file)) 156 | 157 | (testing "non-regex grep, string substitute, no substitutions" (is (= (map :line-number (greplace! #"PANTS" "pants" test-file in-memory-threshold)) 158 | '()))) 159 | (testing "non-regex grep, string substitute, one substitution" (is (= (map :line-number (greplace! #"THE ANTS" "The Ants" test-file in-memory-threshold)) 160 | '(4)))) 161 | (testing "regex grep, string substitute, many substitutions" (is (= (map :line-number (greplace! #"(?i)ants" "ANTS" test-file in-memory-threshold)) 162 | '(1 4 6 14)))) 163 | (testing "regex grep, function substitute, many substitutions" (is (= (map :line-number (greplace! #"(?i)grasshopper" (fn [m] (str (java.util.UUID/randomUUID))) test-file in-memory-threshold)) 164 | '(1 5)))))) 165 | (testing "multiple files" 166 | (let [test-files ["greplace-test-aesop1.txt" 167 | "greplace-test-aesop2.txt" 168 | "greplace-test-aesop3.txt" 169 | "greplace-test-aesop4.txt" 170 | "greplace-test-aesop5.txt"]] 171 | (io/copy (io/file aesop1) (io/file "greplace-test-aesop1.txt")) 172 | (io/copy (io/file aesop2) (io/file "greplace-test-aesop2.txt")) 173 | (io/copy (io/file aesop3) (io/file "greplace-test-aesop3.txt")) 174 | (io/copy (io/file aesop4) (io/file "greplace-test-aesop4.txt")) 175 | (io/copy (io/file aesop5) (io/file "greplace-test-aesop5.txt")) 176 | 177 | (testing "non-regex grep, string substitute, no substitutions" (is (= (map file-name-line-number (greplace! #"PANTS" "pants" test-files)) 178 | '()))) 179 | (testing "non-regex grep, string substitute, many substitutions" (is (= (map file-name-line-number (greplace! #"and the" "AND THE" test-files)) 180 | '(["greplace-test-aesop1.txt" 1] 181 | ["greplace-test-aesop2.txt" 1] 182 | ["greplace-test-aesop4.txt" 1])))) 183 | (testing "regex grep, string substitute, many substitutions" (is (= (map file-name-line-number (greplace! #"(?i)(and|with) the" "and the" test-files)) 184 | '(["greplace-test-aesop1.txt" 1] 185 | ["greplace-test-aesop2.txt" 1] 186 | ["greplace-test-aesop3.txt" 1] 187 | ["greplace-test-aesop4.txt" 1])))) 188 | (testing "regex grep, function substitute, many substitutions" (is (= (map file-name-line-number (greplace! #"(?i)(and|with) the" (fn [m] (str (java.util.UUID/randomUUID))) test-files)) 189 | '(["greplace-test-aesop1.txt" 1] 190 | ["greplace-test-aesop2.txt" 1] 191 | ["greplace-test-aesop3.txt" 1] 192 | ["greplace-test-aesop4.txt" 1])))))))))) 193 | --------------------------------------------------------------------------------